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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/sanitizers/sancov_merger.py | python | merge_parallel | (inputs, merge_fun=merge) | Process several merge jobs in parallel. | Process several merge jobs in parallel. | [
"Process",
"several",
"merge",
"jobs",
"in",
"parallel",
"."
] | def merge_parallel(inputs, merge_fun=merge):
"""Process several merge jobs in parallel."""
pool = Pool(CPUS)
try:
return pool.map(merge_fun, inputs)
finally:
pool.close() | [
"def",
"merge_parallel",
"(",
"inputs",
",",
"merge_fun",
"=",
"merge",
")",
":",
"pool",
"=",
"Pool",
"(",
"CPUS",
")",
"try",
":",
"return",
"pool",
".",
"map",
"(",
"merge_fun",
",",
"inputs",
")",
"finally",
":",
"pool",
".",
"close",
"(",
")"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/sanitizers/sancov_merger.py#L119-L125 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.GetCaretPositionForDefaultStyle | (*args, **kwargs) | return _richtext.RichTextCtrl_GetCaretPositionForDefaultStyle(*args, **kwargs) | GetCaretPositionForDefaultStyle(self) -> long | GetCaretPositionForDefaultStyle(self) -> long | [
"GetCaretPositionForDefaultStyle",
"(",
"self",
")",
"-",
">",
"long"
] | def GetCaretPositionForDefaultStyle(*args, **kwargs):
"""GetCaretPositionForDefaultStyle(self) -> long"""
return _richtext.RichTextCtrl_GetCaretPositionForDefaultStyle(*args, **kwargs) | [
"def",
"GetCaretPositionForDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetCaretPositionForDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4128-L4130 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | bindings/python/htcondor/dags/dag.py | python | DAG.glob | (self, pattern: str) | return self.select(lambda node: fnmatch.fnmatchcase(node.name, pattern)) | Return a :class:`Nodes` of the nodes in the DAG
whose names match the glob ``pattern``. | Return a :class:`Nodes` of the nodes in the DAG
whose names match the glob ``pattern``. | [
"Return",
"a",
":",
"class",
":",
"Nodes",
"of",
"the",
"nodes",
"in",
"the",
"DAG",
"whose",
"names",
"match",
"the",
"glob",
"pattern",
"."
] | def glob(self, pattern: str) -> node.Nodes:
"""
Return a :class:`Nodes` of the nodes in the DAG
whose names match the glob ``pattern``.
"""
return self.select(lambda node: fnmatch.fnmatchcase(node.name, pattern)) | [
"def",
"glob",
"(",
"self",
",",
"pattern",
":",
"str",
")",
"->",
"node",
".",
"Nodes",
":",
"return",
"self",
".",
"select",
"(",
"lambda",
"node",
":",
"fnmatch",
".",
"fnmatchcase",
"(",
"node",
".",
"name",
",",
"pattern",
")",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/dags/dag.py#L324-L329 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/re2/lib/codereview/codereview.py | python | MySend1 | (request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs) | Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string. | Sends an RPC and returns the response. | [
"Sends",
"an",
"RPC",
"and",
"returns",
"the",
"response",
"."
] | def MySend1(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
global rpc
if rpc == None:
rpc = GetRpcServer(upload_options)
self = rpc
if not self.authenticated and force_auth:
self._Authenticate()
if request_path is None:
return
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
f = self.opener.open(req)
response = f.read()
f.close()
# Translate \r\n into \n, because Rietveld doesn't.
response = response.replace('\r\n', '\n')
# who knows what urllib will give us
if type(response) == unicode:
response = response.encode("utf-8")
typecheck(response, str)
return response
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
self._Authenticate()
elif e.code == 302:
loc = e.info()["location"]
if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0:
return ''
self._Authenticate()
else:
raise
finally:
socket.setdefaulttimeout(old_timeout) | [
"def",
"MySend1",
"(",
"request_path",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"\"application/octet-stream\"",
",",
"timeout",
"=",
"None",
",",
"force_auth",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Don't require authentication. Let the server say",
"# whether it is necessary.",
"global",
"rpc",
"if",
"rpc",
"==",
"None",
":",
"rpc",
"=",
"GetRpcServer",
"(",
"upload_options",
")",
"self",
"=",
"rpc",
"if",
"not",
"self",
".",
"authenticated",
"and",
"force_auth",
":",
"self",
".",
"_Authenticate",
"(",
")",
"if",
"request_path",
"is",
"None",
":",
"return",
"old_timeout",
"=",
"socket",
".",
"getdefaulttimeout",
"(",
")",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"try",
":",
"tries",
"=",
"0",
"while",
"True",
":",
"tries",
"+=",
"1",
"args",
"=",
"dict",
"(",
"kwargs",
")",
"url",
"=",
"\"http://%s%s\"",
"%",
"(",
"self",
".",
"host",
",",
"request_path",
")",
"if",
"args",
":",
"url",
"+=",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
"req",
"=",
"self",
".",
"_CreateRequest",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"payload",
")",
"req",
".",
"add_header",
"(",
"\"Content-Type\"",
",",
"content_type",
")",
"try",
":",
"f",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"response",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"# Translate \\r\\n into \\n, because Rietveld doesn't.",
"response",
"=",
"response",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"# who knows what urllib will give us",
"if",
"type",
"(",
"response",
")",
"==",
"unicode",
":",
"response",
"=",
"response",
".",
"encode",
"(",
"\"utf-8\"",
")",
"typecheck",
"(",
"response",
",",
"str",
")",
"return",
"response",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"if",
"tries",
">",
"3",
":",
"raise",
"elif",
"e",
".",
"code",
"==",
"401",
":",
"self",
".",
"_Authenticate",
"(",
")",
"elif",
"e",
".",
"code",
"==",
"302",
":",
"loc",
"=",
"e",
".",
"info",
"(",
")",
"[",
"\"location\"",
"]",
"if",
"not",
"loc",
".",
"startswith",
"(",
"'https://www.google.com/a'",
")",
"or",
"loc",
".",
"find",
"(",
"'/ServiceLogin'",
")",
"<",
"0",
":",
"return",
"''",
"self",
".",
"_Authenticate",
"(",
")",
"else",
":",
"raise",
"finally",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"old_timeout",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/re2/lib/codereview/codereview.py#L2436-L2500 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | libcxx/utils/libcxx/sym_check/extract.py | python | NMExtractor._want_sym | (sym) | return (sym['type'] not in bad_types
and sym['name'] not in ['__bss_start', '_end', '_edata']) | Check that s is a valid symbol that we want to keep. | Check that s is a valid symbol that we want to keep. | [
"Check",
"that",
"s",
"is",
"a",
"valid",
"symbol",
"that",
"we",
"want",
"to",
"keep",
"."
] | def _want_sym(sym):
"""
Check that s is a valid symbol that we want to keep.
"""
if sym is None or len(sym) < 2:
return False
if sym['name'] in extract_ignore_names:
return False
bad_types = ['t', 'b', 'r', 'd', 'w']
return (sym['type'] not in bad_types
and sym['name'] not in ['__bss_start', '_end', '_edata']) | [
"def",
"_want_sym",
"(",
"sym",
")",
":",
"if",
"sym",
"is",
"None",
"or",
"len",
"(",
"sym",
")",
"<",
"2",
":",
"return",
"False",
"if",
"sym",
"[",
"'name'",
"]",
"in",
"extract_ignore_names",
":",
"return",
"False",
"bad_types",
"=",
"[",
"'t'",
",",
"'b'",
",",
"'r'",
",",
"'d'",
",",
"'w'",
"]",
"return",
"(",
"sym",
"[",
"'type'",
"]",
"not",
"in",
"bad_types",
"and",
"sym",
"[",
"'name'",
"]",
"not",
"in",
"[",
"'__bss_start'",
",",
"'_end'",
",",
"'_edata'",
"]",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/libcxx/utils/libcxx/sym_check/extract.py#L84-L94 | |
calamares/calamares | 9f6f82405b3074af7c99dc26487d2e46e4ece3e5 | src/modules/bootloader/main.py | python | install_systemd_boot | (efi_directory) | Installs systemd-boot as bootloader for EFI setups.
:param efi_directory: | Installs systemd-boot as bootloader for EFI setups. | [
"Installs",
"systemd",
"-",
"boot",
"as",
"bootloader",
"for",
"EFI",
"setups",
"."
] | def install_systemd_boot(efi_directory):
"""
Installs systemd-boot as bootloader for EFI setups.
:param efi_directory:
"""
libcalamares.utils.debug("Bootloader: systemd-boot")
install_path = libcalamares.globalstorage.value("rootMountPoint")
install_efi_directory = install_path + efi_directory
uuid = get_uuid()
distribution = get_bootloader_entry_name()
distribution_translated = distribution.translate(file_name_sanitizer)
loader_path = os.path.join(install_efi_directory,
"loader",
"loader.conf")
subprocess.call(["bootctl",
"--path={!s}".format(install_efi_directory),
"install"])
create_systemd_boot_conf(install_path,
efi_directory,
uuid,
distribution,
distribution_translated,
"default")
if "fallback" in libcalamares.job.configuration:
create_systemd_boot_conf(install_path,
efi_directory,
uuid,
distribution,
distribution_translated,
"fallback")
create_loader(loader_path, distribution_translated) | [
"def",
"install_systemd_boot",
"(",
"efi_directory",
")",
":",
"libcalamares",
".",
"utils",
".",
"debug",
"(",
"\"Bootloader: systemd-boot\"",
")",
"install_path",
"=",
"libcalamares",
".",
"globalstorage",
".",
"value",
"(",
"\"rootMountPoint\"",
")",
"install_efi_directory",
"=",
"install_path",
"+",
"efi_directory",
"uuid",
"=",
"get_uuid",
"(",
")",
"distribution",
"=",
"get_bootloader_entry_name",
"(",
")",
"distribution_translated",
"=",
"distribution",
".",
"translate",
"(",
"file_name_sanitizer",
")",
"loader_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"install_efi_directory",
",",
"\"loader\"",
",",
"\"loader.conf\"",
")",
"subprocess",
".",
"call",
"(",
"[",
"\"bootctl\"",
",",
"\"--path={!s}\"",
".",
"format",
"(",
"install_efi_directory",
")",
",",
"\"install\"",
"]",
")",
"create_systemd_boot_conf",
"(",
"install_path",
",",
"efi_directory",
",",
"uuid",
",",
"distribution",
",",
"distribution_translated",
",",
"\"default\"",
")",
"if",
"\"fallback\"",
"in",
"libcalamares",
".",
"job",
".",
"configuration",
":",
"create_systemd_boot_conf",
"(",
"install_path",
",",
"efi_directory",
",",
"uuid",
",",
"distribution",
",",
"distribution_translated",
",",
"\"fallback\"",
")",
"create_loader",
"(",
"loader_path",
",",
"distribution_translated",
")"
] | https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/bootloader/main.py#L469-L500 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py | python | _may_reduce_to_scalar | (keepdims, axis, output) | return output | Set a reduction's output shape to be a scalar if we are certain. | Set a reduction's output shape to be a scalar if we are certain. | [
"Set",
"a",
"reduction",
"s",
"output",
"shape",
"to",
"be",
"a",
"scalar",
"if",
"we",
"are",
"certain",
"."
] | def _may_reduce_to_scalar(keepdims, axis, output):
"""Set a reduction's output shape to be a scalar if we are certain."""
if not common_shapes.has_fully_defined_shape(output) and (not keepdims) and (
axis is None):
output.set_shape(())
return output | [
"def",
"_may_reduce_to_scalar",
"(",
"keepdims",
",",
"axis",
",",
"output",
")",
":",
"if",
"not",
"common_shapes",
".",
"has_fully_defined_shape",
"(",
"output",
")",
"and",
"(",
"not",
"keepdims",
")",
"and",
"(",
"axis",
"is",
"None",
")",
":",
"output",
".",
"set_shape",
"(",
"(",
")",
")",
"return",
"output"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L1454-L1459 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Process.Detach | (*args, **kwargs) | return _misc_.Process_Detach(*args, **kwargs) | Detach(self) | Detach(self) | [
"Detach",
"(",
"self",
")"
] | def Detach(*args, **kwargs):
"""Detach(self)"""
return _misc_.Process_Detach(*args, **kwargs) | [
"def",
"Detach",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Process_Detach",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2015-L2017 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/idl_parser/idl_parser.py | python | IDLParser.p_Arguments | (self, p) | Arguments : ',' Argument Arguments
| | Arguments : ',' Argument Arguments
| | [
"Arguments",
":",
"Argument",
"Arguments",
"|"
] | def p_Arguments(self, p):
"""Arguments : ',' Argument Arguments
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3]) | [
"def",
"p_Arguments",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
">",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"ListFromConcat",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"3",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L690-L694 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/sequence_lod.py | python | sequence_concat | (input, name=None) | return out | :api_attr: Static Graph
**Notes: The Op only receives LoDTensor as input. If your input is Tensor, please use concat Op.(fluid.layers.** :ref:`api_fluid_layers_concat` ).
This operator only supports LoDTensor as input. It concatenates the multiple LoDTensor from input by the LoD information,
and outputs the concatenated LoDTensor.
.. code-block:: text
input is a list of LoDTensor:
input = [x1, x2]
where:
x1.lod = [[0, 3, 5]]
x1.data = [[1], [2], [3], [4], [5]]
x1.shape = [5, 1]
x2.lod = [[0, 2, 4]]
x2.data = [[6], [7], [8], [9]]
x2.shape = [4, 1]
and should satisfy: len(x1.lod[0]) == len(x2.lod[0])
output is LoDTensor:
out.lod = [[0, 3+2, 5+4]]
out.data = [[1], [2], [3], [6], [7], [4], [5], [8], [9]]
out.shape = [9, 1]
Args:
input(list of Variable): List of LoDTensor to be concatenated. The length of each LoDTensor should be same.
The data type can be float32, float64 or int64.
name(str, optional): The default value is None. Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name` .
Returns:
Variable: Output the concatenated LoDTensor. The data type is same as input.
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
x = paddle.static.data(name='x', shape=[-1, 10], dtype='float32', lod_level=1)
y = paddle.static.data(name='y', shape=[-1, 10], dtype='float32', lod_level=1)
out = paddle.static.nn.sequence_concat(input=[x, y]) | :api_attr: Static Graph | [
":",
"api_attr",
":",
"Static",
"Graph"
] | def sequence_concat(input, name=None):
"""
:api_attr: Static Graph
**Notes: The Op only receives LoDTensor as input. If your input is Tensor, please use concat Op.(fluid.layers.** :ref:`api_fluid_layers_concat` ).
This operator only supports LoDTensor as input. It concatenates the multiple LoDTensor from input by the LoD information,
and outputs the concatenated LoDTensor.
.. code-block:: text
input is a list of LoDTensor:
input = [x1, x2]
where:
x1.lod = [[0, 3, 5]]
x1.data = [[1], [2], [3], [4], [5]]
x1.shape = [5, 1]
x2.lod = [[0, 2, 4]]
x2.data = [[6], [7], [8], [9]]
x2.shape = [4, 1]
and should satisfy: len(x1.lod[0]) == len(x2.lod[0])
output is LoDTensor:
out.lod = [[0, 3+2, 5+4]]
out.data = [[1], [2], [3], [6], [7], [4], [5], [8], [9]]
out.shape = [9, 1]
Args:
input(list of Variable): List of LoDTensor to be concatenated. The length of each LoDTensor should be same.
The data type can be float32, float64 or int64.
name(str, optional): The default value is None. Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name` .
Returns:
Variable: Output the concatenated LoDTensor. The data type is same as input.
Examples:
.. code-block:: python
import paddle
paddle.enable_static()
x = paddle.static.data(name='x', shape=[-1, 10], dtype='float32', lod_level=1)
y = paddle.static.data(name='y', shape=[-1, 10], dtype='float32', lod_level=1)
out = paddle.static.nn.sequence_concat(input=[x, y])
"""
assert not in_dygraph_mode(), (
"sequence layer is not supported in dygraph mode yet.")
helper = LayerHelper('sequence_concat', **locals())
check_type(input, 'input', list, 'fluid.layers.sequence_concat')
for i, input_x in enumerate(input):
check_variable_and_dtype(input_x, 'input[' + str(i) + ']',
['int64', 'float32', 'float64'],
'fluid.layers.sequence_concat')
out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())
helper.append_op(
type='sequence_concat', inputs={'X': input}, outputs={'Out': [out]})
return out | [
"def",
"sequence_concat",
"(",
"input",
",",
"name",
"=",
"None",
")",
":",
"assert",
"not",
"in_dygraph_mode",
"(",
")",
",",
"(",
"\"sequence layer is not supported in dygraph mode yet.\"",
")",
"helper",
"=",
"LayerHelper",
"(",
"'sequence_concat'",
",",
"*",
"*",
"locals",
"(",
")",
")",
"check_type",
"(",
"input",
",",
"'input'",
",",
"list",
",",
"'fluid.layers.sequence_concat'",
")",
"for",
"i",
",",
"input_x",
"in",
"enumerate",
"(",
"input",
")",
":",
"check_variable_and_dtype",
"(",
"input_x",
",",
"'input['",
"+",
"str",
"(",
"i",
")",
"+",
"']'",
",",
"[",
"'int64'",
",",
"'float32'",
",",
"'float64'",
"]",
",",
"'fluid.layers.sequence_concat'",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
"=",
"helper",
".",
"input_dtype",
"(",
")",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"'sequence_concat'",
",",
"inputs",
"=",
"{",
"'X'",
":",
"input",
"}",
",",
"outputs",
"=",
"{",
"'Out'",
":",
"[",
"out",
"]",
"}",
")",
"return",
"out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/sequence_lod.py#L380-L440 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle.py | python | _find_imported_submodules | (code, top_level_dependencies) | return subimports | Find currently imported submodules used by a function.
Submodules used by a function need to be detected and referenced for the
function to work correctly at depickling time. Because submodules can be
referenced as attribute of their parent package (``package.submodule``), we
need a special introspection technique that does not rely on GLOBAL-related
opcodes to find references of them in a code object.
Example:
```
import concurrent.futures
import cloudpickle
def func():
x = concurrent.futures.ThreadPoolExecutor
if __name__ == '__main__':
cloudpickle.dumps(func)
```
The globals extracted by cloudpickle in the function's state include the
concurrent package, but not its submodule (here, concurrent.futures), which
is the module used by func. Find_imported_submodules will detect the usage
of concurrent.futures. Saving this module alongside with func will ensure
that calling func once depickled does not fail due to concurrent.futures
not being imported | Find currently imported submodules used by a function. | [
"Find",
"currently",
"imported",
"submodules",
"used",
"by",
"a",
"function",
"."
] | def _find_imported_submodules(code, top_level_dependencies):
"""
Find currently imported submodules used by a function.
Submodules used by a function need to be detected and referenced for the
function to work correctly at depickling time. Because submodules can be
referenced as attribute of their parent package (``package.submodule``), we
need a special introspection technique that does not rely on GLOBAL-related
opcodes to find references of them in a code object.
Example:
```
import concurrent.futures
import cloudpickle
def func():
x = concurrent.futures.ThreadPoolExecutor
if __name__ == '__main__':
cloudpickle.dumps(func)
```
The globals extracted by cloudpickle in the function's state include the
concurrent package, but not its submodule (here, concurrent.futures), which
is the module used by func. Find_imported_submodules will detect the usage
of concurrent.futures. Saving this module alongside with func will ensure
that calling func once depickled does not fail due to concurrent.futures
not being imported
"""
subimports = []
# check if any known dependency is an imported package
for x in top_level_dependencies:
if (isinstance(x, types.ModuleType) and
hasattr(x, '__package__') and x.__package__):
# check if the package has any currently loaded sub-imports
prefix = x.__name__ + '.'
# A concurrent thread could mutate sys.modules,
# make sure we iterate over a copy to avoid exceptions
for name in list(sys.modules):
# Older versions of pytest will add a "None" module to
# sys.modules.
if name is not None and name.startswith(prefix):
# check whether the function can address the sub-module
tokens = set(name[len(prefix):].split('.'))
if not tokens - set(code.co_names):
subimports.append(sys.modules[name])
return subimports | [
"def",
"_find_imported_submodules",
"(",
"code",
",",
"top_level_dependencies",
")",
":",
"subimports",
"=",
"[",
"]",
"# check if any known dependency is an imported package",
"for",
"x",
"in",
"top_level_dependencies",
":",
"if",
"(",
"isinstance",
"(",
"x",
",",
"types",
".",
"ModuleType",
")",
"and",
"hasattr",
"(",
"x",
",",
"'__package__'",
")",
"and",
"x",
".",
"__package__",
")",
":",
"# check if the package has any currently loaded sub-imports",
"prefix",
"=",
"x",
".",
"__name__",
"+",
"'.'",
"# A concurrent thread could mutate sys.modules,",
"# make sure we iterate over a copy to avoid exceptions",
"for",
"name",
"in",
"list",
"(",
"sys",
".",
"modules",
")",
":",
"# Older versions of pytest will add a \"None\" module to",
"# sys.modules.",
"if",
"name",
"is",
"not",
"None",
"and",
"name",
".",
"startswith",
"(",
"prefix",
")",
":",
"# check whether the function can address the sub-module",
"tokens",
"=",
"set",
"(",
"name",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
".",
"split",
"(",
"'.'",
")",
")",
"if",
"not",
"tokens",
"-",
"set",
"(",
"code",
".",
"co_names",
")",
":",
"subimports",
".",
"append",
"(",
"sys",
".",
"modules",
"[",
"name",
"]",
")",
"return",
"subimports"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle.py#L352-L396 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | TextAttr.GetOutlineLevel | (*args, **kwargs) | return _controls_.TextAttr_GetOutlineLevel(*args, **kwargs) | GetOutlineLevel(self) -> int | GetOutlineLevel(self) -> int | [
"GetOutlineLevel",
"(",
"self",
")",
"-",
">",
"int"
] | def GetOutlineLevel(*args, **kwargs):
"""GetOutlineLevel(self) -> int"""
return _controls_.TextAttr_GetOutlineLevel(*args, **kwargs) | [
"def",
"GetOutlineLevel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_GetOutlineLevel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1764-L1766 | |
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Roomba/RLAgent.py | python | TabularRLAgent.start | (self, time, sensors) | return self.previous_action | Called to figure out the first action given the first sensors
@param time current time
@param sensors a DoubleVector of sensors for the agent (use len() and []) | Called to figure out the first action given the first sensors | [
"Called",
"to",
"figure",
"out",
"the",
"first",
"action",
"given",
"the",
"first",
"sensors"
] | def start(self, time, sensors):
"""
Called to figure out the first action given the first sensors
@param time current time
@param sensors a DoubleVector of sensors for the agent (use len() and [])
"""
self.previous_sensors = sensors
self.previous_action = self.get_epsilon_greedy(sensors)
return self.previous_action | [
"def",
"start",
"(",
"self",
",",
"time",
",",
"sensors",
")",
":",
"self",
".",
"previous_sensors",
"=",
"sensors",
"self",
".",
"previous_action",
"=",
"self",
".",
"get_epsilon_greedy",
"(",
"sensors",
")",
"return",
"self",
".",
"previous_action"
] | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/RLAgent.py#L128-L136 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.on_text_removal | (self, sourcebuffer, start_iter, end_iter) | Text removal callback | Text removal callback | [
"Text",
"removal",
"callback"
] | def on_text_removal(self, sourcebuffer, start_iter, end_iter):
"""Text removal callback"""
if self.user_active and self.curr_tree_iter:
self.state_machine.text_variation(self.treestore[self.curr_tree_iter][3],
sourcebuffer.get_text(start_iter, end_iter)) | [
"def",
"on_text_removal",
"(",
"self",
",",
"sourcebuffer",
",",
"start_iter",
",",
"end_iter",
")",
":",
"if",
"self",
".",
"user_active",
"and",
"self",
".",
"curr_tree_iter",
":",
"self",
".",
"state_machine",
".",
"text_variation",
"(",
"self",
".",
"treestore",
"[",
"self",
".",
"curr_tree_iter",
"]",
"[",
"3",
"]",
",",
"sourcebuffer",
".",
"get_text",
"(",
"start_iter",
",",
"end_iter",
")",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L3537-L3541 | ||
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/sanitizers/sancov_formatter.py | python | split | (options) | Implements the 'split' action of this tool. | Implements the 'split' action of this tool. | [
"Implements",
"the",
"split",
"action",
"of",
"this",
"tool",
"."
] | def split(options):
"""Implements the 'split' action of this tool."""
# Load existing json data file for splitting.
with open(options.json_input, 'r') as f:
data = json.load(f)
logging.info('Splitting off %d coverage files from %s',
len(data['files']), options.json_input)
for file_name, coverage in data['files'].iteritems():
# Preserve relative directories that are part of the file name.
file_path = os.path.join(options.output_dir, file_name + '.json')
try:
os.makedirs(os.path.dirname(file_path))
except OSError:
# Ignore existing directories.
pass
with open(file_path, 'w') as f:
# Flat-copy the old dict.
new_data = dict(data)
# Update current file.
new_data['files'] = {file_name: coverage}
# Write json data.
json.dump(new_data, f, sort_keys=True) | [
"def",
"split",
"(",
"options",
")",
":",
"# Load existing json data file for splitting.",
"with",
"open",
"(",
"options",
".",
"json_input",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"logging",
".",
"info",
"(",
"'Splitting off %d coverage files from %s'",
",",
"len",
"(",
"data",
"[",
"'files'",
"]",
")",
",",
"options",
".",
"json_input",
")",
"for",
"file_name",
",",
"coverage",
"in",
"data",
"[",
"'files'",
"]",
".",
"iteritems",
"(",
")",
":",
"# Preserve relative directories that are part of the file name.",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"options",
".",
"output_dir",
",",
"file_name",
"+",
"'.json'",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"file_path",
")",
")",
"except",
"OSError",
":",
"# Ignore existing directories.",
"pass",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"f",
":",
"# Flat-copy the old dict.",
"new_data",
"=",
"dict",
"(",
"data",
")",
"# Update current file.",
"new_data",
"[",
"'files'",
"]",
"=",
"{",
"file_name",
":",
"coverage",
"}",
"# Write json data.",
"json",
".",
"dump",
"(",
"new_data",
",",
"f",
",",
"sort_keys",
"=",
"True",
")"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/sanitizers/sancov_formatter.py#L383-L409 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/emr/connection.py | python | EmrConnection.terminate_jobflows | (self, jobflow_ids) | return self.get_status('TerminateJobFlows', params, verb='POST') | Terminate an Elastic MapReduce job flow
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs | Terminate an Elastic MapReduce job flow | [
"Terminate",
"an",
"Elastic",
"MapReduce",
"job",
"flow"
] | def terminate_jobflows(self, jobflow_ids):
"""
Terminate an Elastic MapReduce job flow
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
"""
params = {}
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
return self.get_status('TerminateJobFlows', params, verb='POST') | [
"def",
"terminate_jobflows",
"(",
"self",
",",
"jobflow_ids",
")",
":",
"params",
"=",
"{",
"}",
"self",
".",
"build_list_params",
"(",
"params",
",",
"jobflow_ids",
",",
"'JobFlowIds.member'",
")",
"return",
"self",
".",
"get_status",
"(",
"'TerminateJobFlows'",
",",
"params",
",",
"verb",
"=",
"'POST'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/emr/connection.py#L317-L326 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sgraph.py | python | SGraph.__init__ | (self, vertices=None, edges=None, vid_field='__id',
src_field='__src_id', dst_field='__dst_id', _proxy=None) | __init__(vertices=None, edges=None, vid_field='__id', src_field='__src_id', dst_field='__dst_id')
By default, construct an empty graph when vertices and edges are None.
Otherwise construct an SGraph with given vertices and edges.
Parameters
----------
vertices : SFrame, optional
An SFrame containing vertex id columns and optional vertex data
columns.
edges : SFrame, optional
An SFrame containing source and target id columns and optional edge
data columns.
vid_field : str, optional
The name of vertex id column in the `vertices` SFrame.
src_field : str, optional
The name of source id column in the `edges` SFrame.
dst_field : str, optional
The name of target id column in the `edges` SFrame. | __init__(vertices=None, edges=None, vid_field='__id', src_field='__src_id', dst_field='__dst_id') | [
"__init__",
"(",
"vertices",
"=",
"None",
"edges",
"=",
"None",
"vid_field",
"=",
"__id",
"src_field",
"=",
"__src_id",
"dst_field",
"=",
"__dst_id",
")"
] | def __init__(self, vertices=None, edges=None, vid_field='__id',
src_field='__src_id', dst_field='__dst_id', _proxy=None):
"""
__init__(vertices=None, edges=None, vid_field='__id', src_field='__src_id', dst_field='__dst_id')
By default, construct an empty graph when vertices and edges are None.
Otherwise construct an SGraph with given vertices and edges.
Parameters
----------
vertices : SFrame, optional
An SFrame containing vertex id columns and optional vertex data
columns.
edges : SFrame, optional
An SFrame containing source and target id columns and optional edge
data columns.
vid_field : str, optional
The name of vertex id column in the `vertices` SFrame.
src_field : str, optional
The name of source id column in the `edges` SFrame.
dst_field : str, optional
The name of target id column in the `edges` SFrame.
"""
if (_proxy is None):
self.__proxy__ = UnityGraphProxy(glconnect.get_client())
if vertices is not None:
self.__proxy__ = self.add_vertices(vertices, vid_field).__proxy__
if edges is not None:
self.__proxy__ = self.add_edges(edges, src_field, dst_field).__proxy__
else:
self.__proxy__ = _proxy
self._vertices = GFrame(self, VERTEX_GFRAME)
self._edges = GFrame(self, EDGE_GFRAME) | [
"def",
"__init__",
"(",
"self",
",",
"vertices",
"=",
"None",
",",
"edges",
"=",
"None",
",",
"vid_field",
"=",
"'__id'",
",",
"src_field",
"=",
"'__src_id'",
",",
"dst_field",
"=",
"'__dst_id'",
",",
"_proxy",
"=",
"None",
")",
":",
"if",
"(",
"_proxy",
"is",
"None",
")",
":",
"self",
".",
"__proxy__",
"=",
"UnityGraphProxy",
"(",
"glconnect",
".",
"get_client",
"(",
")",
")",
"if",
"vertices",
"is",
"not",
"None",
":",
"self",
".",
"__proxy__",
"=",
"self",
".",
"add_vertices",
"(",
"vertices",
",",
"vid_field",
")",
".",
"__proxy__",
"if",
"edges",
"is",
"not",
"None",
":",
"self",
".",
"__proxy__",
"=",
"self",
".",
"add_edges",
"(",
"edges",
",",
"src_field",
",",
"dst_field",
")",
".",
"__proxy__",
"else",
":",
"self",
".",
"__proxy__",
"=",
"_proxy",
"self",
".",
"_vertices",
"=",
"GFrame",
"(",
"self",
",",
"VERTEX_GFRAME",
")",
"self",
".",
"_edges",
"=",
"GFrame",
"(",
"self",
",",
"EDGE_GFRAME",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sgraph.py#L221-L257 | ||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py | python | ISkype.DeleteGroup | (self, GroupId) | Deletes a custom contact group.
Users in the contact group are moved to the All Contacts (hardwired) contact group.
@param GroupId: Group identifier. Get it from L{IGroup.Id}.
@type GroupId: int
@see: L{CreateGroup} | Deletes a custom contact group. | [
"Deletes",
"a",
"custom",
"contact",
"group",
"."
] | def DeleteGroup(self, GroupId):
'''Deletes a custom contact group.
Users in the contact group are moved to the All Contacts (hardwired) contact group.
@param GroupId: Group identifier. Get it from L{IGroup.Id}.
@type GroupId: int
@see: L{CreateGroup}
'''
self._DoCommand('DELETE GROUP %s' % GroupId) | [
"def",
"DeleteGroup",
"(",
"self",
",",
"GroupId",
")",
":",
"self",
".",
"_DoCommand",
"(",
"'DELETE GROUP %s'",
"%",
"GroupId",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py#L648-L657 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/base64.py | python | standard_b64encode | (s) | return b64encode(s) | Encode bytes-like object s using the standard Base64 alphabet.
The result is returned as a bytes object. | Encode bytes-like object s using the standard Base64 alphabet. | [
"Encode",
"bytes",
"-",
"like",
"object",
"s",
"using",
"the",
"standard",
"Base64",
"alphabet",
"."
] | def standard_b64encode(s):
"""Encode bytes-like object s using the standard Base64 alphabet.
The result is returned as a bytes object.
"""
return b64encode(s) | [
"def",
"standard_b64encode",
"(",
"s",
")",
":",
"return",
"b64encode",
"(",
"s",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/base64.py#L90-L95 | |
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | python/caffe/pycaffe.py | python | _Net_set_input_arrays | (self, data, labels) | return self._set_input_arrays(data, labels) | Set input arrays of the in-memory MemoryDataLayer.
(Note: this is only for networks declared with the memory data layer.) | Set input arrays of the in-memory MemoryDataLayer.
(Note: this is only for networks declared with the memory data layer.) | [
"Set",
"input",
"arrays",
"of",
"the",
"in",
"-",
"memory",
"MemoryDataLayer",
".",
"(",
"Note",
":",
"this",
"is",
"only",
"for",
"networks",
"declared",
"with",
"the",
"memory",
"data",
"layer",
".",
")"
] | def _Net_set_input_arrays(self, data, labels):
"""
Set input arrays of the in-memory MemoryDataLayer.
(Note: this is only for networks declared with the memory data layer.)
"""
if labels.ndim == 1:
labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis,
np.newaxis])
return self._set_input_arrays(data, labels) | [
"def",
"_Net_set_input_arrays",
"(",
"self",
",",
"data",
",",
"labels",
")",
":",
"if",
"labels",
".",
"ndim",
"==",
"1",
":",
"labels",
"=",
"np",
".",
"ascontiguousarray",
"(",
"labels",
"[",
":",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
"]",
")",
"return",
"self",
".",
"_set_input_arrays",
"(",
"data",
",",
"labels",
")"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/python/caffe/pycaffe.py#L227-L235 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py | python | Beta.dtype | (self) | return self._a_b_sum.dtype | dtype of samples from this distribution. | dtype of samples from this distribution. | [
"dtype",
"of",
"samples",
"from",
"this",
"distribution",
"."
] | def dtype(self):
"""dtype of samples from this distribution."""
return self._a_b_sum.dtype | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_a_b_sum",
".",
"dtype"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L169-L171 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/train/summary/_writer_pool.py | python | WriterPool.write | (self, data) | Write the event to file.
Args:
data (Optional[str, Tuple[list, int]]): The data to write. | Write the event to file. | [
"Write",
"the",
"event",
"to",
"file",
"."
] | def write(self, data) -> None:
"""
Write the event to file.
Args:
data (Optional[str, Tuple[list, int]]): The data to write.
"""
self._queue.put(('WRITE', data)) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
"->",
"None",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"(",
"'WRITE'",
",",
"data",
")",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/_writer_pool.py#L170-L177 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiTabCtrl.OnMotion | (self, event) | Handles the ``wx.EVT_MOTION`` event for :class:`AuiTabCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_MOTION`` event for :class:`AuiTabCtrl`. | [
"Handles",
"the",
"wx",
".",
"EVT_MOTION",
"event",
"for",
":",
"class",
":",
"AuiTabCtrl",
"."
] | def OnMotion(self, event):
"""
Handles the ``wx.EVT_MOTION`` event for :class:`AuiTabCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
pos = event.GetPosition()
# check if the mouse is hovering above a button
button = self.ButtonHitTest(pos.x, pos.y)
wnd = self.TabHitTest(pos.x, pos.y)
if wnd is not None:
mouse_tab = self.GetIdxFromWindow(wnd)
if not self._pages[mouse_tab].enabled:
self._hover_button = None
return
if self._on_button:
return
if button:
if self._hover_button and button != self._hover_button:
self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL
self._hover_button = None
self.Refresh()
self.Update()
if button.cur_state != AUI_BUTTON_STATE_HOVER:
button.cur_state = AUI_BUTTON_STATE_HOVER
self.Refresh()
self.Update()
self._hover_button = button
return
else:
if self._hover_button:
self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL
self._hover_button = None
self.Refresh()
self.Update()
if not event.LeftIsDown() or self._click_pt == wx.Point(-1, -1):
return
if not self.HasCapture():
return
wnd = self.TabHitTest(pos.x, pos.y)
if not self._is_dragging:
drag_x_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_X)
drag_y_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_Y)
if abs(pos.x - self._click_pt.x) > drag_x_threshold or \
abs(pos.y - self._click_pt.y) > drag_y_threshold:
self._is_dragging = True
if self._drag_image:
self._drag_image.EndDrag()
del self._drag_image
self._drag_image = None
if self._agwFlags & AUI_NB_DRAW_DND_TAB:
# Create the custom draw image from the icons and the text of the item
mouse_tab = self.GetIdxFromWindow(wnd)
page = self._pages[mouse_tab]
tab_button = self._tab_close_buttons[mouse_tab]
self._drag_image = TabDragImage(self, page, tab_button.cur_state, self._art)
if self._agwFlags & AUI_NB_TAB_FLOAT:
self._drag_image.BeginDrag(wx.Point(0,0), self, fullScreen=True)
else:
self._drag_image.BeginDragBounded(wx.Point(0,0), self, self.GetParent())
# Capture the mouse cursor position offset relative to
# The tab image location
self._drag_img_offset = (pos[0] - page.rect.x,
pos[1] - page.rect.y)
self._drag_image.Show()
if not wnd:
evt2 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG, self.GetId())
evt2.SetSelection(self.GetIdxFromWindow(self._click_tab))
evt2.SetOldSelection(evt2.GetSelection())
evt2.SetEventObject(self)
self.GetEventHandler().ProcessEvent(evt2)
if evt2.GetDispatched():
return
evt3 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION, self.GetId())
evt3.SetSelection(self.GetIdxFromWindow(self._click_tab))
evt3.SetOldSelection(evt3.GetSelection())
evt3.SetEventObject(self)
self.GetEventHandler().ProcessEvent(evt3)
if self._drag_image:
# Apply the drag images offset
pos -= self._drag_img_offset
self._drag_image.Move(pos) | [
"def",
"OnMotion",
"(",
"self",
",",
"event",
")",
":",
"pos",
"=",
"event",
".",
"GetPosition",
"(",
")",
"# check if the mouse is hovering above a button",
"button",
"=",
"self",
".",
"ButtonHitTest",
"(",
"pos",
".",
"x",
",",
"pos",
".",
"y",
")",
"wnd",
"=",
"self",
".",
"TabHitTest",
"(",
"pos",
".",
"x",
",",
"pos",
".",
"y",
")",
"if",
"wnd",
"is",
"not",
"None",
":",
"mouse_tab",
"=",
"self",
".",
"GetIdxFromWindow",
"(",
"wnd",
")",
"if",
"not",
"self",
".",
"_pages",
"[",
"mouse_tab",
"]",
".",
"enabled",
":",
"self",
".",
"_hover_button",
"=",
"None",
"return",
"if",
"self",
".",
"_on_button",
":",
"return",
"if",
"button",
":",
"if",
"self",
".",
"_hover_button",
"and",
"button",
"!=",
"self",
".",
"_hover_button",
":",
"self",
".",
"_hover_button",
".",
"cur_state",
"=",
"AUI_BUTTON_STATE_NORMAL",
"self",
".",
"_hover_button",
"=",
"None",
"self",
".",
"Refresh",
"(",
")",
"self",
".",
"Update",
"(",
")",
"if",
"button",
".",
"cur_state",
"!=",
"AUI_BUTTON_STATE_HOVER",
":",
"button",
".",
"cur_state",
"=",
"AUI_BUTTON_STATE_HOVER",
"self",
".",
"Refresh",
"(",
")",
"self",
".",
"Update",
"(",
")",
"self",
".",
"_hover_button",
"=",
"button",
"return",
"else",
":",
"if",
"self",
".",
"_hover_button",
":",
"self",
".",
"_hover_button",
".",
"cur_state",
"=",
"AUI_BUTTON_STATE_NORMAL",
"self",
".",
"_hover_button",
"=",
"None",
"self",
".",
"Refresh",
"(",
")",
"self",
".",
"Update",
"(",
")",
"if",
"not",
"event",
".",
"LeftIsDown",
"(",
")",
"or",
"self",
".",
"_click_pt",
"==",
"wx",
".",
"Point",
"(",
"-",
"1",
",",
"-",
"1",
")",
":",
"return",
"if",
"not",
"self",
".",
"HasCapture",
"(",
")",
":",
"return",
"wnd",
"=",
"self",
".",
"TabHitTest",
"(",
"pos",
".",
"x",
",",
"pos",
".",
"y",
")",
"if",
"not",
"self",
".",
"_is_dragging",
":",
"drag_x_threshold",
"=",
"wx",
".",
"SystemSettings",
".",
"GetMetric",
"(",
"wx",
".",
"SYS_DRAG_X",
")",
"drag_y_threshold",
"=",
"wx",
".",
"SystemSettings",
".",
"GetMetric",
"(",
"wx",
".",
"SYS_DRAG_Y",
")",
"if",
"abs",
"(",
"pos",
".",
"x",
"-",
"self",
".",
"_click_pt",
".",
"x",
")",
">",
"drag_x_threshold",
"or",
"abs",
"(",
"pos",
".",
"y",
"-",
"self",
".",
"_click_pt",
".",
"y",
")",
">",
"drag_y_threshold",
":",
"self",
".",
"_is_dragging",
"=",
"True",
"if",
"self",
".",
"_drag_image",
":",
"self",
".",
"_drag_image",
".",
"EndDrag",
"(",
")",
"del",
"self",
".",
"_drag_image",
"self",
".",
"_drag_image",
"=",
"None",
"if",
"self",
".",
"_agwFlags",
"&",
"AUI_NB_DRAW_DND_TAB",
":",
"# Create the custom draw image from the icons and the text of the item",
"mouse_tab",
"=",
"self",
".",
"GetIdxFromWindow",
"(",
"wnd",
")",
"page",
"=",
"self",
".",
"_pages",
"[",
"mouse_tab",
"]",
"tab_button",
"=",
"self",
".",
"_tab_close_buttons",
"[",
"mouse_tab",
"]",
"self",
".",
"_drag_image",
"=",
"TabDragImage",
"(",
"self",
",",
"page",
",",
"tab_button",
".",
"cur_state",
",",
"self",
".",
"_art",
")",
"if",
"self",
".",
"_agwFlags",
"&",
"AUI_NB_TAB_FLOAT",
":",
"self",
".",
"_drag_image",
".",
"BeginDrag",
"(",
"wx",
".",
"Point",
"(",
"0",
",",
"0",
")",
",",
"self",
",",
"fullScreen",
"=",
"True",
")",
"else",
":",
"self",
".",
"_drag_image",
".",
"BeginDragBounded",
"(",
"wx",
".",
"Point",
"(",
"0",
",",
"0",
")",
",",
"self",
",",
"self",
".",
"GetParent",
"(",
")",
")",
"# Capture the mouse cursor position offset relative to",
"# The tab image location",
"self",
".",
"_drag_img_offset",
"=",
"(",
"pos",
"[",
"0",
"]",
"-",
"page",
".",
"rect",
".",
"x",
",",
"pos",
"[",
"1",
"]",
"-",
"page",
".",
"rect",
".",
"y",
")",
"self",
".",
"_drag_image",
".",
"Show",
"(",
")",
"if",
"not",
"wnd",
":",
"evt2",
"=",
"AuiNotebookEvent",
"(",
"wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG",
",",
"self",
".",
"GetId",
"(",
")",
")",
"evt2",
".",
"SetSelection",
"(",
"self",
".",
"GetIdxFromWindow",
"(",
"self",
".",
"_click_tab",
")",
")",
"evt2",
".",
"SetOldSelection",
"(",
"evt2",
".",
"GetSelection",
"(",
")",
")",
"evt2",
".",
"SetEventObject",
"(",
"self",
")",
"self",
".",
"GetEventHandler",
"(",
")",
".",
"ProcessEvent",
"(",
"evt2",
")",
"if",
"evt2",
".",
"GetDispatched",
"(",
")",
":",
"return",
"evt3",
"=",
"AuiNotebookEvent",
"(",
"wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION",
",",
"self",
".",
"GetId",
"(",
")",
")",
"evt3",
".",
"SetSelection",
"(",
"self",
".",
"GetIdxFromWindow",
"(",
"self",
".",
"_click_tab",
")",
")",
"evt3",
".",
"SetOldSelection",
"(",
"evt3",
".",
"GetSelection",
"(",
")",
")",
"evt3",
".",
"SetEventObject",
"(",
"self",
")",
"self",
".",
"GetEventHandler",
"(",
")",
".",
"ProcessEvent",
"(",
"evt3",
")",
"if",
"self",
".",
"_drag_image",
":",
"# Apply the drag images offset",
"pos",
"-=",
"self",
".",
"_drag_img_offset",
"self",
".",
"_drag_image",
".",
"Move",
"(",
"pos",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L2152-L2258 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsCJKCompatibility | (code) | return ret | Check whether the character is part of CJKCompatibility UCS
Block | Check whether the character is part of CJKCompatibility UCS
Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"CJKCompatibility",
"UCS",
"Block"
] | def uCSIsCJKCompatibility(code):
"""Check whether the character is part of CJKCompatibility UCS
Block """
ret = libxml2mod.xmlUCSIsCJKCompatibility(code)
return ret | [
"def",
"uCSIsCJKCompatibility",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCJKCompatibility",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1399-L1403 | |
OpenNebula/one | 982e09706fc444ae60a8ad2f818d6a795cbbdab4 | src/oca/python/pyone/__init__.py | python | OneServer.__init__ | (self, uri, session, timeout=None, **options) | Override the constructor to take the authentication or session
Will also configure the socket timeout
:param uri: OpenNebula endpoint
:param session: OpenNebula authentication session
:param timeout: Socket timetout
:param options: additional options for ServerProxy | Override the constructor to take the authentication or session
Will also configure the socket timeout
:param uri: OpenNebula endpoint
:param session: OpenNebula authentication session
:param timeout: Socket timetout
:param options: additional options for ServerProxy | [
"Override",
"the",
"constructor",
"to",
"take",
"the",
"authentication",
"or",
"session",
"Will",
"also",
"configure",
"the",
"socket",
"timeout",
":",
"param",
"uri",
":",
"OpenNebula",
"endpoint",
":",
"param",
"session",
":",
"OpenNebula",
"authentication",
"session",
":",
"param",
"timeout",
":",
"Socket",
"timetout",
":",
"param",
"options",
":",
"additional",
"options",
"for",
"ServerProxy"
] | def __init__(self, uri, session, timeout=None, **options):
"""
Override the constructor to take the authentication or session
Will also configure the socket timeout
:param uri: OpenNebula endpoint
:param session: OpenNebula authentication session
:param timeout: Socket timetout
:param options: additional options for ServerProxy
"""
self.__session = session
if timeout:
# note that this will affect other classes using sockets too.
socket.setdefaulttimeout(timeout)
# register helpers:
self.__helpers = {
"marketapp.export": marketapp_export
}
transport = RequestsTransport()
transport.set_https(uri.startswith('https'))
xmlrpc.client.ServerProxy.__init__(
self,
uri,
transport=transport,
**options) | [
"def",
"__init__",
"(",
"self",
",",
"uri",
",",
"session",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"__session",
"=",
"session",
"if",
"timeout",
":",
"# note that this will affect other classes using sockets too.",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"# register helpers:",
"self",
".",
"__helpers",
"=",
"{",
"\"marketapp.export\"",
":",
"marketapp_export",
"}",
"transport",
"=",
"RequestsTransport",
"(",
")",
"transport",
".",
"set_https",
"(",
"uri",
".",
"startswith",
"(",
"'https'",
")",
")",
"xmlrpc",
".",
"client",
".",
"ServerProxy",
".",
"__init__",
"(",
"self",
",",
"uri",
",",
"transport",
"=",
"transport",
",",
"*",
"*",
"options",
")"
] | https://github.com/OpenNebula/one/blob/982e09706fc444ae60a8ad2f818d6a795cbbdab4/src/oca/python/pyone/__init__.py#L190-L217 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.tkraise | (self, aboveThis=None) | Raise this widget in the stacking order. | Raise this widget in the stacking order. | [
"Raise",
"this",
"widget",
"in",
"the",
"stacking",
"order",
"."
] | def tkraise(self, aboveThis=None):
"""Raise this widget in the stacking order."""
self.tk.call('raise', self._w, aboveThis) | [
"def",
"tkraise",
"(",
"self",
",",
"aboveThis",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'raise'",
",",
"self",
".",
"_w",
",",
"aboveThis",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L717-L719 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/quantization_mappings.py | python | get_default_qconfig_propagation_list | () | return copy.deepcopy(QCONFIG_PROPAGATE_MODULE_CLASS_LIST) | Get the default list of module types that we'll attach qconfig
attribute to in prepare | Get the default list of module types that we'll attach qconfig
attribute to in prepare | [
"Get",
"the",
"default",
"list",
"of",
"module",
"types",
"that",
"we",
"ll",
"attach",
"qconfig",
"attribute",
"to",
"in",
"prepare"
] | def get_default_qconfig_propagation_list() -> Set[Callable]:
''' Get the default list of module types that we'll attach qconfig
attribute to in prepare
'''
QCONFIG_PROPAGATE_MODULE_CLASS_LIST = (
(set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys()) |
set(DEFAULT_QAT_MODULE_MAPPINGS.keys()) |
set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys()) |
_INCLUDE_QCONFIG_PROPAGATE_LIST)
)
return copy.deepcopy(QCONFIG_PROPAGATE_MODULE_CLASS_LIST) | [
"def",
"get_default_qconfig_propagation_list",
"(",
")",
"->",
"Set",
"[",
"Callable",
"]",
":",
"QCONFIG_PROPAGATE_MODULE_CLASS_LIST",
"=",
"(",
"(",
"set",
"(",
"DEFAULT_STATIC_QUANT_MODULE_MAPPINGS",
".",
"keys",
"(",
")",
")",
"|",
"set",
"(",
"DEFAULT_QAT_MODULE_MAPPINGS",
".",
"keys",
"(",
")",
")",
"|",
"set",
"(",
"DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS",
".",
"keys",
"(",
")",
")",
"|",
"_INCLUDE_QCONFIG_PROPAGATE_LIST",
")",
")",
"return",
"copy",
".",
"deepcopy",
"(",
"QCONFIG_PROPAGATE_MODULE_CLASS_LIST",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/quantization_mappings.py#L244-L254 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/specs_lib.py | python | debug | (mode=True) | Turn on/off debugging mode.
Debugging mode prints more information about the construction
of a network.
Args:
mode: True if turned on, False otherwise | Turn on/off debugging mode. | [
"Turn",
"on",
"/",
"off",
"debugging",
"mode",
"."
] | def debug(mode=True):
"""Turn on/off debugging mode.
Debugging mode prints more information about the construction
of a network.
Args:
mode: True if turned on, False otherwise
"""
global debug_
debug_ = mode | [
"def",
"debug",
"(",
"mode",
"=",
"True",
")",
":",
"global",
"debug_",
"debug_",
"=",
"mode"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/specs_lib.py#L228-L238 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/platform/benchmark.py | python | Benchmark._get_name | (self, overwrite_name) | return name | Returns full name of class and method calling report_benchmark. | Returns full name of class and method calling report_benchmark. | [
"Returns",
"full",
"name",
"of",
"class",
"and",
"method",
"calling",
"report_benchmark",
"."
] | def _get_name(self, overwrite_name):
"""Returns full name of class and method calling report_benchmark."""
# Find the caller method (outermost Benchmark class)
stack = inspect.stack()
calling_class = None
name = None
for frame in stack[::-1]:
f_locals = frame[0].f_locals
f_self = f_locals.get("self", None)
if isinstance(f_self, Benchmark):
calling_class = f_self # Get the outermost stack Benchmark call
name = frame[3] # Get the method name
break
if calling_class is None:
raise ValueError("Unable to determine calling Benchmark class.")
# Use the method name, or overwrite_name is provided.
name = overwrite_name or name
# Prefix the name with the class name.
class_name = type(calling_class).__name__
name = "%s.%s" % (class_name, name)
return name | [
"def",
"_get_name",
"(",
"self",
",",
"overwrite_name",
")",
":",
"# Find the caller method (outermost Benchmark class)",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"calling_class",
"=",
"None",
"name",
"=",
"None",
"for",
"frame",
"in",
"stack",
"[",
":",
":",
"-",
"1",
"]",
":",
"f_locals",
"=",
"frame",
"[",
"0",
"]",
".",
"f_locals",
"f_self",
"=",
"f_locals",
".",
"get",
"(",
"\"self\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"f_self",
",",
"Benchmark",
")",
":",
"calling_class",
"=",
"f_self",
"# Get the outermost stack Benchmark call",
"name",
"=",
"frame",
"[",
"3",
"]",
"# Get the method name",
"break",
"if",
"calling_class",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to determine calling Benchmark class.\"",
")",
"# Use the method name, or overwrite_name is provided.",
"name",
"=",
"overwrite_name",
"or",
"name",
"# Prefix the name with the class name.",
"class_name",
"=",
"type",
"(",
"calling_class",
")",
".",
"__name__",
"name",
"=",
"\"%s.%s\"",
"%",
"(",
"class_name",
",",
"name",
")",
"return",
"name"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/platform/benchmark.py#L127-L149 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | TopLevelWindow.SetIcons | (*args, **kwargs) | return _windows_.TopLevelWindow_SetIcons(*args, **kwargs) | SetIcons(self, wxIconBundle icons) | SetIcons(self, wxIconBundle icons) | [
"SetIcons",
"(",
"self",
"wxIconBundle",
"icons",
")"
] | def SetIcons(*args, **kwargs):
"""SetIcons(self, wxIconBundle icons)"""
return _windows_.TopLevelWindow_SetIcons(*args, **kwargs) | [
"def",
"SetIcons",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_SetIcons",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L437-L439 | |
googleprojectzero/BrokenType | cf49a52b8e35b7d684fc8bc6b2ea8b923c177c2e | truetype-generator/truetype_generate.py | python | TTXParser._Handler_TTGlyph | (self, path, node) | Resets the number of contours and points in the glyph (because there is a new one), and inserts a child
<instructions> tag if one is not already present, in order to have TrueType instructions executed for all
glyphs in the font. | Resets the number of contours and points in the glyph (because there is a new one), and inserts a child
<instructions> tag if one is not already present, in order to have TrueType instructions executed for all
glyphs in the font. | [
"Resets",
"the",
"number",
"of",
"contours",
"and",
"points",
"in",
"the",
"glyph",
"(",
"because",
"there",
"is",
"a",
"new",
"one",
")",
"and",
"inserts",
"a",
"child",
"<instructions",
">",
"tag",
"if",
"one",
"is",
"not",
"already",
"present",
"in",
"order",
"to",
"have",
"TrueType",
"instructions",
"executed",
"for",
"all",
"glyphs",
"in",
"the",
"font",
"."
] | def _Handler_TTGlyph(self, path, node):
"""Resets the number of contours and points in the glyph (because there is a new one), and inserts a child
<instructions> tag if one is not already present, in order to have TrueType instructions executed for all
glyphs in the font.
"""
self._contours_in_glyph = 0
self._points_in_glyph = 0
# Only add the instructions for glyphs which have at least one contour.
if (node.find("contour") != None) and (node.find("instructions") == None):
instructions_node = ET.SubElement(node, "instructions")
ET.SubElement(instructions_node, "assembly") | [
"def",
"_Handler_TTGlyph",
"(",
"self",
",",
"path",
",",
"node",
")",
":",
"self",
".",
"_contours_in_glyph",
"=",
"0",
"self",
".",
"_points_in_glyph",
"=",
"0",
"# Only add the instructions for glyphs which have at least one contour.",
"if",
"(",
"node",
".",
"find",
"(",
"\"contour\"",
")",
"!=",
"None",
")",
"and",
"(",
"node",
".",
"find",
"(",
"\"instructions\"",
")",
"==",
"None",
")",
":",
"instructions_node",
"=",
"ET",
".",
"SubElement",
"(",
"node",
",",
"\"instructions\"",
")",
"ET",
".",
"SubElement",
"(",
"instructions_node",
",",
"\"assembly\"",
")"
] | https://github.com/googleprojectzero/BrokenType/blob/cf49a52b8e35b7d684fc8bc6b2ea8b923c177c2e/truetype-generator/truetype_generate.py#L671-L682 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | PyGridTableBase.Destroy | (*args, **kwargs) | return _grid.PyGridTableBase_Destroy(*args, **kwargs) | Destroy(self)
Deletes the C++ object this Python object is a proxy for. | Destroy(self) | [
"Destroy",
"(",
"self",
")"
] | def Destroy(*args, **kwargs):
"""
Destroy(self)
Deletes the C++ object this Python object is a proxy for.
"""
args[0].this.own(False)
return _grid.PyGridTableBase_Destroy(*args, **kwargs) | [
"def",
"Destroy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"[",
"0",
"]",
".",
"this",
".",
"own",
"(",
"False",
")",
"return",
"_grid",
".",
"PyGridTableBase_Destroy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L941-L948 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/change_internal_only.py | python | ChangeInternalOnlyHandler._UpdateBot | (self, bot_name, internal_only, cursor=None) | Starts updating internal_only for the given bot and associated data. | Starts updating internal_only for the given bot and associated data. | [
"Starts",
"updating",
"internal_only",
"for",
"the",
"given",
"bot",
"and",
"associated",
"data",
"."
] | def _UpdateBot(self, bot_name, internal_only, cursor=None):
"""Starts updating internal_only for the given bot and associated data."""
master, bot = bot_name.split('/')
bot_key = ndb.Key('Master', master, 'Bot', bot)
if not cursor:
# First time updating for this Bot.
bot_entity = bot_key.get()
if bot_entity.internal_only != internal_only:
bot_entity.internal_only = internal_only
bot_entity.put()
else:
cursor = datastore_query.Cursor(urlsafe=cursor)
# Fetch a certain number of TestMetadata entities starting from cursor. See:
# https://developers.google.com/appengine/docs/python/ndb/queryclass
# Start update tasks for each existing subordinate TestMetadata.
test_query = graph_data.TestMetadata.query(
graph_data.TestMetadata.master_name == master,
graph_data.TestMetadata.bot_name == bot)
test_keys, next_cursor, more = test_query.fetch_page(
_MAX_TESTS_TO_PUT, start_cursor=cursor, keys_only=True)
for test_key in test_keys:
taskqueue.add(
url='/change_internal_only',
params={
'test': test_key.urlsafe(),
'internal_only': 'true' if internal_only else 'false',
},
queue_name=_QUEUE_NAME)
if more:
taskqueue.add(
url='/change_internal_only',
params={
'bots': bot_name,
'cursor': next_cursor.urlsafe(),
'internal_only': 'true' if internal_only else 'false',
},
queue_name=_QUEUE_NAME) | [
"def",
"_UpdateBot",
"(",
"self",
",",
"bot_name",
",",
"internal_only",
",",
"cursor",
"=",
"None",
")",
":",
"master",
",",
"bot",
"=",
"bot_name",
".",
"split",
"(",
"'/'",
")",
"bot_key",
"=",
"ndb",
".",
"Key",
"(",
"'Master'",
",",
"master",
",",
"'Bot'",
",",
"bot",
")",
"if",
"not",
"cursor",
":",
"# First time updating for this Bot.",
"bot_entity",
"=",
"bot_key",
".",
"get",
"(",
")",
"if",
"bot_entity",
".",
"internal_only",
"!=",
"internal_only",
":",
"bot_entity",
".",
"internal_only",
"=",
"internal_only",
"bot_entity",
".",
"put",
"(",
")",
"else",
":",
"cursor",
"=",
"datastore_query",
".",
"Cursor",
"(",
"urlsafe",
"=",
"cursor",
")",
"# Fetch a certain number of TestMetadata entities starting from cursor. See:",
"# https://developers.google.com/appengine/docs/python/ndb/queryclass",
"# Start update tasks for each existing subordinate TestMetadata.",
"test_query",
"=",
"graph_data",
".",
"TestMetadata",
".",
"query",
"(",
"graph_data",
".",
"TestMetadata",
".",
"master_name",
"==",
"master",
",",
"graph_data",
".",
"TestMetadata",
".",
"bot_name",
"==",
"bot",
")",
"test_keys",
",",
"next_cursor",
",",
"more",
"=",
"test_query",
".",
"fetch_page",
"(",
"_MAX_TESTS_TO_PUT",
",",
"start_cursor",
"=",
"cursor",
",",
"keys_only",
"=",
"True",
")",
"for",
"test_key",
"in",
"test_keys",
":",
"taskqueue",
".",
"add",
"(",
"url",
"=",
"'/change_internal_only'",
",",
"params",
"=",
"{",
"'test'",
":",
"test_key",
".",
"urlsafe",
"(",
")",
",",
"'internal_only'",
":",
"'true'",
"if",
"internal_only",
"else",
"'false'",
",",
"}",
",",
"queue_name",
"=",
"_QUEUE_NAME",
")",
"if",
"more",
":",
"taskqueue",
".",
"add",
"(",
"url",
"=",
"'/change_internal_only'",
",",
"params",
"=",
"{",
"'bots'",
":",
"bot_name",
",",
"'cursor'",
":",
"next_cursor",
".",
"urlsafe",
"(",
")",
",",
"'internal_only'",
":",
"'true'",
"if",
"internal_only",
"else",
"'false'",
",",
"}",
",",
"queue_name",
"=",
"_QUEUE_NAME",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/change_internal_only.py#L109-L150 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/multiindex.py | python | MultiIndex.get_loc | (self, key, method=None, tolerance=None) | return mask | Get location for a label or a tuple of labels.
The location is returned as an integer/slice or boolean mask.
Parameters
----------
key : label or tuple of labels (one for each level)
method : None
Returns
-------
loc : int, slice object or boolean mask
- If index is unique, search result is unique, return a single int.
- If index is monotonic, index is returned as a slice object.
- Otherwise, cudf attempts a best effort to convert the search
result into a slice object, and will return a boolean mask if
failed to do so. Notice this can deviate from Pandas behavior
in some situations.
Examples
--------
>>> import cudf
>>> mi = cudf.MultiIndex.from_tuples(
... [('a', 'd'), ('b', 'e'), ('b', 'f')])
>>> mi.get_loc('b')
slice(1, 3, None)
>>> mi.get_loc(('b', 'e'))
1
>>> non_monotonic_non_unique_idx = cudf.MultiIndex.from_tuples(
... [('c', 'd'), ('b', 'e'), ('a', 'f'), ('b', 'e')])
>>> non_monotonic_non_unique_idx.get_loc('b') # differ from pandas
slice(1, 4, 2)
.. pandas-compat::
**MultiIndex.get_loc**
The return types of this function may deviates from the
method provided by Pandas. If the index is neither
lexicographically sorted nor unique, a best effort attempt is made
to coerce the found indices into a slice. For example:
.. code-block::
>>> import pandas as pd
>>> import cudf
>>> x = pd.MultiIndex.from_tuples([
... (2, 1, 1), (1, 2, 3), (1, 2, 1),
... (1, 1, 1), (1, 1, 1), (2, 2, 1),
... ])
>>> x.get_loc(1)
array([False, True, True, True, True, False])
>>> cudf.from_pandas(x).get_loc(1)
slice(1, 5, 1) | Get location for a label or a tuple of labels. | [
"Get",
"location",
"for",
"a",
"label",
"or",
"a",
"tuple",
"of",
"labels",
"."
] | def get_loc(self, key, method=None, tolerance=None):
"""
Get location for a label or a tuple of labels.
The location is returned as an integer/slice or boolean mask.
Parameters
----------
key : label or tuple of labels (one for each level)
method : None
Returns
-------
loc : int, slice object or boolean mask
- If index is unique, search result is unique, return a single int.
- If index is monotonic, index is returned as a slice object.
- Otherwise, cudf attempts a best effort to convert the search
result into a slice object, and will return a boolean mask if
failed to do so. Notice this can deviate from Pandas behavior
in some situations.
Examples
--------
>>> import cudf
>>> mi = cudf.MultiIndex.from_tuples(
... [('a', 'd'), ('b', 'e'), ('b', 'f')])
>>> mi.get_loc('b')
slice(1, 3, None)
>>> mi.get_loc(('b', 'e'))
1
>>> non_monotonic_non_unique_idx = cudf.MultiIndex.from_tuples(
... [('c', 'd'), ('b', 'e'), ('a', 'f'), ('b', 'e')])
>>> non_monotonic_non_unique_idx.get_loc('b') # differ from pandas
slice(1, 4, 2)
.. pandas-compat::
**MultiIndex.get_loc**
The return types of this function may deviates from the
method provided by Pandas. If the index is neither
lexicographically sorted nor unique, a best effort attempt is made
to coerce the found indices into a slice. For example:
.. code-block::
>>> import pandas as pd
>>> import cudf
>>> x = pd.MultiIndex.from_tuples([
... (2, 1, 1), (1, 2, 3), (1, 2, 1),
... (1, 1, 1), (1, 1, 1), (2, 2, 1),
... ])
>>> x.get_loc(1)
array([False, True, True, True, True, False])
>>> cudf.from_pandas(x).get_loc(1)
slice(1, 5, 1)
"""
if tolerance is not None:
raise NotImplementedError(
"Parameter tolerance is unsupported yet."
)
if method is not None:
raise NotImplementedError(
"only the default get_loc method is currently supported for"
" MultiIndex"
)
is_sorted = (
self.is_monotonic_increasing or self.is_monotonic_decreasing
)
is_unique = self.is_unique
key = (key,) if not isinstance(key, tuple) else key
# Handle partial key search. If length of `key` is less than `nlevels`,
# Only search levels up to `len(key)` level.
key_as_table = cudf.core.frame.Frame(
{i: column.as_column(k, length=1) for i, k in enumerate(key)}
)
partial_index = self.__class__._from_data(
data=self._data.select_by_index(slice(key_as_table._num_columns))
)
(lower_bound, upper_bound, sort_inds,) = _lexsorted_equal_range(
partial_index, key_as_table, is_sorted
)
if lower_bound == upper_bound:
raise KeyError(key)
if is_unique and lower_bound + 1 == upper_bound:
# Indices are unique (Pandas constraint), search result is unique,
# return int.
return (
lower_bound
if is_sorted
else sort_inds.element_indexing(lower_bound)
)
if is_sorted:
# In monotonic index, lex search result is continuous. A slice for
# the range is returned.
return slice(lower_bound, upper_bound)
true_inds = sort_inds.slice(lower_bound, upper_bound).values
true_inds = _maybe_indices_to_slice(true_inds)
if isinstance(true_inds, slice):
return true_inds
# Not sorted and not unique. Return a boolean mask
mask = cupy.full(self._data.nrows, False)
mask[true_inds] = True
return mask | [
"def",
"get_loc",
"(",
"self",
",",
"key",
",",
"method",
"=",
"None",
",",
"tolerance",
"=",
"None",
")",
":",
"if",
"tolerance",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Parameter tolerance is unsupported yet.\"",
")",
"if",
"method",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"only the default get_loc method is currently supported for\"",
"\" MultiIndex\"",
")",
"is_sorted",
"=",
"(",
"self",
".",
"is_monotonic_increasing",
"or",
"self",
".",
"is_monotonic_decreasing",
")",
"is_unique",
"=",
"self",
".",
"is_unique",
"key",
"=",
"(",
"key",
",",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"tuple",
")",
"else",
"key",
"# Handle partial key search. If length of `key` is less than `nlevels`,",
"# Only search levels up to `len(key)` level.",
"key_as_table",
"=",
"cudf",
".",
"core",
".",
"frame",
".",
"Frame",
"(",
"{",
"i",
":",
"column",
".",
"as_column",
"(",
"k",
",",
"length",
"=",
"1",
")",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"key",
")",
"}",
")",
"partial_index",
"=",
"self",
".",
"__class__",
".",
"_from_data",
"(",
"data",
"=",
"self",
".",
"_data",
".",
"select_by_index",
"(",
"slice",
"(",
"key_as_table",
".",
"_num_columns",
")",
")",
")",
"(",
"lower_bound",
",",
"upper_bound",
",",
"sort_inds",
",",
")",
"=",
"_lexsorted_equal_range",
"(",
"partial_index",
",",
"key_as_table",
",",
"is_sorted",
")",
"if",
"lower_bound",
"==",
"upper_bound",
":",
"raise",
"KeyError",
"(",
"key",
")",
"if",
"is_unique",
"and",
"lower_bound",
"+",
"1",
"==",
"upper_bound",
":",
"# Indices are unique (Pandas constraint), search result is unique,",
"# return int.",
"return",
"(",
"lower_bound",
"if",
"is_sorted",
"else",
"sort_inds",
".",
"element_indexing",
"(",
"lower_bound",
")",
")",
"if",
"is_sorted",
":",
"# In monotonic index, lex search result is continuous. A slice for",
"# the range is returned.",
"return",
"slice",
"(",
"lower_bound",
",",
"upper_bound",
")",
"true_inds",
"=",
"sort_inds",
".",
"slice",
"(",
"lower_bound",
",",
"upper_bound",
")",
".",
"values",
"true_inds",
"=",
"_maybe_indices_to_slice",
"(",
"true_inds",
")",
"if",
"isinstance",
"(",
"true_inds",
",",
"slice",
")",
":",
"return",
"true_inds",
"# Not sorted and not unique. Return a boolean mask",
"mask",
"=",
"cupy",
".",
"full",
"(",
"self",
".",
"_data",
".",
"nrows",
",",
"False",
")",
"mask",
"[",
"true_inds",
"]",
"=",
"True",
"return",
"mask"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/multiindex.py#L1537-L1646 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | tools/clang/bindings/python/clang/cindex.py | python | Diagnostic.category_number | (self) | return conf.lib.clang_getDiagnosticCategory(self) | The category number for this diagnostic or 0 if unavailable. | The category number for this diagnostic or 0 if unavailable. | [
"The",
"category",
"number",
"for",
"this",
"diagnostic",
"or",
"0",
"if",
"unavailable",
"."
] | def category_number(self):
"""The category number for this diagnostic or 0 if unavailable."""
return conf.lib.clang_getDiagnosticCategory(self) | [
"def",
"category_number",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getDiagnosticCategory",
"(",
"self",
")"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/bindings/python/clang/cindex.py#L446-L448 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ListCtrl.SetItemState | (*args, **kwargs) | return _controls_.ListCtrl_SetItemState(*args, **kwargs) | SetItemState(self, long item, long state, long stateMask) -> bool | SetItemState(self, long item, long state, long stateMask) -> bool | [
"SetItemState",
"(",
"self",
"long",
"item",
"long",
"state",
"long",
"stateMask",
")",
"-",
">",
"bool"
] | def SetItemState(*args, **kwargs):
"""SetItemState(self, long item, long state, long stateMask) -> bool"""
return _controls_.ListCtrl_SetItemState(*args, **kwargs) | [
"def",
"SetItemState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_SetItemState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4535-L4537 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/shellapp.py | python | InteractiveShellApp.init_code | (self) | run the pre-flight code, specified via exec_lines | run the pre-flight code, specified via exec_lines | [
"run",
"the",
"pre",
"-",
"flight",
"code",
"specified",
"via",
"exec_lines"
] | def init_code(self):
"""run the pre-flight code, specified via exec_lines"""
self._run_startup_files()
self._run_exec_lines()
self._run_exec_files()
# Hide variables defined here from %who etc.
if self.hide_initial_ns:
self.shell.user_ns_hidden.update(self.shell.user_ns)
# command-line execution (ipython -i script.py, ipython -m module)
# should *not* be excluded from %whos
self._run_cmd_line_code()
self._run_module()
# flush output, so itwon't be attached to the first cell
sys.stdout.flush()
sys.stderr.flush() | [
"def",
"init_code",
"(",
"self",
")",
":",
"self",
".",
"_run_startup_files",
"(",
")",
"self",
".",
"_run_exec_lines",
"(",
")",
"self",
".",
"_run_exec_files",
"(",
")",
"# Hide variables defined here from %who etc.",
"if",
"self",
".",
"hide_initial_ns",
":",
"self",
".",
"shell",
".",
"user_ns_hidden",
".",
"update",
"(",
"self",
".",
"shell",
".",
"user_ns",
")",
"# command-line execution (ipython -i script.py, ipython -m module)",
"# should *not* be excluded from %whos",
"self",
".",
"_run_cmd_line_code",
"(",
")",
"self",
".",
"_run_module",
"(",
")",
"# flush output, so itwon't be attached to the first cell",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/shellapp.py#L263-L280 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/coordinates.py | python | Frame.worldRotation | (self) | return self._worldCoordinates[0] | Returns an element of SO(3) denoting the rotation from this frame
to world coordinates | Returns an element of SO(3) denoting the rotation from this frame
to world coordinates | [
"Returns",
"an",
"element",
"of",
"SO",
"(",
"3",
")",
"denoting",
"the",
"rotation",
"from",
"this",
"frame",
"to",
"world",
"coordinates"
] | def worldRotation(self):
"""Returns an element of SO(3) denoting the rotation from this frame
to world coordinates"""
return self._worldCoordinates[0] | [
"def",
"worldRotation",
"(",
"self",
")",
":",
"return",
"self",
".",
"_worldCoordinates",
"[",
"0",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/coordinates.py#L59-L62 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/valgrind/common.py | python | PlatformNames | () | Return an array of string to be used in paths for the platform
(e.g. suppressions, gtest filters, ignore files etc.)
The first element of the array describes the 'main' platform | Return an array of string to be used in paths for the platform
(e.g. suppressions, gtest filters, ignore files etc.)
The first element of the array describes the 'main' platform | [
"Return",
"an",
"array",
"of",
"string",
"to",
"be",
"used",
"in",
"paths",
"for",
"the",
"platform",
"(",
"e",
".",
"g",
".",
"suppressions",
"gtest",
"filters",
"ignore",
"files",
"etc",
".",
")",
"The",
"first",
"element",
"of",
"the",
"array",
"describes",
"the",
"main",
"platform"
] | def PlatformNames():
"""Return an array of string to be used in paths for the platform
(e.g. suppressions, gtest filters, ignore files etc.)
The first element of the array describes the 'main' platform
"""
if IsLinux():
return ['linux']
if IsMac():
return ['mac']
if IsWindows():
names = ['win32']
version_name = WindowsVersionName()
if version_name is not None:
names.append('win-%s' % version_name)
return names
raise NotImplementedError('Unknown platform "%s".' % sys.platform) | [
"def",
"PlatformNames",
"(",
")",
":",
"if",
"IsLinux",
"(",
")",
":",
"return",
"[",
"'linux'",
"]",
"if",
"IsMac",
"(",
")",
":",
"return",
"[",
"'mac'",
"]",
"if",
"IsWindows",
"(",
")",
":",
"names",
"=",
"[",
"'win32'",
"]",
"version_name",
"=",
"WindowsVersionName",
"(",
")",
"if",
"version_name",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"'win-%s'",
"%",
"version_name",
")",
"return",
"names",
"raise",
"NotImplementedError",
"(",
"'Unknown platform \"%s\".'",
"%",
"sys",
".",
"platform",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/valgrind/common.py#L147-L162 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/modulegraph/setup.py | python | _extractall | (self, path=".", members=None) | Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers(). | Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers(). | [
"Extract",
"all",
"members",
"from",
"the",
"archive",
"to",
"the",
"current",
"working",
"directory",
"and",
"set",
"owner",
"modification",
"time",
"and",
"permissions",
"on",
"directories",
"afterwards",
".",
"path",
"specifies",
"a",
"different",
"directory",
"to",
"extract",
"to",
".",
"members",
"is",
"optional",
"and",
"must",
"be",
"a",
"subset",
"of",
"the",
"list",
"returned",
"by",
"getmembers",
"()",
"."
] | def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
import copy
import operator
from tarfile import ExtractError
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)
# Reverse sort directories.
if sys.version_info < (2, 4):
def sorter(dir1, dir2):
return cmp(dir1.name, dir2.name)
directories.sort(sorter)
directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e) | [
"def",
"_extractall",
"(",
"self",
",",
"path",
"=",
"\".\"",
",",
"members",
"=",
"None",
")",
":",
"import",
"copy",
"import",
"operator",
"from",
"tarfile",
"import",
"ExtractError",
"directories",
"=",
"[",
"]",
"if",
"members",
"is",
"None",
":",
"members",
"=",
"self",
"for",
"tarinfo",
"in",
"members",
":",
"if",
"tarinfo",
".",
"isdir",
"(",
")",
":",
"# Extract directories with a safe mode.",
"directories",
".",
"append",
"(",
"tarinfo",
")",
"tarinfo",
"=",
"copy",
".",
"copy",
"(",
"tarinfo",
")",
"tarinfo",
".",
"mode",
"=",
"448",
"# decimal for oct 0700",
"self",
".",
"extract",
"(",
"tarinfo",
",",
"path",
")",
"# Reverse sort directories.",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"4",
")",
":",
"def",
"sorter",
"(",
"dir1",
",",
"dir2",
")",
":",
"return",
"cmp",
"(",
"dir1",
".",
"name",
",",
"dir2",
".",
"name",
")",
"directories",
".",
"sort",
"(",
"sorter",
")",
"directories",
".",
"reverse",
"(",
")",
"else",
":",
"directories",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'name'",
")",
",",
"reverse",
"=",
"True",
")",
"# Set correct owner, mtime and filemode on directories.",
"for",
"tarinfo",
"in",
"directories",
":",
"dirpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tarinfo",
".",
"name",
")",
"try",
":",
"self",
".",
"chown",
"(",
"tarinfo",
",",
"dirpath",
")",
"self",
".",
"utime",
"(",
"tarinfo",
",",
"dirpath",
")",
"self",
".",
"chmod",
"(",
"tarinfo",
",",
"dirpath",
")",
"except",
"ExtractError",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"self",
".",
"errorlevel",
">",
"1",
":",
"raise",
"else",
":",
"self",
".",
"_dbg",
"(",
"1",
",",
"\"tarfile: %s\"",
"%",
"e",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/modulegraph/setup.py#L472-L516 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py | python | Event.__init__ | (self, eventtype, source, target, arguments=None) | Constructor of Event objects.
Arguments:
eventtype -- A string describing the event.
source -- The originator of the event (a nick mask or a server).
target -- The target of the event (a nick or a channel).
arguments -- Any event specific arguments. | Constructor of Event objects. | [
"Constructor",
"of",
"Event",
"objects",
"."
] | def __init__(self, eventtype, source, target, arguments=None):
"""Constructor of Event objects.
Arguments:
eventtype -- A string describing the event.
source -- The originator of the event (a nick mask or a server).
target -- The target of the event (a nick or a channel).
arguments -- Any event specific arguments.
"""
self._eventtype = eventtype
self._source = source
self._target = target
if arguments:
self._arguments = arguments
else:
self._arguments = [] | [
"def",
"__init__",
"(",
"self",
",",
"eventtype",
",",
"source",
",",
"target",
",",
"arguments",
"=",
"None",
")",
":",
"self",
".",
"_eventtype",
"=",
"eventtype",
"self",
".",
"_source",
"=",
"source",
"self",
".",
"_target",
"=",
"target",
"if",
"arguments",
":",
"self",
".",
"_arguments",
"=",
"arguments",
"else",
":",
"self",
".",
"_arguments",
"=",
"[",
"]"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L1119-L1138 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | SizerItem.GetFlag | (*args, **kwargs) | return _core_.SizerItem_GetFlag(*args, **kwargs) | GetFlag(self) -> int
Get the flag value for this item. | GetFlag(self) -> int | [
"GetFlag",
"(",
"self",
")",
"-",
">",
"int"
] | def GetFlag(*args, **kwargs):
"""
GetFlag(self) -> int
Get the flag value for this item.
"""
return _core_.SizerItem_GetFlag(*args, **kwargs) | [
"def",
"GetFlag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItem_GetFlag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14211-L14217 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/json_schema_compiler/cpp_type_generator.py | python | CppTypeGenerator.__init__ | (self, model, schema_loader, default_namespace=None) | Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::api::sub. The generator will generate code suitable for
use in the given model's namespace. | Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::api::sub. The generator will generate code suitable for
use in the given model's namespace. | [
"Creates",
"a",
"cpp_type_generator",
".",
"The",
"given",
"root_namespace",
"should",
"be",
"of",
"the",
"format",
"extensions",
"::",
"api",
"::",
"sub",
".",
"The",
"generator",
"will",
"generate",
"code",
"suitable",
"for",
"use",
"in",
"the",
"given",
"model",
"s",
"namespace",
"."
] | def __init__(self, model, schema_loader, default_namespace=None):
"""Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::api::sub. The generator will generate code suitable for
use in the given model's namespace.
"""
self._default_namespace = default_namespace
if self._default_namespace is None:
self._default_namespace = model.namespaces.values()[0]
self._schema_loader = schema_loader | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"schema_loader",
",",
"default_namespace",
"=",
"None",
")",
":",
"self",
".",
"_default_namespace",
"=",
"default_namespace",
"if",
"self",
".",
"_default_namespace",
"is",
"None",
":",
"self",
".",
"_default_namespace",
"=",
"model",
".",
"namespaces",
".",
"values",
"(",
")",
"[",
"0",
"]",
"self",
".",
"_schema_loader",
"=",
"schema_loader"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/cpp_type_generator.py#L28-L36 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | python | DNNLinearCombinedRegressor.predict_scores | (self, x=None, input_fn=None, batch_size=None,
as_iterable=True) | return preds[key] | Returns predicted scores for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted scores (or an iterable of predicted scores if
as_iterable is True). If `label_dimension == 1`, the shape of the output
is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`. | Returns predicted scores for given features. | [
"Returns",
"predicted",
"scores",
"for",
"given",
"features",
"."
] | def predict_scores(self, x=None, input_fn=None, batch_size=None,
as_iterable=True):
"""Returns predicted scores for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted scores (or an iterable of predicted scores if
as_iterable is True). If `label_dimension == 1`, the shape of the output
is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`.
"""
key = prediction_key.PredictionKey.SCORES
preds = super(DNNLinearCombinedRegressor, self).predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key] | [
"def",
"predict_scores",
"(",
"self",
",",
"x",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"as_iterable",
"=",
"True",
")",
":",
"key",
"=",
"prediction_key",
".",
"PredictionKey",
".",
"SCORES",
"preds",
"=",
"super",
"(",
"DNNLinearCombinedRegressor",
",",
"self",
")",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"input_fn",
"=",
"input_fn",
",",
"batch_size",
"=",
"batch_size",
",",
"outputs",
"=",
"[",
"key",
"]",
",",
"as_iterable",
"=",
"as_iterable",
")",
"if",
"as_iterable",
":",
"return",
"(",
"pred",
"[",
"key",
"]",
"for",
"pred",
"in",
"preds",
")",
"return",
"preds",
"[",
"key",
"]"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L1097-L1124 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cygprofile/symbol_extractor.py | python | SymbolInfosFromBinary | (binary_filename) | Runs objdump to get all the symbols from a binary.
Args:
binary_filename: path to the binary.
Returns:
A list of SymbolInfo from the binary. | Runs objdump to get all the symbols from a binary. | [
"Runs",
"objdump",
"to",
"get",
"all",
"the",
"symbols",
"from",
"a",
"binary",
"."
] | def SymbolInfosFromBinary(binary_filename):
"""Runs objdump to get all the symbols from a binary.
Args:
binary_filename: path to the binary.
Returns:
A list of SymbolInfo from the binary.
"""
command = (symbol.ToolPath('objdump'), '-t', '-w', binary_filename)
p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
try:
result = _SymbolInfosFromStream(p.stdout)
return result
finally:
p.stdout.close()
p.wait() | [
"def",
"SymbolInfosFromBinary",
"(",
"binary_filename",
")",
":",
"command",
"=",
"(",
"symbol",
".",
"ToolPath",
"(",
"'objdump'",
")",
",",
"'-t'",
",",
"'-w'",
",",
"binary_filename",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"False",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"try",
":",
"result",
"=",
"_SymbolInfosFromStream",
"(",
"p",
".",
"stdout",
")",
"return",
"result",
"finally",
":",
"p",
".",
"stdout",
".",
"close",
"(",
")",
"p",
".",
"wait",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/symbol_extractor.py#L84-L100 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/TemplatePyMod/DocumentObject.py | python | DocumentObject.getEnumerationsOfProperty | (self,attr) | return self.__object__.getEnumerationsOfProperty(attr) | returns the documentation string of a given property | returns the documentation string of a given property | [
"returns",
"the",
"documentation",
"string",
"of",
"a",
"given",
"property"
] | def getEnumerationsOfProperty(self,attr):
"returns the documentation string of a given property"
return self.__object__.getEnumerationsOfProperty(attr) | [
"def",
"getEnumerationsOfProperty",
"(",
"self",
",",
"attr",
")",
":",
"return",
"self",
".",
"__object__",
".",
"getEnumerationsOfProperty",
"(",
"attr",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/TemplatePyMod/DocumentObject.py#L83-L85 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/browser.py | python | ChildBrowserTreeItem.GetText | (self) | Return the name of the function/class to display. | Return the name of the function/class to display. | [
"Return",
"the",
"name",
"of",
"the",
"function",
"/",
"class",
"to",
"display",
"."
] | def GetText(self):
"Return the name of the function/class to display."
name = self.name
if self.isfunction:
return "def " + name + "(...)"
else:
return "class " + name | [
"def",
"GetText",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"if",
"self",
".",
"isfunction",
":",
"return",
"\"def \"",
"+",
"name",
"+",
"\"(...)\"",
"else",
":",
"return",
"\"class \"",
"+",
"name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/browser.py#L199-L205 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTrace.GetMetaData | (self, error, buf, offset, thread_id) | return _lldb.SBTrace_GetMetaData(self, error, buf, offset, thread_id) | GetMetaData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t | GetMetaData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t | [
"GetMetaData",
"(",
"SBTrace",
"self",
"SBError",
"error",
"void",
"*",
"buf",
"size_t",
"offset",
"lldb",
"::",
"tid_t",
"thread_id",
")",
"-",
">",
"size_t"
] | def GetMetaData(self, error, buf, offset, thread_id):
"""GetMetaData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t"""
return _lldb.SBTrace_GetMetaData(self, error, buf, offset, thread_id) | [
"def",
"GetMetaData",
"(",
"self",
",",
"error",
",",
"buf",
",",
"offset",
",",
"thread_id",
")",
":",
"return",
"_lldb",
".",
"SBTrace_GetMetaData",
"(",
"self",
",",
"error",
",",
"buf",
",",
"offset",
",",
"thread_id",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12237-L12239 | |
husixu1/HUST-Homeworks | fbf6ed749eacab6e14bffea83703aadaf9324828 | DataMining/src/randomCF.py | python | userDistanceTable | (table) | get user-user distance table from original table
:param table: the original table
:return: user-user similarity sparse matrix,
in the form of 2-level dictionary | get user-user distance table from original table
:param table: the original table
:return: user-user similarity sparse matrix,
in the form of 2-level dictionary | [
"get",
"user",
"-",
"user",
"distance",
"table",
"from",
"original",
"table",
":",
"param",
"table",
":",
"the",
"original",
"table",
":",
"return",
":",
"user",
"-",
"user",
"similarity",
"sparse",
"matrix",
"in",
"the",
"form",
"of",
"2",
"-",
"level",
"dictionary"
] | def userDistanceTable(table):
"""get user-user distance table from original table
:param table: the original table
:return: user-user similarity sparse matrix,
in the form of 2-level dictionary
"""
#itemUserTable = table.T
#for users in itemUserTable:
# for user in users:
# user
pass | [
"def",
"userDistanceTable",
"(",
"table",
")",
":",
"#itemUserTable = table.T",
"#for users in itemUserTable:",
"# for user in users:",
"# user",
"pass"
] | https://github.com/husixu1/HUST-Homeworks/blob/fbf6ed749eacab6e14bffea83703aadaf9324828/DataMining/src/randomCF.py#L34-L44 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/build_utils.py | python | VersionString | () | return 'native_client_sdk_%s' % '_'.join(GetVersionNumbers()) | Returns the version of native client based on the svn revision number. | Returns the version of native client based on the svn revision number. | [
"Returns",
"the",
"version",
"of",
"native",
"client",
"based",
"on",
"the",
"svn",
"revision",
"number",
"."
] | def VersionString():
'''Returns the version of native client based on the svn revision number.'''
return 'native_client_sdk_%s' % '_'.join(GetVersionNumbers()) | [
"def",
"VersionString",
"(",
")",
":",
"return",
"'native_client_sdk_%s'",
"%",
"'_'",
".",
"join",
"(",
"GetVersionNumbers",
"(",
")",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/build_utils.py#L190-L192 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListItem.SetData | (self, data) | Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems. | Sets client data for the item. | [
"Sets",
"client",
"data",
"for",
"the",
"item",
"."
] | def SetData(self, data):
"""
Sets client data for the item.
:param `data`: the client data associated to the item.
:note: Please note that client data is associated with the item and not
with subitems.
"""
self._mask |= ULC_MASK_DATA
self._data = data | [
"def",
"SetData",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_mask",
"|=",
"ULC_MASK_DATA",
"self",
".",
"_data",
"=",
"data"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L1552-L1563 | ||
Netflix/NfWebCrypto | 499faf4eb9f9ccf0b21dc728e974970f54bd6c52 | plugin/ppapi/ppapi/generators/idl_gen_pnacl.py | python | PnaclGen.ArgsNeedWrapping | (self, args) | return False | Return true if any parameter in the list needs wrapping. | Return true if any parameter in the list needs wrapping. | [
"Return",
"true",
"if",
"any",
"parameter",
"in",
"the",
"list",
"needs",
"wrapping",
"."
] | def ArgsNeedWrapping(self, args):
"""Return true if any parameter in the list needs wrapping.
"""
for arg in args:
(type_str, name, array_dims, more_args) = arg
if self.TypeNeedsWrapping(type_str, array_dims):
return True
return False | [
"def",
"ArgsNeedWrapping",
"(",
"self",
",",
"args",
")",
":",
"for",
"arg",
"in",
"args",
":",
"(",
"type_str",
",",
"name",
",",
"array_dims",
",",
"more_args",
")",
"=",
"arg",
"if",
"self",
".",
"TypeNeedsWrapping",
"(",
"type_str",
",",
"array_dims",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_gen_pnacl.py#L100-L107 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/png/png.py | python | read_pnm_header | (infile, supported=('P5','P6')) | return header[0], header[1], header[2], depth, header[3] | Read a PNM header, returning (format,width,height,depth,maxval).
`width` and `height` are in pixels. `depth` is the number of
channels in the image; for PBM and PGM it is synthesized as 1, for
PPM as 3; for PAM images it is read from the header. `maxval` is
synthesized (as 1) for PBM images. | Read a PNM header, returning (format,width,height,depth,maxval).
`width` and `height` are in pixels. `depth` is the number of
channels in the image; for PBM and PGM it is synthesized as 1, for
PPM as 3; for PAM images it is read from the header. `maxval` is
synthesized (as 1) for PBM images. | [
"Read",
"a",
"PNM",
"header",
"returning",
"(",
"format",
"width",
"height",
"depth",
"maxval",
")",
".",
"width",
"and",
"height",
"are",
"in",
"pixels",
".",
"depth",
"is",
"the",
"number",
"of",
"channels",
"in",
"the",
"image",
";",
"for",
"PBM",
"and",
"PGM",
"it",
"is",
"synthesized",
"as",
"1",
"for",
"PPM",
"as",
"3",
";",
"for",
"PAM",
"images",
"it",
"is",
"read",
"from",
"the",
"header",
".",
"maxval",
"is",
"synthesized",
"(",
"as",
"1",
")",
"for",
"PBM",
"images",
"."
] | def read_pnm_header(infile, supported=('P5','P6')):
"""
Read a PNM header, returning (format,width,height,depth,maxval).
`width` and `height` are in pixels. `depth` is the number of
channels in the image; for PBM and PGM it is synthesized as 1, for
PPM as 3; for PAM images it is read from the header. `maxval` is
synthesized (as 1) for PBM images.
"""
# Generally, see http://netpbm.sourceforge.net/doc/ppm.html
# and http://netpbm.sourceforge.net/doc/pam.html
supported = [strtobytes(x) for x in supported]
# Technically 'P7' must be followed by a newline, so by using
# rstrip() we are being liberal in what we accept. I think this
# is acceptable.
type = infile.read(3).rstrip()
if type not in supported:
raise NotImplementedError('file format %s not supported' % type)
if type == strtobytes('P7'):
# PAM header parsing is completely different.
return read_pam_header(infile)
# Expected number of tokens in header (3 for P4, 4 for P6)
expected = 4
pbm = ('P1', 'P4')
if type in pbm:
expected = 3
header = [type]
# We have to read the rest of the header byte by byte because the
# final whitespace character (immediately following the MAXVAL in
# the case of P6) may not be a newline. Of course all PNM files in
# the wild use a newline at this point, so it's tempting to use
# readline; but it would be wrong.
def getc():
c = infile.read(1)
if not c:
raise Error('premature EOF reading PNM header')
return c
c = getc()
while True:
# Skip whitespace that precedes a token.
while c.isspace():
c = getc()
# Skip comments.
while c == '#':
while c not in '\n\r':
c = getc()
if not c.isdigit():
raise Error('unexpected character %s found in header' % c)
# According to the specification it is legal to have comments
# that appear in the middle of a token.
# This is bonkers; I've never seen it; and it's a bit awkward to
# code good lexers in Python (no goto). So we break on such
# cases.
token = strtobytes('')
while c.isdigit():
token += c
c = getc()
# Slight hack. All "tokens" are decimal integers, so convert
# them here.
header.append(int(token))
if len(header) == expected:
break
# Skip comments (again)
while c == '#':
while c not in '\n\r':
c = getc()
if not c.isspace():
raise Error('expected header to end with whitespace, not %s' % c)
if type in pbm:
# synthesize a MAXVAL
header.append(1)
depth = (1,3)[type == strtobytes('P6')]
return header[0], header[1], header[2], depth, header[3] | [
"def",
"read_pnm_header",
"(",
"infile",
",",
"supported",
"=",
"(",
"'P5'",
",",
"'P6'",
")",
")",
":",
"# Generally, see http://netpbm.sourceforge.net/doc/ppm.html",
"# and http://netpbm.sourceforge.net/doc/pam.html",
"supported",
"=",
"[",
"strtobytes",
"(",
"x",
")",
"for",
"x",
"in",
"supported",
"]",
"# Technically 'P7' must be followed by a newline, so by using",
"# rstrip() we are being liberal in what we accept. I think this",
"# is acceptable.",
"type",
"=",
"infile",
".",
"read",
"(",
"3",
")",
".",
"rstrip",
"(",
")",
"if",
"type",
"not",
"in",
"supported",
":",
"raise",
"NotImplementedError",
"(",
"'file format %s not supported'",
"%",
"type",
")",
"if",
"type",
"==",
"strtobytes",
"(",
"'P7'",
")",
":",
"# PAM header parsing is completely different.",
"return",
"read_pam_header",
"(",
"infile",
")",
"# Expected number of tokens in header (3 for P4, 4 for P6)",
"expected",
"=",
"4",
"pbm",
"=",
"(",
"'P1'",
",",
"'P4'",
")",
"if",
"type",
"in",
"pbm",
":",
"expected",
"=",
"3",
"header",
"=",
"[",
"type",
"]",
"# We have to read the rest of the header byte by byte because the",
"# final whitespace character (immediately following the MAXVAL in",
"# the case of P6) may not be a newline. Of course all PNM files in",
"# the wild use a newline at this point, so it's tempting to use",
"# readline; but it would be wrong.",
"def",
"getc",
"(",
")",
":",
"c",
"=",
"infile",
".",
"read",
"(",
"1",
")",
"if",
"not",
"c",
":",
"raise",
"Error",
"(",
"'premature EOF reading PNM header'",
")",
"return",
"c",
"c",
"=",
"getc",
"(",
")",
"while",
"True",
":",
"# Skip whitespace that precedes a token.",
"while",
"c",
".",
"isspace",
"(",
")",
":",
"c",
"=",
"getc",
"(",
")",
"# Skip comments.",
"while",
"c",
"==",
"'#'",
":",
"while",
"c",
"not",
"in",
"'\\n\\r'",
":",
"c",
"=",
"getc",
"(",
")",
"if",
"not",
"c",
".",
"isdigit",
"(",
")",
":",
"raise",
"Error",
"(",
"'unexpected character %s found in header'",
"%",
"c",
")",
"# According to the specification it is legal to have comments",
"# that appear in the middle of a token.",
"# This is bonkers; I've never seen it; and it's a bit awkward to",
"# code good lexers in Python (no goto). So we break on such",
"# cases.",
"token",
"=",
"strtobytes",
"(",
"''",
")",
"while",
"c",
".",
"isdigit",
"(",
")",
":",
"token",
"+=",
"c",
"c",
"=",
"getc",
"(",
")",
"# Slight hack. All \"tokens\" are decimal integers, so convert",
"# them here.",
"header",
".",
"append",
"(",
"int",
"(",
"token",
")",
")",
"if",
"len",
"(",
"header",
")",
"==",
"expected",
":",
"break",
"# Skip comments (again)",
"while",
"c",
"==",
"'#'",
":",
"while",
"c",
"not",
"in",
"'\\n\\r'",
":",
"c",
"=",
"getc",
"(",
")",
"if",
"not",
"c",
".",
"isspace",
"(",
")",
":",
"raise",
"Error",
"(",
"'expected header to end with whitespace, not %s'",
"%",
"c",
")",
"if",
"type",
"in",
"pbm",
":",
"# synthesize a MAXVAL",
"header",
".",
"append",
"(",
"1",
")",
"depth",
"=",
"(",
"1",
",",
"3",
")",
"[",
"type",
"==",
"strtobytes",
"(",
"'P6'",
")",
"]",
"return",
"header",
"[",
"0",
"]",
",",
"header",
"[",
"1",
"]",
",",
"header",
"[",
"2",
"]",
",",
"depth",
",",
"header",
"[",
"3",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L3598-L3675 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/filter/CommonFilters.py | python | CommonFilters.setBlurSharpen | (self, amount=0.0) | return self.reconfigure(fullrebuild, "BlurSharpen") | Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have any effect.
A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image. | Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have any effect.
A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image. | [
"Enables",
"the",
"blur",
"/",
"sharpen",
"filter",
".",
"If",
"the",
"amount",
"parameter",
"is",
"1",
".",
"0",
"it",
"will",
"not",
"have",
"any",
"effect",
".",
"A",
"value",
"of",
"0",
".",
"0",
"means",
"fully",
"blurred",
"and",
"a",
"value",
"higher",
"than",
"1",
".",
"0",
"sharpens",
"the",
"image",
"."
] | def setBlurSharpen(self, amount=0.0):
"""Enables the blur/sharpen filter. If the 'amount' parameter is 1.0, it will not have any effect.
A value of 0.0 means fully blurred, and a value higher than 1.0 sharpens the image."""
fullrebuild = ("BlurSharpen" not in self.configuration)
self.configuration["BlurSharpen"] = amount
return self.reconfigure(fullrebuild, "BlurSharpen") | [
"def",
"setBlurSharpen",
"(",
"self",
",",
"amount",
"=",
"0.0",
")",
":",
"fullrebuild",
"=",
"(",
"\"BlurSharpen\"",
"not",
"in",
"self",
".",
"configuration",
")",
"self",
".",
"configuration",
"[",
"\"BlurSharpen\"",
"]",
"=",
"amount",
"return",
"self",
".",
"reconfigure",
"(",
"fullrebuild",
",",
"\"BlurSharpen\"",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/filter/CommonFilters.py#L555-L560 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/nntplib.py | python | NNTP.post | (self, f) | return self.getresp() | Process a POST command. Arguments:
- f: file containing the article
Returns:
- resp: server response if successful | Process a POST command. Arguments:
- f: file containing the article
Returns:
- resp: server response if successful | [
"Process",
"a",
"POST",
"command",
".",
"Arguments",
":",
"-",
"f",
":",
"file",
"containing",
"the",
"article",
"Returns",
":",
"-",
"resp",
":",
"server",
"response",
"if",
"successful"
] | def post(self, f):
"""Process a POST command. Arguments:
- f: file containing the article
Returns:
- resp: server response if successful"""
resp = self.shortcmd('POST')
# Raises error_??? if posting is not allowed
if resp[0] != '3':
raise NNTPReplyError(resp)
while 1:
line = f.readline()
if not line:
break
if line[-1] == '\n':
line = line[:-1]
if line[:1] == '.':
line = '.' + line
self.putline(line)
self.putline('.')
return self.getresp() | [
"def",
"post",
"(",
"self",
",",
"f",
")",
":",
"resp",
"=",
"self",
".",
"shortcmd",
"(",
"'POST'",
")",
"# Raises error_??? if posting is not allowed",
"if",
"resp",
"[",
"0",
"]",
"!=",
"'3'",
":",
"raise",
"NNTPReplyError",
"(",
"resp",
")",
"while",
"1",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"if",
"line",
"[",
":",
"1",
"]",
"==",
"'.'",
":",
"line",
"=",
"'.'",
"+",
"line",
"self",
".",
"putline",
"(",
"line",
")",
"self",
".",
"putline",
"(",
"'.'",
")",
"return",
"self",
".",
"getresp",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/nntplib.py#L549-L569 | |
ucsb-seclab/difuze | bb59a12ff87ad5ae45d9c60e349891bf80d72877 | helper_scripts/components/bear_llvm_build.py | python | build_drivers | (compilation_commands, linker_commands, kernel_src_dir,
target_arch, clang_path, llvm_link_path, llvm_bit_code_out, is_clang_build) | return True | The main method that performs the building and linking of the driver files.
:param compilation_commands: Parsed compilation commands from the json.
:param linker_commands: Parsed linker commands from the json.
:param kernel_src_dir: Path to the kernel source directory.
:param target_arch: Number representing target architecture.
:param clang_path: Path to clang.
:param llvm_link_path: Path to llvm-link
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:param is_clang_build: Flag to indicate that this is a clang build.
:return: True | The main method that performs the building and linking of the driver files.
:param compilation_commands: Parsed compilation commands from the json.
:param linker_commands: Parsed linker commands from the json.
:param kernel_src_dir: Path to the kernel source directory.
:param target_arch: Number representing target architecture.
:param clang_path: Path to clang.
:param llvm_link_path: Path to llvm-link
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:param is_clang_build: Flag to indicate that this is a clang build.
:return: True | [
"The",
"main",
"method",
"that",
"performs",
"the",
"building",
"and",
"linking",
"of",
"the",
"driver",
"files",
".",
":",
"param",
"compilation_commands",
":",
"Parsed",
"compilation",
"commands",
"from",
"the",
"json",
".",
":",
"param",
"linker_commands",
":",
"Parsed",
"linker",
"commands",
"from",
"the",
"json",
".",
":",
"param",
"kernel_src_dir",
":",
"Path",
"to",
"the",
"kernel",
"source",
"directory",
".",
":",
"param",
"target_arch",
":",
"Number",
"representing",
"target",
"architecture",
".",
":",
"param",
"clang_path",
":",
"Path",
"to",
"clang",
".",
":",
"param",
"llvm_link_path",
":",
"Path",
"to",
"llvm",
"-",
"link",
":",
"param",
"llvm_bit_code_out",
":",
"Folder",
"where",
"all",
"the",
"linked",
"bitcode",
"files",
"should",
"be",
"stored",
".",
":",
"param",
"is_clang_build",
":",
"Flag",
"to",
"indicate",
"that",
"this",
"is",
"a",
"clang",
"build",
".",
":",
"return",
":",
"True"
] | def build_drivers(compilation_commands, linker_commands, kernel_src_dir,
target_arch, clang_path, llvm_link_path, llvm_bit_code_out, is_clang_build):
"""
The main method that performs the building and linking of the driver files.
:param compilation_commands: Parsed compilation commands from the json.
:param linker_commands: Parsed linker commands from the json.
:param kernel_src_dir: Path to the kernel source directory.
:param target_arch: Number representing target architecture.
:param clang_path: Path to clang.
:param llvm_link_path: Path to llvm-link
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:param is_clang_build: Flag to indicate that this is a clang build.
:return: True
"""
output_llvm_sh_file = os.path.join(llvm_bit_code_out, 'llvm_build.sh')
fp_out = open(output_llvm_sh_file, 'w')
fp_out.write("#!/bin/bash\n")
log_info("Writing all compilation commands to", output_llvm_sh_file)
all_compilation_commands = []
obj_bc_map = {}
for curr_compilation_command in compilation_commands:
if is_clang_build:
wd, obj_file, bc_file, build_str = _get_llvm_build_str_from_llvm(clang_path, curr_compilation_command.curr_args,
kernel_src_dir, target_arch,
curr_compilation_command.work_dir,
curr_compilation_command.src_file,
curr_compilation_command.output_file,
llvm_bit_code_out)
else:
wd, obj_file, bc_file, build_str = _get_llvm_build_str(clang_path, curr_compilation_command.curr_args,
kernel_src_dir, target_arch,
curr_compilation_command.work_dir,
curr_compilation_command.src_file,
curr_compilation_command.output_file, llvm_bit_code_out)
all_compilation_commands.append((wd, build_str))
obj_bc_map[obj_file] = bc_file
fp_out.write("cd " + wd + ";" + build_str + "\n")
fp_out.close()
log_info("Got", len(all_compilation_commands), "compilation commands.")
log_info("Running compilation commands in multiprocessing modea.")
p = Pool(cpu_count())
return_vals = p.map(run_program_with_wd, all_compilation_commands)
log_success("Finished running compilation commands.")
output_llvm_sh_file = os.path.join(llvm_bit_code_out, 'llvm_link_cmds.sh')
fp_out = open(output_llvm_sh_file, 'w')
fp_out.write("#!/bin/bash\n")
log_info("Writing all linker commands to", output_llvm_sh_file)
all_linker_commands = []
recursive_linker_commands = []
for curr_linked_command in linker_commands:
curr_ret_val = _get_llvm_link_str(llvm_link_path, kernel_src_dir,
curr_linked_command.input_files, obj_bc_map,
curr_linked_command.output_file,
curr_linked_command.work_dir, llvm_bit_code_out)
if curr_ret_val is not None:
wd, obj_file, bc_file, build_str = curr_ret_val
all_linker_commands.append((wd, build_str))
obj_bc_map[obj_file] = bc_file
fp_out.write("cd " + wd + ";" + build_str + "\n")
else:
# these are recursive linker commands.
recursive_linker_commands.append(curr_linked_command)
log_info("Got", len(all_linker_commands), "regular linker commands.")
log_info("Running linker commands in multiprocessing mode.")
p = Pool(cpu_count())
return_vals = p.map(run_program_with_wd, all_linker_commands)
log_success("Finished running linker commands.")
if len(recursive_linker_commands) > 0:
log_info("Got", len(recursive_linker_commands), " recursive linker commands.")
_process_recursive_linker_commands(recursive_linker_commands, kernel_src_dir, llvm_link_path,
llvm_bit_code_out, obj_bc_map, fp_out)
fp_out.close()
return True | [
"def",
"build_drivers",
"(",
"compilation_commands",
",",
"linker_commands",
",",
"kernel_src_dir",
",",
"target_arch",
",",
"clang_path",
",",
"llvm_link_path",
",",
"llvm_bit_code_out",
",",
"is_clang_build",
")",
":",
"output_llvm_sh_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"llvm_bit_code_out",
",",
"'llvm_build.sh'",
")",
"fp_out",
"=",
"open",
"(",
"output_llvm_sh_file",
",",
"'w'",
")",
"fp_out",
".",
"write",
"(",
"\"#!/bin/bash\\n\"",
")",
"log_info",
"(",
"\"Writing all compilation commands to\"",
",",
"output_llvm_sh_file",
")",
"all_compilation_commands",
"=",
"[",
"]",
"obj_bc_map",
"=",
"{",
"}",
"for",
"curr_compilation_command",
"in",
"compilation_commands",
":",
"if",
"is_clang_build",
":",
"wd",
",",
"obj_file",
",",
"bc_file",
",",
"build_str",
"=",
"_get_llvm_build_str_from_llvm",
"(",
"clang_path",
",",
"curr_compilation_command",
".",
"curr_args",
",",
"kernel_src_dir",
",",
"target_arch",
",",
"curr_compilation_command",
".",
"work_dir",
",",
"curr_compilation_command",
".",
"src_file",
",",
"curr_compilation_command",
".",
"output_file",
",",
"llvm_bit_code_out",
")",
"else",
":",
"wd",
",",
"obj_file",
",",
"bc_file",
",",
"build_str",
"=",
"_get_llvm_build_str",
"(",
"clang_path",
",",
"curr_compilation_command",
".",
"curr_args",
",",
"kernel_src_dir",
",",
"target_arch",
",",
"curr_compilation_command",
".",
"work_dir",
",",
"curr_compilation_command",
".",
"src_file",
",",
"curr_compilation_command",
".",
"output_file",
",",
"llvm_bit_code_out",
")",
"all_compilation_commands",
".",
"append",
"(",
"(",
"wd",
",",
"build_str",
")",
")",
"obj_bc_map",
"[",
"obj_file",
"]",
"=",
"bc_file",
"fp_out",
".",
"write",
"(",
"\"cd \"",
"+",
"wd",
"+",
"\";\"",
"+",
"build_str",
"+",
"\"\\n\"",
")",
"fp_out",
".",
"close",
"(",
")",
"log_info",
"(",
"\"Got\"",
",",
"len",
"(",
"all_compilation_commands",
")",
",",
"\"compilation commands.\"",
")",
"log_info",
"(",
"\"Running compilation commands in multiprocessing modea.\"",
")",
"p",
"=",
"Pool",
"(",
"cpu_count",
"(",
")",
")",
"return_vals",
"=",
"p",
".",
"map",
"(",
"run_program_with_wd",
",",
"all_compilation_commands",
")",
"log_success",
"(",
"\"Finished running compilation commands.\"",
")",
"output_llvm_sh_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"llvm_bit_code_out",
",",
"'llvm_link_cmds.sh'",
")",
"fp_out",
"=",
"open",
"(",
"output_llvm_sh_file",
",",
"'w'",
")",
"fp_out",
".",
"write",
"(",
"\"#!/bin/bash\\n\"",
")",
"log_info",
"(",
"\"Writing all linker commands to\"",
",",
"output_llvm_sh_file",
")",
"all_linker_commands",
"=",
"[",
"]",
"recursive_linker_commands",
"=",
"[",
"]",
"for",
"curr_linked_command",
"in",
"linker_commands",
":",
"curr_ret_val",
"=",
"_get_llvm_link_str",
"(",
"llvm_link_path",
",",
"kernel_src_dir",
",",
"curr_linked_command",
".",
"input_files",
",",
"obj_bc_map",
",",
"curr_linked_command",
".",
"output_file",
",",
"curr_linked_command",
".",
"work_dir",
",",
"llvm_bit_code_out",
")",
"if",
"curr_ret_val",
"is",
"not",
"None",
":",
"wd",
",",
"obj_file",
",",
"bc_file",
",",
"build_str",
"=",
"curr_ret_val",
"all_linker_commands",
".",
"append",
"(",
"(",
"wd",
",",
"build_str",
")",
")",
"obj_bc_map",
"[",
"obj_file",
"]",
"=",
"bc_file",
"fp_out",
".",
"write",
"(",
"\"cd \"",
"+",
"wd",
"+",
"\";\"",
"+",
"build_str",
"+",
"\"\\n\"",
")",
"else",
":",
"# these are recursive linker commands.",
"recursive_linker_commands",
".",
"append",
"(",
"curr_linked_command",
")",
"log_info",
"(",
"\"Got\"",
",",
"len",
"(",
"all_linker_commands",
")",
",",
"\"regular linker commands.\"",
")",
"log_info",
"(",
"\"Running linker commands in multiprocessing mode.\"",
")",
"p",
"=",
"Pool",
"(",
"cpu_count",
"(",
")",
")",
"return_vals",
"=",
"p",
".",
"map",
"(",
"run_program_with_wd",
",",
"all_linker_commands",
")",
"log_success",
"(",
"\"Finished running linker commands.\"",
")",
"if",
"len",
"(",
"recursive_linker_commands",
")",
">",
"0",
":",
"log_info",
"(",
"\"Got\"",
",",
"len",
"(",
"recursive_linker_commands",
")",
",",
"\" recursive linker commands.\"",
")",
"_process_recursive_linker_commands",
"(",
"recursive_linker_commands",
",",
"kernel_src_dir",
",",
"llvm_link_path",
",",
"llvm_bit_code_out",
",",
"obj_bc_map",
",",
"fp_out",
")",
"fp_out",
".",
"close",
"(",
")",
"return",
"True"
] | https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/components/bear_llvm_build.py#L302-L379 | |
apache/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | install/python-installer/scripts/httplib2/__init__.py | python | Authentication.request | (self, method, request_uri, headers, content) | Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes. | Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes. | [
"Modify",
"the",
"request",
"headers",
"to",
"add",
"the",
"appropriate",
"Authorization",
"header",
".",
"Over",
"-",
"ride",
"this",
"in",
"sub",
"-",
"classes",
"."
] | def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes."""
pass | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"request_uri",
",",
"headers",
",",
"content",
")",
":",
"pass"
] | https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/install/python-installer/scripts/httplib2/__init__.py#L497-L500 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/filesystem.py | python | find_files | (path, pattern) | return result | Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern. | Returns a list of absolute paths of files beneath path, recursively, | [
"Returns",
"a",
"list",
"of",
"absolute",
"paths",
"of",
"files",
"beneath",
"path",
"recursively"
] | def find_files(path, pattern):
# type: (str, str) -> List[str]
"""Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern."""
result = [] # type: List[str]
for root, _, files in os.walk(path):
matches = fnmatch.filter(files, pattern)
result.extend(os.path.join(root, f) for f in matches)
return result | [
"def",
"find_files",
"(",
"path",
",",
"pattern",
")",
":",
"# type: (str, str) -> List[str]",
"result",
"=",
"[",
"]",
"# type: List[str]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"matches",
"=",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"pattern",
")",
"result",
".",
"extend",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"for",
"f",
"in",
"matches",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/filesystem.py#L327-L343 | |
h2oai/deepwater | 80e345c582e6ef912a31f42707a2f31c01b064da | docs/sphinxext/apigen.py | python | ApiDocWriter._parse_lines | (self, linesource) | return functions, classes | Parse lines of text for functions and classes | Parse lines of text for functions and classes | [
"Parse",
"lines",
"of",
"text",
"for",
"functions",
"and",
"classes"
] | def _parse_lines(self, linesource):
''' Parse lines of text for functions and classes '''
functions = []
classes = []
for line in linesource:
if line.startswith('def ') and line.count('('):
# exclude private stuff
name = self._get_object_name(line)
if not name.startswith('_'):
functions.append(name)
elif line.startswith('class '):
# exclude private stuff
name = self._get_object_name(line)
if not name.startswith('_'):
classes.append(name)
else:
pass
functions.sort()
classes.sort()
return functions, classes | [
"def",
"_parse_lines",
"(",
"self",
",",
"linesource",
")",
":",
"functions",
"=",
"[",
"]",
"classes",
"=",
"[",
"]",
"for",
"line",
"in",
"linesource",
":",
"if",
"line",
".",
"startswith",
"(",
"'def '",
")",
"and",
"line",
".",
"count",
"(",
"'('",
")",
":",
"# exclude private stuff",
"name",
"=",
"self",
".",
"_get_object_name",
"(",
"line",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"functions",
".",
"append",
"(",
"name",
")",
"elif",
"line",
".",
"startswith",
"(",
"'class '",
")",
":",
"# exclude private stuff",
"name",
"=",
"self",
".",
"_get_object_name",
"(",
"line",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"classes",
".",
"append",
"(",
"name",
")",
"else",
":",
"pass",
"functions",
".",
"sort",
"(",
")",
"classes",
".",
"sort",
"(",
")",
"return",
"functions",
",",
"classes"
] | https://github.com/h2oai/deepwater/blob/80e345c582e6ef912a31f42707a2f31c01b064da/docs/sphinxext/apigen.py#L172-L191 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pslinux.py | python | sensors_fans | () | return dict(ret) | Return hardware fans info (for CPU and other peripherals) as a
dict including hardware label and current speed.
Implementation notes:
- /sys/class/hwmon looks like the most recent interface to
retrieve this info, and this implementation relies on it
only (old distros will probably use something else)
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon | Return hardware fans info (for CPU and other peripherals) as a
dict including hardware label and current speed. | [
"Return",
"hardware",
"fans",
"info",
"(",
"for",
"CPU",
"and",
"other",
"peripherals",
")",
"as",
"a",
"dict",
"including",
"hardware",
"label",
"and",
"current",
"speed",
"."
] | def sensors_fans():
"""Return hardware fans info (for CPU and other peripherals) as a
dict including hardware label and current speed.
Implementation notes:
- /sys/class/hwmon looks like the most recent interface to
retrieve this info, and this implementation relies on it
only (old distros will probably use something else)
- lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
"""
ret = collections.defaultdict(list)
basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
if not basenames:
# CentOS has an intermediate /device directory:
# https://github.com/giampaolo/psutil/issues/971
basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
basenames = sorted(set([x.split('_')[0] for x in basenames]))
for base in basenames:
try:
current = int(cat(base + '_input'))
except (IOError, OSError) as err:
warnings.warn("ignoring %r" % err, RuntimeWarning)
continue
unit_name = cat(os.path.join(os.path.dirname(base), 'name'),
binary=False)
label = cat(base + '_label', fallback='', binary=False)
ret[unit_name].append(_common.sfan(label, current))
return dict(ret) | [
"def",
"sensors_fans",
"(",
")",
":",
"ret",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"basenames",
"=",
"glob",
".",
"glob",
"(",
"'/sys/class/hwmon/hwmon*/fan*_*'",
")",
"if",
"not",
"basenames",
":",
"# CentOS has an intermediate /device directory:",
"# https://github.com/giampaolo/psutil/issues/971",
"basenames",
"=",
"glob",
".",
"glob",
"(",
"'/sys/class/hwmon/hwmon*/device/fan*_*'",
")",
"basenames",
"=",
"sorted",
"(",
"set",
"(",
"[",
"x",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"for",
"x",
"in",
"basenames",
"]",
")",
")",
"for",
"base",
"in",
"basenames",
":",
"try",
":",
"current",
"=",
"int",
"(",
"cat",
"(",
"base",
"+",
"'_input'",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"err",
":",
"warnings",
".",
"warn",
"(",
"\"ignoring %r\"",
"%",
"err",
",",
"RuntimeWarning",
")",
"continue",
"unit_name",
"=",
"cat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"base",
")",
",",
"'name'",
")",
",",
"binary",
"=",
"False",
")",
"label",
"=",
"cat",
"(",
"base",
"+",
"'_label'",
",",
"fallback",
"=",
"''",
",",
"binary",
"=",
"False",
")",
"ret",
"[",
"unit_name",
"]",
".",
"append",
"(",
"_common",
".",
"sfan",
"(",
"label",
",",
"current",
")",
")",
"return",
"dict",
"(",
"ret",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pslinux.py#L1293-L1322 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/docking/DockingBar.py | python | DockingBar.OnWindowPosChanged | (self, msg) | return 0 | LPARAM used with WM_WINDOWPOSCHANGED:
typedef struct {
HWND hwnd;
HWND hwndInsertAfter;
int x;
int y;
int cx;
int cy;
UINT flags;} WINDOWPOS; | LPARAM used with WM_WINDOWPOSCHANGED:
typedef struct {
HWND hwnd;
HWND hwndInsertAfter;
int x;
int y;
int cx;
int cy;
UINT flags;} WINDOWPOS; | [
"LPARAM",
"used",
"with",
"WM_WINDOWPOSCHANGED",
":",
"typedef",
"struct",
"{",
"HWND",
"hwnd",
";",
"HWND",
"hwndInsertAfter",
";",
"int",
"x",
";",
"int",
"y",
";",
"int",
"cx",
";",
"int",
"cy",
";",
"UINT",
"flags",
";",
"}",
"WINDOWPOS",
";"
] | def OnWindowPosChanged(self, msg):
if self.GetSafeHwnd()==0 or self.dialog is None:
return 0
lparam = msg[3]
""" LPARAM used with WM_WINDOWPOSCHANGED:
typedef struct {
HWND hwnd;
HWND hwndInsertAfter;
int x;
int y;
int cx;
int cy;
UINT flags;} WINDOWPOS;
"""
format = "PPiiiii"
bytes = win32ui.GetBytes( lparam, struct.calcsize(format) )
hwnd, hwndAfter, x, y, cx, cy, flags = struct.unpack(format, bytes)
if self.bInRecalcNC:
rc = self.GetClientRect()
self.dialog.MoveWindow(rc)
return 0
# Find on which side are we docked
nDockBarID = self.GetParent().GetDlgCtrlID()
# Return if dropped at same location
# no docking side change and no size change
if (nDockBarID == self.nDockBarID) and \
(flags & win32con.SWP_NOSIZE) and \
((self._obj_.dwStyle & afxres.CBRS_BORDER_ANY) != afxres.CBRS_BORDER_ANY):
return
self.nDockBarID = nDockBarID
# Force recalc the non-client area
self.bInRecalcNC = 1
try:
swpflags = win32con.SWP_NOSIZE | win32con.SWP_NOMOVE | win32con.SWP_NOZORDER | win32con.SWP_FRAMECHANGED
self.SetWindowPos(0, (0,0,0,0), swpflags)
finally:
self.bInRecalcNC = 0
return 0 | [
"def",
"OnWindowPosChanged",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"GetSafeHwnd",
"(",
")",
"==",
"0",
"or",
"self",
".",
"dialog",
"is",
"None",
":",
"return",
"0",
"lparam",
"=",
"msg",
"[",
"3",
"]",
"format",
"=",
"\"PPiiiii\"",
"bytes",
"=",
"win32ui",
".",
"GetBytes",
"(",
"lparam",
",",
"struct",
".",
"calcsize",
"(",
"format",
")",
")",
"hwnd",
",",
"hwndAfter",
",",
"x",
",",
"y",
",",
"cx",
",",
"cy",
",",
"flags",
"=",
"struct",
".",
"unpack",
"(",
"format",
",",
"bytes",
")",
"if",
"self",
".",
"bInRecalcNC",
":",
"rc",
"=",
"self",
".",
"GetClientRect",
"(",
")",
"self",
".",
"dialog",
".",
"MoveWindow",
"(",
"rc",
")",
"return",
"0",
"# Find on which side are we docked",
"nDockBarID",
"=",
"self",
".",
"GetParent",
"(",
")",
".",
"GetDlgCtrlID",
"(",
")",
"# Return if dropped at same location",
"# no docking side change and no size change",
"if",
"(",
"nDockBarID",
"==",
"self",
".",
"nDockBarID",
")",
"and",
"(",
"flags",
"&",
"win32con",
".",
"SWP_NOSIZE",
")",
"and",
"(",
"(",
"self",
".",
"_obj_",
".",
"dwStyle",
"&",
"afxres",
".",
"CBRS_BORDER_ANY",
")",
"!=",
"afxres",
".",
"CBRS_BORDER_ANY",
")",
":",
"return",
"self",
".",
"nDockBarID",
"=",
"nDockBarID",
"# Force recalc the non-client area",
"self",
".",
"bInRecalcNC",
"=",
"1",
"try",
":",
"swpflags",
"=",
"win32con",
".",
"SWP_NOSIZE",
"|",
"win32con",
".",
"SWP_NOMOVE",
"|",
"win32con",
".",
"SWP_NOZORDER",
"|",
"win32con",
".",
"SWP_FRAMECHANGED",
"self",
".",
"SetWindowPos",
"(",
"0",
",",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
",",
"swpflags",
")",
"finally",
":",
"self",
".",
"bInRecalcNC",
"=",
"0",
"return",
"0"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/docking/DockingBar.py#L163-L202 | |
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/grokdump.py | python | InspectionShell.do_ko | (self, address) | return self.do_known_oldspace(address) | see known_oldspace | see known_oldspace | [
"see",
"known_oldspace"
] | def do_ko(self, address):
""" see known_oldspace """
return self.do_known_oldspace(address) | [
"def",
"do_ko",
"(",
"self",
",",
"address",
")",
":",
"return",
"self",
".",
"do_known_oldspace",
"(",
"address",
")"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/grokdump.py#L3719-L3721 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py | python | declaration_t.__lt__ | (self, other) | return self._get__cmp__data() < other._get__cmp__data() | .. code-block:: python
if not isinstance( other, self.__class__ ):
return self.__class__.__name__ < other.__class__.__name__
return self._get__cmp__data() < other._get__cmp__data() | .. code-block:: python | [
"..",
"code",
"-",
"block",
"::",
"python"
] | def __lt__(self, other):
"""
.. code-block:: python
if not isinstance( other, self.__class__ ):
return self.__class__.__name__ < other.__class__.__name__
return self._get__cmp__data() < other._get__cmp__data()
"""
if not isinstance(other, self.__class__):
return self.__class__.__name__ < other.__class__.__name__
return self._get__cmp__data() < other._get__cmp__data() | [
"def",
"__lt__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__",
"<",
"other",
".",
"__class__",
".",
"__name__",
"return",
"self",
".",
"_get__cmp__data",
"(",
")",
"<",
"other",
".",
"_get__cmp__data",
"(",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py#L126-L138 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/cluster/vq.py | python | py_vq | (obs, code_book, check_finite=True) | return code, sqrt(min_dist) | Python version of vq algorithm.
The algorithm computes the euclidian distance between each
observation and every frame in the code_book.
Parameters
----------
obs : ndarray
Expects a rank 2 array. Each row is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should have same number of
features (eg columns) than obs.
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Default: True
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code.
Notes
-----
This function is slower than the C version but works for
all input types. If the inputs have the wrong types for the
C versions of the function, this one is called as a last resort.
It is about 20 times slower than the C version. | Python version of vq algorithm. | [
"Python",
"version",
"of",
"vq",
"algorithm",
"."
] | def py_vq(obs, code_book, check_finite=True):
""" Python version of vq algorithm.
The algorithm computes the euclidian distance between each
observation and every frame in the code_book.
Parameters
----------
obs : ndarray
Expects a rank 2 array. Each row is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should have same number of
features (eg columns) than obs.
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Default: True
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code.
Notes
-----
This function is slower than the C version but works for
all input types. If the inputs have the wrong types for the
C versions of the function, this one is called as a last resort.
It is about 20 times slower than the C version.
"""
obs = _asarray_validated(obs, check_finite=check_finite)
code_book = _asarray_validated(code_book, check_finite=check_finite)
# n = number of observations
# d = number of features
if np.ndim(obs) == 1:
if not np.ndim(obs) == np.ndim(code_book):
raise ValueError(
"Observation and code_book should have the same rank")
else:
return _py_vq_1d(obs, code_book)
else:
(n, d) = shape(obs)
# code books and observations should have same number of features and same
# shape
if not np.ndim(obs) == np.ndim(code_book):
raise ValueError("Observation and code_book should have the same rank")
elif not d == code_book.shape[1]:
raise ValueError("Code book(%d) and obs(%d) should have the same "
"number of features (eg columns)""" %
(code_book.shape[1], d))
code = zeros(n, dtype=int)
min_dist = zeros(n)
for i in range(n):
dist = np.sum((obs[i] - code_book) ** 2, 1)
code[i] = argmin(dist)
min_dist[i] = dist[code[i]]
return code, sqrt(min_dist) | [
"def",
"py_vq",
"(",
"obs",
",",
"code_book",
",",
"check_finite",
"=",
"True",
")",
":",
"obs",
"=",
"_asarray_validated",
"(",
"obs",
",",
"check_finite",
"=",
"check_finite",
")",
"code_book",
"=",
"_asarray_validated",
"(",
"code_book",
",",
"check_finite",
"=",
"check_finite",
")",
"# n = number of observations",
"# d = number of features",
"if",
"np",
".",
"ndim",
"(",
"obs",
")",
"==",
"1",
":",
"if",
"not",
"np",
".",
"ndim",
"(",
"obs",
")",
"==",
"np",
".",
"ndim",
"(",
"code_book",
")",
":",
"raise",
"ValueError",
"(",
"\"Observation and code_book should have the same rank\"",
")",
"else",
":",
"return",
"_py_vq_1d",
"(",
"obs",
",",
"code_book",
")",
"else",
":",
"(",
"n",
",",
"d",
")",
"=",
"shape",
"(",
"obs",
")",
"# code books and observations should have same number of features and same",
"# shape",
"if",
"not",
"np",
".",
"ndim",
"(",
"obs",
")",
"==",
"np",
".",
"ndim",
"(",
"code_book",
")",
":",
"raise",
"ValueError",
"(",
"\"Observation and code_book should have the same rank\"",
")",
"elif",
"not",
"d",
"==",
"code_book",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Code book(%d) and obs(%d) should have the same \"",
"\"number of features (eg columns)\"",
"\"\"",
"%",
"(",
"code_book",
".",
"shape",
"[",
"1",
"]",
",",
"d",
")",
")",
"code",
"=",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"int",
")",
"min_dist",
"=",
"zeros",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"dist",
"=",
"np",
".",
"sum",
"(",
"(",
"obs",
"[",
"i",
"]",
"-",
"code_book",
")",
"**",
"2",
",",
"1",
")",
"code",
"[",
"i",
"]",
"=",
"argmin",
"(",
"dist",
")",
"min_dist",
"[",
"i",
"]",
"=",
"dist",
"[",
"code",
"[",
"i",
"]",
"]",
"return",
"code",
",",
"sqrt",
"(",
"min_dist",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/cluster/vq.py#L228-L295 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/_shell_utils.py | python | CommandLineParser.split | (cmd) | Split a command line string into a list of arguments | Split a command line string into a list of arguments | [
"Split",
"a",
"command",
"line",
"string",
"into",
"a",
"list",
"of",
"arguments"
] | def split(cmd):
""" Split a command line string into a list of arguments """
raise NotImplementedError | [
"def",
"split",
"(",
"cmd",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/_shell_utils.py#L30-L32 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/sessions.py | python | SessionRedirectMixin.rebuild_method | (self, prepared_request, response) | When being redirected we may want to change the method of the request
based on certain specs or browser behavior. | When being redirected we may want to change the method of the request
based on certain specs or browser behavior. | [
"When",
"being",
"redirected",
"we",
"may",
"want",
"to",
"change",
"the",
"method",
"of",
"the",
"request",
"based",
"on",
"certain",
"specs",
"or",
"browser",
"behavior",
"."
] | def rebuild_method(self, prepared_request, response):
"""When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
"""
method = prepared_request.method
# https://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != 'HEAD':
method = 'GET'
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if response.status_code == codes.found and method != 'HEAD':
method = 'GET'
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'
prepared_request.method = method | [
"def",
"rebuild_method",
"(",
"self",
",",
"prepared_request",
",",
"response",
")",
":",
"method",
"=",
"prepared_request",
".",
"method",
"# https://tools.ietf.org/html/rfc7231#section-6.4.4",
"if",
"response",
".",
"status_code",
"==",
"codes",
".",
"see_other",
"and",
"method",
"!=",
"'HEAD'",
":",
"method",
"=",
"'GET'",
"# Do what the browsers do, despite standards...",
"# First, turn 302s into GETs.",
"if",
"response",
".",
"status_code",
"==",
"codes",
".",
"found",
"and",
"method",
"!=",
"'HEAD'",
":",
"method",
"=",
"'GET'",
"# Second, if a POST is responded to with a 301, turn it into a GET.",
"# This bizarre behaviour is explained in Issue 1704.",
"if",
"response",
".",
"status_code",
"==",
"codes",
".",
"moved",
"and",
"method",
"==",
"'POST'",
":",
"method",
"=",
"'GET'",
"prepared_request",
".",
"method",
"=",
"method"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/sessions.py#L314-L334 | ||
redpony/cdec | f7c4899b174d86bc70b40b1cae68dcad364615cb | python/cdec/configobj.py | python | InterpolationEngine._parse_match | (self, match) | Implementation-dependent helper function.
Will be passed a match object corresponding to the interpolation
key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
key in the appropriate config file section (using the ``_fetch()``
helper function) and return a 3-tuple: (key, value, section)
``key`` is the name of the key we're looking for
``value`` is the value found for that key
``section`` is a reference to the section where it was found
``key`` and ``section`` should be None if no further
interpolation should be performed on the resulting value
(e.g., if we interpolated "$$" and returned "$"). | Implementation-dependent helper function. | [
"Implementation",
"-",
"dependent",
"helper",
"function",
"."
] | def _parse_match(self, match):
"""Implementation-dependent helper function.
Will be passed a match object corresponding to the interpolation
key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
key in the appropriate config file section (using the ``_fetch()``
helper function) and return a 3-tuple: (key, value, section)
``key`` is the name of the key we're looking for
``value`` is the value found for that key
``section`` is a reference to the section where it was found
``key`` and ``section`` should be None if no further
interpolation should be performed on the resulting value
(e.g., if we interpolated "$$" and returned "$").
"""
raise NotImplementedError() | [
"def",
"_parse_match",
"(",
"self",
",",
"match",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L403-L419 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py | python | IRC.process_once | (self, timeout=0) | Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
incoming data, if there are any. If that seems boring, look
at the process_forever method. | Process data from connections once. | [
"Process",
"data",
"from",
"connections",
"once",
"."
] | def process_once(self, timeout=0):
"""Process data from connections once.
Arguments:
timeout -- How long the select() call should wait if no
data is available.
This method should be called periodically to check and process
incoming data, if there are any. If that seems boring, look
at the process_forever method.
"""
sockets = map(lambda x: x._get_socket(), self.connections)
sockets = filter(lambda x: x != None, sockets)
if sockets:
(i, o, e) = select.select(sockets, [], [], timeout)
self.process_data(i)
else:
time.sleep(timeout)
self.process_timeout() | [
"def",
"process_once",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"sockets",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"_get_socket",
"(",
")",
",",
"self",
".",
"connections",
")",
"sockets",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
"!=",
"None",
",",
"sockets",
")",
"if",
"sockets",
":",
"(",
"i",
",",
"o",
",",
"e",
")",
"=",
"select",
".",
"select",
"(",
"sockets",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"self",
".",
"process_data",
"(",
"i",
")",
"else",
":",
"time",
".",
"sleep",
"(",
"timeout",
")",
"self",
".",
"process_timeout",
"(",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L198-L217 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/fft_ops.py | python | _rfft_grad_helper | (rank, irfft_fn) | return _grad | Returns a gradient function for an RFFT of the provided rank. | Returns a gradient function for an RFFT of the provided rank. | [
"Returns",
"a",
"gradient",
"function",
"for",
"an",
"RFFT",
"of",
"the",
"provided",
"rank",
"."
] | def _rfft_grad_helper(rank, irfft_fn):
"""Returns a gradient function for an RFFT of the provided rank."""
# Can't happen because we don't register a gradient for RFFT3D.
assert rank in (1, 2), "Gradient for RFFT3D is not implemented."
def _grad(op, grad):
"""A gradient function for RFFT with the provided `rank` and `irfft_fn`."""
fft_length = op.inputs[1]
input_shape = _array_ops.shape(op.inputs[0])
is_even = _math_ops.cast(1 - (fft_length[-1] % 2), _dtypes.complex64)
def _tile_for_broadcasting(matrix, t):
expanded = _array_ops.reshape(
matrix,
_array_ops.concat([
_array_ops.ones([_array_ops.rank(t) - 2], _dtypes.int32),
_array_ops.shape(matrix)
], 0))
return _array_ops.tile(
expanded, _array_ops.concat([_array_ops.shape(t)[:-2], [1, 1]], 0))
def _mask_matrix(length):
"""Computes t_n = exp(sqrt(-1) * pi * n^2 / line_len)."""
# TODO(rjryan): Speed up computation of twiddle factors using the
# following recurrence relation and cache them across invocations of RFFT.
#
# t_n = exp(sqrt(-1) * pi * n^2 / line_len)
# for n = 0, 1,..., line_len-1.
# For n > 2, use t_n = t_{n-1}^2 / t_{n-2} * t_1^2
a = _array_ops.tile(
_array_ops.expand_dims(_math_ops.range(length), 0), (length, 1))
b = _array_ops.transpose(a, [1, 0])
return _math_ops.exp(
-2j * np.pi * _math_ops.cast(a * b, _dtypes.complex64) /
_math_ops.cast(length, _dtypes.complex64))
def _ymask(length):
"""A sequence of [1+0j, -1+0j, 1+0j, -1+0j, ...] with length `length`."""
return _math_ops.cast(1 - 2 * (_math_ops.range(length) % 2),
_dtypes.complex64)
y0 = grad[..., 0:1]
if rank == 1:
ym = grad[..., -1:]
extra_terms = y0 + is_even * ym * _ymask(input_shape[-1])
elif rank == 2:
# Create a mask matrix for y0 and ym.
base_mask = _mask_matrix(input_shape[-2])
# Tile base_mask to match y0 in shape so that we can batch-matmul the
# inner 2 dimensions.
tiled_mask = _tile_for_broadcasting(base_mask, y0)
y0_term = _math_ops.matmul(tiled_mask, _math_ops.conj(y0))
extra_terms = y0_term
ym = grad[..., -1:]
ym_term = _math_ops.matmul(tiled_mask, _math_ops.conj(ym))
inner_dim = input_shape[-1]
ym_term = _array_ops.tile(
ym_term,
_array_ops.concat([
_array_ops.ones([_array_ops.rank(grad) - 1], _dtypes.int32),
[inner_dim]
], 0)) * _ymask(inner_dim)
extra_terms += is_even * ym_term
# The gradient of RFFT is the IRFFT of the incoming gradient times a scaling
# factor, plus some additional terms to make up for the components dropped
# due to Hermitian symmetry.
input_size = _math_ops.cast(
_fft_size_for_grad(op.inputs[0], rank), _dtypes.float32)
the_irfft = irfft_fn(grad, fft_length)
return 0.5 * (the_irfft * input_size + _math_ops.real(extra_terms)), None
return _grad | [
"def",
"_rfft_grad_helper",
"(",
"rank",
",",
"irfft_fn",
")",
":",
"# Can't happen because we don't register a gradient for RFFT3D.",
"assert",
"rank",
"in",
"(",
"1",
",",
"2",
")",
",",
"\"Gradient for RFFT3D is not implemented.\"",
"def",
"_grad",
"(",
"op",
",",
"grad",
")",
":",
"\"\"\"A gradient function for RFFT with the provided `rank` and `irfft_fn`.\"\"\"",
"fft_length",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"input_shape",
"=",
"_array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"is_even",
"=",
"_math_ops",
".",
"cast",
"(",
"1",
"-",
"(",
"fft_length",
"[",
"-",
"1",
"]",
"%",
"2",
")",
",",
"_dtypes",
".",
"complex64",
")",
"def",
"_tile_for_broadcasting",
"(",
"matrix",
",",
"t",
")",
":",
"expanded",
"=",
"_array_ops",
".",
"reshape",
"(",
"matrix",
",",
"_array_ops",
".",
"concat",
"(",
"[",
"_array_ops",
".",
"ones",
"(",
"[",
"_array_ops",
".",
"rank",
"(",
"t",
")",
"-",
"2",
"]",
",",
"_dtypes",
".",
"int32",
")",
",",
"_array_ops",
".",
"shape",
"(",
"matrix",
")",
"]",
",",
"0",
")",
")",
"return",
"_array_ops",
".",
"tile",
"(",
"expanded",
",",
"_array_ops",
".",
"concat",
"(",
"[",
"_array_ops",
".",
"shape",
"(",
"t",
")",
"[",
":",
"-",
"2",
"]",
",",
"[",
"1",
",",
"1",
"]",
"]",
",",
"0",
")",
")",
"def",
"_mask_matrix",
"(",
"length",
")",
":",
"\"\"\"Computes t_n = exp(sqrt(-1) * pi * n^2 / line_len).\"\"\"",
"# TODO(rjryan): Speed up computation of twiddle factors using the",
"# following recurrence relation and cache them across invocations of RFFT.",
"#",
"# t_n = exp(sqrt(-1) * pi * n^2 / line_len)",
"# for n = 0, 1,..., line_len-1.",
"# For n > 2, use t_n = t_{n-1}^2 / t_{n-2} * t_1^2",
"a",
"=",
"_array_ops",
".",
"tile",
"(",
"_array_ops",
".",
"expand_dims",
"(",
"_math_ops",
".",
"range",
"(",
"length",
")",
",",
"0",
")",
",",
"(",
"length",
",",
"1",
")",
")",
"b",
"=",
"_array_ops",
".",
"transpose",
"(",
"a",
",",
"[",
"1",
",",
"0",
"]",
")",
"return",
"_math_ops",
".",
"exp",
"(",
"-",
"2j",
"*",
"np",
".",
"pi",
"*",
"_math_ops",
".",
"cast",
"(",
"a",
"*",
"b",
",",
"_dtypes",
".",
"complex64",
")",
"/",
"_math_ops",
".",
"cast",
"(",
"length",
",",
"_dtypes",
".",
"complex64",
")",
")",
"def",
"_ymask",
"(",
"length",
")",
":",
"\"\"\"A sequence of [1+0j, -1+0j, 1+0j, -1+0j, ...] with length `length`.\"\"\"",
"return",
"_math_ops",
".",
"cast",
"(",
"1",
"-",
"2",
"*",
"(",
"_math_ops",
".",
"range",
"(",
"length",
")",
"%",
"2",
")",
",",
"_dtypes",
".",
"complex64",
")",
"y0",
"=",
"grad",
"[",
"...",
",",
"0",
":",
"1",
"]",
"if",
"rank",
"==",
"1",
":",
"ym",
"=",
"grad",
"[",
"...",
",",
"-",
"1",
":",
"]",
"extra_terms",
"=",
"y0",
"+",
"is_even",
"*",
"ym",
"*",
"_ymask",
"(",
"input_shape",
"[",
"-",
"1",
"]",
")",
"elif",
"rank",
"==",
"2",
":",
"# Create a mask matrix for y0 and ym.",
"base_mask",
"=",
"_mask_matrix",
"(",
"input_shape",
"[",
"-",
"2",
"]",
")",
"# Tile base_mask to match y0 in shape so that we can batch-matmul the",
"# inner 2 dimensions.",
"tiled_mask",
"=",
"_tile_for_broadcasting",
"(",
"base_mask",
",",
"y0",
")",
"y0_term",
"=",
"_math_ops",
".",
"matmul",
"(",
"tiled_mask",
",",
"_math_ops",
".",
"conj",
"(",
"y0",
")",
")",
"extra_terms",
"=",
"y0_term",
"ym",
"=",
"grad",
"[",
"...",
",",
"-",
"1",
":",
"]",
"ym_term",
"=",
"_math_ops",
".",
"matmul",
"(",
"tiled_mask",
",",
"_math_ops",
".",
"conj",
"(",
"ym",
")",
")",
"inner_dim",
"=",
"input_shape",
"[",
"-",
"1",
"]",
"ym_term",
"=",
"_array_ops",
".",
"tile",
"(",
"ym_term",
",",
"_array_ops",
".",
"concat",
"(",
"[",
"_array_ops",
".",
"ones",
"(",
"[",
"_array_ops",
".",
"rank",
"(",
"grad",
")",
"-",
"1",
"]",
",",
"_dtypes",
".",
"int32",
")",
",",
"[",
"inner_dim",
"]",
"]",
",",
"0",
")",
")",
"*",
"_ymask",
"(",
"inner_dim",
")",
"extra_terms",
"+=",
"is_even",
"*",
"ym_term",
"# The gradient of RFFT is the IRFFT of the incoming gradient times a scaling",
"# factor, plus some additional terms to make up for the components dropped",
"# due to Hermitian symmetry.",
"input_size",
"=",
"_math_ops",
".",
"cast",
"(",
"_fft_size_for_grad",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
",",
"rank",
")",
",",
"_dtypes",
".",
"float32",
")",
"the_irfft",
"=",
"irfft_fn",
"(",
"grad",
",",
"fft_length",
")",
"return",
"0.5",
"*",
"(",
"the_irfft",
"*",
"input_size",
"+",
"_math_ops",
".",
"real",
"(",
"extra_terms",
")",
")",
",",
"None",
"return",
"_grad"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/signal/fft_ops.py#L218-L295 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/utils/check_cfc/obj_diff.py | python | dump_debug | (objfile) | return [line for line in out.split(os.linesep) if keep_line(line)] | Dump all of the debug info from a file. | Dump all of the debug info from a file. | [
"Dump",
"all",
"of",
"the",
"debug",
"info",
"from",
"a",
"file",
"."
] | def dump_debug(objfile):
"""Dump all of the debug info from a file."""
p = subprocess.Popen([disassembler, '-WliaprmfsoRt', objfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
if p.returncode or err:
print("Dump debug failed: {}".format(objfile))
sys.exit(1)
return [line for line in out.split(os.linesep) if keep_line(line)] | [
"def",
"dump_debug",
"(",
"objfile",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"disassembler",
",",
"'-WliaprmfsoRt'",
",",
"objfile",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"(",
"out",
",",
"err",
")",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"or",
"err",
":",
"print",
"(",
"\"Dump debug failed: {}\"",
".",
"format",
"(",
"objfile",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"[",
"line",
"for",
"line",
"in",
"out",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"if",
"keep_line",
"(",
"line",
")",
"]"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/utils/check_cfc/obj_diff.py#L30-L37 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/variables.py | python | RefVariable.__init__ | (
self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
synchronization=None,
aggregation=None,
shape=None) | Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, also adds the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default
list of variables to use by the `Optimizer` classes. Defaults to `True`,
unless `synchronization` is set to `ON_READ`, in which case it defaults
to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device. If not
`None`, caches on another device. Typical use is to cache on the device
where the Ops using the Variable reside, to deduplicate copying through
`Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates the
Variable object with its contents, referencing the variable's nodes in
the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type. If
`None`, either the datatype will be kept (if `initial_value` is a
Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected to have
this shape.
import_scope: Optional `string`. Name scope to add to the `Variable.` Only
used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled. | Creates a new variable with value `initial_value`. | [
"Creates",
"a",
"new",
"variable",
"with",
"value",
"initial_value",
"."
] | def __init__(
self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
synchronization=None,
aggregation=None,
shape=None):
"""Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, also adds the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default
list of variables to use by the `Optimizer` classes. Defaults to `True`,
unless `synchronization` is set to `ON_READ`, in which case it defaults
to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device. If not
`None`, caches on another device. Typical use is to cache on the device
where the Ops using the Variable reside, to deduplicate copying through
`Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates the
Variable object with its contents, referencing the variable's nodes in
the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type. If
`None`, either the datatype will be kept (if `initial_value` is a
Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected to have
this shape.
import_scope: Optional `string`. Name scope to add to the `Variable.` Only
used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled.
"""
self._in_graph_mode = True
if variable_def:
# If variable_def is provided, recreates the variable from its fields.
if initial_value:
raise ValueError("variable_def and initial_value are mutually "
"exclusive.")
self._init_from_proto(variable_def, import_scope=import_scope)
else:
# Create from initial_value.
self._init_from_args(
initial_value=initial_value,
trainable=trainable,
collections=collections,
validate_shape=validate_shape,
caching_device=caching_device,
name=name,
dtype=dtype,
expected_shape=expected_shape,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation,
shape=shape) | [
"def",
"__init__",
"(",
"self",
",",
"# pylint: disable=super-init-not-called",
"initial_value",
"=",
"None",
",",
"trainable",
"=",
"None",
",",
"collections",
"=",
"None",
",",
"validate_shape",
"=",
"True",
",",
"caching_device",
"=",
"None",
",",
"name",
"=",
"None",
",",
"variable_def",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"expected_shape",
"=",
"None",
",",
"import_scope",
"=",
"None",
",",
"constraint",
"=",
"None",
",",
"synchronization",
"=",
"None",
",",
"aggregation",
"=",
"None",
",",
"shape",
"=",
"None",
")",
":",
"self",
".",
"_in_graph_mode",
"=",
"True",
"if",
"variable_def",
":",
"# If variable_def is provided, recreates the variable from its fields.",
"if",
"initial_value",
":",
"raise",
"ValueError",
"(",
"\"variable_def and initial_value are mutually \"",
"\"exclusive.\"",
")",
"self",
".",
"_init_from_proto",
"(",
"variable_def",
",",
"import_scope",
"=",
"import_scope",
")",
"else",
":",
"# Create from initial_value.",
"self",
".",
"_init_from_args",
"(",
"initial_value",
"=",
"initial_value",
",",
"trainable",
"=",
"trainable",
",",
"collections",
"=",
"collections",
",",
"validate_shape",
"=",
"validate_shape",
",",
"caching_device",
"=",
"caching_device",
",",
"name",
"=",
"name",
",",
"dtype",
"=",
"dtype",
",",
"expected_shape",
"=",
"expected_shape",
",",
"constraint",
"=",
"constraint",
",",
"synchronization",
"=",
"synchronization",
",",
"aggregation",
"=",
"aggregation",
",",
"shape",
"=",
"shape",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L1550-L1659 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | docs/doxygen/doxyxml/base.py | python | Base._get_dict_members | (self, cat=None) | return self._dict_members[cat] | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | [
"For",
"given",
"category",
"a",
"dictionary",
"is",
"returned",
"mapping",
"member",
"names",
"to",
"members",
"of",
"that",
"category",
".",
"For",
"names",
"that",
"are",
"duplicated",
"the",
"name",
"is",
"mapped",
"to",
"None",
"."
] | def _get_dict_members(self, cat=None):
"""
For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None.
"""
self.confirm_no_error()
if cat not in self._dict_members:
new_dict = {}
for mem in self.in_category(cat):
if mem.name() not in new_dict:
new_dict[mem.name()] = mem
else:
new_dict[mem.name()] = self.Duplicate
self._dict_members[cat] = new_dict
return self._dict_members[cat] | [
"def",
"_get_dict_members",
"(",
"self",
",",
"cat",
"=",
"None",
")",
":",
"self",
".",
"confirm_no_error",
"(",
")",
"if",
"cat",
"not",
"in",
"self",
".",
"_dict_members",
":",
"new_dict",
"=",
"{",
"}",
"for",
"mem",
"in",
"self",
".",
"in_category",
"(",
"cat",
")",
":",
"if",
"mem",
".",
"name",
"(",
")",
"not",
"in",
"new_dict",
":",
"new_dict",
"[",
"mem",
".",
"name",
"(",
")",
"]",
"=",
"mem",
"else",
":",
"new_dict",
"[",
"mem",
".",
"name",
"(",
")",
"]",
"=",
"self",
".",
"Duplicate",
"self",
".",
"_dict_members",
"[",
"cat",
"]",
"=",
"new_dict",
"return",
"self",
".",
"_dict_members",
"[",
"cat",
"]"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/docs/doxygen/doxyxml/base.py#L111-L126 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.fromkeys | (cls, iterable, value=None) | return d | OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None). | OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None). | [
"OD",
".",
"fromkeys",
"(",
"S",
"[",
"v",
"]",
")",
"-",
">",
"New",
"ordered",
"dictionary",
"with",
"keys",
"from",
"S",
"and",
"values",
"equal",
"to",
"v",
"(",
"which",
"defaults",
"to",
"None",
")",
"."
] | def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d | [
"def",
"fromkeys",
"(",
"cls",
",",
"iterable",
",",
"value",
"=",
"None",
")",
":",
"d",
"=",
"cls",
"(",
")",
"for",
"key",
"in",
"iterable",
":",
"d",
"[",
"key",
"]",
"=",
"value",
"return",
"d"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py#L225-L233 | |
rbgirshick/caffe-fast-rcnn | 28a579eaf0668850705598b3075b8969f22226d9 | python/caffe/pycaffe.py | python | _Net_blobs | (self) | return OrderedDict(zip(self._blob_names, self._blobs)) | An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name | An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name | [
"An",
"OrderedDict",
"(",
"bottom",
"to",
"top",
"i",
".",
"e",
".",
"input",
"to",
"output",
")",
"of",
"network",
"blobs",
"indexed",
"by",
"name"
] | def _Net_blobs(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name
"""
return OrderedDict(zip(self._blob_names, self._blobs)) | [
"def",
"_Net_blobs",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"zip",
"(",
"self",
".",
"_blob_names",
",",
"self",
".",
"_blobs",
")",
")"
] | https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/python/caffe/pycaffe.py#L22-L27 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py2/jinja2/compiler.py | python | CodeGenerator.visit_Block | (self, node, frame) | Call a block and register it for the template. | Call a block and register it for the template. | [
"Call",
"a",
"block",
"and",
"register",
"it",
"for",
"the",
"template",
"."
] | def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 0
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline("if parent_template is None:")
self.indent()
level += 1
if node.scoped:
context = self.derive_context(frame)
else:
context = self.get_context_ref()
if (
supports_yield_from
and not self.environment.is_async
and frame.buffer is None
):
self.writeline(
"yield from context.blocks[%r][0](%s)" % (node.name, context), node
)
else:
loop = self.environment.is_async and "async for" or "for"
self.writeline(
"%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),
node,
)
self.indent()
self.simple_write("event", frame)
self.outdent()
self.outdent(level) | [
"def",
"visit_Block",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"level",
"=",
"0",
"if",
"frame",
".",
"toplevel",
":",
"# if we know that we are a child template, there is no need to",
"# check if we are one",
"if",
"self",
".",
"has_known_extends",
":",
"return",
"if",
"self",
".",
"extends_so_far",
">",
"0",
":",
"self",
".",
"writeline",
"(",
"\"if parent_template is None:\"",
")",
"self",
".",
"indent",
"(",
")",
"level",
"+=",
"1",
"if",
"node",
".",
"scoped",
":",
"context",
"=",
"self",
".",
"derive_context",
"(",
"frame",
")",
"else",
":",
"context",
"=",
"self",
".",
"get_context_ref",
"(",
")",
"if",
"(",
"supports_yield_from",
"and",
"not",
"self",
".",
"environment",
".",
"is_async",
"and",
"frame",
".",
"buffer",
"is",
"None",
")",
":",
"self",
".",
"writeline",
"(",
"\"yield from context.blocks[%r][0](%s)\"",
"%",
"(",
"node",
".",
"name",
",",
"context",
")",
",",
"node",
")",
"else",
":",
"loop",
"=",
"self",
".",
"environment",
".",
"is_async",
"and",
"\"async for\"",
"or",
"\"for\"",
"self",
".",
"writeline",
"(",
"\"%s event in context.blocks[%r][0](%s):\"",
"%",
"(",
"loop",
",",
"node",
".",
"name",
",",
"context",
")",
",",
"node",
",",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"simple_write",
"(",
"\"event\"",
",",
"frame",
")",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"outdent",
"(",
"level",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/compiler.py#L836-L872 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuItem.GetTextColour | (self) | return self._textColour | Returns this :class:`FlatMenuItem` foreground text colour. | Returns this :class:`FlatMenuItem` foreground text colour. | [
"Returns",
"this",
":",
"class",
":",
"FlatMenuItem",
"foreground",
"text",
"colour",
"."
] | def GetTextColour(self):
""" Returns this :class:`FlatMenuItem` foreground text colour. """
return self._textColour | [
"def",
"GetTextColour",
"(",
"self",
")",
":",
"return",
"self",
".",
"_textColour"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L5271-L5274 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/clang/cindex.py | python | Cursor.get_definition | (self) | return Cursor_def(self) | If the cursor is a reference to a declaration or a declaration of
some entity, return a cursor that points to the definition of that
entity. | If the cursor is a reference to a declaration or a declaration of
some entity, return a cursor that points to the definition of that
entity. | [
"If",
"the",
"cursor",
"is",
"a",
"reference",
"to",
"a",
"declaration",
"or",
"a",
"declaration",
"of",
"some",
"entity",
"return",
"a",
"cursor",
"that",
"points",
"to",
"the",
"definition",
"of",
"that",
"entity",
"."
] | def get_definition(self):
"""
If the cursor is a reference to a declaration or a declaration of
some entity, return a cursor that points to the definition of that
entity.
"""
# TODO: Should probably check that this is either a reference or
# declaration prior to issuing the lookup.
return Cursor_def(self) | [
"def",
"get_definition",
"(",
"self",
")",
":",
"# TODO: Should probably check that this is either a reference or",
"# declaration prior to issuing the lookup.",
"return",
"Cursor_def",
"(",
"self",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/clang/cindex.py#L833-L841 | |
deepmodeling/deepmd-kit | 159e45d248b0429844fb6a8cb3b3a201987c8d79 | deepmd/env.py | python | get_tf_session_config | () | return config | Configure tensorflow session.
Returns
-------
Any
session configure object | Configure tensorflow session. | [
"Configure",
"tensorflow",
"session",
"."
] | def get_tf_session_config() -> Any:
"""Configure tensorflow session.
Returns
-------
Any
session configure object
"""
set_tf_default_nthreads()
intra, inter = get_tf_default_nthreads()
config = tf.ConfigProto(
gpu_options=tf.GPUOptions(allow_growth=True),
intra_op_parallelism_threads=intra, inter_op_parallelism_threads=inter
)
return config | [
"def",
"get_tf_session_config",
"(",
")",
"->",
"Any",
":",
"set_tf_default_nthreads",
"(",
")",
"intra",
",",
"inter",
"=",
"get_tf_default_nthreads",
"(",
")",
"config",
"=",
"tf",
".",
"ConfigProto",
"(",
"gpu_options",
"=",
"tf",
".",
"GPUOptions",
"(",
"allow_growth",
"=",
"True",
")",
",",
"intra_op_parallelism_threads",
"=",
"intra",
",",
"inter_op_parallelism_threads",
"=",
"inter",
")",
"return",
"config"
] | https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/env.py#L111-L125 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | build/fbcode_builder/getdeps/copytree.py | python | find_eden_root | (dirpath) | If the specified directory is inside an EdenFS checkout, returns
the canonical absolute path to the root of that checkout.
Returns None if the specified directory is not in an EdenFS checkout. | If the specified directory is inside an EdenFS checkout, returns
the canonical absolute path to the root of that checkout. | [
"If",
"the",
"specified",
"directory",
"is",
"inside",
"an",
"EdenFS",
"checkout",
"returns",
"the",
"canonical",
"absolute",
"path",
"to",
"the",
"root",
"of",
"that",
"checkout",
"."
] | def find_eden_root(dirpath):
"""If the specified directory is inside an EdenFS checkout, returns
the canonical absolute path to the root of that checkout.
Returns None if the specified directory is not in an EdenFS checkout.
"""
if is_windows():
repo_type, repo_root = containing_repo_type(dirpath)
if repo_root is not None:
if os.path.exists(os.path.join(repo_root, ".eden", "config")):
return os.path.realpath(repo_root)
return None
try:
return os.readlink(os.path.join(dirpath, ".eden", "root"))
except OSError:
return None | [
"def",
"find_eden_root",
"(",
"dirpath",
")",
":",
"if",
"is_windows",
"(",
")",
":",
"repo_type",
",",
"repo_root",
"=",
"containing_repo_type",
"(",
"dirpath",
")",
"if",
"repo_root",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo_root",
",",
"\".eden\"",
",",
"\"config\"",
")",
")",
":",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"repo_root",
")",
"return",
"None",
"try",
":",
"return",
"os",
".",
"readlink",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"\".eden\"",
",",
"\"root\"",
")",
")",
"except",
"OSError",
":",
"return",
"None"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/build/fbcode_builder/getdeps/copytree.py#L29-L45 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tpu/session_support.py | python | WorkerHeartbeatManager.ping | (self, request=None, timeout_in_ms=60000) | return parsed_results | Ping all workers, returning the parsed status results. | Ping all workers, returning the parsed status results. | [
"Ping",
"all",
"workers",
"returning",
"the",
"parsed",
"status",
"results",
"."
] | def ping(self, request=None, timeout_in_ms=60000):
"""Ping all workers, returning the parsed status results."""
if request is None:
request = event_pb2.WorkerHeartbeatRequest()
options = config_pb2.RunOptions(timeout_in_ms=timeout_in_ms)
results = self._session.run(
self._ops,
feed_dict={self._request_placeholder: request.SerializeToString()},
options=options)
parsed_results = [
event_pb2.WorkerHeartbeatResponse.FromString(res_pb)
for res_pb in results
]
logging.debug('Ping results: %s', parsed_results)
return parsed_results | [
"def",
"ping",
"(",
"self",
",",
"request",
"=",
"None",
",",
"timeout_in_ms",
"=",
"60000",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"event_pb2",
".",
"WorkerHeartbeatRequest",
"(",
")",
"options",
"=",
"config_pb2",
".",
"RunOptions",
"(",
"timeout_in_ms",
"=",
"timeout_in_ms",
")",
"results",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"self",
".",
"_ops",
",",
"feed_dict",
"=",
"{",
"self",
".",
"_request_placeholder",
":",
"request",
".",
"SerializeToString",
"(",
")",
"}",
",",
"options",
"=",
"options",
")",
"parsed_results",
"=",
"[",
"event_pb2",
".",
"WorkerHeartbeatResponse",
".",
"FromString",
"(",
"res_pb",
")",
"for",
"res_pb",
"in",
"results",
"]",
"logging",
".",
"debug",
"(",
"'Ping results: %s'",
",",
"parsed_results",
")",
"return",
"parsed_results"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/session_support.py#L105-L120 | |
soui3/soui | c588024b2f4f6d3fadb53c1bfed5ccf00d0b7046 | third-part/jsoncpp/doxybuild.py | python | cd | (newdir) | http://stackoverflow.com/questions/431684/how-do-i-cd-in-python | http://stackoverflow.com/questions/431684/how-do-i-cd-in-python | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"431684",
"/",
"how",
"-",
"do",
"-",
"i",
"-",
"cd",
"-",
"in",
"-",
"python"
] | def cd(newdir):
"""
http://stackoverflow.com/questions/431684/how-do-i-cd-in-python
"""
prevdir = os.getcwd()
os.chdir(newdir)
try:
yield
finally:
os.chdir(prevdir) | [
"def",
"cd",
"(",
"newdir",
")",
":",
"prevdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"newdir",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"prevdir",
")"
] | https://github.com/soui3/soui/blob/c588024b2f4f6d3fadb53c1bfed5ccf00d0b7046/third-part/jsoncpp/doxybuild.py#L15-L24 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/coordinator.py | python | Coordinator.__init__ | (self, clean_stop_exception_types=None) | Create a new Coordinator.
Args:
clean_stop_exception_types: Optional tuple of Exception types that should
cause a clean stop of the coordinator. If an exception of one of these
types is reported to `request_stop(ex)` the coordinator will behave as
if `request_stop(None)` was called. Defaults to
`(tf.errors.OutOfRangeError,)` which is used by input queues to signal
the end of input. When feeding training data from a Python iterator it
is common to add `StopIteration` to this list. | Create a new Coordinator. | [
"Create",
"a",
"new",
"Coordinator",
"."
] | def __init__(self, clean_stop_exception_types=None):
"""Create a new Coordinator.
Args:
clean_stop_exception_types: Optional tuple of Exception types that should
cause a clean stop of the coordinator. If an exception of one of these
types is reported to `request_stop(ex)` the coordinator will behave as
if `request_stop(None)` was called. Defaults to
`(tf.errors.OutOfRangeError,)` which is used by input queues to signal
the end of input. When feeding training data from a Python iterator it
is common to add `StopIteration` to this list.
"""
if clean_stop_exception_types is None:
clean_stop_exception_types = (errors.OutOfRangeError,)
self._clean_stop_exception_types = tuple(clean_stop_exception_types)
# Protects all attributes.
self._lock = threading.Lock()
# Event set when threads must stop.
self._stop_event = threading.Event()
# Python exc_info to report.
# If not None, it should hold the returned value of sys.exc_info(), which is
# a tuple containing exception (type, value, traceback).
self._exc_info_to_raise = None
# True if we have called join() already.
self._joined = False
# Set of threads registered for joining when join() is called. These
# threads will be joined in addition to the threads passed to the join()
# call. It's ok if threads are both registered and passed to the join()
# call.
self._registered_threads = set() | [
"def",
"__init__",
"(",
"self",
",",
"clean_stop_exception_types",
"=",
"None",
")",
":",
"if",
"clean_stop_exception_types",
"is",
"None",
":",
"clean_stop_exception_types",
"=",
"(",
"errors",
".",
"OutOfRangeError",
",",
")",
"self",
".",
"_clean_stop_exception_types",
"=",
"tuple",
"(",
"clean_stop_exception_types",
")",
"# Protects all attributes.",
"self",
".",
"_lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"# Event set when threads must stop.",
"self",
".",
"_stop_event",
"=",
"threading",
".",
"Event",
"(",
")",
"# Python exc_info to report.",
"# If not None, it should hold the returned value of sys.exc_info(), which is",
"# a tuple containing exception (type, value, traceback).",
"self",
".",
"_exc_info_to_raise",
"=",
"None",
"# True if we have called join() already.",
"self",
".",
"_joined",
"=",
"False",
"# Set of threads registered for joining when join() is called. These",
"# threads will be joined in addition to the threads passed to the join()",
"# call. It's ok if threads are both registered and passed to the join()",
"# call.",
"self",
".",
"_registered_threads",
"=",
"set",
"(",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/coordinator.py#L128-L157 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/type.py | python | base | (type) | return __types[type]['base'] | Returns a base type for the given type or nothing in case the given type is
not derived. | Returns a base type for the given type or nothing in case the given type is
not derived. | [
"Returns",
"a",
"base",
"type",
"for",
"the",
"given",
"type",
"or",
"nothing",
"in",
"case",
"the",
"given",
"type",
"is",
"not",
"derived",
"."
] | def base(type):
"""Returns a base type for the given type or nothing in case the given type is
not derived."""
assert isinstance(type, basestring)
return __types[type]['base'] | [
"def",
"base",
"(",
"type",
")",
":",
"assert",
"isinstance",
"(",
"type",
",",
"basestring",
")",
"return",
"__types",
"[",
"type",
"]",
"[",
"'base'",
"]"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/type.py#L175-L179 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | llvm/bindings/python/llvm/object.py | python | Symbol.cache | (self) | Cache all cacheable properties. | Cache all cacheable properties. | [
"Cache",
"all",
"cacheable",
"properties",
"."
] | def cache(self):
"""Cache all cacheable properties."""
getattr(self, 'name')
getattr(self, 'address')
getattr(self, 'size') | [
"def",
"cache",
"(",
"self",
")",
":",
"getattr",
"(",
"self",
",",
"'name'",
")",
"getattr",
"(",
"self",
",",
"'address'",
")",
"getattr",
"(",
"self",
",",
"'size'",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/bindings/python/llvm/object.py#L343-L347 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/valgrind_tools.py | python | AddressSanitizerTool.CopyFiles | (cls, device) | Copies ASan tools to the device. | Copies ASan tools to the device. | [
"Copies",
"ASan",
"tools",
"to",
"the",
"device",
"."
] | def CopyFiles(cls, device):
"""Copies ASan tools to the device."""
libs = glob.glob(os.path.join(DIR_SOURCE_ROOT,
'third_party/llvm-build/Release+Asserts/',
'lib/clang/*/lib/linux/',
'libclang_rt.asan-arm-android.so'))
assert len(libs) == 1
subprocess.call(
[os.path.join(
DIR_SOURCE_ROOT,
'tools/android/asan/third_party/asan_device_setup.sh'),
'--device', str(device),
'--lib', libs[0],
'--extra-options', AddressSanitizerTool.EXTRA_OPTIONS])
device.WaitUntilFullyBooted() | [
"def",
"CopyFiles",
"(",
"cls",
",",
"device",
")",
":",
"libs",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DIR_SOURCE_ROOT",
",",
"'third_party/llvm-build/Release+Asserts/'",
",",
"'lib/clang/*/lib/linux/'",
",",
"'libclang_rt.asan-arm-android.so'",
")",
")",
"assert",
"len",
"(",
"libs",
")",
"==",
"1",
"subprocess",
".",
"call",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"DIR_SOURCE_ROOT",
",",
"'tools/android/asan/third_party/asan_device_setup.sh'",
")",
",",
"'--device'",
",",
"str",
"(",
"device",
")",
",",
"'--lib'",
",",
"libs",
"[",
"0",
"]",
",",
"'--extra-options'",
",",
"AddressSanitizerTool",
".",
"EXTRA_OPTIONS",
"]",
")",
"device",
".",
"WaitUntilFullyBooted",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/valgrind_tools.py#L43-L57 | ||
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/tools/cpplint.py | python | ExpectingFunctionArgs | (clean_lines, linenum) | return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1])))) | Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types. | Checks whether where function type arguments are expected. | [
"Checks",
"whether",
"where",
"function",
"type",
"arguments",
"are",
"expected",
"."
] | def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types.
"""
line = clean_lines.elided[linenum]
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1])))) | [
"def",
"ExpectingFunctionArgs",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"return",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"(",
"linenum",
">=",
"2",
"and",
"(",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\((?:\\S+,)?\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
"or",
"Match",
"(",
"r'^\\s*MOCK_(?:CONST_)?METHOD\\d+(?:_T)?\\(\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"2",
"]",
")",
"or",
"Search",
"(",
"r'\\bstd::m?function\\s*\\<\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
")",
")",
")"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L5324-L5343 | |
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/c64/cpu.py | python | CPU.EOR | (self, opcode) | exclusive OR | exclusive OR | [
"exclusive",
"OR"
] | def EOR(self, opcode):
""" exclusive OR """
reference_value = self.read_register(S_A)
addressing_mode = CPU.EOR_addressing_modes[opcode]
value = self.load_value_advancing(addressing_mode)
result = value ^ reference_value
self.write_register(S_A, result)
self.update_flags_by_number(result) | [
"def",
"EOR",
"(",
"self",
",",
"opcode",
")",
":",
"reference_value",
"=",
"self",
".",
"read_register",
"(",
"S_A",
")",
"addressing_mode",
"=",
"CPU",
".",
"EOR_addressing_modes",
"[",
"opcode",
"]",
"value",
"=",
"self",
".",
"load_value_advancing",
"(",
"addressing_mode",
")",
"result",
"=",
"value",
"^",
"reference_value",
"self",
".",
"write_register",
"(",
"S_A",
",",
"result",
")",
"self",
".",
"update_flags_by_number",
"(",
"result",
")"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/c64/cpu.py#L1335-L1342 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py | python | JIRA.delete_board | (self, id) | Delete an agile board. | Delete an agile board. | [
"Delete",
"an",
"agile",
"board",
"."
] | def delete_board(self, id):
"""Delete an agile board."""
board = Board(self._options, self._session, raw={'id': id})
board.delete() | [
"def",
"delete_board",
"(",
"self",
",",
"id",
")",
":",
"board",
"=",
"Board",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
",",
"raw",
"=",
"{",
"'id'",
":",
"id",
"}",
")",
"board",
".",
"delete",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L3229-L3232 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/_datasource.py | python | Repository.open | (self, path, mode='r', encoding=None, newline=None) | return DataSource.open(self, self._fullpath(path), mode,
encoding=encoding, newline=newline) | Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open. This may, but does not have to,
include the `baseurl` with which the `Repository` was
initialized.
mode : {'r', 'w', 'a'}, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing,
'a' to append. Available modes depend on the type of object
specified by `path`. Default is 'r'.
encoding : {None, str}, optional
Open text file with given encoding. The default encoding will be
what `io.open` uses.
newline : {None, str}, optional
Newline to use when reading text file.
Returns
-------
out : file object
File object. | Open and return file-like object prepending Repository base URL. | [
"Open",
"and",
"return",
"file",
"-",
"like",
"object",
"prepending",
"Repository",
"base",
"URL",
"."
] | def open(self, path, mode='r', encoding=None, newline=None):
"""
Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open. This may, but does not have to,
include the `baseurl` with which the `Repository` was
initialized.
mode : {'r', 'w', 'a'}, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing,
'a' to append. Available modes depend on the type of object
specified by `path`. Default is 'r'.
encoding : {None, str}, optional
Open text file with given encoding. The default encoding will be
what `io.open` uses.
newline : {None, str}, optional
Newline to use when reading text file.
Returns
-------
out : file object
File object.
"""
return DataSource.open(self, self._fullpath(path), mode,
encoding=encoding, newline=newline) | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"return",
"DataSource",
".",
"open",
"(",
"self",
",",
"self",
".",
"_fullpath",
"(",
"path",
")",
",",
"mode",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"newline",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/_datasource.py#L654-L684 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/environment.py | python | Environment.get_or_select_template | (self, template_name_or_list,
parent=None, globals=None) | return self.select_template(template_name_or_list, parent, globals) | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3 | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`. | [
"Does",
"a",
"typecheck",
"and",
"dispatches",
"to",
":",
"meth",
":",
"select_template",
"if",
"an",
"iterable",
"of",
"template",
"names",
"is",
"given",
"otherwise",
"to",
":",
"meth",
":",
"get_template",
"."
] | def get_or_select_template(self, template_name_or_list,
parent=None, globals=None):
"""Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, string_types):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals) | [
"def",
"get_or_select_template",
"(",
"self",
",",
"template_name_or_list",
",",
"parent",
"=",
"None",
",",
"globals",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"template_name_or_list",
",",
"string_types",
")",
":",
"return",
"self",
".",
"get_template",
"(",
"template_name_or_list",
",",
"parent",
",",
"globals",
")",
"elif",
"isinstance",
"(",
"template_name_or_list",
",",
"Template",
")",
":",
"return",
"template_name_or_list",
"return",
"self",
".",
"select_template",
"(",
"template_name_or_list",
",",
"parent",
",",
"globals",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/environment.py#L860-L872 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/configparser/backports/configparser/__init__.py | python | RawConfigParser.get | (self, section, option, **kwargs) | Get an option value for a given section.
If `vars' is provided, it must be a dictionary. The option is looked up
in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
If the key is not found and `fallback' is provided, it is used as
a fallback value. `None' can be provided as a `fallback' value.
If interpolation is enabled and the optional argument `raw' is False,
all interpolations are expanded in the return values.
Arguments `raw', `vars', and `fallback' are keyword only.
The section DEFAULT is special. | Get an option value for a given section. | [
"Get",
"an",
"option",
"value",
"for",
"a",
"given",
"section",
"."
] | def get(self, section, option, **kwargs):
"""Get an option value for a given section.
If `vars' is provided, it must be a dictionary. The option is looked up
in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
If the key is not found and `fallback' is provided, it is used as
a fallback value. `None' can be provided as a `fallback' value.
If interpolation is enabled and the optional argument `raw' is False,
all interpolations are expanded in the return values.
Arguments `raw', `vars', and `fallback' are keyword only.
The section DEFAULT is special.
"""
# keyword-only arguments
raw = kwargs.get('raw', False)
vars = kwargs.get('vars', None)
fallback = kwargs.get('fallback', _UNSET)
try:
d = self._unify_values(section, vars)
except NoSectionError:
if fallback is _UNSET:
raise
else:
return fallback
option = self.optionxform(option)
try:
value = d[option]
except KeyError:
if fallback is _UNSET:
raise NoOptionError(option, section)
else:
return fallback
if raw or value is None:
return value
else:
return self._interpolation.before_get(self, section, option, value, d) | [
"def",
"get",
"(",
"self",
",",
"section",
",",
"option",
",",
"*",
"*",
"kwargs",
")",
":",
"# keyword-only arguments",
"raw",
"=",
"kwargs",
".",
"get",
"(",
"'raw'",
",",
"False",
")",
"vars",
"=",
"kwargs",
".",
"get",
"(",
"'vars'",
",",
"None",
")",
"fallback",
"=",
"kwargs",
".",
"get",
"(",
"'fallback'",
",",
"_UNSET",
")",
"try",
":",
"d",
"=",
"self",
".",
"_unify_values",
"(",
"section",
",",
"vars",
")",
"except",
"NoSectionError",
":",
"if",
"fallback",
"is",
"_UNSET",
":",
"raise",
"else",
":",
"return",
"fallback",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"try",
":",
"value",
"=",
"d",
"[",
"option",
"]",
"except",
"KeyError",
":",
"if",
"fallback",
"is",
"_UNSET",
":",
"raise",
"NoOptionError",
"(",
"option",
",",
"section",
")",
"else",
":",
"return",
"fallback",
"if",
"raw",
"or",
"value",
"is",
"None",
":",
"return",
"value",
"else",
":",
"return",
"self",
".",
"_interpolation",
".",
"before_get",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
",",
"d",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/configparser/backports/configparser/__init__.py#L837-L876 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.DelLineRight | (*args, **kwargs) | return _stc.StyledTextCtrl_DelLineRight(*args, **kwargs) | DelLineRight(self)
Delete forwards from the current position to the end of the line. | DelLineRight(self) | [
"DelLineRight",
"(",
"self",
")"
] | def DelLineRight(*args, **kwargs):
"""
DelLineRight(self)
Delete forwards from the current position to the end of the line.
"""
return _stc.StyledTextCtrl_DelLineRight(*args, **kwargs) | [
"def",
"DelLineRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DelLineRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5154-L5160 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | unique_node_name_from_input | (node_name) | return node_name.replace(":", "__port__").replace("^", "__hat__") | Replaces invalid characters in input names to get a unique node name. | Replaces invalid characters in input names to get a unique node name. | [
"Replaces",
"invalid",
"characters",
"in",
"input",
"names",
"to",
"get",
"a",
"unique",
"node",
"name",
"."
] | def unique_node_name_from_input(node_name):
"""Replaces invalid characters in input names to get a unique node name."""
return node_name.replace(":", "__port__").replace("^", "__hat__") | [
"def",
"unique_node_name_from_input",
"(",
"node_name",
")",
":",
"return",
"node_name",
".",
"replace",
"(",
"\":\"",
",",
"\"__port__\"",
")",
".",
"replace",
"(",
"\"^\"",
",",
"\"__hat__\"",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L173-L175 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py | python | LoggerAdapter.isEnabledFor | (self, level) | return self.logger.isEnabledFor(level) | Is this logger enabled for level 'level'? | Is this logger enabled for level 'level'? | [
"Is",
"this",
"logger",
"enabled",
"for",
"level",
"level",
"?"
] | def isEnabledFor(self, level):
"""
Is this logger enabled for level 'level'?
"""
return self.logger.isEnabledFor(level) | [
"def",
"isEnabledFor",
"(",
"self",
",",
"level",
")",
":",
"return",
"self",
".",
"logger",
".",
"isEnabledFor",
"(",
"level",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L1768-L1772 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/python.py | python | check_python_version | (conf, minver=None) | Check if the python interpreter is found matching a given minimum version.
minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver.
If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR'
(eg. '2.4') of the actual python version found, and PYTHONDIR is
defined, pointing to the site-packages directory appropriate for
this python version, where modules/packages/extensions should be
installed.
:param minver: minimum version
:type minver: tuple of int | Check if the python interpreter is found matching a given minimum version.
minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver. | [
"Check",
"if",
"the",
"python",
"interpreter",
"is",
"found",
"matching",
"a",
"given",
"minimum",
"version",
".",
"minver",
"should",
"be",
"a",
"tuple",
"eg",
".",
"to",
"check",
"for",
"python",
">",
"=",
"2",
".",
"4",
".",
"2",
"pass",
"(",
"2",
"4",
"2",
")",
"as",
"minver",
"."
] | def check_python_version(conf, minver=None):
"""
Check if the python interpreter is found matching a given minimum version.
minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver.
If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR'
(eg. '2.4') of the actual python version found, and PYTHONDIR is
defined, pointing to the site-packages directory appropriate for
this python version, where modules/packages/extensions should be
installed.
:param minver: minimum version
:type minver: tuple of int
"""
assert minver is None or isinstance(minver, tuple)
pybin = conf.env['PYTHON']
if not pybin:
conf.fatal('could not find the python executable')
# Get python version string
cmd = pybin + ['-c', 'import sys\nfor x in sys.version_info: print(str(x))']
Logs.debug('python: Running python command %r' % cmd)
lines = conf.cmd_and_log(cmd).split()
assert len(lines) == 5, "found %i lines, expected 5: %r" % (len(lines), lines)
pyver_tuple = (int(lines[0]), int(lines[1]), int(lines[2]), lines[3], int(lines[4]))
# compare python version with the minimum required
result = (minver is None) or (pyver_tuple >= minver)
if result:
# define useful environment variables
pyver = '.'.join([str(x) for x in pyver_tuple[:2]])
conf.env['PYTHON_VERSION'] = pyver
if 'PYTHONDIR' in conf.environ:
pydir = conf.environ['PYTHONDIR']
else:
if Utils.is_win32:
(python_LIBDEST, pydir) = conf.get_python_variables(
["get_config_var('LIBDEST') or ''",
"get_python_lib(standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']])
else:
python_LIBDEST = None
(pydir,) = conf.get_python_variables( ["get_python_lib(standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']])
if python_LIBDEST is None:
if conf.env['LIBDIR']:
python_LIBDEST = os.path.join(conf.env['LIBDIR'], "python" + pyver)
else:
python_LIBDEST = os.path.join(conf.env['PREFIX'], "lib", "python" + pyver)
if 'PYTHONARCHDIR' in conf.environ:
pyarchdir = conf.environ['PYTHONARCHDIR']
else:
(pyarchdir, ) = conf.get_python_variables( ["get_python_lib(plat_specific=1, standard_lib=0, prefix=%r) or ''" % conf.env['PREFIX']])
if not pyarchdir:
pyarchdir = pydir
if hasattr(conf, 'define'): # conf.define is added by the C tool, so may not exist
conf.define('PYTHONDIR', pydir)
conf.define('PYTHONARCHDIR', pyarchdir)
conf.env['PYTHONDIR'] = pydir
conf.env['PYTHONARCHDIR'] = pyarchdir
# Feedback
pyver_full = '.'.join(map(str, pyver_tuple[:3]))
if minver is None:
conf.msg('Checking for python version', pyver_full)
else:
minver_str = '.'.join(map(str, minver))
conf.msg('Checking for python version', pyver_tuple, ">= %s" % (minver_str,) and 'GREEN' or 'YELLOW')
if not result:
conf.fatal('The python version is too old, expecting %r' % (minver,)) | [
"def",
"check_python_version",
"(",
"conf",
",",
"minver",
"=",
"None",
")",
":",
"assert",
"minver",
"is",
"None",
"or",
"isinstance",
"(",
"minver",
",",
"tuple",
")",
"pybin",
"=",
"conf",
".",
"env",
"[",
"'PYTHON'",
"]",
"if",
"not",
"pybin",
":",
"conf",
".",
"fatal",
"(",
"'could not find the python executable'",
")",
"# Get python version string",
"cmd",
"=",
"pybin",
"+",
"[",
"'-c'",
",",
"'import sys\\nfor x in sys.version_info: print(str(x))'",
"]",
"Logs",
".",
"debug",
"(",
"'python: Running python command %r'",
"%",
"cmd",
")",
"lines",
"=",
"conf",
".",
"cmd_and_log",
"(",
"cmd",
")",
".",
"split",
"(",
")",
"assert",
"len",
"(",
"lines",
")",
"==",
"5",
",",
"\"found %i lines, expected 5: %r\"",
"%",
"(",
"len",
"(",
"lines",
")",
",",
"lines",
")",
"pyver_tuple",
"=",
"(",
"int",
"(",
"lines",
"[",
"0",
"]",
")",
",",
"int",
"(",
"lines",
"[",
"1",
"]",
")",
",",
"int",
"(",
"lines",
"[",
"2",
"]",
")",
",",
"lines",
"[",
"3",
"]",
",",
"int",
"(",
"lines",
"[",
"4",
"]",
")",
")",
"# compare python version with the minimum required",
"result",
"=",
"(",
"minver",
"is",
"None",
")",
"or",
"(",
"pyver_tuple",
">=",
"minver",
")",
"if",
"result",
":",
"# define useful environment variables",
"pyver",
"=",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"pyver_tuple",
"[",
":",
"2",
"]",
"]",
")",
"conf",
".",
"env",
"[",
"'PYTHON_VERSION'",
"]",
"=",
"pyver",
"if",
"'PYTHONDIR'",
"in",
"conf",
".",
"environ",
":",
"pydir",
"=",
"conf",
".",
"environ",
"[",
"'PYTHONDIR'",
"]",
"else",
":",
"if",
"Utils",
".",
"is_win32",
":",
"(",
"python_LIBDEST",
",",
"pydir",
")",
"=",
"conf",
".",
"get_python_variables",
"(",
"[",
"\"get_config_var('LIBDEST') or ''\"",
",",
"\"get_python_lib(standard_lib=0, prefix=%r) or ''\"",
"%",
"conf",
".",
"env",
"[",
"'PREFIX'",
"]",
"]",
")",
"else",
":",
"python_LIBDEST",
"=",
"None",
"(",
"pydir",
",",
")",
"=",
"conf",
".",
"get_python_variables",
"(",
"[",
"\"get_python_lib(standard_lib=0, prefix=%r) or ''\"",
"%",
"conf",
".",
"env",
"[",
"'PREFIX'",
"]",
"]",
")",
"if",
"python_LIBDEST",
"is",
"None",
":",
"if",
"conf",
".",
"env",
"[",
"'LIBDIR'",
"]",
":",
"python_LIBDEST",
"=",
"os",
".",
"path",
".",
"join",
"(",
"conf",
".",
"env",
"[",
"'LIBDIR'",
"]",
",",
"\"python\"",
"+",
"pyver",
")",
"else",
":",
"python_LIBDEST",
"=",
"os",
".",
"path",
".",
"join",
"(",
"conf",
".",
"env",
"[",
"'PREFIX'",
"]",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"pyver",
")",
"if",
"'PYTHONARCHDIR'",
"in",
"conf",
".",
"environ",
":",
"pyarchdir",
"=",
"conf",
".",
"environ",
"[",
"'PYTHONARCHDIR'",
"]",
"else",
":",
"(",
"pyarchdir",
",",
")",
"=",
"conf",
".",
"get_python_variables",
"(",
"[",
"\"get_python_lib(plat_specific=1, standard_lib=0, prefix=%r) or ''\"",
"%",
"conf",
".",
"env",
"[",
"'PREFIX'",
"]",
"]",
")",
"if",
"not",
"pyarchdir",
":",
"pyarchdir",
"=",
"pydir",
"if",
"hasattr",
"(",
"conf",
",",
"'define'",
")",
":",
"# conf.define is added by the C tool, so may not exist",
"conf",
".",
"define",
"(",
"'PYTHONDIR'",
",",
"pydir",
")",
"conf",
".",
"define",
"(",
"'PYTHONARCHDIR'",
",",
"pyarchdir",
")",
"conf",
".",
"env",
"[",
"'PYTHONDIR'",
"]",
"=",
"pydir",
"conf",
".",
"env",
"[",
"'PYTHONARCHDIR'",
"]",
"=",
"pyarchdir",
"# Feedback",
"pyver_full",
"=",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"pyver_tuple",
"[",
":",
"3",
"]",
")",
")",
"if",
"minver",
"is",
"None",
":",
"conf",
".",
"msg",
"(",
"'Checking for python version'",
",",
"pyver_full",
")",
"else",
":",
"minver_str",
"=",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"minver",
")",
")",
"conf",
".",
"msg",
"(",
"'Checking for python version'",
",",
"pyver_tuple",
",",
"\">= %s\"",
"%",
"(",
"minver_str",
",",
")",
"and",
"'GREEN'",
"or",
"'YELLOW'",
")",
"if",
"not",
"result",
":",
"conf",
".",
"fatal",
"(",
"'The python version is too old, expecting %r'",
"%",
"(",
"minver",
",",
")",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/python.py#L375-L449 | ||
abseil/abseil-cpp | 73316fc3c565e5998983b0fb502d938ccddcded2 | absl/abseil.podspec.gen.py | python | write_podspec_map | (f, cur_map, depth) | Writes podspec from rule map recursively. | Writes podspec from rule map recursively. | [
"Writes",
"podspec",
"from",
"rule",
"map",
"recursively",
"."
] | def write_podspec_map(f, cur_map, depth):
"""Writes podspec from rule map recursively."""
for key, value in sorted(cur_map.items()):
indent = " " * (depth + 1)
f.write("{indent}{var0}.subspec '{key}' do |{var1}|\n".format(
indent=indent,
key=key,
var0=get_spec_var(depth),
var1=get_spec_var(depth + 1)))
if isinstance(value, dict):
write_podspec_map(f, value, depth + 1)
else:
write_podspec_rule(f, value, depth + 1)
f.write("{indent}end\n".format(indent=indent)) | [
"def",
"write_podspec_map",
"(",
"f",
",",
"cur_map",
",",
"depth",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"cur_map",
".",
"items",
"(",
")",
")",
":",
"indent",
"=",
"\" \"",
"*",
"(",
"depth",
"+",
"1",
")",
"f",
".",
"write",
"(",
"\"{indent}{var0}.subspec '{key}' do |{var1}|\\n\"",
".",
"format",
"(",
"indent",
"=",
"indent",
",",
"key",
"=",
"key",
",",
"var0",
"=",
"get_spec_var",
"(",
"depth",
")",
",",
"var1",
"=",
"get_spec_var",
"(",
"depth",
"+",
"1",
")",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"write_podspec_map",
"(",
"f",
",",
"value",
",",
"depth",
"+",
"1",
")",
"else",
":",
"write_podspec_rule",
"(",
"f",
",",
"value",
",",
"depth",
"+",
"1",
")",
"f",
".",
"write",
"(",
"\"{indent}end\\n\"",
".",
"format",
"(",
"indent",
"=",
"indent",
")",
")"
] | https://github.com/abseil/abseil-cpp/blob/73316fc3c565e5998983b0fb502d938ccddcded2/absl/abseil.podspec.gen.py#L158-L171 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/utils/chemdraw.py | python | CloseChemDrawDoc | () | force chemdraw to save the active document
NOTE: the extension of the filename will determine the format
used to save the file. | force chemdraw to save the active document | [
"force",
"chemdraw",
"to",
"save",
"the",
"active",
"document"
] | def CloseChemDrawDoc():
"""force chemdraw to save the active document
NOTE: the extension of the filename will determine the format
used to save the file.
"""
d = cdApp.ActiveDocument
d.Close() | [
"def",
"CloseChemDrawDoc",
"(",
")",
":",
"d",
"=",
"cdApp",
".",
"ActiveDocument",
"d",
".",
"Close",
"(",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/utils/chemdraw.py#L209-L216 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | isBaseChar | (ch) | return ret | This function is DEPRECATED. Use xmlIsBaseChar_ch or
xmlIsBaseCharQ instead | This function is DEPRECATED. Use xmlIsBaseChar_ch or
xmlIsBaseCharQ instead | [
"This",
"function",
"is",
"DEPRECATED",
".",
"Use",
"xmlIsBaseChar_ch",
"or",
"xmlIsBaseCharQ",
"instead"
] | def isBaseChar(ch):
"""This function is DEPRECATED. Use xmlIsBaseChar_ch or
xmlIsBaseCharQ instead """
ret = libxml2mod.xmlIsBaseChar(ch)
return ret | [
"def",
"isBaseChar",
"(",
"ch",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlIsBaseChar",
"(",
"ch",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L971-L975 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_schdecl_fresh_relation_rel | (p) | schdecl : FRESH RELATION rels | schdecl : FRESH RELATION rels | [
"schdecl",
":",
"FRESH",
"RELATION",
"rels"
] | def p_schdecl_fresh_relation_rel(p):
'schdecl : FRESH RELATION rels'
p[0] = [FreshConstantDecl(x.args[0]) if isinstance(x,ConstantDecl) else x for x in p[3]] | [
"def",
"p_schdecl_fresh_relation_rel",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"FreshConstantDecl",
"(",
"x",
".",
"args",
"[",
"0",
"]",
")",
"if",
"isinstance",
"(",
"x",
",",
"ConstantDecl",
")",
"else",
"x",
"for",
"x",
"in",
"p",
"[",
"3",
"]",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L551-L553 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlDtd.dtdElementDesc | (self, name) | return __tmp | Search the DTD for the description of this element | Search the DTD for the description of this element | [
"Search",
"the",
"DTD",
"for",
"the",
"description",
"of",
"this",
"element"
] | def dtdElementDesc(self, name):
"""Search the DTD for the description of this element """
ret = libxml2mod.xmlGetDtdElementDesc(self._o, name)
if ret is None:raise treeError('xmlGetDtdElementDesc() failed')
__tmp = xmlElement(_obj=ret)
return __tmp | [
"def",
"dtdElementDesc",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetDtdElementDesc",
"(",
"self",
".",
"_o",
",",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetDtdElementDesc() failed'",
")",
"__tmp",
"=",
"xmlElement",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L4965-L4970 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.