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
sequence
function
stringlengths
34
151k
function_tokens
sequence
url
stringlengths
90
278
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
python_packaging/src/gmxapi/operation.py
python
function_wrapper
(output: dict = None)
return decorator
Generate a decorator for wrapped functions with signature manipulation. New function accepts the same arguments, with additional arguments required by the API. The new function returns an object with an ``output`` attribute containing the named outputs. Example: >>> @function_wrapper(output={'spam': str, 'foo': str}) ... def myfunc(parameter: str = None, output=None): ... output.spam = parameter ... output.foo = parameter + ' ' + parameter ... >>> operation1 = myfunc(parameter='spam spam') >>> assert operation1.output.spam.result() == 'spam spam' >>> assert operation1.output.foo.result() == 'spam spam spam spam' Arguments: output (dict): output names and types If ``output`` is provided to the wrapper, a data structure will be passed to the wrapped functions with the named attributes so that the function can easily publish multiple named results. Otherwise, the ``output`` of the generated operation will just capture the return value of the wrapped function. .. todo:: gmxapi typing stub file(s). The way this wrapper uses parameter annotations is not completely compatible with static type checking (PEP 484). If we decide to keep the convenience functionality by which operation details are inferred from parameter annotations, we should provide a separate stub file (.pyi) to support static type checking of the API.
Generate a decorator for wrapped functions with signature manipulation.
[ "Generate", "a", "decorator", "for", "wrapped", "functions", "with", "signature", "manipulation", "." ]
def function_wrapper(output: dict = None): # Suppress warnings in the example code. # noinspection PyUnresolvedReferences """Generate a decorator for wrapped functions with signature manipulation. New function accepts the same arguments, with additional arguments required by the API. The new function returns an object with an ``output`` attribute containing the named outputs. Example: >>> @function_wrapper(output={'spam': str, 'foo': str}) ... def myfunc(parameter: str = None, output=None): ... output.spam = parameter ... output.foo = parameter + ' ' + parameter ... >>> operation1 = myfunc(parameter='spam spam') >>> assert operation1.output.spam.result() == 'spam spam' >>> assert operation1.output.foo.result() == 'spam spam spam spam' Arguments: output (dict): output names and types If ``output`` is provided to the wrapper, a data structure will be passed to the wrapped functions with the named attributes so that the function can easily publish multiple named results. Otherwise, the ``output`` of the generated operation will just capture the return value of the wrapped function. .. todo:: gmxapi typing stub file(s). The way this wrapper uses parameter annotations is not completely compatible with static type checking (PEP 484). If we decide to keep the convenience functionality by which operation details are inferred from parameter annotations, we should provide a separate stub file (.pyi) to support static type checking of the API. """ if output is not None and not isinstance(output, collections.abc.Mapping): raise exceptions.TypeError( 'If provided, `output` argument must be a mapping of data names to types.') # TODO: (FR5+) gmxapi operations need to allow a context-dependent way to generate an implementation with input. # This function wrapper reproduces the wrapped function's kwargs, but does not allow chaining a # dynamic `input` kwarg and does not dispatch according to a `context` kwarg. We should allow # a default implementation and registration of alternate implementations. We don't have to do that # with functools.singledispatch, but we could, if we add yet another layer to generate a wrapper # that takes the context as the first argument. (`singledispatch` inspects the first argument rather # that a named argument) # Implementation note: The closure of the current function is used to # dynamically define several classes that support the operation to be # created by the returned decorator. def decorator(function) -> typing.Callable: # Explicitly capture `function` and `output` references. provided_output_map = output # Note: Allow operations to be defined entirely in template headers to facilitate # compile-time optimization of fused operations. Consider what distinction, if any, # exists between a fused operation and a more basic operation. Probably it amounts # to aspects related to interaction with the Context that get combined in a fused # operation, such as the resource director, builder, etc. class OperationDetails(OperationDetailsBase): # Warning: function.__qualname__ is not rigorous since function may be in a local scope. # TODO: Improve base identifier. # Suggest registering directly in the Context instead of in this local class definition. __basename = '.'.join((str(function.__module__), function.__qualname__)) __last_uid = 0 _input_signature_description = InputCollectionDescription.from_function(function) # TODO: Separate the class and instance logic for the runner. # Logically, the runner is a detail of a context-specific implementation class, # though the output is not generally fully knowable until an instance is initialized # for a certain input fingerprint. # Note: We are almost at a point where this class can be subsumed into two # possible return types for wrapped_function_runner, acting as an operation helper. _runner = wrapped_function_runner(function, provided_output_map) _output_description = _runner.output_description _output_data_proxy_type = define_output_data_proxy(_output_description) _publishing_data_proxy_type = define_publishing_data_proxy(_output_description) _SourceResource = SourceResource[_output_data_proxy_type, _publishing_data_proxy_type] @classmethod def name(cls) -> str: return cls.__basename.split('.')[-1] @classmethod def namespace(cls) -> str: suffix = '.' + cls.name() try: index = cls.__basename.rindex(suffix) except ValueError: index = None return cls.__basename[:index] @classmethod def director(cls, context: _Context): return cls.operation_director @classmethod def signature(cls) -> InputCollectionDescription: """Mapping of named inputs and input type. Used to determine valid inputs before an Operation node is created. Overrides OperationDetailsBase.signature() to provide an implementation for the bound operation. """ return cls._input_signature_description def output_description(self) -> OutputCollectionDescription: """Mapping of available outputs and types for an existing Operation node. Overrides OperationDetailsBase.output_description() to provide an implementation for the bound operation. """ return self._output_description def publishing_data_proxy(self, *, instance: _SourceResource, client_id: int ) -> _publishing_data_proxy_type: """Factory for Operation output publishing resources. Used internally when the operation is run with resources provided by instance. Overrides OperationDetailsBase.publishing_data_proxy() to provide an implementation for the bound operation. """ assert isinstance(instance, ResourceManager) return self._publishing_data_proxy_type(instance=instance, client_id=client_id) def output_data_proxy(self, instance: _SourceResource) -> _output_data_proxy_type: assert isinstance(instance, ResourceManager) return self._output_data_proxy_type(instance=instance) def __call__(self, resources: PyFunctionRunnerResources): """Execute the operation with provided resources. Resources are prepared in an execution context with aid of resource_director() After the first call, output data has been published and is trivially available through the output_data_proxy() Overrides OperationDetailsBase.__call__(). """ self._runner(resources) @classmethod def make_uid(cls, input): """The unique identity of an operation node tags the output with respect to the input. Combines information on the Operation details and the input to uniquely identify the Operation node. Arguments: input : A (collection of) data source(s) that can provide Fingerprints. Used internally by the Context to manage ownership of data sources, to locate resources for nodes in work graphs, and to manage serialization, deserialization, and checkpointing of the work graph. The UID is a detail of the generic Operation that _should_ be independent of the Context details to allow the framework to manage when and where an operation is executed. Note: This implementation creates a new identifier with every call, even if *input* is the same, because we have not developed our Fingerprinting scheme in gmxapi 0.1+. Design notes on further refinement: TODO: Operations should not single-handedly determine their own uniqueness (but they should participate in the determination with the Context). Context implementations should be allowed to optimize handling of equivalent operations in different sessions or work graphs, but we do not yet TODO: guarantee that UIDs are globally unique! The UID should uniquely indicate an operation node based on that node's input. We need input fingerprinting to identify equivalent nodes in a work graph or distinguish nodes across work graphs. """ uid = str(cls.__basename) + str(cls.__last_uid) cls.__last_uid += 1 return uid @classmethod def resource_director(cls, *, input=None, output: _publishing_data_proxy_type = None) -> PyFunctionRunnerResources: """a Director factory that helps build the Session Resources for the function. The Session launcher provides the director with all of the resources previously requested/negotiated/registered by the Operation. The director uses details of the operation to build the resources object required by the operation runner. For the Python Context, the protocol is for the Context to call the resource_director instance method, passing input and output containers. Raises: exceptions.TypeError if provided resource type does not match input signature. """ resources = PyFunctionRunnerResources() resources.update(input.kwargs) resources.update({'output': output}) # TODO: Remove this hack when we can better handle Futures of Containers and Future slicing. for name in resources: if isinstance(resources[name], (list, tuple)): resources[name] = datamodel.ndarray(resources[name]) # Check data compatibility for name, value in resources.items(): if name != 'output': expected = cls.signature()[name] got = type(value) if got != expected: raise exceptions.TypeError( 'Expected {} but got {} for {} resource {}.'.format(expected, got, cls.__basename, name)) return resources # TODO: (FR4) Update annotations with gmxapi data types. E.g. return -> Future. @functools.wraps(function) def helper(*args, context=None, **kwargs): # Description of the Operation input (and output) occurs in the # decorator closure. By the time this factory is (dynamically) defined, # the OperationDetails and ResourceManager are well defined, but not # yet instantiated. # Inspection of the offered input occurs when this factory is called, # and OperationDetails, ResourceManager, and Operation are instantiated. # This operation factory is specialized for the default package Context. if context is None: context = current_context() else: raise exceptions.ApiError('Non-default context handling not implemented.') # This calls a dispatching function that may not be able to reconcile the input # and Context capabilities. This is the place to handle various exceptions for # whatever reasons this reconciliation cannot occur. handle = OperationDetails.operation_director(*args, context=context, label=None, **kwargs) # TODO: NOW: The input fingerprint describes the provided input # as (a) ensemble input, (b) static, (c) future. By the time the # operation is instantiated, the topology of the node is known. # When compared to the InputCollectionDescription, the data compatibility # can be determined. return handle # to do: The factory itself needs to be able to register a factory with # the context that will be responsible for the Operation handle. # The factories need to be able to serve as dispatchers for themselves, # since an operation in one context may need to be reconstituted in a # different context. # The dispatching factory produces a director for a Context, # which will register a factory with the operation in that context. # The factory function has a DirectorFactory. Director instances talk to a NodeBuilder for a Context to # get handles to new operation nodes managed by the context. Part of that process includes registering # a DirectorFactory with the Context. return helper return decorator
[ "def", "function_wrapper", "(", "output", ":", "dict", "=", "None", ")", ":", "# Suppress warnings in the example code.", "# noinspection PyUnresolvedReferences", "if", "output", "is", "not", "None", "and", "not", "isinstance", "(", "output", ",", "collections", ".", "abc", ".", "Mapping", ")", ":", "raise", "exceptions", ".", "TypeError", "(", "'If provided, `output` argument must be a mapping of data names to types.'", ")", "# TODO: (FR5+) gmxapi operations need to allow a context-dependent way to generate an implementation with input.", "# This function wrapper reproduces the wrapped function's kwargs, but does not allow chaining a", "# dynamic `input` kwarg and does not dispatch according to a `context` kwarg. We should allow", "# a default implementation and registration of alternate implementations. We don't have to do that", "# with functools.singledispatch, but we could, if we add yet another layer to generate a wrapper", "# that takes the context as the first argument. (`singledispatch` inspects the first argument rather", "# that a named argument)", "# Implementation note: The closure of the current function is used to", "# dynamically define several classes that support the operation to be", "# created by the returned decorator.", "def", "decorator", "(", "function", ")", "->", "typing", ".", "Callable", ":", "# Explicitly capture `function` and `output` references.", "provided_output_map", "=", "output", "# Note: Allow operations to be defined entirely in template headers to facilitate", "# compile-time optimization of fused operations. Consider what distinction, if any,", "# exists between a fused operation and a more basic operation. Probably it amounts", "# to aspects related to interaction with the Context that get combined in a fused", "# operation, such as the resource director, builder, etc.", "class", "OperationDetails", "(", "OperationDetailsBase", ")", ":", "# Warning: function.__qualname__ is not rigorous since function may be in a local scope.", "# TODO: Improve base identifier.", "# Suggest registering directly in the Context instead of in this local class definition.", "__basename", "=", "'.'", ".", "join", "(", "(", "str", "(", "function", ".", "__module__", ")", ",", "function", ".", "__qualname__", ")", ")", "__last_uid", "=", "0", "_input_signature_description", "=", "InputCollectionDescription", ".", "from_function", "(", "function", ")", "# TODO: Separate the class and instance logic for the runner.", "# Logically, the runner is a detail of a context-specific implementation class,", "# though the output is not generally fully knowable until an instance is initialized", "# for a certain input fingerprint.", "# Note: We are almost at a point where this class can be subsumed into two", "# possible return types for wrapped_function_runner, acting as an operation helper.", "_runner", "=", "wrapped_function_runner", "(", "function", ",", "provided_output_map", ")", "_output_description", "=", "_runner", ".", "output_description", "_output_data_proxy_type", "=", "define_output_data_proxy", "(", "_output_description", ")", "_publishing_data_proxy_type", "=", "define_publishing_data_proxy", "(", "_output_description", ")", "_SourceResource", "=", "SourceResource", "[", "_output_data_proxy_type", ",", "_publishing_data_proxy_type", "]", "@", "classmethod", "def", "name", "(", "cls", ")", "->", "str", ":", "return", "cls", ".", "__basename", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "@", "classmethod", "def", "namespace", "(", "cls", ")", "->", "str", ":", "suffix", "=", "'.'", "+", "cls", ".", "name", "(", ")", "try", ":", "index", "=", "cls", ".", "__basename", ".", "rindex", "(", "suffix", ")", "except", "ValueError", ":", "index", "=", "None", "return", "cls", ".", "__basename", "[", ":", "index", "]", "@", "classmethod", "def", "director", "(", "cls", ",", "context", ":", "_Context", ")", ":", "return", "cls", ".", "operation_director", "@", "classmethod", "def", "signature", "(", "cls", ")", "->", "InputCollectionDescription", ":", "\"\"\"Mapping of named inputs and input type.\n\n Used to determine valid inputs before an Operation node is created.\n\n Overrides OperationDetailsBase.signature() to provide an\n implementation for the bound operation.\n \"\"\"", "return", "cls", ".", "_input_signature_description", "def", "output_description", "(", "self", ")", "->", "OutputCollectionDescription", ":", "\"\"\"Mapping of available outputs and types for an existing Operation node.\n\n Overrides OperationDetailsBase.output_description() to provide an\n implementation for the bound operation.\n \"\"\"", "return", "self", ".", "_output_description", "def", "publishing_data_proxy", "(", "self", ",", "*", ",", "instance", ":", "_SourceResource", ",", "client_id", ":", "int", ")", "->", "_publishing_data_proxy_type", ":", "\"\"\"Factory for Operation output publishing resources.\n\n Used internally when the operation is run with resources provided by instance.\n\n Overrides OperationDetailsBase.publishing_data_proxy() to provide an\n implementation for the bound operation.\n \"\"\"", "assert", "isinstance", "(", "instance", ",", "ResourceManager", ")", "return", "self", ".", "_publishing_data_proxy_type", "(", "instance", "=", "instance", ",", "client_id", "=", "client_id", ")", "def", "output_data_proxy", "(", "self", ",", "instance", ":", "_SourceResource", ")", "->", "_output_data_proxy_type", ":", "assert", "isinstance", "(", "instance", ",", "ResourceManager", ")", "return", "self", ".", "_output_data_proxy_type", "(", "instance", "=", "instance", ")", "def", "__call__", "(", "self", ",", "resources", ":", "PyFunctionRunnerResources", ")", ":", "\"\"\"Execute the operation with provided resources.\n\n Resources are prepared in an execution context with aid of resource_director()\n\n After the first call, output data has been published and is trivially\n available through the output_data_proxy()\n\n Overrides OperationDetailsBase.__call__().\n \"\"\"", "self", ".", "_runner", "(", "resources", ")", "@", "classmethod", "def", "make_uid", "(", "cls", ",", "input", ")", ":", "\"\"\"The unique identity of an operation node tags the output with respect to the input.\n\n Combines information on the Operation details and the input to uniquely\n identify the Operation node.\n\n Arguments:\n input : A (collection of) data source(s) that can provide Fingerprints.\n\n Used internally by the Context to manage ownership of data sources, to\n locate resources for nodes in work graphs, and to manage serialization,\n deserialization, and checkpointing of the work graph.\n\n The UID is a detail of the generic Operation that _should_ be independent\n of the Context details to allow the framework to manage when and where\n an operation is executed.\n\n Note:\n This implementation creates a new identifier with every call, even if *input*\n is the same, because we have not developed our Fingerprinting scheme in gmxapi 0.1+.\n\n Design notes on further refinement:\n TODO: Operations should not single-handedly determine their own uniqueness\n (but they should participate in the determination with the Context).\n\n Context implementations should be allowed to optimize handling of\n equivalent operations in different sessions or work graphs, but we do not\n yet TODO: guarantee that UIDs are globally unique!\n\n The UID should uniquely indicate an operation node based on that node's input.\n We need input fingerprinting to identify equivalent nodes in a work graph\n or distinguish nodes across work graphs.\n\n \"\"\"", "uid", "=", "str", "(", "cls", ".", "__basename", ")", "+", "str", "(", "cls", ".", "__last_uid", ")", "cls", ".", "__last_uid", "+=", "1", "return", "uid", "@", "classmethod", "def", "resource_director", "(", "cls", ",", "*", ",", "input", "=", "None", ",", "output", ":", "_publishing_data_proxy_type", "=", "None", ")", "->", "PyFunctionRunnerResources", ":", "\"\"\"a Director factory that helps build the Session Resources for the function.\n\n The Session launcher provides the director with all of the resources previously\n requested/negotiated/registered by the Operation. The director uses details of\n the operation to build the resources object required by the operation runner.\n\n For the Python Context, the protocol is for the Context to call the\n resource_director instance method, passing input and output containers.\n\n Raises:\n exceptions.TypeError if provided resource type does not match input signature.\n \"\"\"", "resources", "=", "PyFunctionRunnerResources", "(", ")", "resources", ".", "update", "(", "input", ".", "kwargs", ")", "resources", ".", "update", "(", "{", "'output'", ":", "output", "}", ")", "# TODO: Remove this hack when we can better handle Futures of Containers and Future slicing.", "for", "name", "in", "resources", ":", "if", "isinstance", "(", "resources", "[", "name", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "resources", "[", "name", "]", "=", "datamodel", ".", "ndarray", "(", "resources", "[", "name", "]", ")", "# Check data compatibility", "for", "name", ",", "value", "in", "resources", ".", "items", "(", ")", ":", "if", "name", "!=", "'output'", ":", "expected", "=", "cls", ".", "signature", "(", ")", "[", "name", "]", "got", "=", "type", "(", "value", ")", "if", "got", "!=", "expected", ":", "raise", "exceptions", ".", "TypeError", "(", "'Expected {} but got {} for {} resource {}.'", ".", "format", "(", "expected", ",", "got", ",", "cls", ".", "__basename", ",", "name", ")", ")", "return", "resources", "# TODO: (FR4) Update annotations with gmxapi data types. E.g. return -> Future.", "@", "functools", ".", "wraps", "(", "function", ")", "def", "helper", "(", "*", "args", ",", "context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Description of the Operation input (and output) occurs in the", "# decorator closure. By the time this factory is (dynamically) defined,", "# the OperationDetails and ResourceManager are well defined, but not", "# yet instantiated.", "# Inspection of the offered input occurs when this factory is called,", "# and OperationDetails, ResourceManager, and Operation are instantiated.", "# This operation factory is specialized for the default package Context.", "if", "context", "is", "None", ":", "context", "=", "current_context", "(", ")", "else", ":", "raise", "exceptions", ".", "ApiError", "(", "'Non-default context handling not implemented.'", ")", "# This calls a dispatching function that may not be able to reconcile the input", "# and Context capabilities. This is the place to handle various exceptions for", "# whatever reasons this reconciliation cannot occur.", "handle", "=", "OperationDetails", ".", "operation_director", "(", "*", "args", ",", "context", "=", "context", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", "# TODO: NOW: The input fingerprint describes the provided input", "# as (a) ensemble input, (b) static, (c) future. By the time the", "# operation is instantiated, the topology of the node is known.", "# When compared to the InputCollectionDescription, the data compatibility", "# can be determined.", "return", "handle", "# to do: The factory itself needs to be able to register a factory with", "# the context that will be responsible for the Operation handle.", "# The factories need to be able to serve as dispatchers for themselves,", "# since an operation in one context may need to be reconstituted in a", "# different context.", "# The dispatching factory produces a director for a Context,", "# which will register a factory with the operation in that context.", "# The factory function has a DirectorFactory. Director instances talk to a NodeBuilder for a Context to", "# get handles to new operation nodes managed by the context. Part of that process includes registering", "# a DirectorFactory with the Context.", "return", "helper", "return", "decorator" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L2960-L3228
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py
python
multiline_string_lines
(source, include_docstrings=False)
return line_numbers
Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored.
Return line numbers that are within multiline strings.
[ "Return", "line", "numbers", "that", "are", "within", "multiline", "strings", "." ]
def multiline_string_lines(source, include_docstrings=False): """Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored. """ line_numbers = set() previous_token_type = '' try: for t in generate_tokens(source): token_type = t[0] start_row = t[2][0] end_row = t[3][0] if token_type == tokenize.STRING and start_row != end_row: if ( include_docstrings or previous_token_type != tokenize.INDENT ): # We increment by one since we want the contents of the # string. line_numbers |= set(range(1 + start_row, 1 + end_row)) previous_token_type = token_type except (SyntaxError, tokenize.TokenError): pass return line_numbers
[ "def", "multiline_string_lines", "(", "source", ",", "include_docstrings", "=", "False", ")", ":", "line_numbers", "=", "set", "(", ")", "previous_token_type", "=", "''", "try", ":", "for", "t", "in", "generate_tokens", "(", "source", ")", ":", "token_type", "=", "t", "[", "0", "]", "start_row", "=", "t", "[", "2", "]", "[", "0", "]", "end_row", "=", "t", "[", "3", "]", "[", "0", "]", "if", "token_type", "==", "tokenize", ".", "STRING", "and", "start_row", "!=", "end_row", ":", "if", "(", "include_docstrings", "or", "previous_token_type", "!=", "tokenize", ".", "INDENT", ")", ":", "# We increment by one since we want the contents of the", "# string.", "line_numbers", "|=", "set", "(", "range", "(", "1", "+", "start_row", ",", "1", "+", "end_row", ")", ")", "previous_token_type", "=", "token_type", "except", "(", "SyntaxError", ",", "tokenize", ".", "TokenError", ")", ":", "pass", "return", "line_numbers" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L2685-L2714
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
python/misc_utils/arfcn.py
python
is_valid_uplink
(freq)
return result
Returns True if the given frequency is a valid uplink frequency in the given band
Returns True if the given frequency is a valid uplink frequency in the given band
[ "Returns", "True", "if", "the", "given", "frequency", "is", "a", "valid", "uplink", "frequency", "in", "the", "given", "band" ]
def is_valid_uplink(freq): """ Returns True if the given frequency is a valid uplink frequency in the given band """ result = False band = uplink2band(freq) if band is not None: result = True return result
[ "def", "is_valid_uplink", "(", "freq", ")", ":", "result", "=", "False", "band", "=", "uplink2band", "(", "freq", ")", "if", "band", "is", "not", "None", ":", "result", "=", "True", "return", "result" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/python/misc_utils/arfcn.py#L96-L105
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ToggleButton.Create
(*args, **kwargs)
return _controls_.ToggleButton_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ToggleButtonNameStr) -> bool
Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ToggleButtonNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "label", "=", "EmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "ToggleButtonNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ToggleButtonNameStr) -> bool """ return _controls_.ToggleButton_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToggleButton_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2998-L3005
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/ArmoryUtils.py
python
uriReservedToPercent
(theStr)
return theStr
Convert from a regular string to a percent-encoded string
Convert from a regular string to a percent-encoded string
[ "Convert", "from", "a", "regular", "string", "to", "a", "percent", "-", "encoded", "string" ]
def uriReservedToPercent(theStr): """ Convert from a regular string to a percent-encoded string """ #Must replace '%' first, to avoid recursive (and incorrect) replacement! reserved = "%!*'();:@&=+$,/?#[]\" " for c in reserved: theStr = theStr.replace(c, '%%%s' % int_to_hex(ord(c))) return theStr
[ "def", "uriReservedToPercent", "(", "theStr", ")", ":", "#Must replace '%' first, to avoid recursive (and incorrect) replacement!", "reserved", "=", "\"%!*'();:@&=+$,/?#[]\\\" \"", "for", "c", "in", "reserved", ":", "theStr", "=", "theStr", ".", "replace", "(", "c", ",", "'%%%s'", "%", "int_to_hex", "(", "ord", "(", "c", ")", ")", ")", "return", "theStr" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L2926-L2935
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/fir_filter_design.py
python
firwin
(numtaps, cutoff, width=None, window='hamming', pass_zero=True, scale=True, nyq=None, fs=None)
return h
FIR filter design using the window method. This function computes the coefficients of a finite impulse response filter. The filter will have linear phase; it will be Type I if `numtaps` is odd and Type II if `numtaps` is even. Type II filters always have zero response at the Nyquist frequency, so a ValueError exception is raised if firwin is called with `numtaps` even and having a passband whose right end is at the Nyquist frequency. Parameters ---------- numtaps : int Length of the filter (number of coefficients, i.e. the filter order + 1). `numtaps` must be odd if a passband includes the Nyquist frequency. cutoff : float or 1D array_like Cutoff frequency of filter (expressed in the same units as `fs`) OR an array of cutoff frequencies (that is, band edges). In the latter case, the frequencies in `cutoff` should be positive and monotonically increasing between 0 and `fs/2`. The values 0 and `fs/2` must not be included in `cutoff`. width : float or None, optional If `width` is not None, then assume it is the approximate width of the transition region (expressed in the same units as `fs`) for use in Kaiser FIR filter design. In this case, the `window` argument is ignored. window : string or tuple of string and parameter values, optional Desired window to use. See `scipy.signal.get_window` for a list of windows and required parameters. pass_zero : bool, optional If True, the gain at the frequency 0 (i.e. the "DC gain") is 1. Otherwise the DC gain is 0. scale : bool, optional Set to True to scale the coefficients so that the frequency response is exactly unity at a certain frequency. That frequency is either: - 0 (DC) if the first passband starts at 0 (i.e. pass_zero is True) - `fs/2` (the Nyquist frequency) if the first passband ends at `fs/2` (i.e the filter is a single band highpass filter); center of first passband otherwise nyq : float, optional *Deprecated. Use `fs` instead.* This is the Nyquist frequency. Each frequency in `cutoff` must be between 0 and `nyq`. Default is 1. fs : float, optional The sampling frequency of the signal. Each frequency in `cutoff` must be between 0 and ``fs/2``. Default is 2. Returns ------- h : (numtaps,) ndarray Coefficients of length `numtaps` FIR filter. Raises ------ ValueError If any value in `cutoff` is less than or equal to 0 or greater than or equal to ``fs/2``, if the values in `cutoff` are not strictly monotonically increasing, or if `numtaps` is even but a passband includes the Nyquist frequency. See Also -------- firwin2 firls minimum_phase remez Examples -------- Low-pass from 0 to f: >>> from scipy import signal >>> numtaps = 3 >>> f = 0.1 >>> signal.firwin(numtaps, f) array([ 0.06799017, 0.86401967, 0.06799017]) Use a specific window function: >>> signal.firwin(numtaps, f, window='nuttall') array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04]) High-pass ('stop' from 0 to f): >>> signal.firwin(numtaps, f, pass_zero=False) array([-0.00859313, 0.98281375, -0.00859313]) Band-pass: >>> f1, f2 = 0.1, 0.2 >>> signal.firwin(numtaps, [f1, f2], pass_zero=False) array([ 0.06301614, 0.88770441, 0.06301614]) Band-stop: >>> signal.firwin(numtaps, [f1, f2]) array([-0.00801395, 1.0160279 , -0.00801395]) Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]): >>> f3, f4 = 0.3, 0.4 >>> signal.firwin(numtaps, [f1, f2, f3, f4]) array([-0.01376344, 1.02752689, -0.01376344]) Multi-band (passbands are [f1, f2] and [f3,f4]): >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False) array([ 0.04890915, 0.91284326, 0.04890915])
FIR filter design using the window method.
[ "FIR", "filter", "design", "using", "the", "window", "method", "." ]
def firwin(numtaps, cutoff, width=None, window='hamming', pass_zero=True, scale=True, nyq=None, fs=None): """ FIR filter design using the window method. This function computes the coefficients of a finite impulse response filter. The filter will have linear phase; it will be Type I if `numtaps` is odd and Type II if `numtaps` is even. Type II filters always have zero response at the Nyquist frequency, so a ValueError exception is raised if firwin is called with `numtaps` even and having a passband whose right end is at the Nyquist frequency. Parameters ---------- numtaps : int Length of the filter (number of coefficients, i.e. the filter order + 1). `numtaps` must be odd if a passband includes the Nyquist frequency. cutoff : float or 1D array_like Cutoff frequency of filter (expressed in the same units as `fs`) OR an array of cutoff frequencies (that is, band edges). In the latter case, the frequencies in `cutoff` should be positive and monotonically increasing between 0 and `fs/2`. The values 0 and `fs/2` must not be included in `cutoff`. width : float or None, optional If `width` is not None, then assume it is the approximate width of the transition region (expressed in the same units as `fs`) for use in Kaiser FIR filter design. In this case, the `window` argument is ignored. window : string or tuple of string and parameter values, optional Desired window to use. See `scipy.signal.get_window` for a list of windows and required parameters. pass_zero : bool, optional If True, the gain at the frequency 0 (i.e. the "DC gain") is 1. Otherwise the DC gain is 0. scale : bool, optional Set to True to scale the coefficients so that the frequency response is exactly unity at a certain frequency. That frequency is either: - 0 (DC) if the first passband starts at 0 (i.e. pass_zero is True) - `fs/2` (the Nyquist frequency) if the first passband ends at `fs/2` (i.e the filter is a single band highpass filter); center of first passband otherwise nyq : float, optional *Deprecated. Use `fs` instead.* This is the Nyquist frequency. Each frequency in `cutoff` must be between 0 and `nyq`. Default is 1. fs : float, optional The sampling frequency of the signal. Each frequency in `cutoff` must be between 0 and ``fs/2``. Default is 2. Returns ------- h : (numtaps,) ndarray Coefficients of length `numtaps` FIR filter. Raises ------ ValueError If any value in `cutoff` is less than or equal to 0 or greater than or equal to ``fs/2``, if the values in `cutoff` are not strictly monotonically increasing, or if `numtaps` is even but a passband includes the Nyquist frequency. See Also -------- firwin2 firls minimum_phase remez Examples -------- Low-pass from 0 to f: >>> from scipy import signal >>> numtaps = 3 >>> f = 0.1 >>> signal.firwin(numtaps, f) array([ 0.06799017, 0.86401967, 0.06799017]) Use a specific window function: >>> signal.firwin(numtaps, f, window='nuttall') array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04]) High-pass ('stop' from 0 to f): >>> signal.firwin(numtaps, f, pass_zero=False) array([-0.00859313, 0.98281375, -0.00859313]) Band-pass: >>> f1, f2 = 0.1, 0.2 >>> signal.firwin(numtaps, [f1, f2], pass_zero=False) array([ 0.06301614, 0.88770441, 0.06301614]) Band-stop: >>> signal.firwin(numtaps, [f1, f2]) array([-0.00801395, 1.0160279 , -0.00801395]) Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]): >>> f3, f4 = 0.3, 0.4 >>> signal.firwin(numtaps, [f1, f2, f3, f4]) array([-0.01376344, 1.02752689, -0.01376344]) Multi-band (passbands are [f1, f2] and [f3,f4]): >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False) array([ 0.04890915, 0.91284326, 0.04890915]) """ # The major enhancements to this function added in November 2010 were # developed by Tom Krauss (see ticket #902). nyq = 0.5 * _get_fs(fs, nyq) cutoff = np.atleast_1d(cutoff) / float(nyq) # Check for invalid input. if cutoff.ndim > 1: raise ValueError("The cutoff argument must be at most " "one-dimensional.") if cutoff.size == 0: raise ValueError("At least one cutoff frequency must be given.") if cutoff.min() <= 0 or cutoff.max() >= 1: raise ValueError("Invalid cutoff frequency: frequencies must be " "greater than 0 and less than fs/2.") if np.any(np.diff(cutoff) <= 0): raise ValueError("Invalid cutoff frequencies: the frequencies " "must be strictly increasing.") if width is not None: # A width was given. Find the beta parameter of the Kaiser window # and set `window`. This overrides the value of `window` passed in. atten = kaiser_atten(numtaps, float(width) / nyq) beta = kaiser_beta(atten) window = ('kaiser', beta) pass_nyquist = bool(cutoff.size & 1) ^ pass_zero if pass_nyquist and numtaps % 2 == 0: raise ValueError("A filter with an even number of coefficients must " "have zero response at the Nyquist frequency.") # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff # is even, and each pair in cutoff corresponds to passband. cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist)) # `bands` is a 2D array; each row gives the left and right edges of # a passband. bands = cutoff.reshape(-1, 2) # Build up the coefficients. alpha = 0.5 * (numtaps - 1) m = np.arange(0, numtaps) - alpha h = 0 for left, right in bands: h += right * sinc(right * m) h -= left * sinc(left * m) # Get and apply the window function. from .signaltools import get_window win = get_window(window, numtaps, fftbins=False) h *= win # Now handle scaling if desired. if scale: # Get the first passband. left, right = bands[0] if left == 0: scale_frequency = 0.0 elif right == 1: scale_frequency = 1.0 else: scale_frequency = 0.5 * (left + right) c = np.cos(np.pi * m * scale_frequency) s = np.sum(h * c) h /= s return h
[ "def", "firwin", "(", "numtaps", ",", "cutoff", ",", "width", "=", "None", ",", "window", "=", "'hamming'", ",", "pass_zero", "=", "True", ",", "scale", "=", "True", ",", "nyq", "=", "None", ",", "fs", "=", "None", ")", ":", "# The major enhancements to this function added in November 2010 were", "# developed by Tom Krauss (see ticket #902).", "nyq", "=", "0.5", "*", "_get_fs", "(", "fs", ",", "nyq", ")", "cutoff", "=", "np", ".", "atleast_1d", "(", "cutoff", ")", "/", "float", "(", "nyq", ")", "# Check for invalid input.", "if", "cutoff", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"The cutoff argument must be at most \"", "\"one-dimensional.\"", ")", "if", "cutoff", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"At least one cutoff frequency must be given.\"", ")", "if", "cutoff", ".", "min", "(", ")", "<=", "0", "or", "cutoff", ".", "max", "(", ")", ">=", "1", ":", "raise", "ValueError", "(", "\"Invalid cutoff frequency: frequencies must be \"", "\"greater than 0 and less than fs/2.\"", ")", "if", "np", ".", "any", "(", "np", ".", "diff", "(", "cutoff", ")", "<=", "0", ")", ":", "raise", "ValueError", "(", "\"Invalid cutoff frequencies: the frequencies \"", "\"must be strictly increasing.\"", ")", "if", "width", "is", "not", "None", ":", "# A width was given. Find the beta parameter of the Kaiser window", "# and set `window`. This overrides the value of `window` passed in.", "atten", "=", "kaiser_atten", "(", "numtaps", ",", "float", "(", "width", ")", "/", "nyq", ")", "beta", "=", "kaiser_beta", "(", "atten", ")", "window", "=", "(", "'kaiser'", ",", "beta", ")", "pass_nyquist", "=", "bool", "(", "cutoff", ".", "size", "&", "1", ")", "^", "pass_zero", "if", "pass_nyquist", "and", "numtaps", "%", "2", "==", "0", ":", "raise", "ValueError", "(", "\"A filter with an even number of coefficients must \"", "\"have zero response at the Nyquist frequency.\"", ")", "# Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff", "# is even, and each pair in cutoff corresponds to passband.", "cutoff", "=", "np", ".", "hstack", "(", "(", "[", "0.0", "]", "*", "pass_zero", ",", "cutoff", ",", "[", "1.0", "]", "*", "pass_nyquist", ")", ")", "# `bands` is a 2D array; each row gives the left and right edges of", "# a passband.", "bands", "=", "cutoff", ".", "reshape", "(", "-", "1", ",", "2", ")", "# Build up the coefficients.", "alpha", "=", "0.5", "*", "(", "numtaps", "-", "1", ")", "m", "=", "np", ".", "arange", "(", "0", ",", "numtaps", ")", "-", "alpha", "h", "=", "0", "for", "left", ",", "right", "in", "bands", ":", "h", "+=", "right", "*", "sinc", "(", "right", "*", "m", ")", "h", "-=", "left", "*", "sinc", "(", "left", "*", "m", ")", "# Get and apply the window function.", "from", ".", "signaltools", "import", "get_window", "win", "=", "get_window", "(", "window", ",", "numtaps", ",", "fftbins", "=", "False", ")", "h", "*=", "win", "# Now handle scaling if desired.", "if", "scale", ":", "# Get the first passband.", "left", ",", "right", "=", "bands", "[", "0", "]", "if", "left", "==", "0", ":", "scale_frequency", "=", "0.0", "elif", "right", "==", "1", ":", "scale_frequency", "=", "1.0", "else", ":", "scale_frequency", "=", "0.5", "*", "(", "left", "+", "right", ")", "c", "=", "np", ".", "cos", "(", "np", ".", "pi", "*", "m", "*", "scale_frequency", ")", "s", "=", "np", ".", "sum", "(", "h", "*", "c", ")", "h", "/=", "s", "return", "h" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/fir_filter_design.py#L262-L447
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/winres.py
python
load_rc_tool
(conf)
Detect the programs RC or windres, depending on the C/C++ compiler in use
Detect the programs RC or windres, depending on the C/C++ compiler in use
[ "Detect", "the", "programs", "RC", "or", "windres", "depending", "on", "the", "C", "/", "C", "++", "compiler", "in", "use" ]
def load_rc_tool(conf): """ Detect the programs RC or windres, depending on the C/C++ compiler in use """ v = conf.env if not v['WINRC']: conf.fatal('Error: Resource compiler "WINRC" path has not been set.') v['WINRC_TGT_F'] = '/fo' v['WINRC_SRC_F'] = '' v['WINRCFLAGS'] = [ '/l0x0409', # Set default language '/nologo' # Hide Logo ]
[ "def", "load_rc_tool", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "if", "not", "v", "[", "'WINRC'", "]", ":", "conf", ".", "fatal", "(", "'Error: Resource compiler \"WINRC\" path has not been set.'", ")", "v", "[", "'WINRC_TGT_F'", "]", "=", "'/fo'", "v", "[", "'WINRC_SRC_F'", "]", "=", "''", "v", "[", "'WINRCFLAGS'", "]", "=", "[", "'/l0x0409'", ",", "# Set default language", "'/nologo'", "# Hide Logo", "]" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/winres.py#L126-L141
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py
python
_BaseNet.iter_subnets
(self, prefixlen_diff=1, new_prefix=None)
The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), return a list with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network)
The subnets which join to make the current subnet.
[ "The", "subnets", "which", "join", "to", "make", "the", "current", "subnet", "." ]
def iter_subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), return a list with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if not self._is_valid_netmask(str(new_prefixlen)): raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, str(self))) first = IPNetwork('%s/%s' % (str(self.network), str(self._prefixlen + prefixlen_diff)), version=self._version) yield first current = first while True: broadcast = current.broadcast if broadcast == self.broadcast: return new_addr = IPAddress(int(broadcast) + 1, version=self._version) current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)), version=self._version) yield current
[ "def", "iter_subnets", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "self", ".", "_max_prefixlen", ":", "yield", "self", "return", "if", "new_prefix", "is", "not", "None", ":", "if", "new_prefix", "<", "self", ".", "_prefixlen", ":", "raise", "ValueError", "(", "'new prefix must be longer'", ")", "if", "prefixlen_diff", "!=", "1", ":", "raise", "ValueError", "(", "'cannot set prefixlen_diff and new_prefix'", ")", "prefixlen_diff", "=", "new_prefix", "-", "self", ".", "_prefixlen", "if", "prefixlen_diff", "<", "0", ":", "raise", "ValueError", "(", "'prefix length diff must be > 0'", ")", "new_prefixlen", "=", "self", ".", "_prefixlen", "+", "prefixlen_diff", "if", "not", "self", ".", "_is_valid_netmask", "(", "str", "(", "new_prefixlen", ")", ")", ":", "raise", "ValueError", "(", "'prefix length diff %d is invalid for netblock %s'", "%", "(", "new_prefixlen", ",", "str", "(", "self", ")", ")", ")", "first", "=", "IPNetwork", "(", "'%s/%s'", "%", "(", "str", "(", "self", ".", "network", ")", ",", "str", "(", "self", ".", "_prefixlen", "+", "prefixlen_diff", ")", ")", ",", "version", "=", "self", ".", "_version", ")", "yield", "first", "current", "=", "first", "while", "True", ":", "broadcast", "=", "current", ".", "broadcast", "if", "broadcast", "==", "self", ".", "broadcast", ":", "return", "new_addr", "=", "IPAddress", "(", "int", "(", "broadcast", ")", "+", "1", ",", "version", "=", "self", ".", "_version", ")", "current", "=", "IPNetwork", "(", "'%s/%s'", "%", "(", "str", "(", "new_addr", ")", ",", "str", "(", "new_prefixlen", ")", ")", ",", "version", "=", "self", ".", "_version", ")", "yield", "current" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py#L889-L949
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/prettytable.py
python
TableHandler.generate_table
(self, rows)
return table
Generates from a list of rows a PrettyTable object.
Generates from a list of rows a PrettyTable object.
[ "Generates", "from", "a", "list", "of", "rows", "a", "PrettyTable", "object", "." ]
def generate_table(self, rows): """ Generates from a list of rows a PrettyTable object. """ table = PrettyTable(**self.kwargs) for row in self.rows: if len(row[0]) < self.max_row_width: appends = self.max_row_width - len(row[0]) for i in range(1, appends): row[0].append("-") if row[1] == True: self.make_fields_unique(row[0]) table.field_names = row[0] else: table.add_row(row[0]) return table
[ "def", "generate_table", "(", "self", ",", "rows", ")", ":", "table", "=", "PrettyTable", "(", "*", "*", "self", ".", "kwargs", ")", "for", "row", "in", "self", ".", "rows", ":", "if", "len", "(", "row", "[", "0", "]", ")", "<", "self", ".", "max_row_width", ":", "appends", "=", "self", ".", "max_row_width", "-", "len", "(", "row", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "appends", ")", ":", "row", "[", "0", "]", ".", "append", "(", "\"-\"", ")", "if", "row", "[", "1", "]", "==", "True", ":", "self", ".", "make_fields_unique", "(", "row", "[", "0", "]", ")", "table", ".", "field_names", "=", "row", "[", "0", "]", "else", ":", "table", ".", "add_row", "(", "row", "[", "0", "]", ")", "return", "table" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/prettytable.py#L1403-L1419
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/numpy_support.py
python
_check_struct_alignment
(rec, fields)
Check alignment compatibility with Numpy
Check alignment compatibility with Numpy
[ "Check", "alignment", "compatibility", "with", "Numpy" ]
def _check_struct_alignment(rec, fields): """Check alignment compatibility with Numpy""" if rec.aligned: for k, dt in zip(fields['names'], fields['formats']): llvm_align = rec.alignof(k) npy_align = dt.alignment if llvm_align is not None and npy_align != llvm_align: msg = ( 'NumPy is using a different alignment ({}) ' 'than Numba/LLVM ({}) for {}. ' 'This is likely a NumPy bug.' ) raise ValueError(msg.format(npy_align, llvm_align, dt))
[ "def", "_check_struct_alignment", "(", "rec", ",", "fields", ")", ":", "if", "rec", ".", "aligned", ":", "for", "k", ",", "dt", "in", "zip", "(", "fields", "[", "'names'", "]", ",", "fields", "[", "'formats'", "]", ")", ":", "llvm_align", "=", "rec", ".", "alignof", "(", "k", ")", "npy_align", "=", "dt", ".", "alignment", "if", "llvm_align", "is", "not", "None", "and", "npy_align", "!=", "llvm_align", ":", "msg", "=", "(", "'NumPy is using a different alignment ({}) '", "'than Numba/LLVM ({}) for {}. '", "'This is likely a NumPy bug.'", ")", "raise", "ValueError", "(", "msg", ".", "format", "(", "npy_align", ",", "llvm_align", ",", "dt", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/numpy_support.py#L182-L194
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py
python
update_all_medoids
(pairwise_distances, predictions, labels, chosen_ids, margin_multiplier, margin_type)
return chosen_ids
Updates all cluster medoids a cluster at a time. Args: pairwise_distances: 2-D Tensor of pairwise distances. predictions: 1-D Tensor of predicted cluster assignment. labels: 1-D Tensor of ground truth cluster assignment. chosen_ids: 1-D Tensor of cluster centroid indices. margin_multiplier: multiplication constant. margin_type: Type of structured margin to use. Default is nmi. Returns: chosen_ids: Updated 1-D Tensor of cluster centroid indices.
Updates all cluster medoids a cluster at a time.
[ "Updates", "all", "cluster", "medoids", "a", "cluster", "at", "a", "time", "." ]
def update_all_medoids(pairwise_distances, predictions, labels, chosen_ids, margin_multiplier, margin_type): """Updates all cluster medoids a cluster at a time. Args: pairwise_distances: 2-D Tensor of pairwise distances. predictions: 1-D Tensor of predicted cluster assignment. labels: 1-D Tensor of ground truth cluster assignment. chosen_ids: 1-D Tensor of cluster centroid indices. margin_multiplier: multiplication constant. margin_type: Type of structured margin to use. Default is nmi. Returns: chosen_ids: Updated 1-D Tensor of cluster centroid indices. """ def func_cond_augmented_pam(iteration, chosen_ids): del chosen_ids # Unused argument. return iteration < num_classes def func_body_augmented_pam(iteration, chosen_ids): """Call the update_medoid_per_cluster subroutine.""" mask = math_ops.equal( math_ops.cast(predictions, dtypes.int64), math_ops.cast(iteration, dtypes.int64)) this_cluster_ids = array_ops.where(mask) pairwise_distances_subset = array_ops.transpose( array_ops.gather( array_ops.transpose( array_ops.gather(pairwise_distances, this_cluster_ids)), this_cluster_ids)) chosen_ids = update_medoid_per_cluster(pairwise_distances, pairwise_distances_subset, labels, chosen_ids, this_cluster_ids, iteration, margin_multiplier, margin_type) return iteration + 1, chosen_ids unique_class_ids = array_ops.unique(labels)[0] num_classes = array_ops.size(unique_class_ids) iteration = array_ops.constant(0) _, chosen_ids = control_flow_ops.while_loop( func_cond_augmented_pam, func_body_augmented_pam, [iteration, chosen_ids]) return chosen_ids
[ "def", "update_all_medoids", "(", "pairwise_distances", ",", "predictions", ",", "labels", ",", "chosen_ids", ",", "margin_multiplier", ",", "margin_type", ")", ":", "def", "func_cond_augmented_pam", "(", "iteration", ",", "chosen_ids", ")", ":", "del", "chosen_ids", "# Unused argument.", "return", "iteration", "<", "num_classes", "def", "func_body_augmented_pam", "(", "iteration", ",", "chosen_ids", ")", ":", "\"\"\"Call the update_medoid_per_cluster subroutine.\"\"\"", "mask", "=", "math_ops", ".", "equal", "(", "math_ops", ".", "cast", "(", "predictions", ",", "dtypes", ".", "int64", ")", ",", "math_ops", ".", "cast", "(", "iteration", ",", "dtypes", ".", "int64", ")", ")", "this_cluster_ids", "=", "array_ops", ".", "where", "(", "mask", ")", "pairwise_distances_subset", "=", "array_ops", ".", "transpose", "(", "array_ops", ".", "gather", "(", "array_ops", ".", "transpose", "(", "array_ops", ".", "gather", "(", "pairwise_distances", ",", "this_cluster_ids", ")", ")", ",", "this_cluster_ids", ")", ")", "chosen_ids", "=", "update_medoid_per_cluster", "(", "pairwise_distances", ",", "pairwise_distances_subset", ",", "labels", ",", "chosen_ids", ",", "this_cluster_ids", ",", "iteration", ",", "margin_multiplier", ",", "margin_type", ")", "return", "iteration", "+", "1", ",", "chosen_ids", "unique_class_ids", "=", "array_ops", ".", "unique", "(", "labels", ")", "[", "0", "]", "num_classes", "=", "array_ops", ".", "size", "(", "unique_class_ids", ")", "iteration", "=", "array_ops", ".", "constant", "(", "0", ")", "_", ",", "chosen_ids", "=", "control_flow_ops", ".", "while_loop", "(", "func_cond_augmented_pam", ",", "func_body_augmented_pam", ",", "[", "iteration", ",", "chosen_ids", "]", ")", "return", "chosen_ids" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/losses/python/metric_learning/metric_loss_ops.py#L831-L877
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
libpyclingo/clingo/application.py
python
Application.validate_options
(self)
Function to validate custom options. Returns ------- This function should return false if option validation fails.
Function to validate custom options.
[ "Function", "to", "validate", "custom", "options", "." ]
def validate_options(self) -> bool: ''' Function to validate custom options. Returns ------- This function should return false if option validation fails. '''
[ "def", "validate_options", "(", "self", ")", "->", "bool", ":" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/application.py#L182-L189
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/tpu/python/tpu/tpu.py
python
batch_parallel
(computation, inputs=None, num_shards=1, infeed_queue=None, global_tpu_id=None, name=None)
return shard( computation, inputs, num_shards=num_shards, infeed_queue=infeed_queue, global_tpu_id=global_tpu_id, name=name)
Shards `computation` along the batch dimension for parallel execution. Convenience wrapper around shard(). `inputs` must be a list of Tensors or None (equivalent to an empty list). Each input is split into `num_shards` pieces along the 0-th dimension, and computation is applied to each shard in parallel. Tensors are broadcast to all shards if they are lexically captured by `computation`. e.g., x = tf.constant(7) def computation(): return x + 3 ... = shard(computation, ...) The outputs from all shards are concatenated back together along their 0-th dimension. Inputs and outputs of the computation must be at least rank-1 Tensors. Args: computation: a Python function that builds a computation to apply to each shard of the input. inputs: a list of input tensors or None (equivalent to an empty list). The 0-th dimension of each Tensor must have size divisible by `num_shards`. num_shards: the number of shards. infeed_queue: if not None, the InfeedQueue from which to append a tuple of arguments as inputs to `computation`. global_tpu_id: if not None, a Numpy 2D array indicating the global id of each TPU device in the system. The outer dimension of the array is host task id, and the inner dimension is device ordinal, so e.g., global_tpu_id[x][y] indicates the global id of device /task:x/device:TPU_NODE:y. name: name of the operator. Returns: A list of output tensors. Raises: ValueError: if num_shards <= 0
Shards `computation` along the batch dimension for parallel execution.
[ "Shards", "computation", "along", "the", "batch", "dimension", "for", "parallel", "execution", "." ]
def batch_parallel(computation, inputs=None, num_shards=1, infeed_queue=None, global_tpu_id=None, name=None): """Shards `computation` along the batch dimension for parallel execution. Convenience wrapper around shard(). `inputs` must be a list of Tensors or None (equivalent to an empty list). Each input is split into `num_shards` pieces along the 0-th dimension, and computation is applied to each shard in parallel. Tensors are broadcast to all shards if they are lexically captured by `computation`. e.g., x = tf.constant(7) def computation(): return x + 3 ... = shard(computation, ...) The outputs from all shards are concatenated back together along their 0-th dimension. Inputs and outputs of the computation must be at least rank-1 Tensors. Args: computation: a Python function that builds a computation to apply to each shard of the input. inputs: a list of input tensors or None (equivalent to an empty list). The 0-th dimension of each Tensor must have size divisible by `num_shards`. num_shards: the number of shards. infeed_queue: if not None, the InfeedQueue from which to append a tuple of arguments as inputs to `computation`. global_tpu_id: if not None, a Numpy 2D array indicating the global id of each TPU device in the system. The outer dimension of the array is host task id, and the inner dimension is device ordinal, so e.g., global_tpu_id[x][y] indicates the global id of device /task:x/device:TPU_NODE:y. name: name of the operator. Returns: A list of output tensors. Raises: ValueError: if num_shards <= 0 """ return shard( computation, inputs, num_shards=num_shards, infeed_queue=infeed_queue, global_tpu_id=global_tpu_id, name=name)
[ "def", "batch_parallel", "(", "computation", ",", "inputs", "=", "None", ",", "num_shards", "=", "1", ",", "infeed_queue", "=", "None", ",", "global_tpu_id", "=", "None", ",", "name", "=", "None", ")", ":", "return", "shard", "(", "computation", ",", "inputs", ",", "num_shards", "=", "num_shards", ",", "infeed_queue", "=", "infeed_queue", ",", "global_tpu_id", "=", "global_tpu_id", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tpu/python/tpu/tpu.py#L491-L544
martinmoene/string-view-lite
6c2ba8672db54a355a6d76c820dd46ecda254038
script/upload-conan.py
python
createConanPackage
( args )
Create conan package and upload it.
Create conan package and upload it.
[ "Create", "conan", "package", "and", "upload", "it", "." ]
def createConanPackage( args ): """Create conan package and upload it.""" cmd = tpl_conan_create.format(usr=args.user, chn=args.channel) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: subprocess.call( cmd, shell=False )
[ "def", "createConanPackage", "(", "args", ")", ":", "cmd", "=", "tpl_conan_create", ".", "format", "(", "usr", "=", "args", ".", "user", ",", "chn", "=", "args", ".", "channel", ")", "if", "args", ".", "verbose", ":", "print", "(", "\"> {}\"", ".", "format", "(", "cmd", ")", ")", "if", "not", "args", ".", "dry_run", ":", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "False", ")" ]
https://github.com/martinmoene/string-view-lite/blob/6c2ba8672db54a355a6d76c820dd46ecda254038/script/upload-conan.py#L38-L44
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/solvers/conic_solvers/glpk_mi_conif.py
python
GLPK_MI.invert
(self, solution, inverse_data)
Returns the solution to the original problem given the inverse_data.
Returns the solution to the original problem given the inverse_data.
[ "Returns", "the", "solution", "to", "the", "original", "problem", "given", "the", "inverse_data", "." ]
def invert(self, solution, inverse_data): """Returns the solution to the original problem given the inverse_data. """ status = solution['status'] if status in s.SOLUTION_PRESENT: opt_val = solution['value'] + inverse_data[s.OFFSET] primal_vars = {inverse_data[self.VAR_ID]: solution['primal']} return Solution(status, opt_val, primal_vars, None, {}) else: return failure_solution(status)
[ "def", "invert", "(", "self", ",", "solution", ",", "inverse_data", ")", ":", "status", "=", "solution", "[", "'status'", "]", "if", "status", "in", "s", ".", "SOLUTION_PRESENT", ":", "opt_val", "=", "solution", "[", "'value'", "]", "+", "inverse_data", "[", "s", ".", "OFFSET", "]", "primal_vars", "=", "{", "inverse_data", "[", "self", ".", "VAR_ID", "]", ":", "solution", "[", "'primal'", "]", "}", "return", "Solution", "(", "status", ",", "opt_val", ",", "primal_vars", ",", "None", ",", "{", "}", ")", "else", ":", "return", "failure_solution", "(", "status", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/solvers/conic_solvers/glpk_mi_conif.py#L102-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/numba_.py
python
make_rolling_apply
( func: Callable[..., Scalar], args: Tuple, nogil: bool, parallel: bool, nopython: bool, )
return roll_apply
Creates a JITted rolling apply function with a JITted version of the user's function. Parameters ---------- func : function function to be applied to each window and will be JITed args : tuple *args to be passed into the function nogil : bool nogil parameter from engine_kwargs for numba.jit parallel : bool parallel parameter from engine_kwargs for numba.jit nopython : bool nopython parameter from engine_kwargs for numba.jit Returns ------- Numba function
Creates a JITted rolling apply function with a JITted version of the user's function.
[ "Creates", "a", "JITted", "rolling", "apply", "function", "with", "a", "JITted", "version", "of", "the", "user", "s", "function", "." ]
def make_rolling_apply( func: Callable[..., Scalar], args: Tuple, nogil: bool, parallel: bool, nopython: bool, ): """ Creates a JITted rolling apply function with a JITted version of the user's function. Parameters ---------- func : function function to be applied to each window and will be JITed args : tuple *args to be passed into the function nogil : bool nogil parameter from engine_kwargs for numba.jit parallel : bool parallel parameter from engine_kwargs for numba.jit nopython : bool nopython parameter from engine_kwargs for numba.jit Returns ------- Numba function """ numba = import_optional_dependency("numba") if parallel: loop_range = numba.prange else: loop_range = range if isinstance(func, numba.targets.registry.CPUDispatcher): # Don't jit a user passed jitted function numba_func = func else: @numba.generated_jit(nopython=nopython, nogil=nogil, parallel=parallel) def numba_func(window, *_args): if getattr(np, func.__name__, False) is func or isinstance( func, types.BuiltinFunctionType ): jf = func else: jf = numba.jit(func, nopython=nopython, nogil=nogil) def impl(window, *_args): return jf(window, *_args) return impl @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def roll_apply( values: np.ndarray, begin: np.ndarray, end: np.ndarray, minimum_periods: int, ) -> np.ndarray: result = np.empty(len(begin)) for i in loop_range(len(result)): start = begin[i] stop = end[i] window = values[start:stop] count_nan = np.sum(np.isnan(window)) if len(window) - count_nan >= minimum_periods: result[i] = numba_func(window, *args) else: result[i] = np.nan return result return roll_apply
[ "def", "make_rolling_apply", "(", "func", ":", "Callable", "[", "...", ",", "Scalar", "]", ",", "args", ":", "Tuple", ",", "nogil", ":", "bool", ",", "parallel", ":", "bool", ",", "nopython", ":", "bool", ",", ")", ":", "numba", "=", "import_optional_dependency", "(", "\"numba\"", ")", "if", "parallel", ":", "loop_range", "=", "numba", ".", "prange", "else", ":", "loop_range", "=", "range", "if", "isinstance", "(", "func", ",", "numba", ".", "targets", ".", "registry", ".", "CPUDispatcher", ")", ":", "# Don't jit a user passed jitted function", "numba_func", "=", "func", "else", ":", "@", "numba", ".", "generated_jit", "(", "nopython", "=", "nopython", ",", "nogil", "=", "nogil", ",", "parallel", "=", "parallel", ")", "def", "numba_func", "(", "window", ",", "*", "_args", ")", ":", "if", "getattr", "(", "np", ",", "func", ".", "__name__", ",", "False", ")", "is", "func", "or", "isinstance", "(", "func", ",", "types", ".", "BuiltinFunctionType", ")", ":", "jf", "=", "func", "else", ":", "jf", "=", "numba", ".", "jit", "(", "func", ",", "nopython", "=", "nopython", ",", "nogil", "=", "nogil", ")", "def", "impl", "(", "window", ",", "*", "_args", ")", ":", "return", "jf", "(", "window", ",", "*", "_args", ")", "return", "impl", "@", "numba", ".", "jit", "(", "nopython", "=", "nopython", ",", "nogil", "=", "nogil", ",", "parallel", "=", "parallel", ")", "def", "roll_apply", "(", "values", ":", "np", ".", "ndarray", ",", "begin", ":", "np", ".", "ndarray", ",", "end", ":", "np", ".", "ndarray", ",", "minimum_periods", ":", "int", ",", ")", "->", "np", ".", "ndarray", ":", "result", "=", "np", ".", "empty", "(", "len", "(", "begin", ")", ")", "for", "i", "in", "loop_range", "(", "len", "(", "result", ")", ")", ":", "start", "=", "begin", "[", "i", "]", "stop", "=", "end", "[", "i", "]", "window", "=", "values", "[", "start", ":", "stop", "]", "count_nan", "=", "np", ".", "sum", "(", "np", ".", "isnan", "(", "window", ")", ")", "if", "len", "(", "window", ")", "-", "count_nan", ">=", "minimum_periods", ":", "result", "[", "i", "]", "=", "numba_func", "(", "window", ",", "*", "args", ")", "else", ":", "result", "[", "i", "]", "=", "np", ".", "nan", "return", "result", "return", "roll_apply" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/numba_.py#L10-L80
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
utils/grid.py
python
MainWindow.__set_bigger_cb
(self, widget)
! Set Bigger Callback @param self this object @param widget widget @return none
! Set Bigger Callback
[ "!", "Set", "Bigger", "Callback" ]
def __set_bigger_cb(self, widget): """! Set Bigger Callback @param self this object @param widget widget @return none """ self.__render.set_bigger_zoom()
[ "def", "__set_bigger_cb", "(", "self", ",", "widget", ")", ":", "self", ".", "__render", ".", "set_bigger_zoom", "(", ")" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/utils/grid.py#L1569-L1575
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/framework/foundation/future.py
python
Future.traceback
(self, timeout=None)
Access the traceback of the exception raised by the computation. This method may return immediately or may block. Args: timeout: The length of time in seconds to wait for the computation to terminate or be cancelled, or None if this method should block until the computation is terminated or is cancelled no matter how long that takes. Returns: The traceback of the exception raised by the computation, or None if the computation did not raise an exception. Raises: TimeoutError: If a timeout value is passed and the computation does not terminate within the allotted time. CancelledError: If the computation was cancelled.
Access the traceback of the exception raised by the computation.
[ "Access", "the", "traceback", "of", "the", "exception", "raised", "by", "the", "computation", "." ]
def traceback(self, timeout=None): """Access the traceback of the exception raised by the computation. This method may return immediately or may block. Args: timeout: The length of time in seconds to wait for the computation to terminate or be cancelled, or None if this method should block until the computation is terminated or is cancelled no matter how long that takes. Returns: The traceback of the exception raised by the computation, or None if the computation did not raise an exception. Raises: TimeoutError: If a timeout value is passed and the computation does not terminate within the allotted time. CancelledError: If the computation was cancelled. """ raise NotImplementedError()
[ "def", "traceback", "(", "self", ",", "timeout", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/foundation/future.py#L186-L206
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Runner.py
python
Consumer.run
(self)
Processes a single task
Processes a single task
[ "Processes", "a", "single", "task" ]
def run(self): """ Processes a single task """ try: if not self.spawner.master.stop: self.spawner.master.process_task(self.task) finally: self.spawner.sem.release() self.spawner.master.out.put(self.task) self.task = None self.spawner = None
[ "def", "run", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "spawner", ".", "master", ".", "stop", ":", "self", ".", "spawner", ".", "master", ".", "process_task", "(", "self", ".", "task", ")", "finally", ":", "self", ".", "spawner", ".", "sem", ".", "release", "(", ")", "self", ".", "spawner", ".", "master", ".", "out", ".", "put", "(", "self", ".", "task", ")", "self", ".", "task", "=", "None", "self", ".", "spawner", "=", "None" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Runner.py#L74-L85
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/backend.py
python
Backend.get_supported_devices
()
return devices
Return a list of devices supported by pymcuprog. This will be the list of devices with a corresponding device file :returns: List of device names
Return a list of devices supported by pymcuprog.
[ "Return", "a", "list", "of", "devices", "supported", "by", "pymcuprog", "." ]
def get_supported_devices(): """ Return a list of devices supported by pymcuprog. This will be the list of devices with a corresponding device file :returns: List of device names """ devices = [] for filename in os.listdir(DEVICE_FOLDER): if filename not in NON_DEVICEFILES and filename.endswith('.py'): devices.append(filename.split('.py')[0]) return devices
[ "def", "get_supported_devices", "(", ")", ":", "devices", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "DEVICE_FOLDER", ")", ":", "if", "filename", "not", "in", "NON_DEVICEFILES", "and", "filename", ".", "endswith", "(", "'.py'", ")", ":", "devices", ".", "append", "(", "filename", ".", "split", "(", "'.py'", ")", "[", "0", "]", ")", "return", "devices" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/backend.py#L92-L104
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
libcxx/utils/google-benchmark/tools/compare.py
python
check_inputs
(in1, in2, flags)
Perform checking on the user provided inputs and diagnose any abnormalities
Perform checking on the user provided inputs and diagnose any abnormalities
[ "Perform", "checking", "on", "the", "user", "provided", "inputs", "and", "diagnose", "any", "abnormalities" ]
def check_inputs(in1, in2, flags): """ Perform checking on the user provided inputs and diagnose any abnormalities """ in1_kind, in1_err = classify_input_file(in1) in2_kind, in2_err = classify_input_file(in2) output_file = find_benchmark_flag('--benchmark_out=', flags) output_type = find_benchmark_flag('--benchmark_out_format=', flags) if in1_kind == IT_Executable and in2_kind == IT_Executable and output_file: print(("WARNING: '--benchmark_out=%s' will be passed to both " "benchmarks causing it to be overwritten") % output_file) if in1_kind == IT_JSON and in2_kind == IT_JSON and len(flags) > 0: print("WARNING: passing optional flags has no effect since both " "inputs are JSON") if output_type is not None and output_type != 'json': print(("ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" " is not supported.") % output_type) sys.exit(1)
[ "def", "check_inputs", "(", "in1", ",", "in2", ",", "flags", ")", ":", "in1_kind", ",", "in1_err", "=", "classify_input_file", "(", "in1", ")", "in2_kind", ",", "in2_err", "=", "classify_input_file", "(", "in2", ")", "output_file", "=", "find_benchmark_flag", "(", "'--benchmark_out='", ",", "flags", ")", "output_type", "=", "find_benchmark_flag", "(", "'--benchmark_out_format='", ",", "flags", ")", "if", "in1_kind", "==", "IT_Executable", "and", "in2_kind", "==", "IT_Executable", "and", "output_file", ":", "print", "(", "(", "\"WARNING: '--benchmark_out=%s' will be passed to both \"", "\"benchmarks causing it to be overwritten\"", ")", "%", "output_file", ")", "if", "in1_kind", "==", "IT_JSON", "and", "in2_kind", "==", "IT_JSON", "and", "len", "(", "flags", ")", ">", "0", ":", "print", "(", "\"WARNING: passing optional flags has no effect since both \"", "\"inputs are JSON\"", ")", "if", "output_type", "is", "not", "None", "and", "output_type", "!=", "'json'", ":", "print", "(", "(", "\"ERROR: passing '--benchmark_out_format=%s' to 'compare.py`\"", "\" is not supported.\"", ")", "%", "output_type", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/libcxx/utils/google-benchmark/tools/compare.py#L16-L33
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
elf/utils_elf.py
python
GCWrapper.Stop
(self)
Stop all game environments. :func:`Start()` cannot be called again after :func:`Stop()` has been called.
Stop all game environments. :func:`Start()` cannot be called again after :func:`Stop()` has been called.
[ "Stop", "all", "game", "environments", ".", ":", "func", ":", "Start", "()", "cannot", "be", "called", "again", "after", ":", "func", ":", "Stop", "()", "has", "been", "called", "." ]
def Stop(self): '''Stop all game environments. :func:`Start()` cannot be called again after :func:`Stop()` has been called.''' self.GC.Stop()
[ "def", "Stop", "(", "self", ")", ":", "self", ".", "GC", ".", "Stop", "(", ")" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/elf/utils_elf.py#L388-L390
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/image_tool.py
python
ImageTool.resize_by_hw_range
(self, rng, inplace=True)
return self.resize_by_hw_list(size_list, 1, inplace)
Args: rng: a tuple ((hbegin[0], hend[0]), (wbegin[1], wend[1])), include begin, exclude end inplace: inplace imgs or not (return new_imgs)
Args: rng: a tuple ((hbegin[0], hend[0]), (wbegin[1], wend[1])), include begin, exclude end inplace: inplace imgs or not (return new_imgs)
[ "Args", ":", "rng", ":", "a", "tuple", "((", "hbegin", "[", "0", "]", "hend", "[", "0", "]", ")", "(", "wbegin", "[", "1", "]", "wend", "[", "1", "]", "))", "include", "begin", "exclude", "end", "inplace", ":", "inplace", "imgs", "or", "not", "(", "return", "new_imgs", ")" ]
def resize_by_hw_range(self, rng, inplace=True): ''' Args: rng: a tuple ((hbegin[0], hend[0]), (wbegin[1], wend[1])), include begin, exclude end inplace: inplace imgs or not (return new_imgs) ''' if rng[0][1] - rng[0][0] != rng[1][1] - rng[1][0]: raise Exception('num of widths and heights must be the same!') heights = range(rng[0][0], rng[0][1]) widths = range(rng[1][0], rng[1][1]) size_list = zip(heights, widths) return self.resize_by_hw_list(size_list, 1, inplace)
[ "def", "resize_by_hw_range", "(", "self", ",", "rng", ",", "inplace", "=", "True", ")", ":", "if", "rng", "[", "0", "]", "[", "1", "]", "-", "rng", "[", "0", "]", "[", "0", "]", "!=", "rng", "[", "1", "]", "[", "1", "]", "-", "rng", "[", "1", "]", "[", "0", "]", ":", "raise", "Exception", "(", "'num of widths and heights must be the same!'", ")", "heights", "=", "range", "(", "rng", "[", "0", "]", "[", "0", "]", ",", "rng", "[", "0", "]", "[", "1", "]", ")", "widths", "=", "range", "(", "rng", "[", "1", "]", "[", "0", "]", ",", "rng", "[", "1", "]", "[", "1", "]", ")", "size_list", "=", "zip", "(", "heights", ",", "widths", ")", "return", "self", ".", "resize_by_hw_list", "(", "size_list", ",", "1", ",", "inplace", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/image_tool.py#L302-L313
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBCommandInterpreter.HandleCommandsFromFile
(self, file, override_context, options, result)
return _lldb.SBCommandInterpreter_HandleCommandsFromFile(self, file, override_context, options, result)
HandleCommandsFromFile(SBCommandInterpreter self, SBFileSpec file, SBExecutionContext override_context, SBCommandInterpreterRunOptions options, SBCommandReturnObject result)
HandleCommandsFromFile(SBCommandInterpreter self, SBFileSpec file, SBExecutionContext override_context, SBCommandInterpreterRunOptions options, SBCommandReturnObject result)
[ "HandleCommandsFromFile", "(", "SBCommandInterpreter", "self", "SBFileSpec", "file", "SBExecutionContext", "override_context", "SBCommandInterpreterRunOptions", "options", "SBCommandReturnObject", "result", ")" ]
def HandleCommandsFromFile(self, file, override_context, options, result): """HandleCommandsFromFile(SBCommandInterpreter self, SBFileSpec file, SBExecutionContext override_context, SBCommandInterpreterRunOptions options, SBCommandReturnObject result)""" return _lldb.SBCommandInterpreter_HandleCommandsFromFile(self, file, override_context, options, result)
[ "def", "HandleCommandsFromFile", "(", "self", ",", "file", ",", "override_context", ",", "options", ",", "result", ")", ":", "return", "_lldb", ".", "SBCommandInterpreter_HandleCommandsFromFile", "(", "self", ",", "file", ",", "override_context", ",", "options", ",", "result", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2778-L2780
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/experimental/ops/optimization.py
python
model
()
return _apply_fn
A transformation that models performance. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`.
A transformation that models performance.
[ "A", "transformation", "that", "models", "performance", "." ]
def model(): """A transformation that models performance. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. """ def _apply_fn(dataset): """Function from `Dataset` to `Dataset` that applies the transformation.""" return dataset_ops._ModelDataset(dataset) # pylint: disable=protected-access return _apply_fn
[ "def", "model", "(", ")", ":", "def", "_apply_fn", "(", "dataset", ")", ":", "\"\"\"Function from `Dataset` to `Dataset` that applies the transformation.\"\"\"", "return", "dataset_ops", ".", "_ModelDataset", "(", "dataset", ")", "# pylint: disable=protected-access", "return", "_apply_fn" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/experimental/ops/optimization.py#L47-L59
intel/ideep
b57539e4608e75f80dbc5c2784643d5f2f242003
python/ideep4py/__init__.py
python
array
(x, itype=dat_array)
Create a :class:`ideep4py.mdarray` object according to ``x``. Args: array (numpy.ndarray or ideep4py.mdarray): if ``x`` is numpy.ndarray not in C contiguous, it will be converted to C contiguous before ideep4py.mdarray created. itype (=data_type): ideep4py.mdarray created is optimized according ``itype`` flag. Returns: Instance of :class:`ideep4py.mdarray`.
Create a :class:`ideep4py.mdarray` object according to ``x``.
[ "Create", "a", ":", "class", ":", "ideep4py", ".", "mdarray", "object", "according", "to", "x", "." ]
def array(x, itype=dat_array): """Create a :class:`ideep4py.mdarray` object according to ``x``. Args: array (numpy.ndarray or ideep4py.mdarray): if ``x`` is numpy.ndarray not in C contiguous, it will be converted to C contiguous before ideep4py.mdarray created. itype (=data_type): ideep4py.mdarray created is optimized according ``itype`` flag. Returns: Instance of :class:`ideep4py.mdarray`. """ if isinstance(x, numpy.ndarray) and \ x.dtype == numpy.dtype('float32'): if x.flags.contiguous is False: x = numpy.ascontiguousarray(x) return mdarray(x, itype) else: return x
[ "def", "array", "(", "x", ",", "itype", "=", "dat_array", ")", ":", "if", "isinstance", "(", "x", ",", "numpy", ".", "ndarray", ")", "and", "x", ".", "dtype", "==", "numpy", ".", "dtype", "(", "'float32'", ")", ":", "if", "x", ".", "flags", ".", "contiguous", "is", "False", ":", "x", "=", "numpy", ".", "ascontiguousarray", "(", "x", ")", "return", "mdarray", "(", "x", ",", "itype", ")", "else", ":", "return", "x" ]
https://github.com/intel/ideep/blob/b57539e4608e75f80dbc5c2784643d5f2f242003/python/ideep4py/__init__.py#L41-L61
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/text_format.py
python
Merge
(text, message)
return MergeLines(text.split('\n'), message)
Parses an ASCII representation of a protocol message into a message. Like Parse(), but allows repeated values for a non-repeated field, and uses the last one. Args: text: Message ASCII representation. message: A protocol buffer message to merge into. Returns: The same message passed as argument. Raises: ParseError: On ASCII parsing problems.
Parses an ASCII representation of a protocol message into a message.
[ "Parses", "an", "ASCII", "representation", "of", "a", "protocol", "message", "into", "a", "message", "." ]
def Merge(text, message): """Parses an ASCII representation of a protocol message into a message. Like Parse(), but allows repeated values for a non-repeated field, and uses the last one. Args: text: Message ASCII representation. message: A protocol buffer message to merge into. Returns: The same message passed as argument. Raises: ParseError: On ASCII parsing problems. """ return MergeLines(text.split('\n'), message)
[ "def", "Merge", "(", "text", ",", "message", ")", ":", "return", "MergeLines", "(", "text", ".", "split", "(", "'\\n'", ")", ",", "message", ")" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/text_format.py#L253-L269
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py
python
random_saturation
(image, lower, upper, seed=None)
return adjust_saturation(image, saturation_factor)
Adjust the saturation of RGB images by a random factor. Equivalent to `adjust_saturation()` but uses a `saturation_factor` randomly picked in the interval `[lower, upper]`. Args: image: RGB image or images. Size of the last dimension must be 3. lower: float. Lower bound for the random saturation factor. upper: float. Upper bound for the random saturation factor. seed: An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed. Returns: Adjusted image(s), same shape and DType as `image`. Raises: ValueError: if `upper <= lower` or if `lower < 0`.
Adjust the saturation of RGB images by a random factor.
[ "Adjust", "the", "saturation", "of", "RGB", "images", "by", "a", "random", "factor", "." ]
def random_saturation(image, lower, upper, seed=None): """Adjust the saturation of RGB images by a random factor. Equivalent to `adjust_saturation()` but uses a `saturation_factor` randomly picked in the interval `[lower, upper]`. Args: image: RGB image or images. Size of the last dimension must be 3. lower: float. Lower bound for the random saturation factor. upper: float. Upper bound for the random saturation factor. seed: An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed. Returns: Adjusted image(s), same shape and DType as `image`. Raises: ValueError: if `upper <= lower` or if `lower < 0`. """ if upper <= lower: raise ValueError('upper must be > lower.') if lower < 0: raise ValueError('lower must be non-negative.') # Pick a float in [lower, upper] saturation_factor = random_ops.random_uniform([], lower, upper, seed=seed) return adjust_saturation(image, saturation_factor)
[ "def", "random_saturation", "(", "image", ",", "lower", ",", "upper", ",", "seed", "=", "None", ")", ":", "if", "upper", "<=", "lower", ":", "raise", "ValueError", "(", "'upper must be > lower.'", ")", "if", "lower", "<", "0", ":", "raise", "ValueError", "(", "'lower must be non-negative.'", ")", "# Pick a float in [lower, upper]", "saturation_factor", "=", "random_ops", ".", "random_uniform", "(", "[", "]", ",", "lower", ",", "upper", ",", "seed", "=", "seed", ")", "return", "adjust_saturation", "(", "image", ",", "saturation_factor", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py#L2051-L2080
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/matlib.py
python
randn
(*args)
return asmatrix(np.random.randn(*args))
Return a random matrix with data from the "standard normal" distribution. `randn` generates a matrix filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- Z : matrix of floats A matrix of floating-point samples drawn from the standard normal distribution. See Also -------- rand, numpy.random.RandomState.randn Notes ----- For random samples from :math:`N(\\mu, \\sigma^2)`, use: ``sigma * np.matlib.randn(...) + mu`` Examples -------- >>> np.random.seed(123) >>> import numpy.matlib >>> np.matlib.randn(1) matrix([[-1.0856306]]) >>> np.matlib.randn(1, 2, 3) matrix([[ 0.99734545, 0.2829785 , -1.50629471], [-0.57860025, 1.65143654, -2.42667924]]) Two-by-four matrix of samples from :math:`N(3, 6.25)`: >>> 2.5 * np.matlib.randn((2, 4)) + 3 matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462], [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]])
Return a random matrix with data from the "standard normal" distribution.
[ "Return", "a", "random", "matrix", "with", "data", "from", "the", "standard", "normal", "distribution", "." ]
def randn(*args): """ Return a random matrix with data from the "standard normal" distribution. `randn` generates a matrix filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- Z : matrix of floats A matrix of floating-point samples drawn from the standard normal distribution. See Also -------- rand, numpy.random.RandomState.randn Notes ----- For random samples from :math:`N(\\mu, \\sigma^2)`, use: ``sigma * np.matlib.randn(...) + mu`` Examples -------- >>> np.random.seed(123) >>> import numpy.matlib >>> np.matlib.randn(1) matrix([[-1.0856306]]) >>> np.matlib.randn(1, 2, 3) matrix([[ 0.99734545, 0.2829785 , -1.50629471], [-0.57860025, 1.65143654, -2.42667924]]) Two-by-four matrix of samples from :math:`N(3, 6.25)`: >>> 2.5 * np.matlib.randn((2, 4)) + 3 matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462], [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]]) """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.randn(*args))
[ "def", "randn", "(", "*", "args", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "return", "asmatrix", "(", "np", ".", "random", ".", "randn", "(", "*", "args", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/matlib.py#L266-L315
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/string.py
python
rstrip
(s, chars=None)
return s.rstrip(chars)
rstrip(s [,chars]) -> string Return a copy of the string s with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
rstrip(s [,chars]) -> string
[ "rstrip", "(", "s", "[", "chars", "]", ")", "-", ">", "string" ]
def rstrip(s, chars=None): """rstrip(s [,chars]) -> string Return a copy of the string s with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return s.rstrip(chars)
[ "def", "rstrip", "(", "s", ",", "chars", "=", "None", ")", ":", "return", "s", ".", "rstrip", "(", "chars", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/string.py#L270-L277
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiDockArt.SetColour
(*args, **kwargs)
return _aui.AuiDockArt_SetColour(*args, **kwargs)
SetColour(self, int id, Colour colour)
SetColour(self, int id, Colour colour)
[ "SetColour", "(", "self", "int", "id", "Colour", "colour", ")" ]
def SetColour(*args, **kwargs): """SetColour(self, int id, Colour colour)""" return _aui.AuiDockArt_SetColour(*args, **kwargs)
[ "def", "SetColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiDockArt_SetColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L986-L988
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/interval/FunctionInterval.py
python
ScaleInterval.__init__
(self, nodePath, scale, duration = 0.0, name = None, other = None)
__init__(nodePath, scale, duration, name)
__init__(nodePath, scale, duration, name)
[ "__init__", "(", "nodePath", "scale", "duration", "name", ")" ]
def __init__(self, nodePath, scale, duration = 0.0, name = None, other = None): """__init__(nodePath, scale, duration, name) """ # Create function def scaleFunc(np = nodePath, scale = scale, other = other): if other: np.setScale(other, scale) else: np.setScale(scale) # Determine name if name is None: name = 'ScaleInterval-%d' % ScaleInterval.scaleIntervalNum ScaleInterval.scaleIntervalNum += 1 # Create function interval FunctionInterval.__init__(self, scaleFunc, name = name)
[ "def", "__init__", "(", "self", ",", "nodePath", ",", "scale", ",", "duration", "=", "0.0", ",", "name", "=", "None", ",", "other", "=", "None", ")", ":", "# Create function", "def", "scaleFunc", "(", "np", "=", "nodePath", ",", "scale", "=", "scale", ",", "other", "=", "other", ")", ":", "if", "other", ":", "np", ".", "setScale", "(", "other", ",", "scale", ")", "else", ":", "np", ".", "setScale", "(", "scale", ")", "# Determine name", "if", "name", "is", "None", ":", "name", "=", "'ScaleInterval-%d'", "%", "ScaleInterval", ".", "scaleIntervalNum", "ScaleInterval", ".", "scaleIntervalNum", "+=", "1", "# Create function interval", "FunctionInterval", ".", "__init__", "(", "self", ",", "scaleFunc", ",", "name", "=", "name", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/interval/FunctionInterval.py#L217-L232
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
clang/bindings/python/clang/cindex.py
python
CursorKind.is_declaration
(self)
return conf.lib.clang_isDeclaration(self)
Test if this is a declaration kind.
Test if this is a declaration kind.
[ "Test", "if", "this", "is", "a", "declaration", "kind", "." ]
def is_declaration(self): """Test if this is a declaration kind.""" return conf.lib.clang_isDeclaration(self)
[ "def", "is_declaration", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isDeclaration", "(", "self", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L671-L673
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/training_utils_v1.py
python
Aggregator.create
(self, batch_outs)
Creates the initial results from the first batch outputs. Args: batch_outs: A list of batch-level outputs.
Creates the initial results from the first batch outputs.
[ "Creates", "the", "initial", "results", "from", "the", "first", "batch", "outputs", "." ]
def create(self, batch_outs): """Creates the initial results from the first batch outputs. Args: batch_outs: A list of batch-level outputs. """ raise NotImplementedError('Must be implemented in subclasses.')
[ "def", "create", "(", "self", ",", "batch_outs", ")", ":", "raise", "NotImplementedError", "(", "'Must be implemented in subclasses.'", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_utils_v1.py#L90-L96
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this marker if the comment goes beyond this line", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "find", "(", "'*/'", ",", "2", ")", "<", "0", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1364-L1372
tiann/android-native-debug
198903ed9346dc4a74327a63cb98d449b97d8047
app/source/art/tools/cpplint.py
python
_BlockInfo.CheckBegin
(self, filename, clean_lines, linenum, error)
Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. 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 up to the opening brace.
[ "Run", "checks", "that", "applies", "to", "text", "up", "to", "the", "opening", "brace", "." ]
def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. 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", "CheckBegin", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/tiann/android-native-debug/blob/198903ed9346dc4a74327a63cb98d449b97d8047/app/source/art/tools/cpplint.py#L1372-L1385
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
python
GetAllDefines
(target_list, target_dicts, data, config_name, params, compiler_path)
return all_defines
Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses.
Calculate the defines for a project.
[ "Calculate", "the", "defines", "for", "a", "project", "." ]
def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp files. all_defines = {} flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) extra_defines = msvs_settings.GetComputedDefines(config_name) else: extra_defines = [] if config_name in target['configurations']: config = target['configurations'][config_name] target_defines = config['defines'] else: target_defines = [] for define in target_defines + extra_defines: split_define = define.split('=', 1) if len(split_define) == 1: split_define.append('1') if split_define[0].strip() in all_defines: # Already defined continue all_defines[split_define[0].strip()] = split_define[1].strip() # Get default compiler defines (if possible). if flavor == 'win': return all_defines # Default defines already processed in the loop above. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-dM', '-']) cpp_proc = subprocess.Popen(args=command, cwd='.', stdin=subprocess.PIPE, stdout=subprocess.PIPE) cpp_output = cpp_proc.communicate()[0] cpp_lines = cpp_output.split('\n') for cpp_line in cpp_lines: if not cpp_line.strip(): continue cpp_line_parts = cpp_line.split(' ', 2) key = cpp_line_parts[1] if len(cpp_line_parts) >= 3: val = cpp_line_parts[2] else: val = '1' all_defines[key] = val return all_defines
[ "def", "GetAllDefines", "(", "target_list", ",", "target_dicts", ",", "data", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "# Get defines declared in the gyp files.", "all_defines", "=", "{", "}", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'win'", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "if", "flavor", "==", "'win'", ":", "msvs_settings", "=", "gyp", ".", "msvs_emulation", ".", "MsvsSettings", "(", "target", ",", "generator_flags", ")", "extra_defines", "=", "msvs_settings", ".", "GetComputedDefines", "(", "config_name", ")", "else", ":", "extra_defines", "=", "[", "]", "if", "config_name", "in", "target", "[", "'configurations'", "]", ":", "config", "=", "target", "[", "'configurations'", "]", "[", "config_name", "]", "target_defines", "=", "config", "[", "'defines'", "]", "else", ":", "target_defines", "=", "[", "]", "for", "define", "in", "target_defines", "+", "extra_defines", ":", "split_define", "=", "define", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "split_define", ")", "==", "1", ":", "split_define", ".", "append", "(", "'1'", ")", "if", "split_define", "[", "0", "]", ".", "strip", "(", ")", "in", "all_defines", ":", "# Already defined", "continue", "all_defines", "[", "split_define", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "split_define", "[", "1", "]", ".", "strip", "(", ")", "# Get default compiler defines (if possible).", "if", "flavor", "==", "'win'", ":", "return", "all_defines", "# Default defines already processed in the loop above.", "if", "compiler_path", ":", "command", "=", "shlex", ".", "split", "(", "compiler_path", ")", "command", ".", "extend", "(", "[", "'-E'", ",", "'-dM'", ",", "'-'", "]", ")", "cpp_proc", "=", "subprocess", ".", "Popen", "(", "args", "=", "command", ",", "cwd", "=", "'.'", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "cpp_output", "=", "cpp_proc", ".", "communicate", "(", ")", "[", "0", "]", "cpp_lines", "=", "cpp_output", ".", "split", "(", "'\\n'", ")", "for", "cpp_line", "in", "cpp_lines", ":", "if", "not", "cpp_line", ".", "strip", "(", ")", ":", "continue", "cpp_line_parts", "=", "cpp_line", ".", "split", "(", "' '", ",", "2", ")", "key", "=", "cpp_line_parts", "[", "1", "]", "if", "len", "(", "cpp_line_parts", ")", ">=", "3", ":", "val", "=", "cpp_line_parts", "[", "2", "]", "else", ":", "val", "=", "'1'", "all_defines", "[", "key", "]", "=", "val", "return", "all_defines" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L193-L249
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/run_m_script.py
python
apply_run_m_script
(tg)
Task generator customising the options etc. to call Matlab in batch mode for running a m-script.
Task generator customising the options etc. to call Matlab in batch mode for running a m-script.
[ "Task", "generator", "customising", "the", "options", "etc", ".", "to", "call", "Matlab", "in", "batch", "mode", "for", "running", "a", "m", "-", "script", "." ]
def apply_run_m_script(tg): """Task generator customising the options etc. to call Matlab in batch mode for running a m-script. """ # Convert sources and targets to nodes src_node = tg.path.find_resource(tg.source) tgt_nodes = [tg.path.find_or_declare(t) for t in tg.to_list(tg.target)] tsk = tg.create_task('run_m_script', src=src_node, tgt=tgt_nodes) tsk.cwd = src_node.parent.abspath() tsk.env.MSCRIPTTRUNK = os.path.splitext(src_node.name)[0] tsk.env.LOGFILEPATH = os.path.join(tg.bld.bldnode.abspath(), '%s_%d.log' % (tsk.env.MSCRIPTTRUNK, tg.idx)) # dependencies (if the attribute 'deps' changes, trigger a recompilation) for x in tg.to_list(getattr(tg, 'deps', [])): node = tg.path.find_resource(x) if not node: tg.bld.fatal('Could not find dependency %r for running %r' % (x, src_node.abspath())) tsk.dep_nodes.append(node) Logs.debug('deps: found dependencies %r for running %r', tsk.dep_nodes, src_node.abspath()) # Bypass the execution of process_source by setting the source to an empty list tg.source = []
[ "def", "apply_run_m_script", "(", "tg", ")", ":", "# Convert sources and targets to nodes ", "src_node", "=", "tg", ".", "path", ".", "find_resource", "(", "tg", ".", "source", ")", "tgt_nodes", "=", "[", "tg", ".", "path", ".", "find_or_declare", "(", "t", ")", "for", "t", "in", "tg", ".", "to_list", "(", "tg", ".", "target", ")", "]", "tsk", "=", "tg", ".", "create_task", "(", "'run_m_script'", ",", "src", "=", "src_node", ",", "tgt", "=", "tgt_nodes", ")", "tsk", ".", "cwd", "=", "src_node", ".", "parent", ".", "abspath", "(", ")", "tsk", ".", "env", ".", "MSCRIPTTRUNK", "=", "os", ".", "path", ".", "splitext", "(", "src_node", ".", "name", ")", "[", "0", "]", "tsk", ".", "env", ".", "LOGFILEPATH", "=", "os", ".", "path", ".", "join", "(", "tg", ".", "bld", ".", "bldnode", ".", "abspath", "(", ")", ",", "'%s_%d.log'", "%", "(", "tsk", ".", "env", ".", "MSCRIPTTRUNK", ",", "tg", ".", "idx", ")", ")", "# dependencies (if the attribute 'deps' changes, trigger a recompilation)", "for", "x", "in", "tg", ".", "to_list", "(", "getattr", "(", "tg", ",", "'deps'", ",", "[", "]", ")", ")", ":", "node", "=", "tg", ".", "path", ".", "find_resource", "(", "x", ")", "if", "not", "node", ":", "tg", ".", "bld", ".", "fatal", "(", "'Could not find dependency %r for running %r'", "%", "(", "x", ",", "src_node", ".", "abspath", "(", ")", ")", ")", "tsk", ".", "dep_nodes", ".", "append", "(", "node", ")", "Logs", ".", "debug", "(", "'deps: found dependencies %r for running %r'", ",", "tsk", ".", "dep_nodes", ",", "src_node", ".", "abspath", "(", ")", ")", "# Bypass the execution of process_source by setting the source to an empty list", "tg", ".", "source", "=", "[", "]" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/run_m_script.py#L65-L88
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.atom_to_unique_offset
(self, iatom)
return -1
Converts an atom number to the offset of this atom in the list of generated atoms. The unique atom itself is allowed offset 0.
Converts an atom number to the offset of this atom in the list of generated atoms. The unique atom itself is allowed offset 0.
[ "Converts", "an", "atom", "number", "to", "the", "offset", "of", "this", "atom", "in", "the", "list", "of", "generated", "atoms", ".", "The", "unique", "atom", "itself", "is", "allowed", "offset", "0", "." ]
def atom_to_unique_offset(self, iatom): """Converts an atom number to the offset of this atom in the list of generated atoms. The unique atom itself is allowed offset 0. """ iuniq = self.PYatom_to_unique[iatom] nequiv = self.nequiv[iuniq] for i in range(nequiv): if self.equiv[iuniq][i] == iatom: return i raise ValidationError("Molecule::atom_to_unique_offset: I should've found the atom requested...but didn't.") return -1
[ "def", "atom_to_unique_offset", "(", "self", ",", "iatom", ")", ":", "iuniq", "=", "self", ".", "PYatom_to_unique", "[", "iatom", "]", "nequiv", "=", "self", ".", "nequiv", "[", "iuniq", "]", "for", "i", "in", "range", "(", "nequiv", ")", ":", "if", "self", ".", "equiv", "[", "iuniq", "]", "[", "i", "]", "==", "iatom", ":", "return", "i", "raise", "ValidationError", "(", "\"Molecule::atom_to_unique_offset: I should've found the atom requested...but didn't.\"", ")", "return", "-", "1" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L3113-L3124
google-coral/edgetpu
5020de9386ff370dcc1f63291a2d0f98eeb98adb
edgetpu/classification/engine.py
python
ClassificationEngine.classify_with_input_tensor
(self, input_tensor, threshold=0.0, top_k=3)
return result[:top_k]
Performs classification with a raw input tensor. This requires you to process the input data (the image) and convert it to the appropriately formatted input tensor for your model. Args: input_tensor (:obj:`numpy.ndarray`): A 1-D array as the input tensor. threshold (float): Minimum confidence threshold for returned classifications. For example, use ``0.5`` to receive only classifications with a confidence equal-to or higher-than 0.5. top_k (int): The maximum number of classifications to return. Returns: A :obj:`list` of classifications, each of which is a list [int, float] that represents the label id (int) and the confidence score (float). Raises: ValueError: If argument values are invalid.
Performs classification with a raw input tensor.
[ "Performs", "classification", "with", "a", "raw", "input", "tensor", "." ]
def classify_with_input_tensor(self, input_tensor, threshold=0.0, top_k=3): """Performs classification with a raw input tensor. This requires you to process the input data (the image) and convert it to the appropriately formatted input tensor for your model. Args: input_tensor (:obj:`numpy.ndarray`): A 1-D array as the input tensor. threshold (float): Minimum confidence threshold for returned classifications. For example, use ``0.5`` to receive only classifications with a confidence equal-to or higher-than 0.5. top_k (int): The maximum number of classifications to return. Returns: A :obj:`list` of classifications, each of which is a list [int, float] that represents the label id (int) and the confidence score (float). Raises: ValueError: If argument values are invalid. """ if top_k <= 0: raise ValueError('top_k must be positive!') _, self._raw_result = self.run_inference( input_tensor) # top_k must be less or equal to number of possible results. top_k = min(top_k, len(self._raw_result)) result = [] indices = numpy.argpartition(self._raw_result, -top_k)[-top_k:] for i in indices: if self._raw_result[i] > threshold: result.append((i, self._raw_result[i])) result.sort(key=lambda tup: -tup[1]) return result[:top_k]
[ "def", "classify_with_input_tensor", "(", "self", ",", "input_tensor", ",", "threshold", "=", "0.0", ",", "top_k", "=", "3", ")", ":", "if", "top_k", "<=", "0", ":", "raise", "ValueError", "(", "'top_k must be positive!'", ")", "_", ",", "self", ".", "_raw_result", "=", "self", ".", "run_inference", "(", "input_tensor", ")", "# top_k must be less or equal to number of possible results.", "top_k", "=", "min", "(", "top_k", ",", "len", "(", "self", ".", "_raw_result", ")", ")", "result", "=", "[", "]", "indices", "=", "numpy", ".", "argpartition", "(", "self", ".", "_raw_result", ",", "-", "top_k", ")", "[", "-", "top_k", ":", "]", "for", "i", "in", "indices", ":", "if", "self", ".", "_raw_result", "[", "i", "]", ">", "threshold", ":", "result", ".", "append", "(", "(", "i", ",", "self", ".", "_raw_result", "[", "i", "]", ")", ")", "result", ".", "sort", "(", "key", "=", "lambda", "tup", ":", "-", "tup", "[", "1", "]", ")", "return", "result", "[", ":", "top_k", "]" ]
https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/edgetpu/classification/engine.py#L101-L132
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/net_builder.py
python
NetBuilder.stop_blob
(self)
return self._stop_blob
Returns the BlobReference to the stop_blob of this NetBuilder. If one is not yet available, creates one. This function assumes that the stop_blob() will be used immediatelly in the current net, so it doesn't initialize it if the current net is the first of the builder.
Returns the BlobReference to the stop_blob of this NetBuilder. If one is not yet available, creates one. This function assumes that the stop_blob() will be used immediatelly in the current net, so it doesn't initialize it if the current net is the first of the builder.
[ "Returns", "the", "BlobReference", "to", "the", "stop_blob", "of", "this", "NetBuilder", ".", "If", "one", "is", "not", "yet", "available", "creates", "one", ".", "This", "function", "assumes", "that", "the", "stop_blob", "()", "will", "be", "used", "immediatelly", "in", "the", "current", "net", "so", "it", "doesn", "t", "initialize", "it", "if", "the", "current", "net", "is", "the", "first", "of", "the", "builder", "." ]
def stop_blob(self): """ Returns the BlobReference to the stop_blob of this NetBuilder. If one is not yet available, creates one. This function assumes that the stop_blob() will be used immediatelly in the current net, so it doesn't initialize it if the current net is the first of the builder. """ assert not self._use_control_ops, \ 'Stop blobs are not used with control operators' if self._stop_blob is None: net = self.current_net() self._stop_blob = core.BlobReference( net.NextName('stop_blob'), net=net) net.Const(False, blob_out=self._stop_blob) if self._current_net != self._children[0]: self._children.insert(0, core.Net('stop_blob_init')) self._children[0].Const(False, blob_out=self._stop_blob) return self._stop_blob
[ "def", "stop_blob", "(", "self", ")", ":", "assert", "not", "self", ".", "_use_control_ops", ",", "'Stop blobs are not used with control operators'", "if", "self", ".", "_stop_blob", "is", "None", ":", "net", "=", "self", ".", "current_net", "(", ")", "self", ".", "_stop_blob", "=", "core", ".", "BlobReference", "(", "net", ".", "NextName", "(", "'stop_blob'", ")", ",", "net", "=", "net", ")", "net", ".", "Const", "(", "False", ",", "blob_out", "=", "self", ".", "_stop_blob", ")", "if", "self", ".", "_current_net", "!=", "self", ".", "_children", "[", "0", "]", ":", "self", ".", "_children", ".", "insert", "(", "0", ",", "core", ".", "Net", "(", "'stop_blob_init'", ")", ")", "self", ".", "_children", "[", "0", "]", ".", "Const", "(", "False", ",", "blob_out", "=", "self", ".", "_stop_blob", ")", "return", "self", ".", "_stop_blob" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/net_builder.py#L57-L75
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
python/caffe/draw.py
python
get_pooling_types_dict
()
return d
Get dictionary mapping pooling type number to type name
Get dictionary mapping pooling type number to type name
[ "Get", "dictionary", "mapping", "pooling", "type", "number", "to", "type", "name" ]
def get_pooling_types_dict(): """Get dictionary mapping pooling type number to type name """ desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR d = {} for k, v in desc.values_by_name.items(): d[v.number] = k return d
[ "def", "get_pooling_types_dict", "(", ")", ":", "desc", "=", "caffe_pb2", ".", "PoolingParameter", ".", "PoolMethod", ".", "DESCRIPTOR", "d", "=", "{", "}", "for", "k", ",", "v", "in", "desc", ".", "values_by_name", ".", "items", "(", ")", ":", "d", "[", "v", ".", "number", "]", "=", "k", "return", "d" ]
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/python/caffe/draw.py#L36-L43
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/RANSApplication/python_scripts/formulations/rans_formulation.py
python
RansFormulation.GetModelPart
(self)
return None
Returns the model part used for solving current formulation (if a strategy is used only.) Returns: Kratos.ModelPart: Model part used for solving current formulation
Returns the model part used for solving current formulation (if a strategy is used only.)
[ "Returns", "the", "model", "part", "used", "for", "solving", "current", "formulation", "(", "if", "a", "strategy", "is", "used", "only", ".", ")" ]
def GetModelPart(self): """Returns the model part used for solving current formulation (if a strategy is used only.) Returns: Kratos.ModelPart: Model part used for solving current formulation """ if (self.GetStrategy() is not None): return self.GetStrategy().GetModelPart() return None
[ "def", "GetModelPart", "(", "self", ")", ":", "if", "(", "self", ".", "GetStrategy", "(", ")", "is", "not", "None", ")", ":", "return", "self", ".", "GetStrategy", "(", ")", ".", "GetModelPart", "(", ")", "return", "None" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/RANSApplication/python_scripts/formulations/rans_formulation.py#L341-L350
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/distributed/group.py
python
get_world_size
()
return _sd.world_size if _sd is not None else 1
r"""Get the total number of processes participating in the job.
r"""Get the total number of processes participating in the job.
[ "r", "Get", "the", "total", "number", "of", "processes", "participating", "in", "the", "job", "." ]
def get_world_size() -> int: r"""Get the total number of processes participating in the job.""" return _sd.world_size if _sd is not None else 1
[ "def", "get_world_size", "(", ")", "->", "int", ":", "return", "_sd", ".", "world_size", "if", "_sd", "is", "not", "None", "else", "1" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/distributed/group.py#L205-L207
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/code.py
python
InteractiveInterpreter.__init__
(self, locals=None)
Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None.
Constructor.
[ "Constructor", "." ]
def __init__(self, locals=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. """ if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler()
[ "def", "__init__", "(", "self", ",", "locals", "=", "None", ")", ":", "if", "locals", "is", "None", ":", "locals", "=", "{", "\"__name__\"", ":", "\"__console__\"", ",", "\"__doc__\"", ":", "None", "}", "self", ".", "locals", "=", "locals", "self", ".", "compile", "=", "CommandCompiler", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/code.py#L24-L36
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
base/android/jni_generator/jni_generator.py
python
ExtractCalledByNatives
(contents)
return MangleCalledByNatives(called_by_natives)
Parses all methods annotated with @CalledByNative. Args: contents: the contents of the java file. Returns: A list of dict with information about the annotated methods. TODO(bulach): return a CalledByNative object. Raises: ParseError: if unable to parse.
Parses all methods annotated with @CalledByNative.
[ "Parses", "all", "methods", "annotated", "with", "@CalledByNative", "." ]
def ExtractCalledByNatives(contents): """Parses all methods annotated with @CalledByNative. Args: contents: the contents of the java file. Returns: A list of dict with information about the annotated methods. TODO(bulach): return a CalledByNative object. Raises: ParseError: if unable to parse. """ called_by_natives = [] for match in re.finditer(RE_CALLED_BY_NATIVE, contents): called_by_natives += [CalledByNative( system_class=False, unchecked='Unchecked' in match.group('Unchecked'), static='static' in match.group('prefix'), java_class_name=match.group('annotation') or '', return_type=match.group('return_type'), env_call=GetEnvCallForReturnType(match.group('return_type')), name=match.group('name'), params=ParseParams(match.group('params')))] # Check for any @CalledByNative occurrences that weren't matched. unmatched_lines = re.sub(RE_CALLED_BY_NATIVE, '', contents).split('\n') for line1, line2 in zip(unmatched_lines, unmatched_lines[1:]): if '@CalledByNative' in line1: raise ParseError('could not parse @CalledByNative method signature', line1, line2) return MangleCalledByNatives(called_by_natives)
[ "def", "ExtractCalledByNatives", "(", "contents", ")", ":", "called_by_natives", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "RE_CALLED_BY_NATIVE", ",", "contents", ")", ":", "called_by_natives", "+=", "[", "CalledByNative", "(", "system_class", "=", "False", ",", "unchecked", "=", "'Unchecked'", "in", "match", ".", "group", "(", "'Unchecked'", ")", ",", "static", "=", "'static'", "in", "match", ".", "group", "(", "'prefix'", ")", ",", "java_class_name", "=", "match", ".", "group", "(", "'annotation'", ")", "or", "''", ",", "return_type", "=", "match", ".", "group", "(", "'return_type'", ")", ",", "env_call", "=", "GetEnvCallForReturnType", "(", "match", ".", "group", "(", "'return_type'", ")", ")", ",", "name", "=", "match", ".", "group", "(", "'name'", ")", ",", "params", "=", "ParseParams", "(", "match", ".", "group", "(", "'params'", ")", ")", ")", "]", "# Check for any @CalledByNative occurrences that weren't matched.", "unmatched_lines", "=", "re", ".", "sub", "(", "RE_CALLED_BY_NATIVE", ",", "''", ",", "contents", ")", ".", "split", "(", "'\\n'", ")", "for", "line1", ",", "line2", "in", "zip", "(", "unmatched_lines", ",", "unmatched_lines", "[", "1", ":", "]", ")", ":", "if", "'@CalledByNative'", "in", "line1", ":", "raise", "ParseError", "(", "'could not parse @CalledByNative method signature'", ",", "line1", ",", "line2", ")", "return", "MangleCalledByNatives", "(", "called_by_natives", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/base/android/jni_generator/jni_generator.py#L348-L378
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/templite.py
python
Templite._syntax_error
(self, msg, thing)
Raise a syntax error using `msg`, and showing `thing`.
Raise a syntax error using `msg`, and showing `thing`.
[ "Raise", "a", "syntax", "error", "using", "msg", "and", "showing", "thing", "." ]
def _syntax_error(self, msg, thing): """Raise a syntax error using `msg`, and showing `thing`.""" raise TempliteSyntaxError("%s: %r" % (msg, thing))
[ "def", "_syntax_error", "(", "self", ",", "msg", ",", "thing", ")", ":", "raise", "TempliteSyntaxError", "(", "\"%s: %r\"", "%", "(", "msg", ",", "thing", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/templite.py#L234-L236
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_annotationstyleeditor.py
python
AnnotationStyleEditor.update_style
(self, arg=None)
Update the current style with the values from the editor.
Update the current style with the values from the editor.
[ "Update", "the", "current", "style", "with", "the", "values", "from", "the", "editor", "." ]
def update_style(self, arg=None): """Update the current style with the values from the editor.""" index = self.form.comboBoxStyles.currentIndex() if index > 1: values = {} style = self.form.comboBoxStyles.itemText(index) for key in DEFAULT.keys(): control = getattr(self.form, key) if DEFAULT[key][0] == "str": values[key] = control.text() elif DEFAULT[key][0] == "font": values[key] = control.currentFont().family() elif DEFAULT[key][0] == "color": values[key] = control.property("color").rgb() << 8 elif DEFAULT[key][0] in ["int", "float"]: values[key] = control.value() elif DEFAULT[key][0] == "bool": values[key] = control.isChecked() elif DEFAULT[key][0] == "index": values[key] = control.currentIndex() self.styles[style] = values
[ "def", "update_style", "(", "self", ",", "arg", "=", "None", ")", ":", "index", "=", "self", ".", "form", ".", "comboBoxStyles", ".", "currentIndex", "(", ")", "if", "index", ">", "1", ":", "values", "=", "{", "}", "style", "=", "self", ".", "form", ".", "comboBoxStyles", ".", "itemText", "(", "index", ")", "for", "key", "in", "DEFAULT", ".", "keys", "(", ")", ":", "control", "=", "getattr", "(", "self", ".", "form", ",", "key", ")", "if", "DEFAULT", "[", "key", "]", "[", "0", "]", "==", "\"str\"", ":", "values", "[", "key", "]", "=", "control", ".", "text", "(", ")", "elif", "DEFAULT", "[", "key", "]", "[", "0", "]", "==", "\"font\"", ":", "values", "[", "key", "]", "=", "control", ".", "currentFont", "(", ")", ".", "family", "(", ")", "elif", "DEFAULT", "[", "key", "]", "[", "0", "]", "==", "\"color\"", ":", "values", "[", "key", "]", "=", "control", ".", "property", "(", "\"color\"", ")", ".", "rgb", "(", ")", "<<", "8", "elif", "DEFAULT", "[", "key", "]", "[", "0", "]", "in", "[", "\"int\"", ",", "\"float\"", "]", ":", "values", "[", "key", "]", "=", "control", ".", "value", "(", ")", "elif", "DEFAULT", "[", "key", "]", "[", "0", "]", "==", "\"bool\"", ":", "values", "[", "key", "]", "=", "control", ".", "isChecked", "(", ")", "elif", "DEFAULT", "[", "key", "]", "[", "0", "]", "==", "\"index\"", ":", "values", "[", "key", "]", "=", "control", ".", "currentIndex", "(", ")", "self", ".", "styles", "[", "style", "]", "=", "values" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_annotationstyleeditor.py#L353-L373
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
HDFStore.select
(self, key, where=None, start=None, stop=None, columns=None, iterator=False, chunksize=None, auto_close=False, **kwargs)
return it.get_result()
Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- key : object where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection columns : a list of columns that if not None, will limit the return columns iterator : boolean, return an iterator, default False chunksize : nrows to include in iteration, return an iterator auto_close : boolean, should automatically close the store when finished, default is False Returns ------- The selected object
Retrieve pandas object stored in file, optionally based on where criteria
[ "Retrieve", "pandas", "object", "stored", "in", "file", "optionally", "based", "on", "where", "criteria" ]
def select(self, key, where=None, start=None, stop=None, columns=None, iterator=False, chunksize=None, auto_close=False, **kwargs): """ Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- key : object where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection stop : integer (defaults to None), row number to stop selection columns : a list of columns that if not None, will limit the return columns iterator : boolean, return an iterator, default False chunksize : nrows to include in iteration, return an iterator auto_close : boolean, should automatically close the store when finished, default is False Returns ------- The selected object """ group = self.get_node(key) if group is None: raise KeyError('No object named {key} in the file'.format(key=key)) # create the storer and axes where = _ensure_term(where, scope_level=1) s = self._create_storer(group) s.infer_axes() # function to call on iteration def func(_start, _stop, _where): return s.read(start=_start, stop=_stop, where=_where, columns=columns) # create the iterator it = TableIterator(self, s, func, where=where, nrows=s.nrows, start=start, stop=stop, iterator=iterator, chunksize=chunksize, auto_close=auto_close) return it.get_result()
[ "def", "select", "(", "self", ",", "key", ",", "where", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "columns", "=", "None", ",", "iterator", "=", "False", ",", "chunksize", "=", "None", ",", "auto_close", "=", "False", ",", "*", "*", "kwargs", ")", ":", "group", "=", "self", ".", "get_node", "(", "key", ")", "if", "group", "is", "None", ":", "raise", "KeyError", "(", "'No object named {key} in the file'", ".", "format", "(", "key", "=", "key", ")", ")", "# create the storer and axes", "where", "=", "_ensure_term", "(", "where", ",", "scope_level", "=", "1", ")", "s", "=", "self", ".", "_create_storer", "(", "group", ")", "s", ".", "infer_axes", "(", ")", "# function to call on iteration", "def", "func", "(", "_start", ",", "_stop", ",", "_where", ")", ":", "return", "s", ".", "read", "(", "start", "=", "_start", ",", "stop", "=", "_stop", ",", "where", "=", "_where", ",", "columns", "=", "columns", ")", "# create the iterator", "it", "=", "TableIterator", "(", "self", ",", "s", ",", "func", ",", "where", "=", "where", ",", "nrows", "=", "s", ".", "nrows", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "iterator", "=", "iterator", ",", "chunksize", "=", "chunksize", ",", "auto_close", "=", "auto_close", ")", "return", "it", ".", "get_result", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L697-L740
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/wxgui.py
python
WxGui.init_widgets
(self, mainframe)
Set mainframe and initialize widgets to various places.
Set mainframe and initialize widgets to various places.
[ "Set", "mainframe", "and", "initialize", "widgets", "to", "various", "places", "." ]
def init_widgets(self, mainframe): """ Set mainframe and initialize widgets to various places. """ self._mainframe = mainframe #self._neteditor = mainframe.add_view("Network", Neteditor) # mainframe.browse_obj(self._module) self.make_menu() self.make_toolbar()
[ "def", "init_widgets", "(", "self", ",", "mainframe", ")", ":", "self", ".", "_mainframe", "=", "mainframe", "#self._neteditor = mainframe.add_view(\"Network\", Neteditor)", "# mainframe.browse_obj(self._module)", "self", ".", "make_menu", "(", ")", "self", ".", "make_toolbar", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/wxgui.py#L275-L284
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/math_ops.py
python
conj
(x, name=None)
r"""Returns the complex conjugate of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of complex numbers that are the complex conjugate of each element in `input`. The complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. The complex conjugate returned by this operation is of the form \\(a - bj\\). For example: # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j] If `x` is real, it is returned unchanged. Args: x: `Tensor` to conjugate. Must have numeric type. name: A name for the operation (optional). Returns: A `Tensor` that is the conjugate of `x` (with the same type). Raises: TypeError: If `x` is not a numeric tensor.
r"""Returns the complex conjugate of a complex number.
[ "r", "Returns", "the", "complex", "conjugate", "of", "a", "complex", "number", "." ]
def conj(x, name=None): r"""Returns the complex conjugate of a complex number. Given a tensor `input` of complex numbers, this operation returns a tensor of complex numbers that are the complex conjugate of each element in `input`. The complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. The complex conjugate returned by this operation is of the form \\(a - bj\\). For example: # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] tf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j] If `x` is real, it is returned unchanged. Args: x: `Tensor` to conjugate. Must have numeric type. name: A name for the operation (optional). Returns: A `Tensor` that is the conjugate of `x` (with the same type). Raises: TypeError: If `x` is not a numeric tensor. """ with ops.name_scope(name, "Conj", [x]) as name: x = ops.convert_to_tensor(x, name="x") if x.dtype.is_complex: return gen_math_ops._conj(x, name=name) elif x.dtype.is_floating or x.dtype.is_integer: return x else: raise TypeError("Expected numeric tensor, got dtype %r" % x.dtype)
[ "def", "conj", "(", "x", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Conj\"", ",", "[", "x", "]", ")", "as", "name", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", "=", "\"x\"", ")", "if", "x", ".", "dtype", ".", "is_complex", ":", "return", "gen_math_ops", ".", "_conj", "(", "x", ",", "name", "=", "name", ")", "elif", "x", ".", "dtype", ".", "is_floating", "or", "x", ".", "dtype", ".", "is_integer", ":", "return", "x", "else", ":", "raise", "TypeError", "(", "\"Expected numeric tensor, got dtype %r\"", "%", "x", ".", "dtype", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_ops.py#L1760-L1794
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiTabContainer.GetArtProvider
(*args, **kwargs)
return _aui.AuiTabContainer_GetArtProvider(*args, **kwargs)
GetArtProvider(self) -> AuiTabArt
GetArtProvider(self) -> AuiTabArt
[ "GetArtProvider", "(", "self", ")", "-", ">", "AuiTabArt" ]
def GetArtProvider(*args, **kwargs): """GetArtProvider(self) -> AuiTabArt""" return _aui.AuiTabContainer_GetArtProvider(*args, **kwargs)
[ "def", "GetArtProvider", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiTabContainer_GetArtProvider", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1133-L1135
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextParagraphLayoutBox.GetStyleForRange
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_GetStyleForRange(*args, **kwargs)
GetStyleForRange(self, RichTextRange range, RichTextAttr style) -> bool
GetStyleForRange(self, RichTextRange range, RichTextAttr style) -> bool
[ "GetStyleForRange", "(", "self", "RichTextRange", "range", "RichTextAttr", "style", ")", "-", ">", "bool" ]
def GetStyleForRange(*args, **kwargs): """GetStyleForRange(self, RichTextRange range, RichTextAttr style) -> bool""" return _richtext.RichTextParagraphLayoutBox_GetStyleForRange(*args, **kwargs)
[ "def", "GetStyleForRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_GetStyleForRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1744-L1746
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/depends.py
python
Require.is_current
(self, paths=None)
return self.version_ok(version)
Return true if dependency is present and up-to-date on 'paths
Return true if dependency is present and up-to-date on 'paths
[ "Return", "true", "if", "dependency", "is", "present", "and", "up", "-", "to", "-", "date", "on", "paths" ]
def is_current(self, paths=None): """Return true if dependency is present and up-to-date on 'paths'""" version = self.get_version(paths) if version is None: return False return self.version_ok(version)
[ "def", "is_current", "(", "self", ",", "paths", "=", "None", ")", ":", "version", "=", "self", ".", "get_version", "(", "paths", ")", "if", "version", "is", "None", ":", "return", "False", "return", "self", ".", "version_ok", "(", "version", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/depends.py#L77-L82
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/profiler/internal/flops_registry.py
python
_conv_2d_backprop_filter_flops
(graph, node)
return ops.OpStats("flops", (2 * image_shape.num_elements() * kernel_shape.num_elements() / (image_shape.dims[-1].value * strides_product)))
Compute flops for Conv2DBackpropFilter operation.
Compute flops for Conv2DBackpropFilter operation.
[ "Compute", "flops", "for", "Conv2DBackpropFilter", "operation", "." ]
def _conv_2d_backprop_filter_flops(graph, node): """Compute flops for Conv2DBackpropFilter operation.""" # Formula same as for Conv2DBackpropInput: # batch_size * image_x_dim * image_y_dim * kernel_x_dim * kernel_y_dim # * input_depth * output_depth * 2 / (image_x_stride * image_x_stride) # _verify_conv_data_format(node) # image_shape = [batch_size, image_y_dim, image_x_dim, input_depth] image_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) image_shape.assert_is_fully_defined() # kernel_shape = [kernel_y_dim, kernel_x_dim, input_depth, output_depth] kernel_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) kernel_shape.assert_is_fully_defined() # strides strides_shape = list(node.attr["strides"].list.i) strides_product = strides_shape[1] * strides_shape[2] return ops.OpStats("flops", (2 * image_shape.num_elements() * kernel_shape.num_elements() / (image_shape.dims[-1].value * strides_product)))
[ "def", "_conv_2d_backprop_filter_flops", "(", "graph", ",", "node", ")", ":", "# Formula same as for Conv2DBackpropInput:", "# batch_size * image_x_dim * image_y_dim * kernel_x_dim * kernel_y_dim", "# * input_depth * output_depth * 2 / (image_x_stride * image_x_stride)", "#", "_verify_conv_data_format", "(", "node", ")", "# image_shape = [batch_size, image_y_dim, image_x_dim, input_depth]", "image_shape", "=", "graph_util", ".", "tensor_shape_from_node_def_name", "(", "graph", ",", "node", ".", "input", "[", "0", "]", ")", "image_shape", ".", "assert_is_fully_defined", "(", ")", "# kernel_shape = [kernel_y_dim, kernel_x_dim, input_depth, output_depth]", "kernel_shape", "=", "graph_util", ".", "tensor_shape_from_node_def_name", "(", "graph", ",", "node", ".", "name", ")", "kernel_shape", ".", "assert_is_fully_defined", "(", ")", "# strides", "strides_shape", "=", "list", "(", "node", ".", "attr", "[", "\"strides\"", "]", ".", "list", ".", "i", ")", "strides_product", "=", "strides_shape", "[", "1", "]", "*", "strides_shape", "[", "2", "]", "return", "ops", ".", "OpStats", "(", "\"flops\"", ",", "(", "2", "*", "image_shape", ".", "num_elements", "(", ")", "*", "kernel_shape", ".", "num_elements", "(", ")", "/", "(", "image_shape", ".", "dims", "[", "-", "1", "]", ".", "value", "*", "strides_product", ")", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/profiler/internal/flops_registry.py#L410-L429
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/optimize.py
python
OptimizationProblemBuilder.isFeasible
(self,eqTol=1e-3)
return True
Returns True if the currently bound state passes all equality, inequality, joint limit, and black-box feasibility tests. Equality and IK constraints mut be met with equality tolerance eqTol.
Returns True if the currently bound state passes all equality, inequality, joint limit, and black-box feasibility tests. Equality and IK constraints mut be met with equality tolerance eqTol.
[ "Returns", "True", "if", "the", "currently", "bound", "state", "passes", "all", "equality", "inequality", "joint", "limit", "and", "black", "-", "box", "feasibility", "tests", ".", "Equality", "and", "IK", "constraints", "mut", "be", "met", "with", "equality", "tolerance", "eqTol", "." ]
def isFeasible(self,eqTol=1e-3): """Returns True if the currently bound state passes all equality, inequality, joint limit, and black-box feasibility tests. Equality and IK constraints mut be met with equality tolerance eqTol.""" if not self.inBounds(): return False res = self.equalityResidual() if any(abs(r) > eqTol for r in res): return False res = self.inequalityResidual() if any(r > 0 for r in res): return False if not self.feasibilityTestsPass(): return False return True
[ "def", "isFeasible", "(", "self", ",", "eqTol", "=", "1e-3", ")", ":", "if", "not", "self", ".", "inBounds", "(", ")", ":", "return", "False", "res", "=", "self", ".", "equalityResidual", "(", ")", "if", "any", "(", "abs", "(", "r", ")", ">", "eqTol", "for", "r", "in", "res", ")", ":", "return", "False", "res", "=", "self", ".", "inequalityResidual", "(", ")", "if", "any", "(", "r", ">", "0", "for", "r", "in", "res", ")", ":", "return", "False", "if", "not", "self", ".", "feasibilityTestsPass", "(", ")", ":", "return", "False", "return", "True" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L998-L1010
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowserplotinteraction.py
python
FitPropertyBrowserPlotInteraction.plot_current_guess
(self)
Plot the guess workspace of the currently selected function
Plot the guess workspace of the currently selected function
[ "Plot", "the", "guess", "workspace", "of", "the", "currently", "selected", "function" ]
def plot_current_guess(self): """ Plot the guess workspace of the currently selected function """ fun = self.fit_browser.currentHandler().ifun() ws_name = self.fit_browser.workspaceName() if fun == '' or ws_name == '': return out_ws_name = self._get_current_prefixed_function_name() line = self._plot_guess_workspace(ws_name, fun, out_ws_name) if line: self.guess_lines[self._get_current_prefixed_function_name()] = line
[ "def", "plot_current_guess", "(", "self", ")", ":", "fun", "=", "self", ".", "fit_browser", ".", "currentHandler", "(", ")", ".", "ifun", "(", ")", "ws_name", "=", "self", ".", "fit_browser", ".", "workspaceName", "(", ")", "if", "fun", "==", "''", "or", "ws_name", "==", "''", ":", "return", "out_ws_name", "=", "self", ".", "_get_current_prefixed_function_name", "(", ")", "line", "=", "self", ".", "_plot_guess_workspace", "(", "ws_name", ",", "fun", ",", "out_ws_name", ")", "if", "line", ":", "self", ".", "guess_lines", "[", "self", ".", "_get_current_prefixed_function_name", "(", ")", "]", "=", "line" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowserplotinteraction.py#L99-L112
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/ops.py
python
get_default_session
()
return _default_session_stack.get_default()
Returns the default session for the current thread. The returned `Session` will be the innermost session on which a `Session` or `Session.as_default()` context has been entered. NOTE: The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function. Returns: The default `Session` being used in the current thread.
Returns the default session for the current thread.
[ "Returns", "the", "default", "session", "for", "the", "current", "thread", "." ]
def get_default_session(): """Returns the default session for the current thread. The returned `Session` will be the innermost session on which a `Session` or `Session.as_default()` context has been entered. NOTE: The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function. Returns: The default `Session` being used in the current thread. """ return _default_session_stack.get_default()
[ "def", "get_default_session", "(", ")", ":", "return", "_default_session_stack", ".", "get_default", "(", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L3715-L3729
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/generic_utils.py
python
serialize_keras_class_and_config
( cls_name, cls_config, obj=None, shared_object_id=None)
return base_config
Returns the serialization of the class with the given config.
Returns the serialization of the class with the given config.
[ "Returns", "the", "serialization", "of", "the", "class", "with", "the", "given", "config", "." ]
def serialize_keras_class_and_config( cls_name, cls_config, obj=None, shared_object_id=None): """Returns the serialization of the class with the given config.""" base_config = {'class_name': cls_name, 'config': cls_config} # We call `serialize_keras_class_and_config` for some branches of the load # path. In that case, we may already have a shared object ID we'd like to # retain. if shared_object_id is not None: base_config[SHARED_OBJECT_KEY] = shared_object_id # If we have an active `SharedObjectSavingScope`, check whether we've already # serialized this config. If so, just use that config. This will store an # extra ID field in the config, allowing us to re-create the shared object # relationship at load time. if _shared_object_saving_scope() is not None and obj is not None: shared_object_config = _shared_object_saving_scope().get_config(obj) if shared_object_config is None: return _shared_object_saving_scope().create_config(base_config, obj) return shared_object_config return base_config
[ "def", "serialize_keras_class_and_config", "(", "cls_name", ",", "cls_config", ",", "obj", "=", "None", ",", "shared_object_id", "=", "None", ")", ":", "base_config", "=", "{", "'class_name'", ":", "cls_name", ",", "'config'", ":", "cls_config", "}", "# We call `serialize_keras_class_and_config` for some branches of the load", "# path. In that case, we may already have a shared object ID we'd like to", "# retain.", "if", "shared_object_id", "is", "not", "None", ":", "base_config", "[", "SHARED_OBJECT_KEY", "]", "=", "shared_object_id", "# If we have an active `SharedObjectSavingScope`, check whether we've already", "# serialized this config. If so, just use that config. This will store an", "# extra ID field in the config, allowing us to re-create the shared object", "# relationship at load time.", "if", "_shared_object_saving_scope", "(", ")", "is", "not", "None", "and", "obj", "is", "not", "None", ":", "shared_object_config", "=", "_shared_object_saving_scope", "(", ")", ".", "get_config", "(", "obj", ")", "if", "shared_object_config", "is", "None", ":", "return", "_shared_object_saving_scope", "(", ")", ".", "create_config", "(", "base_config", ",", "obj", ")", "return", "shared_object_config", "return", "base_config" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/generic_utils.py#L320-L341
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_clone.py
python
Clone.finish
(self, close=False)
Terminate the operation of the tool.
Terminate the operation of the tool.
[ "Terminate", "the", "operation", "of", "the", "tool", "." ]
def finish(self, close=False): """Terminate the operation of the tool.""" super(Clone, self).finish(close=False) if self.moveAfterCloning: todo.ToDo.delay(Gui.runCommand, "Draft_Move")
[ "def", "finish", "(", "self", ",", "close", "=", "False", ")", ":", "super", "(", "Clone", ",", "self", ")", ".", "finish", "(", "close", "=", "False", ")", "if", "self", ".", "moveAfterCloning", ":", "todo", ".", "ToDo", ".", "delay", "(", "Gui", ".", "runCommand", ",", "\"Draft_Move\"", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_clone.py#L113-L117
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppocr/utils/e2e_utils/extract_textpoint_fast.py
python
point_pair2poly
(point_pair_list)
return np.array(point_list).reshape(-1, 2)
Transfer vertical point_pairs into poly point in clockwise.
Transfer vertical point_pairs into poly point in clockwise.
[ "Transfer", "vertical", "point_pairs", "into", "poly", "point", "in", "clockwise", "." ]
def point_pair2poly(point_pair_list): """ Transfer vertical point_pairs into poly point in clockwise. """ point_num = len(point_pair_list) * 2 point_list = [0] * point_num for idx, point_pair in enumerate(point_pair_list): point_list[idx] = point_pair[0] point_list[point_num - 1 - idx] = point_pair[1] return np.array(point_list).reshape(-1, 2)
[ "def", "point_pair2poly", "(", "point_pair_list", ")", ":", "point_num", "=", "len", "(", "point_pair_list", ")", "*", "2", "point_list", "=", "[", "0", "]", "*", "point_num", "for", "idx", ",", "point_pair", "in", "enumerate", "(", "point_pair_list", ")", ":", "point_list", "[", "idx", "]", "=", "point_pair", "[", "0", "]", "point_list", "[", "point_num", "-", "1", "-", "idx", "]", "=", "point_pair", "[", "1", "]", "return", "np", ".", "array", "(", "point_list", ")", ".", "reshape", "(", "-", "1", ",", "2", ")" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/utils/e2e_utils/extract_textpoint_fast.py#L268-L277
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py
python
_collapse_addresses_internal
(addresses)
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed.
Loops through the addresses, collapsing concurrent netblocks.
[ "Loops", "through", "the", "addresses", "collapsing", "concurrent", "netblocks", "." ]
def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: subnets[supernet] = net elif existing != net: # Merge consecutive subnets del subnets[supernet] to_merge.append(supernet) # Then iterate over resulting networks, skipping subsumed subnets last = None for net in sorted(subnets.values()): if last is not None: # Since they are sorted, last.network_address <= net.network_address # is a given. if last.broadcast_address >= net.broadcast_address: continue yield net last = net
[ "def", "_collapse_addresses_internal", "(", "addresses", ")", ":", "# First merge", "to_merge", "=", "list", "(", "addresses", ")", "subnets", "=", "{", "}", "while", "to_merge", ":", "net", "=", "to_merge", ".", "pop", "(", ")", "supernet", "=", "net", ".", "supernet", "(", ")", "existing", "=", "subnets", ".", "get", "(", "supernet", ")", "if", "existing", "is", "None", ":", "subnets", "[", "supernet", "]", "=", "net", "elif", "existing", "!=", "net", ":", "# Merge consecutive subnets", "del", "subnets", "[", "supernet", "]", "to_merge", ".", "append", "(", "supernet", ")", "# Then iterate over resulting networks, skipping subsumed subnets", "last", "=", "None", "for", "net", "in", "sorted", "(", "subnets", ".", "values", "(", ")", ")", ":", "if", "last", "is", "not", "None", ":", "# Since they are sorted, last.network_address <= net.network_address", "# is a given.", "if", "last", ".", "broadcast_address", ">=", "net", ".", "broadcast_address", ":", "continue", "yield", "net", "last", "=", "net" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L257-L303
scylladb/seastar
0cdd2329beb1cc4c0af8828598c26114397ffa9c
scripts/perftune.py
python
PerfTunerBase.compute_cpu_mask
(self)
return self.__compute_cpu_mask
Return the CPU mask to use for seastar application binding.
Return the CPU mask to use for seastar application binding.
[ "Return", "the", "CPU", "mask", "to", "use", "for", "seastar", "application", "binding", "." ]
def compute_cpu_mask(self): """ Return the CPU mask to use for seastar application binding. """ # see the __set_mode_and_masks() description if self.__compute_cpu_mask is None: self.__set_mode_and_masks() return self.__compute_cpu_mask
[ "def", "compute_cpu_mask", "(", "self", ")", ":", "# see the __set_mode_and_masks() description", "if", "self", ".", "__compute_cpu_mask", "is", "None", ":", "self", ".", "__set_mode_and_masks", "(", ")", "return", "self", ".", "__compute_cpu_mask" ]
https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/perftune.py#L384-L392
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/_exceptions.py
python
SAXException.__init__
(self, msg, exception=None)
Creates an exception. The message is required, but the exception is optional.
Creates an exception. The message is required, but the exception is optional.
[ "Creates", "an", "exception", ".", "The", "message", "is", "required", "but", "the", "exception", "is", "optional", "." ]
def __init__(self, msg, exception=None): """Creates an exception. The message is required, but the exception is optional.""" self._msg = msg self._exception = exception Exception.__init__(self, msg)
[ "def", "__init__", "(", "self", ",", "msg", ",", "exception", "=", "None", ")", ":", "self", ".", "_msg", "=", "msg", "self", ".", "_exception", "=", "exception", "Exception", ".", "__init__", "(", "self", ",", "msg", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/_exceptions.py#L19-L24
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
python/caffe/pycaffe.py
python
_Net_forward_backward_all
(self, blobs=None, diffs=None, **kwargs)
return all_outs, all_diffs
Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict.
Run net forward + backward in batches.
[ "Run", "net", "forward", "+", "backward", "in", "batches", "." ]
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs): """ Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict. """ # Batch blobs and diffs. all_outs = {out: [] for out in set(self.outputs + (blobs or []))} all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))} forward_batches = self._batch({in_: kwargs[in_] for in_ in self.inputs if in_ in kwargs}) backward_batches = self._batch({out: kwargs[out] for out in self.outputs if out in kwargs}) # Collect outputs from batches (and heed lack of forward/backward batches). for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}): batch_blobs = self.forward(blobs=blobs, **fb) batch_diffs = self.backward(diffs=diffs, **bb) for out, out_blobs in six.iteritems(batch_blobs): all_outs[out].extend(out_blobs.copy()) for diff, out_diffs in six.iteritems(batch_diffs): all_diffs[diff].extend(out_diffs.copy()) # Package in ndarray. for out, diff in zip(all_outs, all_diffs): all_outs[out] = np.asarray(all_outs[out]) all_diffs[diff] = np.asarray(all_diffs[diff]) # Discard padding at the end and package in ndarray. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out, diff in zip(all_outs, all_diffs): all_outs[out] = all_outs[out][:-pad] all_diffs[diff] = all_diffs[diff][:-pad] return all_outs, all_diffs
[ "def", "_Net_forward_backward_all", "(", "self", ",", "blobs", "=", "None", ",", "diffs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Batch blobs and diffs.", "all_outs", "=", "{", "out", ":", "[", "]", "for", "out", "in", "set", "(", "self", ".", "outputs", "+", "(", "blobs", "or", "[", "]", ")", ")", "}", "all_diffs", "=", "{", "diff", ":", "[", "]", "for", "diff", "in", "set", "(", "self", ".", "inputs", "+", "(", "diffs", "or", "[", "]", ")", ")", "}", "forward_batches", "=", "self", ".", "_batch", "(", "{", "in_", ":", "kwargs", "[", "in_", "]", "for", "in_", "in", "self", ".", "inputs", "if", "in_", "in", "kwargs", "}", ")", "backward_batches", "=", "self", ".", "_batch", "(", "{", "out", ":", "kwargs", "[", "out", "]", "for", "out", "in", "self", ".", "outputs", "if", "out", "in", "kwargs", "}", ")", "# Collect outputs from batches (and heed lack of forward/backward batches).", "for", "fb", ",", "bb", "in", "izip_longest", "(", "forward_batches", ",", "backward_batches", ",", "fillvalue", "=", "{", "}", ")", ":", "batch_blobs", "=", "self", ".", "forward", "(", "blobs", "=", "blobs", ",", "*", "*", "fb", ")", "batch_diffs", "=", "self", ".", "backward", "(", "diffs", "=", "diffs", ",", "*", "*", "bb", ")", "for", "out", ",", "out_blobs", "in", "six", ".", "iteritems", "(", "batch_blobs", ")", ":", "all_outs", "[", "out", "]", ".", "extend", "(", "out_blobs", ".", "copy", "(", ")", ")", "for", "diff", ",", "out_diffs", "in", "six", ".", "iteritems", "(", "batch_diffs", ")", ":", "all_diffs", "[", "diff", "]", ".", "extend", "(", "out_diffs", ".", "copy", "(", ")", ")", "# Package in ndarray.", "for", "out", ",", "diff", "in", "zip", "(", "all_outs", ",", "all_diffs", ")", ":", "all_outs", "[", "out", "]", "=", "np", ".", "asarray", "(", "all_outs", "[", "out", "]", ")", "all_diffs", "[", "diff", "]", "=", "np", ".", "asarray", "(", "all_diffs", "[", "diff", "]", ")", "# Discard padding at the end and package in ndarray.", "pad", "=", "len", "(", "six", ".", "next", "(", "six", ".", "itervalues", "(", "all_outs", ")", ")", ")", "-", "len", "(", "six", ".", "next", "(", "six", ".", "itervalues", "(", "kwargs", ")", ")", ")", "if", "pad", ":", "for", "out", ",", "diff", "in", "zip", "(", "all_outs", ",", "all_diffs", ")", ":", "all_outs", "[", "out", "]", "=", "all_outs", "[", "out", "]", "[", ":", "-", "pad", "]", "all_diffs", "[", "diff", "]", "=", "all_diffs", "[", "diff", "]", "[", ":", "-", "pad", "]", "return", "all_outs", ",", "all_diffs" ]
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/pycaffe.py#L216-L258
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/config/sphinxdoc.py
python
reverse_aliases
(app)
return res
Produce a mapping of trait names to lists of command line aliases.
Produce a mapping of trait names to lists of command line aliases.
[ "Produce", "a", "mapping", "of", "trait", "names", "to", "lists", "of", "command", "line", "aliases", "." ]
def reverse_aliases(app): """Produce a mapping of trait names to lists of command line aliases. """ res = defaultdict(list) for alias, trait in app.aliases.items(): res[trait].append(alias) # Flags also often act as aliases for a boolean trait. # Treat flags which set one trait to True as aliases. for flag, (cfg, _) in app.flags.items(): if len(cfg) == 1: classname = list(cfg)[0] cls_cfg = cfg[classname] if len(cls_cfg) == 1: traitname = list(cls_cfg)[0] if cls_cfg[traitname] is True: res[classname+'.'+traitname].append(flag) return res
[ "def", "reverse_aliases", "(", "app", ")", ":", "res", "=", "defaultdict", "(", "list", ")", "for", "alias", ",", "trait", "in", "app", ".", "aliases", ".", "items", "(", ")", ":", "res", "[", "trait", "]", ".", "append", "(", "alias", ")", "# Flags also often act as aliases for a boolean trait.", "# Treat flags which set one trait to True as aliases.", "for", "flag", ",", "(", "cfg", ",", "_", ")", "in", "app", ".", "flags", ".", "items", "(", ")", ":", "if", "len", "(", "cfg", ")", "==", "1", ":", "classname", "=", "list", "(", "cfg", ")", "[", "0", "]", "cls_cfg", "=", "cfg", "[", "classname", "]", "if", "len", "(", "cls_cfg", ")", "==", "1", ":", "traitname", "=", "list", "(", "cls_cfg", ")", "[", "0", "]", "if", "cls_cfg", "[", "traitname", "]", "is", "True", ":", "res", "[", "classname", "+", "'.'", "+", "traitname", "]", ".", "append", "(", "flag", ")", "return", "res" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/config/sphinxdoc.py#L117-L135
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Utils.py
python
subst_vars
(expr, params)
return reg_subst.sub(repl_var, expr)
Replaces ${VAR} with the value of VAR taken from a dict or a config set:: from waflib import Utils s = Utils.subst_vars('${PREFIX}/bin', env) :type expr: string :param expr: String to perform substitution on :param params: Dictionary or config set to look up variable values.
Replaces ${VAR} with the value of VAR taken from a dict or a config set::
[ "Replaces", "$", "{", "VAR", "}", "with", "the", "value", "of", "VAR", "taken", "from", "a", "dict", "or", "a", "config", "set", "::" ]
def subst_vars(expr, params): """ Replaces ${VAR} with the value of VAR taken from a dict or a config set:: from waflib import Utils s = Utils.subst_vars('${PREFIX}/bin', env) :type expr: string :param expr: String to perform substitution on :param params: Dictionary or config set to look up variable values. """ def repl_var(m): if m.group(1): return '\\' if m.group(2): return '$' try: # ConfigSet instances may contain lists return params.get_flat(m.group(3)) except AttributeError: return params[m.group(3)] # if you get a TypeError, it means that 'expr' is not a string... # Utils.subst_vars(None, env) will not work return reg_subst.sub(repl_var, expr)
[ "def", "subst_vars", "(", "expr", ",", "params", ")", ":", "def", "repl_var", "(", "m", ")", ":", "if", "m", ".", "group", "(", "1", ")", ":", "return", "'\\\\'", "if", "m", ".", "group", "(", "2", ")", ":", "return", "'$'", "try", ":", "# ConfigSet instances may contain lists", "return", "params", ".", "get_flat", "(", "m", ".", "group", "(", "3", ")", ")", "except", "AttributeError", ":", "return", "params", "[", "m", ".", "group", "(", "3", ")", "]", "# if you get a TypeError, it means that 'expr' is not a string...", "# Utils.subst_vars(None, env) will not work", "return", "reg_subst", ".", "sub", "(", "repl_var", ",", "expr", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Utils.py#L673-L696
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/msvs.py
python
_AddConfigurationToMSVS
(p, spec, tools, config, config_type, config_name)
Add to the project file the configuration specified by config. Arguments: p: The target project being generated. spec: the target project dict. tools: A dictionary of settings; the tool name is the key. config: The dictionary that defines the special processing to be done for this configuration. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration.
Add to the project file the configuration specified by config.
[ "Add", "to", "the", "project", "file", "the", "configuration", "specified", "by", "config", "." ]
def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name): """Add to the project file the configuration specified by config. Arguments: p: The target project being generated. spec: the target project dict. tools: A dictionary of settings; the tool name is the key. config: The dictionary that defines the special processing to be done for this configuration. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration. """ attributes = _GetMSVSAttributes(spec, config, config_type) # Add in this configuration. tool_list = _ConvertToolsToExpectedForm(tools) p.AddConfig(_ConfigFullName(config_name, config), attrs=attributes, tools=tool_list)
[ "def", "_AddConfigurationToMSVS", "(", "p", ",", "spec", ",", "tools", ",", "config", ",", "config_type", ",", "config_name", ")", ":", "attributes", "=", "_GetMSVSAttributes", "(", "spec", ",", "config", ",", "config_type", ")", "# Add in this configuration.", "tool_list", "=", "_ConvertToolsToExpectedForm", "(", "tools", ")", "p", ".", "AddConfig", "(", "_ConfigFullName", "(", "config_name", ",", "config", ")", ",", "attrs", "=", "attributes", ",", "tools", "=", "tool_list", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L1369-L1385
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/types.py
python
Reconstruction.__init__
(self)
Defaut constructor
Defaut constructor
[ "Defaut", "constructor" ]
def __init__(self): """Defaut constructor""" self.cameras = {} self.shots = {} self.points = {} self.reference = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "cameras", "=", "{", "}", "self", ".", "shots", "=", "{", "}", "self", ".", "points", "=", "{", "}", "self", ".", "reference", "=", "None" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/types.py#L691-L696
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/plasma/Plasma.py
python
PtGetNPCCount
()
This will return the number of NPCs in the current age
This will return the number of NPCs in the current age
[ "This", "will", "return", "the", "number", "of", "NPCs", "in", "the", "current", "age" ]
def PtGetNPCCount(): """This will return the number of NPCs in the current age""" pass
[ "def", "PtGetNPCCount", "(", ")", ":", "pass" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L487-L489
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
scripts/cpp_lint.py
python
_FunctionState.Begin
(self, function_name)
Start analyzing function body. Args: function_name: The name of the function being tracked.
Start analyzing function body.
[ "Start", "analyzing", "function", "body", "." ]
def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name
[ "def", "Begin", "(", "self", ",", "function_name", ")", ":", "self", ".", "in_a_function", "=", "True", "self", ".", "lines_in_function", "=", "0", "self", ".", "current_function", "=", "function_name" ]
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L821-L829
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
TimerRunner.__init__
(self, *args)
__init__(self, wxTimer timer) -> TimerRunner __init__(self, wxTimer timer, int milli, bool oneShot=False) -> TimerRunner
__init__(self, wxTimer timer) -> TimerRunner __init__(self, wxTimer timer, int milli, bool oneShot=False) -> TimerRunner
[ "__init__", "(", "self", "wxTimer", "timer", ")", "-", ">", "TimerRunner", "__init__", "(", "self", "wxTimer", "timer", "int", "milli", "bool", "oneShot", "=", "False", ")", "-", ">", "TimerRunner" ]
def __init__(self, *args): """ __init__(self, wxTimer timer) -> TimerRunner __init__(self, wxTimer timer, int milli, bool oneShot=False) -> TimerRunner """ _misc_.TimerRunner_swiginit(self,_misc_.new_TimerRunner(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_misc_", ".", "TimerRunner_swiginit", "(", "self", ",", "_misc_", ".", "new_TimerRunner", "(", "*", "args", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1396-L1401
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py
python
FileStorageUri.is_stream
(self)
return bool(self.stream)
Returns True if this URI represents input/output stream.
Returns True if this URI represents input/output stream.
[ "Returns", "True", "if", "this", "URI", "represents", "input", "/", "output", "stream", "." ]
def is_stream(self): """Returns True if this URI represents input/output stream. """ return bool(self.stream)
[ "def", "is_stream", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "stream", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py#L876-L879
kiwix/kiwix-xulrunner
38f4a10ae4b1585c16cb11730bb0dcc4924ae19f
android/gen-custom-android-build.py
python
step_update_main_menu_xml
(jsdata, **options)
remove Open File menu item from main menu
remove Open File menu item from main menu
[ "remove", "Open", "File", "menu", "item", "from", "main", "menu" ]
def step_update_main_menu_xml(jsdata, **options): """ remove Open File menu item from main menu """ move_to_android_placeholder() # Parse and edit res/menu/main.xml menu_xml = os.path.join(ANDROID_PATH, 'res', 'menu', 'menu_main.xml') soup = soup = BeautifulSoup(open(menu_xml, 'r'), 'xml', from_encoding='utf-8') for elem in soup.findAll('item'): if elem.get('android:id') == '@+id/menu_openfile': elem['android:showAsAction'] = "never" elem['android:visible'] = "false" flushxml(soup, 'menu', menu_xml, head=False)
[ "def", "step_update_main_menu_xml", "(", "jsdata", ",", "*", "*", "options", ")", ":", "move_to_android_placeholder", "(", ")", "# Parse and edit res/menu/main.xml", "menu_xml", "=", "os", ".", "path", ".", "join", "(", "ANDROID_PATH", ",", "'res'", ",", "'menu'", ",", "'menu_main.xml'", ")", "soup", "=", "soup", "=", "BeautifulSoup", "(", "open", "(", "menu_xml", ",", "'r'", ")", ",", "'xml'", ",", "from_encoding", "=", "'utf-8'", ")", "for", "elem", "in", "soup", ".", "findAll", "(", "'item'", ")", ":", "if", "elem", ".", "get", "(", "'android:id'", ")", "==", "'@+id/menu_openfile'", ":", "elem", "[", "'android:showAsAction'", "]", "=", "\"never\"", "elem", "[", "'android:visible'", "]", "=", "\"false\"", "flushxml", "(", "soup", ",", "'menu'", ",", "menu_xml", ",", "head", "=", "False", ")" ]
https://github.com/kiwix/kiwix-xulrunner/blob/38f4a10ae4b1585c16cb11730bb0dcc4924ae19f/android/gen-custom-android-build.py#L320-L333
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/client/timeline.py
python
Timeline._alloc_pid
(self)
return pid
Allocate a process Id.
Allocate a process Id.
[ "Allocate", "a", "process", "Id", "." ]
def _alloc_pid(self): """Allocate a process Id.""" pid = self._next_pid self._next_pid += 1 return pid
[ "def", "_alloc_pid", "(", "self", ")", ":", "pid", "=", "self", ".", "_next_pid", "self", ".", "_next_pid", "+=", "1", "return", "pid" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/client/timeline.py#L375-L379
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/compiler-rt/lib/asan/scripts/asan_symbolize.py
python
LLVMSymbolizer.symbolize
(self, addr, binary, offset)
return result
Overrides Symbolizer.symbolize.
Overrides Symbolizer.symbolize.
[ "Overrides", "Symbolizer", ".", "symbolize", "." ]
def symbolize(self, addr, binary, offset): """Overrides Symbolizer.symbolize.""" if not self.pipe: return None result = [] try: symbolizer_input = '"%s" %s' % (binary, offset) if DEBUG: print symbolizer_input print >> self.pipe.stdin, symbolizer_input while True: function_name = self.pipe.stdout.readline().rstrip() if not function_name: break file_name = self.pipe.stdout.readline().rstrip() file_name = fix_filename(file_name) if (not function_name.startswith('??') or not file_name.startswith('??')): # Append only non-trivial frames. result.append('%s in %s %s' % (addr, function_name, file_name)) except Exception: result = [] if not result: result = None return result
[ "def", "symbolize", "(", "self", ",", "addr", ",", "binary", ",", "offset", ")", ":", "if", "not", "self", ".", "pipe", ":", "return", "None", "result", "=", "[", "]", "try", ":", "symbolizer_input", "=", "'\"%s\" %s'", "%", "(", "binary", ",", "offset", ")", "if", "DEBUG", ":", "print", "symbolizer_input", "print", ">>", "self", ".", "pipe", ".", "stdin", ",", "symbolizer_input", "while", "True", ":", "function_name", "=", "self", ".", "pipe", ".", "stdout", ".", "readline", "(", ")", ".", "rstrip", "(", ")", "if", "not", "function_name", ":", "break", "file_name", "=", "self", ".", "pipe", ".", "stdout", ".", "readline", "(", ")", ".", "rstrip", "(", ")", "file_name", "=", "fix_filename", "(", "file_name", ")", "if", "(", "not", "function_name", ".", "startswith", "(", "'??'", ")", "or", "not", "file_name", ".", "startswith", "(", "'??'", ")", ")", ":", "# Append only non-trivial frames.", "result", ".", "append", "(", "'%s in %s %s'", "%", "(", "addr", ",", "function_name", ",", "file_name", ")", ")", "except", "Exception", ":", "result", "=", "[", "]", "if", "not", "result", ":", "result", "=", "None", "return", "result" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/compiler-rt/lib/asan/scripts/asan_symbolize.py#L100-L125
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakeFile.SetContents
(self, contents)
Sets the file contents and size. Args: contents: string, new content of file.
Sets the file contents and size.
[ "Sets", "the", "file", "contents", "and", "size", "." ]
def SetContents(self, contents): """Sets the file contents and size. Args: contents: string, new content of file. """ # Wrap byte arrays into a safe format if sys.version_info >= (3, 0) and isinstance(contents, bytes): contents = Hexlified(contents) self.st_size = len(contents) self.contents = contents self.epoch += 1
[ "def", "SetContents", "(", "self", ",", "contents", ")", ":", "# Wrap byte arrays into a safe format", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", "and", "isinstance", "(", "contents", ",", "bytes", ")", ":", "contents", "=", "Hexlified", "(", "contents", ")", "self", ".", "st_size", "=", "len", "(", "contents", ")", "self", ".", "contents", "=", "contents", "self", ".", "epoch", "+=", "1" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L238-L250
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/tools/scan-build-py/libear/__init__.py
python
Toolset.set_compiler
(self, compiler)
part of public interface
part of public interface
[ "part", "of", "public", "interface" ]
def set_compiler(self, compiler): """ part of public interface """ self.compiler = compiler
[ "def", "set_compiler", "(", "self", ",", "compiler", ")", ":", "self", ".", "compiler", "=", "compiler" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libear/__init__.py#L87-L89
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/floatcanvas/FloatCanvas.py
python
_colorGenerator
()
return _cycleidxs(indexcount=3, maxvalue=256, step=1)
Generates a series of unique colors used to do hit-tests with the Hit Test bitmap
Generates a series of unique colors used to do hit-tests with the Hit Test bitmap
[ "Generates", "a", "series", "of", "unique", "colors", "used", "to", "do", "hit", "-", "tests", "with", "the", "Hit", "Test", "bitmap" ]
def _colorGenerator(): """ Generates a series of unique colors used to do hit-tests with the Hit Test bitmap """ return _cycleidxs(indexcount=3, maxvalue=256, step=1)
[ "def", "_colorGenerator", "(", ")", ":", "return", "_cycleidxs", "(", "indexcount", "=", "3", ",", "maxvalue", "=", "256", ",", "step", "=", "1", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/floatcanvas/FloatCanvas.py#L138-L144
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
examples/python/route_guide/route_guide_pb2_grpc.py
python
RouteGuideServicer.RecordRoute
(self, request_iterator, context)
A client-to-server streaming RPC. Accepts a stream of Points on a route being traversed, returning a RouteSummary when traversal is completed.
A client-to-server streaming RPC.
[ "A", "client", "-", "to", "-", "server", "streaming", "RPC", "." ]
def RecordRoute(self, request_iterator, context): """A client-to-server streaming RPC. Accepts a stream of Points on a route being traversed, returning a RouteSummary when traversal is completed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def", "RecordRoute", "(", "self", ",", "request_iterator", ",", "context", ")", ":", "context", ".", "set_code", "(", "grpc", ".", "StatusCode", ".", "UNIMPLEMENTED", ")", "context", ".", "set_details", "(", "'Method not implemented!'", ")", "raise", "NotImplementedError", "(", "'Method not implemented!'", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/examples/python/route_guide/route_guide_pb2_grpc.py#L67-L75
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
DateTime.ParseFormat
(*args, **kwargs)
return _misc_.DateTime_ParseFormat(*args, **kwargs)
ParseFormat(self, String date, String format=DefaultDateTimeFormat, DateTime dateDef=DefaultDateTime) -> int
ParseFormat(self, String date, String format=DefaultDateTimeFormat, DateTime dateDef=DefaultDateTime) -> int
[ "ParseFormat", "(", "self", "String", "date", "String", "format", "=", "DefaultDateTimeFormat", "DateTime", "dateDef", "=", "DefaultDateTime", ")", "-", ">", "int" ]
def ParseFormat(*args, **kwargs): """ParseFormat(self, String date, String format=DefaultDateTimeFormat, DateTime dateDef=DefaultDateTime) -> int""" return _misc_.DateTime_ParseFormat(*args, **kwargs)
[ "def", "ParseFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_ParseFormat", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4134-L4136
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/extras.py
python
unique
(ar1, return_index=False, return_inverse=False)
return output
Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays.
Finds the unique elements of an array.
[ "Finds", "the", "unique", "elements", "of", "an", "array", "." ]
def unique(ar1, return_index=False, return_inverse=False): """ Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays. """ output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output
[ "def", "unique", "(", "ar1", ",", "return_index", "=", "False", ",", "return_inverse", "=", "False", ")", ":", "output", "=", "np", ".", "unique", "(", "ar1", ",", "return_index", "=", "return_index", ",", "return_inverse", "=", "return_inverse", ")", "if", "isinstance", "(", "output", ",", "tuple", ")", ":", "output", "=", "list", "(", "output", ")", "output", "[", "0", "]", "=", "output", "[", "0", "]", ".", "view", "(", "MaskedArray", ")", "output", "=", "tuple", "(", "output", ")", "else", ":", "output", "=", "output", ".", "view", "(", "MaskedArray", ")", "return", "output" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/extras.py#L1073-L1094
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/ttk.py
python
Style.map
(self, style, query_opt=None, **kw)
return _splitdict( self.tk, self.tk.call(self._name, "map", style, *_format_mapdict(kw)), conv=_tclobj_to_py)
Query or sets dynamic values of the specified option(s) in style. Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, or list, or something else of your preference. A statespec is compound of one or more states and then a value.
Query or sets dynamic values of the specified option(s) in style.
[ "Query", "or", "sets", "dynamic", "values", "of", "the", "specified", "option", "(", "s", ")", "in", "style", "." ]
def map(self, style, query_opt=None, **kw): """Query or sets dynamic values of the specified option(s) in style. Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, or list, or something else of your preference. A statespec is compound of one or more states and then a value.""" if query_opt is not None: return _list_from_statespec(self.tk.splitlist( self.tk.call(self._name, "map", style, '-%s' % query_opt))) return _splitdict( self.tk, self.tk.call(self._name, "map", style, *_format_mapdict(kw)), conv=_tclobj_to_py)
[ "def", "map", "(", "self", ",", "style", ",", "query_opt", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "query_opt", "is", "not", "None", ":", "return", "_list_from_statespec", "(", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_name", ",", "\"map\"", ",", "style", ",", "'-%s'", "%", "query_opt", ")", ")", ")", "return", "_splitdict", "(", "self", ".", "tk", ",", "self", ".", "tk", ".", "call", "(", "self", ".", "_name", ",", "\"map\"", ",", "style", ",", "*", "_format_mapdict", "(", "kw", ")", ")", ",", "conv", "=", "_tclobj_to_py", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L389-L404
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/tools/scan-build-py/lib/libscanbuild/compilation.py
python
compiler_language
(command)
return None
A predicate to decide the command is a compiler call or not. Returns 'c' or 'c++' when it match. None otherwise.
A predicate to decide the command is a compiler call or not.
[ "A", "predicate", "to", "decide", "the", "command", "is", "a", "compiler", "call", "or", "not", "." ]
def compiler_language(command): """ A predicate to decide the command is a compiler call or not. Returns 'c' or 'c++' when it match. None otherwise. """ cplusplus = re.compile(r'^(.+)(\+\+)(-.+|)$') if command: executable = os.path.basename(command[0]) if any(pattern.match(executable) for pattern in COMPILER_PATTERNS): return 'c++' if cplusplus.match(executable) else 'c' return None
[ "def", "compiler_language", "(", "command", ")", ":", "cplusplus", "=", "re", ".", "compile", "(", "r'^(.+)(\\+\\+)(-.+|)$'", ")", "if", "command", ":", "executable", "=", "os", ".", "path", ".", "basename", "(", "command", "[", "0", "]", ")", "if", "any", "(", "pattern", ".", "match", "(", "executable", ")", "for", "pattern", "in", "COMPILER_PATTERNS", ")", ":", "return", "'c++'", "if", "cplusplus", ".", "match", "(", "executable", ")", "else", "'c'", "return", "None" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/tools/scan-build-py/lib/libscanbuild/compilation.py#L129-L140
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/molecule.py
python
Molecule.inertia_tensor_partial
(self, part, masswt=True, zero=ZERO)
return tensor
Compute inertia tensor based on atoms in *part*.
Compute inertia tensor based on atoms in *part*.
[ "Compute", "inertia", "tensor", "based", "on", "atoms", "in", "*", "part", "*", "." ]
def inertia_tensor_partial(self, part, masswt=True, zero=ZERO): """Compute inertia tensor based on atoms in *part*. """ tensor = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in part: if masswt: # I(alpha, alpha) tensor[0][0] += self.mass(i) * (self.y(i) * self.y(i) + self.z(i) * self.z(i)) tensor[1][1] += self.mass(i) * (self.x(i) * self.x(i) + self.z(i) * self.z(i)) tensor[2][2] += self.mass(i) * (self.x(i) * self.x(i) + self.y(i) * self.y(i)) # I(alpha, beta) tensor[0][1] -= self.mass(i) * self.x(i) * self.y(i) tensor[0][2] -= self.mass(i) * self.x(i) * self.z(i) tensor[1][2] -= self.mass(i) * self.y(i) * self.z(i) else: # I(alpha, alpha) tensor[0][0] += self.y(i) * self.y(i) + self.z(i) * self.z(i) tensor[1][1] += self.x(i) * self.x(i) + self.z(i) * self.z(i) tensor[2][2] += self.x(i) * self.x(i) + self.y(i) * self.y(i) # I(alpha, beta) tensor[0][1] -= self.x(i) * self.y(i) tensor[0][2] -= self.x(i) * self.z(i) tensor[1][2] -= self.y(i) * self.z(i) # mirror tensor[1][0] = tensor[0][1] tensor[2][0] = tensor[0][2] tensor[2][1] = tensor[1][2] # Check the elements for zero and make them a hard zero. for i in range(3): for j in range(3): if math.fabs(tensor[i][j]) < zero: tensor[i][j] = 0.0 return tensor
[ "def", "inertia_tensor_partial", "(", "self", ",", "part", ",", "masswt", "=", "True", ",", "zero", "=", "ZERO", ")", ":", "tensor", "=", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", "for", "i", "in", "part", ":", "if", "masswt", ":", "# I(alpha, alpha)", "tensor", "[", "0", "]", "[", "0", "]", "+=", "self", ".", "mass", "(", "i", ")", "*", "(", "self", ".", "y", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "+", "self", ".", "z", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", ")", "tensor", "[", "1", "]", "[", "1", "]", "+=", "self", ".", "mass", "(", "i", ")", "*", "(", "self", ".", "x", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "+", "self", ".", "z", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", ")", "tensor", "[", "2", "]", "[", "2", "]", "+=", "self", ".", "mass", "(", "i", ")", "*", "(", "self", ".", "x", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "+", "self", ".", "y", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", ")", "# I(alpha, beta)", "tensor", "[", "0", "]", "[", "1", "]", "-=", "self", ".", "mass", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "tensor", "[", "0", "]", "[", "2", "]", "-=", "self", ".", "mass", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "tensor", "[", "1", "]", "[", "2", "]", "-=", "self", ".", "mass", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "else", ":", "# I(alpha, alpha)", "tensor", "[", "0", "]", "[", "0", "]", "+=", "self", ".", "y", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "+", "self", ".", "z", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "tensor", "[", "1", "]", "[", "1", "]", "+=", "self", ".", "x", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "+", "self", ".", "z", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "tensor", "[", "2", "]", "[", "2", "]", "+=", "self", ".", "x", "(", "i", ")", "*", "self", ".", "x", "(", "i", ")", "+", "self", ".", "y", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "# I(alpha, beta)", "tensor", "[", "0", "]", "[", "1", "]", "-=", "self", ".", "x", "(", "i", ")", "*", "self", ".", "y", "(", "i", ")", "tensor", "[", "0", "]", "[", "2", "]", "-=", "self", ".", "x", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "tensor", "[", "1", "]", "[", "2", "]", "-=", "self", ".", "y", "(", "i", ")", "*", "self", ".", "z", "(", "i", ")", "# mirror", "tensor", "[", "1", "]", "[", "0", "]", "=", "tensor", "[", "0", "]", "[", "1", "]", "tensor", "[", "2", "]", "[", "0", "]", "=", "tensor", "[", "0", "]", "[", "2", "]", "tensor", "[", "2", "]", "[", "1", "]", "=", "tensor", "[", "1", "]", "[", "2", "]", "# Check the elements for zero and make them a hard zero.", "for", "i", "in", "range", "(", "3", ")", ":", "for", "j", "in", "range", "(", "3", ")", ":", "if", "math", ".", "fabs", "(", "tensor", "[", "i", "]", "[", "j", "]", ")", "<", "zero", ":", "tensor", "[", "i", "]", "[", "j", "]", "=", "0.0", "return", "tensor" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/molecule.py#L756-L795
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py
python
write_AIRSPEED_config
(f)
write airspeed config defines
write airspeed config defines
[ "write", "airspeed", "config", "defines" ]
def write_AIRSPEED_config(f): '''write airspeed config defines''' global airspeed_list devlist = [] seen = set() idx = 0 for dev in airspeed_list: if seen_str(dev) in seen: error("Duplicate AIRSPEED: %s" % seen_str(dev)) seen.add(seen_str(dev)) driver = dev[0] wrapper = '' a = driver.split(':') driver = a[0] for i in range(1, len(dev)): if dev[i].startswith("SPI:"): dev[i] = parse_spi_device(dev[i]) elif dev[i].startswith("I2C:"): (wrapper, dev[i]) = parse_i2c_device(dev[i]) if dev[i].startswith('hal.i2c_mgr'): dev[i] = 'std::move(%s)' % dev[i] n = len(devlist)+1 devlist.append('HAL_AIRSPEED_PROBE%u' % n) args = ['*this', str(idx)] + dev[1:] f.write( '#define HAL_AIRSPEED_PROBE%u %s ADD_BACKEND(AP_Airspeed_%s::probe(%s))\n' % (n, wrapper, driver, ','.join(args))) idx += 1 if len(devlist) > 0: f.write('#define HAL_AIRSPEED_PROBE_LIST %s\n\n' % ';'.join(devlist))
[ "def", "write_AIRSPEED_config", "(", "f", ")", ":", "global", "airspeed_list", "devlist", "=", "[", "]", "seen", "=", "set", "(", ")", "idx", "=", "0", "for", "dev", "in", "airspeed_list", ":", "if", "seen_str", "(", "dev", ")", "in", "seen", ":", "error", "(", "\"Duplicate AIRSPEED: %s\"", "%", "seen_str", "(", "dev", ")", ")", "seen", ".", "add", "(", "seen_str", "(", "dev", ")", ")", "driver", "=", "dev", "[", "0", "]", "wrapper", "=", "''", "a", "=", "driver", ".", "split", "(", "':'", ")", "driver", "=", "a", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "dev", ")", ")", ":", "if", "dev", "[", "i", "]", ".", "startswith", "(", "\"SPI:\"", ")", ":", "dev", "[", "i", "]", "=", "parse_spi_device", "(", "dev", "[", "i", "]", ")", "elif", "dev", "[", "i", "]", ".", "startswith", "(", "\"I2C:\"", ")", ":", "(", "wrapper", ",", "dev", "[", "i", "]", ")", "=", "parse_i2c_device", "(", "dev", "[", "i", "]", ")", "if", "dev", "[", "i", "]", ".", "startswith", "(", "'hal.i2c_mgr'", ")", ":", "dev", "[", "i", "]", "=", "'std::move(%s)'", "%", "dev", "[", "i", "]", "n", "=", "len", "(", "devlist", ")", "+", "1", "devlist", ".", "append", "(", "'HAL_AIRSPEED_PROBE%u'", "%", "n", ")", "args", "=", "[", "'*this'", ",", "str", "(", "idx", ")", "]", "+", "dev", "[", "1", ":", "]", "f", ".", "write", "(", "'#define HAL_AIRSPEED_PROBE%u %s ADD_BACKEND(AP_Airspeed_%s::probe(%s))\\n'", "%", "(", "n", ",", "wrapper", ",", "driver", ",", "','", ".", "join", "(", "args", ")", ")", ")", "idx", "+=", "1", "if", "len", "(", "devlist", ")", ">", "0", ":", "f", ".", "write", "(", "'#define HAL_AIRSPEED_PROBE_LIST %s\\n\\n'", "%", "';'", ".", "join", "(", "devlist", ")", ")" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py#L1448-L1477
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
tools/performance/benchmark_tool.py
python
CpuSpeedSettings.get_no_turbo
(self)
Return the current no-turbo state as string, either '1' or '0'.
Return the current no-turbo state as string, either '1' or '0'.
[ "Return", "the", "current", "no", "-", "turbo", "state", "as", "string", "either", "1", "or", "0", "." ]
def get_no_turbo(self): """Return the current no-turbo state as string, either '1' or '0'.""" with open(self.NO_TURBO_CONTROL_FILE, 'r', encoding='utf-8') as fo: return fo.read().strip()
[ "def", "get_no_turbo", "(", "self", ")", ":", "with", "open", "(", "self", ".", "NO_TURBO_CONTROL_FILE", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "fo", ":", "return", "fo", ".", "read", "(", ")", ".", "strip", "(", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/performance/benchmark_tool.py#L93-L96
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/decoder.py
python
StringDecoder
(field_number, is_repeated, is_packed, key, new_default)
Returns a decoder for a string field.
Returns a decoder for a string field.
[ "Returns", "a", "decoder", "for", "a", "string", "field", "." ]
def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint local_unicode = unicode assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) def DecodeRepeatedField(buffer, pos, end, message, field_dict): value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated string.') value.append(local_unicode(buffer[pos:new_pos], 'utf-8')) # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeRepeatedField else: def DecodeField(buffer, pos, end, message, field_dict): (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated string.') field_dict[key] = local_unicode(buffer[pos:new_pos], 'utf-8') return new_pos return DecodeField
[ "def", "StringDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "local_DecodeVarint", "=", "_DecodeVarint", "local_unicode", "=", "unicode", "assert", "not", "is_packed", "if", "is_repeated", ":", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "tag_len", "=", "len", "(", "tag_bytes", ")", "def", "DecodeRepeatedField", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "value", "=", "field_dict", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "key", ",", "new_default", "(", "message", ")", ")", "while", "1", ":", "(", "size", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "new_pos", "=", "pos", "+", "size", "if", "new_pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated string.'", ")", "value", ".", "append", "(", "local_unicode", "(", "buffer", "[", "pos", ":", "new_pos", "]", ",", "'utf-8'", ")", ")", "# Predict that the next tag is another copy of the same repeated field.", "pos", "=", "new_pos", "+", "tag_len", "if", "buffer", "[", "new_pos", ":", "pos", "]", "!=", "tag_bytes", "or", "new_pos", "==", "end", ":", "# Prediction failed. Return.", "return", "new_pos", "return", "DecodeRepeatedField", "else", ":", "def", "DecodeField", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "(", "size", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "new_pos", "=", "pos", "+", "size", "if", "new_pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated string.'", ")", "field_dict", "[", "key", "]", "=", "local_unicode", "(", "buffer", "[", "pos", ":", "new_pos", "]", ",", "'utf-8'", ")", "return", "new_pos", "return", "DecodeField" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/decoder.py#L377-L412
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/_cpwsgi.py
python
AppResponse.close
(self)
Close and de-reference the current request and response. (Core)
Close and de-reference the current request and response. (Core)
[ "Close", "and", "de", "-", "reference", "the", "current", "request", "and", "response", ".", "(", "Core", ")" ]
def close(self): """Close and de-reference the current request and response. (Core)""" self.cpapp.release_serving()
[ "def", "close", "(", "self", ")", ":", "self", ".", "cpapp", ".", "release_serving", "(", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/_cpwsgi.py#L263-L265
lighttransport/nanort
74063967336311f54ede5dffdfa242123825033b
deps/cpplint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_width", "(", "uc", ")", "in", "(", "'W'", ",", "'F'", ")", ":", "width", "+=", "2", "elif", "not", "unicodedata", ".", "combining", "(", "uc", ")", ":", "width", "+=", "1", "return", "width", "else", ":", "return", "len", "(", "line", ")" ]
https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L4351-L4370
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
parserCtxt.htmlCtxtUseOptions
(self, options)
return ret
Applies the options to the parser context
Applies the options to the parser context
[ "Applies", "the", "options", "to", "the", "parser", "context" ]
def htmlCtxtUseOptions(self, options): """Applies the options to the parser context """ ret = libxml2mod.htmlCtxtUseOptions(self._o, options) return ret
[ "def", "htmlCtxtUseOptions", "(", "self", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "htmlCtxtUseOptions", "(", "self", ".", "_o", ",", "options", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L4203-L4206
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosbag/src/rosbag/bag.py
python
_BagReader102_Unindexed.reindex
(self)
Generates all bag index information by rereading the message records.
Generates all bag index information by rereading the message records.
[ "Generates", "all", "bag", "index", "information", "by", "rereading", "the", "message", "records", "." ]
def reindex(self): """Generates all bag index information by rereading the message records.""" f = self.bag._file total_bytes = self.bag.size # Re-read the file header to get to the start of the first message self.bag._file.seek(self.bag._file_header_pos) offset = f.tell() # Read message definition and data records while offset < total_bytes: yield offset op = _peek_next_header_op(f) if op == _OP_MSG_DEF: connection_info = self.read_message_definition_record() if connection_info.topic not in self.bag._topic_connections: self.bag._topic_connections[connection_info.topic] = connection_info.id self.bag._connections[connection_info.id] = connection_info self.bag._connection_indexes[connection_info.id] = [] elif op == _OP_MSG_DATA: # Read the topic and timestamp from the header header = _read_header(f) topic = _read_str_field(header, 'topic') secs = _read_uint32_field(header, 'sec') nsecs = _read_uint32_field(header, 'nsec') t = genpy.Time(secs, nsecs) if topic not in self.bag._topic_connections: datatype = _read_str_field(header, 'type') self._create_connection_info_for_datatype(topic, datatype) connection_id = self.bag._topic_connections[topic] info = self.bag._connections[connection_id] # Skip over the message content _skip_sized(f) # Insert the message entry (in order) into the connection index bisect.insort_right(self.bag._connection_indexes[connection_id], _IndexEntry102(t, offset)) offset = f.tell()
[ "def", "reindex", "(", "self", ")", ":", "f", "=", "self", ".", "bag", ".", "_file", "total_bytes", "=", "self", ".", "bag", ".", "size", "# Re-read the file header to get to the start of the first message", "self", ".", "bag", ".", "_file", ".", "seek", "(", "self", ".", "bag", ".", "_file_header_pos", ")", "offset", "=", "f", ".", "tell", "(", ")", "# Read message definition and data records", "while", "offset", "<", "total_bytes", ":", "yield", "offset", "op", "=", "_peek_next_header_op", "(", "f", ")", "if", "op", "==", "_OP_MSG_DEF", ":", "connection_info", "=", "self", ".", "read_message_definition_record", "(", ")", "if", "connection_info", ".", "topic", "not", "in", "self", ".", "bag", ".", "_topic_connections", ":", "self", ".", "bag", ".", "_topic_connections", "[", "connection_info", ".", "topic", "]", "=", "connection_info", ".", "id", "self", ".", "bag", ".", "_connections", "[", "connection_info", ".", "id", "]", "=", "connection_info", "self", ".", "bag", ".", "_connection_indexes", "[", "connection_info", ".", "id", "]", "=", "[", "]", "elif", "op", "==", "_OP_MSG_DATA", ":", "# Read the topic and timestamp from the header", "header", "=", "_read_header", "(", "f", ")", "topic", "=", "_read_str_field", "(", "header", ",", "'topic'", ")", "secs", "=", "_read_uint32_field", "(", "header", ",", "'sec'", ")", "nsecs", "=", "_read_uint32_field", "(", "header", ",", "'nsec'", ")", "t", "=", "genpy", ".", "Time", "(", "secs", ",", "nsecs", ")", "if", "topic", "not", "in", "self", ".", "bag", ".", "_topic_connections", ":", "datatype", "=", "_read_str_field", "(", "header", ",", "'type'", ")", "self", ".", "_create_connection_info_for_datatype", "(", "topic", ",", "datatype", ")", "connection_id", "=", "self", ".", "bag", ".", "_topic_connections", "[", "topic", "]", "info", "=", "self", ".", "bag", ".", "_connections", "[", "connection_id", "]", "# Skip over the message content", "_skip_sized", "(", "f", ")", "# Insert the message entry (in order) into the connection index", "bisect", ".", "insort_right", "(", "self", ".", "bag", ".", "_connection_indexes", "[", "connection_id", "]", ",", "_IndexEntry102", "(", "t", ",", "offset", ")", ")", "offset", "=", "f", ".", "tell", "(", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/bag.py#L1749-L1796
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/ceph-volume/ceph_volume/devices/simple/scan.py
python
parse_keyring
(file_contents)
return keyring.strip()
Extract the actual key from a string. Usually from a keyring file, where the keyring will be in a client section. In the case of a lockbox, it is something like:: [client.osd-lockbox.8d7a8ab2-5db0-4f83-a785-2809aba403d5]\n\tkey = AQDtoGha/GYJExAA7HNl7Ukhqr7AKlCpLJk6UA==\n From the above case, it would return:: AQDtoGha/GYJExAA7HNl7Ukhqr7AKlCpLJk6UA==
Extract the actual key from a string. Usually from a keyring file, where the keyring will be in a client section. In the case of a lockbox, it is something like::
[ "Extract", "the", "actual", "key", "from", "a", "string", ".", "Usually", "from", "a", "keyring", "file", "where", "the", "keyring", "will", "be", "in", "a", "client", "section", ".", "In", "the", "case", "of", "a", "lockbox", "it", "is", "something", "like", "::" ]
def parse_keyring(file_contents): """ Extract the actual key from a string. Usually from a keyring file, where the keyring will be in a client section. In the case of a lockbox, it is something like:: [client.osd-lockbox.8d7a8ab2-5db0-4f83-a785-2809aba403d5]\n\tkey = AQDtoGha/GYJExAA7HNl7Ukhqr7AKlCpLJk6UA==\n From the above case, it would return:: AQDtoGha/GYJExAA7HNl7Ukhqr7AKlCpLJk6UA== """ # remove newlines that might be trailing keyring = file_contents.strip('\n') # Now split on spaces keyring = keyring.split(' ')[-1] # Split on newlines keyring = keyring.split('\n')[-1] return keyring.strip()
[ "def", "parse_keyring", "(", "file_contents", ")", ":", "# remove newlines that might be trailing", "keyring", "=", "file_contents", ".", "strip", "(", "'\\n'", ")", "# Now split on spaces", "keyring", "=", "keyring", ".", "split", "(", "' '", ")", "[", "-", "1", "]", "# Split on newlines", "keyring", "=", "keyring", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", "return", "keyring", ".", "strip", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/simple/scan.py#L18-L39
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/run.py
python
MyHandler.EOFhook
(self)
Override SocketIO method - terminate wait on callback and exit thread
Override SocketIO method - terminate wait on callback and exit thread
[ "Override", "SocketIO", "method", "-", "terminate", "wait", "on", "callback", "and", "exit", "thread" ]
def EOFhook(self): "Override SocketIO method - terminate wait on callback and exit thread" global quitting quitting = True thread.interrupt_main()
[ "def", "EOFhook", "(", "self", ")", ":", "global", "quitting", "quitting", "=", "True", "thread", ".", "interrupt_main", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/run.py#L279-L283
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/setitem_impl.py
python
_list_setitem_with_string
(data, number_index, value)
return F.list_setitem(data, number_index, value)
Assigns value to list. Inputs: data (list): Data of type list. number_index (Number): Index of data. Outputs: list, type is the same as the element type of data.
Assigns value to list.
[ "Assigns", "value", "to", "list", "." ]
def _list_setitem_with_string(data, number_index, value): """ Assigns value to list. Inputs: data (list): Data of type list. number_index (Number): Index of data. Outputs: list, type is the same as the element type of data. """ return F.list_setitem(data, number_index, value)
[ "def", "_list_setitem_with_string", "(", "data", ",", "number_index", ",", "value", ")", ":", "return", "F", ".", "list_setitem", "(", "data", ",", "number_index", ",", "value", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/setitem_impl.py#L27-L38
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py
python
_NNTPBase.body
(self, message_spec=None, *, file=None)
return self._artcmd(cmd, file)
Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines)
Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines)
[ "Process", "a", "BODY", "command", ".", "Argument", ":", "-", "message_spec", ":", "article", "number", "or", "message", "id", "-", "file", ":", "filename", "string", "or", "file", "object", "to", "store", "the", "body", "in", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "ArticleInfo", ":", "(", "article", "number", "message", "id", "list", "of", "body", "lines", ")" ]
def body(self, message_spec=None, *, file=None): """Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines) """ if message_spec is not None: cmd = 'BODY {0}'.format(message_spec) else: cmd = 'BODY' return self._artcmd(cmd, file)
[ "def", "body", "(", "self", ",", "message_spec", "=", "None", ",", "*", ",", "file", "=", "None", ")", ":", "if", "message_spec", "is", "not", "None", ":", "cmd", "=", "'BODY {0}'", ".", "format", "(", "message_spec", ")", "else", ":", "cmd", "=", "'BODY'", "return", "self", ".", "_artcmd", "(", "cmd", ",", "file", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L744-L756
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/build/android/pylib/valgrind_tools.py
python
MemcheckTool.GetTimeoutScale
(self)
return 30
Returns a multiplier that should be applied to timeout values.
Returns a multiplier that should be applied to timeout values.
[ "Returns", "a", "multiplier", "that", "should", "be", "applied", "to", "timeout", "values", "." ]
def GetTimeoutScale(self): """Returns a multiplier that should be applied to timeout values.""" return 30
[ "def", "GetTimeoutScale", "(", "self", ")", ":", "return", "30" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/valgrind_tools.py#L201-L203
heremaps/pptk
697c09ac1a5a652d43aa8c4deb98c27c3a0b77e3
pptk/viewer/viewer.py
python
viewer.wait
(self)
Blocks until :kbd:`Enter`/:kbd:`Return` key is pressed in viewer Examples: >>> v = pptk.viewer(xyz) >>> v.wait() Press enter in viewer to return control to python terminal.
[]
def wait(self): """ Blocks until :kbd:`Enter`/:kbd:`Return` key is pressed in viewer Examples: >>> v = pptk.viewer(xyz) >>> v.wait() Press enter in viewer to return control to python terminal. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', self._portNumber)) s.send(struct.pack('b', 7)) s.setblocking(1) buf = b'' while len(buf) == 0: buf += s.recv(1) if buf != b'x': raise RuntimeError('expecting return code \'x\'') s.close()
[ "def", "wait", "(", "self", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "s", ".", "connect", "(", "(", "'localhost'", ",", "self", ".", "_portNumber", ")", ")", "s", ".", "send", "(", "struct", ".", "pack", "(", "'b'", ",", "7", ")", ")", "s", ".", "setblocking", "(", "1", ")", "buf", "=", "b''", "while", "len", "(", "buf", ")", "==", "0", ":", "buf", "+=", "s", ".", "recv", "(", "1", ")", "if", "buf", "!=", "b'x'", ":", "raise", "RuntimeError", "(", "'expecting return code \\'x\\''", ")", "s", ".", "close", "(", ")" ]
https://github.com/heremaps/pptk/blob/697c09ac1a5a652d43aa8c4deb98c27c3a0b77e3/pptk/viewer/viewer.py#L408-L430
psmoveservice/PSMoveService
22bbe20e9de53f3f3581137bce7b88e2587a27e7
misc/python/pypsmove/transformations.py
python
unit_vector
(data, axis=None, out=None)
Return ndarray normalized by length, i.e. Euclidean norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) >>> numpy.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) >>> numpy.allclose(v1, v2) True >>> v1 = numpy.empty((5, 4, 3)) >>> unit_vector(v0, axis=1, out=v1) >>> numpy.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1])) [1.0]
Return ndarray normalized by length, i.e. Euclidean norm, along axis.
[ "Return", "ndarray", "normalized", "by", "length", "i", ".", "e", ".", "Euclidean", "norm", "along", "axis", "." ]
def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. Euclidean norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) >>> numpy.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) >>> numpy.allclose(v1, v2) True >>> v1 = numpy.empty((5, 4, 3)) >>> unit_vector(v0, axis=1, out=v1) >>> numpy.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1])) [1.0] """ if out is None: data = numpy.array(data, dtype=numpy.float64, copy=True) if data.ndim == 1: data /= math.sqrt(numpy.dot(data, data)) return data else: if out is not data: out[:] = numpy.array(data, copy=False) data = out length = numpy.atleast_1d(numpy.sum(data*data, axis)) numpy.sqrt(length, length) if axis is not None: length = numpy.expand_dims(length, axis) data /= length if out is None: return data
[ "def", "unit_vector", "(", "data", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "data", "=", "numpy", ".", "array", "(", "data", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "if", "data", ".", "ndim", "==", "1", ":", "data", "/=", "math", ".", "sqrt", "(", "numpy", ".", "dot", "(", "data", ",", "data", ")", ")", "return", "data", "else", ":", "if", "out", "is", "not", "data", ":", "out", "[", ":", "]", "=", "numpy", ".", "array", "(", "data", ",", "copy", "=", "False", ")", "data", "=", "out", "length", "=", "numpy", ".", "atleast_1d", "(", "numpy", ".", "sum", "(", "data", "*", "data", ",", "axis", ")", ")", "numpy", ".", "sqrt", "(", "length", ",", "length", ")", "if", "axis", "is", "not", "None", ":", "length", "=", "numpy", ".", "expand_dims", "(", "length", ",", "axis", ")", "data", "/=", "length", "if", "out", "is", "None", ":", "return", "data" ]
https://github.com/psmoveservice/PSMoveService/blob/22bbe20e9de53f3f3581137bce7b88e2587a27e7/misc/python/pypsmove/transformations.py#L1722-L1763
PlatformLab/Arachne
e67391471007174dd4002dc2c160628e19c284e8
scripts/cpplint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "(", "line", "[", "pos", "]", "not", "in", "'({[<'", ")", "or", "Match", "(", "r'<[<=]'", ",", "line", "[", "pos", ":", "]", ")", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "# Check first line", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "[", "]", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Continue scanning forward", "while", "stack", "and", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "stack", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "stack", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Did not find end of expression before end of file, give up", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")" ]
https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L1570-L1611