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
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Tools/CryVersionSelector/cryselect.py
python
cmd_run_project
(args, sys_argv=sys.argv[1:])
Runs the command on the project, by invoking it on the cryrun.exe that is used by the engine the project is registered to.
Runs the command on the project, by invoking it on the cryrun.exe that is used by the engine the project is registered to.
[ "Runs", "the", "command", "on", "the", "project", "by", "invoking", "it", "on", "the", "cryrun", ".", "exe", "that", "is", "used", "by", "the", "engine", "the", "project", "is", "registered", "to", "." ]
def cmd_run_project(args, sys_argv=sys.argv[1:]): """ Runs the command on the project, by invoking it on the cryrun.exe that is used by the engine the project is registered to. """ if not os.path.isfile(args.project_file): error_project_not_found(args) project = cryproject.CryProject() try: project.load(args.project_file) except Exception: error_project_json_decode(args) engine_id = project.engine_id() engine_path = "" # Start by checking for the ability to specifying use of the local engine if engine_id is '.': engine_path = os.path.dirname(args.project_file) else: # Now check the registry engine_registry = cryregistry.load_engines() engine_path = cryregistry.engine_path(engine_registry, engine_id) if engine_path is None: error_engine_path_not_found(args, engine_id) if getattr(sys, 'frozen', False): subcmd = [get_cryrun_path(engine_path)] else: subcmd = [ get_python_path(), get_cryrun_path(engine_path) ] if not os.path.isfile(subcmd[-1]): error_engine_tool_not_found(args, subcmd[-1]) subcmd.extend(sys_argv) print_subprocess(subcmd) try: subprocess.run(subcmd, stdout=None, stderr=None, check=True, universal_newlines=True) except subprocess.CalledProcessError as e: error_subprocess_error( args, "Encountered an error while running command '{}'!".format(e.cmd), e.returncode)
[ "def", "cmd_run_project", "(", "args", ",", "sys_argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "project_file", ")", ":", "error_project_not_found", "(", "args", ")", "pr...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/cryselect.py#L977-L1024
hydrogen-music/hydrogen
8a4eff74f9706922bd3a649a17cb18f4f5849cc1
windows/ci/copy_thirdparty_dlls.py
python
LibraryResolver.scan_dependencies
(file_name: str)
return [entry.dll.decode("utf-8") for entry in pe.DIRECTORY_ENTRY_IMPORT]
Find libraries that given file depends on.
Find libraries that given file depends on.
[ "Find", "libraries", "that", "given", "file", "depends", "on", "." ]
def scan_dependencies(file_name: str) -> List[str]: """ Find libraries that given file depends on. """ pe = pefile.PE(file_name) return [entry.dll.decode("utf-8") for entry in pe.DIRECTORY_ENTRY_IMPORT]
[ "def", "scan_dependencies", "(", "file_name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "pe", "=", "pefile", ".", "PE", "(", "file_name", ")", "return", "[", "entry", ".", "dll", ".", "decode", "(", "\"utf-8\"", ")", "for", "entry", "in", ...
https://github.com/hydrogen-music/hydrogen/blob/8a4eff74f9706922bd3a649a17cb18f4f5849cc1/windows/ci/copy_thirdparty_dlls.py#L136-L141
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/ops.py
python
get_all_collection_keys
()
return get_default_graph().get_all_collection_keys()
Returns a list of collections used in the default graph.
Returns a list of collections used in the default graph.
[ "Returns", "a", "list", "of", "collections", "used", "in", "the", "default", "graph", "." ]
def get_all_collection_keys(): """Returns a list of collections used in the default graph.""" return get_default_graph().get_all_collection_keys()
[ "def", "get_all_collection_keys", "(", ")", ":", "return", "get_default_graph", "(", ")", ".", "get_all_collection_keys", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/ops.py#L6690-L6692
tensor-compiler/taco
d0654a84137169883973c40a951dfdb89883fd9c
python_bindings/pytaco/pytensor/taco_tensor.py
python
tensor.copy
(self)
return new_t
Returns a deep copy of a tensor.
Returns a deep copy of a tensor.
[ "Returns", "a", "deep", "copy", "of", "a", "tensor", "." ]
def copy(self): """ Returns a deep copy of a tensor. """ new_t = tensor(self.shape, self.format, dtype=self.dtype) idx_vars = _cm.get_index_vars(self.order) new_t[idx_vars] = self[idx_vars] return new_t
[ "def", "copy", "(", "self", ")", ":", "new_t", "=", "tensor", "(", "self", ".", "shape", ",", "self", ".", "format", ",", "dtype", "=", "self", ".", "dtype", ")", "idx_vars", "=", "_cm", ".", "get_index_vars", "(", "self", ".", "order", ")", "new_t...
https://github.com/tensor-compiler/taco/blob/d0654a84137169883973c40a951dfdb89883fd9c/python_bindings/pytaco/pytensor/taco_tensor.py#L423-L430
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
_ShouldPrintError
(category, confidence, linenum)
return True
If confidence >= verbose, category passes filter and is not suppressed.
If confidence >= verbose, category passes filter and is not suppressed.
[ "If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "." ]
def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True
[ "def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "# There are three ways we might decide not to print an error message:", "# a \"NOLINT(category)\" comment appears in the source,", "# the verbosity level isn't high enough, or the filters filter it out...
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L1161-L1186
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/text_format.py
python
_Tokenizer._ParseError
(self, message)
return ParseError('%d:%d : %s' % ( self._line + 1, self._column + 1, message))
Creates and *returns* a ParseError for the current token.
Creates and *returns* a ParseError for the current token.
[ "Creates", "and", "*", "returns", "*", "a", "ParseError", "for", "the", "current", "token", "." ]
def _ParseError(self, message): """Creates and *returns* a ParseError for the current token.""" return ParseError('%d:%d : %s' % ( self._line + 1, self._column + 1, message))
[ "def", "_ParseError", "(", "self", ",", "message", ")", ":", "return", "ParseError", "(", "'%d:%d : %s'", "%", "(", "self", ".", "_line", "+", "1", ",", "self", ".", "_column", "+", "1", ",", "message", ")", ")" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/text_format.py#L561-L564
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
utils/pylit/pylit.py
python
TextCodeConverter.convert
(self, lines)
Iterate over lines of a program document and convert between "text" and "code" format
Iterate over lines of a program document and convert between "text" and "code" format
[ "Iterate", "over", "lines", "of", "a", "program", "document", "and", "convert", "between", "text", "and", "code", "format" ]
def convert(self, lines): """Iterate over lines of a program document and convert between "text" and "code" format """ # Initialise internal data arguments. (Done here, so that every new iteration # re-initialises them.) # # `state` # the "type" of the currently processed block of lines. One of # # :"": initial state: check for header, # :"header": leading code block: strip `header_string`, # :"documentation": documentation part: comment out, # :"code_block": literal blocks containing source code: unindent. # # :: self.state = "" # `_codeindent` # * Do not confuse the internal attribute `_codeindent` with the configurable # `codeindent` (without the leading underscore). # * `_codeindent` is set in `Text2Code.code_block_handler`_ to the indent of # first non-blank "code_block" line and stripped from all "code_block" lines # in the text-to-code conversion, # * `codeindent` is set in `__init__` to `defaults.codeindent`_ and added to # "code_block" lines in the code-to-text conversion. # # :: self._codeindent = 0 # `_textindent` # * set by `Text2Code.documentation_handler`_ to the minimal indent of a # documentation block, # * used in `Text2Code.set_state`_ to find the end of a code block. # # :: self._textindent = 0 # `_add_code_block_marker` # If the last paragraph of a documentation block does not end with a # code_block_marker_, it should be added (otherwise, the back-conversion # fails.). # # `_add_code_block_marker` is set by `Code2Text.documentation_handler`_ # and evaluated by `Code2Text.code_block_handler`_, because the # documentation_handler does not know whether the next block will be # documentation (with no need for a code_block_marker) or a code block. # # :: self._add_code_block_marker = False # Determine the state of the block and convert with the matching "handler":: for block in collect_blocks(expandtabs_filter(lines)): self.set_state(block) for line in getattr(self, self.state+"_handler")(block): yield line
[ "def", "convert", "(", "self", ",", "lines", ")", ":", "# Initialise internal data arguments. (Done here, so that every new iteration", "# re-initialises them.)", "#", "# `state`", "# the \"type\" of the currently processed block of lines. One of", "#", "# :\"\": initial...
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/utils/pylit/pylit.py#L547-L610
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/symbolic.py
python
Type.info
(self)
Returns a verbose, human readable string representation of this type
Returns a verbose, human readable string representation of this type
[ "Returns", "a", "verbose", "human", "readable", "string", "representation", "of", "this", "type" ]
def info(self): """Returns a verbose, human readable string representation of this type""" if self.char is None: return 'unknown' typedesc = "%s (%s)"%(self._TYPE_DESCRIPTIONS[self.char],self.char) if self.size is not None: if isinstance(self.size,(list,tuple)): sizedesc = 'x'.join(str(v) for v in self.size) typedesc = sizedesc + ' ' + typedesc else: sizedesc = str(self.size) typedesc = sizedesc + '-' + typedesc if self.subtype is None: return typedesc else: if self.char == 'U': return '%s of type %s'%(typedesc,self.subtype) if isinstance(self.subtype,list): return '%s of subtypes [%s]'%(typedesc,','.join(str(s) for s in self.subtype)) else: return '%s of subtype (%s)'%(typedesc,self.subtype.info())
[ "def", "info", "(", "self", ")", ":", "if", "self", ".", "char", "is", "None", ":", "return", "'unknown'", "typedesc", "=", "\"%s (%s)\"", "%", "(", "self", ".", "_TYPE_DESCRIPTIONS", "[", "self", ".", "char", "]", ",", "self", ".", "char", ")", "if"...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L853-L873
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py
python
ParserElement.__call__
(self, name=None)
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}.
[ "Shortcut", "for", "C", "{", "L", "{", "setResultsName", "}}", "with", "C", "{", "listAllMatches", "=", "False", "}", ".", "If", "C", "{", "name", "}", "is", "given", "with", "a", "trailing", "C", "{", "*", "}", "character", "then", "C", "{", "list...
def __call__(self, name=None): """ Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") """ if name is not None: return self.setResultsName(name) else: return self.copy()
[ "def", "__call__", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", "return", "self", ".", "setResultsName", "(", "name", ")", "else", ":", "return", "self", ".", "copy", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L2026-L2043
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
mlir/utils/spirv/gen_spirv_dialect.py
python
get_description
(text, appendix)
return fmt_str.format(text=text, appendix=appendix)
Generates the description for the given SPIR-V instruction. Arguments: - text: Textual description of the operation as string. - appendix: Additional contents to attach in description as string, includking IR examples, and others. Returns: - A string that corresponds to the description of the Tablegen op.
Generates the description for the given SPIR-V instruction.
[ "Generates", "the", "description", "for", "the", "given", "SPIR", "-", "V", "instruction", "." ]
def get_description(text, appendix): """Generates the description for the given SPIR-V instruction. Arguments: - text: Textual description of the operation as string. - appendix: Additional contents to attach in description as string, includking IR examples, and others. Returns: - A string that corresponds to the description of the Tablegen op. """ fmt_str = '{text}\n\n <!-- End of AutoGen section -->\n{appendix}\n ' return fmt_str.format(text=text, appendix=appendix)
[ "def", "get_description", "(", "text", ",", "appendix", ")", ":", "fmt_str", "=", "'{text}\\n\\n <!-- End of AutoGen section -->\\n{appendix}\\n '", "return", "fmt_str", ".", "format", "(", "text", "=", "text", ",", "appendix", "=", "appendix", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/mlir/utils/spirv/gen_spirv_dialect.py#L657-L669
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PreviewControlBar.GetPrintPreview
(*args, **kwargs)
return _windows_.PreviewControlBar_GetPrintPreview(*args, **kwargs)
GetPrintPreview(self) -> PrintPreview
GetPrintPreview(self) -> PrintPreview
[ "GetPrintPreview", "(", "self", ")", "-", ">", "PrintPreview" ]
def GetPrintPreview(*args, **kwargs): """GetPrintPreview(self) -> PrintPreview""" return _windows_.PreviewControlBar_GetPrintPreview(*args, **kwargs)
[ "def", "GetPrintPreview", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PreviewControlBar_GetPrintPreview", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5545-L5547
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBProcess.GetAddressByteSize
(self)
return _lldb.SBProcess_GetAddressByteSize(self)
GetAddressByteSize(SBProcess self) -> uint32_t
GetAddressByteSize(SBProcess self) -> uint32_t
[ "GetAddressByteSize", "(", "SBProcess", "self", ")", "-", ">", "uint32_t" ]
def GetAddressByteSize(self): """GetAddressByteSize(SBProcess self) -> uint32_t""" return _lldb.SBProcess_GetAddressByteSize(self)
[ "def", "GetAddressByteSize", "(", "self", ")", ":", "return", "_lldb", ".", "SBProcess_GetAddressByteSize", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8497-L8499
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/callback/_summary_collector.py
python
SummaryCollector._collect_dataset_graph
(self, cb_params)
Only collect train dataset graph.
Only collect train dataset graph.
[ "Only", "collect", "train", "dataset", "graph", "." ]
def _collect_dataset_graph(self, cb_params): """Only collect train dataset graph.""" if not self._collect_specified_data.get('collect_dataset_graph'): return # After analysis, we think that the validated dataset graph and the training dataset graph # should be consistent under normal scenarios, so only the training dataset graph is collected. if cb_params.mode == ModeEnum.TRAIN.value: train_dataset = cb_params.train_dataset dataset_graph = DatasetGraph() graph_bytes = dataset_graph.package_dataset_graph(train_dataset) if graph_bytes is None: return self._record.add_value('dataset_graph', 'train_dataset', graph_bytes)
[ "def", "_collect_dataset_graph", "(", "self", ",", "cb_params", ")", ":", "if", "not", "self", ".", "_collect_specified_data", ".", "get", "(", "'collect_dataset_graph'", ")", ":", "return", "# After analysis, we think that the validated dataset graph and the training dataset...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/callback/_summary_collector.py#L713-L726
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/linalg.py
python
eigvalsh
(x, UPLO='L', name=None)
return out_value
Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x should be one of float32, float64, complex64, complex128. UPLO(str, optional): Lower triangular part of a (‘L’, default) or the upper triangular part (‘U’). 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: Tensor: The tensor eigenvalues in ascending order. Examples: .. code-block:: python import numpy as np import paddle x_data = np.array([[1, -2j], [2j, 5]]) x = paddle.to_tensor(x_data) out_value = paddle.eigvalsh(x, UPLO='L') print(out_value) #[0.17157288, 5.82842712]
Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix.
[ "Computes", "the", "eigenvalues", "of", "a", "complex", "Hermitian", "(", "conjugate", "symmetric", ")", "or", "a", "real", "symmetric", "matrix", "." ]
def eigvalsh(x, UPLO='L', name=None): """ Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x should be one of float32, float64, complex64, complex128. UPLO(str, optional): Lower triangular part of a (‘L’, default) or the upper triangular part (‘U’). 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: Tensor: The tensor eigenvalues in ascending order. Examples: .. code-block:: python import numpy as np import paddle x_data = np.array([[1, -2j], [2j, 5]]) x = paddle.to_tensor(x_data) out_value = paddle.eigvalsh(x, UPLO='L') print(out_value) #[0.17157288, 5.82842712] """ if in_dygraph_mode(): is_test = x.stop_gradient values, _ = _C_ops.eigvalsh(x, 'UPLO', UPLO, 'is_test', is_test) return values def __check_input(x, UPLO): x_shape = list(x.shape) if len(x.shape) < 2: raise ValueError( "Input(input) only support >=2 tensor, but received " "length of Input(input) is %s." % len(x.shape)) if x_shape[-1] != x_shape[-2]: raise ValueError( "The input matrix must be batches of square matrices. But received x's dimention: {}". format(x_shape)) if UPLO is not 'L' and UPLO is not 'U': raise ValueError( "UPLO must be L or U. But received UPLO is: {}".format(UPLO)) __check_input(x, UPLO) helper = LayerHelper('eigvalsh', **locals()) check_variable_and_dtype(x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'eigvalsh') out_value = helper.create_variable_for_type_inference(dtype=x.dtype) out_vector = helper.create_variable_for_type_inference(dtype=x.dtype) is_test = x.stop_gradient helper.append_op( type='eigvalsh', inputs={'X': x}, outputs={'Eigenvalues': out_value, 'Eigenvectors': out_vector}, attrs={'UPLO': UPLO, 'is_test': is_test}) return out_value
[ "def", "eigvalsh", "(", "x", ",", "UPLO", "=", "'L'", ",", "name", "=", "None", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "is_test", "=", "x", ".", "stop_gradient", "values", ",", "_", "=", "_C_ops", ".", "eigvalsh", "(", "x", ",", "'UPLO'"...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/linalg.py#L2752-L2816
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_AccessControl.py
python
_get_permission_list
(resource_name, logical_resource_id, permission_metadata_list, problems)
return permission_list
Constructs a list of permissions from resource metadata. Args: resource_name - the name of the resource or resource group that defines the resource with the permission logical_resource_id - the logical id of the resource with the permission permission_metadata_list - The permission metadata from the resource. [ # optional list or a single object { "AbstractRole": [ "<abstract-role-name>", ... ], # required list or single string "Action": [ "<allowed-action>", ... ] # required list or single string "ResourceSuffix": [ "<resource-suffix>", ... ] # required list or single string }, ... ] problems - A ProblemList object used to report problems Returns: A list constructed from the provided metadata: [ { "AbstractRole": [ ["<resource-group-name>", "<abstract-role-name>"], ... ], "Action": [ "<allowed-action>", ... ], "ResourceSuffix": [ "<resource-suffix>", ... ], "LogicalResourceId": "<logical-resource-id>" }, ... ]
Constructs a list of permissions from resource metadata.
[ "Constructs", "a", "list", "of", "permissions", "from", "resource", "metadata", "." ]
def _get_permission_list(resource_name, logical_resource_id, permission_metadata_list, problems): """Constructs a list of permissions from resource metadata. Args: resource_name - the name of the resource or resource group that defines the resource with the permission logical_resource_id - the logical id of the resource with the permission permission_metadata_list - The permission metadata from the resource. [ # optional list or a single object { "AbstractRole": [ "<abstract-role-name>", ... ], # required list or single string "Action": [ "<allowed-action>", ... ] # required list or single string "ResourceSuffix": [ "<resource-suffix>", ... ] # required list or single string }, ... ] problems - A ProblemList object used to report problems Returns: A list constructed from the provided metadata: [ { "AbstractRole": [ ["<resource-group-name>", "<abstract-role-name>"], ... ], "Action": [ "<allowed-action>", ... ], "ResourceSuffix": [ "<resource-suffix>", ... ], "LogicalResourceId": "<logical-resource-id>" }, ... ] """ permission_list = [] if not isinstance(permission_metadata_list, list): permission_metadata_list = [permission_metadata_list] for permission_metadata in permission_metadata_list: permission = _get_permission(resource_name, logical_resource_id, permission_metadata, problems) if permission is not None: permission_list.append(permission) return permission_list
[ "def", "_get_permission_list", "(", "resource_name", ",", "logical_resource_id", ",", "permission_metadata_list", ",", "problems", ")", ":", "permission_list", "=", "[", "]", "if", "not", "isinstance", "(", "permission_metadata_list", ",", "list", ")", ":", "permiss...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_AccessControl.py#L384-L431
facebook/watchman
0917460c71b000b96be9b9575d77f06f2f6053bb
watchman/python/pywatchman_aio/__init__.py
python
AsyncCodec.send
(self, *args)
Send the given message via the underlying transport.
Send the given message via the underlying transport.
[ "Send", "the", "given", "message", "via", "the", "underlying", "transport", "." ]
async def send(self, *args): """Send the given message via the underlying transport.""" raise NotImplementedError()
[ "async", "def", "send", "(", "self", ",", "*", "args", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/watchman/python/pywatchman_aio/__init__.py#L131-L133
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/numpy_.py
python
PandasDtype.construct_array_type
(cls)
return PandasArray
Return the array type associated with this dtype. Returns ------- type
Return the array type associated with this dtype.
[ "Return", "the", "array", "type", "associated", "with", "this", "dtype", "." ]
def construct_array_type(cls): """ Return the array type associated with this dtype. Returns ------- type """ return PandasArray
[ "def", "construct_array_type", "(", "cls", ")", ":", "return", "PandasArray" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/numpy_.py#L82-L90
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/symbol/symbol.py
python
Symbol.nansum
(self, *args, **kwargs)
return op.nansum(self, *args, **kwargs)
Convenience fluent method for :py:func:`nansum`. The arguments are the same as for :py:func:`nansum`, with this array as data.
Convenience fluent method for :py:func:`nansum`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "nansum", "." ]
def nansum(self, *args, **kwargs): """Convenience fluent method for :py:func:`nansum`. The arguments are the same as for :py:func:`nansum`, with this array as data. """ return op.nansum(self, *args, **kwargs)
[ "def", "nansum", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "nansum", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/symbol/symbol.py#L2206-L2212
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/datetimes.py
python
_maybe_localize_point
(ts, is_none, is_not_none, freq, tz)
return ts
Localize a start or end Timestamp to the timezone of the corresponding start or end Timestamp Parameters ---------- ts : start or end Timestamp to potentially localize is_none : argument that should be None is_not_none : argument that should not be None freq : Tick, DateOffset, or None tz : str, timezone object or None Returns ------- ts : Timestamp
Localize a start or end Timestamp to the timezone of the corresponding start or end Timestamp
[ "Localize", "a", "start", "or", "end", "Timestamp", "to", "the", "timezone", "of", "the", "corresponding", "start", "or", "end", "Timestamp" ]
def _maybe_localize_point(ts, is_none, is_not_none, freq, tz): """ Localize a start or end Timestamp to the timezone of the corresponding start or end Timestamp Parameters ---------- ts : start or end Timestamp to potentially localize is_none : argument that should be None is_not_none : argument that should not be None freq : Tick, DateOffset, or None tz : str, timezone object or None Returns ------- ts : Timestamp """ # Make sure start and end are timezone localized if: # 1) freq = a Timedelta-like frequency (Tick) # 2) freq = None i.e. generating a linspaced range if isinstance(freq, Tick) or freq is None: localize_args = {'tz': tz, 'ambiguous': False} else: localize_args = {'tz': None} if is_none is None and is_not_none is not None: ts = ts.tz_localize(**localize_args) return ts
[ "def", "_maybe_localize_point", "(", "ts", ",", "is_none", ",", "is_not_none", ",", "freq", ",", "tz", ")", ":", "# Make sure start and end are timezone localized if:", "# 1) freq = a Timedelta-like frequency (Tick)", "# 2) freq = None i.e. generating a linspaced range", "if", "i...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimes.py#L2126-L2152
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py
python
_get_stratified_batch_from_tensors
(val_list, label, accept_probs, batch_size, queue_threads=3)
return final_q.dequeue_many(batch_size)
Accepts examples one-at-a-time based on class.
Accepts examples one-at-a-time based on class.
[ "Accepts", "examples", "one", "-", "at", "-", "a", "-", "time", "based", "on", "class", "." ]
def _get_stratified_batch_from_tensors(val_list, label, accept_probs, batch_size, queue_threads=3): """Accepts examples one-at-a-time based on class.""" # Make queue that will have proper class proportions. Contains exactly one # batch at a time. vals_shapes = [val.get_shape() for val in val_list] vals_dtypes = [val.dtype for val in val_list] label_shape = label.get_shape() final_q = data_flow_ops.FIFOQueue(capacity=batch_size, shapes=vals_shapes + [label_shape], dtypes=vals_dtypes + [label.dtype], name='batched_queue') # Conditionally enqueue. tensors_to_enqueue = val_list + [label] eq_tf = array_ops.reshape(math_ops.less( random_ops.random_uniform([1]), array_ops.slice(accept_probs, [label], [1])), []) conditional_enqueue = control_flow_ops.cond( eq_tf, lambda: final_q.enqueue(tensors_to_enqueue), control_flow_ops.no_op) queue_runner.add_queue_runner(queue_runner.QueueRunner( final_q, [conditional_enqueue] * queue_threads)) return final_q.dequeue_many(batch_size)
[ "def", "_get_stratified_batch_from_tensors", "(", "val_list", ",", "label", ",", "accept_probs", ",", "batch_size", ",", "queue_threads", "=", "3", ")", ":", "# Make queue that will have proper class proportions. Contains exactly one", "# batch at a time.", "vals_shapes", "=", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py#L374-L400
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/data/_utils/worker.py
python
get_worker_info
()
return _worker_info
r"""Returns the information about the current :class:`~torch.utils.data.DataLoader` iterator worker process. When called in a worker, this returns an object guaranteed to have the following attributes: * :attr:`id`: the current worker id. * :attr:`num_workers`: the total number of workers. * :attr:`seed`: the random seed set for the current worker. This value is determined by main process RNG and the worker id. See :class:`~torch.utils.data.DataLoader`'s documentation for more details. * :attr:`dataset`: the copy of the dataset object in **this** process. Note that this will be a different object in a different process than the one in the main process. When called in the main process, this returns ``None``. .. note:: When used in a :attr:`worker_init_fn` passed over to :class:`~torch.utils.data.DataLoader`, this method can be useful to set up each worker process differently, for instance, using ``worker_id`` to configure the ``dataset`` object to only read a specific fraction of a sharded dataset, or use ``seed`` to seed other libraries used in dataset code.
r"""Returns the information about the current :class:`~torch.utils.data.DataLoader` iterator worker process.
[ "r", "Returns", "the", "information", "about", "the", "current", ":", "class", ":", "~torch", ".", "utils", ".", "data", ".", "DataLoader", "iterator", "worker", "process", "." ]
def get_worker_info(): r"""Returns the information about the current :class:`~torch.utils.data.DataLoader` iterator worker process. When called in a worker, this returns an object guaranteed to have the following attributes: * :attr:`id`: the current worker id. * :attr:`num_workers`: the total number of workers. * :attr:`seed`: the random seed set for the current worker. This value is determined by main process RNG and the worker id. See :class:`~torch.utils.data.DataLoader`'s documentation for more details. * :attr:`dataset`: the copy of the dataset object in **this** process. Note that this will be a different object in a different process than the one in the main process. When called in the main process, this returns ``None``. .. note:: When used in a :attr:`worker_init_fn` passed over to :class:`~torch.utils.data.DataLoader`, this method can be useful to set up each worker process differently, for instance, using ``worker_id`` to configure the ``dataset`` object to only read a specific fraction of a sharded dataset, or use ``seed`` to seed other libraries used in dataset code. """ return _worker_info
[ "def", "get_worker_info", "(", ")", ":", "return", "_worker_info" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/data/_utils/worker.py#L83-L109
Tencent/Pebble
68315f176d9e328a233ace29b7579a829f89879f
tools/blade/src/blade/cc_targets.py
python
cc_binary
(name, srcs=[], deps=[], warning='yes', defs=[], incs=[], optimize=[], dynamic_link=False, extra_cppflags=[], extra_linkflags=[], export_dynamic=False, **kwargs)
cc_binary target.
cc_binary target.
[ "cc_binary", "target", "." ]
def cc_binary(name, srcs=[], deps=[], warning='yes', defs=[], incs=[], optimize=[], dynamic_link=False, extra_cppflags=[], extra_linkflags=[], export_dynamic=False, **kwargs): """cc_binary target. """ cc_binary_target = CcBinary(name, srcs, deps, warning, defs, incs, optimize, dynamic_link, extra_cppflags, extra_linkflags, export_dynamic, blade.blade, kwargs) blade.blade.register_target(cc_binary_target)
[ "def", "cc_binary", "(", "name", ",", "srcs", "=", "[", "]", ",", "deps", "=", "[", "]", ",", "warning", "=", "'yes'", ",", "defs", "=", "[", "]", ",", "incs", "=", "[", "]", ",", "optimize", "=", "[", "]", ",", "dynamic_link", "=", "False", ...
https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/cc_targets.py#L861-L887
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues.KeyFlagsByModuleDict
(self)
return self.__dict__['__key_flags_by_module']
Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects.
Returns the dictionary of module_name -> list of key flags.
[ "Returns", "the", "dictionary", "of", "module_name", "-", ">", "list", "of", "key", "flags", "." ]
def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module']
[ "def", "KeyFlagsByModuleDict", "(", "self", ")", ":", "return", "self", ".", "__dict__", "[", "'__key_flags_by_module'", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L867-L874
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py
python
SocketHandler.makeSocket
(self, timeout=1)
return result
A factory method which allows subclasses to define the precise type of socket they want.
A factory method which allows subclasses to define the precise type of socket they want.
[ "A", "factory", "method", "which", "allows", "subclasses", "to", "define", "the", "precise", "type", "of", "socket", "they", "want", "." ]
def makeSocket(self, timeout=1): """ A factory method which allows subclasses to define the precise type of socket they want. """ if self.port is not None: result = socket.create_connection(self.address, timeout=timeout) else: result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) result.settimeout(timeout) try: result.connect(self.address) except OSError: result.close() # Issue 19182 raise return result
[ "def", "makeSocket", "(", "self", ",", "timeout", "=", "1", ")", ":", "if", "self", ".", "port", "is", "not", "None", ":", "result", "=", "socket", ".", "create_connection", "(", "self", ".", "address", ",", "timeout", "=", "timeout", ")", "else", ":...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py#L521-L536
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/file_util.py
python
remove_dir
(name, quiet = True)
Remove the specified directory.
Remove the specified directory.
[ "Remove", "the", "specified", "directory", "." ]
def remove_dir(name, quiet = True): """ Remove the specified directory. """ try: if path_exists(name): shutil.rmtree(name, ignore_errors=False, onerror=handle_remove_readonly) if not quiet: sys.stdout.write('Removing '+name+' directory.\n') except IOError, (errno, strerror): sys.stderr.write('Failed to remove directory '+name+': '+strerror) raise
[ "def", "remove_dir", "(", "name", ",", "quiet", "=", "True", ")", ":", "try", ":", "if", "path_exists", "(", "name", ")", ":", "shutil", ".", "rmtree", "(", "name", ",", "ignore_errors", "=", "False", ",", "onerror", "=", "handle_remove_readonly", ")", ...
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/file_util.py#L108-L117
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/base.py
python
Index._set_names
(self, values, level=None)
Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels). Otherwise level must be None Raises ------ TypeError if each name is not hashable.
Set new names on index. Each name has to be a hashable type.
[ "Set", "new", "names", "on", "index", ".", "Each", "name", "has", "to", "be", "a", "hashable", "type", "." ]
def _set_names(self, values, level=None) -> None: """ Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels). Otherwise level must be None Raises ------ TypeError if each name is not hashable. """ if not is_list_like(values): raise ValueError("Names must be a list-like") if len(values) != 1: raise ValueError(f"Length of new names must be 1, got {len(values)}") # GH 20527 # All items in 'name' need to be hashable: validate_all_hashable(*values, error_name=f"{type(self).__name__}.name") self._name = values[0]
[ "def", "_set_names", "(", "self", ",", "values", ",", "level", "=", "None", ")", "->", "None", ":", "if", "not", "is_list_like", "(", "values", ")", ":", "raise", "ValueError", "(", "\"Names must be a list-like\"", ")", "if", "len", "(", "values", ")", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L1503-L1528
baidu/tera
dbcd28af792d879d961bf9fc7eb60de81b437646
src/sdk/python/TeraSdk.py
python
RowReader.SetTimeRange
(self, start, end)
set time range
set time range
[ "set", "time", "range" ]
def SetTimeRange(self, start, end): """ set time range """ lib.tera_row_reader_set_time_range(self.reader, start, end)
[ "def", "SetTimeRange", "(", "self", ",", "start", ",", "end", ")", ":", "lib", ".", "tera_row_reader_set_time_range", "(", "self", ".", "reader", ",", "start", ",", "end", ")" ]
https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L723-L725
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py
python
MaskedArray.harden_mask
(self)
return self
Force the mask to hard. Whether the mask of a masked array is hard or soft is determined by its `hardmask` property. `harden_mask` sets `hardmask` to True. See Also -------- hardmask
Force the mask to hard.
[ "Force", "the", "mask", "to", "hard", "." ]
def harden_mask(self): """ Force the mask to hard. Whether the mask of a masked array is hard or soft is determined by its `hardmask` property. `harden_mask` sets `hardmask` to True. See Also -------- hardmask """ self._hardmask = True return self
[ "def", "harden_mask", "(", "self", ")", ":", "self", ".", "_hardmask", "=", "True", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L3499-L3512
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/campus_factory/python-lib/campus_factory/ClusterStatus.py
python
CondorConfig.get
(self, key)
@param key: string key @return: string - value corresponding to key or "" if key is non-valid
[]
def get(self, key): """ @param key: string key @return: string - value corresponding to key or "" if key is non-valid """ if self.config_dict.has_key(key): return self.config_dict[key] else: (stdout, stderr) = RunExternal("condor_config_val %s" % key) if len(stdout) == 0: logging.warning("Unable to get any output from condor_config_val. Is key = %s correct?" % key) logging.warning("Stderr: %s" % stderr) self.config_dict[key] = stdout.strip() return stdout.strip()
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "self", ".", "config_dict", ".", "has_key", "(", "key", ")", ":", "return", "self", ".", "config_dict", "[", "key", "]", "else", ":", "(", "stdout", ",", "stderr", ")", "=", "RunExternal", "(",...
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/campus_factory/python-lib/campus_factory/ClusterStatus.py#L56-L71
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py
python
Node.get_build_scanner_path
(self, scanner)
return self.get_executor().get_build_scanner_path(scanner)
Fetch the appropriate scanner path for this node.
Fetch the appropriate scanner path for this node.
[ "Fetch", "the", "appropriate", "scanner", "path", "for", "this", "node", "." ]
def get_build_scanner_path(self, scanner): """Fetch the appropriate scanner path for this node.""" return self.get_executor().get_build_scanner_path(scanner)
[ "def", "get_build_scanner_path", "(", "self", ",", "scanner", ")", ":", "return", "self", ".", "get_executor", "(", ")", ".", "get_build_scanner_path", "(", "scanner", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/__init__.py#L644-L646
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py
python
TarFile.getnames
(self)
return [tarinfo.name for tarinfo in self.getmembers()]
Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers().
Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers().
[ "Return", "the", "members", "of", "the", "archive", "as", "a", "list", "of", "their", "names", ".", "It", "has", "the", "same", "order", "as", "the", "list", "returned", "by", "getmembers", "()", "." ]
def getnames(self): """Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers(). """ return [tarinfo.name for tarinfo in self.getmembers()]
[ "def", "getnames", "(", "self", ")", ":", "return", "[", "tarinfo", ".", "name", "for", "tarinfo", "in", "self", ".", "getmembers", "(", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L1767-L1771
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRtnFromFutureToBankByFuture
(self, RspTransferField)
期货发起期货资金转银行通知
期货发起期货资金转银行通知
[ "期货发起期货资金转银行通知" ]
def onRtnFromFutureToBankByFuture(self, RspTransferField): """期货发起期货资金转银行通知""" pass
[ "def", "onRtnFromFutureToBankByFuture", "(", "self", ",", "RspTransferField", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L479-L481
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/__init__.py
python
Pool
(processes=None, initializer=None, initargs=(), maxtasksperchild=None)
return Pool(processes, initializer, initargs, maxtasksperchild)
Returns a process pool object
Returns a process pool object
[ "Returns", "a", "process", "pool", "object" ]
def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None): ''' Returns a process pool object ''' from multiprocessing.pool import Pool return Pool(processes, initializer, initargs, maxtasksperchild)
[ "def", "Pool", "(", "processes", "=", "None", ",", "initializer", "=", "None", ",", "initargs", "=", "(", ")", ",", "maxtasksperchild", "=", "None", ")", ":", "from", "multiprocessing", ".", "pool", "import", "Pool", "return", "Pool", "(", "processes", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/__init__.py#L227-L232
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/generator_jit/gen_intrinsic_func.py
python
SignatureParser.create_lazy_ir_construction
(self, f, intrinsic, signature)
Create a lazy IR construction call for a given intrinsic, signature pair.
Create a lazy IR construction call for a given intrinsic, signature pair.
[ "Create", "a", "lazy", "IR", "construction", "call", "for", "a", "given", "intrinsic", "signature", "pair", "." ]
def create_lazy_ir_construction(self, f, intrinsic, signature): """Create a lazy IR construction call for a given intrinsic, signature pair.""" ret_type, params = self.split_signature(signature) mode = self.intrinsic_modes.get(intrinsic + signature) func_index = self.get_function_index((intrinsic, signature)) self.write(f, "if (llvm::Function *func = m_intrinsics[%d * 2 + return_derivs])\n" % func_index) self.indent += 1 self.write(f, "return func;\n") self.indent -= 1 mod_name = self.m_intrinsic_mods[intrinsic] if mod_name == "state": self.write(f, "if (m_use_user_state_module) {\n") self.indent += 1; self.write(f, "llvm::Function *func;\n") self.write(f, "if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE)\n") self.indent += 1 self.write(f, "func = m_code_gen.get_llvm_module()->getFunction(\"%s\");\n" % self.get_mangled_state_func_name(intrinsic, "State_core")) self.indent -= 1 self.write(f, "else\n") self.indent += 1 self.write(f, "func = m_code_gen.get_llvm_module()->getFunction(\"%s\");\n" % self.get_mangled_state_func_name(intrinsic, "State_environment")) self.indent -= 1 self.write(f, "if (func != NULL) {\n") self.indent += 1 self.write(f, "m_code_gen.create_context_data(func_def, return_derivs, func);\n") self.write(f, "return m_intrinsics[%d * 2 + return_derivs] = func;\n" % func_index) self.indent -= 1 self.write(f, "}\n") self.indent -= 1 self.write(f, "}\n") suffix = signature if suffix[-1] == '_': # no parameters suffix = suffix[:-1] self.write(f, "return m_intrinsics[%d * 2 + return_derivs] = create_%s_%s_%s(func_def, return_derivs);\n" % (func_index, mod_name, intrinsic, suffix))
[ "def", "create_lazy_ir_construction", "(", "self", ",", "f", ",", "intrinsic", ",", "signature", ")", ":", "ret_type", ",", "params", "=", "self", ".", "split_signature", "(", "signature", ")", "mode", "=", "self", ".", "intrinsic_modes", ".", "get", "(", ...
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/generator_jit/gen_intrinsic_func.py#L1072-L1117
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/build_tools/sdk_tools/third_party/fancy_urllib/__init__.py
python
can_validate_certs
()
Return True if we have the SSL package and can validate certificates.
Return True if we have the SSL package and can validate certificates.
[ "Return", "True", "if", "we", "have", "the", "SSL", "package", "and", "can", "validate", "certificates", "." ]
def can_validate_certs(): """Return True if we have the SSL package and can validate certificates.""" try: import ssl return True except ImportError: return False
[ "def", "can_validate_certs", "(", ")", ":", "try", ":", "import", "ssl", "return", "True", "except", "ImportError", ":", "return", "False" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/sdk_tools/third_party/fancy_urllib/__init__.py#L46-L52
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ListCtrl.SetColumn
(*args, **kwargs)
return _controls_.ListCtrl_SetColumn(*args, **kwargs)
SetColumn(self, int col, ListItem item) -> bool
SetColumn(self, int col, ListItem item) -> bool
[ "SetColumn", "(", "self", "int", "col", "ListItem", "item", ")", "-", ">", "bool" ]
def SetColumn(*args, **kwargs): """SetColumn(self, int col, ListItem item) -> bool""" return _controls_.ListCtrl_SetColumn(*args, **kwargs)
[ "def", "SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4472-L4474
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/applications/workbench/workbench/plotting/plotscriptgenerator/__init__.py
python
get_tick_commands
(ax, ax_object_var)
return ["{ax_obj}.{cmd}".format(ax_obj=ax_object_var, cmd=cmd) for cmd in tick_commands]
Get ax.tick_params commands for setting properties of tick marks and grid lines.
Get ax.tick_params commands for setting properties of tick marks and grid lines.
[ "Get", "ax", ".", "tick_params", "commands", "for", "setting", "properties", "of", "tick", "marks", "and", "grid", "lines", "." ]
def get_tick_commands(ax, ax_object_var): """Get ax.tick_params commands for setting properties of tick marks and grid lines.""" tick_commands = generate_tick_commands(ax) return ["{ax_obj}.{cmd}".format(ax_obj=ax_object_var, cmd=cmd) for cmd in tick_commands]
[ "def", "get_tick_commands", "(", "ax", ",", "ax_object_var", ")", ":", "tick_commands", "=", "generate_tick_commands", "(", "ax", ")", "return", "[", "\"{ax_obj}.{cmd}\"", ".", "format", "(", "ax_obj", "=", "ax_object_var", ",", "cmd", "=", "cmd", ")", "for", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/plotting/plotscriptgenerator/__init__.py#L192-L195
tpfister/caffe-heatmap
4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e
python/caffe/pycaffe.py
python
_Net_backward
(self, diffs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].diff for out in outputs}
Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict.
Backward pass: prepare diffs and run the net backward.
[ "Backward", "pass", ":", "prepare", "diffs", "and", "run", "the", "net", "backward", "." ]
def _Net_backward(self, diffs=None, start=None, end=None, **kwargs): """ Backward pass: prepare diffs and run the net backward. Parameters ---------- diffs : list of diffs to return in addition to bottom diffs. kwargs : Keys are output blob names and values are diff ndarrays. If None, top diffs are taken from forward loss. start : optional name of layer at which to begin the backward pass end : optional name of layer at which to finish the backward pass (inclusive) Returns ------- outs: {blob name: diff ndarray} dict. """ if diffs is None: diffs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = len(self.layers) - 1 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + diffs) else: end_ind = 0 outputs = set(self.inputs + diffs) if kwargs: if set(kwargs.keys()) != set(self.outputs): raise Exception('Top diff arguments do not match net outputs.') # Set top diffs according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for top, diff in kwargs.iteritems(): if diff.ndim != 4: raise Exception('{} diff is not 4-d'.format(top)) if diff.shape[0] != self.blobs[top].num: raise Exception('Diff is not batch sized') self.blobs[top].diff[...] = diff self._backward(start_ind, end_ind) # Unpack diffs to extract return {out: self.blobs[out].diff for out in outputs}
[ "def", "_Net_backward", "(", "self", ",", "diffs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "diffs", "is", "None", ":", "diffs", "=", "[", "]", "if", "start", "is", "not", "None", ...
https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/python/caffe/pycaffe.py#L111-L158
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/property_set.py
python
PropertySet.get_properties
(self, feature)
return result
Returns all contained properties associated with 'feature
Returns all contained properties associated with 'feature
[ "Returns", "all", "contained", "properties", "associated", "with", "feature" ]
def get_properties(self, feature): """Returns all contained properties associated with 'feature'""" if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) result = [] for p in self.all_: if p.feature == feature: result.append(p) return result
[ "def", "get_properties", "(", "self", ",", "feature", ")", ":", "if", "not", "isinstance", "(", "feature", ",", "b2", ".", "build", ".", "feature", ".", "Feature", ")", ":", "feature", "=", "b2", ".", "build", ".", "feature", ".", "get", "(", "featur...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/property_set.py#L477-L487
stepcode/stepcode
2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39
src/exp2python/python/SCL/ConstructedDataTypes.py
python
SELECT.get_allowed_basic_types
(self)
return b
if a select contains some subselect, goes down through the different sublayers until there is no more
if a select contains some subselect, goes down through the different sublayers until there is no more
[ "if", "a", "select", "contains", "some", "subselect", "goes", "down", "through", "the", "different", "sublayers", "until", "there", "is", "no", "more" ]
def get_allowed_basic_types(self): ''' if a select contains some subselect, goes down through the different sublayers until there is no more ''' b = [] _auth_types = self.get_allowed_types() for _auth_type in _auth_types: if isinstance(_auth_type,SELECT) or isinstance(_auth_type,ENUMERATION): h = _auth_type.get_allowed_types() b.extend(h) else: b = _auth_types return b
[ "def", "get_allowed_basic_types", "(", "self", ")", ":", "b", "=", "[", "]", "_auth_types", "=", "self", ".", "get_allowed_types", "(", ")", "for", "_auth_type", "in", "_auth_types", ":", "if", "isinstance", "(", "_auth_type", ",", "SELECT", ")", "or", "is...
https://github.com/stepcode/stepcode/blob/2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39/src/exp2python/python/SCL/ConstructedDataTypes.py#L85-L96
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite_e.py
python
hermevander2d
(x, y, deg)
return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg)
Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the HermiteE polynomials. If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D HermiteE series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- hermevander, hermevander3d, hermeval2d, hermeval3d Notes ----- .. versionadded:: 1.7.0
Pseudo-Vandermonde matrix of given degrees.
[ "Pseudo", "-", "Vandermonde", "matrix", "of", "given", "degrees", "." ]
def hermevander2d(x, y, deg): """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the HermiteE polynomials. If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D HermiteE series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- hermevander, hermevander3d, hermeval2d, hermeval3d Notes ----- .. versionadded:: 1.7.0 """ return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg)
[ "def", "hermevander2d", "(", "x", ",", "y", ",", "deg", ")", ":", "return", "pu", ".", "_vander_nd_flat", "(", "(", "hermevander", ",", "hermevander", ")", ",", "(", "x", ",", "y", ")", ",", "deg", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite_e.py#L1139-L1189
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
toolkit/components/telemetry/histogram_tools.py
python
Histogram.keyed
(self)
return self._keyed
Returns True if this a keyed histogram, false otherwise.
Returns True if this a keyed histogram, false otherwise.
[ "Returns", "True", "if", "this", "a", "keyed", "histogram", "false", "otherwise", "." ]
def keyed(self): """Returns True if this a keyed histogram, false otherwise.""" return self._keyed
[ "def", "keyed", "(", "self", ")", ":", "return", "self", ".", "_keyed" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/components/telemetry/histogram_tools.py#L134-L136
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_trackers.py
python
rectangleTracker.p2
(self)
return Vector(self.coords.point.getValues()[3].getValue())
Get the second point (on u axis) of the rectangle.
Get the second point (on u axis) of the rectangle.
[ "Get", "the", "second", "point", "(", "on", "u", "axis", ")", "of", "the", "rectangle", "." ]
def p2(self): """Get the second point (on u axis) of the rectangle.""" return Vector(self.coords.point.getValues()[3].getValue())
[ "def", "p2", "(", "self", ")", ":", "return", "Vector", "(", "self", ".", "coords", ".", "point", ".", "getValues", "(", ")", "[", "3", "]", ".", "getValue", "(", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trackers.py#L277-L279
alexgkendall/caffe-segnet
344c113bf1832886f1cbe9f33ffe28a3beeaf412
scripts/cpp_lint.py
python
_BlockInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text after the closing brace.
[ "Run", "checks", "that", "applies", "to", "text", "after", "the", "closing", "brace", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/scripts/cpp_lint.py#L1778-L1789
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucket.py
python
Bucket.configure_lifecycle
(self, lifecycle_config, headers=None)
Configure lifecycle for this bucket. :type lifecycle_config: :class:`boto.s3.lifecycle.Lifecycle` :param lifecycle_config: The lifecycle configuration you want to configure for this bucket.
Configure lifecycle for this bucket.
[ "Configure", "lifecycle", "for", "this", "bucket", "." ]
def configure_lifecycle(self, lifecycle_config, headers=None): """ Configure lifecycle for this bucket. :type lifecycle_config: :class:`boto.s3.lifecycle.Lifecycle` :param lifecycle_config: The lifecycle configuration you want to configure for this bucket. """ xml = lifecycle_config.to_xml() #xml = xml.encode('utf-8') fp = StringIO(xml) md5 = boto.utils.compute_md5(fp) if headers is None: headers = {} headers['Content-MD5'] = md5[1] headers['Content-Type'] = 'text/xml' response = self.connection.make_request('PUT', self.name, data=fp.getvalue(), query_args='lifecycle', headers=headers) body = response.read() if response.status == 200: return True else: raise self.connection.provider.storage_response_error( response.status, response.reason, body)
[ "def", "configure_lifecycle", "(", "self", ",", "lifecycle_config", ",", "headers", "=", "None", ")", ":", "xml", "=", "lifecycle_config", ".", "to_xml", "(", ")", "#xml = xml.encode('utf-8')", "fp", "=", "StringIO", "(", "xml", ")", "md5", "=", "boto", ".",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucket.py#L1339-L1364
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py
python
Bernoulli.q
(self)
return self._q
1-p.
1-p.
[ "1", "-", "p", "." ]
def q(self): """1-p.""" return self._q
[ "def", "q", "(", "self", ")", ":", "return", "self", ".", "_q" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py#L129-L131
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
build/plugins/_xsyn_includes.py
python
get_include_callback
()
return get_include
.. function: get_include_callback returns function that processes each DOM element to get xsyn include from it, and it's aware of directory with all the xsyns. :param xsyn_dir directory with xsyns.
.. function: get_include_callback returns function that processes each DOM element to get xsyn include from it, and it's aware of directory with all the xsyns.
[ "..", "function", ":", "get_include_callback", "returns", "function", "that", "processes", "each", "DOM", "element", "to", "get", "xsyn", "include", "from", "it", "and", "it", "s", "aware", "of", "directory", "with", "all", "the", "xsyns", "." ]
def get_include_callback(): """ .. function: get_include_callback returns function that processes each DOM element to get xsyn include from it, and it's aware of directory with all the xsyns. :param xsyn_dir directory with xsyns. """ def get_include(element): """ .. function: get_include returns list of includes from this DOM element. :param element DOM element. """ res = [] if element.nodeType == element.ELEMENT_NODE and element.nodeName == "parse:include": attrs = element.attributes for i in xrange(attrs.length): attr = attrs.item(i) if attr.nodeName == "path": include_filename = attr.nodeValue res.append(include_filename) return res return get_include
[ "def", "get_include_callback", "(", ")", ":", "def", "get_include", "(", "element", ")", ":", "\"\"\"\n .. function: get_include returns list of includes from this DOM element.\n\n :param element DOM element.\n \"\"\"", "res", "=", "[", "]", "if",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/build/plugins/_xsyn_includes.py#L1-L23
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
pack
(values, axis=0, name="pack")
return gen_array_ops._pack(values, axis=axis, name=name)
Packs a list of rank-`R` tensors into one rank-`(R+1)` tensor. Packs the list of tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the `axis` dimension. Given a list of length `N` of tensors of shape `(A, B, C)`; if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. Etc. For example: ```prettyprint # 'x' is [1, 4] # 'y' is [2, 5] # 'z' is [3, 6] pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]] ``` This is the opposite of unpack. The numpy equivalent is tf.pack([x, y, z]) = np.asarray([x, y, z]) Args: values: A list of `Tensor` objects with the same shape and type. axis: An `int`. The axis to pack along. Defaults to the first dimension. Supports negative indexes. name: A name for this operation (optional). Returns: output: A packed `Tensor` with the same type as `values`. Raises: ValueError: If `axis` is out of the range [-(R+1), R+1).
Packs a list of rank-`R` tensors into one rank-`(R+1)` tensor.
[ "Packs", "a", "list", "of", "rank", "-", "R", "tensors", "into", "one", "rank", "-", "(", "R", "+", "1", ")", "tensor", "." ]
def pack(values, axis=0, name="pack"): """Packs a list of rank-`R` tensors into one rank-`(R+1)` tensor. Packs the list of tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the `axis` dimension. Given a list of length `N` of tensors of shape `(A, B, C)`; if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. Etc. For example: ```prettyprint # 'x' is [1, 4] # 'y' is [2, 5] # 'z' is [3, 6] pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]] ``` This is the opposite of unpack. The numpy equivalent is tf.pack([x, y, z]) = np.asarray([x, y, z]) Args: values: A list of `Tensor` objects with the same shape and type. axis: An `int`. The axis to pack along. Defaults to the first dimension. Supports negative indexes. name: A name for this operation (optional). Returns: output: A packed `Tensor` with the same type as `values`. Raises: ValueError: If `axis` is out of the range [-(R+1), R+1). """ if axis == 0: try: # If the input is a constant list, it can be converted to a constant op return ops.convert_to_tensor(values, name=name) except (TypeError, ValueError): pass # Input list contains non-constant tensors value_shape = ops.convert_to_tensor(values[0], name=name).get_shape() if value_shape.ndims is not None: expanded_num_dims = value_shape.ndims + 1 if axis < -expanded_num_dims or axis >= expanded_num_dims: raise ValueError("axis = %d not in [%d, %d)" % (axis, -expanded_num_dims, expanded_num_dims)) return gen_array_ops._pack(values, axis=axis, name=name)
[ "def", "pack", "(", "values", ",", "axis", "=", "0", ",", "name", "=", "\"pack\"", ")", ":", "if", "axis", "==", "0", ":", "try", ":", "# If the input is a constant list, it can be converted to a constant op", "return", "ops", ".", "convert_to_tensor", "(", "val...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L436-L487
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/descriptor.py
python
FieldDescriptor.ProtoTypeToCppProtoType
(proto_type)
Converts from a Python proto type to a C++ Proto Type. The Python ProtocolBuffer classes specify both the 'Python' datatype and the 'C++' datatype - and they're not the same. This helper method should translate from one to another. Args: proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) Returns: int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. Raises: TypeTransformationError: when the Python proto type isn't known.
Converts from a Python proto type to a C++ Proto Type.
[ "Converts", "from", "a", "Python", "proto", "type", "to", "a", "C", "++", "Proto", "Type", "." ]
def ProtoTypeToCppProtoType(proto_type): """Converts from a Python proto type to a C++ Proto Type. The Python ProtocolBuffer classes specify both the 'Python' datatype and the 'C++' datatype - and they're not the same. This helper method should translate from one to another. Args: proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) Returns: int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. Raises: TypeTransformationError: when the Python proto type isn't known. """ try: return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] except KeyError: raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
[ "def", "ProtoTypeToCppProtoType", "(", "proto_type", ")", ":", "try", ":", "return", "FieldDescriptor", ".", "_PYTHON_TO_CPP_PROTO_TYPE_MAP", "[", "proto_type", "]", "except", "KeyError", ":", "raise", "TypeTransformationError", "(", "'Unknown proto_type: %s'", "%", "pr...
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/descriptor.py#L621-L638
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
BookCtrlBase.IsVertical
(*args, **kwargs)
return _core_.BookCtrlBase_IsVertical(*args, **kwargs)
IsVertical(self) -> bool
IsVertical(self) -> bool
[ "IsVertical", "(", "self", ")", "-", ">", "bool" ]
def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _core_.BookCtrlBase_IsVertical(*args, **kwargs)
[ "def", "IsVertical", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_IsVertical", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13582-L13584
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
AABBPoser.__init__
(self)
r""" __init__(AABBPoser self) -> AABBPoser
r""" __init__(AABBPoser self) -> AABBPoser
[ "r", "__init__", "(", "AABBPoser", "self", ")", "-", ">", "AABBPoser" ]
def __init__(self): r""" __init__(AABBPoser self) -> AABBPoser """ _robotsim.AABBPoser_swiginit(self, _robotsim.new_AABBPoser())
[ "def", "__init__", "(", "self", ")", ":", "_robotsim", ".", "AABBPoser_swiginit", "(", "self", ",", "_robotsim", ".", "new_AABBPoser", "(", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3719-L3725
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGrid.SetSortFunction
(*args, **kwargs)
return _propgrid.PropertyGrid_SetSortFunction(*args, **kwargs)
SetSortFunction(self, PGSortCallback sortFunction)
SetSortFunction(self, PGSortCallback sortFunction)
[ "SetSortFunction", "(", "self", "PGSortCallback", "sortFunction", ")" ]
def SetSortFunction(*args, **kwargs): """SetSortFunction(self, PGSortCallback sortFunction)""" return _propgrid.PropertyGrid_SetSortFunction(*args, **kwargs)
[ "def", "SetSortFunction", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_SetSortFunction", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2279-L2281
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/nvmpic.py
python
NvmAccessProviderCmsisDapPic.read
(self, memory_info, offset, numbytes)
return []
Read the memory :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset in the memory type :param numbytes: number of bytes to read :return: array of bytes read
Read the memory
[ "Read", "the", "memory" ]
def read(self, memory_info, offset, numbytes): """ Read the memory :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset in the memory type :param numbytes: number of bytes to read :return: array of bytes read """ mem_name = memory_info[DeviceInfoKeys.NAME] offset += memory_info[DeviceMemoryInfoKeys.ADDRESS] if mem_name in [MemoryNames.FLASH, MemoryNames.USER_ID, MemoryNames.ICD]: mem = self.pic.read_flash_memory(offset, numbytes) return mem if mem_name == MemoryNames.CONFIG_WORD: mem = self.pic.read_config_memory(offset, numbytes) return mem if mem_name == MemoryNames.EEPROM: mem = self.pic.read_eeprom_memory(offset, numbytes) return mem self.logger.error("Unsupported memtype!") return []
[ "def", "read", "(", "self", ",", "memory_info", ",", "offset", ",", "numbytes", ")", ":", "mem_name", "=", "memory_info", "[", "DeviceInfoKeys", ".", "NAME", "]", "offset", "+=", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "ADDRESS", "]", "if", "mem_nam...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmpic.py#L71-L92
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/quant.py
python
DenseQuant.extend_repr
(self)
return s
A pretty print for Dense layer.
A pretty print for Dense layer.
[ "A", "pretty", "print", "for", "Dense", "layer", "." ]
def extend_repr(self): """A pretty print for Dense layer.""" s = 'in_channels={}, out_channels={}, weight={}, has_bias={}'.format( self.in_channels, self.out_channels, self.weight, self.has_bias) if self.has_bias: s += ', bias={}'.format(self.bias) if self.activation_flag: s += ', activation={}'.format(self.activation) return s
[ "def", "extend_repr", "(", "self", ")", ":", "s", "=", "'in_channels={}, out_channels={}, weight={}, has_bias={}'", ".", "format", "(", "self", ".", "in_channels", ",", "self", ".", "out_channels", ",", "self", ".", "weight", ",", "self", ".", "has_bias", ")", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/quant.py#L1478-L1486
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/constraint_solver/samples/tsp_cities.py
python
main
()
Entry point of the program.
Entry point of the program.
[ "Entry", "point", "of", "the", "program", "." ]
def main(): """Entry point of the program.""" # Instantiate the data problem. # [START data] data = create_data_model() # [END data] # Create the routing index manager. # [START index_manager] manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) # [END index_manager] # Create Routing Model. # [START routing_model] routing = pywrapcp.RoutingModel(manager) # [END routing_model] # [START transit_callback] def distance_callback(from_index, to_index): """Returns the distance between the two nodes.""" # Convert from routing variable Index to distance matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['distance_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) # [END transit_callback] # Define cost of each arc. # [START arc_cost] routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # [END arc_cost] # Setting first solution heuristic. # [START parameters] search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # [END parameters] # Solve the problem. # [START solve] solution = routing.SolveWithParameters(search_parameters) # [END solve] # Print solution on console. # [START print_solution] if solution: print_solution(manager, routing, solution)
[ "def", "main", "(", ")", ":", "# Instantiate the data problem.", "# [START data]", "data", "=", "create_data_model", "(", ")", "# [END data]", "# Create the routing index manager.", "# [START index_manager]", "manager", "=", "pywrapcp", ".", "RoutingIndexManager", "(", "len...
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/constraint_solver/samples/tsp_cities.py#L66-L116
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/type.py
python
register
(type, suffixes = [], base_type = None)
Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string
Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string
[ "Registers", "a", "target", "type", "possibly", "derived", "from", "a", "base", "-", "type", ".", "If", "suffixes", "are", "provided", "they", "list", "all", "the", "suffixes", "that", "mean", "a", "file", "is", "of", "type", ".", "Also", "the", "first",...
def register (type, suffixes = [], base_type = None): """ Registers a target type, possibly derived from a 'base-type'. If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'. Also, the first element gives the suffix to be used when constructing and object of 'type'. type: a string suffixes: None or a sequence of strings base_type: None or a string """ # Type names cannot contain hyphens, because when used as # feature-values they will be interpreted as composite features # which need to be decomposed. if __re_hyphen.search (type): raise BaseException ('type name "%s" contains a hyphen' % type) # it's possible for a type to be registered with a # base type that hasn't been registered yet. in the # check for base_type below and the following calls to setdefault() # the key `type` will be added to __types. When the base type # actually gets registered, it would fail after the simple check # of "type in __types"; thus the check for "'base' in __types[type]" if type in __types and 'base' in __types[type]: raise BaseException ('Type "%s" is already registered.' % type) entry = __types.setdefault(type, {}) entry['base'] = base_type entry.setdefault('derived', []) entry.setdefault('scanner', None) if base_type: __types.setdefault(base_type, {}).setdefault('derived', []).append(type) if len (suffixes) > 0: # Generated targets of 'type' will use the first of 'suffixes' # (this may be overriden) set_generated_target_suffix (type, [], suffixes [0]) # Specify mapping from suffixes to type register_suffixes (suffixes, type) feature.extend('target-type', [type]) feature.extend('main-target-type', [type]) feature.extend('base-target-type', [type]) if base_type: feature.compose ('<target-type>' + type, [replace_grist (base_type, '<base-target-type>')]) feature.compose ('<base-target-type>' + type, ['<base-target-type>' + base_type]) import b2.build.generators as generators # Adding a new derived type affects generator selection so we need to # make the generator selection module update any of its cached # information related to a new derived type being defined. generators.update_cached_information_with_a_new_type(type) # FIXME: resolving recursive dependency. from b2.manager import get_manager get_manager().projects().project_rules().add_rule_for_type(type)
[ "def", "register", "(", "type", ",", "suffixes", "=", "[", "]", ",", "base_type", "=", "None", ")", ":", "# Type names cannot contain hyphens, because when used as", "# feature-values they will be interpreted as composite features", "# which need to be decomposed.", "if", "__re...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/type.py#L59-L115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlWinParser.GetContainer
(*args, **kwargs)
return _html.HtmlWinParser_GetContainer(*args, **kwargs)
GetContainer(self) -> HtmlContainerCell
GetContainer(self) -> HtmlContainerCell
[ "GetContainer", "(", "self", ")", "-", ">", "HtmlContainerCell" ]
def GetContainer(*args, **kwargs): """GetContainer(self) -> HtmlContainerCell""" return _html.HtmlWinParser_GetContainer(*args, **kwargs)
[ "def", "GetContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWinParser_GetContainer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L272-L274
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/categorical.py
python
Categorical.T
(self)
return self
Return transposed numpy array.
Return transposed numpy array.
[ "Return", "transposed", "numpy", "array", "." ]
def T(self): """ Return transposed numpy array. """ return self
[ "def", "T", "(", "self", ")", ":", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L1330-L1334
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/descriptor.py
python
_NestedDescriptorBase.CopyToProto
(self, proto)
Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldn't be serialized, due to to few constructor arguments.
Copies this to the matching proto in descriptor_pb2.
[ "Copies", "this", "to", "the", "matching", "proto", "in", "descriptor_pb2", "." ]
def CopyToProto(self, proto): """Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldn't be serialized, due to to few constructor arguments. """ if (self.file is not None and self._serialized_start is not None and self._serialized_end is not None): proto.ParseFromString(self.file.serialized_pb[ self._serialized_start:self._serialized_end]) else: raise Error('Descriptor does not contain serialization.')
[ "def", "CopyToProto", "(", "self", ",", "proto", ")", ":", "if", "(", "self", ".", "file", "is", "not", "None", "and", "self", ".", "_serialized_start", "is", "not", "None", "and", "self", ".", "_serialized_end", "is", "not", "None", ")", ":", "proto",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/descriptor.py#L223-L239
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Solver.add
(self, *args)
Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2]
Assert constraints into the solver.
[ "Assert", "constraints", "into", "the", "solver", "." ]
def add(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args)
[ "def", "add", "(", "self", ",", "*", "args", ")", ":", "self", ".", "assert_exprs", "(", "*", "args", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L6958-L6967
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/buttonpanel.py
python
ButtonPanel.SetUseHelp
(self, useHelp=True)
Sets whether or not short and long help strings should be displayed as tooltips and :class:`StatusBar` items respectively. :param bool `useHelp`: ``True`` to display short and long help strings as tooltips and :class:`StatusBar` items respectively, ``False`` otherwise.
Sets whether or not short and long help strings should be displayed as tooltips and :class:`StatusBar` items respectively.
[ "Sets", "whether", "or", "not", "short", "and", "long", "help", "strings", "should", "be", "displayed", "as", "tooltips", "and", ":", "class", ":", "StatusBar", "items", "respectively", "." ]
def SetUseHelp(self, useHelp=True): """ Sets whether or not short and long help strings should be displayed as tooltips and :class:`StatusBar` items respectively. :param bool `useHelp`: ``True`` to display short and long help strings as tooltips and :class:`StatusBar` items respectively, ``False`` otherwise. """ self._useHelp = useHelp
[ "def", "SetUseHelp", "(", "self", ",", "useHelp", "=", "True", ")", ":", "self", ".", "_useHelp", "=", "useHelp" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L2676-L2685
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/tools/release/releases.py
python
BuildRevisionRanges
(cr_releases)
return dict((hsh, ", ".join(ran)) for hsh, ran in range_lists.iteritems())
Returns a mapping of v8 revision -> chromium ranges. The ranges are comma-separated, each range has the form R1:R2. The newest entry is the only one of the form R1, as there is no end range. cr_releases is a list of [cr_rev, v8_hsh] reverse-sorted by cr_rev. cr_rev either refers to a chromium commit position or a chromium branch number.
Returns a mapping of v8 revision -> chromium ranges. The ranges are comma-separated, each range has the form R1:R2. The newest entry is the only one of the form R1, as there is no end range.
[ "Returns", "a", "mapping", "of", "v8", "revision", "-", ">", "chromium", "ranges", ".", "The", "ranges", "are", "comma", "-", "separated", "each", "range", "has", "the", "form", "R1", ":", "R2", ".", "The", "newest", "entry", "is", "the", "only", "one"...
def BuildRevisionRanges(cr_releases): """Returns a mapping of v8 revision -> chromium ranges. The ranges are comma-separated, each range has the form R1:R2. The newest entry is the only one of the form R1, as there is no end range. cr_releases is a list of [cr_rev, v8_hsh] reverse-sorted by cr_rev. cr_rev either refers to a chromium commit position or a chromium branch number. """ range_lists = {} cr_releases = FilterDuplicatesAndReverse(cr_releases) # Visit pairs of cr releases from oldest to newest. for cr_from, cr_to in itertools.izip( cr_releases, itertools.islice(cr_releases, 1, None)): # Assume the chromium revisions are all different. assert cr_from[0] != cr_to[0] ran = "%s:%d" % (cr_from[0], int(cr_to[0]) - 1) # Collect the ranges in lists per revision. range_lists.setdefault(cr_from[1], []).append(ran) # Add the newest revision. if cr_releases: range_lists.setdefault(cr_releases[-1][1], []).append(cr_releases[-1][0]) # Stringify and comma-separate the range lists. return dict((hsh, ", ".join(ran)) for hsh, ran in range_lists.iteritems())
[ "def", "BuildRevisionRanges", "(", "cr_releases", ")", ":", "range_lists", "=", "{", "}", "cr_releases", "=", "FilterDuplicatesAndReverse", "(", "cr_releases", ")", "# Visit pairs of cr releases from oldest to newest.", "for", "cr_from", ",", "cr_to", "in", "itertools", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/tools/release/releases.py#L86-L115
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py
python
MergeManifests._IsDuplicate
(self, node_to_copy, node)
return False
Is element a duplicate?
Is element a duplicate?
[ "Is", "element", "a", "duplicate?" ]
def _IsDuplicate(self, node_to_copy, node): """Is element a duplicate?""" for merger_node in self._merger_dom.getElementsByTagName(node_to_copy): if (merger_node.getAttribute(self._ANDROID_NAME) == node.getAttribute(self._ANDROID_NAME)): return True return False
[ "def", "_IsDuplicate", "(", "self", ",", "node_to_copy", ",", "node", ")", ":", "for", "merger_node", "in", "self", ".", "_merger_dom", ".", "getElementsByTagName", "(", "node_to_copy", ")", ":", "if", "(", "merger_node", ".", "getAttribute", "(", "self", "....
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py#L212-L218
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/linalg_ops_impl.py
python
eye
(num_rows, num_columns=None, batch_shape=None, dtype=dtypes.float32, name=None)
Construct an identity matrix, or a batch of matrices. See `linalg_ops.eye`.
Construct an identity matrix, or a batch of matrices.
[ "Construct", "an", "identity", "matrix", "or", "a", "batch", "of", "matrices", "." ]
def eye(num_rows, num_columns=None, batch_shape=None, dtype=dtypes.float32, name=None): """Construct an identity matrix, or a batch of matrices. See `linalg_ops.eye`. """ with ops.name_scope( name, default_name='eye', values=[num_rows, num_columns, batch_shape]): is_square = num_columns is None batch_shape = [] if batch_shape is None else batch_shape num_columns = num_rows if num_columns is None else num_columns # We cannot statically infer what the diagonal size should be: if (isinstance(num_rows, ops.Tensor) or isinstance(num_columns, ops.Tensor)): diag_size = math_ops.minimum(num_rows, num_columns) else: # We can statically infer the diagonal size, and whether it is square. if not isinstance(num_rows, compat.integral_types) or not isinstance( num_columns, compat.integral_types): raise TypeError( 'Arguments `num_rows` and `num_columns` must be positive integer ' f'values. Received: num_rows={num_rows}, num_columns={num_columns}') is_square = num_rows == num_columns diag_size = np.minimum(num_rows, num_columns) # We can not statically infer the shape of the tensor. if isinstance(batch_shape, ops.Tensor) or isinstance(diag_size, ops.Tensor): batch_shape = ops.convert_to_tensor( batch_shape, name='shape', dtype=dtypes.int32) diag_shape = array_ops.concat((batch_shape, [diag_size]), axis=0) if not is_square: shape = array_ops.concat((batch_shape, [num_rows, num_columns]), axis=0) # We can statically infer everything. else: batch_shape = list(batch_shape) diag_shape = batch_shape + [diag_size] if not is_square: shape = batch_shape + [num_rows, num_columns] diag_ones = array_ops.ones(diag_shape, dtype=dtype) if is_square: return array_ops.matrix_diag(diag_ones) else: zero_matrix = array_ops.zeros(shape, dtype=dtype) return array_ops.matrix_set_diag(zero_matrix, diag_ones)
[ "def", "eye", "(", "num_rows", ",", "num_columns", "=", "None", ",", "batch_shape", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "default_name", "=", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg_ops_impl.py#L29-L77
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBPlatform.Run
(self, shell_command)
return _lldb.SBPlatform_Run(self, shell_command)
Run(SBPlatform self, SBPlatformShellCommand shell_command) -> SBError
Run(SBPlatform self, SBPlatformShellCommand shell_command) -> SBError
[ "Run", "(", "SBPlatform", "self", "SBPlatformShellCommand", "shell_command", ")", "-", ">", "SBError" ]
def Run(self, shell_command): """Run(SBPlatform self, SBPlatformShellCommand shell_command) -> SBError""" return _lldb.SBPlatform_Run(self, shell_command)
[ "def", "Run", "(", "self", ",", "shell_command", ")", ":", "return", "_lldb", ".", "SBPlatform_Run", "(", "self", ",", "shell_command", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8196-L8198
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/optimize.py
python
_minimize_scalar_bounded
(func, bounds, args=(), xatol=1e-5, maxiter=500, disp=0, **unknown_options)
return result
Options ------- maxiter : int Maximum number of iterations to perform. disp: int, optional If non-zero, print messages. 0 : no message printing. 1 : non-convergence notification messages only. 2 : print a message on convergence too. 3 : print iteration results. xatol : float Absolute error in solution `xopt` acceptable for convergence.
Options ------- maxiter : int Maximum number of iterations to perform. disp: int, optional If non-zero, print messages. 0 : no message printing. 1 : non-convergence notification messages only. 2 : print a message on convergence too. 3 : print iteration results. xatol : float Absolute error in solution `xopt` acceptable for convergence.
[ "Options", "-------", "maxiter", ":", "int", "Maximum", "number", "of", "iterations", "to", "perform", ".", "disp", ":", "int", "optional", "If", "non", "-", "zero", "print", "messages", ".", "0", ":", "no", "message", "printing", ".", "1", ":", "non", ...
def _minimize_scalar_bounded(func, bounds, args=(), xatol=1e-5, maxiter=500, disp=0, **unknown_options): """ Options ------- maxiter : int Maximum number of iterations to perform. disp: int, optional If non-zero, print messages. 0 : no message printing. 1 : non-convergence notification messages only. 2 : print a message on convergence too. 3 : print iteration results. xatol : float Absolute error in solution `xopt` acceptable for convergence. """ _check_unknown_options(unknown_options) maxfun = maxiter # Test bounds are of correct form if len(bounds) != 2: raise ValueError('bounds must have two elements.') x1, x2 = bounds if not (is_array_scalar(x1) and is_array_scalar(x2)): raise ValueError("Optimisation bounds must be scalars" " or array scalars.") if x1 > x2: raise ValueError("The lower bound exceeds the upper bound.") flag = 0 header = ' Func-count x f(x) Procedure' step = ' initial' sqrt_eps = sqrt(2.2e-16) golden_mean = 0.5 * (3.0 - sqrt(5.0)) a, b = x1, x2 fulc = a + golden_mean * (b - a) nfc, xf = fulc, fulc rat = e = 0.0 x = xf fx = func(x, *args) num = 1 fmin_data = (1, xf, fx) ffulc = fnfc = fx xm = 0.5 * (a + b) tol1 = sqrt_eps * numpy.abs(xf) + xatol / 3.0 tol2 = 2.0 * tol1 if disp > 2: print(" ") print(header) print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,))) while (numpy.abs(xf - xm) > (tol2 - 0.5 * (b - a))): golden = 1 # Check for parabolic fit if numpy.abs(e) > tol1: golden = 0 r = (xf - nfc) * (fx - ffulc) q = (xf - fulc) * (fx - fnfc) p = (xf - fulc) * q - (xf - nfc) * r q = 2.0 * (q - r) if q > 0.0: p = -p q = numpy.abs(q) r = e e = rat # Check for acceptability of parabola if ((numpy.abs(p) < numpy.abs(0.5*q*r)) and (p > q*(a - xf)) and (p < q * (b - xf))): rat = (p + 0.0) / q x = xf + rat step = ' parabolic' if ((x - a) < tol2) or ((b - x) < tol2): si = numpy.sign(xm - xf) + ((xm - xf) == 0) rat = tol1 * si else: # do a golden section step golden = 1 if golden: # Do a golden-section step if xf >= xm: e = a - xf else: e = b - xf rat = golden_mean*e step = ' golden' si = numpy.sign(rat) + (rat == 0) x = xf + si * numpy.max([numpy.abs(rat), tol1]) fu = func(x, *args) num += 1 fmin_data = (num, x, fu) if disp > 2: print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,))) if fu <= fx: if x >= xf: a = xf else: b = xf fulc, ffulc = nfc, fnfc nfc, fnfc = xf, fx xf, fx = x, fu else: if x < xf: a = x else: b = x if (fu <= fnfc) or (nfc == xf): fulc, ffulc = nfc, fnfc nfc, fnfc = x, fu elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc): fulc, ffulc = x, fu xm = 0.5 * (a + b) tol1 = sqrt_eps * numpy.abs(xf) + xatol / 3.0 tol2 = 2.0 * tol1 if num >= maxfun: flag = 1 break fval = fx if disp > 0: _endprint(x, flag, fval, maxfun, xatol, disp) result = OptimizeResult(fun=fval, status=flag, success=(flag == 0), message={0: 'Solution found.', 1: 'Maximum number of function calls ' 'reached.'}.get(flag, ''), x=xf, nfev=num) return result
[ "def", "_minimize_scalar_bounded", "(", "func", ",", "bounds", ",", "args", "=", "(", ")", ",", "xatol", "=", "1e-5", ",", "maxiter", "=", "500", ",", "disp", "=", "0", ",", "*", "*", "unknown_options", ")", ":", "_check_unknown_options", "(", "unknown_o...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/optimize.py#L1706-L1843
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_basic.py
python
Shape.GetEventHandler
(self)
return self._eventHandler
Return the event handler for this shape.
Return the event handler for this shape.
[ "Return", "the", "event", "handler", "for", "this", "shape", "." ]
def GetEventHandler(self): """Return the event handler for this shape.""" return self._eventHandler
[ "def", "GetEventHandler", "(", "self", ")", ":", "return", "self", ".", "_eventHandler" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1938-L1940
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/mac/find_sdk.py
python
parse_version
(version_str)
return map(int, re.findall(r'(\d+)', version_str))
10.6' => [10, 6]
10.6' => [10, 6]
[ "10", ".", "6", "=", ">", "[", "10", "6", "]" ]
def parse_version(version_str): """'10.6' => [10, 6]""" return map(int, re.findall(r'(\d+)', version_str))
[ "def", "parse_version", "(", "version_str", ")", ":", "return", "map", "(", "int", ",", "re", ".", "findall", "(", "r'(\\d+)'", ",", "version_str", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/mac/find_sdk.py#L24-L26
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/play_services/update.py
python
_CheckLicenseAgreement
(expected_license_path, actual_license_path, version_number)
return raw_input('> ') in ('Y', 'y')
Checks that the new license is the one already accepted by the user. If it isn't, it prompts the user to accept it. Returns whether the expected license has been accepted.
Checks that the new license is the one already accepted by the user. If it isn't, it prompts the user to accept it. Returns whether the expected license has been accepted.
[ "Checks", "that", "the", "new", "license", "is", "the", "one", "already", "accepted", "by", "the", "user", ".", "If", "it", "isn", "t", "it", "prompts", "the", "user", "to", "accept", "it", ".", "Returns", "whether", "the", "expected", "license", "has", ...
def _CheckLicenseAgreement(expected_license_path, actual_license_path, version_number): ''' Checks that the new license is the one already accepted by the user. If it isn't, it prompts the user to accept it. Returns whether the expected license has been accepted. ''' if utils.FileEquals(expected_license_path, actual_license_path): return True with open(expected_license_path) as license_file: # Uses plain print rather than logging to make sure this is not formatted # by the logger. print ('Updating the Google Play services SDK to ' 'version %d.' % version_number) # The output is buffered when running as part of gclient hooks. We split # the text here and flush is explicitly to avoid having part of it dropped # out. # Note: text contains *escaped* new lines, so we split by '\\n', not '\n'. for license_part in license_file.read().split('\\n'): print license_part sys.stdout.flush() # Need to put the prompt on a separate line otherwise the gclient hook buffer # only prints it after we received an input. print 'Do you accept the license? [y/n]: ' sys.stdout.flush() return raw_input('> ') in ('Y', 'y')
[ "def", "_CheckLicenseAgreement", "(", "expected_license_path", ",", "actual_license_path", ",", "version_number", ")", ":", "if", "utils", ".", "FileEquals", "(", "expected_license_path", ",", "actual_license_path", ")", ":", "return", "True", "with", "open", "(", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/play_services/update.py#L376-L405
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/premises/model_final_cnn_2x.py
python
Model.conjecture_embedding
(self, conjectures)
return self.make_embedding(conjectures)
Compute the embedding for each of the conjectures.
Compute the embedding for each of the conjectures.
[ "Compute", "the", "embedding", "for", "each", "of", "the", "conjectures", "." ]
def conjecture_embedding(self, conjectures): """Compute the embedding for each of the conjectures.""" return self.make_embedding(conjectures)
[ "def", "conjecture_embedding", "(", "self", ",", "conjectures", ")", ":", "return", "self", ".", "make_embedding", "(", "conjectures", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/premises/model_final_cnn_2x.py#L47-L49
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/core.py
python
read_data_page
(f, helper, header, metadata, skip_nulls=False, selfmade=False)
return definition_levels, repetition_levels, values[:nval]
Read a data page: definitions, repetitions, values (in order) Only values are guaranteed to exist, e.g., for a top-level, required field.
Read a data page: definitions, repetitions, values (in order)
[ "Read", "a", "data", "page", ":", "definitions", "repetitions", "values", "(", "in", "order", ")" ]
def read_data_page(f, helper, header, metadata, skip_nulls=False, selfmade=False): """Read a data page: definitions, repetitions, values (in order) Only values are guaranteed to exist, e.g., for a top-level, required field. """ daph = header.data_page_header raw_bytes = _read_page(f, header, metadata) io_obj = encoding.Numpy8(np.frombuffer(byte_buffer(raw_bytes), dtype=np.uint8)) repetition_levels = read_rep(io_obj, daph, helper, metadata) if skip_nulls and not helper.is_required(metadata.path_in_schema): num_nulls = 0 definition_levels = None skip_definition_bytes(io_obj, daph.num_values) else: definition_levels, num_nulls = read_def(io_obj, daph, helper, metadata) nval = daph.num_values - num_nulls if daph.encoding == parquet_thrift.Encoding.PLAIN: width = helper.schema_element(metadata.path_in_schema).type_length values = encoding.read_plain(raw_bytes[io_obj.loc:], metadata.type, int(daph.num_values - num_nulls), width=width) elif daph.encoding in [parquet_thrift.Encoding.PLAIN_DICTIONARY, parquet_thrift.Encoding.RLE]: # bit_width is stored as single byte. if daph.encoding == parquet_thrift.Encoding.RLE: bit_width = helper.schema_element( metadata.path_in_schema).type_length else: bit_width = io_obj.read_byte() if bit_width in [8, 16, 32] and selfmade: num = (encoding.read_unsigned_var_int(io_obj) >> 1) * 8 values = io_obj.read(num * bit_width // 8).view('int%i' % bit_width) elif bit_width: values = encoding.Numpy32(np.empty(daph.num_values-num_nulls+7, dtype=np.int32)) # length is simply "all data left in this page" encoding.read_rle_bit_packed_hybrid( io_obj, bit_width, io_obj.len-io_obj.loc, o=values) values = values.data[:nval] else: values = np.zeros(nval, dtype=np.int8) else: raise NotImplementedError('Encoding %s' % daph.encoding) return definition_levels, repetition_levels, values[:nval]
[ "def", "read_data_page", "(", "f", ",", "helper", ",", "header", ",", "metadata", ",", "skip_nulls", "=", "False", ",", "selfmade", "=", "False", ")", ":", "daph", "=", "header", ".", "data_page_header", "raw_bytes", "=", "_read_page", "(", "f", ",", "he...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/core.py#L91-L141
apple/foundationdb
f7118ad406f44ab7a33970fc8370647ed0085e18
layers/taskbucket/__init__.py
python
Future.joined_future
(self, tr)
return f
Returns a new unset future which this future is join()ed to.
Returns a new unset future which this future is join()ed to.
[ "Returns", "a", "new", "unset", "future", "which", "this", "future", "is", "join", "()", "ed", "to", "." ]
def joined_future(self, tr): """Returns a new unset future which this future is join()ed to.""" if self.system_access: tr.options.set_access_system_keys() f = self.bucket.future(tr) self.join(tr, f) return f
[ "def", "joined_future", "(", "self", ",", "tr", ")", ":", "if", "self", ".", "system_access", ":", "tr", ".", "options", ".", "set_access_system_keys", "(", ")", "f", "=", "self", ".", "bucket", ".", "future", "(", "tr", ")", "self", ".", "join", "("...
https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/layers/taskbucket/__init__.py#L385-L391
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py
python
_enable_parse_arg
(cmd_name, arg)
return argv
Internal worker function to take an argument from enable/disable and return a tuple of arguments. Arguments: cmd_name: Name of the command invoking this function. args: The argument as a string. Returns: A tuple containing the dictionary, and the argument, or just the dictionary in the case of "all".
Internal worker function to take an argument from enable/disable and return a tuple of arguments.
[ "Internal", "worker", "function", "to", "take", "an", "argument", "from", "enable", "/", "disable", "and", "return", "a", "tuple", "of", "arguments", "." ]
def _enable_parse_arg(cmd_name, arg): """ Internal worker function to take an argument from enable/disable and return a tuple of arguments. Arguments: cmd_name: Name of the command invoking this function. args: The argument as a string. Returns: A tuple containing the dictionary, and the argument, or just the dictionary in the case of "all". """ argv = gdb.string_to_argv(arg); argc = len(argv) if argv[0] == "all" and argc > 1: raise gdb.GdbError(cmd_name + ": with 'all' " \ "you may not specify a filter.") else: if argv[0] != "all" and argc != 2: raise gdb.GdbError(cmd_name + " takes exactly two arguments.") return argv
[ "def", "_enable_parse_arg", "(", "cmd_name", ",", "arg", ")", ":", "argv", "=", "gdb", ".", "string_to_argv", "(", "arg", ")", "argc", "=", "len", "(", "argv", ")", "if", "argv", "[", "0", "]", "==", "\"all\"", "and", "argc", ">", "1", ":", "raise"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/command/frame_filters.py#L108-L130
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
projects/humans/c3d/controllers/c3d_viewer/c3d.py
python
Param.uint8_array
(self)
return self._as_array('B')
Get the param as an array of 8-bit unsigned integers.
Get the param as an array of 8-bit unsigned integers.
[ "Get", "the", "param", "as", "an", "array", "of", "8", "-", "bit", "unsigned", "integers", "." ]
def uint8_array(self): '''Get the param as an array of 8-bit unsigned integers.''' return self._as_array('B')
[ "def", "uint8_array", "(", "self", ")", ":", "return", "self", ".", "_as_array", "(", "'B'", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/humans/c3d/controllers/c3d_viewer/c3d.py#L338-L340
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py
python
TimingScriptGenerator.writeTimingCall
(self, filename, numFuncs, funcsCalled, totalCalls)
Echo some comments and invoke both versions of toy
Echo some comments and invoke both versions of toy
[ "Echo", "some", "comments", "and", "invoke", "both", "versions", "of", "toy" ]
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls): """Echo some comments and invoke both versions of toy""" rootname = filename if '.' in filename: rootname = filename[:filename.rfind('.')] self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
[ "def", "writeTimingCall", "(", "self", ",", "filename", ",", "numFuncs", ",", "funcsCalled", ",", "totalCalls", ")", ":", "rootname", "=", "filename", "if", "'.'", "in", "filename", ":", "rootname", "=", "filename", "[", ":", "filename", ".", "rfind", "(",...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L13-L30
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
RobotModelDriver.getAffineCoeffs
(self)
return _robotsim.RobotModelDriver_getAffineCoeffs(self)
r""" getAffineCoeffs(RobotModelDriver self) For "affine" links, returns the scale and offset of the driver value mapped to the world. Returns a pair (scale,offset), each of length len(getAffectedLinks()).
r""" getAffineCoeffs(RobotModelDriver self)
[ "r", "getAffineCoeffs", "(", "RobotModelDriver", "self", ")" ]
def getAffineCoeffs(self) -> "void": r""" getAffineCoeffs(RobotModelDriver self) For "affine" links, returns the scale and offset of the driver value mapped to the world. Returns a pair (scale,offset), each of length len(getAffectedLinks()). """ return _robotsim.RobotModelDriver_getAffineCoeffs(self)
[ "def", "getAffineCoeffs", "(", "self", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "RobotModelDriver_getAffineCoeffs", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4649-L4660
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/ast.py
python
walk
(node)
Recursively yield all child nodes of *node*, in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
Recursively yield all child nodes of *node*, in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
[ "Recursively", "yield", "all", "child", "nodes", "of", "*", "node", "*", "in", "no", "specified", "order", ".", "This", "is", "useful", "if", "you", "only", "want", "to", "modify", "nodes", "in", "place", "and", "don", "t", "care", "about", "the", "con...
def walk(node): """ Recursively yield all child nodes of *node*, in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = todo.popleft() todo.extend(iter_child_nodes(node)) yield node
[ "def", "walk", "(", "node", ")", ":", "from", "collections", "import", "deque", "todo", "=", "deque", "(", "[", "node", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "todo", ".", "extend", "(", "iter_child_nodes", "("...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ast.py#L193-L204
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/dist/icon.py
python
Icon.makeICNS
(self, fn)
return True
Writes the images to an Apple ICNS file. Returns True on success.
Writes the images to an Apple ICNS file. Returns True on success.
[ "Writes", "the", "images", "to", "an", "Apple", "ICNS", "file", ".", "Returns", "True", "on", "success", "." ]
def makeICNS(self, fn): """ Writes the images to an Apple ICNS file. Returns True on success. """ if not isinstance(fn, Filename): fn = Filename.fromOsSpecific(fn) fn.setBinary() icns = open(fn, 'wb') icns.write(b'icns\0\0\0\0') icon_types = {16: b'is32', 32: b'il32', 48: b'ih32', 128: b'it32'} mask_types = {16: b's8mk', 32: b'l8mk', 48: b'h8mk', 128: b't8mk'} png_types = {256: b'ic08', 512: b'ic09', 1024: b'ic10'} pngtype = PNMFileTypeRegistry.getGlobalPtr().getTypeFromExtension("png") for size, image in sorted(self.images.items(), key=lambda item:item[0]): if size in png_types and pngtype is not None: stream = StringStream() image.write(stream, "", pngtype) pngdata = stream.data icns.write(png_types[size]) icns.write(struct.pack('>I', len(pngdata))) icns.write(pngdata) elif size in icon_types: # If it has an alpha channel, we write out a mask too. if image.hasAlpha(): icns.write(mask_types[size]) icns.write(struct.pack('>I', size * size + 8)) for y in range(size): for x in range(size): icns.write(struct.pack('<B', int(image.getAlpha(x, y) * 255))) icns.write(icon_types[size]) icns.write(struct.pack('>I', size * size * 4 + 8)) for y in range(size): for x in range(size): r, g, b = image.getXel(x, y) icns.write(struct.pack('>BBBB', 0, int(r * 255), int(g * 255), int(b * 255))) length = icns.tell() icns.seek(4) icns.write(struct.pack('>I', length)) icns.close() return True
[ "def", "makeICNS", "(", "self", ",", "fn", ")", ":", "if", "not", "isinstance", "(", "fn", ",", "Filename", ")", ":", "fn", "=", "Filename", ".", "fromOsSpecific", "(", "fn", ")", "fn", ".", "setBinary", "(", ")", "icns", "=", "open", "(", "fn", ...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/dist/icon.py#L225-L274
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_NV_DefineSpace_REQUEST.fromTpm
(buf)
return buf.createObj(TPM2_NV_DefineSpace_REQUEST)
Returns new TPM2_NV_DefineSpace_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPM2_NV_DefineSpace_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPM2_NV_DefineSpace_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPM2_NV_DefineSpace_REQUEST object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPM2_NV_DefineSpace_REQUEST)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPM2_NV_DefineSpace_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16589-L16593
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py
python
IOBase.tell
(self)
return self.seek(0, 1)
Return current stream position.
Return current stream position.
[ "Return", "current", "stream", "position", "." ]
def tell(self): """Return current stream position.""" return self.seek(0, 1)
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "seek", "(", "0", ",", "1", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py#L313-L315
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/distributions/multinomial.py
python
Multinomial._maybe_assert_valid_sample
(self, counts)
return control_flow_ops.with_dependencies([ check_ops.assert_equal( self.total_count, math_ops.reduce_sum(counts, -1), message="counts must sum to `self.total_count`"), ], counts)
Check counts for proper shape, values, then return tensor version.
Check counts for proper shape, values, then return tensor version.
[ "Check", "counts", "for", "proper", "shape", "values", "then", "return", "tensor", "version", "." ]
def _maybe_assert_valid_sample(self, counts): """Check counts for proper shape, values, then return tensor version.""" if not self.validate_args: return counts counts = distribution_util.embed_check_nonnegative_integer_form(counts) return control_flow_ops.with_dependencies([ check_ops.assert_equal( self.total_count, math_ops.reduce_sum(counts, -1), message="counts must sum to `self.total_count`"), ], counts)
[ "def", "_maybe_assert_valid_sample", "(", "self", ",", "counts", ")", ":", "if", "not", "self", ".", "validate_args", ":", "return", "counts", "counts", "=", "distribution_util", ".", "embed_check_nonnegative_integer_form", "(", "counts", ")", "return", "control_flo...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/multinomial.py#L286-L295
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/build/android/device_status_check.py
python
CheckForMissingDevices
(options, adb_online_devs)
Uses file of previous online devices to detect broken phones. Args: options: out_dir parameter of options argument is used as the base directory to load and update the cache file. adb_online_devs: A list of serial numbers of the currently visible and online attached devices.
Uses file of previous online devices to detect broken phones.
[ "Uses", "file", "of", "previous", "online", "devices", "to", "detect", "broken", "phones", "." ]
def CheckForMissingDevices(options, adb_online_devs): """Uses file of previous online devices to detect broken phones. Args: options: out_dir parameter of options argument is used as the base directory to load and update the cache file. adb_online_devs: A list of serial numbers of the currently visible and online attached devices. """ # TODO(navabi): remove this once the bug that causes different number # of devices to be detected between calls is fixed. logger = logging.getLogger() logger.setLevel(logging.INFO) out_dir = os.path.abspath(options.out_dir) def ReadDeviceList(file_name): devices_path = os.path.join(out_dir, file_name) devices = [] try: with open(devices_path) as f: devices = f.read().splitlines() except IOError: # Ignore error, file might not exist pass return devices def WriteDeviceList(file_name, device_list): path = os.path.join(out_dir, file_name) if not os.path.exists(out_dir): os.makedirs(out_dir) with open(path, 'w') as f: # Write devices currently visible plus devices previously seen. f.write('\n'.join(set(device_list))) last_devices_path = os.path.join(out_dir, '.last_devices') last_devices = ReadDeviceList('.last_devices') missing_devs = list(set(last_devices) - set(adb_online_devs)) if missing_devs: from_address = 'buildbot@chromium.org' to_address = 'chromium-android-device-alerts@google.com' bot_name = os.environ['BUILDBOT_BUILDERNAME'] slave_name = os.environ['BUILDBOT_SLAVENAME'] num_online_devs = len(adb_online_devs) subject = 'Devices offline on %s, %s (%d remaining).' % (slave_name, bot_name, num_online_devs) buildbot_report.PrintWarning() devices_missing_msg = '%d devices not detected.' % len(missing_devs) buildbot_report.PrintSummaryText(devices_missing_msg) # TODO(navabi): Debug by printing both output from GetCmdOutput and # GetAttachedDevices to compare results. body = '\n'.join( ['Current online devices: %s' % adb_online_devs, '%s are no longer visible. Were they removed?\n' % missing_devs, 'SHERIFF: See go/chrome_device_monitor', 'Cache file: %s\n\n' % last_devices_path, 'adb devices: %s' % GetCmdOutput(['adb', 'devices']), 'adb devices(GetAttachedDevices): %s' % GetAttachedDevices()]) print body # Only send email if the first time a particular device goes offline last_missing = ReadDeviceList('.last_missing') new_missing_devs = set(missing_devs) - set(last_missing) if new_missing_devs: msg_body = '\r\n'.join( ['From: %s' % from_address, 'To: %s' % to_address, 'Subject: %s' % subject, '', body]) try: server = smtplib.SMTP('localhost') server.sendmail(from_address, [to_address], msg_body) server.quit() except Exception as e: print 'Failed to send alert email. Error: %s' % e else: new_devs = set(adb_online_devs) - set(last_devices) if new_devs and os.path.exists(last_devices_path): buildbot_report.PrintWarning() buildbot_report.PrintSummaryText( '%d new devices detected' % len(new_devs)) print ('New devices detected %s. And now back to your ' 'regularly scheduled program.' % list(new_devs)) WriteDeviceList('.last_devices', (adb_online_devs + last_devices)) WriteDeviceList('.last_missing', missing_devs)
[ "def", "CheckForMissingDevices", "(", "options", ",", "adb_online_devs", ")", ":", "# TODO(navabi): remove this once the bug that causes different number", "# of devices to be detected between calls is fixed.", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/device_status_check.py#L53-L142
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/Symmetrise.py
python
Symmetrise._calculate_array_points
(self, sample_x, sample_array_len)
Finds the points in the array that match the cut points. @param sample_x - Sample X axis data @param sample_array_len - Length of data array for sample data
Finds the points in the array that match the cut points.
[ "Finds", "the", "points", "in", "the", "array", "that", "match", "the", "cut", "points", "." ]
def _calculate_array_points(self, sample_x, sample_array_len): """ Finds the points in the array that match the cut points. @param sample_x - Sample X axis data @param sample_array_len - Length of data array for sample data """ # Find array index of the first negative XMin negative_min_diff = sample_x + self._x_min self._negative_min_index = np.where(negative_min_diff > 0)[0][0] self._check_bounds(self._negative_min_index, sample_array_len, label='Negative') # Find array index of the first positive XMin, that is smaller than the required positive_min_diff = sample_x + sample_x[self._negative_min_index] self._positive_min_index = np.where(positive_min_diff > 0)[0][0] self._check_bounds(self._positive_min_index, sample_array_len, label='Positive') # Find array index of the first positive XMax, that is smaller than the required self._positive_max_index = np.where(sample_x < self._x_max)[0][-1] if self._positive_max_index == sample_array_len: self._positive_max_index -= 1 self._check_bounds(self._positive_max_index, sample_array_len, label='Positive')
[ "def", "_calculate_array_points", "(", "self", ",", "sample_x", ",", "sample_array_len", ")", ":", "# Find array index of the first negative XMin", "negative_min_diff", "=", "sample_x", "+", "self", ".", "_x_min", "self", ".", "_negative_min_index", "=", "np", ".", "w...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/Symmetrise.py#L237-L258
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/index.py
python
DatetimeIndex.isocalendar
(self)
return cudf.core.tools.datetimes._to_iso_calendar(self)
Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard. Returns ------- DataFrame with columns year, week and day Examples -------- >>> gIndex = cudf.DatetimeIndex(["2020-05-31 08:00:00", ... "1999-12-31 18:40:00"]) >>> gIndex.isocalendar() year week day 2020-05-31 08:00:00 2020 22 7 1999-12-31 18:40:00 1999 52 5
Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard.
[ "Returns", "a", "DataFrame", "with", "the", "year", "week", "and", "day", "calculated", "according", "to", "the", "ISO", "8601", "standard", "." ]
def isocalendar(self): """ Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard. Returns ------- DataFrame with columns year, week and day Examples -------- >>> gIndex = cudf.DatetimeIndex(["2020-05-31 08:00:00", ... "1999-12-31 18:40:00"]) >>> gIndex.isocalendar() year week day 2020-05-31 08:00:00 2020 22 7 1999-12-31 18:40:00 1999 52 5 """ return cudf.core.tools.datetimes._to_iso_calendar(self)
[ "def", "isocalendar", "(", "self", ")", ":", "return", "cudf", ".", "core", ".", "tools", ".", "datetimes", ".", "_to_iso_calendar", "(", "self", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/index.py#L1839-L1858
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_logic_parser.py
python
p_terms_terms_term
(p)
terms : terms COMMA term
terms : terms COMMA term
[ "terms", ":", "terms", "COMMA", "term" ]
def p_terms_terms_term(p): 'terms : terms COMMA term' p[0] = p[1] p[0].append(p[3])
[ "def", "p_terms_terms_term", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", "(", "p", "[", "3", "]", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_parser.py#L219-L222
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/filters.py
python
do_urlencode
(value)
return u'&'.join(unicode_urlencode(k) + '=' + unicode_urlencode(v, for_qs=True) for k, v in itemiter)
Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7
Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.
[ "Escape", "strings", "for", "use", "in", "URLs", "(", "uses", "UTF", "-", "8", "encoding", ")", ".", "It", "accepts", "both", "dictionaries", "and", "regular", "strings", "as", "well", "as", "pairwise", "iterables", "." ]
def do_urlencode(value): """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 """ itemiter = None if isinstance(value, dict): itemiter = iteritems(value) elif not isinstance(value, string_types): try: itemiter = iter(value) except TypeError: pass if itemiter is None: return unicode_urlencode(value) return u'&'.join(unicode_urlencode(k) + '=' + unicode_urlencode(v, for_qs=True) for k, v in itemiter)
[ "def", "do_urlencode", "(", "value", ")", ":", "itemiter", "=", "None", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "itemiter", "=", "iteritems", "(", "value", ")", "elif", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/filters.py#L80-L98
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/_custom_op/img2col_impl.py
python
height56_width56
(tik_instance, input_x, res, input_shape, shape_info)
return tik_instance, res
height56_width56
height56_width56
[ "height56_width56" ]
def height56_width56(tik_instance, input_x, res, input_shape, shape_info): """height56_width56""" if input_shape == ((32, 4, 56, 56, 16), 'float16', (3, 3), (1, 1)): tik_instance, res = shape56_0(tik_instance, input_x, res, input_shape, shape_info) if input_shape == ((32, 8, 56, 56, 16), 'float16', (3, 3), (2, 2)): tik_instance, res = shape56_1(tik_instance, input_x, res, input_shape, shape_info) if input_shape == ((32, 4, 56, 56, 16), 'float16', (1, 1), (1, 1)): tik_instance, res = shape56_2(tik_instance, input_x, res, input_shape, shape_info) if input_shape == ((32, 16, 56, 56, 16), 'float16', (1, 1), (1, 1)): tik_instance, res = shape56_3(tik_instance, input_x, res, input_shape, shape_info) if input_shape == ((32, 16, 56, 56, 16), 'float16', (1, 1), (2, 2)): tik_instance, res = shape56_4(tik_instance, input_x, res, input_shape, shape_info) return tik_instance, res
[ "def", "height56_width56", "(", "tik_instance", ",", "input_x", ",", "res", ",", "input_shape", ",", "shape_info", ")", ":", "if", "input_shape", "==", "(", "(", "32", ",", "4", ",", "56", ",", "56", ",", "16", ")", ",", "'float16'", ",", "(", "3", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/_custom_op/img2col_impl.py#L743-L760
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/pypack/modulegraph/pkg_resources.py
python
WorkingSet.subscribe
(self, callback)
Invoke `callback` for all distributions (including existing ones)
Invoke `callback` for all distributions (including existing ones)
[ "Invoke", "callback", "for", "all", "distributions", "(", "including", "existing", "ones", ")" ]
def subscribe(self, callback): """Invoke `callback` for all distributions (including existing ones)""" if callback in self.callbacks: return self.callbacks.append(callback) for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "for", "dist", "in", "self", ":", "callback", "(", "dist", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/modulegraph/pkg_resources.py#L550-L556
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/prefilter.py
python
AssignmentChecker.check
(self, line_info)
Check to see if user is assigning to a var for the first time, in which case we want to avoid any sort of automagic / autocall games. This allows users to assign to either alias or magic names true python variables (the magic/alias systems always take second seat to true python code). E.g. ls='hi', or ls,that=1,2
Check to see if user is assigning to a var for the first time, in which case we want to avoid any sort of automagic / autocall games.
[ "Check", "to", "see", "if", "user", "is", "assigning", "to", "a", "var", "for", "the", "first", "time", "in", "which", "case", "we", "want", "to", "avoid", "any", "sort", "of", "automagic", "/", "autocall", "games", "." ]
def check(self, line_info): """Check to see if user is assigning to a var for the first time, in which case we want to avoid any sort of automagic / autocall games. This allows users to assign to either alias or magic names true python variables (the magic/alias systems always take second seat to true python code). E.g. ls='hi', or ls,that=1,2""" if line_info.the_rest: if line_info.the_rest[0] in '=,': return self.prefilter_manager.get_handler_by_name('normal') else: return None
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "line_info", ".", "the_rest", ":", "if", "line_info", ".", "the_rest", "[", "0", "]", "in", "'=,'", ":", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'normal'",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L440-L451
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/WX/pidWxDc.py
python
PiddleWxDc._setWXfont
(self, font=None)
return (wx_font)
set/return the current font for the dc jjk 10/28/99
set/return the current font for the dc jjk 10/28/99
[ "set", "/", "return", "the", "current", "font", "for", "the", "dc", "jjk", "10", "/", "28", "/", "99" ]
def _setWXfont(self, font=None): '''set/return the current font for the dc jjk 10/28/99''' wx_font = self._getWXfont(font) self.dc.SetFont(wx_font) return (wx_font)
[ "def", "_setWXfont", "(", "self", ",", "font", "=", "None", ")", ":", "wx_font", "=", "self", ".", "_getWXfont", "(", "font", ")", "self", ".", "dc", ".", "SetFont", "(", "wx_font", ")", "return", "(", "wx_font", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/WX/pidWxDc.py#L114-L119
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/base/Translator.py
python
Translator.renderer
(self)
return self.__renderer
Return the Renderer object.
Return the Renderer object.
[ "Return", "the", "Renderer", "object", "." ]
def renderer(self): """Return the Renderer object.""" return self.__renderer
[ "def", "renderer", "(", "self", ")", ":", "return", "self", ".", "__renderer" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/base/Translator.py#L98-L100
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py
python
_Union
(module, parsed_union)
return union
Args: module: {mojom.Module} Module currently being constructed. parsed_union: {ast.Union} Parsed union. Returns: {mojom.Union} AST union.
Args: module: {mojom.Module} Module currently being constructed. parsed_union: {ast.Union} Parsed union.
[ "Args", ":", "module", ":", "{", "mojom", ".", "Module", "}", "Module", "currently", "being", "constructed", ".", "parsed_union", ":", "{", "ast", ".", "Union", "}", "Parsed", "union", "." ]
def _Union(module, parsed_union): """ Args: module: {mojom.Module} Module currently being constructed. parsed_union: {ast.Union} Parsed union. Returns: {mojom.Union} AST union. """ union = mojom.Union(module=module) union.mojom_name = parsed_union.mojom_name union.spec = 'x:' + module.mojom_namespace + '.' + union.mojom_name module.kinds[union.spec] = union # Stash fields parsed_union here temporarily. union.fields_data = _ElemsOfType( parsed_union.body, ast.UnionField, parsed_union.mojom_name) union.attributes = _AttributeListToDict(parsed_union.attribute_list) return union
[ "def", "_Union", "(", "module", ",", "parsed_union", ")", ":", "union", "=", "mojom", ".", "Union", "(", "module", "=", "module", ")", "union", ".", "mojom_name", "=", "parsed_union", ".", "mojom_name", "union", ".", "spec", "=", "'x:'", "+", "module", ...
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py#L303-L320
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pydoc.py
python
TextDoc.section
(self, title, contents)
return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
Format a section with a given heading.
Format a section with a given heading.
[ "Format", "a", "section", "with", "a", "given", "heading", "." ]
def section(self, title, contents): """Format a section with a given heading.""" return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
[ "def", "section", "(", "self", ",", "title", ",", "contents", ")", ":", "return", "self", ".", "bold", "(", "title", ")", "+", "'\\n'", "+", "rstrip", "(", "self", ".", "indent", "(", "contents", ")", ")", "+", "'\\n\\n'" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L1048-L1050
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py
python
Response.json
(self, **kwargs)
return complexjson.loads(self.text, **kwargs)
r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json.
r"""Returns the json-encoded content of a response, if any.
[ "r", "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs)
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "self", ".", "content", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should ex...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py#L874-L898
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
ml_perf/utils.py
python
wait
(aws)
return results if isinstance(aws, list) else results[0]
Waits for all of the awaitable objects (e.g. coroutines) in aws to finish. All the awaitable objects are waited for, even if one of them raises an exception. When one or more awaitable raises an exception, the exception from the awaitable with the lowest index in the aws list will be reraised. Args: aws: a single awaitable, or list awaitables. Returns: If aws is a single awaitable, its result. If aws is a list of awaitables, a list containing the of each awaitable in the list. Raises: Exception: if any of the awaitables raises.
Waits for all of the awaitable objects (e.g. coroutines) in aws to finish.
[ "Waits", "for", "all", "of", "the", "awaitable", "objects", "(", "e", ".", "g", ".", "coroutines", ")", "in", "aws", "to", "finish", "." ]
def wait(aws): """Waits for all of the awaitable objects (e.g. coroutines) in aws to finish. All the awaitable objects are waited for, even if one of them raises an exception. When one or more awaitable raises an exception, the exception from the awaitable with the lowest index in the aws list will be reraised. Args: aws: a single awaitable, or list awaitables. Returns: If aws is a single awaitable, its result. If aws is a list of awaitables, a list containing the of each awaitable in the list. Raises: Exception: if any of the awaitables raises. """ aws_list = aws if isinstance(aws, list) else [aws] results = asyncio.get_event_loop().run_until_complete(asyncio.gather( *aws_list, return_exceptions=True)) # If any of the cmds failed, re-raise the error. for result in results: if isinstance(result, Exception): raise result return results if isinstance(aws, list) else results[0]
[ "def", "wait", "(", "aws", ")", ":", "aws_list", "=", "aws", "if", "isinstance", "(", "aws", ",", "list", ")", "else", "[", "aws", "]", "results", "=", "asyncio", ".", "get_event_loop", "(", ")", ".", "run_until_complete", "(", "asyncio", ".", "gather"...
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/ml_perf/utils.py#L176-L202
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/codecs.py
python
StreamReader.reset
(self)
Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
Resets the codec buffers used for keeping state.
[ "Resets", "the", "codec", "buffers", "used", "for", "keeping", "state", "." ]
def reset(self): """ Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors. """ self.bytebuffer = "" self.charbuffer = u"" self.linebuffer = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "bytebuffer", "=", "\"\"", "self", ".", "charbuffer", "=", "u\"\"", "self", ".", "linebuffer", "=", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/codecs.py#L608-L619
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/applelink.py
python
_applelib_versioned_lib_suffix
(env, suffix, version)
return suffix
For suffix='.dylib' and version='0.1.2' it returns '.0.1.2.dylib
For suffix='.dylib' and version='0.1.2' it returns '.0.1.2.dylib
[ "For", "suffix", "=", ".", "dylib", "and", "version", "=", "0", ".", "1", ".", "2", "it", "returns", ".", "0", ".", "1", ".", "2", ".", "dylib" ]
def _applelib_versioned_lib_suffix(env, suffix, version): """For suffix='.dylib' and version='0.1.2' it returns '.0.1.2.dylib'""" Verbose = False if Verbose: print("_applelib_versioned_lib_suffix: suffix={!r}".format(suffix)) print("_applelib_versioned_lib_suffix: version={!r}".format(version)) if version not in suffix: suffix = "." + version + suffix if Verbose: print("_applelib_versioned_lib_suffix: return suffix={!r}".format(suffix)) return suffix
[ "def", "_applelib_versioned_lib_suffix", "(", "env", ",", "suffix", ",", "version", ")", ":", "Verbose", "=", "False", "if", "Verbose", ":", "print", "(", "\"_applelib_versioned_lib_suffix: suffix={!r}\"", ".", "format", "(", "suffix", ")", ")", "print", "(", "\...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/applelink.py#L50-L60
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/dfxml.py
python
fileobject.savefile
(self,filename=None)
Saves the file.
Saves the file.
[ "Saves", "the", "file", "." ]
def savefile(self,filename=None): """Saves the file.""" with open(filename,"wb") as f: for run in self.byte_runs(): self.imagefile.seek(run.img_offset) count = run.len while count>0: xfer_len = min(count,1024*1024) # transfer up to a megabyte at a time buf = self.imagefile.read(xfer_len) if len(buf)==0: break f.write(buf) count -= xfer_len
[ "def", "savefile", "(", "self", ",", "filename", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"wb\"", ")", "as", "f", ":", "for", "run", "in", "self", ".", "byte_runs", "(", ")", ":", "self", ".", "imagefile", ".", "seek", "(", ...
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L872-L883
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/lexers/base.py
python
Lexer.invalidation_hash
(self)
return id(self)
When this changes, `lex_document` could give a different output. (Only used for `DynamicLexer`.)
When this changes, `lex_document` could give a different output. (Only used for `DynamicLexer`.)
[ "When", "this", "changes", "lex_document", "could", "give", "a", "different", "output", ".", "(", "Only", "used", "for", "DynamicLexer", ".", ")" ]
def invalidation_hash(self) -> Hashable: """ When this changes, `lex_document` could give a different output. (Only used for `DynamicLexer`.) """ return id(self)
[ "def", "invalidation_hash", "(", "self", ")", "->", "Hashable", ":", "return", "id", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/lexers/base.py#L33-L38
MegaGlest/megaglest-source
e3af470288a3c9cc179f63b5a1eb414a669e3772
mk/windoze/symbolstore.py
python
StartProcessFilesWork
(dumper, files, arch_num, arch, vcs_root, after, after_arg)
return dumper.ProcessFilesWork(files, arch_num, arch, vcs_root, after, after_arg)
multiprocessing can't handle methods as Process targets, so we define a simple wrapper function around the work method.
multiprocessing can't handle methods as Process targets, so we define a simple wrapper function around the work method.
[ "multiprocessing", "can", "t", "handle", "methods", "as", "Process", "targets", "so", "we", "define", "a", "simple", "wrapper", "function", "around", "the", "work", "method", "." ]
def StartProcessFilesWork(dumper, files, arch_num, arch, vcs_root, after, after_arg): """multiprocessing can't handle methods as Process targets, so we define a simple wrapper function around the work method.""" return dumper.ProcessFilesWork(files, arch_num, arch, vcs_root, after, after_arg)
[ "def", "StartProcessFilesWork", "(", "dumper", ",", "files", ",", "arch_num", ",", "arch", ",", "vcs_root", ",", "after", ",", "after_arg", ")", ":", "return", "dumper", ".", "ProcessFilesWork", "(", "files", ",", "arch_num", ",", "arch", ",", "vcs_root", ...
https://github.com/MegaGlest/megaglest-source/blob/e3af470288a3c9cc179f63b5a1eb414a669e3772/mk/windoze/symbolstore.py#L314-L317