nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.GetExtraStyle
(*args, **kwargs)
return _core_.Window_GetExtraStyle(*args, **kwargs)
GetExtraStyle(self) -> long Returns the extra style bits for the window.
GetExtraStyle(self) -> long
[ "GetExtraStyle", "(", "self", ")", "-", ">", "long" ]
def GetExtraStyle(*args, **kwargs): """ GetExtraStyle(self) -> long Returns the extra style bits for the window. """ return _core_.Window_GetExtraStyle(*args, **kwargs)
[ "def", "GetExtraStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetExtraStyle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L10073-L10079
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/geodesy/bounding_box.py
python
isGlobal
(bbox)
return bbox.min_pt.latitude != bbox.min_pt.latitude
Global bounding box predicate. :param bbox: `geographic_msgs/BoundingBox`_. :returns: True if *bbox* matches any global coordinate.
Global bounding box predicate.
[ "Global", "bounding", "box", "predicate", "." ]
def isGlobal(bbox): """ Global bounding box predicate. :param bbox: `geographic_msgs/BoundingBox`_. :returns: True if *bbox* matches any global coordinate. """ return bbox.min_pt.latitude != bbox.min_pt.latitude
[ "def", "isGlobal", "(", "bbox", ")", ":", "return", "bbox", ".", "min_pt", ".", "latitude", "!=", "bbox", ".", "min_pt", ".", "latitude" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/geodesy/bounding_box.py#L63-L70
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.add_ipmaddr
(self, ip: Union[str, ipaddress.IPv6Address])
Subscribe the Thread interface to the IPv6 multicast address.
Subscribe the Thread interface to the IPv6 multicast address.
[ "Subscribe", "the", "Thread", "interface", "to", "the", "IPv6", "multicast", "address", "." ]
def add_ipmaddr(self, ip: Union[str, ipaddress.IPv6Address]): """Subscribe the Thread interface to the IPv6 multicast address.""" self.execute_command(f'ipmaddr add {ip}')
[ "def", "add_ipmaddr", "(", "self", ",", "ip", ":", "Union", "[", "str", ",", "ipaddress", ".", "IPv6Address", "]", ")", ":", "self", ".", "execute_command", "(", "f'ipmaddr add {ip}'", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L1908-L1910
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/python/caffe/coord_map.py
python
coord_map_from_to
(top_from, top_to)
Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted.
Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted.
[ "Determine", "the", "coordinate", "mapping", "betweeen", "a", "top", "(", "from", ")", "and", "a", "top", "(", "to", ")", ".", "Walk", "the", "graph", "to", "find", "a", "common", "ancestor", "while", "composing", "the", "coord", "maps", "for", "from", "and", "to", "until", "they", "meet", ".", "As", "a", "last", "step", "the", "from", "map", "is", "inverted", "." ]
def coord_map_from_to(top_from, top_to): """ Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted. """ # We need to find a common ancestor of top_from and top_to. # We'll assume that all ancestors are equivalent here (otherwise the graph # is an inconsistent state (which we could improve this to check for)). # For now use a brute-force algorithm. def collect_bottoms(top): """ Collect the bottoms to walk for the coordinate mapping. The general rule is that all the bottoms of a layer can be mapped, as most layers have the same coordinate mapping for each bottom. Crop layer is a notable exception. Only the first/cropped bottom is mappable; the second/dimensions bottom is excluded from the walk. """ bottoms = top.fn.inputs if top.fn.type_name == 'Crop': bottoms = bottoms[:1] return bottoms # walk back from top_from, keeping the coord map as we go from_maps = {top_from: (None, 1, 0)} frontier = {top_from} while frontier: top = frontier.pop() try: bottoms = collect_bottoms(top) for bottom in bottoms: from_maps[bottom] = compose(from_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: pass # now walk back from top_to until we hit a common blob to_maps = {top_to: (None, 1, 0)} frontier = {top_to} while frontier: top = frontier.pop() if top in from_maps: return compose(to_maps[top], inverse(from_maps[top])) try: bottoms = collect_bottoms(top) for bottom in bottoms: to_maps[bottom] = compose(to_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: continue # if we got here, we did not find a blob in common raise RuntimeError('Could not compute map between tops; are they ' 'connected by spatial layers?')
[ "def", "coord_map_from_to", "(", "top_from", ",", "top_to", ")", ":", "# We need to find a common ancestor of top_from and top_to.", "# We'll assume that all ancestors are equivalent here (otherwise the graph", "# is an inconsistent state (which we could improve this to check for)).", "# For now use a brute-force algorithm.", "def", "collect_bottoms", "(", "top", ")", ":", "\"\"\"\n Collect the bottoms to walk for the coordinate mapping.\n The general rule is that all the bottoms of a layer can be mapped, as\n most layers have the same coordinate mapping for each bottom.\n Crop layer is a notable exception. Only the first/cropped bottom is\n mappable; the second/dimensions bottom is excluded from the walk.\n \"\"\"", "bottoms", "=", "top", ".", "fn", ".", "inputs", "if", "top", ".", "fn", ".", "type_name", "==", "'Crop'", ":", "bottoms", "=", "bottoms", "[", ":", "1", "]", "return", "bottoms", "# walk back from top_from, keeping the coord map as we go", "from_maps", "=", "{", "top_from", ":", "(", "None", ",", "1", ",", "0", ")", "}", "frontier", "=", "{", "top_from", "}", "while", "frontier", ":", "top", "=", "frontier", ".", "pop", "(", ")", "try", ":", "bottoms", "=", "collect_bottoms", "(", "top", ")", "for", "bottom", "in", "bottoms", ":", "from_maps", "[", "bottom", "]", "=", "compose", "(", "from_maps", "[", "top", "]", ",", "coord_map", "(", "top", ".", "fn", ")", ")", "frontier", ".", "add", "(", "bottom", ")", "except", "UndefinedMapException", ":", "pass", "# now walk back from top_to until we hit a common blob", "to_maps", "=", "{", "top_to", ":", "(", "None", ",", "1", ",", "0", ")", "}", "frontier", "=", "{", "top_to", "}", "while", "frontier", ":", "top", "=", "frontier", ".", "pop", "(", ")", "if", "top", "in", "from_maps", ":", "return", "compose", "(", "to_maps", "[", "top", "]", ",", "inverse", "(", "from_maps", "[", "top", "]", ")", ")", "try", ":", "bottoms", "=", "collect_bottoms", "(", "top", ")", "for", "bottom", "in", "bottoms", ":", "to_maps", "[", "bottom", "]", "=", "compose", "(", "to_maps", "[", "top", "]", ",", "coord_map", "(", "top", ".", "fn", ")", ")", "frontier", ".", "add", "(", "bottom", ")", "except", "UndefinedMapException", ":", "continue", "# if we got here, we did not find a blob in common", "raise", "RuntimeError", "(", "'Could not compute map between tops; are they '", "'connected by spatial layers?'", ")" ]
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/coord_map.py#L115-L169
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/transforms.py
python
sort
(pcollection, reverse=False)
return bigflow.transform_impls.sort.sort(pcollection, reverse)
对于输入PCollection,将其进行排序 Args: pcollection (PCollection): 输入PCollection reverse (bool): 若True则降序排列,否则为升序排列 Returns: PCollection: 排序结果 >>> from bigflow import transforms >>> _p = _pipeline.parallelize([3, 1, 2, 8]) >>> transforms.sort(_p).get() [1, 2, 3, 8]
对于输入PCollection,将其进行排序
[ "对于输入PCollection,将其进行排序" ]
def sort(pcollection, reverse=False): """ 对于输入PCollection,将其进行排序 Args: pcollection (PCollection): 输入PCollection reverse (bool): 若True则降序排列,否则为升序排列 Returns: PCollection: 排序结果 >>> from bigflow import transforms >>> _p = _pipeline.parallelize([3, 1, 2, 8]) >>> transforms.sort(_p).get() [1, 2, 3, 8] """ import bigflow.transform_impls.sort return bigflow.transform_impls.sort.sort(pcollection, reverse)
[ "def", "sort", "(", "pcollection", ",", "reverse", "=", "False", ")", ":", "import", "bigflow", ".", "transform_impls", ".", "sort", "return", "bigflow", ".", "transform_impls", ".", "sort", ".", "sort", "(", "pcollection", ",", "reverse", ")" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/transforms.py#L840-L858
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/util/__init__.py
python
_try_inject_s3_credentials
(url)
Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey] If s3 url already contains secret key/id pairs, just return as is.
Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]
[ "Inject", "aws", "credentials", "into", "s3", "url", "as", "s3", ":", "//", "[", "aws_id", "]", ":", "[", "aws_key", "]", ":", "[", "bucket", "/", "]", "[", "objectkey", "]" ]
def _try_inject_s3_credentials(url): """ Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey] If s3 url already contains secret key/id pairs, just return as is. """ assert url.startswith("s3://") path = url[5:] # Check if the path already contains credentials tokens = path.split(":") # If there are two ':', its possible that we have already injected credentials if len(tokens) == 3: # Edge case: there are exactly two ':'s in the object key which is a false alarm. # We prevent this by checking that '/' is not in the assumed key and id. if ("/" not in tokens[0]) and ("/" not in tokens[1]): return url # S3 url does not contain secret key/id pair, query the environment variables (k, v) = _get_aws_credentials() # below is the form that turi customized, used in C++ impl. # s3://[access_key_id]:[secret_key]:[endpoint/]:[bucket]/[object_name] if path: return "s3://" + k + ":" + v + ":" + path raise ValueError("bucket not set for %s." % url)
[ "def", "_try_inject_s3_credentials", "(", "url", ")", ":", "assert", "url", ".", "startswith", "(", "\"s3://\"", ")", "path", "=", "url", "[", "5", ":", "]", "# Check if the path already contains credentials", "tokens", "=", "path", ".", "split", "(", "\":\"", ")", "# If there are two ':', its possible that we have already injected credentials", "if", "len", "(", "tokens", ")", "==", "3", ":", "# Edge case: there are exactly two ':'s in the object key which is a false alarm.", "# We prevent this by checking that '/' is not in the assumed key and id.", "if", "(", "\"/\"", "not", "in", "tokens", "[", "0", "]", ")", "and", "(", "\"/\"", "not", "in", "tokens", "[", "1", "]", ")", ":", "return", "url", "# S3 url does not contain secret key/id pair, query the environment variables", "(", "k", ",", "v", ")", "=", "_get_aws_credentials", "(", ")", "# below is the form that turi customized, used in C++ impl.", "# s3://[access_key_id]:[secret_key]:[endpoint/]:[bucket]/[object_name]", "if", "path", ":", "return", "\"s3://\"", "+", "k", "+", "\":\"", "+", "v", "+", "\":\"", "+", "path", "raise", "ValueError", "(", "\"bucket not set for %s.\"", "%", "url", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/util/__init__.py#L77-L102
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_CognitoIdPoolSharedRole.py
python
handler
(event, context)
return custom_resource_response.success_response({'Arn': arn}, arn)
Entry point for the Custom::CognitoIdPoolSharedRole resource handler.
Entry point for the Custom::CognitoIdPoolSharedRole resource handler.
[ "Entry", "point", "for", "the", "Custom", "::", "CognitoIdPoolSharedRole", "resource", "handler", "." ]
def handler(event, context): """Entry point for the Custom::CognitoIdPoolSharedRole resource handler.""" stack_id = event['StackId'] if event['RequestType'] == 'Delete': return custom_resource_response.success_response({'Arn': ''}, '') props = properties.load(event, { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'LogicalPoolName': properties.String(), 'RoleType': properties.String(default=""), 'Path': properties.String(), 'AssumeRolePolicyDocument': properties.Dictionary() }) stack_manager = stack_info.StackInfoManager() stack = stack_manager.get_stack_info(stack_id) identity_client = identity_pool.get_identity_client() cognito_pool_info = aws_utils.get_cognito_pool_from_file(props.ConfigurationBucket, props.ConfigurationKey, props.LogicalPoolName, stack) arn = '' if cognito_pool_info: response = identity_client.get_identity_pool_roles(IdentityPoolId=cognito_pool_info['PhysicalResourceId']) arn = response.get("Roles", {}).get(props.RoleType, "") else: # Set up resource tags for all resources created tags = [ {"Key": constant.PROJECT_NAME_TAG, "Value": stack.project_stack.project_name}, {"Key": constant.STACK_ID_TAG, "Value": stack_id} ] name = "{}{}Role".format(stack.stack_name, event['LogicalResourceId']) arn = _create_role(name, props, tags) return custom_resource_response.success_response({'Arn': arn}, arn)
[ "def", "handler", "(", "event", ",", "context", ")", ":", "stack_id", "=", "event", "[", "'StackId'", "]", "if", "event", "[", "'RequestType'", "]", "==", "'Delete'", ":", "return", "custom_resource_response", ".", "success_response", "(", "{", "'Arn'", ":", "''", "}", ",", "''", ")", "props", "=", "properties", ".", "load", "(", "event", ",", "{", "'ConfigurationBucket'", ":", "properties", ".", "String", "(", ")", ",", "'ConfigurationKey'", ":", "properties", ".", "String", "(", ")", ",", "'LogicalPoolName'", ":", "properties", ".", "String", "(", ")", ",", "'RoleType'", ":", "properties", ".", "String", "(", "default", "=", "\"\"", ")", ",", "'Path'", ":", "properties", ".", "String", "(", ")", ",", "'AssumeRolePolicyDocument'", ":", "properties", ".", "Dictionary", "(", ")", "}", ")", "stack_manager", "=", "stack_info", ".", "StackInfoManager", "(", ")", "stack", "=", "stack_manager", ".", "get_stack_info", "(", "stack_id", ")", "identity_client", "=", "identity_pool", ".", "get_identity_client", "(", ")", "cognito_pool_info", "=", "aws_utils", ".", "get_cognito_pool_from_file", "(", "props", ".", "ConfigurationBucket", ",", "props", ".", "ConfigurationKey", ",", "props", ".", "LogicalPoolName", ",", "stack", ")", "arn", "=", "''", "if", "cognito_pool_info", ":", "response", "=", "identity_client", ".", "get_identity_pool_roles", "(", "IdentityPoolId", "=", "cognito_pool_info", "[", "'PhysicalResourceId'", "]", ")", "arn", "=", "response", ".", "get", "(", "\"Roles\"", ",", "{", "}", ")", ".", "get", "(", "props", ".", "RoleType", ",", "\"\"", ")", "else", ":", "# Set up resource tags for all resources created", "tags", "=", "[", "{", "\"Key\"", ":", "constant", ".", "PROJECT_NAME_TAG", ",", "\"Value\"", ":", "stack", ".", "project_stack", ".", "project_name", "}", ",", "{", "\"Key\"", ":", "constant", ".", "STACK_ID_TAG", ",", "\"Value\"", ":", "stack_id", "}", "]", "name", "=", "\"{}{}Role\"", ".", "format", "(", "stack", ".", "stack_name", ",", "event", "[", "'LogicalResourceId'", "]", ")", "arn", "=", "_create_role", "(", "name", ",", "props", ",", "tags", ")", "return", "custom_resource_response", ".", "success_response", "(", "{", "'Arn'", ":", "arn", "}", ",", "arn", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_CognitoIdPoolSharedRole.py#L25-L62
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py
python
packages_distributions
()
return dict(pkg_to_dist)
Return a mapping of top-level packages to their distributions. >>> import collections.abc >>> pkgs = packages_distributions() >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) True
Return a mapping of top-level packages to their distributions.
[ "Return", "a", "mapping", "of", "top", "-", "level", "packages", "to", "their", "distributions", "." ]
def packages_distributions() -> Mapping[str, List[str]]: """ Return a mapping of top-level packages to their distributions. >>> import collections.abc >>> pkgs = packages_distributions() >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) True """ pkg_to_dist = collections.defaultdict(list) for dist in distributions(): for pkg in _top_level_declared(dist) or _top_level_inferred(dist): pkg_to_dist[pkg].append(dist.metadata['Name']) return dict(pkg_to_dist)
[ "def", "packages_distributions", "(", ")", "->", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", ":", "pkg_to_dist", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "dist", "in", "distributions", "(", ")", ":", "for", "pkg", "in", "_top_level_declared", "(", "dist", ")", "or", "_top_level_inferred", "(", "dist", ")", ":", "pkg_to_dist", "[", "pkg", "]", ".", "append", "(", "dist", ".", "metadata", "[", "'Name'", "]", ")", "return", "dict", "(", "pkg_to_dist", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py3/importlib_metadata/__init__.py#L1087-L1101
nasa/trick
7b85aa66329d62fe8816462627c09a353aac8299
share/trick/pymods/trick/variable_server.py
python
VariableServer.readline
(self, synchronous_channel=True)
return Message(int(line[0]), line[1])
Read a newline-terminated line, blocking if necessary. Calling this directly is only necessary if you have directly called send and expect a response from the variable server. The newline character is stripped. Parameters ---------- synchronous_channel : bool True to read from the synchronous channel. False to read from the asynchronous channel. Returns ------- Message The next available message. Raises ------ IOError If the remote endpoint has closed the connection.
Read a newline-terminated line, blocking if necessary. Calling this directly is only necessary if you have directly called send and expect a response from the variable server. The newline character is stripped.
[ "Read", "a", "newline", "-", "terminated", "line", "blocking", "if", "necessary", ".", "Calling", "this", "directly", "is", "only", "necessary", "if", "you", "have", "directly", "called", "send", "and", "expect", "a", "response", "from", "the", "variable", "server", ".", "The", "newline", "character", "is", "stripped", "." ]
def readline(self, synchronous_channel=True): """ Read a newline-terminated line, blocking if necessary. Calling this directly is only necessary if you have directly called send and expect a response from the variable server. The newline character is stripped. Parameters ---------- synchronous_channel : bool True to read from the synchronous channel. False to read from the asynchronous channel. Returns ------- Message The next available message. Raises ------ IOError If the remote endpoint has closed the connection. """ file_interface = (self._synchronous_file_interface if synchronous_channel else self._asynchronous_file_interface) line = file_interface.readline() if not line: raise IOError("The remote endpoint has closed the connection") line = line.rstrip(os.linesep).split('\t', 1) return Message(int(line[0]), line[1])
[ "def", "readline", "(", "self", ",", "synchronous_channel", "=", "True", ")", ":", "file_interface", "=", "(", "self", ".", "_synchronous_file_interface", "if", "synchronous_channel", "else", "self", ".", "_asynchronous_file_interface", ")", "line", "=", "file_interface", ".", "readline", "(", ")", "if", "not", "line", ":", "raise", "IOError", "(", "\"The remote endpoint has closed the connection\"", ")", "line", "=", "line", ".", "rstrip", "(", "os", ".", "linesep", ")", ".", "split", "(", "'\\t'", ",", "1", ")", "return", "Message", "(", "int", "(", "line", "[", "0", "]", ")", ",", "line", "[", "1", "]", ")" ]
https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/pymods/trick/variable_server.py#L901-L931
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'/**/'" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1615-L1620
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HelpControllerBase.SetViewer
(*args, **kwargs)
return _html.HelpControllerBase_SetViewer(*args, **kwargs)
SetViewer(self, String viewer, long flags=0)
SetViewer(self, String viewer, long flags=0)
[ "SetViewer", "(", "self", "String", "viewer", "long", "flags", "=", "0", ")" ]
def SetViewer(*args, **kwargs): """SetViewer(self, String viewer, long flags=0)""" return _html.HelpControllerBase_SetViewer(*args, **kwargs)
[ "def", "SetViewer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HelpControllerBase_SetViewer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1868-L1870
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/boto_resumable_upload.py
python
BotoResumableUpload._QueryServiceState
(self, conn, file_length)
return AWSAuthConnection.make_request( conn, 'PUT', path=self.upload_url_path, auth_path=self.upload_url_path, headers=put_headers, host=self.upload_url_host)
Queries service to find out state of given upload. Note that this method really just makes special case use of the fact that the upload service always returns the current start/end state whenever a PUT doesn't complete. Args: conn: HTTPConnection to use for the query. file_length: Total length of the file. Returns: HTTP response from sending request. Raises: ResumableUploadException if problem querying service.
Queries service to find out state of given upload.
[ "Queries", "service", "to", "find", "out", "state", "of", "given", "upload", "." ]
def _QueryServiceState(self, conn, file_length): """Queries service to find out state of given upload. Note that this method really just makes special case use of the fact that the upload service always returns the current start/end state whenever a PUT doesn't complete. Args: conn: HTTPConnection to use for the query. file_length: Total length of the file. Returns: HTTP response from sending request. Raises: ResumableUploadException if problem querying service. """ # Send an empty PUT so that service replies with this resumable # transfer's state. put_headers = {} put_headers['Content-Range'] = ( self._BuildContentRangeHeader('*', file_length)) put_headers['Content-Length'] = '0' return AWSAuthConnection.make_request( conn, 'PUT', path=self.upload_url_path, auth_path=self.upload_url_path, headers=put_headers, host=self.upload_url_host)
[ "def", "_QueryServiceState", "(", "self", ",", "conn", ",", "file_length", ")", ":", "# Send an empty PUT so that service replies with this resumable", "# transfer's state.", "put_headers", "=", "{", "}", "put_headers", "[", "'Content-Range'", "]", "=", "(", "self", ".", "_BuildContentRangeHeader", "(", "'*'", ",", "file_length", ")", ")", "put_headers", "[", "'Content-Length'", "]", "=", "'0'", "return", "AWSAuthConnection", ".", "make_request", "(", "conn", ",", "'PUT'", ",", "path", "=", "self", ".", "upload_url_path", ",", "auth_path", "=", "self", ".", "upload_url_path", ",", "headers", "=", "put_headers", ",", "host", "=", "self", ".", "upload_url_host", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/boto_resumable_upload.py#L124-L149
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/locators.py
python
DependencyFinder.find
(self, requirement, tests=False, prereleases=False)
return dists, problems
Find a distribution matching requirement and all distributions it depends on. Use the ``tests`` argument to determine whether distributions used only for testing should be included in the results. Allow ``requirement`` to be either a :class:`Distribution` instance or a string expressing a requirement. If ``prereleases`` is True, allow pre-release versions to be returned - otherwise, don't. Return a set of :class:`Distribution` instances and a set of problems. The distributions returned should be such that they have the :attr:`required` attribute set to ``True`` if they were from the ``requirement`` passed to ``find()``, and they have the :attr:`build_time_dependency` attribute set to ``True`` unless they are post-installation dependencies of the ``requirement``. The problems should be a tuple consisting of the string ``'unsatisfied'`` and the requirement which couldn't be satisfied by any distribution known to the locator.
Find a distribution matching requirement and all distributions it depends on. Use the ``tests`` argument to determine whether distributions used only for testing should be included in the results. Allow ``requirement`` to be either a :class:`Distribution` instance or a string expressing a requirement. If ``prereleases`` is True, allow pre-release versions to be returned - otherwise, don't.
[ "Find", "a", "distribution", "matching", "requirement", "and", "all", "distributions", "it", "depends", "on", ".", "Use", "the", "tests", "argument", "to", "determine", "whether", "distributions", "used", "only", "for", "testing", "should", "be", "included", "in", "the", "results", ".", "Allow", "requirement", "to", "be", "either", "a", ":", "class", ":", "Distribution", "instance", "or", "a", "string", "expressing", "a", "requirement", ".", "If", "prereleases", "is", "True", "allow", "pre", "-", "release", "versions", "to", "be", "returned", "-", "otherwise", "don", "t", "." ]
def find(self, requirement, tests=False, prereleases=False): """ Find a distribution matching requirement and all distributions it depends on. Use the ``tests`` argument to determine whether distributions used only for testing should be included in the results. Allow ``requirement`` to be either a :class:`Distribution` instance or a string expressing a requirement. If ``prereleases`` is True, allow pre-release versions to be returned - otherwise, don't. Return a set of :class:`Distribution` instances and a set of problems. The distributions returned should be such that they have the :attr:`required` attribute set to ``True`` if they were from the ``requirement`` passed to ``find()``, and they have the :attr:`build_time_dependency` attribute set to ``True`` unless they are post-installation dependencies of the ``requirement``. The problems should be a tuple consisting of the string ``'unsatisfied'`` and the requirement which couldn't be satisfied by any distribution known to the locator. """ self.provided = {} self.dists = {} self.dists_by_name = {} self.reqts = {} if isinstance(requirement, Distribution): dist = odist = requirement logger.debug('passed %s as requirement', odist) else: dist = odist = self.locator.locate(requirement, prereleases=prereleases) if dist is None: raise DistlibException('Unable to locate %r' % requirement) logger.debug('located %s', odist) dist.requested = True problems = set() todo = set([dist]) install_dists = set([odist]) while todo: dist = todo.pop() name = dist.key # case-insensitive if name not in self.dists_by_name: self.add_distribution(dist) else: #import pdb; pdb.set_trace() other = self.dists_by_name[name] if other != dist: self.try_to_replace(dist, other, problems) ireqts = dist.requires sreqts = dist.setup_requires ereqts = set() if not tests or dist not in install_dists: treqts = set() else: treqts = dist.test_requires all_reqts = ireqts | sreqts | treqts | ereqts for r in all_reqts: providers = self.find_providers(r) if not providers: logger.debug('No providers found for %r', r) provider = self.locator.locate(r, prereleases=prereleases) if provider is None: logger.debug('Cannot satisfy %r', r) problems.add(('unsatisfied', r)) else: n, v = provider.key, provider.version if (n, v) not in self.dists: todo.add(provider) providers.add(provider) if r in ireqts and dist in install_dists: install_dists.add(provider) logger.debug('Adding %s to install_dists', provider.name_and_version) for p in providers: name = p.key if name not in self.dists_by_name: self.reqts.setdefault(p, set()).add(r) else: other = self.dists_by_name[name] if other != p: # see if other can be replaced by p self.try_to_replace(p, other, problems) dists = set(self.dists.values()) for dist in dists: dist.build_time_dependency = dist not in install_dists if dist.build_time_dependency: logger.debug('%s is a build-time dependency only.', dist.name_and_version) logger.debug('find done for %s', odist) return dists, problems
[ "def", "find", "(", "self", ",", "requirement", ",", "tests", "=", "False", ",", "prereleases", "=", "False", ")", ":", "self", ".", "provided", "=", "{", "}", "self", ".", "dists", "=", "{", "}", "self", ".", "dists_by_name", "=", "{", "}", "self", ".", "reqts", "=", "{", "}", "if", "isinstance", "(", "requirement", ",", "Distribution", ")", ":", "dist", "=", "odist", "=", "requirement", "logger", ".", "debug", "(", "'passed %s as requirement'", ",", "odist", ")", "else", ":", "dist", "=", "odist", "=", "self", ".", "locator", ".", "locate", "(", "requirement", ",", "prereleases", "=", "prereleases", ")", "if", "dist", "is", "None", ":", "raise", "DistlibException", "(", "'Unable to locate %r'", "%", "requirement", ")", "logger", ".", "debug", "(", "'located %s'", ",", "odist", ")", "dist", ".", "requested", "=", "True", "problems", "=", "set", "(", ")", "todo", "=", "set", "(", "[", "dist", "]", ")", "install_dists", "=", "set", "(", "[", "odist", "]", ")", "while", "todo", ":", "dist", "=", "todo", ".", "pop", "(", ")", "name", "=", "dist", ".", "key", "# case-insensitive", "if", "name", "not", "in", "self", ".", "dists_by_name", ":", "self", ".", "add_distribution", "(", "dist", ")", "else", ":", "#import pdb; pdb.set_trace()", "other", "=", "self", ".", "dists_by_name", "[", "name", "]", "if", "other", "!=", "dist", ":", "self", ".", "try_to_replace", "(", "dist", ",", "other", ",", "problems", ")", "ireqts", "=", "dist", ".", "requires", "sreqts", "=", "dist", ".", "setup_requires", "ereqts", "=", "set", "(", ")", "if", "not", "tests", "or", "dist", "not", "in", "install_dists", ":", "treqts", "=", "set", "(", ")", "else", ":", "treqts", "=", "dist", ".", "test_requires", "all_reqts", "=", "ireqts", "|", "sreqts", "|", "treqts", "|", "ereqts", "for", "r", "in", "all_reqts", ":", "providers", "=", "self", ".", "find_providers", "(", "r", ")", "if", "not", "providers", ":", "logger", ".", "debug", "(", "'No providers found for %r'", ",", "r", ")", "provider", "=", "self", ".", "locator", ".", "locate", "(", "r", ",", "prereleases", "=", "prereleases", ")", "if", "provider", "is", "None", ":", "logger", ".", "debug", "(", "'Cannot satisfy %r'", ",", "r", ")", "problems", ".", "add", "(", "(", "'unsatisfied'", ",", "r", ")", ")", "else", ":", "n", ",", "v", "=", "provider", ".", "key", ",", "provider", ".", "version", "if", "(", "n", ",", "v", ")", "not", "in", "self", ".", "dists", ":", "todo", ".", "add", "(", "provider", ")", "providers", ".", "add", "(", "provider", ")", "if", "r", "in", "ireqts", "and", "dist", "in", "install_dists", ":", "install_dists", ".", "add", "(", "provider", ")", "logger", ".", "debug", "(", "'Adding %s to install_dists'", ",", "provider", ".", "name_and_version", ")", "for", "p", "in", "providers", ":", "name", "=", "p", ".", "key", "if", "name", "not", "in", "self", ".", "dists_by_name", ":", "self", ".", "reqts", ".", "setdefault", "(", "p", ",", "set", "(", ")", ")", ".", "add", "(", "r", ")", "else", ":", "other", "=", "self", ".", "dists_by_name", "[", "name", "]", "if", "other", "!=", "p", ":", "# see if other can be replaced by p", "self", ".", "try_to_replace", "(", "p", ",", "other", ",", "problems", ")", "dists", "=", "set", "(", "self", ".", "dists", ".", "values", "(", ")", ")", "for", "dist", "in", "dists", ":", "dist", ".", "build_time_dependency", "=", "dist", "not", "in", "install_dists", "if", "dist", ".", "build_time_dependency", ":", "logger", ".", "debug", "(", "'%s is a build-time dependency only.'", ",", "dist", ".", "name_and_version", ")", "logger", ".", "debug", "(", "'find done for %s'", ",", "odist", ")", "return", "dists", ",", "problems" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/locators.py#L1036-L1131
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/blas.py
python
find_best_blas_type
(arrays=(), dtype=None)
return prefix, dtype, prefer_fortran
Find best-matching BLAS/LAPACK type. Arrays are used to determine the optimal prefix of BLAS routines. Parameters ---------- arrays : sequence of ndarrays, optional Arrays can be given to determine optimal prefix of BLAS routines. If not given, double-precision routines will be used, otherwise the most generic type in arrays will be used. dtype : str or dtype, optional Data-type specifier. Not used if `arrays` is non-empty. Returns ------- prefix : str BLAS/LAPACK prefix character. dtype : dtype Inferred Numpy data type. prefer_fortran : bool Whether to prefer Fortran order routines over C order. Examples -------- >>> import scipy.linalg.blas as bla >>> a = np.random.rand(10,15) >>> b = np.asfortranarray(a) # Change the memory layout order >>> bla.find_best_blas_type((a,)) ('d', dtype('float64'), False) >>> bla.find_best_blas_type((a*1j,)) ('z', dtype('complex128'), False) >>> bla.find_best_blas_type((b,)) ('d', dtype('float64'), True)
Find best-matching BLAS/LAPACK type.
[ "Find", "best", "-", "matching", "BLAS", "/", "LAPACK", "type", "." ]
def find_best_blas_type(arrays=(), dtype=None): """Find best-matching BLAS/LAPACK type. Arrays are used to determine the optimal prefix of BLAS routines. Parameters ---------- arrays : sequence of ndarrays, optional Arrays can be given to determine optimal prefix of BLAS routines. If not given, double-precision routines will be used, otherwise the most generic type in arrays will be used. dtype : str or dtype, optional Data-type specifier. Not used if `arrays` is non-empty. Returns ------- prefix : str BLAS/LAPACK prefix character. dtype : dtype Inferred Numpy data type. prefer_fortran : bool Whether to prefer Fortran order routines over C order. Examples -------- >>> import scipy.linalg.blas as bla >>> a = np.random.rand(10,15) >>> b = np.asfortranarray(a) # Change the memory layout order >>> bla.find_best_blas_type((a,)) ('d', dtype('float64'), False) >>> bla.find_best_blas_type((a*1j,)) ('z', dtype('complex128'), False) >>> bla.find_best_blas_type((b,)) ('d', dtype('float64'), True) """ dtype = _np.dtype(dtype) prefer_fortran = False if arrays: # use the most generic type in arrays dtypes = [ar.dtype for ar in arrays] dtype = _np.find_common_type(dtypes, ()) try: index = dtypes.index(dtype) except ValueError: index = 0 if arrays[index].flags['FORTRAN']: # prefer Fortran for leading array with column major order prefer_fortran = True prefix = _type_conv.get(dtype.char, 'd') if dtype.char == 'G': # complex256 -> complex128 (i.e., C long double -> C double) dtype = _np.dtype('D') elif dtype.char not in 'fdFD': dtype = _np.dtype('d') return prefix, dtype, prefer_fortran
[ "def", "find_best_blas_type", "(", "arrays", "=", "(", ")", ",", "dtype", "=", "None", ")", ":", "dtype", "=", "_np", ".", "dtype", "(", "dtype", ")", "prefer_fortran", "=", "False", "if", "arrays", ":", "# use the most generic type in arrays", "dtypes", "=", "[", "ar", ".", "dtype", "for", "ar", "in", "arrays", "]", "dtype", "=", "_np", ".", "find_common_type", "(", "dtypes", ",", "(", ")", ")", "try", ":", "index", "=", "dtypes", ".", "index", "(", "dtype", ")", "except", "ValueError", ":", "index", "=", "0", "if", "arrays", "[", "index", "]", ".", "flags", "[", "'FORTRAN'", "]", ":", "# prefer Fortran for leading array with column major order", "prefer_fortran", "=", "True", "prefix", "=", "_type_conv", ".", "get", "(", "dtype", ".", "char", ",", "'d'", ")", "if", "dtype", ".", "char", "==", "'G'", ":", "# complex256 -> complex128 (i.e., C long double -> C double)", "dtype", "=", "_np", ".", "dtype", "(", "'D'", ")", "elif", "dtype", ".", "char", "not", "in", "'fdFD'", ":", "dtype", "=", "_np", ".", "dtype", "(", "'d'", ")", "return", "prefix", ",", "dtype", ",", "prefer_fortran" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/blas.py#L236-L294
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py
python
PublishManagerHelper._QueryVirtualHostIdAndDbId
(self, target_id)
return (virtual_host_id, db_id)
Queries Virtual Host ID and Db ID by target ID. Args: target_id: target ID. Raises: psycopg2.Error/Warning. Returns: tuple (virtual_host_id, db_id). If there is no DB published on specified target then it returns tuple (None, None).
Queries Virtual Host ID and Db ID by target ID.
[ "Queries", "Virtual", "Host", "ID", "and", "Db", "ID", "by", "target", "ID", "." ]
def _QueryVirtualHostIdAndDbId(self, target_id): """Queries Virtual Host ID and Db ID by target ID. Args: target_id: target ID. Raises: psycopg2.Error/Warning. Returns: tuple (virtual_host_id, db_id). If there is no DB published on specified target then it returns tuple (None, None). """ query_string = ("SELECT virtual_host_id, db_id FROM target_db_table" " WHERE target_id = %s") result = self.DbQuery(query_string, (target_id,)) virtual_host_id = None db_id = None if result: assert isinstance(result[0], tuple) virtual_host_id = int(result[0][0]) db_id = int(result[0][1]) return (virtual_host_id, db_id)
[ "def", "_QueryVirtualHostIdAndDbId", "(", "self", ",", "target_id", ")", ":", "query_string", "=", "(", "\"SELECT virtual_host_id, db_id FROM target_db_table\"", "\" WHERE target_id = %s\"", ")", "result", "=", "self", ".", "DbQuery", "(", "query_string", ",", "(", "target_id", ",", ")", ")", "virtual_host_id", "=", "None", "db_id", "=", "None", "if", "result", ":", "assert", "isinstance", "(", "result", "[", "0", "]", ",", "tuple", ")", "virtual_host_id", "=", "int", "(", "result", "[", "0", "]", "[", "0", "]", ")", "db_id", "=", "int", "(", "result", "[", "0", "]", "[", "1", "]", ")", "return", "(", "virtual_host_id", ",", "db_id", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py#L972-L993
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/mesh.py
python
Mesh.structured_get_hex
(self, i, j, k)
return _structured_step_iter( meshset_iterate(self.mesh, self.structured_set, types.MBHEX, 3), n)
Return the handle for the (i,j,k)'th hexahedron in the mesh
Return the handle for the (i,j,k)'th hexahedron in the mesh
[ "Return", "the", "handle", "for", "the", "(", "i", "j", "k", ")", "th", "hexahedron", "in", "the", "mesh" ]
def structured_get_hex(self, i, j, k): """Return the handle for the (i,j,k)'th hexahedron in the mesh""" self._structured_check() n = _structured_find_idx(self.dims, (i, j, k)) return _structured_step_iter( meshset_iterate(self.mesh, self.structured_set, types.MBHEX, 3), n)
[ "def", "structured_get_hex", "(", "self", ",", "i", ",", "j", ",", "k", ")", ":", "self", ".", "_structured_check", "(", ")", "n", "=", "_structured_find_idx", "(", "self", ".", "dims", ",", "(", "i", ",", "j", ",", "k", ")", ")", "return", "_structured_step_iter", "(", "meshset_iterate", "(", "self", ".", "mesh", ",", "self", ".", "structured_set", ",", "types", ".", "MBHEX", ",", "3", ")", ",", "n", ")" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mesh.py#L1305-L1310
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/png/png.py
python
isarray
(x)
Same as ``isinstance(x, array)`` except on Python 2.2, where it always returns ``False``. This helps PyPNG work on Python 2.2.
Same as ``isinstance(x, array)`` except on Python 2.2, where it always returns ``False``. This helps PyPNG work on Python 2.2.
[ "Same", "as", "isinstance", "(", "x", "array", ")", "except", "on", "Python", "2", ".", "2", "where", "it", "always", "returns", "False", ".", "This", "helps", "PyPNG", "work", "on", "Python", "2", ".", "2", "." ]
def isarray(x): """Same as ``isinstance(x, array)`` except on Python 2.2, where it always returns ``False``. This helps PyPNG work on Python 2.2. """ try: return isinstance(x, array) except: return False
[ "def", "isarray", "(", "x", ")", ":", "try", ":", "return", "isinstance", "(", "x", ",", "array", ")", "except", ":", "return", "False" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L211-L219
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/msvs_emulation.py
python
VerifyMissingSources
(sources, build_dir, generator_flags, gyp_to_ninja)
Emulate behavior of msvs_error_on_missing_sources present in the msvs generator: Check that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation when building via VS, and we want this check to match for people/bots that build using ninja, so they're not surprised when the VS build fails.
Emulate behavior of msvs_error_on_missing_sources present in the msvs generator: Check that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation when building via VS, and we want this check to match for people/bots that build using ninja, so they're not surprised when the VS build fails.
[ "Emulate", "behavior", "of", "msvs_error_on_missing_sources", "present", "in", "the", "msvs", "generator", ":", "Check", "that", "all", "regular", "source", "files", "i", ".", "e", ".", "not", "created", "at", "run", "time", "exist", "on", "disk", ".", "Missing", "files", "cause", "needless", "recompilation", "when", "building", "via", "VS", "and", "we", "want", "this", "check", "to", "match", "for", "people", "/", "bots", "that", "build", "using", "ninja", "so", "they", "re", "not", "surprised", "when", "the", "VS", "build", "fails", "." ]
def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja): """Emulate behavior of msvs_error_on_missing_sources present in the msvs generator: Check that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation when building via VS, and we want this check to match for people/bots that build using ninja, so they're not surprised when the VS build fails.""" if int(generator_flags.get('msvs_error_on_missing_sources', 0)): no_specials = filter(lambda x: '$' not in x, sources) relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials] missing = filter(lambda x: not os.path.exists(x), relative) if missing: # They'll look like out\Release\..\..\stuff\things.cc, so normalize the # path for a slightly less crazy looking output. cleaned_up = [os.path.normpath(x) for x in missing] raise Exception('Missing input files:\n%s' % '\n'.join(cleaned_up))
[ "def", "VerifyMissingSources", "(", "sources", ",", "build_dir", ",", "generator_flags", ",", "gyp_to_ninja", ")", ":", "if", "int", "(", "generator_flags", ".", "get", "(", "'msvs_error_on_missing_sources'", ",", "0", ")", ")", ":", "no_specials", "=", "filter", "(", "lambda", "x", ":", "'$'", "not", "in", "x", ",", "sources", ")", "relative", "=", "[", "os", ".", "path", ".", "join", "(", "build_dir", ",", "gyp_to_ninja", "(", "s", ")", ")", "for", "s", "in", "no_specials", "]", "missing", "=", "filter", "(", "lambda", "x", ":", "not", "os", ".", "path", ".", "exists", "(", "x", ")", ",", "relative", ")", "if", "missing", ":", "# They'll look like out\\Release\\..\\..\\stuff\\things.cc, so normalize the", "# path for a slightly less crazy looking output.", "cleaned_up", "=", "[", "os", ".", "path", ".", "normpath", "(", "x", ")", "for", "x", "in", "missing", "]", "raise", "Exception", "(", "'Missing input files:\\n%s'", "%", "'\\n'", ".", "join", "(", "cleaned_up", ")", ")" ]
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/msvs_emulation.py#L1054-L1068
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/compiler.py
python
IpuStrategy.batch_size
(self)
return self._ipu_strategy.batch_size
Get the batch_size used in dynamic batch_size graph from IpuStrategy instance.
Get the batch_size used in dynamic batch_size graph from IpuStrategy instance.
[ "Get", "the", "batch_size", "used", "in", "dynamic", "batch_size", "graph", "from", "IpuStrategy", "instance", "." ]
def batch_size(self): """ Get the batch_size used in dynamic batch_size graph from IpuStrategy instance. """ return self._ipu_strategy.batch_size
[ "def", "batch_size", "(", "self", ")", ":", "return", "self", ".", "_ipu_strategy", ".", "batch_size" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/compiler.py#L670-L674
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Conv.py
python
Conv3D.free_term
(self)
return Blob.Blob(self._internal.get_free_term())
Gets the free term. The blob size is filter_count.
Gets the free term. The blob size is filter_count.
[ "Gets", "the", "free", "term", ".", "The", "blob", "size", "is", "filter_count", "." ]
def free_term(self): """Gets the free term. The blob size is filter_count. """ return Blob.Blob(self._internal.get_free_term())
[ "def", "free_term", "(", "self", ")", ":", "return", "Blob", ".", "Blob", "(", "self", ".", "_internal", ".", "get_free_term", "(", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Conv.py#L388-L391
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py
python
peekable.peek
(self, default=_marker)
return self._cache[0]
Return the item that will be next returned from ``next()``. Return ``default`` if there are no items left. If ``default`` is not provided, raise ``StopIteration``.
Return the item that will be next returned from ``next()``.
[ "Return", "the", "item", "that", "will", "be", "next", "returned", "from", "next", "()", "." ]
def peek(self, default=_marker): """Return the item that will be next returned from ``next()``. Return ``default`` if there are no items left. If ``default`` is not provided, raise ``StopIteration``. """ if not self._cache: try: self._cache.append(next(self._it)) except StopIteration: if default is _marker: raise return default return self._cache[0]
[ "def", "peek", "(", "self", ",", "default", "=", "_marker", ")", ":", "if", "not", "self", ".", "_cache", ":", "try", ":", "self", ".", "_cache", ".", "append", "(", "next", "(", "self", ".", "_it", ")", ")", "except", "StopIteration", ":", "if", "default", "is", "_marker", ":", "raise", "return", "default", "return", "self", ".", "_cache", "[", "0", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py#L307-L321
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py
python
OptionName
(widget)
return widget.tk.call('tixOptionName', widget._w)
Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py
Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py
[ "Returns", "the", "qualified", "path", "name", "for", "the", "widget", ".", "Normally", "used", "to", "set", "default", "options", "for", "subwidgets", ".", "See", "tixwidgets", ".", "py" ]
def OptionName(widget): '''Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py''' return widget.tk.call('tixOptionName', widget._w)
[ "def", "OptionName", "(", "widget", ")", ":", "return", "widget", ".", "tk", ".", "call", "(", "'tixOptionName'", ",", "widget", ".", "_w", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py#L1741-L1744
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/graph/lattice.py
python
Lattice.site_to_coord
(self, site_id: int)
return self.positions[site_id]
Deprecated. please use :code:`positions[site_id]` instead.
Deprecated. please use :code:`positions[site_id]` instead.
[ "Deprecated", ".", "please", "use", ":", "code", ":", "positions", "[", "site_id", "]", "instead", "." ]
def site_to_coord(self, site_id: int) -> PositionT: """Deprecated. please use :code:`positions[site_id]` instead.""" return self.positions[site_id]
[ "def", "site_to_coord", "(", "self", ",", "site_id", ":", "int", ")", "->", "PositionT", ":", "return", "self", ".", "positions", "[", "site_id", "]" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/lattice.py#L717-L719
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.Z
(self, atom)
return self.atoms[atom].Z()
Nuclear charge of atom (0-indexed) >>> print(H2OH2O.Z(4)) 1
Nuclear charge of atom (0-indexed)
[ "Nuclear", "charge", "of", "atom", "(", "0", "-", "indexed", ")" ]
def Z(self, atom): """Nuclear charge of atom (0-indexed) >>> print(H2OH2O.Z(4)) 1 """ return self.atoms[atom].Z()
[ "def", "Z", "(", "self", ",", "atom", ")", ":", "return", "self", ".", "atoms", "[", "atom", "]", ".", "Z", "(", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L378-L385
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/dbgen/ndsfpy.py
python
getpoint
(line)
return data
Gets data entries from html lines
Gets data entries from html lines
[ "Gets", "data", "entries", "from", "html", "lines" ]
def getpoint(line): """Gets data entries from html lines """ spline = line.split('<tr><td class="xl28b">&nbsp;&nbsp;') if len(spline) > 1: data = spline[1].split('</td></tr>')[0] else: data = None return data
[ "def", "getpoint", "(", "line", ")", ":", "spline", "=", "line", ".", "split", "(", "'<tr><td class=\"xl28b\">&nbsp;&nbsp;'", ")", "if", "len", "(", "spline", ")", ">", "1", ":", "data", "=", "spline", "[", "1", "]", ".", "split", "(", "'</td></tr>'", ")", "[", "0", "]", "else", ":", "data", "=", "None", "return", "data" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/ndsfpy.py#L107-L115
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Geometry.GetArea
(self, *args)
return _ogr.Geometry_GetArea(self, *args)
r"""GetArea(Geometry self) -> double
r"""GetArea(Geometry self) -> double
[ "r", "GetArea", "(", "Geometry", "self", ")", "-", ">", "double" ]
def GetArea(self, *args): r"""GetArea(Geometry self) -> double""" return _ogr.Geometry_GetArea(self, *args)
[ "def", "GetArea", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "Geometry_GetArea", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L5962-L5964
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/self_outdated_check.py
python
was_installed_by_pip
(pkg)
return "pip" == get_installer(dist)
Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora.
Checks whether pkg was installed by pip
[ "Checks", "whether", "pkg", "was", "installed", "by", "pip" ]
def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ dist = get_distribution(pkg) if not dist: return False return "pip" == get_installer(dist)
[ "def", "was_installed_by_pip", "(", "pkg", ")", ":", "# type: (str) -> bool", "dist", "=", "get_distribution", "(", "pkg", ")", "if", "not", "dist", ":", "return", "False", "return", "\"pip\"", "==", "get_installer", "(", "dist", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/self_outdated_check.py#L99-L109
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Utilities/Scripts/SlicerWizard/ExtensionProject.py
python
ExtensionProject._collect_cmakefiles
(path)
return cmakeFiles
Return list of CMakeLists.txt found in `path` at depth=1
Return list of CMakeLists.txt found in `path` at depth=1
[ "Return", "list", "of", "CMakeLists", ".", "txt", "found", "in", "path", "at", "depth", "=", "1" ]
def _collect_cmakefiles(path): """Return list of CMakeLists.txt found in `path` at depth=1""" cmakeFiles = [] dirnames = [] for _, dirnames, _ in os.walk(path): break for dirname in dirnames: cmakeFile = os.path.join(path, dirname, "CMakeLists.txt") if os.path.exists(cmakeFile): cmakeFiles.append(cmakeFile) return cmakeFiles
[ "def", "_collect_cmakefiles", "(", "path", ")", ":", "cmakeFiles", "=", "[", "]", "dirnames", "=", "[", "]", "for", "_", ",", "dirnames", ",", "_", "in", "os", ".", "walk", "(", "path", ")", ":", "break", "for", "dirname", "in", "dirnames", ":", "cmakeFile", "=", "os", ".", "path", ".", "join", "(", "path", ",", "dirname", ",", "\"CMakeLists.txt\"", ")", "if", "os", ".", "path", ".", "exists", "(", "cmakeFile", ")", ":", "cmakeFiles", ".", "append", "(", "cmakeFile", ")", "return", "cmakeFiles" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Utilities/Scripts/SlicerWizard/ExtensionProject.py#L69-L79
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/linter/git.py
python
get_base_dir
()
Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory.
Get the base directory for mongo repo.
[ "Get", "the", "base", "directory", "for", "mongo", "repo", "." ]
def get_base_dir(): # type: () -> str """ Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory. """ try: return _git.Repository.get_base_directory() except _git.GitException: # We are not in a valid git directory. Use the script path instead. return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
[ "def", "get_base_dir", "(", ")", ":", "# type: () -> str", "try", ":", "return", "_git", ".", "Repository", ".", "get_base_directory", "(", ")", "except", "_git", ".", "GitException", ":", "# We are not in a valid git directory. Use the script path instead.", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/linter/git.py#L19-L31
cinder/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
docs/generateDocs.py
python
update_links_abs
(html, src_path)
Replace all of the relative a links with absolut links :param html: :param src_path: :param dest_path: :return:
Replace all of the relative a links with absolut links :param html: :param src_path: :param dest_path: :return:
[ "Replace", "all", "of", "the", "relative", "a", "links", "with", "absolut", "links", ":", "param", "html", ":", ":", "param", "src_path", ":", ":", "param", "dest_path", ":", ":", "return", ":" ]
def update_links_abs(html, src_path): """ Replace all of the relative a links with absolut links :param html: :param src_path: :param dest_path: :return: """ # css links for link in html.find_all("link"): if link.has_attr("href"): link["href"] = update_link_abs(link["href"], src_path) # a links for a in html.find_all("a"): if a.has_attr("href"): link_href = a["href"] # if the link is an hpp file, lets link to the github link since we likely don't have it in our docs if link_href.find(config.GLM_MODULE_CONFIG["source_file_ext"]) > -1: a["href"] = config.GLM_MODULE_CONFIG["url_prefix"] + a.text else: a["href"] = update_link_abs(a["href"], src_path) # script links for script in html.find_all("script"): if script.has_attr("src"): script["src"] = update_link_abs(script["src"], src_path) # images for img in html.find_all("img"): if img.has_attr("src"): img["src"] = update_link_abs(img["src"], src_path) # iframes for iframe in html.find_all("iframe"): if iframe.has_attr("src"): link_src = iframe["src"] if link_src.startswith('javascript') or link_src.startswith('http'): return new_link = update_link_abs(link_src, src_path) iframe["src"] = new_link
[ "def", "update_links_abs", "(", "html", ",", "src_path", ")", ":", "# css links", "for", "link", "in", "html", ".", "find_all", "(", "\"link\"", ")", ":", "if", "link", ".", "has_attr", "(", "\"href\"", ")", ":", "link", "[", "\"href\"", "]", "=", "update_link_abs", "(", "link", "[", "\"href\"", "]", ",", "src_path", ")", "# a links", "for", "a", "in", "html", ".", "find_all", "(", "\"a\"", ")", ":", "if", "a", ".", "has_attr", "(", "\"href\"", ")", ":", "link_href", "=", "a", "[", "\"href\"", "]", "# if the link is an hpp file, lets link to the github link since we likely don't have it in our docs", "if", "link_href", ".", "find", "(", "config", ".", "GLM_MODULE_CONFIG", "[", "\"source_file_ext\"", "]", ")", ">", "-", "1", ":", "a", "[", "\"href\"", "]", "=", "config", ".", "GLM_MODULE_CONFIG", "[", "\"url_prefix\"", "]", "+", "a", ".", "text", "else", ":", "a", "[", "\"href\"", "]", "=", "update_link_abs", "(", "a", "[", "\"href\"", "]", ",", "src_path", ")", "# script links", "for", "script", "in", "html", ".", "find_all", "(", "\"script\"", ")", ":", "if", "script", ".", "has_attr", "(", "\"src\"", ")", ":", "script", "[", "\"src\"", "]", "=", "update_link_abs", "(", "script", "[", "\"src\"", "]", ",", "src_path", ")", "# images", "for", "img", "in", "html", ".", "find_all", "(", "\"img\"", ")", ":", "if", "img", ".", "has_attr", "(", "\"src\"", ")", ":", "img", "[", "\"src\"", "]", "=", "update_link_abs", "(", "img", "[", "\"src\"", "]", ",", "src_path", ")", "# iframes", "for", "iframe", "in", "html", ".", "find_all", "(", "\"iframe\"", ")", ":", "if", "iframe", ".", "has_attr", "(", "\"src\"", ")", ":", "link_src", "=", "iframe", "[", "\"src\"", "]", "if", "link_src", ".", "startswith", "(", "'javascript'", ")", "or", "link_src", ".", "startswith", "(", "'http'", ")", ":", "return", "new_link", "=", "update_link_abs", "(", "link_src", ",", "src_path", ")", "iframe", "[", "\"src\"", "]", "=", "new_link" ]
https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/generateDocs.py#L2850-L2893
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/misc.py
python
SetViewerUserThread
(env,viewername,userfn)
Adds a viewer to the environment if one doesn't exist yet and starts it on this thread. Then creates a new thread to call the user-defined function to continue computation. This function will return when the viewer and uesrfn exits. If userfn exits first, then will quit the viewer
Adds a viewer to the environment if one doesn't exist yet and starts it on this thread. Then creates a new thread to call the user-defined function to continue computation. This function will return when the viewer and uesrfn exits. If userfn exits first, then will quit the viewer
[ "Adds", "a", "viewer", "to", "the", "environment", "if", "one", "doesn", "t", "exist", "yet", "and", "starts", "it", "on", "this", "thread", ".", "Then", "creates", "a", "new", "thread", "to", "call", "the", "user", "-", "defined", "function", "to", "continue", "computation", ".", "This", "function", "will", "return", "when", "the", "viewer", "and", "uesrfn", "exits", ".", "If", "userfn", "exits", "first", "then", "will", "quit", "the", "viewer" ]
def SetViewerUserThread(env,viewername,userfn): """Adds a viewer to the environment if one doesn't exist yet and starts it on this thread. Then creates a new thread to call the user-defined function to continue computation. This function will return when the viewer and uesrfn exits. If userfn exits first, then will quit the viewer """ if env.GetViewer() is not None or viewername is None: userfn() viewer = None if sysplatformname.startswith('darwin'): viewer = openravepy_int.RaveCreateViewer(env,viewername) else: # create in a separate thread for windows and linux since the signals do not get messed up env.SetViewer(viewername) if viewer is None: userfn() # add the viewer before starting the user function env.Add(viewer) threading = __import__('threading') Thread = threading.Thread def localuserfn(userfn,viewer): try: userfn() finally: # user function quit, so have to destroy the viewer viewer.quitmainloop() userthread = Thread(target=localuserfn,args=(userfn,viewer)) userthread.start() sig_thread_id = 0 for tid, tobj in threading._active.items(): if tobj is userthread: sig_thread_id = tid break try: viewer.main(True,sig_thread_id) finally: userthread.join()
[ "def", "SetViewerUserThread", "(", "env", ",", "viewername", ",", "userfn", ")", ":", "if", "env", ".", "GetViewer", "(", ")", "is", "not", "None", "or", "viewername", "is", "None", ":", "userfn", "(", ")", "viewer", "=", "None", "if", "sysplatformname", ".", "startswith", "(", "'darwin'", ")", ":", "viewer", "=", "openravepy_int", ".", "RaveCreateViewer", "(", "env", ",", "viewername", ")", "else", ":", "# create in a separate thread for windows and linux since the signals do not get messed up", "env", ".", "SetViewer", "(", "viewername", ")", "if", "viewer", "is", "None", ":", "userfn", "(", ")", "# add the viewer before starting the user function", "env", ".", "Add", "(", "viewer", ")", "threading", "=", "__import__", "(", "'threading'", ")", "Thread", "=", "threading", ".", "Thread", "def", "localuserfn", "(", "userfn", ",", "viewer", ")", ":", "try", ":", "userfn", "(", ")", "finally", ":", "# user function quit, so have to destroy the viewer", "viewer", ".", "quitmainloop", "(", ")", "userthread", "=", "Thread", "(", "target", "=", "localuserfn", ",", "args", "=", "(", "userfn", ",", "viewer", ")", ")", "userthread", ".", "start", "(", ")", "sig_thread_id", "=", "0", "for", "tid", ",", "tobj", "in", "threading", ".", "_active", ".", "items", "(", ")", ":", "if", "tobj", "is", "userthread", ":", "sig_thread_id", "=", "tid", "break", "try", ":", "viewer", ".", "main", "(", "True", ",", "sig_thread_id", ")", "finally", ":", "userthread", ".", "join", "(", ")" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/misc.py#L89-L123
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
webkit/support/setup_third_party.py
python
GetHeaderFilesInDir
(dir_path)
return all_files
Return a list of all header files in dir_path.
Return a list of all header files in dir_path.
[ "Return", "a", "list", "of", "all", "header", "files", "in", "dir_path", "." ]
def GetHeaderFilesInDir(dir_path): """Return a list of all header files in dir_path.""" all_files = [] for root, dirs, files in os.walk(dir_path): # Backslashes get shell escaped by gyp, so force forward slash for # path separators. all_files.extend([os.path.join(root, f).replace(os.sep, '/') for f in files if f.endswith('.h')]) return all_files
[ "def", "GetHeaderFilesInDir", "(", "dir_path", ")", ":", "all_files", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "dir_path", ")", ":", "# Backslashes get shell escaped by gyp, so force forward slash for", "# path separators.", "all_files", ".", "extend", "(", "[", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ".", "replace", "(", "os", ".", "sep", ",", "'/'", ")", "for", "f", "in", "files", "if", "f", ".", "endswith", "(", "'.h'", ")", "]", ")", "return", "all_files" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/webkit/support/setup_third_party.py#L13-L21
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/cpplint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. 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.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/invalid_increment'", ",", "5", ",", "'Changing pointer instead of value (or unused value of operator*).'", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L2271-L2290
Illumina/hap.py
84011695b2ff2406c16a335106db6831fb67fdfe
install.py
python
test_haplotypes
(source_dir, python_shebang, args)
Run the unit + integration tests
Run the unit + integration tests
[ "Run", "the", "unit", "+", "integration", "tests" ]
def test_haplotypes(source_dir, python_shebang, args): """ Run the unit + integration tests """ to_run = "cd %s && %s" % (args.targetdir, os.path.join(source_dir, "src", "sh", "run_tests.sh")) print >>sys.stderr, to_run os.environ["PYTHON"] = python_shebang[2:] subprocess.check_call(to_run, shell=True)
[ "def", "test_haplotypes", "(", "source_dir", ",", "python_shebang", ",", "args", ")", ":", "to_run", "=", "\"cd %s && %s\"", "%", "(", "args", ".", "targetdir", ",", "os", ".", "path", ".", "join", "(", "source_dir", ",", "\"src\"", ",", "\"sh\"", ",", "\"run_tests.sh\"", ")", ")", "print", ">>", "sys", ".", "stderr", ",", "to_run", "os", ".", "environ", "[", "\"PYTHON\"", "]", "=", "python_shebang", "[", "2", ":", "]", "subprocess", ".", "check_call", "(", "to_run", ",", "shell", "=", "True", ")" ]
https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/install.py#L164-L170
wang-bin/QtAV
3b937991afce248648836ae811324d4051b31def
python/configure.py
python
_HostPythonConfiguration.__init__
(self)
Initialise the configuration.
Initialise the configuration.
[ "Initialise", "the", "configuration", "." ]
def __init__(self): """ Initialise the configuration. """ self.platform = sys.platform self.version = sys.hexversion >> 8 self.inc_dir = sysconfig.get_python_inc() self.venv_inc_dir = sysconfig.get_python_inc(prefix=sys.prefix) self.module_dir = sysconfig.get_python_lib(plat_specific=1) self.debug = hasattr(sys, 'gettotalrefcount') if sys.platform == 'win32': try: # Python v3.3 and later. base_prefix = sys.base_prefix except AttributeError: try: # virtualenv for Python v2. base_prefix = sys.real_prefix except AttributeError: # We can't detect the base prefix in Python v3 prior to # v3.3. base_prefix = sys.prefix self.data_dir = sys.prefix self.lib_dir = base_prefix + '\\libs' else: self.data_dir = sys.prefix + '/share' self.lib_dir = sys.prefix + '/lib'
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "platform", "=", "sys", ".", "platform", "self", ".", "version", "=", "sys", ".", "hexversion", ">>", "8", "self", ".", "inc_dir", "=", "sysconfig", ".", "get_python_inc", "(", ")", "self", ".", "venv_inc_dir", "=", "sysconfig", ".", "get_python_inc", "(", "prefix", "=", "sys", ".", "prefix", ")", "self", ".", "module_dir", "=", "sysconfig", ".", "get_python_lib", "(", "plat_specific", "=", "1", ")", "self", ".", "debug", "=", "hasattr", "(", "sys", ",", "'gettotalrefcount'", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "try", ":", "# Python v3.3 and later.", "base_prefix", "=", "sys", ".", "base_prefix", "except", "AttributeError", ":", "try", ":", "# virtualenv for Python v2.", "base_prefix", "=", "sys", ".", "real_prefix", "except", "AttributeError", ":", "# We can't detect the base prefix in Python v3 prior to", "# v3.3.", "base_prefix", "=", "sys", ".", "prefix", "self", ".", "data_dir", "=", "sys", ".", "prefix", "self", ".", "lib_dir", "=", "base_prefix", "+", "'\\\\libs'", "else", ":", "self", ".", "data_dir", "=", "sys", ".", "prefix", "+", "'/share'", "self", ".", "lib_dir", "=", "sys", ".", "prefix", "+", "'/lib'" ]
https://github.com/wang-bin/QtAV/blob/3b937991afce248648836ae811324d4051b31def/python/configure.py#L664-L694
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
ungroup
(expr)
return TokenConverter(expr).setParseAction(lambda t:t[0])
Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.
Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty.
[ "Helper", "to", "undo", "pyparsing", "s", "default", "grouping", "of", "And", "expressions", "even", "if", "all", "but", "one", "are", "non", "-", "empty", "." ]
def ungroup(expr): """ Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. """ return TokenConverter(expr).setParseAction(lambda t:t[0])
[ "def", "ungroup", "(", "expr", ")", ":", "return", "TokenConverter", "(", "expr", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L4718-L4723
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/ext/pybind11/tools/clang/cindex.py
python
Cursor.get_arguments
(self)
Return an iterator for accessing the arguments of this cursor.
Return an iterator for accessing the arguments of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "arguments", "of", "this", "cursor", "." ]
def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in range(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i)
[ "def", "get_arguments", "(", "self", ")", ":", "num_args", "=", "conf", ".", "lib", ".", "clang_Cursor_getNumArguments", "(", "self", ")", "for", "i", "in", "range", "(", "0", ",", "num_args", ")", ":", "yield", "conf", ".", "lib", ".", "clang_Cursor_getArgument", "(", "self", ",", "i", ")" ]
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/pybind11/tools/clang/cindex.py#L1492-L1496
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/math_ops.py
python
matmul
(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None)
Multiplies matrix `a` by matrix `b`, producing `a` * `b`. The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match. Both matrices must be of the same type. The supported types are: `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`. Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to `True`. These are `False` by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes `bfloat16` or `float32`. For example: ```python # 2-D tensor `a` # [[1, 2, 3], # [4, 5, 6]] a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) # 2-D tensor `b` # [[ 7, 8], # [ 9, 10], # [11, 12]] b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) # `a` * `b` # [[ 58, 64], # [139, 154]] c = tf.matmul(a, b) # 3-D tensor `a` # [[[ 1, 2, 3], # [ 4, 5, 6]], # [[ 7, 8, 9], # [10, 11, 12]]] a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) # 3-D tensor `b` # [[[13, 14], # [15, 16], # [17, 18]], # [[19, 20], # [21, 22], # [23, 24]]] b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2]) # `a` * `b` # [[[ 94, 100], # [229, 244]], # [[508, 532], # [697, 730]]] c = tf.matmul(a, b) # Since python >= 3.5 the @ operator is supported (see PEP 465). # In TensorFlow, it simply calls the `tf.matmul()` function, so the # following lines are equivalent: d = a @ b @ [[10.], [11.]] d = tf.matmul(tf.matmul(a, b), [[10.], [11.]]) ``` Args: a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128` and rank > 1. b: `Tensor` with same type and rank as `a`. transpose_a: If `True`, `a` is transposed before multiplication. transpose_b: If `True`, `b` is transposed before multiplication. adjoint_a: If `True`, `a` is conjugated and transposed before multiplication. adjoint_b: If `True`, `b` is conjugated and transposed before multiplication. a_is_sparse: If `True`, `a` is treated as a sparse matrix. b_is_sparse: If `True`, `b` is treated as a sparse matrix. name: Name for the operation (optional). Returns: A `Tensor` of the same type as `a` and `b` where each inner-most matrix is the product of the corresponding matrices in `a` and `b`, e.g. if all transpose or adjoint attributes are `False`: `output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]), for all indices i, j. Note: This is matrix product, not element-wise product. Raises: ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_b are both set to True.
Multiplies matrix `a` by matrix `b`, producing `a` * `b`.
[ "Multiplies", "matrix", "a", "by", "matrix", "b", "producing", "a", "*", "b", "." ]
def matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None): """Multiplies matrix `a` by matrix `b`, producing `a` * `b`. The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match. Both matrices must be of the same type. The supported types are: `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`. Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to `True`. These are `False` by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes `bfloat16` or `float32`. For example: ```python # 2-D tensor `a` # [[1, 2, 3], # [4, 5, 6]] a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) # 2-D tensor `b` # [[ 7, 8], # [ 9, 10], # [11, 12]] b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) # `a` * `b` # [[ 58, 64], # [139, 154]] c = tf.matmul(a, b) # 3-D tensor `a` # [[[ 1, 2, 3], # [ 4, 5, 6]], # [[ 7, 8, 9], # [10, 11, 12]]] a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) # 3-D tensor `b` # [[[13, 14], # [15, 16], # [17, 18]], # [[19, 20], # [21, 22], # [23, 24]]] b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2]) # `a` * `b` # [[[ 94, 100], # [229, 244]], # [[508, 532], # [697, 730]]] c = tf.matmul(a, b) # Since python >= 3.5 the @ operator is supported (see PEP 465). # In TensorFlow, it simply calls the `tf.matmul()` function, so the # following lines are equivalent: d = a @ b @ [[10.], [11.]] d = tf.matmul(tf.matmul(a, b), [[10.], [11.]]) ``` Args: a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128` and rank > 1. b: `Tensor` with same type and rank as `a`. transpose_a: If `True`, `a` is transposed before multiplication. transpose_b: If `True`, `b` is transposed before multiplication. adjoint_a: If `True`, `a` is conjugated and transposed before multiplication. adjoint_b: If `True`, `b` is conjugated and transposed before multiplication. a_is_sparse: If `True`, `a` is treated as a sparse matrix. b_is_sparse: If `True`, `b` is treated as a sparse matrix. name: Name for the operation (optional). Returns: A `Tensor` of the same type as `a` and `b` where each inner-most matrix is the product of the corresponding matrices in `a` and `b`, e.g. if all transpose or adjoint attributes are `False`: `output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]), for all indices i, j. Note: This is matrix product, not element-wise product. Raises: ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_b are both set to True. """ with ops.name_scope(name, "MatMul", [a, b]) as name: if transpose_a and adjoint_a: raise ValueError("Only one of transpose_a and adjoint_a can be True.") if transpose_b and adjoint_b: raise ValueError("Only one of transpose_b and adjoint_b can be True.") a = ops.convert_to_tensor(a, name="a") b = ops.convert_to_tensor(b, name="b") # TODO(apassos) remove _shape_tuple here when it is not needed. a_shape = a._shape_tuple() # pylint: disable=protected-access b_shape = b._shape_tuple() # pylint: disable=protected-access if (not a_is_sparse and not b_is_sparse) and ( (a_shape is None or len(a_shape) > 2) and (b_shape is None or len(b_shape) > 2)): # BatchMatmul does not support transpose, so we conjugate the matrix and # use adjoint instead. Conj() is a noop for real matrices. if transpose_a: a = conj(a) adjoint_a = True if transpose_b: b = conj(b) adjoint_b = True return gen_math_ops._batch_mat_mul( a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name) # Neither matmul nor sparse_matmul support adjoint, so we conjugate # the matrix and use transpose instead. Conj() is a noop for real # matrices. if adjoint_a: a = conj(a) transpose_a = True if adjoint_b: b = conj(b) transpose_b = True use_sparse_matmul = False if a_is_sparse or b_is_sparse: sparse_matmul_types = [dtypes.bfloat16, dtypes.float32] use_sparse_matmul = (a.dtype in sparse_matmul_types and b.dtype in sparse_matmul_types) if a.dtype == dtypes.bfloat16 or b.dtype == dtypes.bfloat16: # matmul currently doesn't handle bfloat16 inputs. use_sparse_matmul = True if use_sparse_matmul: return sparse_matmul( a, b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name) else: return gen_math_ops._mat_mul( a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
[ "def", "matmul", "(", "a", ",", "b", ",", "transpose_a", "=", "False", ",", "transpose_b", "=", "False", ",", "adjoint_a", "=", "False", ",", "adjoint_b", "=", "False", ",", "a_is_sparse", "=", "False", ",", "b_is_sparse", "=", "False", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"MatMul\"", ",", "[", "a", ",", "b", "]", ")", "as", "name", ":", "if", "transpose_a", "and", "adjoint_a", ":", "raise", "ValueError", "(", "\"Only one of transpose_a and adjoint_a can be True.\"", ")", "if", "transpose_b", "and", "adjoint_b", ":", "raise", "ValueError", "(", "\"Only one of transpose_b and adjoint_b can be True.\"", ")", "a", "=", "ops", ".", "convert_to_tensor", "(", "a", ",", "name", "=", "\"a\"", ")", "b", "=", "ops", ".", "convert_to_tensor", "(", "b", ",", "name", "=", "\"b\"", ")", "# TODO(apassos) remove _shape_tuple here when it is not needed.", "a_shape", "=", "a", ".", "_shape_tuple", "(", ")", "# pylint: disable=protected-access", "b_shape", "=", "b", ".", "_shape_tuple", "(", ")", "# pylint: disable=protected-access", "if", "(", "not", "a_is_sparse", "and", "not", "b_is_sparse", ")", "and", "(", "(", "a_shape", "is", "None", "or", "len", "(", "a_shape", ")", ">", "2", ")", "and", "(", "b_shape", "is", "None", "or", "len", "(", "b_shape", ")", ">", "2", ")", ")", ":", "# BatchMatmul does not support transpose, so we conjugate the matrix and", "# use adjoint instead. Conj() is a noop for real matrices.", "if", "transpose_a", ":", "a", "=", "conj", "(", "a", ")", "adjoint_a", "=", "True", "if", "transpose_b", ":", "b", "=", "conj", "(", "b", ")", "adjoint_b", "=", "True", "return", "gen_math_ops", ".", "_batch_mat_mul", "(", "a", ",", "b", ",", "adj_x", "=", "adjoint_a", ",", "adj_y", "=", "adjoint_b", ",", "name", "=", "name", ")", "# Neither matmul nor sparse_matmul support adjoint, so we conjugate", "# the matrix and use transpose instead. Conj() is a noop for real", "# matrices.", "if", "adjoint_a", ":", "a", "=", "conj", "(", "a", ")", "transpose_a", "=", "True", "if", "adjoint_b", ":", "b", "=", "conj", "(", "b", ")", "transpose_b", "=", "True", "use_sparse_matmul", "=", "False", "if", "a_is_sparse", "or", "b_is_sparse", ":", "sparse_matmul_types", "=", "[", "dtypes", ".", "bfloat16", ",", "dtypes", ".", "float32", "]", "use_sparse_matmul", "=", "(", "a", ".", "dtype", "in", "sparse_matmul_types", "and", "b", ".", "dtype", "in", "sparse_matmul_types", ")", "if", "a", ".", "dtype", "==", "dtypes", ".", "bfloat16", "or", "b", ".", "dtype", "==", "dtypes", ".", "bfloat16", ":", "# matmul currently doesn't handle bfloat16 inputs.", "use_sparse_matmul", "=", "True", "if", "use_sparse_matmul", ":", "return", "sparse_matmul", "(", "a", ",", "b", ",", "transpose_a", "=", "transpose_a", ",", "transpose_b", "=", "transpose_b", ",", "a_is_sparse", "=", "a_is_sparse", ",", "b_is_sparse", "=", "b_is_sparse", ",", "name", "=", "name", ")", "else", ":", "return", "gen_math_ops", ".", "_mat_mul", "(", "a", ",", "b", ",", "transpose_a", "=", "transpose_a", ",", "transpose_b", "=", "transpose_b", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_ops.py#L1735-L1898
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/mixins/treemixin.py
python
VirtualTree.OnGetItemType
(self, index)
return 0
This function may be overloaded in the derived class, but that only makes sense when this class is mixed in with a tree control that supports checkable items, i.e. CustomTreeCtrl. This method should return whether the item is to be normal (0, the default), a checkbox (1) or a radiobutton (2). Note that OnGetItemChecked needs to be implemented as well; it should return whether the item is actually checked.
This function may be overloaded in the derived class, but that only makes sense when this class is mixed in with a tree control that supports checkable items, i.e. CustomTreeCtrl. This method should return whether the item is to be normal (0, the default), a checkbox (1) or a radiobutton (2). Note that OnGetItemChecked needs to be implemented as well; it should return whether the item is actually checked.
[ "This", "function", "may", "be", "overloaded", "in", "the", "derived", "class", "but", "that", "only", "makes", "sense", "when", "this", "class", "is", "mixed", "in", "with", "a", "tree", "control", "that", "supports", "checkable", "items", "i", ".", "e", ".", "CustomTreeCtrl", ".", "This", "method", "should", "return", "whether", "the", "item", "is", "to", "be", "normal", "(", "0", "the", "default", ")", "a", "checkbox", "(", "1", ")", "or", "a", "radiobutton", "(", "2", ")", ".", "Note", "that", "OnGetItemChecked", "needs", "to", "be", "implemented", "as", "well", ";", "it", "should", "return", "whether", "the", "item", "is", "actually", "checked", "." ]
def OnGetItemType(self, index): """ This function may be overloaded in the derived class, but that only makes sense when this class is mixed in with a tree control that supports checkable items, i.e. CustomTreeCtrl. This method should return whether the item is to be normal (0, the default), a checkbox (1) or a radiobutton (2). Note that OnGetItemChecked needs to be implemented as well; it should return whether the item is actually checked. """ return 0
[ "def", "OnGetItemType", "(", "self", ",", "index", ")", ":", "return", "0" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/mixins/treemixin.py#L330-L338
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/utils.py
python
GetTestContainerKey
(test)
return ndb.Key('TestContainer', test_path)
Gets the TestContainer key for the given TestMetadata. Args: test: Either a TestMetadata entity or its ndb.Key. Returns: ndb.Key('TestContainer', test path)
Gets the TestContainer key for the given TestMetadata.
[ "Gets", "the", "TestContainer", "key", "for", "the", "given", "TestMetadata", "." ]
def GetTestContainerKey(test): """Gets the TestContainer key for the given TestMetadata. Args: test: Either a TestMetadata entity or its ndb.Key. Returns: ndb.Key('TestContainer', test path) """ test_path = None if type(test) is ndb.Key: test_path = TestPath(test) else: test_path = test.test_path return ndb.Key('TestContainer', test_path)
[ "def", "GetTestContainerKey", "(", "test", ")", ":", "test_path", "=", "None", "if", "type", "(", "test", ")", "is", "ndb", ".", "Key", ":", "test_path", "=", "TestPath", "(", "test", ")", "else", ":", "test_path", "=", "test", ".", "test_path", "return", "ndb", ".", "Key", "(", "'TestContainer'", ",", "test_path", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/utils.py#L219-L233
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/dfxml.py
python
fileobject_dom.tag
(self,name)
Returns the wholeText for any given NAME. Raises KeyError if the NAME does not exist.
Returns the wholeText for any given NAME. Raises KeyError if the NAME does not exist.
[ "Returns", "the", "wholeText", "for", "any", "given", "NAME", ".", "Raises", "KeyError", "if", "the", "NAME", "does", "not", "exist", "." ]
def tag(self,name): """Returns the wholeText for any given NAME. Raises KeyError if the NAME does not exist.""" try: return self.doc.getElementsByTagName(name)[0].firstChild.wholeText except IndexError: # Check for a hash tag with legacy API if name in ['md5','sha1','sha256']: for e in self.doc.getElementsByTagName('hashdigest'): if e.getAttribute('type').lower()==name: return e.firstChild.wholeText raise KeyError(name+" not in XML")
[ "def", "tag", "(", "self", ",", "name", ")", ":", "try", ":", "return", "self", ".", "doc", ".", "getElementsByTagName", "(", "name", ")", "[", "0", "]", ".", "firstChild", ".", "wholeText", "except", "IndexError", ":", "# Check for a hash tag with legacy API", "if", "name", "in", "[", "'md5'", ",", "'sha1'", ",", "'sha256'", "]", ":", "for", "e", "in", "self", ".", "doc", ".", "getElementsByTagName", "(", "'hashdigest'", ")", ":", "if", "e", ".", "getAttribute", "(", "'type'", ")", ".", "lower", "(", ")", "==", "name", ":", "return", "e", ".", "firstChild", ".", "wholeText", "raise", "KeyError", "(", "name", "+", "\" not in XML\"", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L899-L910
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py
python
_EscapeEnvironmentVariableExpansion
(s)
return s
Escapes % characters. Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this. Args: s: The string to be escaped. Returns: The escaped string.
Escapes % characters.
[ "Escapes", "%", "characters", "." ]
def _EscapeEnvironmentVariableExpansion(s): """Escapes % characters. Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this. Args: s: The string to be escaped. Returns: The escaped string. """ s = s.replace('%', '%%') return s
[ "def", "_EscapeEnvironmentVariableExpansion", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "'%'", ",", "'%%'", ")", "return", "s" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/msvs.py#L684-L699
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/examples/lstm.py
python
_LSTMModel._exogenous_input_step
( self, current_times, current_exogenous_regressors, state)
return (state_from_time, prediction, current_exogenous_regressors, lstm_state)
Save exogenous regressors in model state for use in _prediction_step.
Save exogenous regressors in model state for use in _prediction_step.
[ "Save", "exogenous", "regressors", "in", "model", "state", "for", "use", "in", "_prediction_step", "." ]
def _exogenous_input_step( self, current_times, current_exogenous_regressors, state): """Save exogenous regressors in model state for use in _prediction_step.""" state_from_time, prediction, _, lstm_state = state return (state_from_time, prediction, current_exogenous_regressors, lstm_state)
[ "def", "_exogenous_input_step", "(", "self", ",", "current_times", ",", "current_exogenous_regressors", ",", "state", ")", ":", "state_from_time", ",", "prediction", ",", "_", ",", "lstm_state", "=", "state", "return", "(", "state_from_time", ",", "prediction", ",", "current_exogenous_regressors", ",", "lstm_state", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/examples/lstm.py#L179-L184
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/mpi_collectives/mpi_ops.py
python
_load_library
(name, op_list=None)
Loads a .so file containing the specified operators. Args: name: The name of the .so file to load. op_list: A list of names of operators that the library should have. If None then the .so file's contents will not be verified. Raises: NameError if one of the required ops is missing.
Loads a .so file containing the specified operators.
[ "Loads", "a", ".", "so", "file", "containing", "the", "specified", "operators", "." ]
def _load_library(name, op_list=None): """Loads a .so file containing the specified operators. Args: name: The name of the .so file to load. op_list: A list of names of operators that the library should have. If None then the .so file's contents will not be verified. Raises: NameError if one of the required ops is missing. """ try: filename = resource_loader.get_path_to_datafile(name) library = load_library.load_op_library(filename) for expected_op in (op_list or []): for lib_op in library.OP_LIST.op: if lib_op.name == expected_op: break else: raise NameError( 'Could not find operator %s in dynamic library %s' % (expected_op, name)) return library except errors.NotFoundError: logging.warning('%s file could not be loaded.', name)
[ "def", "_load_library", "(", "name", ",", "op_list", "=", "None", ")", ":", "try", ":", "filename", "=", "resource_loader", ".", "get_path_to_datafile", "(", "name", ")", "library", "=", "load_library", ".", "load_op_library", "(", "filename", ")", "for", "expected_op", "in", "(", "op_list", "or", "[", "]", ")", ":", "for", "lib_op", "in", "library", ".", "OP_LIST", ".", "op", ":", "if", "lib_op", ".", "name", "==", "expected_op", ":", "break", "else", ":", "raise", "NameError", "(", "'Could not find operator %s in dynamic library %s'", "%", "(", "expected_op", ",", "name", ")", ")", "return", "library", "except", "errors", ".", "NotFoundError", ":", "logging", ".", "warning", "(", "'%s file could not be loaded.'", ",", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/mpi_collectives/mpi_ops.py#L30-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aquabutton.py
python
AquaButton.GetDisabledColour
(self)
return self._disableColour
Returns the button colour when it is disabled. :return: An instance of :class:`Colour`.
Returns the button colour when it is disabled.
[ "Returns", "the", "button", "colour", "when", "it", "is", "disabled", "." ]
def GetDisabledColour(self): """ Returns the button colour when it is disabled. :return: An instance of :class:`Colour`. """ return self._disableColour
[ "def", "GetDisabledColour", "(", "self", ")", ":", "return", "self", ".", "_disableColour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aquabutton.py#L732-L739
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/domains/__init__.py
python
regions
()
return get_regions('route53domains', connection_cls=Route53DomainsConnection)
Get all available regions for the Amazon Route 53 Domains service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo`
Get all available regions for the Amazon Route 53 Domains service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo`
[ "Get", "all", "available", "regions", "for", "the", "Amazon", "Route", "53", "Domains", "service", ".", ":", "rtype", ":", "list", ":", "return", ":", "A", "list", "of", ":", "class", ":", "boto", ".", "regioninfo", ".", "RegionInfo" ]
def regions(): """ Get all available regions for the Amazon Route 53 Domains service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo` """ from boto.route53.domains.layer1 import Route53DomainsConnection return get_regions('route53domains', connection_cls=Route53DomainsConnection)
[ "def", "regions", "(", ")", ":", "from", "boto", ".", "route53", ".", "domains", ".", "layer1", "import", "Route53DomainsConnection", "return", "get_regions", "(", "'route53domains'", ",", "connection_cls", "=", "Route53DomainsConnection", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/domains/__init__.py#L25-L33
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/email/mime/image.py
python
MIMEImage.__init__
(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params)
Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
Create an image/* type MIME document.
[ "Create", "an", "image", "/", "*", "type", "MIME", "document", "." ]
def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
[ "def", "__init__", "(", "self", ",", "_imagedata", ",", "_subtype", "=", "None", ",", "_encoder", "=", "encoders", ".", "encode_base64", ",", "*", "*", "_params", ")", ":", "if", "_subtype", "is", "None", ":", "_subtype", "=", "imghdr", ".", "what", "(", "None", ",", "_imagedata", ")", "if", "_subtype", "is", "None", ":", "raise", "TypeError", "(", "'Could not guess image MIME subtype'", ")", "MIMENonMultipart", ".", "__init__", "(", "self", ",", "'image'", ",", "_subtype", ",", "*", "*", "_params", ")", "self", ".", "set_payload", "(", "_imagedata", ")", "_encoder", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/mime/image.py#L19-L46
eclipse/omr
056e7c9ce9d503649190bc5bd9931fac30b4e4bc
jitbuilder/apigen/genutils.py
python
APIDescription.__init_containing_table
(self, table, cs, outer_classes=[])
Generates a dictionary from class names to complete class names that include the names of containing classes from a list of client API class descriptions.
Generates a dictionary from class names to complete class names that include the names of containing classes from a list of client API class descriptions.
[ "Generates", "a", "dictionary", "from", "class", "names", "to", "complete", "class", "names", "that", "include", "the", "names", "of", "containing", "classes", "from", "a", "list", "of", "client", "API", "class", "descriptions", "." ]
def __init_containing_table(self, table, cs, outer_classes=[]): """ Generates a dictionary from class names to complete class names that include the names of containing classes from a list of client API class descriptions. """ for c in cs: self.__init_containing_table(table, c.inner_classes(), outer_classes + [c.name()]) table[c.name()] = outer_classes
[ "def", "__init_containing_table", "(", "self", ",", "table", ",", "cs", ",", "outer_classes", "=", "[", "]", ")", ":", "for", "c", "in", "cs", ":", "self", ".", "__init_containing_table", "(", "table", ",", "c", ".", "inner_classes", "(", ")", ",", "outer_classes", "+", "[", "c", ".", "name", "(", ")", "]", ")", "table", "[", "c", ".", "name", "(", ")", "]", "=", "outer_classes" ]
https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/genutils.py#L384-L392
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextParagraphLayoutBox.GetParagraphText
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_GetParagraphText(*args, **kwargs)
GetParagraphText(self, long paragraphNumber) -> String
GetParagraphText(self, long paragraphNumber) -> String
[ "GetParagraphText", "(", "self", "long", "paragraphNumber", ")", "-", ">", "String" ]
def GetParagraphText(*args, **kwargs): """GetParagraphText(self, long paragraphNumber) -> String""" return _richtext.RichTextParagraphLayoutBox_GetParagraphText(*args, **kwargs)
[ "def", "GetParagraphText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_GetParagraphText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1716-L1718
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/aoc/auxiliary_subprocessor.py
python
AoCAuxiliarySubprocessor.get_creatable_game_entity
(line)
Creates the CreatableGameEntity object for a unit/building line. :param line: Unit/Building line. :type line: ...dataformat.converter_object.ConverterObjectGroup
Creates the CreatableGameEntity object for a unit/building line.
[ "Creates", "the", "CreatableGameEntity", "object", "for", "a", "unit", "/", "building", "line", "." ]
def get_creatable_game_entity(line): """ Creates the CreatableGameEntity object for a unit/building line. :param line: Unit/Building line. :type line: ...dataformat.converter_object.ConverterObjectGroup """ if isinstance(line, GenieVillagerGroup): current_unit = line.variants[0].line[0] else: current_unit = line.line[0] current_unit_id = line.get_head_unit_id() dataset = line.data name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) game_entity_name = name_lookup_dict[current_unit_id][0] obj_ref = f"{game_entity_name}.CreatableGameEntity" obj_name = f"{game_entity_name}Creatable" creatable_raw_api_object = RawAPIObject(obj_ref, obj_name, dataset.nyan_api_objects) creatable_raw_api_object.add_raw_parent("engine.util.create.CreatableGameEntity") # Get train location of line train_location_id = line.get_train_location_id() if isinstance(line, GenieBuildingLineGroup): train_location = dataset.unit_lines[train_location_id] train_location_name = name_lookup_dict[train_location_id][0] else: train_location = dataset.building_lines[train_location_id] train_location_name = name_lookup_dict[train_location_id][0] # Location of the object depends on whether it'a a unique unit or a normal unit if line.is_unique(): # Add object to the Civ object enabling_research_id = line.get_enabling_research_id() enabling_research = dataset.genie_techs[enabling_research_id] enabling_civ_id = enabling_research["civilization_id"].get_value() civ = dataset.civ_groups[enabling_civ_id] civ_name = civ_lookup_dict[enabling_civ_id][0] creatable_location = ForwardRef(civ, civ_name) else: # Add object to the train location's Create ability creatable_location = ForwardRef(train_location, f"{train_location_name}.Create") creatable_raw_api_object.set_location(creatable_location) # Game Entity game_entity_forward_ref = ForwardRef(line, game_entity_name) creatable_raw_api_object.add_raw_member("game_entity", game_entity_forward_ref, "engine.util.create.CreatableGameEntity") # TODO: Variants variants_set = [] creatable_raw_api_object.add_raw_member("variants", variants_set, "engine.util.create.CreatableGameEntity") # Cost (construction) cost_name = f"{game_entity_name}.CreatableGameEntity.{game_entity_name}Cost" cost_raw_api_object = RawAPIObject(cost_name, f"{game_entity_name}Cost", dataset.nyan_api_objects) cost_raw_api_object.add_raw_parent("engine.util.cost.type.ResourceCost") creatable_forward_ref = ForwardRef(line, obj_ref) cost_raw_api_object.set_location(creatable_forward_ref) payment_mode = dataset.nyan_api_objects["engine.util.payment_mode.type.Advance"] cost_raw_api_object.add_raw_member("payment_mode", payment_mode, "engine.util.cost.Cost") if line.is_repairable(): # Cost (repair) for buildings cost_repair_name = "%s.CreatableGameEntity.%sRepairCost" % (game_entity_name, game_entity_name) cost_repair_raw_api_object = RawAPIObject(cost_repair_name, f"{game_entity_name}RepairCost", dataset.nyan_api_objects) cost_repair_raw_api_object.add_raw_parent("engine.util.cost.type.ResourceCost") creatable_forward_ref = ForwardRef(line, obj_ref) cost_repair_raw_api_object.set_location(creatable_forward_ref) payment_repair_mode = dataset.nyan_api_objects["engine.util.payment_mode.type.Adaptive"] cost_repair_raw_api_object.add_raw_member("payment_mode", payment_repair_mode, "engine.util.cost.Cost") line.add_raw_api_object(cost_repair_raw_api_object) cost_amounts = [] cost_repair_amounts = [] for resource_amount in current_unit["resource_cost"].get_value(): resource_id = resource_amount["type_id"].get_value() resource = None resource_name = "" if resource_id == -1: # Not a valid resource continue if resource_id == 0: resource = dataset.pregen_nyan_objects["util.resource.types.Food"].get_nyan_object() resource_name = "Food" elif resource_id == 1: resource = dataset.pregen_nyan_objects["util.resource.types.Wood"].get_nyan_object() resource_name = "Wood" elif resource_id == 2: resource = dataset.pregen_nyan_objects["util.resource.types.Stone"].get_nyan_object() resource_name = "Stone" elif resource_id == 3: resource = dataset.pregen_nyan_objects["util.resource.types.Gold"].get_nyan_object() resource_name = "Gold" else: # Other resource ids are handled differently continue # Skip resources that are only expected to be there if not resource_amount["enabled"].get_value(): continue amount = resource_amount["amount"].get_value() cost_amount_name = f"{cost_name}.{resource_name}Amount" cost_amount = RawAPIObject(cost_amount_name, f"{resource_name}Amount", dataset.nyan_api_objects) cost_amount.add_raw_parent("engine.util.resource.ResourceAmount") cost_forward_ref = ForwardRef(line, cost_name) cost_amount.set_location(cost_forward_ref) cost_amount.add_raw_member("type", resource, "engine.util.resource.ResourceAmount") cost_amount.add_raw_member("amount", amount, "engine.util.resource.ResourceAmount") cost_amount_forward_ref = ForwardRef(line, cost_amount_name) cost_amounts.append(cost_amount_forward_ref) line.add_raw_api_object(cost_amount) if line.is_repairable(): # Cost for repairing = half of the construction cost cost_amount_name = f"{cost_repair_name}.{resource_name}Amount" cost_amount = RawAPIObject(cost_amount_name, f"{resource_name}Amount", dataset.nyan_api_objects) cost_amount.add_raw_parent("engine.util.resource.ResourceAmount") cost_forward_ref = ForwardRef(line, cost_repair_name) cost_amount.set_location(cost_forward_ref) cost_amount.add_raw_member("type", resource, "engine.util.resource.ResourceAmount") cost_amount.add_raw_member("amount", amount / 2, "engine.util.resource.ResourceAmount") cost_amount_forward_ref = ForwardRef(line, cost_amount_name) cost_repair_amounts.append(cost_amount_forward_ref) line.add_raw_api_object(cost_amount) cost_raw_api_object.add_raw_member("amount", cost_amounts, "engine.util.cost.type.ResourceCost") if line.is_repairable(): cost_repair_raw_api_object.add_raw_member("amount", cost_repair_amounts, "engine.util.cost.type.ResourceCost") cost_forward_ref = ForwardRef(line, cost_name) creatable_raw_api_object.add_raw_member("cost", cost_forward_ref, "engine.util.create.CreatableGameEntity") # Creation time if isinstance(line, GenieUnitLineGroup): creation_time = current_unit["creation_time"].get_value() else: # Buildings are created immediately creation_time = 0 creatable_raw_api_object.add_raw_member("creation_time", creation_time, "engine.util.create.CreatableGameEntity") # Creation sound creation_sound_id = current_unit["train_sound_id"].get_value() # Create sound object obj_name = f"{game_entity_name}.CreatableGameEntity.Sound" sound_raw_api_object = RawAPIObject(obj_name, "CreationSound", dataset.nyan_api_objects) sound_raw_api_object.add_raw_parent("engine.util.sound.Sound") sound_location = ForwardRef(line, obj_ref) sound_raw_api_object.set_location(sound_location) # Search for the sound if it exists creation_sounds = [] if creation_sound_id > -1: # Creation sound should be civ agnostic genie_sound = dataset.genie_sounds[creation_sound_id] file_id = genie_sound.get_sounds(civ_id=-1)[0] if file_id in dataset.combined_sounds: creation_sound = dataset.combined_sounds[file_id] creation_sound.add_reference(sound_raw_api_object) else: creation_sound = CombinedSound(creation_sound_id, file_id, f"creation_sound_{creation_sound_id}", dataset) dataset.combined_sounds.update({file_id: creation_sound}) creation_sound.add_reference(sound_raw_api_object) creation_sounds.append(creation_sound) sound_raw_api_object.add_raw_member("play_delay", 0, "engine.util.sound.Sound") sound_raw_api_object.add_raw_member("sounds", creation_sounds, "engine.util.sound.Sound") sound_forward_ref = ForwardRef(line, obj_name) creatable_raw_api_object.add_raw_member("creation_sounds", [sound_forward_ref], "engine.util.create.CreatableGameEntity") line.add_raw_api_object(sound_raw_api_object) # Condition unlock_conditions = [] enabling_research_id = line.get_enabling_research_id() if enabling_research_id > -1: unlock_conditions.extend(AoCAuxiliarySubprocessor.get_condition(line, obj_ref, enabling_research_id)) creatable_raw_api_object.add_raw_member("condition", unlock_conditions, "engine.util.create.CreatableGameEntity") # Placement modes placement_modes = [] if isinstance(line, GenieBuildingLineGroup): # Buildings are placed on the map # Place mode obj_name = f"{game_entity_name}.CreatableGameEntity.Place" place_raw_api_object = RawAPIObject(obj_name, "Place", dataset.nyan_api_objects) place_raw_api_object.add_raw_parent("engine.util.placement_mode.type.Place") place_location = ForwardRef(line, f"{game_entity_name}.CreatableGameEntity") place_raw_api_object.set_location(place_location) # Tile snap distance (uses 1.0 for grid placement) place_raw_api_object.add_raw_member("tile_snap_distance", 1.0, "engine.util.placement_mode.type.Place") # Clearance size clearance_size_x = current_unit["clearance_size_x"].get_value() clearance_size_y = current_unit["clearance_size_y"].get_value() place_raw_api_object.add_raw_member("clearance_size_x", clearance_size_x, "engine.util.placement_mode.type.Place") place_raw_api_object.add_raw_member("clearance_size_y", clearance_size_y, "engine.util.placement_mode.type.Place") # Allow rotation place_raw_api_object.add_raw_member("allow_rotation", True, "engine.util.placement_mode.type.Place") # Max elevation difference elevation_mode = current_unit["elevation_mode"].get_value() if elevation_mode == 2: max_elevation_difference = 0 elif elevation_mode == 3: max_elevation_difference = 1 else: max_elevation_difference = MemberSpecialValue.NYAN_INF place_raw_api_object.add_raw_member("max_elevation_difference", max_elevation_difference, "engine.util.placement_mode.type.Place") line.add_raw_api_object(place_raw_api_object) place_forward_ref = ForwardRef(line, obj_name) placement_modes.append(place_forward_ref) if line.get_class_id() == 39: # Gates obj_name = f"{game_entity_name}.CreatableGameEntity.Replace" replace_raw_api_object = RawAPIObject(obj_name, "Replace", dataset.nyan_api_objects) replace_raw_api_object.add_raw_parent("engine.util.placement_mode.type.Replace") replace_location = ForwardRef(line, f"{game_entity_name}.CreatableGameEntity") replace_raw_api_object.set_location(replace_location) # Game entities (only stone wall) wall_line_id = 117 wall_line = dataset.building_lines[wall_line_id] wall_name = name_lookup_dict[117][0] game_entities = [ForwardRef(wall_line, wall_name)] replace_raw_api_object.add_raw_member("game_entities", game_entities, "engine.util.placement_mode.type.Replace") line.add_raw_api_object(replace_raw_api_object) replace_forward_ref = ForwardRef(line, obj_name) placement_modes.append(replace_forward_ref) else: placement_modes.append(dataset.nyan_api_objects["engine.util.placement_mode.type.Eject"]) # OwnStorage mode obj_name = f"{game_entity_name}.CreatableGameEntity.OwnStorage" own_storage_raw_api_object = RawAPIObject(obj_name, "OwnStorage", dataset.nyan_api_objects) own_storage_raw_api_object.add_raw_parent("engine.util.placement_mode.type.OwnStorage") own_storage_location = ForwardRef(line, f"{game_entity_name}.CreatableGameEntity") own_storage_raw_api_object.set_location(own_storage_location) # Container container_forward_ref = ForwardRef(train_location, "%s.Storage.%sContainer" % (train_location_name, train_location_name)) own_storage_raw_api_object.add_raw_member("container", container_forward_ref, "engine.util.placement_mode.type.OwnStorage") line.add_raw_api_object(own_storage_raw_api_object) own_storage_forward_ref = ForwardRef(line, obj_name) placement_modes.append(own_storage_forward_ref) creatable_raw_api_object.add_raw_member("placement_modes", placement_modes, "engine.util.create.CreatableGameEntity") line.add_raw_api_object(creatable_raw_api_object) line.add_raw_api_object(cost_raw_api_object)
[ "def", "get_creatable_game_entity", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "GenieVillagerGroup", ")", ":", "current_unit", "=", "line", ".", "variants", "[", "0", "]", ".", "line", "[", "0", "]", "else", ":", "current_unit", "=", "line", ".", "line", "[", "0", "]", "current_unit_id", "=", "line", ".", "get_head_unit_id", "(", ")", "dataset", "=", "line", ".", "data", "name_lookup_dict", "=", "internal_name_lookups", ".", "get_entity_lookups", "(", "dataset", ".", "game_version", ")", "civ_lookup_dict", "=", "internal_name_lookups", ".", "get_civ_lookups", "(", "dataset", ".", "game_version", ")", "game_entity_name", "=", "name_lookup_dict", "[", "current_unit_id", "]", "[", "0", "]", "obj_ref", "=", "f\"{game_entity_name}.CreatableGameEntity\"", "obj_name", "=", "f\"{game_entity_name}Creatable\"", "creatable_raw_api_object", "=", "RawAPIObject", "(", "obj_ref", ",", "obj_name", ",", "dataset", ".", "nyan_api_objects", ")", "creatable_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.create.CreatableGameEntity\"", ")", "# Get train location of line", "train_location_id", "=", "line", ".", "get_train_location_id", "(", ")", "if", "isinstance", "(", "line", ",", "GenieBuildingLineGroup", ")", ":", "train_location", "=", "dataset", ".", "unit_lines", "[", "train_location_id", "]", "train_location_name", "=", "name_lookup_dict", "[", "train_location_id", "]", "[", "0", "]", "else", ":", "train_location", "=", "dataset", ".", "building_lines", "[", "train_location_id", "]", "train_location_name", "=", "name_lookup_dict", "[", "train_location_id", "]", "[", "0", "]", "# Location of the object depends on whether it'a a unique unit or a normal unit", "if", "line", ".", "is_unique", "(", ")", ":", "# Add object to the Civ object", "enabling_research_id", "=", "line", ".", "get_enabling_research_id", "(", ")", "enabling_research", "=", "dataset", ".", "genie_techs", "[", "enabling_research_id", "]", "enabling_civ_id", "=", "enabling_research", "[", "\"civilization_id\"", "]", ".", "get_value", "(", ")", "civ", "=", "dataset", ".", "civ_groups", "[", "enabling_civ_id", "]", "civ_name", "=", "civ_lookup_dict", "[", "enabling_civ_id", "]", "[", "0", "]", "creatable_location", "=", "ForwardRef", "(", "civ", ",", "civ_name", ")", "else", ":", "# Add object to the train location's Create ability", "creatable_location", "=", "ForwardRef", "(", "train_location", ",", "f\"{train_location_name}.Create\"", ")", "creatable_raw_api_object", ".", "set_location", "(", "creatable_location", ")", "# Game Entity", "game_entity_forward_ref", "=", "ForwardRef", "(", "line", ",", "game_entity_name", ")", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"game_entity\"", ",", "game_entity_forward_ref", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "# TODO: Variants", "variants_set", "=", "[", "]", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"variants\"", ",", "variants_set", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "# Cost (construction)", "cost_name", "=", "f\"{game_entity_name}.CreatableGameEntity.{game_entity_name}Cost\"", "cost_raw_api_object", "=", "RawAPIObject", "(", "cost_name", ",", "f\"{game_entity_name}Cost\"", ",", "dataset", ".", "nyan_api_objects", ")", "cost_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.cost.type.ResourceCost\"", ")", "creatable_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_ref", ")", "cost_raw_api_object", ".", "set_location", "(", "creatable_forward_ref", ")", "payment_mode", "=", "dataset", ".", "nyan_api_objects", "[", "\"engine.util.payment_mode.type.Advance\"", "]", "cost_raw_api_object", ".", "add_raw_member", "(", "\"payment_mode\"", ",", "payment_mode", ",", "\"engine.util.cost.Cost\"", ")", "if", "line", ".", "is_repairable", "(", ")", ":", "# Cost (repair) for buildings", "cost_repair_name", "=", "\"%s.CreatableGameEntity.%sRepairCost\"", "%", "(", "game_entity_name", ",", "game_entity_name", ")", "cost_repair_raw_api_object", "=", "RawAPIObject", "(", "cost_repair_name", ",", "f\"{game_entity_name}RepairCost\"", ",", "dataset", ".", "nyan_api_objects", ")", "cost_repair_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.cost.type.ResourceCost\"", ")", "creatable_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_ref", ")", "cost_repair_raw_api_object", ".", "set_location", "(", "creatable_forward_ref", ")", "payment_repair_mode", "=", "dataset", ".", "nyan_api_objects", "[", "\"engine.util.payment_mode.type.Adaptive\"", "]", "cost_repair_raw_api_object", ".", "add_raw_member", "(", "\"payment_mode\"", ",", "payment_repair_mode", ",", "\"engine.util.cost.Cost\"", ")", "line", ".", "add_raw_api_object", "(", "cost_repair_raw_api_object", ")", "cost_amounts", "=", "[", "]", "cost_repair_amounts", "=", "[", "]", "for", "resource_amount", "in", "current_unit", "[", "\"resource_cost\"", "]", ".", "get_value", "(", ")", ":", "resource_id", "=", "resource_amount", "[", "\"type_id\"", "]", ".", "get_value", "(", ")", "resource", "=", "None", "resource_name", "=", "\"\"", "if", "resource_id", "==", "-", "1", ":", "# Not a valid resource", "continue", "if", "resource_id", "==", "0", ":", "resource", "=", "dataset", ".", "pregen_nyan_objects", "[", "\"util.resource.types.Food\"", "]", ".", "get_nyan_object", "(", ")", "resource_name", "=", "\"Food\"", "elif", "resource_id", "==", "1", ":", "resource", "=", "dataset", ".", "pregen_nyan_objects", "[", "\"util.resource.types.Wood\"", "]", ".", "get_nyan_object", "(", ")", "resource_name", "=", "\"Wood\"", "elif", "resource_id", "==", "2", ":", "resource", "=", "dataset", ".", "pregen_nyan_objects", "[", "\"util.resource.types.Stone\"", "]", ".", "get_nyan_object", "(", ")", "resource_name", "=", "\"Stone\"", "elif", "resource_id", "==", "3", ":", "resource", "=", "dataset", ".", "pregen_nyan_objects", "[", "\"util.resource.types.Gold\"", "]", ".", "get_nyan_object", "(", ")", "resource_name", "=", "\"Gold\"", "else", ":", "# Other resource ids are handled differently", "continue", "# Skip resources that are only expected to be there", "if", "not", "resource_amount", "[", "\"enabled\"", "]", ".", "get_value", "(", ")", ":", "continue", "amount", "=", "resource_amount", "[", "\"amount\"", "]", ".", "get_value", "(", ")", "cost_amount_name", "=", "f\"{cost_name}.{resource_name}Amount\"", "cost_amount", "=", "RawAPIObject", "(", "cost_amount_name", ",", "f\"{resource_name}Amount\"", ",", "dataset", ".", "nyan_api_objects", ")", "cost_amount", ".", "add_raw_parent", "(", "\"engine.util.resource.ResourceAmount\"", ")", "cost_forward_ref", "=", "ForwardRef", "(", "line", ",", "cost_name", ")", "cost_amount", ".", "set_location", "(", "cost_forward_ref", ")", "cost_amount", ".", "add_raw_member", "(", "\"type\"", ",", "resource", ",", "\"engine.util.resource.ResourceAmount\"", ")", "cost_amount", ".", "add_raw_member", "(", "\"amount\"", ",", "amount", ",", "\"engine.util.resource.ResourceAmount\"", ")", "cost_amount_forward_ref", "=", "ForwardRef", "(", "line", ",", "cost_amount_name", ")", "cost_amounts", ".", "append", "(", "cost_amount_forward_ref", ")", "line", ".", "add_raw_api_object", "(", "cost_amount", ")", "if", "line", ".", "is_repairable", "(", ")", ":", "# Cost for repairing = half of the construction cost", "cost_amount_name", "=", "f\"{cost_repair_name}.{resource_name}Amount\"", "cost_amount", "=", "RawAPIObject", "(", "cost_amount_name", ",", "f\"{resource_name}Amount\"", ",", "dataset", ".", "nyan_api_objects", ")", "cost_amount", ".", "add_raw_parent", "(", "\"engine.util.resource.ResourceAmount\"", ")", "cost_forward_ref", "=", "ForwardRef", "(", "line", ",", "cost_repair_name", ")", "cost_amount", ".", "set_location", "(", "cost_forward_ref", ")", "cost_amount", ".", "add_raw_member", "(", "\"type\"", ",", "resource", ",", "\"engine.util.resource.ResourceAmount\"", ")", "cost_amount", ".", "add_raw_member", "(", "\"amount\"", ",", "amount", "/", "2", ",", "\"engine.util.resource.ResourceAmount\"", ")", "cost_amount_forward_ref", "=", "ForwardRef", "(", "line", ",", "cost_amount_name", ")", "cost_repair_amounts", ".", "append", "(", "cost_amount_forward_ref", ")", "line", ".", "add_raw_api_object", "(", "cost_amount", ")", "cost_raw_api_object", ".", "add_raw_member", "(", "\"amount\"", ",", "cost_amounts", ",", "\"engine.util.cost.type.ResourceCost\"", ")", "if", "line", ".", "is_repairable", "(", ")", ":", "cost_repair_raw_api_object", ".", "add_raw_member", "(", "\"amount\"", ",", "cost_repair_amounts", ",", "\"engine.util.cost.type.ResourceCost\"", ")", "cost_forward_ref", "=", "ForwardRef", "(", "line", ",", "cost_name", ")", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"cost\"", ",", "cost_forward_ref", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "# Creation time", "if", "isinstance", "(", "line", ",", "GenieUnitLineGroup", ")", ":", "creation_time", "=", "current_unit", "[", "\"creation_time\"", "]", ".", "get_value", "(", ")", "else", ":", "# Buildings are created immediately", "creation_time", "=", "0", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"creation_time\"", ",", "creation_time", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "# Creation sound", "creation_sound_id", "=", "current_unit", "[", "\"train_sound_id\"", "]", ".", "get_value", "(", ")", "# Create sound object", "obj_name", "=", "f\"{game_entity_name}.CreatableGameEntity.Sound\"", "sound_raw_api_object", "=", "RawAPIObject", "(", "obj_name", ",", "\"CreationSound\"", ",", "dataset", ".", "nyan_api_objects", ")", "sound_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.sound.Sound\"", ")", "sound_location", "=", "ForwardRef", "(", "line", ",", "obj_ref", ")", "sound_raw_api_object", ".", "set_location", "(", "sound_location", ")", "# Search for the sound if it exists", "creation_sounds", "=", "[", "]", "if", "creation_sound_id", ">", "-", "1", ":", "# Creation sound should be civ agnostic", "genie_sound", "=", "dataset", ".", "genie_sounds", "[", "creation_sound_id", "]", "file_id", "=", "genie_sound", ".", "get_sounds", "(", "civ_id", "=", "-", "1", ")", "[", "0", "]", "if", "file_id", "in", "dataset", ".", "combined_sounds", ":", "creation_sound", "=", "dataset", ".", "combined_sounds", "[", "file_id", "]", "creation_sound", ".", "add_reference", "(", "sound_raw_api_object", ")", "else", ":", "creation_sound", "=", "CombinedSound", "(", "creation_sound_id", ",", "file_id", ",", "f\"creation_sound_{creation_sound_id}\"", ",", "dataset", ")", "dataset", ".", "combined_sounds", ".", "update", "(", "{", "file_id", ":", "creation_sound", "}", ")", "creation_sound", ".", "add_reference", "(", "sound_raw_api_object", ")", "creation_sounds", ".", "append", "(", "creation_sound", ")", "sound_raw_api_object", ".", "add_raw_member", "(", "\"play_delay\"", ",", "0", ",", "\"engine.util.sound.Sound\"", ")", "sound_raw_api_object", ".", "add_raw_member", "(", "\"sounds\"", ",", "creation_sounds", ",", "\"engine.util.sound.Sound\"", ")", "sound_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_name", ")", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"creation_sounds\"", ",", "[", "sound_forward_ref", "]", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "line", ".", "add_raw_api_object", "(", "sound_raw_api_object", ")", "# Condition", "unlock_conditions", "=", "[", "]", "enabling_research_id", "=", "line", ".", "get_enabling_research_id", "(", ")", "if", "enabling_research_id", ">", "-", "1", ":", "unlock_conditions", ".", "extend", "(", "AoCAuxiliarySubprocessor", ".", "get_condition", "(", "line", ",", "obj_ref", ",", "enabling_research_id", ")", ")", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"condition\"", ",", "unlock_conditions", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "# Placement modes", "placement_modes", "=", "[", "]", "if", "isinstance", "(", "line", ",", "GenieBuildingLineGroup", ")", ":", "# Buildings are placed on the map", "# Place mode", "obj_name", "=", "f\"{game_entity_name}.CreatableGameEntity.Place\"", "place_raw_api_object", "=", "RawAPIObject", "(", "obj_name", ",", "\"Place\"", ",", "dataset", ".", "nyan_api_objects", ")", "place_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.placement_mode.type.Place\"", ")", "place_location", "=", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.CreatableGameEntity\"", ")", "place_raw_api_object", ".", "set_location", "(", "place_location", ")", "# Tile snap distance (uses 1.0 for grid placement)", "place_raw_api_object", ".", "add_raw_member", "(", "\"tile_snap_distance\"", ",", "1.0", ",", "\"engine.util.placement_mode.type.Place\"", ")", "# Clearance size", "clearance_size_x", "=", "current_unit", "[", "\"clearance_size_x\"", "]", ".", "get_value", "(", ")", "clearance_size_y", "=", "current_unit", "[", "\"clearance_size_y\"", "]", ".", "get_value", "(", ")", "place_raw_api_object", ".", "add_raw_member", "(", "\"clearance_size_x\"", ",", "clearance_size_x", ",", "\"engine.util.placement_mode.type.Place\"", ")", "place_raw_api_object", ".", "add_raw_member", "(", "\"clearance_size_y\"", ",", "clearance_size_y", ",", "\"engine.util.placement_mode.type.Place\"", ")", "# Allow rotation", "place_raw_api_object", ".", "add_raw_member", "(", "\"allow_rotation\"", ",", "True", ",", "\"engine.util.placement_mode.type.Place\"", ")", "# Max elevation difference", "elevation_mode", "=", "current_unit", "[", "\"elevation_mode\"", "]", ".", "get_value", "(", ")", "if", "elevation_mode", "==", "2", ":", "max_elevation_difference", "=", "0", "elif", "elevation_mode", "==", "3", ":", "max_elevation_difference", "=", "1", "else", ":", "max_elevation_difference", "=", "MemberSpecialValue", ".", "NYAN_INF", "place_raw_api_object", ".", "add_raw_member", "(", "\"max_elevation_difference\"", ",", "max_elevation_difference", ",", "\"engine.util.placement_mode.type.Place\"", ")", "line", ".", "add_raw_api_object", "(", "place_raw_api_object", ")", "place_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_name", ")", "placement_modes", ".", "append", "(", "place_forward_ref", ")", "if", "line", ".", "get_class_id", "(", ")", "==", "39", ":", "# Gates", "obj_name", "=", "f\"{game_entity_name}.CreatableGameEntity.Replace\"", "replace_raw_api_object", "=", "RawAPIObject", "(", "obj_name", ",", "\"Replace\"", ",", "dataset", ".", "nyan_api_objects", ")", "replace_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.placement_mode.type.Replace\"", ")", "replace_location", "=", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.CreatableGameEntity\"", ")", "replace_raw_api_object", ".", "set_location", "(", "replace_location", ")", "# Game entities (only stone wall)", "wall_line_id", "=", "117", "wall_line", "=", "dataset", ".", "building_lines", "[", "wall_line_id", "]", "wall_name", "=", "name_lookup_dict", "[", "117", "]", "[", "0", "]", "game_entities", "=", "[", "ForwardRef", "(", "wall_line", ",", "wall_name", ")", "]", "replace_raw_api_object", ".", "add_raw_member", "(", "\"game_entities\"", ",", "game_entities", ",", "\"engine.util.placement_mode.type.Replace\"", ")", "line", ".", "add_raw_api_object", "(", "replace_raw_api_object", ")", "replace_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_name", ")", "placement_modes", ".", "append", "(", "replace_forward_ref", ")", "else", ":", "placement_modes", ".", "append", "(", "dataset", ".", "nyan_api_objects", "[", "\"engine.util.placement_mode.type.Eject\"", "]", ")", "# OwnStorage mode", "obj_name", "=", "f\"{game_entity_name}.CreatableGameEntity.OwnStorage\"", "own_storage_raw_api_object", "=", "RawAPIObject", "(", "obj_name", ",", "\"OwnStorage\"", ",", "dataset", ".", "nyan_api_objects", ")", "own_storage_raw_api_object", ".", "add_raw_parent", "(", "\"engine.util.placement_mode.type.OwnStorage\"", ")", "own_storage_location", "=", "ForwardRef", "(", "line", ",", "f\"{game_entity_name}.CreatableGameEntity\"", ")", "own_storage_raw_api_object", ".", "set_location", "(", "own_storage_location", ")", "# Container", "container_forward_ref", "=", "ForwardRef", "(", "train_location", ",", "\"%s.Storage.%sContainer\"", "%", "(", "train_location_name", ",", "train_location_name", ")", ")", "own_storage_raw_api_object", ".", "add_raw_member", "(", "\"container\"", ",", "container_forward_ref", ",", "\"engine.util.placement_mode.type.OwnStorage\"", ")", "line", ".", "add_raw_api_object", "(", "own_storage_raw_api_object", ")", "own_storage_forward_ref", "=", "ForwardRef", "(", "line", ",", "obj_name", ")", "placement_modes", ".", "append", "(", "own_storage_forward_ref", ")", "creatable_raw_api_object", ".", "add_raw_member", "(", "\"placement_modes\"", ",", "placement_modes", ",", "\"engine.util.create.CreatableGameEntity\"", ")", "line", ".", "add_raw_api_object", "(", "creatable_raw_api_object", ")", "line", ".", "add_raw_api_object", "(", "cost_raw_api_object", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/auxiliary_subprocessor.py#L24-L390
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/distro.py
python
DistroStack.__init__
(self, stack_name, stack_version, release_name, rules)
:param stack_name: Name of stack :param stack_version: Version number of stack. :param release_name: name of distribution release. Necessary for rule expansion. :param rules: raw '_rules' data. Will be converted into appropriate vcs config instance.
:param stack_name: Name of stack :param stack_version: Version number of stack. :param release_name: name of distribution release. Necessary for rule expansion. :param rules: raw '_rules' data. Will be converted into appropriate vcs config instance.
[ ":", "param", "stack_name", ":", "Name", "of", "stack", ":", "param", "stack_version", ":", "Version", "number", "of", "stack", ".", ":", "param", "release_name", ":", "name", "of", "distribution", "release", ".", "Necessary", "for", "rule", "expansion", ".", ":", "param", "rules", ":", "raw", "_rules", "data", ".", "Will", "be", "converted", "into", "appropriate", "vcs", "config", "instance", "." ]
def __init__(self, stack_name, stack_version, release_name, rules): """ :param stack_name: Name of stack :param stack_version: Version number of stack. :param release_name: name of distribution release. Necessary for rule expansion. :param rules: raw '_rules' data. Will be converted into appropriate vcs config instance. """ self.name = stack_name self.version = stack_version self.release_name = release_name self._rules = rules self.repo = rules.get('repo', None) self.vcs_config = load_vcs_config(self._rules, self._expand_rule)
[ "def", "__init__", "(", "self", ",", "stack_name", ",", "stack_version", ",", "release_name", ",", "rules", ")", ":", "self", ".", "name", "=", "stack_name", "self", ".", "version", "=", "stack_version", "self", ".", "release_name", "=", "release_name", "self", ".", "_rules", "=", "rules", "self", ".", "repo", "=", "rules", ".", "get", "(", "'repo'", ",", "None", ")", "self", ".", "vcs_config", "=", "load_vcs_config", "(", "self", ".", "_rules", ",", "self", ".", "_expand_rule", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/distro.py#L78-L90
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
reduce_sum
(input_tensor, reduction_indices=None, keep_dims=False, name=None)
return gen_math_ops._sum(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
Computes the sum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[1, 1, 1] # [1, 1, 1]] tf.reduce_sum(x) ==> 6 tf.reduce_sum(x, 0) ==> [2, 2, 2] tf.reduce_sum(x, 1) ==> [3, 3] tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]] tf.reduce_sum(x, [0, 1]) ==> 6 ``` Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor.
Computes the sum of elements across dimensions of a tensor.
[ "Computes", "the", "sum", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the sum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[1, 1, 1] # [1, 1, 1]] tf.reduce_sum(x) ==> 6 tf.reduce_sum(x, 0) ==> [2, 2, 2] tf.reduce_sum(x, 1) ==> [3, 3] tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]] tf.reduce_sum(x, [0, 1]) ==> 6 ``` Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._sum(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
[ "def", "reduce_sum", "(", "input_tensor", ",", "reduction_indices", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_sum", "(", "input_tensor", ",", "_ReductionDims", "(", "input_tensor", ",", "reduction_indices", ")", ",", "keep_dims", ",", "name", "=", "name", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1022-L1058
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozbuild/virtualenv.py
python
VirtualenvManager.populate
(self)
Populate the virtualenv. The manifest file consists of colon-delimited fields. The first field specifies the action. The remaining fields are arguments to that action. The following actions are supported: setup.py -- Invoke setup.py for a package. Expects the arguments: 1. relative path directory containing setup.py. 2. argument(s) to setup.py. e.g. "develop". Each program argument is delimited by a colon. Arguments with colons are not yet supported. filename.pth -- Adds the path given as argument to filename.pth under the virtualenv site packages directory. optional -- This denotes the action as optional. The requested action is attempted. If it fails, we issue a warning and go on. The initial "optional" field is stripped then the remaining line is processed like normal. e.g. "optional:setup.py:python/foo:built_ext:-i" copy -- Copies the given file in the virtualenv site packages directory. packages.txt -- Denotes that the specified path is a child manifest. It will be read and processed as if its contents were concatenated into the manifest being read. objdir -- Denotes a relative path in the object directory to add to the search path. e.g. "objdir:build" will add $topobjdir/build to the search path. Note that the Python interpreter running this function should be the one from the virtualenv. If it is the system Python or if the environment is not configured properly, packages could be installed into the wrong place. This is how virtualenv's work.
Populate the virtualenv.
[ "Populate", "the", "virtualenv", "." ]
def populate(self): """Populate the virtualenv. The manifest file consists of colon-delimited fields. The first field specifies the action. The remaining fields are arguments to that action. The following actions are supported: setup.py -- Invoke setup.py for a package. Expects the arguments: 1. relative path directory containing setup.py. 2. argument(s) to setup.py. e.g. "develop". Each program argument is delimited by a colon. Arguments with colons are not yet supported. filename.pth -- Adds the path given as argument to filename.pth under the virtualenv site packages directory. optional -- This denotes the action as optional. The requested action is attempted. If it fails, we issue a warning and go on. The initial "optional" field is stripped then the remaining line is processed like normal. e.g. "optional:setup.py:python/foo:built_ext:-i" copy -- Copies the given file in the virtualenv site packages directory. packages.txt -- Denotes that the specified path is a child manifest. It will be read and processed as if its contents were concatenated into the manifest being read. objdir -- Denotes a relative path in the object directory to add to the search path. e.g. "objdir:build" will add $topobjdir/build to the search path. Note that the Python interpreter running this function should be the one from the virtualenv. If it is the system Python or if the environment is not configured properly, packages could be installed into the wrong place. This is how virtualenv's work. """ packages = self.packages() def handle_package(package): python_lib = distutils.sysconfig.get_python_lib() if package[0] == 'setup.py': assert len(package) >= 2 self.call_setup(os.path.join(self.topsrcdir, package[1]), package[2:]) return True if package[0] == 'copy': assert len(package) == 2 src = os.path.join(self.topsrcdir, package[1]) dst = os.path.join(python_lib, os.path.basename(package[1])) shutil.copy(src, dst) return True if package[0] == 'packages.txt': assert len(package) == 2 src = os.path.join(self.topsrcdir, package[1]) assert os.path.isfile(src), "'%s' does not exist" % src submanager = VirtualenvManager(self.topsrcdir, self.topobjdir, self.virtualenv_root, self.log_handle, src) submanager.populate() return True if package[0].endswith('.pth'): assert len(package) == 2 path = os.path.join(self.topsrcdir, package[1]) with open(os.path.join(python_lib, package[0]), 'a') as f: # This path is relative to the .pth file. Using a # relative path allows the srcdir/objdir combination # to be moved around (as long as the paths relative to # each other remain the same). try: f.write("%s\n" % os.path.relpath(path, python_lib)) except ValueError: # When objdir is on a separate drive, relpath throws f.write("%s\n" % os.path.join(python_lib, path)) return True if package[0] == 'optional': try: handle_package(package[1:]) return True except: print('Error processing command. Ignoring', \ 'because optional. (%s)' % ':'.join(package), file=self.log_handle) return False if package[0] == 'objdir': assert len(package) == 2 path = os.path.join(self.topobjdir, package[1]) with open(os.path.join(python_lib, 'objdir.pth'), 'a') as f: f.write('%s\n' % path) return True raise Exception('Unknown action: %s' % package[0]) # We always target the OS X deployment target that Python itself was # built with, regardless of what's in the current environment. If we # don't do # this, we may run into a Python bug. See # http://bugs.python.org/issue9516 and bug 659881. # # Note that this assumes that nothing compiled in the virtualenv is # shipped as part of a distribution. If we do ship anything, the # deployment target here may be different from what's targeted by the # shipping binaries and # virtualenv-produced binaries may fail to # work. # # We also ignore environment variables that may have been altered by # configure or a mozconfig activated in the current shell. We trust # Python is smart enough to find a proper compiler and to use the # proper compiler flags. If it isn't your Python is likely broken. IGNORE_ENV_VARIABLES = ('CC', 'CXX', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'PYTHONDONTWRITEBYTECODE') try: old_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) sysconfig_target = \ distutils.sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') if sysconfig_target is not None: os.environ['MACOSX_DEPLOYMENT_TARGET'] = sysconfig_target old_env_variables = {} for k in IGNORE_ENV_VARIABLES: if k not in os.environ: continue old_env_variables[k] = os.environ[k] del os.environ[k] # HACK ALERT. # # The following adjustment to the VSNNCOMNTOOLS environment # variables are wrong. This is done as a hack to facilitate the # building of binary Python packages - notably psutil - on Windows # machines that don't have the Visual Studio 2008 binaries # installed. This hack assumes the Python on that system was built # with Visual Studio 2008. The hack is wrong for the reasons # explained at # http://stackoverflow.com/questions/3047542/building-lxml-for-python-2-7-on-windows/5122521#5122521. if sys.platform in ('win32', 'cygwin') and \ 'VS90COMNTOOLS' not in os.environ: warnings.warn('Hacking environment to allow binary Python ' 'extensions to build. You can make this warning go away ' 'by installing Visual Studio 2008. You can download the ' 'Express Edition installer from ' 'http://go.microsoft.com/?linkid=7729279') # We list in order from oldest to newest to prefer the closest # to 2008 so differences are minimized. for ver in ('100', '110', '120'): var = 'VS%sCOMNTOOLS' % ver if var in os.environ: os.environ['VS90COMNTOOLS'] = os.environ[var] break for package in packages: handle_package(package) finally: os.environ.pop('MACOSX_DEPLOYMENT_TARGET', None) if old_target is not None: os.environ['MACOSX_DEPLOYMENT_TARGET'] = old_target os.environ.update(old_env_variables)
[ "def", "populate", "(", "self", ")", ":", "packages", "=", "self", ".", "packages", "(", ")", "def", "handle_package", "(", "package", ")", ":", "python_lib", "=", "distutils", ".", "sysconfig", ".", "get_python_lib", "(", ")", "if", "package", "[", "0", "]", "==", "'setup.py'", ":", "assert", "len", "(", "package", ")", ">=", "2", "self", ".", "call_setup", "(", "os", ".", "path", ".", "join", "(", "self", ".", "topsrcdir", ",", "package", "[", "1", "]", ")", ",", "package", "[", "2", ":", "]", ")", "return", "True", "if", "package", "[", "0", "]", "==", "'copy'", ":", "assert", "len", "(", "package", ")", "==", "2", "src", "=", "os", ".", "path", ".", "join", "(", "self", ".", "topsrcdir", ",", "package", "[", "1", "]", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "python_lib", ",", "os", ".", "path", ".", "basename", "(", "package", "[", "1", "]", ")", ")", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "return", "True", "if", "package", "[", "0", "]", "==", "'packages.txt'", ":", "assert", "len", "(", "package", ")", "==", "2", "src", "=", "os", ".", "path", ".", "join", "(", "self", ".", "topsrcdir", ",", "package", "[", "1", "]", ")", "assert", "os", ".", "path", ".", "isfile", "(", "src", ")", ",", "\"'%s' does not exist\"", "%", "src", "submanager", "=", "VirtualenvManager", "(", "self", ".", "topsrcdir", ",", "self", ".", "topobjdir", ",", "self", ".", "virtualenv_root", ",", "self", ".", "log_handle", ",", "src", ")", "submanager", ".", "populate", "(", ")", "return", "True", "if", "package", "[", "0", "]", ".", "endswith", "(", "'.pth'", ")", ":", "assert", "len", "(", "package", ")", "==", "2", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "topsrcdir", ",", "package", "[", "1", "]", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "python_lib", ",", "package", "[", "0", "]", ")", ",", "'a'", ")", "as", "f", ":", "# This path is relative to the .pth file. Using a", "# relative path allows the srcdir/objdir combination", "# to be moved around (as long as the paths relative to", "# each other remain the same).", "try", ":", "f", ".", "write", "(", "\"%s\\n\"", "%", "os", ".", "path", ".", "relpath", "(", "path", ",", "python_lib", ")", ")", "except", "ValueError", ":", "# When objdir is on a separate drive, relpath throws", "f", ".", "write", "(", "\"%s\\n\"", "%", "os", ".", "path", ".", "join", "(", "python_lib", ",", "path", ")", ")", "return", "True", "if", "package", "[", "0", "]", "==", "'optional'", ":", "try", ":", "handle_package", "(", "package", "[", "1", ":", "]", ")", "return", "True", "except", ":", "print", "(", "'Error processing command. Ignoring'", ",", "'because optional. (%s)'", "%", "':'", ".", "join", "(", "package", ")", ",", "file", "=", "self", ".", "log_handle", ")", "return", "False", "if", "package", "[", "0", "]", "==", "'objdir'", ":", "assert", "len", "(", "package", ")", "==", "2", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "topobjdir", ",", "package", "[", "1", "]", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "python_lib", ",", "'objdir.pth'", ")", ",", "'a'", ")", "as", "f", ":", "f", ".", "write", "(", "'%s\\n'", "%", "path", ")", "return", "True", "raise", "Exception", "(", "'Unknown action: %s'", "%", "package", "[", "0", "]", ")", "# We always target the OS X deployment target that Python itself was", "# built with, regardless of what's in the current environment. If we", "# don't do # this, we may run into a Python bug. See", "# http://bugs.python.org/issue9516 and bug 659881.", "#", "# Note that this assumes that nothing compiled in the virtualenv is", "# shipped as part of a distribution. If we do ship anything, the", "# deployment target here may be different from what's targeted by the", "# shipping binaries and # virtualenv-produced binaries may fail to", "# work.", "#", "# We also ignore environment variables that may have been altered by", "# configure or a mozconfig activated in the current shell. We trust", "# Python is smart enough to find a proper compiler and to use the", "# proper compiler flags. If it isn't your Python is likely broken.", "IGNORE_ENV_VARIABLES", "=", "(", "'CC'", ",", "'CXX'", ",", "'CFLAGS'", ",", "'CXXFLAGS'", ",", "'LDFLAGS'", ",", "'PYTHONDONTWRITEBYTECODE'", ")", "try", ":", "old_target", "=", "os", ".", "environ", ".", "get", "(", "'MACOSX_DEPLOYMENT_TARGET'", ",", "None", ")", "sysconfig_target", "=", "distutils", ".", "sysconfig", ".", "get_config_var", "(", "'MACOSX_DEPLOYMENT_TARGET'", ")", "if", "sysconfig_target", "is", "not", "None", ":", "os", ".", "environ", "[", "'MACOSX_DEPLOYMENT_TARGET'", "]", "=", "sysconfig_target", "old_env_variables", "=", "{", "}", "for", "k", "in", "IGNORE_ENV_VARIABLES", ":", "if", "k", "not", "in", "os", ".", "environ", ":", "continue", "old_env_variables", "[", "k", "]", "=", "os", ".", "environ", "[", "k", "]", "del", "os", ".", "environ", "[", "k", "]", "# HACK ALERT.", "#", "# The following adjustment to the VSNNCOMNTOOLS environment", "# variables are wrong. This is done as a hack to facilitate the", "# building of binary Python packages - notably psutil - on Windows", "# machines that don't have the Visual Studio 2008 binaries", "# installed. This hack assumes the Python on that system was built", "# with Visual Studio 2008. The hack is wrong for the reasons", "# explained at", "# http://stackoverflow.com/questions/3047542/building-lxml-for-python-2-7-on-windows/5122521#5122521.", "if", "sys", ".", "platform", "in", "(", "'win32'", ",", "'cygwin'", ")", "and", "'VS90COMNTOOLS'", "not", "in", "os", ".", "environ", ":", "warnings", ".", "warn", "(", "'Hacking environment to allow binary Python '", "'extensions to build. You can make this warning go away '", "'by installing Visual Studio 2008. You can download the '", "'Express Edition installer from '", "'http://go.microsoft.com/?linkid=7729279'", ")", "# We list in order from oldest to newest to prefer the closest", "# to 2008 so differences are minimized.", "for", "ver", "in", "(", "'100'", ",", "'110'", ",", "'120'", ")", ":", "var", "=", "'VS%sCOMNTOOLS'", "%", "ver", "if", "var", "in", "os", ".", "environ", ":", "os", ".", "environ", "[", "'VS90COMNTOOLS'", "]", "=", "os", ".", "environ", "[", "var", "]", "break", "for", "package", "in", "packages", ":", "handle_package", "(", "package", ")", "finally", ":", "os", ".", "environ", ".", "pop", "(", "'MACOSX_DEPLOYMENT_TARGET'", ",", "None", ")", "if", "old_target", "is", "not", "None", ":", "os", ".", "environ", "[", "'MACOSX_DEPLOYMENT_TARGET'", "]", "=", "old_target", "os", ".", "environ", ".", "update", "(", "old_env_variables", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/virtualenv.py#L157-L340
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/debug.py
python
ProcessedTraceback.exc_info
(self)
return self.exc_type, self.exc_value, self.frames[0]
Exception info tuple with a proxy around the frame objects.
Exception info tuple with a proxy around the frame objects.
[ "Exception", "info", "tuple", "with", "a", "proxy", "around", "the", "frame", "objects", "." ]
def exc_info(self): """Exception info tuple with a proxy around the frame objects.""" return self.exc_type, self.exc_value, self.frames[0]
[ "def", "exc_info", "(", "self", ")", ":", "return", "self", ".", "exc_type", ",", "self", ".", "exc_value", ",", "self", ".", "frames", "[", "0", "]" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/debug.py#L117-L119
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/graph_to_function_def.py
python
_add_op_node
(op, func, input_dict)
Converts an op to a function def node and add it to `func`.
Converts an op to a function def node and add it to `func`.
[ "Converts", "an", "op", "to", "a", "function", "def", "node", "and", "add", "it", "to", "func", "." ]
def _add_op_node(op, func, input_dict): """Converts an op to a function def node and add it to `func`.""" # Add an entry in func.node_def # Note that extend() makes a copy in this case, see: # https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields func.node_def.extend([_get_node_def(op)]) node_def = func.node_def[-1] for i in range(len(node_def.input)): if not node_def.input[i].startswith("^"): assert node_def.input[i] in input_dict, ("%s missing from %s" % (node_def.input[i], input_dict.items())) node_def.input[i] = input_dict[node_def.input[i]] # The function is stateful if any of its operations are stateful. # NOTE(mrry): The "Const" node typically does not have an `OpDef` associated # with it, so we assume any nodes without an `OpDef` are stateless. # TODO(skyewm): Remove the `is not None` test after we transition to the C # API. if op.op_def is not None and op.op_def.is_stateful: func.signature.is_stateful = True
[ "def", "_add_op_node", "(", "op", ",", "func", ",", "input_dict", ")", ":", "# Add an entry in func.node_def", "# Note that extend() makes a copy in this case, see:", "# https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields", "func", ".", "node_def", ".", "extend", "(", "[", "_get_node_def", "(", "op", ")", "]", ")", "node_def", "=", "func", ".", "node_def", "[", "-", "1", "]", "for", "i", "in", "range", "(", "len", "(", "node_def", ".", "input", ")", ")", ":", "if", "not", "node_def", ".", "input", "[", "i", "]", ".", "startswith", "(", "\"^\"", ")", ":", "assert", "node_def", ".", "input", "[", "i", "]", "in", "input_dict", ",", "(", "\"%s missing from %s\"", "%", "(", "node_def", ".", "input", "[", "i", "]", ",", "input_dict", ".", "items", "(", ")", ")", ")", "node_def", ".", "input", "[", "i", "]", "=", "input_dict", "[", "node_def", ".", "input", "[", "i", "]", "]", "# The function is stateful if any of its operations are stateful.", "# NOTE(mrry): The \"Const\" node typically does not have an `OpDef` associated", "# with it, so we assume any nodes without an `OpDef` are stateless.", "# TODO(skyewm): Remove the `is not None` test after we transition to the C", "# API.", "if", "op", ".", "op_def", "is", "not", "None", "and", "op", ".", "op_def", ".", "is_stateful", ":", "func", ".", "signature", ".", "is_stateful", "=", "True" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/graph_to_function_def.py#L99-L119
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/publish/publish_servlet.py
python
PublishServlet.__init__
(self)
Inits publish servlet.
Inits publish servlet.
[ "Inits", "publish", "servlet", "." ]
def __init__(self): """Inits publish servlet.""" try: self._publish_manager = publish_manager.PublishManager() except exceptions.PublishServeException as e: self._publish_manager = None logger.error(e, exc_info=True) except psycopg2.Warning as w: self._publish_manager = None logger.error(w, exc_info=True) except psycopg2.Error as e: self._publish_manager = None logger.error(e, exc_info=True) except Exception as e: self._publish_manager = None logger.error(e, exc_info=True)
[ "def", "__init__", "(", "self", ")", ":", "try", ":", "self", ".", "_publish_manager", "=", "publish_manager", ".", "PublishManager", "(", ")", "except", "exceptions", ".", "PublishServeException", "as", "e", ":", "self", ".", "_publish_manager", "=", "None", "logger", ".", "error", "(", "e", ",", "exc_info", "=", "True", ")", "except", "psycopg2", ".", "Warning", "as", "w", ":", "self", ".", "_publish_manager", "=", "None", "logger", ".", "error", "(", "w", ",", "exc_info", "=", "True", ")", "except", "psycopg2", ".", "Error", "as", "e", ":", "self", ".", "_publish_manager", "=", "None", "logger", ".", "error", "(", "e", ",", "exc_info", "=", "True", ")", "except", "Exception", "as", "e", ":", "self", ".", "_publish_manager", "=", "None", "logger", ".", "error", "(", "e", ",", "exc_info", "=", "True", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/publish_servlet.py#L39-L57
runtimejs/runtime
0a6e84c30823d35a4548d6634166784260ae7b74
deps/v8/tools/ninja/ninja_output.py
python
GetNinjaOutputDirectory
(v8_root, configuration=None)
return debug_path
Returns <v8_root>/<output_dir>/(Release|Debug). The configuration chosen is the one most recently generated/built, but can be overriden via the <configuration> parameter. Detects a custom output_dir specified by GYP_GENERATOR_FLAGS.
Returns <v8_root>/<output_dir>/(Release|Debug).
[ "Returns", "<v8_root", ">", "/", "<output_dir", ">", "/", "(", "Release|Debug", ")", "." ]
def GetNinjaOutputDirectory(v8_root, configuration=None): """Returns <v8_root>/<output_dir>/(Release|Debug). The configuration chosen is the one most recently generated/built, but can be overriden via the <configuration> parameter. Detects a custom output_dir specified by GYP_GENERATOR_FLAGS.""" output_dir = 'out' generator_flags = os.getenv('GYP_GENERATOR_FLAGS', '').split(' ') for flag in generator_flags: name_value = flag.split('=', 1) if len(name_value) == 2 and name_value[0] == 'output_dir': output_dir = name_value[1] root = os.path.join(v8_root, output_dir) if configuration: return os.path.join(root, configuration) debug_path = os.path.join(root, 'Debug') release_path = os.path.join(root, 'Release') def is_release_newer(test_path): try: debug_mtime = os.path.getmtime(os.path.join(debug_path, test_path)) except os.error: debug_mtime = 0 try: rel_mtime = os.path.getmtime(os.path.join(release_path, test_path)) except os.error: rel_mtime = 0 return rel_mtime >= debug_mtime if is_release_newer('.ninja_log') or is_release_newer('.ninja_deps'): return release_path return debug_path
[ "def", "GetNinjaOutputDirectory", "(", "v8_root", ",", "configuration", "=", "None", ")", ":", "output_dir", "=", "'out'", "generator_flags", "=", "os", ".", "getenv", "(", "'GYP_GENERATOR_FLAGS'", ",", "''", ")", ".", "split", "(", "' '", ")", "for", "flag", "in", "generator_flags", ":", "name_value", "=", "flag", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "name_value", ")", "==", "2", "and", "name_value", "[", "0", "]", "==", "'output_dir'", ":", "output_dir", "=", "name_value", "[", "1", "]", "root", "=", "os", ".", "path", ".", "join", "(", "v8_root", ",", "output_dir", ")", "if", "configuration", ":", "return", "os", ".", "path", ".", "join", "(", "root", ",", "configuration", ")", "debug_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'Debug'", ")", "release_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'Release'", ")", "def", "is_release_newer", "(", "test_path", ")", ":", "try", ":", "debug_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "os", ".", "path", ".", "join", "(", "debug_path", ",", "test_path", ")", ")", "except", "os", ".", "error", ":", "debug_mtime", "=", "0", "try", ":", "rel_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "os", ".", "path", ".", "join", "(", "release_path", ",", "test_path", ")", ")", "except", "os", ".", "error", ":", "rel_mtime", "=", "0", "return", "rel_mtime", ">=", "debug_mtime", "if", "is_release_newer", "(", "'.ninja_log'", ")", "or", "is_release_newer", "(", "'.ninja_deps'", ")", ":", "return", "release_path", "return", "debug_path" ]
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/tools/ninja/ninja_output.py#L10-L44
neo-ai/neo-ai-dlr
bf397aa0367a5207654c00d2985f900d94ad1543
python/dlr/counter/system.py
python
Factory.get_system
(sys_typ)
Return instance of System as per operating system type
Return instance of System as per operating system type
[ "Return", "instance", "of", "System", "as", "per", "operating", "system", "type" ]
def get_system(sys_typ): """Return instance of System as per operating system type""" try: os_name = platform.system() map_sys_typ = [ item for item in SUPPORTED_SYSTEM_LIST if item.lower() in os_name.lower() ] system_class = Linux() if map_sys_typ else None return system_class except Exception: logging.exception("unable to create system class instance", exc_info=False)
[ "def", "get_system", "(", "sys_typ", ")", ":", "try", ":", "os_name", "=", "platform", ".", "system", "(", ")", "map_sys_typ", "=", "[", "item", "for", "item", "in", "SUPPORTED_SYSTEM_LIST", "if", "item", ".", "lower", "(", ")", "in", "os_name", ".", "lower", "(", ")", "]", "system_class", "=", "Linux", "(", ")", "if", "map_sys_typ", "else", "None", "return", "system_class", "except", "Exception", ":", "logging", ".", "exception", "(", "\"unable to create system class instance\"", ",", "exc_info", "=", "False", ")" ]
https://github.com/neo-ai/neo-ai-dlr/blob/bf397aa0367a5207654c00d2985f900d94ad1543/python/dlr/counter/system.py#L58-L71
ucbrise/clipper
9f25e3fc7f8edc891615e81c5b80d3d8aed72608
clipper_admin/clipper_admin/container_manager.py
python
ContainerManager.stop_models
(self, models)
return
Stops all replicas of the specified models. Parameters ---------- models : dict(str, list(str)) For each entry in the dict, the key is a model name and the value is a list of model versions. All replicas for each version of each model will be stopped.
Stops all replicas of the specified models.
[ "Stops", "all", "replicas", "of", "the", "specified", "models", "." ]
def stop_models(self, models): """Stops all replicas of the specified models. Parameters ---------- models : dict(str, list(str)) For each entry in the dict, the key is a model name and the value is a list of model versions. All replicas for each version of each model will be stopped. """ return
[ "def", "stop_models", "(", "self", ",", "models", ")", ":", "return" ]
https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/container_manager.py#L120-L129
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/DraftGui.py
python
DraftToolBar.selectEdge
(self)
allows the dimension command to select an edge
allows the dimension command to select an edge
[ "allows", "the", "dimension", "command", "to", "select", "an", "edge" ]
def selectEdge(self): """allows the dimension command to select an edge""" if hasattr(self.sourceCmd,"selectEdge"): self.sourceCmd.selectEdge()
[ "def", "selectEdge", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "sourceCmd", ",", "\"selectEdge\"", ")", ":", "self", ".", "sourceCmd", ".", "selectEdge", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/DraftGui.py#L1601-L1604
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/optimal_learning/python/python_version/gaussian_process.py
python
GaussianProcess.compute_grad_mean_of_points
(self, points_to_sample, num_derivatives=-1)
return grad_mu_star
r"""Compute the gradient of the mean of this GP at each of point of ``Xs`` (``points_to_sample``) wrt ``Xs``. .. Warning:: ``points_to_sample`` should not contain duplicate points. Observe that ``grad_mu`` is nominally sized: ``grad_mu[num_to_sample][num_to_sample][dim]``. This is the the d-th component of the derivative evaluated at the i-th input wrt the j-th input. However, for ``0 <= i,j < num_to_sample``, ``i != j``, ``grad_mu[j][i][d] = 0``. (See references or implementation for further details.) Thus, ``grad_mu`` is stored in a reduced form which only tracks the nonzero entries. .. Note:: Comments are copied from :mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_mean_of_points` :param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped :type num_derivatives: int :return: grad_mu: gradient of the mean of the GP. ``grad_mu[i][d]`` is actually the gradient of ``\mu_i`` wrt ``x_{i,d}``, the d-th dim of the i-th entry of ``points_to_sample``. :rtype: array of float64 with shape (num_derivatives, dim)
r"""Compute the gradient of the mean of this GP at each of point of ``Xs`` (``points_to_sample``) wrt ``Xs``.
[ "r", "Compute", "the", "gradient", "of", "the", "mean", "of", "this", "GP", "at", "each", "of", "point", "of", "Xs", "(", "points_to_sample", ")", "wrt", "Xs", "." ]
def compute_grad_mean_of_points(self, points_to_sample, num_derivatives=-1): r"""Compute the gradient of the mean of this GP at each of point of ``Xs`` (``points_to_sample``) wrt ``Xs``. .. Warning:: ``points_to_sample`` should not contain duplicate points. Observe that ``grad_mu`` is nominally sized: ``grad_mu[num_to_sample][num_to_sample][dim]``. This is the the d-th component of the derivative evaluated at the i-th input wrt the j-th input. However, for ``0 <= i,j < num_to_sample``, ``i != j``, ``grad_mu[j][i][d] = 0``. (See references or implementation for further details.) Thus, ``grad_mu`` is stored in a reduced form which only tracks the nonzero entries. .. Note:: Comments are copied from :mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_mean_of_points` :param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped :type num_derivatives: int :return: grad_mu: gradient of the mean of the GP. ``grad_mu[i][d]`` is actually the gradient of ``\mu_i`` wrt ``x_{i,d}``, the d-th dim of the i-th entry of ``points_to_sample``. :rtype: array of float64 with shape (num_derivatives, dim) """ num_derivatives = self._clamp_num_derivatives(points_to_sample.shape[0], num_derivatives) grad_K_star = numpy.empty((num_derivatives, self._points_sampled.shape[0], self.dim)) for i, point_one in enumerate(points_to_sample[:num_derivatives, ...]): for j, point_two in enumerate(self._points_sampled): grad_K_star[i, j, ...] = self._covariance.grad_covariance(point_one, point_two) # y_{k,i} = A_{k,j,i} * x_j grad_mu_star = numpy.einsum('ijk, j', grad_K_star, self._K_inv_y) return grad_mu_star
[ "def", "compute_grad_mean_of_points", "(", "self", ",", "points_to_sample", ",", "num_derivatives", "=", "-", "1", ")", ":", "num_derivatives", "=", "self", ".", "_clamp_num_derivatives", "(", "points_to_sample", ".", "shape", "[", "0", "]", ",", "num_derivatives", ")", "grad_K_star", "=", "numpy", ".", "empty", "(", "(", "num_derivatives", ",", "self", ".", "_points_sampled", ".", "shape", "[", "0", "]", ",", "self", ".", "dim", ")", ")", "for", "i", ",", "point_one", "in", "enumerate", "(", "points_to_sample", "[", ":", "num_derivatives", ",", "...", "]", ")", ":", "for", "j", ",", "point_two", "in", "enumerate", "(", "self", ".", "_points_sampled", ")", ":", "grad_K_star", "[", "i", ",", "j", ",", "...", "]", "=", "self", ".", "_covariance", ".", "grad_covariance", "(", "point_one", ",", "point_two", ")", "# y_{k,i} = A_{k,j,i} * x_j", "grad_mu_star", "=", "numpy", ".", "einsum", "(", "'ijk, j'", ",", "grad_K_star", ",", "self", ".", "_K_inv_y", ")", "return", "grad_mu_star" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/python_version/gaussian_process.py#L163-L194
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py
python
Environment.scan
(self, search_path=None)
Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.
Scan `search_path` for distributions usable in this environment
[ "Scan", "search_path", "for", "distributions", "usable", "in", "this", "environment" ]
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
[ "def", "scan", "(", "self", ",", "search_path", "=", "None", ")", ":", "if", "search_path", "is", "None", ":", "search_path", "=", "sys", ".", "path", "for", "item", "in", "search_path", ":", "for", "dist", "in", "find_distributions", "(", "item", ")", ":", "self", ".", "add", "(", "dist", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py#L1005-L1018
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
tools/clang/bindings/python/clang/cindex.py
python
Type.get_array_size
(self)
return conf.lib.clang_getArraySize(self)
Retrieve the size of the constant array.
Retrieve the size of the constant array.
[ "Retrieve", "the", "size", "of", "the", "constant", "array", "." ]
def get_array_size(self): """ Retrieve the size of the constant array. """ return conf.lib.clang_getArraySize(self)
[ "def", "get_array_size", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getArraySize", "(", "self", ")" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1941-L1945
facebook/redex
fac189a289bca2647061f9e364016afc1096500d
tools/python/dex.py
python
DexMethod.get_method_index
(self)
return self.encoded_method.method_idx
Get the method index into the method_ids array in the DEX file.
Get the method index into the method_ids array in the DEX file.
[ "Get", "the", "method", "index", "into", "the", "method_ids", "array", "in", "the", "DEX", "file", "." ]
def get_method_index(self): """Get the method index into the method_ids array in the DEX file.""" return self.encoded_method.method_idx
[ "def", "get_method_index", "(", "self", ")", ":", "return", "self", ".", "encoded_method", ".", "method_idx" ]
https://github.com/facebook/redex/blob/fac189a289bca2647061f9e364016afc1096500d/tools/python/dex.py#L1238-L1240
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/windows/windows.py
python
general_cosine
(M, a, sym=True)
return _truncate(w, needs_trunc)
r""" Generic weighted sum of cosine terms window Parameters ---------- M : int Number of points in the output window a : array_like Sequence of weighting coefficients. This uses the convention of being centered on the origin, so these will typically all be positive numbers, not alternating sign. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. References ---------- .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows", February 15, 2002 https://holometer.fnal.gov/GH_FFT.pdf Examples -------- Heinzel describes a flat-top window named "HFT90D" with formula: [2]_ .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z) - 0.440811 \cos(3z) + 0.043097 \cos(4z) where .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1 Since this uses the convention of starting at the origin, to reproduce the window, we need to convert every other coefficient to a positive number: >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097] The paper states that the highest sidelobe is at -90.2 dB. Reproduce Figure 42 by plotting the window and its frequency response, and confirm the sidelobe level in red: >>> from scipy.signal.windows import general_cosine >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = general_cosine(1000, HFT90D, sym=False) >>> plt.plot(window) >>> plt.title("HFT90D window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 10000) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-50/1000, 50/1000, -140, 0]) >>> plt.title("Frequency response of the HFT90D window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axhline(-90.2, color='red') >>> plt.show()
r""" Generic weighted sum of cosine terms window
[ "r", "Generic", "weighted", "sum", "of", "cosine", "terms", "window" ]
def general_cosine(M, a, sym=True): r""" Generic weighted sum of cosine terms window Parameters ---------- M : int Number of points in the output window a : array_like Sequence of weighting coefficients. This uses the convention of being centered on the origin, so these will typically all be positive numbers, not alternating sign. sym : bool, optional When True (default), generates a symmetric window, for use in filter design. When False, generates a periodic window, for use in spectral analysis. References ---------- .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`. .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows", February 15, 2002 https://holometer.fnal.gov/GH_FFT.pdf Examples -------- Heinzel describes a flat-top window named "HFT90D" with formula: [2]_ .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z) - 0.440811 \cos(3z) + 0.043097 \cos(4z) where .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1 Since this uses the convention of starting at the origin, to reproduce the window, we need to convert every other coefficient to a positive number: >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097] The paper states that the highest sidelobe is at -90.2 dB. Reproduce Figure 42 by plotting the window and its frequency response, and confirm the sidelobe level in red: >>> from scipy.signal.windows import general_cosine >>> from scipy.fftpack import fft, fftshift >>> import matplotlib.pyplot as plt >>> window = general_cosine(1000, HFT90D, sym=False) >>> plt.plot(window) >>> plt.title("HFT90D window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.figure() >>> A = fft(window, 10000) / (len(window)/2.0) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) >>> plt.plot(freq, response) >>> plt.axis([-50/1000, 50/1000, -140, 0]) >>> plt.title("Frequency response of the HFT90D window") >>> plt.ylabel("Normalized magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axhline(-90.2, color='red') >>> plt.show() """ if _len_guards(M): return np.ones(M) M, needs_trunc = _extend(M, sym) fac = np.linspace(-np.pi, np.pi, M) w = np.zeros(M) for k in range(len(a)): w += a[k] * np.cos(k * fac) return _truncate(w, needs_trunc)
[ "def", "general_cosine", "(", "M", ",", "a", ",", "sym", "=", "True", ")", ":", "if", "_len_guards", "(", "M", ")", ":", "return", "np", ".", "ones", "(", "M", ")", "M", ",", "needs_trunc", "=", "_extend", "(", "M", ",", "sym", ")", "fac", "=", "np", ".", "linspace", "(", "-", "np", ".", "pi", ",", "np", ".", "pi", ",", "M", ")", "w", "=", "np", ".", "zeros", "(", "M", ")", "for", "k", "in", "range", "(", "len", "(", "a", ")", ")", ":", "w", "+=", "a", "[", "k", "]", "*", "np", ".", "cos", "(", "k", "*", "fac", ")", "return", "_truncate", "(", "w", ",", "needs_trunc", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/windows/windows.py#L42-L120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/credentials.py
python
CanonicalNameCredentialSourcer.is_supported
(self, source_name)
return source_name in [p.CANONICAL_NAME for p in self._providers]
Validates a given source name. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: bool :returns: True if the credential provider is supported, False otherwise.
Validates a given source name.
[ "Validates", "a", "given", "source", "name", "." ]
def is_supported(self, source_name): """Validates a given source name. :type source_name: str :param source_name: The value of credential_source in the config file. This is the canonical name of the credential provider. :rtype: bool :returns: True if the credential provider is supported, False otherwise. """ return source_name in [p.CANONICAL_NAME for p in self._providers]
[ "def", "is_supported", "(", "self", ",", "source_name", ")", ":", "return", "source_name", "in", "[", "p", ".", "CANONICAL_NAME", "for", "p", "in", "self", ".", "_providers", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/credentials.py#L1708-L1719
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/ma/core.py
python
_DomainGreaterEqual.__call__
(self, x)
return umath.less(x, self.critical_value)
Executes the call behavior.
Executes the call behavior.
[ "Executes", "the", "call", "behavior", "." ]
def __call__ (self, x): "Executes the call behavior." return umath.less(x, self.critical_value)
[ "def", "__call__", "(", "self", ",", "x", ")", ":", "return", "umath", ".", "less", "(", "x", ",", "self", ".", "critical_value", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L794-L796
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
docs/tutorials/Repurposing-a-pretrained-image-classifier/retarget_validation.py
python
main
(args)
Entry point for the script when called directly
Entry point for the script when called directly
[ "Entry", "point", "for", "the", "script", "when", "called", "directly" ]
def main(args): """Entry point for the script when called directly""" categories_filename = 'categories.txt' validation_filename = 'validation.gsdf' confusion_matrix_filename = 'confusion_matrix.txt' # Read the category names with open(categories_filename, "r") as categories_file: categories = categories_file.read().splitlines() # Get the model's input shape. We will use this information later to resize # images appropriately. input_shape = model.get_default_input_shape() # Get the model's output shape and create an array to hold the model's # output predictions output_shape = model.get_default_output_shape() # Declare a variable to hold the prediction times prediction_times = [] mean_time_to_predict = 0.0 print("Loading dataset") dataset = ell.data.AutoSupervisedDataset() dataset.Load(validation_filename) num = dataset.NumExamples() print("Number of Examples:", num) features = dataset.NumFeatures() print("Number of Features:", features) num_classes = len(categories) confusion_matrix = np.zeros((num_classes,num_classes), dtype=np.int32) num_correct = 0 for i in range(num): example = dataset.GetExample(i) av = example.GetData() x = np.asarray(av.ToArray()).astype(np.float_, copy=False) start = time.time() predictions = model.predict(x) end = time.time() mean_time_to_predict = helpers.get_mean_duration( prediction_times, end - start) predicted = np.argmax(predictions) expected = int(example.GetLabel()) predicted_label = categories[predicted] expected_label = categories[expected] print("Predict {}, expected {}".format(predicted_label, expected_label)) confusion_matrix[predicted, expected] += 1 if predicted == expected: num_correct += 1 print("Mean prediction time: {:.0f}ms/frame".format( mean_time_to_predict * 1000)) print("Accuracy: {}/{} = {:.1%}%".format(num_correct, num, num_correct / num)) save_confusion_matrix(categories, confusion_matrix_filename, confusion_matrix, num_correct, num, mean_time_to_predict)
[ "def", "main", "(", "args", ")", ":", "categories_filename", "=", "'categories.txt'", "validation_filename", "=", "'validation.gsdf'", "confusion_matrix_filename", "=", "'confusion_matrix.txt'", "# Read the category names", "with", "open", "(", "categories_filename", ",", "\"r\"", ")", "as", "categories_file", ":", "categories", "=", "categories_file", ".", "read", "(", ")", ".", "splitlines", "(", ")", "# Get the model's input shape. We will use this information later to resize", "# images appropriately.", "input_shape", "=", "model", ".", "get_default_input_shape", "(", ")", "# Get the model's output shape and create an array to hold the model's", "# output predictions", "output_shape", "=", "model", ".", "get_default_output_shape", "(", ")", "# Declare a variable to hold the prediction times", "prediction_times", "=", "[", "]", "mean_time_to_predict", "=", "0.0", "print", "(", "\"Loading dataset\"", ")", "dataset", "=", "ell", ".", "data", ".", "AutoSupervisedDataset", "(", ")", "dataset", ".", "Load", "(", "validation_filename", ")", "num", "=", "dataset", ".", "NumExamples", "(", ")", "print", "(", "\"Number of Examples:\"", ",", "num", ")", "features", "=", "dataset", ".", "NumFeatures", "(", ")", "print", "(", "\"Number of Features:\"", ",", "features", ")", "num_classes", "=", "len", "(", "categories", ")", "confusion_matrix", "=", "np", ".", "zeros", "(", "(", "num_classes", ",", "num_classes", ")", ",", "dtype", "=", "np", ".", "int32", ")", "num_correct", "=", "0", "for", "i", "in", "range", "(", "num", ")", ":", "example", "=", "dataset", ".", "GetExample", "(", "i", ")", "av", "=", "example", ".", "GetData", "(", ")", "x", "=", "np", ".", "asarray", "(", "av", ".", "ToArray", "(", ")", ")", ".", "astype", "(", "np", ".", "float_", ",", "copy", "=", "False", ")", "start", "=", "time", ".", "time", "(", ")", "predictions", "=", "model", ".", "predict", "(", "x", ")", "end", "=", "time", ".", "time", "(", ")", "mean_time_to_predict", "=", "helpers", ".", "get_mean_duration", "(", "prediction_times", ",", "end", "-", "start", ")", "predicted", "=", "np", ".", "argmax", "(", "predictions", ")", "expected", "=", "int", "(", "example", ".", "GetLabel", "(", ")", ")", "predicted_label", "=", "categories", "[", "predicted", "]", "expected_label", "=", "categories", "[", "expected", "]", "print", "(", "\"Predict {}, expected {}\"", ".", "format", "(", "predicted_label", ",", "expected_label", ")", ")", "confusion_matrix", "[", "predicted", ",", "expected", "]", "+=", "1", "if", "predicted", "==", "expected", ":", "num_correct", "+=", "1", "print", "(", "\"Mean prediction time: {:.0f}ms/frame\"", ".", "format", "(", "mean_time_to_predict", "*", "1000", ")", ")", "print", "(", "\"Accuracy: {}/{} = {:.1%}%\"", ".", "format", "(", "num_correct", ",", "num", ",", "num_correct", "/", "num", ")", ")", "save_confusion_matrix", "(", "categories", ",", "confusion_matrix_filename", ",", "confusion_matrix", ",", "num_correct", ",", "num", ",", "mean_time_to_predict", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/docs/tutorials/Repurposing-a-pretrained-image-classifier/retarget_validation.py#L53-L113
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/nero_mod.py
python
list_bases
()
return bases
list all available bases (directories starting with an underscore)
list all available bases (directories starting with an underscore)
[ "list", "all", "available", "bases", "(", "directories", "starting", "with", "an", "underscore", ")" ]
def list_bases(): " list all available bases (directories starting with an underscore) " bases = [] files = os.listdir(MOD_PATH) bases = [f for f in files if mod_is_base(f)] return bases
[ "def", "list_bases", "(", ")", ":", "bases", "=", "[", "]", "files", "=", "os", ".", "listdir", "(", "MOD_PATH", ")", "bases", "=", "[", "f", "for", "f", "in", "files", "if", "mod_is_base", "(", "f", ")", "]", "return", "bases" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/nero_mod.py#L143-L148
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AzCodeGenerator/bin/windows/az_code_gen/clang_cpp.py
python
format_enums
(json_object)
Collects all enums and enum annotations found in json_object['objects'] and coalesces/moves them into json_object['enums'] @param json_object The raw JSON output from clang's AST dump
Collects all enums and enum annotations found in json_object['objects'] and coalesces/moves them into json_object['enums']
[ "Collects", "all", "enums", "and", "enum", "annotations", "found", "in", "json_object", "[", "objects", "]", "and", "coalesces", "/", "moves", "them", "into", "json_object", "[", "enums", "]" ]
def format_enums(json_object): """ Collects all enums and enum annotations found in json_object['objects'] and coalesces/moves them into json_object['enums'] @param json_object The raw JSON output from clang's AST dump """ enums = {} annotations = {} decls_to_remove = set() for object in json_object.get('objects', []): # objects with type 'enum SomeEnum' are enum annotations cpp_type = object['type'] if 'canonical_type' in object: cpp_type = object['canonical_type'] if cpp_type.startswith('enum '): enum = cpp_type.replace('enum ', '') annotations[enum] = object['annotations'] decls_to_remove.add(object['qualified_name']) # objects with type enum are the enums themselves elif cpp_type == 'enum': enum = object['qualified_name'] enums[enum] = object decls_to_remove.add(object['qualified_name']) # move enums into the top level enums entry and coalesce annotations into them json_object['enums'] = [] for name, enum in enums.items(): if name in annotations: # only include enums with annotations enum_annotations = annotations[name] enum.setdefault('annotations', {}).update(enum_annotations) json_object['enums'].append(enum) # Strip out top level decls that have been coalesced if len(decls_to_remove) > 0: json_object['objects'] = [obj for obj in json_object['objects'] if obj['qualified_name'] not in decls_to_remove]
[ "def", "format_enums", "(", "json_object", ")", ":", "enums", "=", "{", "}", "annotations", "=", "{", "}", "decls_to_remove", "=", "set", "(", ")", "for", "object", "in", "json_object", ".", "get", "(", "'objects'", ",", "[", "]", ")", ":", "# objects with type 'enum SomeEnum' are enum annotations", "cpp_type", "=", "object", "[", "'type'", "]", "if", "'canonical_type'", "in", "object", ":", "cpp_type", "=", "object", "[", "'canonical_type'", "]", "if", "cpp_type", ".", "startswith", "(", "'enum '", ")", ":", "enum", "=", "cpp_type", ".", "replace", "(", "'enum '", ",", "''", ")", "annotations", "[", "enum", "]", "=", "object", "[", "'annotations'", "]", "decls_to_remove", ".", "add", "(", "object", "[", "'qualified_name'", "]", ")", "# objects with type enum are the enums themselves", "elif", "cpp_type", "==", "'enum'", ":", "enum", "=", "object", "[", "'qualified_name'", "]", "enums", "[", "enum", "]", "=", "object", "decls_to_remove", ".", "add", "(", "object", "[", "'qualified_name'", "]", ")", "# move enums into the top level enums entry and coalesce annotations into them", "json_object", "[", "'enums'", "]", "=", "[", "]", "for", "name", ",", "enum", "in", "enums", ".", "items", "(", ")", ":", "if", "name", "in", "annotations", ":", "# only include enums with annotations", "enum_annotations", "=", "annotations", "[", "name", "]", "enum", ".", "setdefault", "(", "'annotations'", ",", "{", "}", ")", ".", "update", "(", "enum_annotations", ")", "json_object", "[", "'enums'", "]", ".", "append", "(", "enum", ")", "# Strip out top level decls that have been coalesced", "if", "len", "(", "decls_to_remove", ")", ">", "0", ":", "json_object", "[", "'objects'", "]", "=", "[", "obj", "for", "obj", "in", "json_object", "[", "'objects'", "]", "if", "obj", "[", "'qualified_name'", "]", "not", "in", "decls_to_remove", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AzCodeGenerator/bin/windows/az_code_gen/clang_cpp.py#L114-L147
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Utils.py
python
h_fun
(fun)
Hash functions :param fun: function to hash :type fun: function :return: hash of the function
Hash functions
[ "Hash", "functions" ]
def h_fun(fun): """ Hash functions :param fun: function to hash :type fun: function :return: hash of the function """ try: return fun.code except AttributeError: try: h = inspect.getsource(fun) except IOError: h = "nocode" try: fun.code = h except AttributeError: pass return h
[ "def", "h_fun", "(", "fun", ")", ":", "try", ":", "return", "fun", ".", "code", "except", "AttributeError", ":", "try", ":", "h", "=", "inspect", ".", "getsource", "(", "fun", ")", "except", "IOError", ":", "h", "=", "\"nocode\"", "try", ":", "fun", ".", "code", "=", "h", "except", "AttributeError", ":", "pass", "return", "h" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Utils.py#L512-L531
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/origen22.py
python
write_tape4
(mat, outfile="TAPE4.INP")
Writes a TAPE4.INP ORIGEN input file for a material. Parameters ---------- mat : Material Material with mass weights in units of grams. outfile : str or file handler, optional Path to tape4 file or file-like object.
Writes a TAPE4.INP ORIGEN input file for a material.
[ "Writes", "a", "TAPE4", ".", "INP", "ORIGEN", "input", "file", "for", "a", "material", "." ]
def write_tape4(mat, outfile="TAPE4.INP"): """Writes a TAPE4.INP ORIGEN input file for a material. Parameters ---------- mat : Material Material with mass weights in units of grams. outfile : str or file handler, optional Path to tape4 file or file-like object. """ lower_z = mat[:'AC'] upper_z = mat['AC':] lower_lines = ["1 {0} {1:.10E} 0 0 0 0 0 0".format(nucname.zzaaam(nuc), mass) \ for nuc, mass in lower_z.mult_by_mass().items()] upper_lines = ["2 {0} {1:.10E} 0 0 0 0 0 0".format(nucname.zzaaam(nuc), mass) \ for nuc, mass in upper_z.mult_by_mass().items()] lines = lower_lines + upper_lines + ["0 0 0 0\n"] tape4 = "\n".join(lines) # Write to the file opened_here = False if isinstance(outfile, basestring): outfile = open(outfile, 'w') opened_here = True outfile.write(tape4) if opened_here: outfile.close()
[ "def", "write_tape4", "(", "mat", ",", "outfile", "=", "\"TAPE4.INP\"", ")", ":", "lower_z", "=", "mat", "[", ":", "'AC'", "]", "upper_z", "=", "mat", "[", "'AC'", ":", "]", "lower_lines", "=", "[", "\"1 {0} {1:.10E} 0 0 0 0 0 0\"", ".", "format", "(", "nucname", ".", "zzaaam", "(", "nuc", ")", ",", "mass", ")", "for", "nuc", ",", "mass", "in", "lower_z", ".", "mult_by_mass", "(", ")", ".", "items", "(", ")", "]", "upper_lines", "=", "[", "\"2 {0} {1:.10E} 0 0 0 0 0 0\"", ".", "format", "(", "nucname", ".", "zzaaam", "(", "nuc", ")", ",", "mass", ")", "for", "nuc", ",", "mass", "in", "upper_z", ".", "mult_by_mass", "(", ")", ".", "items", "(", ")", "]", "lines", "=", "lower_lines", "+", "upper_lines", "+", "[", "\"0 0 0 0\\n\"", "]", "tape4", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "# Write to the file", "opened_here", "=", "False", "if", "isinstance", "(", "outfile", ",", "basestring", ")", ":", "outfile", "=", "open", "(", "outfile", ",", "'w'", ")", "opened_here", "=", "True", "outfile", ".", "write", "(", "tape4", ")", "if", "opened_here", ":", "outfile", ".", "close", "(", ")" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/origen22.py#L382-L412
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/httpclient.py
python
DetailedHTTPResponse.read_chunks
(self)
return chunks, delays
Return the response body content and timing data. The returned chunks have the chunk size and CRLFs stripped off. If the response was compressed, the returned data is still compressed. Returns: (chunks, delays) chunks: [response_body] # non-chunked responses [chunk_1, chunk_2, ...] # chunked responses delays: [0] # non-chunked responses [chunk_1_first_byte_delay, ...] # chunked responses The delay for the first body item should be recorded by the caller.
Return the response body content and timing data.
[ "Return", "the", "response", "body", "content", "and", "timing", "data", "." ]
def read_chunks(self): """Return the response body content and timing data. The returned chunks have the chunk size and CRLFs stripped off. If the response was compressed, the returned data is still compressed. Returns: (chunks, delays) chunks: [response_body] # non-chunked responses [chunk_1, chunk_2, ...] # chunked responses delays: [0] # non-chunked responses [chunk_1_first_byte_delay, ...] # chunked responses The delay for the first body item should be recorded by the caller. """ buf = [] chunks = [] delays = [] if not self.chunked: chunks.append(self.read()) delays.append(0) else: start = TIMER() try: while True: line = self.fp.readline() chunk_size = self._read_chunk_size(line) if chunk_size is None: raise httplib.IncompleteRead(''.join(chunks)) if chunk_size == 0: break delays.append(TIMER() - start) chunks.append(self._safe_read(chunk_size)) self._safe_read(2) # skip the CRLF at the end of the chunk start = TIMER() # Ignore any trailers. while True: line = self.fp.readline() if not line or line == '\r\n': break finally: self.close() return chunks, delays
[ "def", "read_chunks", "(", "self", ")", ":", "buf", "=", "[", "]", "chunks", "=", "[", "]", "delays", "=", "[", "]", "if", "not", "self", ".", "chunked", ":", "chunks", ".", "append", "(", "self", ".", "read", "(", ")", ")", "delays", ".", "append", "(", "0", ")", "else", ":", "start", "=", "TIMER", "(", ")", "try", ":", "while", "True", ":", "line", "=", "self", ".", "fp", ".", "readline", "(", ")", "chunk_size", "=", "self", ".", "_read_chunk_size", "(", "line", ")", "if", "chunk_size", "is", "None", ":", "raise", "httplib", ".", "IncompleteRead", "(", "''", ".", "join", "(", "chunks", ")", ")", "if", "chunk_size", "==", "0", ":", "break", "delays", ".", "append", "(", "TIMER", "(", ")", "-", "start", ")", "chunks", ".", "append", "(", "self", ".", "_safe_read", "(", "chunk_size", ")", ")", "self", ".", "_safe_read", "(", "2", ")", "# skip the CRLF at the end of the chunk", "start", "=", "TIMER", "(", ")", "# Ignore any trailers.", "while", "True", ":", "line", "=", "self", ".", "fp", ".", "readline", "(", ")", "if", "not", "line", "or", "line", "==", "'\\r\\n'", ":", "break", "finally", ":", "self", ".", "close", "(", ")", "return", "chunks", ",", "delays" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/httpclient.py#L115-L160
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
catalogGetPublic
(pubID)
return ret
Try to lookup the catalog reference associated to a public ID DEPRECATED, use xmlCatalogResolvePublic()
Try to lookup the catalog reference associated to a public ID DEPRECATED, use xmlCatalogResolvePublic()
[ "Try", "to", "lookup", "the", "catalog", "reference", "associated", "to", "a", "public", "ID", "DEPRECATED", "use", "xmlCatalogResolvePublic", "()" ]
def catalogGetPublic(pubID): """Try to lookup the catalog reference associated to a public ID DEPRECATED, use xmlCatalogResolvePublic() """ ret = libxml2mod.xmlCatalogGetPublic(pubID) return ret
[ "def", "catalogGetPublic", "(", "pubID", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCatalogGetPublic", "(", "pubID", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L139-L143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
SizerItem.GetBorder
(*args, **kwargs)
return _core_.SizerItem_GetBorder(*args, **kwargs)
GetBorder(self) -> int Get the border value for this item.
GetBorder(self) -> int
[ "GetBorder", "(", "self", ")", "-", ">", "int" ]
def GetBorder(*args, **kwargs): """ GetBorder(self) -> int Get the border value for this item. """ return _core_.SizerItem_GetBorder(*args, **kwargs)
[ "def", "GetBorder", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerItem_GetBorder", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14227-L14233
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/install_lib.py
python
install_lib._all_packages
(pkg_name)
>>> list(install_lib._all_packages('foo.bar.baz')) ['foo.bar.baz', 'foo.bar', 'foo']
>>> list(install_lib._all_packages('foo.bar.baz')) ['foo.bar.baz', 'foo.bar', 'foo']
[ ">>>", "list", "(", "install_lib", ".", "_all_packages", "(", "foo", ".", "bar", ".", "baz", "))", "[", "foo", ".", "bar", ".", "baz", "foo", ".", "bar", "foo", "]" ]
def _all_packages(pkg_name): """ >>> list(install_lib._all_packages('foo.bar.baz')) ['foo.bar.baz', 'foo.bar', 'foo'] """ while pkg_name: yield pkg_name pkg_name, sep, child = pkg_name.rpartition('.')
[ "def", "_all_packages", "(", "pkg_name", ")", ":", "while", "pkg_name", ":", "yield", "pkg_name", "pkg_name", ",", "sep", ",", "child", "=", "pkg_name", ".", "rpartition", "(", "'.'", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/install_lib.py#L40-L47
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
dsa/XVDPU-TRD/xvdpu_ip/aie/scripts/getAddr.py
python
getAddr
(start_col, start_row)
form = ' {:18}\t{:8}\t{:10}\t{:10}\n' pStr = form.format('name', 'size(B)', 'start addr', 'end addr') for k in map_A: pStr += form.format(k, map_A[k][0],hex(map_A[k][1]),hex(map_A[k][2])) #print '[INFO]: addr map from original file '+mapfname #print pStr
form = ' {:18}\t{:8}\t{:10}\t{:10}\n' pStr = form.format('name', 'size(B)', 'start addr', 'end addr') for k in map_A: pStr += form.format(k, map_A[k][0],hex(map_A[k][1]),hex(map_A[k][2])) #print '[INFO]: addr map from original file '+mapfname #print pStr
[ "form", "=", "{", ":", "18", "}", "\\", "t", "{", ":", "8", "}", "\\", "t", "{", ":", "10", "}", "\\", "t", "{", ":", "10", "}", "\\", "n", "pStr", "=", "form", ".", "format", "(", "name", "size", "(", "B", ")", "start", "addr", "end", "addr", ")", "for", "k", "in", "map_A", ":", "pStr", "+", "=", "form", ".", "format", "(", "k", "map_A", "[", "k", "]", "[", "0", "]", "hex", "(", "map_A", "[", "k", "]", "[", "1", "]", ")", "hex", "(", "map_A", "[", "k", "]", "[", "2", "]", "))", "#print", "[", "INFO", "]", ":", "addr", "map", "from", "original", "file", "+", "mapfname", "#print", "pStr" ]
def getAddr(start_col, start_row): col = start_col row = start_row mapfname = "./Work/aie/"+str(col) + "_"+str(row)+"/Release/"+str(col)+"_"+str(row)+".map" map_A = getAddrMap(mapfname) cfg = '----------------------------------------------------\n' cfg += 'addr_map of core (col, row)=(' + str(col) + ','+str(row)+')\n' ''' form = ' {:18}\t{:8}\t{:10}\t{:10}\n' pStr = form.format('name', 'size(B)', 'start addr', 'end addr') for k in map_A: pStr += form.format(k, map_A[k][0],hex(map_A[k][1]),hex(map_A[k][2])) #print '[INFO]: addr map from original file '+mapfname #print pStr ''' cfg += genMapCom(map_A, start_col, start_row) print(cfg)
[ "def", "getAddr", "(", "start_col", ",", "start_row", ")", ":", "col", "=", "start_col", "row", "=", "start_row", "mapfname", "=", "\"./Work/aie/\"", "+", "str", "(", "col", ")", "+", "\"_\"", "+", "str", "(", "row", ")", "+", "\"/Release/\"", "+", "str", "(", "col", ")", "+", "\"_\"", "+", "str", "(", "row", ")", "+", "\".map\"", "map_A", "=", "getAddrMap", "(", "mapfname", ")", "cfg", "=", "'----------------------------------------------------\\n'", "cfg", "+=", "'addr_map of core (col, row)=('", "+", "str", "(", "col", ")", "+", "','", "+", "str", "(", "row", ")", "+", "')\\n'", "cfg", "+=", "genMapCom", "(", "map_A", ",", "start_col", ",", "start_row", ")", "print", "(", "cfg", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/dsa/XVDPU-TRD/xvdpu_ip/aie/scripts/getAddr.py#L59-L75
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/environment.py
python
Environment.getitem
(self, obj, argument)
Get an item or attribute of an object but prefer the item.
Get an item or attribute of an object but prefer the item.
[ "Get", "an", "item", "or", "attribute", "of", "an", "object", "but", "prefer", "the", "item", "." ]
def getitem(self, obj, argument): """Get an item or attribute of an object but prefer the item.""" try: return obj[argument] except (AttributeError, TypeError, LookupError): if isinstance(argument, string_types): try: attr = str(argument) except Exception: pass else: try: return getattr(obj, attr) except AttributeError: pass return self.undefined(obj=obj, name=argument)
[ "def", "getitem", "(", "self", ",", "obj", ",", "argument", ")", ":", "try", ":", "return", "obj", "[", "argument", "]", "except", "(", "AttributeError", ",", "TypeError", ",", "LookupError", ")", ":", "if", "isinstance", "(", "argument", ",", "string_types", ")", ":", "try", ":", "attr", "=", "str", "(", "argument", ")", "except", "Exception", ":", "pass", "else", ":", "try", ":", "return", "getattr", "(", "obj", ",", "attr", ")", "except", "AttributeError", ":", "pass", "return", "self", ".", "undefined", "(", "obj", "=", "obj", ",", "name", "=", "argument", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L408-L423
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py
python
get_subj_alt_name
(peer_cert)
return names
Given an PyOpenSSL certificate, provides all the subject alternative names.
Given an PyOpenSSL certificate, provides all the subject alternative names.
[ "Given", "an", "PyOpenSSL", "certificate", "provides", "all", "the", "subject", "alternative", "names", "." ]
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
[ "def", "get_subj_alt_name", "(", "peer_cert", ")", ":", "# Pass the cert to cryptography, which has much better APIs for this.", "if", "hasattr", "(", "peer_cert", ",", "\"to_cryptography\"", ")", ":", "cert", "=", "peer_cert", ".", "to_cryptography", "(", ")", "else", ":", "# This is technically using private APIs, but should work across all", "# relevant versions before PyOpenSSL got a proper API for this.", "cert", "=", "_Certificate", "(", "openssl_backend", ",", "peer_cert", ".", "_x509", ")", "# We want to find the SAN extension. Ask Cryptography to locate it (it's", "# faster than looping in Python)", "try", ":", "ext", "=", "cert", ".", "extensions", ".", "get_extension_for_class", "(", "x509", ".", "SubjectAlternativeName", ")", ".", "value", "except", "x509", ".", "ExtensionNotFound", ":", "# No such extension, return the empty list.", "return", "[", "]", "except", "(", "x509", ".", "DuplicateExtension", ",", "UnsupportedExtension", ",", "x509", ".", "UnsupportedGeneralNameType", ",", "UnicodeError", ",", ")", "as", "e", ":", "# A problem has been found with the quality of the certificate. Assume", "# no SAN field is present.", "log", ".", "warning", "(", "\"A problem was encountered with the certificate that prevented \"", "\"urllib3 from finding the SubjectAlternativeName field. This can \"", "\"affect certificate validation. The error was %s\"", ",", "e", ",", ")", "return", "[", "]", "# We want to return dNSName and iPAddress fields. We need to cast the IPs", "# back to strings because the match_hostname function wants them as", "# strings.", "# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8", "# decoded. This is pretty frustrating, but that's what the standard library", "# does with certificates, and so we need to attempt to do the same.", "# We also want to skip over names which cannot be idna encoded.", "names", "=", "[", "(", "\"DNS\"", ",", "name", ")", "for", "name", "in", "map", "(", "_dnsname_to_stdlib", ",", "ext", ".", "get_values_for_type", "(", "x509", ".", "DNSName", ")", ")", "if", "name", "is", "not", "None", "]", "names", ".", "extend", "(", "(", "\"IP Address\"", ",", "str", "(", "name", ")", ")", "for", "name", "in", "ext", ".", "get_values_for_type", "(", "x509", ".", "IPAddress", ")", ")", "return", "names" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py#L208-L259
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.cleanup_headers
(self)
Make any necessary header changes or defaults Subclasses can extend this to add other defaults.
Make any necessary header changes or defaults
[ "Make", "any", "necessary", "header", "changes", "or", "defaults" ]
def cleanup_headers(self): """Make any necessary header changes or defaults Subclasses can extend this to add other defaults. """ if 'Content-Length' not in self.headers: self.set_content_length()
[ "def", "cleanup_headers", "(", "self", ")", ":", "if", "'Content-Length'", "not", "in", "self", ".", "headers", ":", "self", ".", "set_content_length", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/handlers.py#L152-L158
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
_CppLintState.PrintErrorCounts
(self)
Print a summary of errors by category, and the total.
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "." ]
def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
[ "def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "self", ".", "errors_by_category", ".", "iteritems", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category", ",", "count", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Total errors found: %d\\n'", "%", "self", ".", "error_count", ")" ]
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L841-L846
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/MetaSearch/dialogs/maindialog.py
python
MetaSearchDialog.add_to_ows
(self)
add to OWS provider connection list
add to OWS provider connection list
[ "add", "to", "OWS", "provider", "connection", "list" ]
def add_to_ows(self): """add to OWS provider connection list""" conn_name_matches = [] item = self.treeRecords.currentItem() if not item: return item_data = json.loads(get_item_data(item, 'link')) caller = self.sender().objectName() # stype = human name,/qgis/connections-%s,providername if caller == 'mActionAddWms': stype = ['OGC:WMS/OGC:WMTS', 'wms', 'wms'] data_url = item_data['wms'] elif caller == 'mActionAddWfs': stype = ['OGC:WFS', 'wfs', 'WFS'] data_url = item_data['wfs'] elif caller == 'mActionAddWcs': stype = ['OGC:WCS', 'wcs', 'wcs'] data_url = item_data['wcs'] elif caller == 'mActionAddAms': stype = ['ESRI:ArcGIS:MapServer', 'ams', 'arcgismapserver'] data_url = item_data['ams'].split('MapServer')[0] + 'MapServer' elif caller == 'mActionAddAfs': stype = ['ESRI:ArcGIS:FeatureServer', 'afs', 'arcgisfeatureserver'] data_url = (item_data['afs'].split('FeatureServer')[0] + 'FeatureServer') sname = '%s from MetaSearch' % stype[1] # store connection # check if there is a connection with same name if caller in ['mActionAddAms', 'mActionAddAfs']: self.settings.beginGroup('/qgis/connections-%s' % stype[2]) else: self.settings.beginGroup('/qgis/connections-%s' % stype[1]) keys = self.settings.childGroups() self.settings.endGroup() for key in keys: if key.startswith(sname): conn_name_matches.append(key) if conn_name_matches: sname = conn_name_matches[-1] # check for duplicates if sname in keys: # duplicate found msg = self.tr('Connection {0} exists. Overwrite?').format(sname) res = QMessageBox.warning( self, self.tr('Saving server'), msg, QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if res == QMessageBox.No: # assign new name with serial sname = serialize_string(sname) elif res == QMessageBox.Cancel: return # no dups detected or overwrite is allowed if caller in ['mActionAddAms', 'mActionAddAfs']: self.settings.beginGroup('/qgis/connections-%s' % stype[2]) else: self.settings.beginGroup('/qgis/connections-%s' % stype[1]) self.settings.setValue('/%s/url' % sname, clean_ows_url(data_url)) self.settings.endGroup() # open provider window ows_provider = QgsGui.sourceSelectProviderRegistry().\ createSelectionWidget( stype[2], self, Qt.Widget, QgsProviderRegistry.WidgetMode.Embedded) service_type = stype[0] # connect dialog signals to iface slots if service_type == 'OGC:WMS/OGC:WMTS': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections') connect = 'btnConnect_clicked' elif service_type == 'OGC:WFS': def addVectorLayer(path, name): self.iface.addVectorLayer(path, name, 'WFS') ows_provider.addVectorLayer.connect(addVectorLayer) conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections') connect = 'connectToServer' elif service_type == 'OGC:WCS': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QWidget, 'mConnectionsComboBox') connect = 'mConnectButton_clicked' elif service_type == 'ESRI:ArcGIS:MapServer': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QComboBox) connect = 'connectToServer' elif service_type == 'ESRI:ArcGIS:FeatureServer': def addAfsLayer(path, name): self.iface.addVectorLayer(path, name, 'afs') ows_provider.addVectorLayer.connect(addAfsLayer) conn_cmb = ows_provider.findChild(QComboBox) connect = 'connectToServer' ows_provider.setModal(False) ows_provider.show() # open provider dialogue against added OWS index = conn_cmb.findText(sname) if index > -1: conn_cmb.setCurrentIndex(index) # only for wfs if service_type == 'OGC:WFS': ows_provider.cmbConnections_activated(index) elif service_type in ['ESRI:ArcGIS:MapServer', 'ESRI:ArcGIS:FeatureServer']: # noqa ows_provider.cmbConnections_activated(index) getattr(ows_provider, connect)()
[ "def", "add_to_ows", "(", "self", ")", ":", "conn_name_matches", "=", "[", "]", "item", "=", "self", ".", "treeRecords", ".", "currentItem", "(", ")", "if", "not", "item", ":", "return", "item_data", "=", "json", ".", "loads", "(", "get_item_data", "(", "item", ",", "'link'", ")", ")", "caller", "=", "self", ".", "sender", "(", ")", ".", "objectName", "(", ")", "# stype = human name,/qgis/connections-%s,providername", "if", "caller", "==", "'mActionAddWms'", ":", "stype", "=", "[", "'OGC:WMS/OGC:WMTS'", ",", "'wms'", ",", "'wms'", "]", "data_url", "=", "item_data", "[", "'wms'", "]", "elif", "caller", "==", "'mActionAddWfs'", ":", "stype", "=", "[", "'OGC:WFS'", ",", "'wfs'", ",", "'WFS'", "]", "data_url", "=", "item_data", "[", "'wfs'", "]", "elif", "caller", "==", "'mActionAddWcs'", ":", "stype", "=", "[", "'OGC:WCS'", ",", "'wcs'", ",", "'wcs'", "]", "data_url", "=", "item_data", "[", "'wcs'", "]", "elif", "caller", "==", "'mActionAddAms'", ":", "stype", "=", "[", "'ESRI:ArcGIS:MapServer'", ",", "'ams'", ",", "'arcgismapserver'", "]", "data_url", "=", "item_data", "[", "'ams'", "]", ".", "split", "(", "'MapServer'", ")", "[", "0", "]", "+", "'MapServer'", "elif", "caller", "==", "'mActionAddAfs'", ":", "stype", "=", "[", "'ESRI:ArcGIS:FeatureServer'", ",", "'afs'", ",", "'arcgisfeatureserver'", "]", "data_url", "=", "(", "item_data", "[", "'afs'", "]", ".", "split", "(", "'FeatureServer'", ")", "[", "0", "]", "+", "'FeatureServer'", ")", "sname", "=", "'%s from MetaSearch'", "%", "stype", "[", "1", "]", "# store connection", "# check if there is a connection with same name", "if", "caller", "in", "[", "'mActionAddAms'", ",", "'mActionAddAfs'", "]", ":", "self", ".", "settings", ".", "beginGroup", "(", "'/qgis/connections-%s'", "%", "stype", "[", "2", "]", ")", "else", ":", "self", ".", "settings", ".", "beginGroup", "(", "'/qgis/connections-%s'", "%", "stype", "[", "1", "]", ")", "keys", "=", "self", ".", "settings", ".", "childGroups", "(", ")", "self", ".", "settings", ".", "endGroup", "(", ")", "for", "key", "in", "keys", ":", "if", "key", ".", "startswith", "(", "sname", ")", ":", "conn_name_matches", ".", "append", "(", "key", ")", "if", "conn_name_matches", ":", "sname", "=", "conn_name_matches", "[", "-", "1", "]", "# check for duplicates", "if", "sname", "in", "keys", ":", "# duplicate found", "msg", "=", "self", ".", "tr", "(", "'Connection {0} exists. Overwrite?'", ")", ".", "format", "(", "sname", ")", "res", "=", "QMessageBox", ".", "warning", "(", "self", ",", "self", ".", "tr", "(", "'Saving server'", ")", ",", "msg", ",", "QMessageBox", ".", "Yes", "|", "QMessageBox", ".", "No", "|", "QMessageBox", ".", "Cancel", ")", "if", "res", "==", "QMessageBox", ".", "No", ":", "# assign new name with serial", "sname", "=", "serialize_string", "(", "sname", ")", "elif", "res", "==", "QMessageBox", ".", "Cancel", ":", "return", "# no dups detected or overwrite is allowed", "if", "caller", "in", "[", "'mActionAddAms'", ",", "'mActionAddAfs'", "]", ":", "self", ".", "settings", ".", "beginGroup", "(", "'/qgis/connections-%s'", "%", "stype", "[", "2", "]", ")", "else", ":", "self", ".", "settings", ".", "beginGroup", "(", "'/qgis/connections-%s'", "%", "stype", "[", "1", "]", ")", "self", ".", "settings", ".", "setValue", "(", "'/%s/url'", "%", "sname", ",", "clean_ows_url", "(", "data_url", ")", ")", "self", ".", "settings", ".", "endGroup", "(", ")", "# open provider window", "ows_provider", "=", "QgsGui", ".", "sourceSelectProviderRegistry", "(", ")", ".", "createSelectionWidget", "(", "stype", "[", "2", "]", ",", "self", ",", "Qt", ".", "Widget", ",", "QgsProviderRegistry", ".", "WidgetMode", ".", "Embedded", ")", "service_type", "=", "stype", "[", "0", "]", "# connect dialog signals to iface slots", "if", "service_type", "==", "'OGC:WMS/OGC:WMTS'", ":", "ows_provider", ".", "addRasterLayer", ".", "connect", "(", "self", ".", "iface", ".", "addRasterLayer", ")", "conn_cmb", "=", "ows_provider", ".", "findChild", "(", "QWidget", ",", "'cmbConnections'", ")", "connect", "=", "'btnConnect_clicked'", "elif", "service_type", "==", "'OGC:WFS'", ":", "def", "addVectorLayer", "(", "path", ",", "name", ")", ":", "self", ".", "iface", ".", "addVectorLayer", "(", "path", ",", "name", ",", "'WFS'", ")", "ows_provider", ".", "addVectorLayer", ".", "connect", "(", "addVectorLayer", ")", "conn_cmb", "=", "ows_provider", ".", "findChild", "(", "QWidget", ",", "'cmbConnections'", ")", "connect", "=", "'connectToServer'", "elif", "service_type", "==", "'OGC:WCS'", ":", "ows_provider", ".", "addRasterLayer", ".", "connect", "(", "self", ".", "iface", ".", "addRasterLayer", ")", "conn_cmb", "=", "ows_provider", ".", "findChild", "(", "QWidget", ",", "'mConnectionsComboBox'", ")", "connect", "=", "'mConnectButton_clicked'", "elif", "service_type", "==", "'ESRI:ArcGIS:MapServer'", ":", "ows_provider", ".", "addRasterLayer", ".", "connect", "(", "self", ".", "iface", ".", "addRasterLayer", ")", "conn_cmb", "=", "ows_provider", ".", "findChild", "(", "QComboBox", ")", "connect", "=", "'connectToServer'", "elif", "service_type", "==", "'ESRI:ArcGIS:FeatureServer'", ":", "def", "addAfsLayer", "(", "path", ",", "name", ")", ":", "self", ".", "iface", ".", "addVectorLayer", "(", "path", ",", "name", ",", "'afs'", ")", "ows_provider", ".", "addVectorLayer", ".", "connect", "(", "addAfsLayer", ")", "conn_cmb", "=", "ows_provider", ".", "findChild", "(", "QComboBox", ")", "connect", "=", "'connectToServer'", "ows_provider", ".", "setModal", "(", "False", ")", "ows_provider", ".", "show", "(", ")", "# open provider dialogue against added OWS", "index", "=", "conn_cmb", ".", "findText", "(", "sname", ")", "if", "index", ">", "-", "1", ":", "conn_cmb", ".", "setCurrentIndex", "(", "index", ")", "# only for wfs", "if", "service_type", "==", "'OGC:WFS'", ":", "ows_provider", ".", "cmbConnections_activated", "(", "index", ")", "elif", "service_type", "in", "[", "'ESRI:ArcGIS:MapServer'", ",", "'ESRI:ArcGIS:FeatureServer'", "]", ":", "# noqa", "ows_provider", ".", "cmbConnections_activated", "(", "index", ")", "getattr", "(", "ows_provider", ",", "connect", ")", "(", ")" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/dialogs/maindialog.py#L708-L823
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/parsers/XmlSerializeParser.py
python
XmlSerializeParser.get_members
(self)
return self.__members
Returns a list of member (name, type, optional size, optional format, optional comment) needed.
Returns a list of member (name, type, optional size, optional format, optional comment) needed.
[ "Returns", "a", "list", "of", "member", "(", "name", "type", "optional", "size", "optional", "format", "optional", "comment", ")", "needed", "." ]
def get_members(self): """ Returns a list of member (name, type, optional size, optional format, optional comment) needed. """ return self.__members
[ "def", "get_members", "(", "self", ")", ":", "return", "self", ".", "__members" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/parsers/XmlSerializeParser.py#L322-L326
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/dataset/dataset.py
python
InMemoryDataset.__init__
(self)
Init.
Init.
[ "Init", "." ]
def __init__(self): """ Init. """ super(InMemoryDataset, self).__init__() self.proto_desc.name = "MultiSlotInMemoryDataFeed" self.fleet_send_batch_size = None self.is_user_set_queue_num = False self.queue_num = None self.parse_ins_id = False self.parse_content = False self.parse_logkey = False self.merge_by_sid = True self.enable_pv_merge = False self.merge_by_lineid = False self.fleet_send_sleep_seconds = None
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "InMemoryDataset", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "proto_desc", ".", "name", "=", "\"MultiSlotInMemoryDataFeed\"", "self", ".", "fleet_send_batch_size", "=", "None", "self", ".", "is_user_set_queue_num", "=", "False", "self", ".", "queue_num", "=", "None", "self", ".", "parse_ins_id", "=", "False", "self", ".", "parse_content", "=", "False", "self", ".", "parse_logkey", "=", "False", "self", ".", "merge_by_sid", "=", "True", "self", ".", "enable_pv_merge", "=", "False", "self", ".", "merge_by_lineid", "=", "False", "self", ".", "fleet_send_sleep_seconds", "=", "None" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/dataset/dataset.py#L356-L369
GrammaTech/gtirb
415dd72e1e3c475004d013723c16cdcb29c0826e
python/gtirb/ir.py
python
IR.symbolic_expressions_at
( self, addrs: typing.Union[int, range] )
return symbolic_expressions_at(self.modules, addrs)
Finds all the symbolic expressions that begin at an address or range of addresses. :param addrs: Either a ``range`` object or a single address. :returns: Yields ``(interval, offset, symexpr)`` tuples for every symbolic expression in the range.
Finds all the symbolic expressions that begin at an address or range of addresses.
[ "Finds", "all", "the", "symbolic", "expressions", "that", "begin", "at", "an", "address", "or", "range", "of", "addresses", "." ]
def symbolic_expressions_at( self, addrs: typing.Union[int, range] ) -> typing.Iterable[SymbolicExpressionElement]: """Finds all the symbolic expressions that begin at an address or range of addresses. :param addrs: Either a ``range`` object or a single address. :returns: Yields ``(interval, offset, symexpr)`` tuples for every symbolic expression in the range. """ return symbolic_expressions_at(self.modules, addrs)
[ "def", "symbolic_expressions_at", "(", "self", ",", "addrs", ":", "typing", ".", "Union", "[", "int", ",", "range", "]", ")", "->", "typing", ".", "Iterable", "[", "SymbolicExpressionElement", "]", ":", "return", "symbolic_expressions_at", "(", "self", ".", "modules", ",", "addrs", ")" ]
https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/ir.py#L373-L384
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/externals/joblib/numpy_pickle.py
python
NumpyArrayWrapper.__init__
(self, subclass, shape, order, dtype, allow_mmap=False)
Constructor. Store the useful information for later.
Constructor. Store the useful information for later.
[ "Constructor", ".", "Store", "the", "useful", "information", "for", "later", "." ]
def __init__(self, subclass, shape, order, dtype, allow_mmap=False): """Constructor. Store the useful information for later.""" self.subclass = subclass self.shape = shape self.order = order self.dtype = dtype self.allow_mmap = allow_mmap
[ "def", "__init__", "(", "self", ",", "subclass", ",", "shape", ",", "order", ",", "dtype", ",", "allow_mmap", "=", "False", ")", ":", "self", ".", "subclass", "=", "subclass", "self", ".", "shape", "=", "shape", "self", ".", "order", "=", "order", "self", ".", "dtype", "=", "dtype", "self", ".", "allow_mmap", "=", "allow_mmap" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/numpy_pickle.py#L64-L70
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/extension.py
python
read_setup_file
(filename)
return extensions
Reads a Setup file and returns Extension instances.
Reads a Setup file and returns Extension instances.
[ "Reads", "a", "Setup", "file", "and", "returns", "Extension", "instances", "." ]
def read_setup_file(filename): """Reads a Setup file and returns Extension instances.""" from distutils.sysconfig import (parse_makefile, expand_makefile_vars, _variable_rx) from distutils.text_file import TextFile from distutils.util import split_quoted # First pass over the file to gather "VAR = VALUE" assignments. vars = parse_makefile(filename) # Second pass to gobble up the real content: lines of the form # <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...] file = TextFile(filename, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1) try: extensions = [] while True: line = file.readline() if line is None: # eof break if _variable_rx.match(line): # VAR=VALUE, handled in first pass continue if line[0] == line[-1] == "*": file.warn("'%s' lines not handled yet" % line) continue line = expand_makefile_vars(line, vars) words = split_quoted(line) # NB. this parses a slightly different syntax than the old # makesetup script: here, there must be exactly one extension per # line, and it must be the first word of the line. I have no idea # why the old syntax supported multiple extensions per line, as # they all wind up being the same. module = words[0] ext = Extension(module, []) append_next_word = None for word in words[1:]: if append_next_word is not None: append_next_word.append(word) append_next_word = None continue suffix = os.path.splitext(word)[1] switch = word[0:2] ; value = word[2:] if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"): # hmm, should we do something about C vs. C++ sources? # or leave it up to the CCompiler implementation to # worry about? ext.sources.append(word) elif switch == "-I": ext.include_dirs.append(value) elif switch == "-D": equals = value.find("=") if equals == -1: # bare "-DFOO" -- no value ext.define_macros.append((value, None)) else: # "-DFOO=blah" ext.define_macros.append((value[0:equals], value[equals+2:])) elif switch == "-U": ext.undef_macros.append(value) elif switch == "-C": # only here 'cause makesetup has it! ext.extra_compile_args.append(word) elif switch == "-l": ext.libraries.append(value) elif switch == "-L": ext.library_dirs.append(value) elif switch == "-R": ext.runtime_library_dirs.append(value) elif word == "-rpath": append_next_word = ext.runtime_library_dirs elif word == "-Xlinker": append_next_word = ext.extra_link_args elif word == "-Xcompiler": append_next_word = ext.extra_compile_args elif switch == "-u": ext.extra_link_args.append(word) if not value: append_next_word = ext.extra_link_args elif suffix in (".a", ".so", ".sl", ".o", ".dylib"): # NB. a really faithful emulation of makesetup would # append a .o file to extra_objects only if it # had a slash in it; otherwise, it would s/.o/.c/ # and append it to sources. Hmmmm. ext.extra_objects.append(word) else: file.warn("unrecognized argument '%s'" % word) extensions.append(ext) finally: file.close() return extensions
[ "def", "read_setup_file", "(", "filename", ")", ":", "from", "distutils", ".", "sysconfig", "import", "(", "parse_makefile", ",", "expand_makefile_vars", ",", "_variable_rx", ")", "from", "distutils", ".", "text_file", "import", "TextFile", "from", "distutils", ".", "util", "import", "split_quoted", "# First pass over the file to gather \"VAR = VALUE\" assignments.", "vars", "=", "parse_makefile", "(", "filename", ")", "# Second pass to gobble up the real content: lines of the form", "# <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]", "file", "=", "TextFile", "(", "filename", ",", "strip_comments", "=", "1", ",", "skip_blanks", "=", "1", ",", "join_lines", "=", "1", ",", "lstrip_ws", "=", "1", ",", "rstrip_ws", "=", "1", ")", "try", ":", "extensions", "=", "[", "]", "while", "True", ":", "line", "=", "file", ".", "readline", "(", ")", "if", "line", "is", "None", ":", "# eof", "break", "if", "_variable_rx", ".", "match", "(", "line", ")", ":", "# VAR=VALUE, handled in first pass", "continue", "if", "line", "[", "0", "]", "==", "line", "[", "-", "1", "]", "==", "\"*\"", ":", "file", ".", "warn", "(", "\"'%s' lines not handled yet\"", "%", "line", ")", "continue", "line", "=", "expand_makefile_vars", "(", "line", ",", "vars", ")", "words", "=", "split_quoted", "(", "line", ")", "# NB. this parses a slightly different syntax than the old", "# makesetup script: here, there must be exactly one extension per", "# line, and it must be the first word of the line. I have no idea", "# why the old syntax supported multiple extensions per line, as", "# they all wind up being the same.", "module", "=", "words", "[", "0", "]", "ext", "=", "Extension", "(", "module", ",", "[", "]", ")", "append_next_word", "=", "None", "for", "word", "in", "words", "[", "1", ":", "]", ":", "if", "append_next_word", "is", "not", "None", ":", "append_next_word", ".", "append", "(", "word", ")", "append_next_word", "=", "None", "continue", "suffix", "=", "os", ".", "path", ".", "splitext", "(", "word", ")", "[", "1", "]", "switch", "=", "word", "[", "0", ":", "2", "]", "value", "=", "word", "[", "2", ":", "]", "if", "suffix", "in", "(", "\".c\"", ",", "\".cc\"", ",", "\".cpp\"", ",", "\".cxx\"", ",", "\".c++\"", ",", "\".m\"", ",", "\".mm\"", ")", ":", "# hmm, should we do something about C vs. C++ sources?", "# or leave it up to the CCompiler implementation to", "# worry about?", "ext", ".", "sources", ".", "append", "(", "word", ")", "elif", "switch", "==", "\"-I\"", ":", "ext", ".", "include_dirs", ".", "append", "(", "value", ")", "elif", "switch", "==", "\"-D\"", ":", "equals", "=", "value", ".", "find", "(", "\"=\"", ")", "if", "equals", "==", "-", "1", ":", "# bare \"-DFOO\" -- no value", "ext", ".", "define_macros", ".", "append", "(", "(", "value", ",", "None", ")", ")", "else", ":", "# \"-DFOO=blah\"", "ext", ".", "define_macros", ".", "append", "(", "(", "value", "[", "0", ":", "equals", "]", ",", "value", "[", "equals", "+", "2", ":", "]", ")", ")", "elif", "switch", "==", "\"-U\"", ":", "ext", ".", "undef_macros", ".", "append", "(", "value", ")", "elif", "switch", "==", "\"-C\"", ":", "# only here 'cause makesetup has it!", "ext", ".", "extra_compile_args", ".", "append", "(", "word", ")", "elif", "switch", "==", "\"-l\"", ":", "ext", ".", "libraries", ".", "append", "(", "value", ")", "elif", "switch", "==", "\"-L\"", ":", "ext", ".", "library_dirs", ".", "append", "(", "value", ")", "elif", "switch", "==", "\"-R\"", ":", "ext", ".", "runtime_library_dirs", ".", "append", "(", "value", ")", "elif", "word", "==", "\"-rpath\"", ":", "append_next_word", "=", "ext", ".", "runtime_library_dirs", "elif", "word", "==", "\"-Xlinker\"", ":", "append_next_word", "=", "ext", ".", "extra_link_args", "elif", "word", "==", "\"-Xcompiler\"", ":", "append_next_word", "=", "ext", ".", "extra_compile_args", "elif", "switch", "==", "\"-u\"", ":", "ext", ".", "extra_link_args", ".", "append", "(", "word", ")", "if", "not", "value", ":", "append_next_word", "=", "ext", ".", "extra_link_args", "elif", "suffix", "in", "(", "\".a\"", ",", "\".so\"", ",", "\".sl\"", ",", "\".o\"", ",", "\".dylib\"", ")", ":", "# NB. a really faithful emulation of makesetup would", "# append a .o file to extra_objects only if it", "# had a slash in it; otherwise, it would s/.o/.c/", "# and append it to sources. Hmmmm.", "ext", ".", "extra_objects", ".", "append", "(", "word", ")", "else", ":", "file", ".", "warn", "(", "\"unrecognized argument '%s'\"", "%", "word", ")", "extensions", ".", "append", "(", "ext", ")", "finally", ":", "file", ".", "close", "(", ")", "return", "extensions" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/extension.py#L141-L240
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_sdr_rtlamr/KismetCaptureRtlamr/kismetexternal/__init__.py
python
ExternalInterface.kill
(self)
Shutdown the external interface service :return: None
Shutdown the external interface service
[ "Shutdown", "the", "external", "interface", "service" ]
def kill(self): """ Shutdown the external interface service :return: None """ self.kill_ioloop = True self.running = False [task.cancel() for task in self.additional_tasks] [cb() for cb in self.exit_callbacks] if not self.main_io_task == None: self.main_io_task.cancel() # Try to mask python 3.5 signal handling bugs, as per # https://github.com/python/asyncio/issues/396 try: self.loop.stop() except TypeError: pass
[ "def", "kill", "(", "self", ")", ":", "self", ".", "kill_ioloop", "=", "True", "self", ".", "running", "=", "False", "[", "task", ".", "cancel", "(", ")", "for", "task", "in", "self", ".", "additional_tasks", "]", "[", "cb", "(", ")", "for", "cb", "in", "self", ".", "exit_callbacks", "]", "if", "not", "self", ".", "main_io_task", "==", "None", ":", "self", ".", "main_io_task", ".", "cancel", "(", ")", "# Try to mask python 3.5 signal handling bugs, as per", "# https://github.com/python/asyncio/issues/396", "try", ":", "self", ".", "loop", ".", "stop", "(", ")", "except", "TypeError", ":", "pass" ]
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtlamr/KismetCaptureRtlamr/kismetexternal/__init__.py#L512-L532
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
RendererNative.GetVersion
(*args, **kwargs)
return _gdi_.RendererNative_GetVersion(*args, **kwargs)
GetVersion(self) -> RendererVersion Returns the version of the renderer. Will be used for ensuring compatibility of dynamically loaded renderers.
GetVersion(self) -> RendererVersion
[ "GetVersion", "(", "self", ")", "-", ">", "RendererVersion" ]
def GetVersion(*args, **kwargs): """ GetVersion(self) -> RendererVersion Returns the version of the renderer. Will be used for ensuring compatibility of dynamically loaded renderers. """ return _gdi_.RendererNative_GetVersion(*args, **kwargs)
[ "def", "GetVersion", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "RendererNative_GetVersion", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L7505-L7512
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
AcceleratorEntry_Create
(*args, **kwargs)
return _core_.AcceleratorEntry_Create(*args, **kwargs)
AcceleratorEntry_Create(String str) -> AcceleratorEntry Create accelerator corresponding to the specified string, or None if it coulnd't be parsed.
AcceleratorEntry_Create(String str) -> AcceleratorEntry
[ "AcceleratorEntry_Create", "(", "String", "str", ")", "-", ">", "AcceleratorEntry" ]
def AcceleratorEntry_Create(*args, **kwargs): """ AcceleratorEntry_Create(String str) -> AcceleratorEntry Create accelerator corresponding to the specified string, or None if it coulnd't be parsed. """ return _core_.AcceleratorEntry_Create(*args, **kwargs)
[ "def", "AcceleratorEntry_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "AcceleratorEntry_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L8984-L8991
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/traitlets.py
python
Container.__init__
(self, trait=None, default_value=Undefined, **kwargs)
Create a container trait type from a list, set, or tuple. The default value is created by doing ``List(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. allow_none : bool [ default False ] Whether to allow the value to be None **kwargs : any further keys for extensions to the Trait (e.g. config)
Create a container trait type from a list, set, or tuple.
[ "Create", "a", "container", "trait", "type", "from", "a", "list", "set", "or", "tuple", "." ]
def __init__(self, trait=None, default_value=Undefined, **kwargs): """Create a container trait type from a list, set, or tuple. The default value is created by doing ``List(default_value)``, which creates a copy of the ``default_value``. ``trait`` can be specified, which restricts the type of elements in the container to that TraitType. If only one arg is given and it is not a Trait, it is taken as ``default_value``: ``c = List([1, 2, 3])`` Parameters ---------- trait : TraitType [ optional ] the type for restricting the contents of the Container. If unspecified, types are not checked. default_value : SequenceType [ optional ] The default value for the Trait. Must be list/tuple/set, and will be cast to the container type. allow_none : bool [ default False ] Whether to allow the value to be None **kwargs : any further keys for extensions to the Trait (e.g. config) """ # allow List([values]): if trait is not None and default_value is Undefined and not is_trait(trait): default_value = trait trait = None if default_value is None and not kwargs.get("allow_none", False): # improve backward-compatibility for possible subclasses # specifying default_value=None as default, # keeping 'unspecified' behavior (i.e. empty container) warn( f"Specifying {self.__class__.__name__}(default_value=None)" " for no default is deprecated in traitlets 5.0.5." " Use default_value=Undefined", DeprecationWarning, stacklevel=2, ) default_value = Undefined if default_value is Undefined: args = () elif default_value is None: # default_value back on kwargs for super() to handle args = () kwargs["default_value"] = None elif isinstance(default_value, self._valid_defaults): args = (default_value,) else: raise TypeError( "default value of %s was %s" % (self.__class__.__name__, default_value) ) if is_trait(trait): if isinstance(trait, type): warn( "Traits should be given as instances, not types (for example, `Int()`, not `Int`)." " Passing types is deprecated in traitlets 4.1.", DeprecationWarning, stacklevel=3, ) self._trait = trait() if isinstance(trait, type) else trait elif trait is not None: raise TypeError( "`trait` must be a Trait or None, got %s" % repr_type(trait) ) super(Container, self).__init__(klass=self.klass, args=args, **kwargs)
[ "def", "__init__", "(", "self", ",", "trait", "=", "None", ",", "default_value", "=", "Undefined", ",", "*", "*", "kwargs", ")", ":", "# allow List([values]):", "if", "trait", "is", "not", "None", "and", "default_value", "is", "Undefined", "and", "not", "is_trait", "(", "trait", ")", ":", "default_value", "=", "trait", "trait", "=", "None", "if", "default_value", "is", "None", "and", "not", "kwargs", ".", "get", "(", "\"allow_none\"", ",", "False", ")", ":", "# improve backward-compatibility for possible subclasses", "# specifying default_value=None as default,", "# keeping 'unspecified' behavior (i.e. empty container)", "warn", "(", "f\"Specifying {self.__class__.__name__}(default_value=None)\"", "\" for no default is deprecated in traitlets 5.0.5.\"", "\" Use default_value=Undefined\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "default_value", "=", "Undefined", "if", "default_value", "is", "Undefined", ":", "args", "=", "(", ")", "elif", "default_value", "is", "None", ":", "# default_value back on kwargs for super() to handle", "args", "=", "(", ")", "kwargs", "[", "\"default_value\"", "]", "=", "None", "elif", "isinstance", "(", "default_value", ",", "self", ".", "_valid_defaults", ")", ":", "args", "=", "(", "default_value", ",", ")", "else", ":", "raise", "TypeError", "(", "\"default value of %s was %s\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "default_value", ")", ")", "if", "is_trait", "(", "trait", ")", ":", "if", "isinstance", "(", "trait", ",", "type", ")", ":", "warn", "(", "\"Traits should be given as instances, not types (for example, `Int()`, not `Int`).\"", "\" Passing types is deprecated in traitlets 4.1.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ",", ")", "self", ".", "_trait", "=", "trait", "(", ")", "if", "isinstance", "(", "trait", ",", "type", ")", "else", "trait", "elif", "trait", "is", "not", "None", ":", "raise", "TypeError", "(", "\"`trait` must be a Trait or None, got %s\"", "%", "repr_type", "(", "trait", ")", ")", "super", "(", "Container", ",", "self", ")", ".", "__init__", "(", "klass", "=", "self", ".", "klass", ",", "args", "=", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/traitlets.py#L2423-L2497
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/python_gflags/gflags.py
python
FlagValues._GetKeyFlagsForModule
(self, module)
return key_flags
Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object.
Returns the list of key flags for a module.
[ "Returns", "the", "list", "of", "key", "flags", "for", "a", "module", "." ]
def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags
[ "def", "_GetKeyFlagsForModule", "(", "self", ",", "module", ")", ":", "if", "not", "isinstance", "(", "module", ",", "str", ")", ":", "module", "=", "module", ".", "__name__", "# Any flag is a key flag for the module that defined it. NOTE:", "# key_flags is a fresh list: we can update it without affecting the", "# internals of this FlagValues object.", "key_flags", "=", "self", ".", "_GetFlagsDefinedByModule", "(", "module", ")", "# Take into account flags explicitly declared as key for a module.", "for", "flag", "in", "self", ".", "KeyFlagsByModuleDict", "(", ")", ".", "get", "(", "module", ",", "[", "]", ")", ":", "if", "flag", "not", "in", "key_flags", ":", "key_flags", ".", "append", "(", "flag", ")", "return", "key_flags" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L929-L952
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
third_party/gpus/find_cuda_config.py
python
_matches_version
(actual_version, required_version)
return actual_version.startswith(required_version)
Checks whether some version meets the requirements. All elements of the required_version need to be present in the actual_version. required_version actual_version result ----------------------------------------- 1 1.1 True 1.2 1 False 1.2 1.3 False 1 True Args: required_version: The version specified by the user. actual_version: The version detected from the CUDA installation. Returns: Whether the actual version matches the required one.
Checks whether some version meets the requirements.
[ "Checks", "whether", "some", "version", "meets", "the", "requirements", "." ]
def _matches_version(actual_version, required_version): """Checks whether some version meets the requirements. All elements of the required_version need to be present in the actual_version. required_version actual_version result ----------------------------------------- 1 1.1 True 1.2 1 False 1.2 1.3 False 1 True Args: required_version: The version specified by the user. actual_version: The version detected from the CUDA installation. Returns: Whether the actual version matches the required one. """ if actual_version is None: return False # Strip spaces from the versions. actual_version = actual_version.strip() required_version = required_version.strip() return actual_version.startswith(required_version)
[ "def", "_matches_version", "(", "actual_version", ",", "required_version", ")", ":", "if", "actual_version", "is", "None", ":", "return", "False", "# Strip spaces from the versions.", "actual_version", "=", "actual_version", ".", "strip", "(", ")", "required_version", "=", "required_version", ".", "strip", "(", ")", "return", "actual_version", ".", "startswith", "(", "required_version", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/third_party/gpus/find_cuda_config.py#L82-L106
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/timer.py
python
Timer.FormatElapsed
(self)
return '%s %s' % (elapsed, unit)
Returns the elapsed time as a string in a pretty format; as a whole number in either seconds or milliseconds depending on which is more appropriate. Must already be Stopped.
Returns the elapsed time as a string in a pretty format; as a whole number in either seconds or milliseconds depending on which is more appropriate. Must already be Stopped.
[ "Returns", "the", "elapsed", "time", "as", "a", "string", "in", "a", "pretty", "format", ";", "as", "a", "whole", "number", "in", "either", "seconds", "or", "milliseconds", "depending", "on", "which", "is", "more", "appropriate", ".", "Must", "already", "be", "Stopped", "." ]
def FormatElapsed(self): '''Returns the elapsed time as a string in a pretty format; as a whole number in either seconds or milliseconds depending on which is more appropriate. Must already be Stopped. ''' assert self._elapsed is not None elapsed = self._elapsed if elapsed < 1: elapsed = int(elapsed * 1000) unit = 'ms' else: elapsed = int(elapsed) unit = 'second' if elapsed == 1 else 'seconds' return '%s %s' % (elapsed, unit)
[ "def", "FormatElapsed", "(", "self", ")", ":", "assert", "self", ".", "_elapsed", "is", "not", "None", "elapsed", "=", "self", ".", "_elapsed", "if", "elapsed", "<", "1", ":", "elapsed", "=", "int", "(", "elapsed", "*", "1000", ")", "unit", "=", "'ms'", "else", ":", "elapsed", "=", "int", "(", "elapsed", ")", "unit", "=", "'second'", "if", "elapsed", "==", "1", "else", "'seconds'", "return", "'%s %s'", "%", "(", "elapsed", ",", "unit", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/timer.py#L34-L47
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py
python
Serial.deserialize
(self, str)
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
[ "unpack", "serialized", "message", "in", "str", "into", "this", "message", "instance", ":", "param", "str", ":", "byte", "array", "of", "serialized", "message", "str" ]
def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: if self.header is None: self.header = std_msgs.msg.Header() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.header.frame_id = str[start:end].decode('utf-8') else: self.header.frame_id = str[start:end] _x = self start = end end += 2 (_x.channel, _x.type,) = _struct_2B.unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length self.data = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e)
[ "def", "deserialize", "(", "self", ",", "str", ")", ":", "try", ":", "if", "self", ".", "header", "is", "None", ":", "self", ".", "header", "=", "std_msgs", ".", "msg", ".", "Header", "(", ")", "end", "=", "0", "_x", "=", "self", "start", "=", "end", "end", "+=", "12", "(", "_x", ".", "header", ".", "seq", ",", "_x", ".", "header", ".", "stamp", ".", "secs", ",", "_x", ".", "header", ".", "stamp", ".", "nsecs", ",", ")", "=", "_struct_3I", ".", "unpack", "(", "str", "[", "start", ":", "end", "]", ")", "start", "=", "end", "end", "+=", "4", "(", "length", ",", ")", "=", "_struct_I", ".", "unpack", "(", "str", "[", "start", ":", "end", "]", ")", "start", "=", "end", "end", "+=", "length", "if", "python3", ":", "self", ".", "header", ".", "frame_id", "=", "str", "[", "start", ":", "end", "]", ".", "decode", "(", "'utf-8'", ")", "else", ":", "self", ".", "header", ".", "frame_id", "=", "str", "[", "start", ":", "end", "]", "_x", "=", "self", "start", "=", "end", "end", "+=", "2", "(", "_x", ".", "channel", ",", "_x", ".", "type", ",", ")", "=", "_struct_2B", ".", "unpack", "(", "str", "[", "start", ":", "end", "]", ")", "start", "=", "end", "end", "+=", "4", "(", "length", ",", ")", "=", "_struct_I", ".", "unpack", "(", "str", "[", "start", ":", "end", "]", ")", "start", "=", "end", "end", "+=", "length", "self", ".", "data", "=", "str", "[", "start", ":", "end", "]", "return", "self", "except", "struct", ".", "error", "as", "e", ":", "raise", "genpy", ".", "DeserializationError", "(", "e", ")" ]
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py#L123-L157
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/functions/supportedplatform.py
python
SupportedPlatform.calcInWizard
(self)
return self.calcInWizard_
Return a boolean indicating whether this Addin function should execute under the Function Wizard on the Excel platform.
Return a boolean indicating whether this Addin function should execute under the Function Wizard on the Excel platform.
[ "Return", "a", "boolean", "indicating", "whether", "this", "Addin", "function", "should", "execute", "under", "the", "Function", "Wizard", "on", "the", "Excel", "platform", "." ]
def calcInWizard(self): """Return a boolean indicating whether this Addin function should execute under the Function Wizard on the Excel platform.""" return self.calcInWizard_
[ "def", "calcInWizard", "(", "self", ")", ":", "return", "self", ".", "calcInWizard_" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/functions/supportedplatform.py#L68-L71
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/pyhit/pyhit.py
python
Node.__getitem__
(self, name)
return self.__hitnode.param(name)
Provides operator [] access to the parameters of this node.
Provides operator [] access to the parameters of this node.
[ "Provides", "operator", "[]", "access", "to", "the", "parameters", "of", "this", "node", "." ]
def __getitem__(self, name): """ Provides operator [] access to the parameters of this node. """ return self.__hitnode.param(name)
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "__hitnode", ".", "param", "(", "name", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/pyhit/pyhit.py#L240-L244
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/translation_helper.py
python
LifecycleTranslation.JsonLifecycleToMessage
(cls, json_txt)
Translates lifecycle JSON to an apitools message.
Translates lifecycle JSON to an apitools message.
[ "Translates", "lifecycle", "JSON", "to", "an", "apitools", "message", "." ]
def JsonLifecycleToMessage(cls, json_txt): """Translates lifecycle JSON to an apitools message.""" try: deserialized_lifecycle = json.loads(json_txt) # If lifecycle JSON is the in the following format # {'lifecycle': {'rule': ... then strip out the 'lifecycle' key # and reduce it to the following format # {'rule': ... if 'lifecycle' in deserialized_lifecycle: deserialized_lifecycle = deserialized_lifecycle['lifecycle'] lifecycle = encoding.DictToMessage( deserialized_lifecycle, apitools_messages.Bucket.LifecycleValue) return lifecycle except ValueError: CheckForXmlConfigurationAndRaise('lifecycle', json_txt)
[ "def", "JsonLifecycleToMessage", "(", "cls", ",", "json_txt", ")", ":", "try", ":", "deserialized_lifecycle", "=", "json", ".", "loads", "(", "json_txt", ")", "# If lifecycle JSON is the in the following format", "# {'lifecycle': {'rule': ... then strip out the 'lifecycle' key", "# and reduce it to the following format", "# {'rule': ...", "if", "'lifecycle'", "in", "deserialized_lifecycle", ":", "deserialized_lifecycle", "=", "deserialized_lifecycle", "[", "'lifecycle'", "]", "lifecycle", "=", "encoding", ".", "DictToMessage", "(", "deserialized_lifecycle", ",", "apitools_messages", ".", "Bucket", ".", "LifecycleValue", ")", "return", "lifecycle", "except", "ValueError", ":", "CheckForXmlConfigurationAndRaise", "(", "'lifecycle'", ",", "json_txt", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/translation_helper.py#L510-L524
i42output/neoGFX
529857e006466271f9775e1a77882c3919e1c3e1
3rdparty/freetype/freetype-2.11.0/src/tools/make_distribution_archives.py
python
is_git_dir_clean
(git_dir)
return len(out) == 0
Return True iff |git_dir| is a git directory in clean state.
Return True iff |git_dir| is a git directory in clean state.
[ "Return", "True", "iff", "|git_dir|", "is", "a", "git", "directory", "in", "clean", "state", "." ]
def is_git_dir_clean(git_dir): """Return True iff |git_dir| is a git directory in clean state.""" out = get_cmd_output(["git", "status", "--porcelain"], cwd=git_dir) return len(out) == 0
[ "def", "is_git_dir_clean", "(", "git_dir", ")", ":", "out", "=", "get_cmd_output", "(", "[", "\"git\"", ",", "\"status\"", ",", "\"--porcelain\"", "]", ",", "cwd", "=", "git_dir", ")", "return", "len", "(", "out", ")", "==", "0" ]
https://github.com/i42output/neoGFX/blob/529857e006466271f9775e1a77882c3919e1c3e1/3rdparty/freetype/freetype-2.11.0/src/tools/make_distribution_archives.py#L27-L30
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/__init__.py
python
Node.is_literal
(self)
return 1
Always pass the string representation of a Node to the command interpreter literally.
Always pass the string representation of a Node to the command interpreter literally.
[ "Always", "pass", "the", "string", "representation", "of", "a", "Node", "to", "the", "command", "interpreter", "literally", "." ]
def is_literal(self): """Always pass the string representation of a Node to the command interpreter literally.""" return 1
[ "def", "is_literal", "(", "self", ")", ":", "return", "1" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/__init__.py#L1496-L1499