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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/parsers/base_parser.py
python
ParserBase._open_handles
(self, src: FilePathOrBuffer, kwds: dict[str, Any])
Let the readers open IOHandles after they are done with their potential raises.
Let the readers open IOHandles after they are done with their potential raises.
[ "Let", "the", "readers", "open", "IOHandles", "after", "they", "are", "done", "with", "their", "potential", "raises", "." ]
def _open_handles(self, src: FilePathOrBuffer, kwds: dict[str, Any]) -> None: """ Let the readers open IOHandles after they are done with their potential raises. """ self.handles = get_handle( src, "r", encoding=kwds.get("encoding", None), compression=kwds.get("compression", None), memory_map=kwds.get("memory_map", False), storage_options=kwds.get("storage_options", None), errors=kwds.get("encoding_errors", "strict"), )
[ "def", "_open_handles", "(", "self", ",", "src", ":", "FilePathOrBuffer", ",", "kwds", ":", "dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "self", ".", "handles", "=", "get_handle", "(", "src", ",", "\"r\"", ",", "encoding", "=", "kwds", ".", "get", "(", "\"encoding\"", ",", "None", ")", ",", "compression", "=", "kwds", ".", "get", "(", "\"compression\"", ",", "None", ")", ",", "memory_map", "=", "kwds", ".", "get", "(", "\"memory_map\"", ",", "False", ")", ",", "storage_options", "=", "kwds", ".", "get", "(", "\"storage_options\"", ",", "None", ")", ",", "errors", "=", "kwds", ".", "get", "(", "\"encoding_errors\"", ",", "\"strict\"", ")", ",", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/parsers/base_parser.py#L218-L230
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/portable_server.py
python
InfoHandler.get
(self)
Handle GET request for unknown path.
Handle GET request for unknown path.
[ "Handle", "GET", "request", "for", "unknown", "path", "." ]
def get(self): """Handle GET request for unknown path.""" self.set_header("Content-Type", "text/plain") tornado.web.local_server_.LocalInfoHandler(self) self.finish()
[ "def", "get", "(", "self", ")", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"text/plain\"", ")", "tornado", ".", "web", ".", "local_server_", ".", "LocalInfoHandler", "(", "self", ")", "self", ".", "finish", "(", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/portable_server.py#L376-L380
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_funcs.py
python
has
(cls)
return getattr(cls, "__attrs_attrs__", None) is not None
Check whether *cls* is a class with ``attrs`` attributes. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :rtype: bool
Check whether *cls* is a class with ``attrs`` attributes.
[ "Check", "whether", "*", "cls", "*", "is", "a", "class", "with", "attrs", "attributes", "." ]
def has(cls): """ Check whether *cls* is a class with ``attrs`` attributes. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :rtype: bool """ return getattr(cls, "__attrs_attrs__", None) is not None
[ "def", "has", "(", "cls", ")", ":", "return", "getattr", "(", "cls", ",", "\"__attrs_attrs__\"", ",", "None", ")", "is", "not", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_funcs.py#L215-L224
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/ntpath.py
python
splitunc
(p)
return '', p
Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have an UNC part.
Split a pathname into UNC mount point and relative path specifiers.
[ "Split", "a", "pathname", "into", "UNC", "mount", "point", "and", "relative", "path", "specifiers", "." ]
def splitunc(p): """Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have an UNC part. """ if p[1:2] == ':': return '', p # Drive letter present firstTwo = p[0:2] if firstTwo == '//' or firstTwo == '\\\\': # is a UNC path: # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter # \\machine\mountpoint\directories... # directory ^^^^^^^^^^^^^^^ normp = normcase(p) index = normp.find('\\', 2) if index == -1: ##raise RuntimeError, 'illegal UNC path: "' + p + '"' return ("", p) index = normp.find('\\', index + 1) if index == -1: index = len(p) return p[:index], p[index:] return '', p
[ "def", "splitunc", "(", "p", ")", ":", "if", "p", "[", "1", ":", "2", "]", "==", "':'", ":", "return", "''", ",", "p", "# Drive letter present", "firstTwo", "=", "p", "[", "0", ":", "2", "]", "if", "firstTwo", "==", "'//'", "or", "firstTwo", "==", "'\\\\\\\\'", ":", "# is a UNC path:", "# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter", "# \\\\machine\\mountpoint\\directories...", "# directory ^^^^^^^^^^^^^^^", "normp", "=", "normcase", "(", "p", ")", "index", "=", "normp", ".", "find", "(", "'\\\\'", ",", "2", ")", "if", "index", "==", "-", "1", ":", "##raise RuntimeError, 'illegal UNC path: \"' + p + '\"'", "return", "(", "\"\"", ",", "p", ")", "index", "=", "normp", ".", "find", "(", "'\\\\'", ",", "index", "+", "1", ")", "if", "index", "==", "-", "1", ":", "index", "=", "len", "(", "p", ")", "return", "p", "[", ":", "index", "]", ",", "p", "[", "index", ":", "]", "return", "''", ",", "p" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ntpath.py#L131-L156
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py
python
accept_search
()
Accept current search query. Focus original `BufferControl` again.
Accept current search query. Focus original `BufferControl` again.
[ "Accept", "current", "search", "query", ".", "Focus", "original", "BufferControl", "again", "." ]
def accept_search() -> None: """ Accept current search query. Focus original `BufferControl` again. """ layout = get_app().layout search_control = layout.current_control target_buffer_control = layout.search_target_buffer_control from prompt_toolkit.layout.controls import BufferControl if not isinstance(search_control, BufferControl): return if target_buffer_control is None: return search_state = target_buffer_control.search_state # Update search state. if search_control.buffer.text: search_state.text = search_control.buffer.text # Apply search. target_buffer_control.buffer.apply_search( search_state, include_current_position=True ) # Add query to history of search line. search_control.buffer.append_to_history() # Stop search and focus previous control again. stop_search(target_buffer_control)
[ "def", "accept_search", "(", ")", "->", "None", ":", "layout", "=", "get_app", "(", ")", ".", "layout", "search_control", "=", "layout", ".", "current_control", "target_buffer_control", "=", "layout", ".", "search_target_buffer_control", "from", "prompt_toolkit", ".", "layout", ".", "controls", "import", "BufferControl", "if", "not", "isinstance", "(", "search_control", ",", "BufferControl", ")", ":", "return", "if", "target_buffer_control", "is", "None", ":", "return", "search_state", "=", "target_buffer_control", ".", "search_state", "# Update search state.", "if", "search_control", ".", "buffer", ".", "text", ":", "search_state", ".", "text", "=", "search_control", ".", "buffer", ".", "text", "# Apply search.", "target_buffer_control", ".", "buffer", ".", "apply_search", "(", "search_state", ",", "include_current_position", "=", "True", ")", "# Add query to history of search line.", "search_control", ".", "buffer", ".", "append_to_history", "(", ")", "# Stop search and focus previous control again.", "stop_search", "(", "target_buffer_control", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py#L186-L217
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/distributions/python/ops/onehot_categorical.py
python
OneHotCategorical.event_size
(self)
return self._event_size
Scalar `int32` tensor: the number of classes.
Scalar `int32` tensor: the number of classes.
[ "Scalar", "int32", "tensor", ":", "the", "number", "of", "classes", "." ]
def event_size(self): """Scalar `int32` tensor: the number of classes.""" return self._event_size
[ "def", "event_size", "(", "self", ")", ":", "return", "self", ".", "_event_size" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/onehot_categorical.py#L148-L150
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/subfields/core.py
python
MeshModel.get_gaussian_hyps
(self, sameGaussianParameters, mesh)
This function should return a tuple of (meanHyps, nHyps) for Gaussian parameter estimation.
This function should return a tuple of (meanHyps, nHyps) for Gaussian parameter estimation.
[ "This", "function", "should", "return", "a", "tuple", "of", "(", "meanHyps", "nHyps", ")", "for", "Gaussian", "parameter", "estimation", "." ]
def get_gaussian_hyps(self, sameGaussianParameters, mesh): """ This function should return a tuple of (meanHyps, nHyps) for Gaussian parameter estimation. """ raise NotImplementedError('A MeshModel subclass must implement the get_gaussian_hyps() function!')
[ "def", "get_gaussian_hyps", "(", "self", ",", "sameGaussianParameters", ",", "mesh", ")", ":", "raise", "NotImplementedError", "(", "'A MeshModel subclass must implement the get_gaussian_hyps() function!'", ")" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/subfields/core.py#L774-L778
tomahawk-player/tomahawk-resolvers
7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d
archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/service_reflection.py
python
_ServiceStubBuilder.__init__
(self, service_descriptor)
Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class.
Initializes an instance of the service stub class builder.
[ "Initializes", "an", "instance", "of", "the", "service", "stub", "class", "builder", "." ]
def __init__(self, service_descriptor): """Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class. """ self.descriptor = service_descriptor
[ "def", "__init__", "(", "self", ",", "service_descriptor", ")", ":", "self", ".", "descriptor", "=", "service_descriptor" ]
https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/service_reflection.py#L242-L249
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/mongo/gotools/vendor/src/github.com/smartystreets/assertions/internal/go-render/PRESUBMIT.py
python
source_file_filter
(input_api)
return lambda x: input_api.FilterSourceFile(x, white_list=wl, black_list=bl)
Returns filter that selects source code files only.
Returns filter that selects source code files only.
[ "Returns", "filter", "that", "selects", "source", "code", "files", "only", "." ]
def source_file_filter(input_api): """Returns filter that selects source code files only.""" bl = list(input_api.DEFAULT_BLACK_LIST) + [ r'.+\.pb\.go$', r'.+_string\.go$', ] wl = list(input_api.DEFAULT_WHITE_LIST) + [ r'.+\.go$', ] return lambda x: input_api.FilterSourceFile(x, white_list=wl, black_list=bl)
[ "def", "source_file_filter", "(", "input_api", ")", ":", "bl", "=", "list", "(", "input_api", ".", "DEFAULT_BLACK_LIST", ")", "+", "[", "r'.+\\.pb\\.go$'", ",", "r'.+_string\\.go$'", ",", "]", "wl", "=", "list", "(", "input_api", ".", "DEFAULT_WHITE_LIST", ")", "+", "[", "r'.+\\.go$'", ",", "]", "return", "lambda", "x", ":", "input_api", ".", "FilterSourceFile", "(", "x", ",", "white_list", "=", "wl", ",", "black_list", "=", "bl", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/mongo/gotools/vendor/src/github.com/smartystreets/assertions/internal/go-render/PRESUBMIT.py#L68-L77
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/tools/stats-viewer.py
python
UiCounter.Set
(self, value)
Updates the ui for this counter. Args: value: The value to display Returns: True if the value had changed, otherwise False. The first call always returns True.
Updates the ui for this counter.
[ "Updates", "the", "ui", "for", "this", "counter", "." ]
def Set(self, value): """Updates the ui for this counter. Args: value: The value to display Returns: True if the value had changed, otherwise False. The first call always returns True. """ if value == self.last_value: return False else: self.last_value = value self.var.set(self.format % value) return True
[ "def", "Set", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "last_value", ":", "return", "False", "else", ":", "self", ".", "last_value", "=", "value", "self", ".", "var", ".", "set", "(", "self", ".", "format", "%", "value", ")", "return", "True" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/tools/stats-viewer.py#L282-L297
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/packaging/_manylinux.py
python
_glibc_version_string_confstr
()
return version
Primary implementation of glibc_version_string using os.confstr.
Primary implementation of glibc_version_string using os.confstr.
[ "Primary", "implementation", "of", "glibc_version_string", "using", "os", ".", "confstr", "." ]
def _glibc_version_string_confstr() -> Optional[str]: """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module. # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 try: # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17". version_string = os.confstr("CS_GNU_LIBC_VERSION") assert version_string is not None _, version = version_string.split() except (AssertionError, AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version
[ "def", "_glibc_version_string_confstr", "(", ")", "->", "Optional", "[", "str", "]", ":", "# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely", "# to be broken or missing. This strategy is used in the standard library", "# platform module.", "# https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183", "try", ":", "# os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\".", "version_string", "=", "os", ".", "confstr", "(", "\"CS_GNU_LIBC_VERSION\"", ")", "assert", "version_string", "is", "not", "None", "_", ",", "version", "=", "version_string", ".", "split", "(", ")", "except", "(", "AssertionError", ",", "AttributeError", ",", "OSError", ",", "ValueError", ")", ":", "# os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...", "return", "None", "return", "version" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/packaging/_manylinux.py#L135-L151
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet._build_from_requirements
(cls, req_spec)
return ws
Build a working set from a requirement spec. Rewrites sys.path.
Build a working set from a requirement spec. Rewrites sys.path.
[ "Build", "a", "working", "set", "from", "a", "requirement", "spec", ".", "Rewrites", "sys", ".", "path", "." ]
def _build_from_requirements(cls, req_spec): """ Build a working set from a requirement spec. Rewrites sys.path. """ # try it without defaults already on sys.path # by starting with an empty path ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) # add any missing entries from sys.path for entry in sys.path: if entry not in ws.entries: ws.add_entry(entry) # then copy back to sys.path sys.path[:] = ws.entries return ws
[ "def", "_build_from_requirements", "(", "cls", ",", "req_spec", ")", ":", "# try it without defaults already on sys.path", "# by starting with an empty path", "ws", "=", "cls", "(", "[", "]", ")", "reqs", "=", "parse_requirements", "(", "req_spec", ")", "dists", "=", "ws", ".", "resolve", "(", "reqs", ",", "Environment", "(", ")", ")", "for", "dist", "in", "dists", ":", "ws", ".", "add", "(", "dist", ")", "# add any missing entries from sys.path", "for", "entry", "in", "sys", ".", "path", ":", "if", "entry", "not", "in", "ws", ".", "entries", ":", "ws", ".", "add_entry", "(", "entry", ")", "# then copy back to sys.path", "sys", ".", "path", "[", ":", "]", "=", "ws", ".", "entries", "return", "ws" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L590-L609
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py
python
removeQuotes
(s,l,t)
return t[0][1:-1]
Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
Helper parse action for removing quotation marks from parsed quoted strings.
[ "Helper", "parse", "action", "for", "removing", "quotation", "marks", "from", "parsed", "quoted", "strings", "." ]
def removeQuotes(s,l,t): """ Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] """ return t[0][1:-1]
[ "def", "removeQuotes", "(", "s", ",", "l", ",", "t", ")", ":", "return", "t", "[", "0", "]", "[", "1", ":", "-", "1", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py#L4811-L4823
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/autodiff/ad.py
python
var
(x)
return ADTerminal(x)
Creates a new variable symbol with name x.
Creates a new variable symbol with name x.
[ "Creates", "a", "new", "variable", "symbol", "with", "name", "x", "." ]
def var(x): """Creates a new variable symbol with name x.""" return ADTerminal(x)
[ "def", "var", "(", "x", ")", ":", "return", "ADTerminal", "(", "x", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/autodiff/ad.py#L973-L975
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
Symbol.shape_array
(self, *args, **kwargs)
return op.shape_array(self, *args, **kwargs)
Convenience fluent method for :py:func:`shape_array`. The arguments are the same as for :py:func:`shape_op`, with this array as data.
Convenience fluent method for :py:func:`shape_array`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "shape_array", "." ]
def shape_array(self, *args, **kwargs): """Convenience fluent method for :py:func:`shape_array`. The arguments are the same as for :py:func:`shape_op`, with this array as data. """ return op.shape_array(self, *args, **kwargs)
[ "def", "shape_array", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "shape_array", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L2165-L2171
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/benchmark/cub/csp_kp_tfs.py
python
CSPTester.map_kp_img1_to_img2_cyc
(self, vis_inds, kps1, kps2, xy_map1, xy_map2, mask1, mask2)
return transfer_kps, torch.stack([kp_transfer_error, kp_mask], dim=1)
xy_map1 --> xy_map1 256 x 256 x 2
xy_map1 --> xy_map1 256 x 256 x 2
[ "xy_map1", "--", ">", "xy_map1", "256", "x", "256", "x", "2" ]
def map_kp_img1_to_img2_cyc(self, vis_inds, kps1, kps2, xy_map1, xy_map2, mask1, mask2): img_size = self.opts.img_size kp_mask = torch.zeros([len(kps1)]).cuda() kp_mask[vis_inds] = 1 ''' xy_map1 --> xy_map1 256 x 256 x 2 ''' xy_map1 = xy_map1.permute(1,2,0) xy_map2 = xy_map2.permute(1,2,0) mask1 = (mask1 > 0.5).float() mask2 = (mask2 > 0.5).float() xy_map1 = xy_map1 + 1000*(1 -mask1).permute(1,2,0) + 1000*(1 -mask2).permute(1,2,0) distances = (xy_map1[None, : , : ,:] - kps1[:,None, None,0:2])**2 distances = distances.sum(-1) min_dist, min_indices = torch.min(distances.view(len(kps1), -1), -1) imgUV_H = xy_map1.size(0) imgUV_W = xy_map1.size(1) transfer_kps = (xy_map2[min_indices//imgUV_W, min_indices % imgUV_W, :] + 1)*0.5*img_size kps2 = (kps2 + 1) * 0.5 * img_size kp_transfer_error = torch.norm( kp_mask[:, None] * (transfer_kps.float() - kps2[:, 0:2]), dim=1) # pdb.set_trace() return transfer_kps, torch.stack([kp_transfer_error, kp_mask], dim=1)
[ "def", "map_kp_img1_to_img2_cyc", "(", "self", ",", "vis_inds", ",", "kps1", ",", "kps2", ",", "xy_map1", ",", "xy_map2", ",", "mask1", ",", "mask2", ")", ":", "img_size", "=", "self", ".", "opts", ".", "img_size", "kp_mask", "=", "torch", ".", "zeros", "(", "[", "len", "(", "kps1", ")", "]", ")", ".", "cuda", "(", ")", "kp_mask", "[", "vis_inds", "]", "=", "1", "xy_map1", "=", "xy_map1", ".", "permute", "(", "1", ",", "2", ",", "0", ")", "xy_map2", "=", "xy_map2", ".", "permute", "(", "1", ",", "2", ",", "0", ")", "mask1", "=", "(", "mask1", ">", "0.5", ")", ".", "float", "(", ")", "mask2", "=", "(", "mask2", ">", "0.5", ")", ".", "float", "(", ")", "xy_map1", "=", "xy_map1", "+", "1000", "*", "(", "1", "-", "mask1", ")", ".", "permute", "(", "1", ",", "2", ",", "0", ")", "+", "1000", "*", "(", "1", "-", "mask2", ")", ".", "permute", "(", "1", ",", "2", ",", "0", ")", "distances", "=", "(", "xy_map1", "[", "None", ",", ":", ",", ":", ",", ":", "]", "-", "kps1", "[", ":", ",", "None", ",", "None", ",", "0", ":", "2", "]", ")", "**", "2", "distances", "=", "distances", ".", "sum", "(", "-", "1", ")", "min_dist", ",", "min_indices", "=", "torch", ".", "min", "(", "distances", ".", "view", "(", "len", "(", "kps1", ")", ",", "-", "1", ")", ",", "-", "1", ")", "imgUV_H", "=", "xy_map1", ".", "size", "(", "0", ")", "imgUV_W", "=", "xy_map1", ".", "size", "(", "1", ")", "transfer_kps", "=", "(", "xy_map2", "[", "min_indices", "//", "imgUV_W", ",", "min_indices", "%", "imgUV_W", ",", ":", "]", "+", "1", ")", "*", "0.5", "*", "img_size", "kps2", "=", "(", "kps2", "+", "1", ")", "*", "0.5", "*", "img_size", "kp_transfer_error", "=", "torch", ".", "norm", "(", "kp_mask", "[", ":", ",", "None", "]", "*", "(", "transfer_kps", ".", "float", "(", ")", "-", "kps2", "[", ":", ",", "0", ":", "2", "]", ")", ",", "dim", "=", "1", ")", "# pdb.set_trace()", "return", "transfer_kps", ",", "torch", ".", "stack", "(", "[", "kp_transfer_error", ",", "kp_mask", "]", ",", "dim", "=", "1", ")" ]
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/benchmark/cub/csp_kp_tfs.py#L213-L239
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py
python
StateSpaceModel._loss_additions
(self, times, values, mode)
Add regularization during training.
Add regularization during training.
[ "Add", "regularization", "during", "training", "." ]
def _loss_additions(self, times, values, mode): """Add regularization during training.""" if mode == estimator_lib.ModeKeys.TRAIN: if (self._input_statistics is not None and self._configuration.bayesian_prior_weighting): normalization = 1. / math_ops.cast( self._input_statistics.total_observation_count, self.dtype) else: # If there is no total observation count recorded, or if we are not # doing a Bayesian prior weighting, assumes/pretends that the full # dataset size is the window size. normalization = 1. / math_ops.cast( array_ops.shape(times)[1], self.dtype) transition_contribution = ops.convert_to_tensor( self._configuration.covariance_prior_fn( self.state_transition_noise_covariance), dtype=self.dtype) if (self._configuration.use_observation_noise and self._observation_noise_covariance is not None): observation_contribution = ops.convert_to_tensor( self._configuration.covariance_prior_fn( self._observation_noise_covariance), dtype=self.dtype) regularization_sum = transition_contribution + observation_contribution else: regularization_sum = transition_contribution return -normalization * regularization_sum else: return array_ops.zeros([], dtype=self.dtype)
[ "def", "_loss_additions", "(", "self", ",", "times", ",", "values", ",", "mode", ")", ":", "if", "mode", "==", "estimator_lib", ".", "ModeKeys", ".", "TRAIN", ":", "if", "(", "self", ".", "_input_statistics", "is", "not", "None", "and", "self", ".", "_configuration", ".", "bayesian_prior_weighting", ")", ":", "normalization", "=", "1.", "/", "math_ops", ".", "cast", "(", "self", ".", "_input_statistics", ".", "total_observation_count", ",", "self", ".", "dtype", ")", "else", ":", "# If there is no total observation count recorded, or if we are not", "# doing a Bayesian prior weighting, assumes/pretends that the full", "# dataset size is the window size.", "normalization", "=", "1.", "/", "math_ops", ".", "cast", "(", "array_ops", ".", "shape", "(", "times", ")", "[", "1", "]", ",", "self", ".", "dtype", ")", "transition_contribution", "=", "ops", ".", "convert_to_tensor", "(", "self", ".", "_configuration", ".", "covariance_prior_fn", "(", "self", ".", "state_transition_noise_covariance", ")", ",", "dtype", "=", "self", ".", "dtype", ")", "if", "(", "self", ".", "_configuration", ".", "use_observation_noise", "and", "self", ".", "_observation_noise_covariance", "is", "not", "None", ")", ":", "observation_contribution", "=", "ops", ".", "convert_to_tensor", "(", "self", ".", "_configuration", ".", "covariance_prior_fn", "(", "self", ".", "_observation_noise_covariance", ")", ",", "dtype", "=", "self", ".", "dtype", ")", "regularization_sum", "=", "transition_contribution", "+", "observation_contribution", "else", ":", "regularization_sum", "=", "transition_contribution", "return", "-", "normalization", "*", "regularization_sum", "else", ":", "return", "array_ops", ".", "zeros", "(", "[", "]", ",", "dtype", "=", "self", ".", "dtype", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L613-L641
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/mpcd/collide.py
python
srd.set_params
(self, angle=None, shift=None, kT=None)
Set parameters for the SRD collision method Args: angle (float): SRD rotation angle (degrees) shift (bool): If True, perform a random shift of the underlying cell list kT (:py:mod:`hoomd.variant` or :py:obj:`float` or bool): Temperature set point for the thermostat (in energy units). If False, any set thermostat is removed and an NVE simulation is run. Examples:: srd.set_params(angle=90.) srd.set_params(shift=False) srd.set_params(angle=130., shift=True, kT=1.0) srd.set_params(kT=hoomd.data.variant.linear_interp([[0,1.0],[100,5.0]])) srd.set_params(kT=False)
Set parameters for the SRD collision method
[ "Set", "parameters", "for", "the", "SRD", "collision", "method" ]
def set_params(self, angle=None, shift=None, kT=None): """ Set parameters for the SRD collision method Args: angle (float): SRD rotation angle (degrees) shift (bool): If True, perform a random shift of the underlying cell list kT (:py:mod:`hoomd.variant` or :py:obj:`float` or bool): Temperature set point for the thermostat (in energy units). If False, any set thermostat is removed and an NVE simulation is run. Examples:: srd.set_params(angle=90.) srd.set_params(shift=False) srd.set_params(angle=130., shift=True, kT=1.0) srd.set_params(kT=hoomd.data.variant.linear_interp([[0,1.0],[100,5.0]])) srd.set_params(kT=False) """ if angle is not None: self.angle = angle self._cpp.setRotationAngle(angle * np.pi / 180.) if shift is not None: self.shift = shift self._cpp.enableGridShifting(shift) if kT is not None: if kT is False: self._cpp.unsetTemperature() self.kT = kT else: self.kT = hoomd.variant._setup_variant_input(kT) self._cpp.setTemperature(self.kT.cpp_variant)
[ "def", "set_params", "(", "self", ",", "angle", "=", "None", ",", "shift", "=", "None", ",", "kT", "=", "None", ")", ":", "if", "angle", "is", "not", "None", ":", "self", ".", "angle", "=", "angle", "self", ".", "_cpp", ".", "setRotationAngle", "(", "angle", "*", "np", ".", "pi", "/", "180.", ")", "if", "shift", "is", "not", "None", ":", "self", ".", "shift", "=", "shift", "self", ".", "_cpp", ".", "enableGridShifting", "(", "shift", ")", "if", "kT", "is", "not", "None", ":", "if", "kT", "is", "False", ":", "self", ".", "_cpp", ".", "unsetTemperature", "(", ")", "self", ".", "kT", "=", "kT", "else", ":", "self", ".", "kT", "=", "hoomd", ".", "variant", ".", "_setup_variant_input", "(", "kT", ")", "self", ".", "_cpp", ".", "setTemperature", "(", "self", ".", "kT", ".", "cpp_variant", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/mpcd/collide.py#L335-L367
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/common/dump.py
python
set_dump
(target, enabled=True)
Enable or disable dump for the target and its contents. Target should be an instance of Cell or Primitive. The default enabled status for a cell or primitive is False. Please note that this API takes effect only when the dump_mode field in dump config file is 2. See the `dump document <https://mindspore.cn/docs/programming_guide/zh-CN/master/dump_in_graph_mode.html>`_ for details. .. warning:: This is an experimental prototype that is subject to change or deletion. Note: 1. This API is only effective for GRAPH_MODE with Ascend backend. 2. When target is a cell and enabled is True, this API will the enable dump for the primitive operator members of the cell instance and its child cell instances recursively. If an operator is not a member of the cell instance, the dump flag will not be set for this operator (e.g. functional operators used directly in construct method). To make this API effective, please use self.some_op = SomeOp() in your cell's __init__ method. 3. After using set_dump(cell, True), operators in forward computation of the cell will be dumped. Most backward computation (computation generated by the grad operations) will not be dumped by design. However, due to the graph optimization, a few backward computation data will still be dumped. You can ignore the backward computation data which contains "Gradients" in their filenames. 4. This API is not designed to use in the middle of training process. If you call this API in the middle of training, it only takes effect for the later compiled graphs. If there is no new graph compilation, you will see no effect. 5. For operator SparseSoftmaxCrossEntropyWithLogits, the forward computation and backward computation use the same set of operators. So you can only see dump data from backward computation. Please note that operator SoftmaxCrossEntropyWithLogits will also use the above operator internally when initialized with sparse=True and reduction="mean". Args: target (Union[Cell, Primitive]): The Cell instance or Primitive instance to which the dump flag is set. enabled (bool): True means enable dump, False means disable dump. Default: True. Supported Platforms: ``Ascend`` Examples: >>> # Please set the dump config file and environment variable before >>> # running this example to actually get the dump data. >>> # See the document of this API for details. >>> import numpy as np >>> >>> import mindspore.nn as nn >>> import mindspore.context as context >>> from mindspore import Tensor, set_dump >>> >>> context.set_context(device_target="Ascend", mode=context.GRAPH_MODE) >>> >>> class MyNet(nn.Cell): ... def __init__(self): ... super().__init__() ... self.conv1 = nn.Conv2d(5, 6, 5, pad_mode='valid') ... self.relu1 = nn.ReLU() ... ... def construct(self, x): ... x = self.conv1(x) ... x = self.relu1(x) ... return x >>> >>> net = MyNet() >>> set_dump(net.conv1) >>> input_tensor = Tensor(np.ones([1, 5, 10, 10], dtype=np.float32)) >>> net(input_tensor)
Enable or disable dump for the target and its contents.
[ "Enable", "or", "disable", "dump", "for", "the", "target", "and", "its", "contents", "." ]
def set_dump(target, enabled=True): """ Enable or disable dump for the target and its contents. Target should be an instance of Cell or Primitive. The default enabled status for a cell or primitive is False. Please note that this API takes effect only when the dump_mode field in dump config file is 2. See the `dump document <https://mindspore.cn/docs/programming_guide/zh-CN/master/dump_in_graph_mode.html>`_ for details. .. warning:: This is an experimental prototype that is subject to change or deletion. Note: 1. This API is only effective for GRAPH_MODE with Ascend backend. 2. When target is a cell and enabled is True, this API will the enable dump for the primitive operator members of the cell instance and its child cell instances recursively. If an operator is not a member of the cell instance, the dump flag will not be set for this operator (e.g. functional operators used directly in construct method). To make this API effective, please use self.some_op = SomeOp() in your cell's __init__ method. 3. After using set_dump(cell, True), operators in forward computation of the cell will be dumped. Most backward computation (computation generated by the grad operations) will not be dumped by design. However, due to the graph optimization, a few backward computation data will still be dumped. You can ignore the backward computation data which contains "Gradients" in their filenames. 4. This API is not designed to use in the middle of training process. If you call this API in the middle of training, it only takes effect for the later compiled graphs. If there is no new graph compilation, you will see no effect. 5. For operator SparseSoftmaxCrossEntropyWithLogits, the forward computation and backward computation use the same set of operators. So you can only see dump data from backward computation. Please note that operator SoftmaxCrossEntropyWithLogits will also use the above operator internally when initialized with sparse=True and reduction="mean". Args: target (Union[Cell, Primitive]): The Cell instance or Primitive instance to which the dump flag is set. enabled (bool): True means enable dump, False means disable dump. Default: True. Supported Platforms: ``Ascend`` Examples: >>> # Please set the dump config file and environment variable before >>> # running this example to actually get the dump data. >>> # See the document of this API for details. >>> import numpy as np >>> >>> import mindspore.nn as nn >>> import mindspore.context as context >>> from mindspore import Tensor, set_dump >>> >>> context.set_context(device_target="Ascend", mode=context.GRAPH_MODE) >>> >>> class MyNet(nn.Cell): ... def __init__(self): ... super().__init__() ... self.conv1 = nn.Conv2d(5, 6, 5, pad_mode='valid') ... self.relu1 = nn.ReLU() ... ... def construct(self, x): ... x = self.conv1(x) ... x = self.relu1(x) ... return x >>> >>> net = MyNet() >>> set_dump(net.conv1) >>> input_tensor = Tensor(np.ones([1, 5, 10, 10], dtype=np.float32)) >>> net(input_tensor) """ if security.enable_security(): raise ValueError('The set_dump API is not supported, please recompile ' 'source without "-s on".') import mindspore.nn as nn # avoid circular import from mindspore.ops import Primitive if not isinstance(target, nn.Cell) and not isinstance(target, Primitive): raise ValueError(f"The \"target\" parameter must be an instance of " f"Cell or Primitive, " f"but got an instance of {type(target)}.") if not isinstance(enabled, bool): raise ValueError("The \"enabled\" parameter must be bool.") # Checking for device target and mode. current_target = context.get_context("device_target") if current_target != "Ascend": # We will not return here in case user changed device_target later. warn("Current device_target is {}, which is not supported by set_dump. " "Only Ascend device target is supported currently. " "If you have Ascend device, consider set device_target to Ascend " "before calling set_dump.".format(current_target)) current_mode = context.get_context("mode") if current_mode != context.GRAPH_MODE: # We will not return here in case user changed mode later. warn( "Current mode is PYNATIVE_MODE, which is not supported by set_dump. " "Only GRAPH_MODE is supported currently. " "Consider set mode to GRAPH_MODE " "before calling set_dump.") # The actual set dump logic. mode = "true" if enabled else "false" if isinstance(target, nn.Cell): primitives = getattr(target, "_primitives", {}) for value in primitives.values(): if value: value.add_prim_attr("dump", mode) for cell in target.cells(): set_dump(cell, enabled) return if isinstance(target, Primitive): target.add_prim_attr("dump", mode) return
[ "def", "set_dump", "(", "target", ",", "enabled", "=", "True", ")", ":", "if", "security", ".", "enable_security", "(", ")", ":", "raise", "ValueError", "(", "'The set_dump API is not supported, please recompile '", "'source without \"-s on\".'", ")", "import", "mindspore", ".", "nn", "as", "nn", "# avoid circular import", "from", "mindspore", ".", "ops", "import", "Primitive", "if", "not", "isinstance", "(", "target", ",", "nn", ".", "Cell", ")", "and", "not", "isinstance", "(", "target", ",", "Primitive", ")", ":", "raise", "ValueError", "(", "f\"The \\\"target\\\" parameter must be an instance of \"", "f\"Cell or Primitive, \"", "f\"but got an instance of {type(target)}.\"", ")", "if", "not", "isinstance", "(", "enabled", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"The \\\"enabled\\\" parameter must be bool.\"", ")", "# Checking for device target and mode.", "current_target", "=", "context", ".", "get_context", "(", "\"device_target\"", ")", "if", "current_target", "!=", "\"Ascend\"", ":", "# We will not return here in case user changed device_target later.", "warn", "(", "\"Current device_target is {}, which is not supported by set_dump. \"", "\"Only Ascend device target is supported currently. \"", "\"If you have Ascend device, consider set device_target to Ascend \"", "\"before calling set_dump.\"", ".", "format", "(", "current_target", ")", ")", "current_mode", "=", "context", ".", "get_context", "(", "\"mode\"", ")", "if", "current_mode", "!=", "context", ".", "GRAPH_MODE", ":", "# We will not return here in case user changed mode later.", "warn", "(", "\"Current mode is PYNATIVE_MODE, which is not supported by set_dump. \"", "\"Only GRAPH_MODE is supported currently. \"", "\"Consider set mode to GRAPH_MODE \"", "\"before calling set_dump.\"", ")", "# The actual set dump logic.", "mode", "=", "\"true\"", "if", "enabled", "else", "\"false\"", "if", "isinstance", "(", "target", ",", "nn", ".", "Cell", ")", ":", "primitives", "=", "getattr", "(", "target", ",", "\"_primitives\"", ",", "{", "}", ")", "for", "value", "in", "primitives", ".", "values", "(", ")", ":", "if", "value", ":", "value", ".", "add_prim_attr", "(", "\"dump\"", ",", "mode", ")", "for", "cell", "in", "target", ".", "cells", "(", ")", ":", "set_dump", "(", "cell", ",", "enabled", ")", "return", "if", "isinstance", "(", "target", ",", "Primitive", ")", ":", "target", ".", "add_prim_attr", "(", "\"dump\"", ",", "mode", ")", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/common/dump.py#L22-L143
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py
python
get_installed_distributions
(local_only=True, skip=('setuptools', 'pip', 'python'), include_editables=True, editables_only=False)
return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) ]
Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also skip virtualenv?] If ``editables`` is False, don't report editables. If ``editables_only`` is True , only report editables.
Return a list of installed Distribution objects.
[ "Return", "a", "list", "of", "installed", "Distribution", "objects", "." ]
def get_installed_distributions(local_only=True, skip=('setuptools', 'pip', 'python'), include_editables=True, editables_only=False): """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also skip virtualenv?] If ``editables`` is False, don't report editables. If ``editables_only`` is True , only report editables. """ if local_only: local_test = dist_is_local else: local_test = lambda d: True if include_editables: editable_test = lambda d: True else: editable_test = lambda d: not dist_is_editable(d) if editables_only: editables_only_test = lambda d: dist_is_editable(d) else: editables_only_test = lambda d: True return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip and editable_test(d) and editables_only_test(d) ]
[ "def", "get_installed_distributions", "(", "local_only", "=", "True", ",", "skip", "=", "(", "'setuptools'", ",", "'pip'", ",", "'python'", ")", ",", "include_editables", "=", "True", ",", "editables_only", "=", "False", ")", ":", "if", "local_only", ":", "local_test", "=", "dist_is_local", "else", ":", "local_test", "=", "lambda", "d", ":", "True", "if", "include_editables", ":", "editable_test", "=", "lambda", "d", ":", "True", "else", ":", "editable_test", "=", "lambda", "d", ":", "not", "dist_is_editable", "(", "d", ")", "if", "editables_only", ":", "editables_only_test", "=", "lambda", "d", ":", "dist_is_editable", "(", "d", ")", "else", ":", "editables_only_test", "=", "lambda", "d", ":", "True", "return", "[", "d", "for", "d", "in", "pkg_resources", ".", "working_set", "if", "local_test", "(", "d", ")", "and", "d", ".", "key", "not", "in", "skip", "and", "editable_test", "(", "d", ")", "and", "editables_only_test", "(", "d", ")", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/util.py#L350-L389
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntH.LoadXml
(self, *args)
return _snap.TIntH_LoadXml(self, *args)
LoadXml(TIntH self, PXmlTok const & XmlTok, TStr Nm="") Parameters: XmlTok: PXmlTok const & Nm: TStr const & LoadXml(TIntH self, PXmlTok const & XmlTok) Parameters: XmlTok: PXmlTok const &
LoadXml(TIntH self, PXmlTok const & XmlTok, TStr Nm="")
[ "LoadXml", "(", "TIntH", "self", "PXmlTok", "const", "&", "XmlTok", "TStr", "Nm", "=", ")" ]
def LoadXml(self, *args): """ LoadXml(TIntH self, PXmlTok const & XmlTok, TStr Nm="") Parameters: XmlTok: PXmlTok const & Nm: TStr const & LoadXml(TIntH self, PXmlTok const & XmlTok) Parameters: XmlTok: PXmlTok const & """ return _snap.TIntH_LoadXml(self, *args)
[ "def", "LoadXml", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TIntH_LoadXml", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L18329-L18343
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
_CppLintState.IncrementErrorCount
(self, category)
Bumps the module's error statistic.
Bumps the module's error statistic.
[ "Bumps", "the", "module", "s", "error", "statistic", "." ]
def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1
[ "def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "category", "=", "category", ".", "split", "(", "'/'", ")", "[", "0", "]", "if", "category", "not", "in", "self", ".", "errors_by_category", ":", "self", ".", "errors_by_category", "[", "category", "]", "=", "0", "self", ".", "errors_by_category", "[", "category", "]", "+=", "1" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L1348-L1356
intel/linux-sgx
2ee53db4e8fd25437a817612d3bcb94b66a28373
sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py
python
enclave_info.get_peak_heap_used
(self)
return peak_heap_used
Get the peak value of the heap used
Get the peak value of the heap used
[ "Get", "the", "peak", "value", "of", "the", "heap", "used" ]
def get_peak_heap_used(self): """Get the peak value of the heap used""" if self.heap_addr == 0: return -2 # read the peak_heap_used value string = read_from_memory(self.heap_addr, SIZE) if string == None: return -1 if SIZE == 4: fmt = 'I' elif SIZE == 8: fmt = "Q" peak_heap_used = struct.unpack(fmt, string)[0] return peak_heap_used
[ "def", "get_peak_heap_used", "(", "self", ")", ":", "if", "self", ".", "heap_addr", "==", "0", ":", "return", "-", "2", "# read the peak_heap_used value", "string", "=", "read_from_memory", "(", "self", ".", "heap_addr", ",", "SIZE", ")", "if", "string", "==", "None", ":", "return", "-", "1", "if", "SIZE", "==", "4", ":", "fmt", "=", "'I'", "elif", "SIZE", "==", "8", ":", "fmt", "=", "\"Q\"", "peak_heap_used", "=", "struct", ".", "unpack", "(", "fmt", ",", "string", ")", "[", "0", "]", "return", "peak_heap_used" ]
https://github.com/intel/linux-sgx/blob/2ee53db4e8fd25437a817612d3bcb94b66a28373/sdk/debugger_interface/linux/gdb-sgx-plugin/gdb_sgx_plugin.py#L178-L191
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/_lib/_version.py
python
NumpyVersion._compare_pre_release
(self, other)
return vercmp
Compare alpha/beta/rc/final.
Compare alpha/beta/rc/final.
[ "Compare", "alpha", "/", "beta", "/", "rc", "/", "final", "." ]
def _compare_pre_release(self, other): """Compare alpha/beta/rc/final.""" if self.pre_release == other.pre_release: vercmp = 0 elif self.pre_release == 'final': vercmp = 1 elif other.pre_release == 'final': vercmp = -1 elif self.pre_release > other.pre_release: vercmp = 1 else: vercmp = -1 return vercmp
[ "def", "_compare_pre_release", "(", "self", ",", "other", ")", ":", "if", "self", ".", "pre_release", "==", "other", ".", "pre_release", ":", "vercmp", "=", "0", "elif", "self", ".", "pre_release", "==", "'final'", ":", "vercmp", "=", "1", "elif", "other", ".", "pre_release", "==", "'final'", ":", "vercmp", "=", "-", "1", "elif", "self", ".", "pre_release", ">", "other", ".", "pre_release", ":", "vercmp", "=", "1", "else", ":", "vercmp", "=", "-", "1", "return", "vercmp" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/_lib/_version.py#L99-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Decimal.__ceil__
(self)
return int(self._rescale(0, ROUND_CEILING))
Return the ceiling of self, as an integer. For a finite Decimal instance self, return the least integer n such that n >= self. If self is infinite or a NaN then a Python exception is raised.
Return the ceiling of self, as an integer.
[ "Return", "the", "ceiling", "of", "self", "as", "an", "integer", "." ]
def __ceil__(self): """Return the ceiling of self, as an integer. For a finite Decimal instance self, return the least integer n such that n >= self. If self is infinite or a NaN then a Python exception is raised. """ if self._is_special: if self.is_nan(): raise ValueError("cannot round a NaN") else: raise OverflowError("cannot round an infinity") return int(self._rescale(0, ROUND_CEILING))
[ "def", "__ceil__", "(", "self", ")", ":", "if", "self", ".", "_is_special", ":", "if", "self", ".", "is_nan", "(", ")", ":", "raise", "ValueError", "(", "\"cannot round a NaN\"", ")", "else", ":", "raise", "OverflowError", "(", "\"cannot round an infinity\"", ")", "return", "int", "(", "self", ".", "_rescale", "(", "0", ",", "ROUND_CEILING", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L1907-L1920
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialposix.py
python
Serial.out_waiting
(self)
return struct.unpack('I', s)[0]
Return the number of bytes currently in the output buffer.
Return the number of bytes currently in the output buffer.
[ "Return", "the", "number", "of", "bytes", "currently", "in", "the", "output", "buffer", "." ]
def out_waiting(self): """Return the number of bytes currently in the output buffer.""" #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCOUTQ, TIOCM_zero_str) return struct.unpack('I', s)[0]
[ "def", "out_waiting", "(", "self", ")", ":", "#~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str)", "s", "=", "fcntl", ".", "ioctl", "(", "self", ".", "fd", ",", "TIOCOUTQ", ",", "TIOCM_zero_str", ")", "return", "struct", ".", "unpack", "(", "'I'", ",", "s", ")", "[", "0", "]" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialposix.py#L673-L677
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py
python
VersionConflict.with_context
(self, required_by)
return ContextualVersionConflict(*args)
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
[ "If", "required_by", "is", "non", "-", "empty", "return", "a", "version", "of", "self", "that", "is", "a", "ContextualVersionConflict", "." ]
def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args)
[ "def", "with_context", "(", "self", ",", "required_by", ")", ":", "if", "not", "required_by", ":", "return", "self", "args", "=", "self", ".", "args", "+", "(", "required_by", ",", ")", "return", "ContextualVersionConflict", "(", "*", "args", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L280-L288
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/sdk/shared_prefs.py
python
SharedPrefs.Commit
(self)
Save the current set of preferences to the device. Only actually saves if some preferences have been modified.
Save the current set of preferences to the device.
[ "Save", "the", "current", "set", "of", "preferences", "to", "the", "device", "." ]
def Commit(self): """Save the current set of preferences to the device. Only actually saves if some preferences have been modified. """ if not self.changed: return self._device.RunShellCommand( ['mkdir', '-p', posixpath.dirname(self.path)], as_root=True, check_return=True) self._device.WriteFile(self.path, str(self), as_root=True) self._device.KillAll(self.package, exact=True, as_root=True, quiet=True) self._changed = False
[ "def", "Commit", "(", "self", ")", ":", "if", "not", "self", ".", "changed", ":", "return", "self", ".", "_device", ".", "RunShellCommand", "(", "[", "'mkdir'", ",", "'-p'", ",", "posixpath", ".", "dirname", "(", "self", ".", "path", ")", "]", ",", "as_root", "=", "True", ",", "check_return", "=", "True", ")", "self", ".", "_device", ".", "WriteFile", "(", "self", ".", "path", ",", "str", "(", "self", ")", ",", "as_root", "=", "True", ")", "self", ".", "_device", ".", "KillAll", "(", "self", ".", "package", ",", "exact", "=", "True", ",", "as_root", "=", "True", ",", "quiet", "=", "True", ")", "self", ".", "_changed", "=", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/shared_prefs.py#L260-L272
google/ml-metadata
b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d
ml_metadata/metadata_store/metadata_store.py
python
MetadataStore.get_context_types
(self)
return result
Gets all context types. Returns: A list of all known ContextTypes. Raises: errors.InternalError: if query execution fails.
Gets all context types.
[ "Gets", "all", "context", "types", "." ]
def get_context_types(self) -> List[proto.ContextType]: """Gets all context types. Returns: A list of all known ContextTypes. Raises: errors.InternalError: if query execution fails. """ request = metadata_store_service_pb2.GetContextTypesRequest() response = metadata_store_service_pb2.GetContextTypesResponse() self._call('GetContextTypes', request, response) result = [] for x in response.context_types: result.append(x) return result
[ "def", "get_context_types", "(", "self", ")", "->", "List", "[", "proto", ".", "ContextType", "]", ":", "request", "=", "metadata_store_service_pb2", ".", "GetContextTypesRequest", "(", ")", "response", "=", "metadata_store_service_pb2", ".", "GetContextTypesResponse", "(", ")", "self", ".", "_call", "(", "'GetContextTypes'", ",", "request", ",", "response", ")", "result", "=", "[", "]", "for", "x", "in", "response", ".", "context_types", ":", "result", ".", "append", "(", "x", ")", "return", "result" ]
https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/metadata_store/metadata_store.py#L809-L825
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/sync_replicas_optimizer.py
python
SyncReplicasOptimizer.__init__
(self, opt, replicas_to_aggregate, variable_averages=None, variables_to_average=None, replica_id=None, total_num_replicas=0, use_locking=False, name="sync_replicas")
Construct a sync_replicas optimizer. Args: opt: The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. replicas_to_aggregate: number of replicas to aggregate for each variable update. variable_averages: Optional `ExponentialMovingAverage` object, used to maintain moving averages for the variables passed in `variables_to_average`. variables_to_average: a list of variables that need to be averaged. Only needed if variable_averages is passed in. replica_id: This is the task/worker/replica ID. Needed as index to access local_steps to check staleness. Must be in the interval: [0, total_num_replicas) total_num_replicas: Total number of tasks/workers/replicas, could be different from replicas_to_aggregate. If total_num_replicas > replicas_to_aggregate: it is backup_replicas + replicas_to_aggregate. If total_num_replicas < replicas_to_aggregate: Replicas compute multiple batches per update to variables. use_locking: If True use locks for update operation. name: string. Optional name of the returned operation.
Construct a sync_replicas optimizer.
[ "Construct", "a", "sync_replicas", "optimizer", "." ]
def __init__(self, opt, replicas_to_aggregate, variable_averages=None, variables_to_average=None, replica_id=None, total_num_replicas=0, use_locking=False, name="sync_replicas"): """Construct a sync_replicas optimizer. Args: opt: The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. replicas_to_aggregate: number of replicas to aggregate for each variable update. variable_averages: Optional `ExponentialMovingAverage` object, used to maintain moving averages for the variables passed in `variables_to_average`. variables_to_average: a list of variables that need to be averaged. Only needed if variable_averages is passed in. replica_id: This is the task/worker/replica ID. Needed as index to access local_steps to check staleness. Must be in the interval: [0, total_num_replicas) total_num_replicas: Total number of tasks/workers/replicas, could be different from replicas_to_aggregate. If total_num_replicas > replicas_to_aggregate: it is backup_replicas + replicas_to_aggregate. If total_num_replicas < replicas_to_aggregate: Replicas compute multiple batches per update to variables. use_locking: If True use locks for update operation. name: string. Optional name of the returned operation. """ if total_num_replicas == 0: total_num_replicas = replicas_to_aggregate super(SyncReplicasOptimizer, self).__init__(use_locking, name) logging.info( "SyncReplicas enabled: replicas_to_aggregate=%s; total_num_replicas=%s", replicas_to_aggregate, total_num_replicas) self._opt = opt self._replicas_to_aggregate = replicas_to_aggregate self._gradients_applied = False self._variable_averages = variable_averages self._variables_to_average = variables_to_average self._replica_id = replica_id self._total_num_replicas = total_num_replicas self._tokens_per_step = max(total_num_replicas, replicas_to_aggregate) self._global_step = None self._sync_token_queue = None # This will be executed in a queue runner and includes the synchronization # operations done by the chief. self._chief_queue_runner = None # Remember which queue is on which device for the "clear" operation. # This list contains list of the following format: (grad_queue, device). self._one_element_queue_list = [] # Sparse gradients queue has both value and index self._sparse_grad_queues_and_devs = [] # clean_up_op will be executed when the chief is about to restart. # If chief restarts, it is possible that some variables have already been # updated before and when chief comes back, these variables will not be # updated again as the workers have already computed the gradients for # them. # But chief still waits for all variables to be updated, which will hang # the training. # To avoid such hang, every time the chief is about to die, it will call # abort_op to kill the PS with the token_queue so all replicas will also # restart. # TODO(jmchen): When training restarts, the variables are restored from the # previous checkpoint. As such all the gradients in all the queues should be # removed as they are computed from potentially different variables. # Currently this is not done. self._clean_up_op = None
[ "def", "__init__", "(", "self", ",", "opt", ",", "replicas_to_aggregate", ",", "variable_averages", "=", "None", ",", "variables_to_average", "=", "None", ",", "replica_id", "=", "None", ",", "total_num_replicas", "=", "0", ",", "use_locking", "=", "False", ",", "name", "=", "\"sync_replicas\"", ")", ":", "if", "total_num_replicas", "==", "0", ":", "total_num_replicas", "=", "replicas_to_aggregate", "super", "(", "SyncReplicasOptimizer", ",", "self", ")", ".", "__init__", "(", "use_locking", ",", "name", ")", "logging", ".", "info", "(", "\"SyncReplicas enabled: replicas_to_aggregate=%s; total_num_replicas=%s\"", ",", "replicas_to_aggregate", ",", "total_num_replicas", ")", "self", ".", "_opt", "=", "opt", "self", ".", "_replicas_to_aggregate", "=", "replicas_to_aggregate", "self", ".", "_gradients_applied", "=", "False", "self", ".", "_variable_averages", "=", "variable_averages", "self", ".", "_variables_to_average", "=", "variables_to_average", "self", ".", "_replica_id", "=", "replica_id", "self", ".", "_total_num_replicas", "=", "total_num_replicas", "self", ".", "_tokens_per_step", "=", "max", "(", "total_num_replicas", ",", "replicas_to_aggregate", ")", "self", ".", "_global_step", "=", "None", "self", ".", "_sync_token_queue", "=", "None", "# This will be executed in a queue runner and includes the synchronization", "# operations done by the chief.", "self", ".", "_chief_queue_runner", "=", "None", "# Remember which queue is on which device for the \"clear\" operation.", "# This list contains list of the following format: (grad_queue, device).", "self", ".", "_one_element_queue_list", "=", "[", "]", "# Sparse gradients queue has both value and index", "self", ".", "_sparse_grad_queues_and_devs", "=", "[", "]", "# clean_up_op will be executed when the chief is about to restart.", "# If chief restarts, it is possible that some variables have already been", "# updated before and when chief comes back, these variables will not be", "# updated again as the workers have already computed the gradients for", "# them.", "# But chief still waits for all variables to be updated, which will hang", "# the training.", "# To avoid such hang, every time the chief is about to die, it will call", "# abort_op to kill the PS with the token_queue so all replicas will also", "# restart.", "# TODO(jmchen): When training restarts, the variables are restored from the", "# previous checkpoint. As such all the gradients in all the queues should be", "# removed as they are computed from potentially different variables.", "# Currently this is not done.", "self", ".", "_clean_up_op", "=", "None" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/sync_replicas_optimizer.py#L136-L211
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
xpcom/idl-parser/xpidl.py
python
IDLParser.p_productions_include
(self, p)
productions : INCLUDE productions
productions : INCLUDE productions
[ "productions", ":", "INCLUDE", "productions" ]
def p_productions_include(self, p): """productions : INCLUDE productions""" p[0] = list(p[2]) p[0].insert(0, Include(p[1], self.getLocation(p, 1)))
[ "def", "p_productions_include", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "list", "(", "p", "[", "2", "]", ")", "p", "[", "0", "]", ".", "insert", "(", "0", ",", "Include", "(", "p", "[", "1", "]", ",", "self", ".", "getLocation", "(", "p", ",", "1", ")", ")", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/xpcom/idl-parser/xpidl.py#L1104-L1107
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/compile/xop_creator.py
python
_pack
(xgraph: XGraph, node: Node, pack_name: str, packed_item: List[Any], quant_config: NndctQuantInfo)
return sub_op_pack, pack_list
pack items into stack op
pack items into stack op
[ "pack", "items", "into", "stack", "op" ]
def _pack(xgraph: XGraph, node: Node, pack_name: str, packed_item: List[Any], quant_config: NndctQuantInfo) -> Tuple[Op, List[Op]]: """ pack items into stack op """ pack_list = [] pack_input_ops: Dict[str, List[Op]] = {} for i, item in enumerate(packed_item): if isinstance(item, Tensor): pack_list.append(xgraph.get_op_by_name(item.node.name)) else: # dtype = np.int64 if isinstance(item, int) else np.float64 dtype = np.float32 const_op = xgraph.create_fixed_const_op( name=node.name + f"_{pack_name}_attr[{i}]", data=np.array([item], dtype=dtype), quant_info=quant_config) pack_list.append(const_op) pack_input_ops["input"] = pack_list attrs: Dict[str, Any] = {} attrs["axis"] = 0 sub_op_pack = xgraph.create_fixed_normal_op( node.name + f"_{pack_name}_i0", "stack", quant_config, attrs=attrs, input_ops=pack_input_ops) return sub_op_pack, pack_list
[ "def", "_pack", "(", "xgraph", ":", "XGraph", ",", "node", ":", "Node", ",", "pack_name", ":", "str", ",", "packed_item", ":", "List", "[", "Any", "]", ",", "quant_config", ":", "NndctQuantInfo", ")", "->", "Tuple", "[", "Op", ",", "List", "[", "Op", "]", "]", ":", "pack_list", "=", "[", "]", "pack_input_ops", ":", "Dict", "[", "str", ",", "List", "[", "Op", "]", "]", "=", "{", "}", "for", "i", ",", "item", "in", "enumerate", "(", "packed_item", ")", ":", "if", "isinstance", "(", "item", ",", "Tensor", ")", ":", "pack_list", ".", "append", "(", "xgraph", ".", "get_op_by_name", "(", "item", ".", "node", ".", "name", ")", ")", "else", ":", "# dtype = np.int64 if isinstance(item, int) else np.float64", "dtype", "=", "np", ".", "float32", "const_op", "=", "xgraph", ".", "create_fixed_const_op", "(", "name", "=", "node", ".", "name", "+", "f\"_{pack_name}_attr[{i}]\"", ",", "data", "=", "np", ".", "array", "(", "[", "item", "]", ",", "dtype", "=", "dtype", ")", ",", "quant_info", "=", "quant_config", ")", "pack_list", ".", "append", "(", "const_op", ")", "pack_input_ops", "[", "\"input\"", "]", "=", "pack_list", "attrs", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "attrs", "[", "\"axis\"", "]", "=", "0", "sub_op_pack", "=", "xgraph", ".", "create_fixed_normal_op", "(", "node", ".", "name", "+", "f\"_{pack_name}_i0\"", ",", "\"stack\"", ",", "quant_config", ",", "attrs", "=", "attrs", ",", "input_ops", "=", "pack_input_ops", ")", "return", "sub_op_pack", ",", "pack_list" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/compile/xop_creator.py#L92-L120
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/generator_jit/gen_libbsdf_runtime_header.py
python
eat_until
(token_set, tokens)
return eaten_tokens, [None]
eat tokens until token_kind is found and return them, handle parenthesis
eat tokens until token_kind is found and return them, handle parenthesis
[ "eat", "tokens", "until", "token_kind", "is", "found", "and", "return", "them", "handle", "parenthesis" ]
def eat_until(token_set, tokens): """eat tokens until token_kind is found and return them, handle parenthesis""" r = 0 e = 0 g = 0 a = 0 l = len(tokens) eaten_tokens = [] while l > 0: tok = tokens[0] if r == 0 and e == 0 and g == 0 and a == 0 and tok in token_set: return eaten_tokens, tokens if tok == '(': r += 1 elif tok == ')': r -= 1 elif tok == '[': e += 1 elif tok == ']': e -= 1 elif tok == '{': g += 1 elif tok == '}': g -= 1 elif tok == '[[': a += 1 elif tok == ']]': a -= 1 eaten_tokens.append(tokens[0]) tokens = tokens[1:] l -= 1 # do not return empty tokens, the parser do not like that return eaten_tokens, [None]
[ "def", "eat_until", "(", "token_set", ",", "tokens", ")", ":", "r", "=", "0", "e", "=", "0", "g", "=", "0", "a", "=", "0", "l", "=", "len", "(", "tokens", ")", "eaten_tokens", "=", "[", "]", "while", "l", ">", "0", ":", "tok", "=", "tokens", "[", "0", "]", "if", "r", "==", "0", "and", "e", "==", "0", "and", "g", "==", "0", "and", "a", "==", "0", "and", "tok", "in", "token_set", ":", "return", "eaten_tokens", ",", "tokens", "if", "tok", "==", "'('", ":", "r", "+=", "1", "elif", "tok", "==", "')'", ":", "r", "-=", "1", "elif", "tok", "==", "'['", ":", "e", "+=", "1", "elif", "tok", "==", "']'", ":", "e", "-=", "1", "elif", "tok", "==", "'{'", ":", "g", "+=", "1", "elif", "tok", "==", "'}'", ":", "g", "-=", "1", "elif", "tok", "==", "'[['", ":", "a", "+=", "1", "elif", "tok", "==", "']]'", ":", "a", "-=", "1", "eaten_tokens", ".", "append", "(", "tokens", "[", "0", "]", ")", "tokens", "=", "tokens", "[", "1", ":", "]", "l", "-=", "1", "# do not return empty tokens, the parser do not like that", "return", "eaten_tokens", ",", "[", "None", "]" ]
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/generator_jit/gen_libbsdf_runtime_header.py#L60-L93
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteActions
(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all)
Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'actions' from the gyp input.
[ "Write", "Makefile", "code", "for", "any", "actions", "from", "the", "gyp", "input", "." ]
def WriteActions(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action['action'] if self.flavor == 'mac': action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands] command = gyp.common.EncodePOSIXShellList(action_commands) if 'message' in action: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) else: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name)) if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd %s; ' % Sourceify(self.path or '.') # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:' '$(builddir)/lib.target:$$LD_LIBRARY_PATH; ' 'export LD_LIBRARY_PATH; ' '%s%s' % (name, cd_action, command)) self.WriteLn() outputs = map(self.Absolutify, outputs) # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert ' ' not in input, ( "Spaces in action input filenames not supported (%s)" % input) for output in outputs: assert ' ' not in output, ( "Spaces in action output filenames not supported (%s)" % output) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)), part_of_all=part_of_all, command=name) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = 'action_%s_outputs' % name self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs))) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn() self.WriteLn()
[ "def", "WriteActions", "(", "self", ",", "actions", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", ")", "for", "action", "in", "actions", ":", "name", "=", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "qualified_target", ",", "action", "[", "'action_name'", "]", ")", ")", "self", ".", "WriteLn", "(", "'### Rules for action \"%s\":'", "%", "action", "[", "'action_name'", "]", ")", "inputs", "=", "action", "[", "'inputs'", "]", "outputs", "=", "action", "[", "'outputs'", "]", "# Build up a list of outputs.", "# Collect the output dirs we'll need.", "dirs", "=", "set", "(", ")", "for", "out", "in", "outputs", ":", "dir", "=", "os", ".", "path", ".", "split", "(", "out", ")", "[", "0", "]", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "if", "int", "(", "action", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", "+=", "outputs", "if", "int", "(", "action", ".", "get", "(", "'process_outputs_as_mac_bundle_resources'", ",", "False", ")", ")", ":", "extra_mac_bundle_resources", "+=", "outputs", "# Write the actual command.", "action_commands", "=", "action", "[", "'action'", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "action_commands", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "command", ",", "env", ")", "for", "command", "in", "action_commands", "]", "command", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "action_commands", ")", "if", "'message'", "in", "action", ":", "self", ".", "WriteLn", "(", "'quiet_cmd_%s = ACTION %s $@'", "%", "(", "name", ",", "action", "[", "'message'", "]", ")", ")", "else", ":", "self", ".", "WriteLn", "(", "'quiet_cmd_%s = ACTION %s $@'", "%", "(", "name", ",", "name", ")", ")", "if", "len", "(", "dirs", ")", ">", "0", ":", "command", "=", "'mkdir -p %s'", "%", "' '", ".", "join", "(", "dirs", ")", "+", "'; '", "+", "command", "cd_action", "=", "'cd %s; '", "%", "Sourceify", "(", "self", ".", "path", "or", "'.'", ")", "# command and cd_action get written to a toplevel variable called", "# cmd_foo. Toplevel variables can't handle things that change per", "# makefile like $(TARGET), so hardcode the target.", "command", "=", "command", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "cd_action", "=", "cd_action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "# Set LD_LIBRARY_PATH in case the action runs an executable from this", "# build which links to shared libs from this build.", "# actions run on the host, so they should in theory only use host", "# libraries, but until everything is made cross-compile safe, also use", "# target libraries.", "# TODO(piman): when everything is cross-compile safe, remove lib.target", "self", ".", "WriteLn", "(", "'cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:'", "'$(builddir)/lib.target:$$LD_LIBRARY_PATH; '", "'export LD_LIBRARY_PATH; '", "'%s%s'", "%", "(", "name", ",", "cd_action", ",", "command", ")", ")", "self", ".", "WriteLn", "(", ")", "outputs", "=", "map", "(", "self", ".", "Absolutify", ",", "outputs", ")", "# The makefile rules are all relative to the top dir, but the gyp actions", "# are defined relative to their containing dir. This replaces the obj", "# variable for the action rule with an absolute version so that the output", "# goes in the right place.", "# Only write the 'obj' and 'builddir' rules for the \"primary\" output (:1);", "# it's superfluous for the \"extra outputs\", and this avoids accidentally", "# writing duplicate dummy rules for those outputs.", "# Same for environment.", "self", ".", "WriteLn", "(", "\"%s: obj := $(abs_obj)\"", "%", "QuoteSpaces", "(", "outputs", "[", "0", "]", ")", ")", "self", ".", "WriteLn", "(", "\"%s: builddir := $(abs_builddir)\"", "%", "QuoteSpaces", "(", "outputs", "[", "0", "]", ")", ")", "self", ".", "WriteSortedXcodeEnv", "(", "outputs", "[", "0", "]", ",", "self", ".", "GetSortedXcodeEnv", "(", ")", ")", "for", "input", "in", "inputs", ":", "assert", "' '", "not", "in", "input", ",", "(", "\"Spaces in action input filenames not supported (%s)\"", "%", "input", ")", "for", "output", "in", "outputs", ":", "assert", "' '", "not", "in", "output", ",", "(", "\"Spaces in action output filenames not supported (%s)\"", "%", "output", ")", "# See the comment in WriteCopies about expanding env vars.", "outputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "o", ",", "env", ")", "for", "o", "in", "outputs", "]", "inputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "i", ",", "env", ")", "for", "i", "in", "inputs", "]", "self", ".", "WriteDoCmd", "(", "outputs", ",", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "inputs", ")", ")", ",", "part_of_all", "=", "part_of_all", ",", "command", "=", "name", ")", "# Stuff the outputs in a variable so we can refer to them later.", "outputs_variable", "=", "'action_%s_outputs'", "%", "name", "self", ".", "WriteLn", "(", "'%s := %s'", "%", "(", "outputs_variable", ",", "' '", ".", "join", "(", "outputs", ")", ")", ")", "extra_outputs", ".", "append", "(", "'$(%s)'", "%", "outputs_variable", ")", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py#L835-L932
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/ISISDirecInelasticConfig.py
python
MantidConfigDirectInelastic.get_data_folder_name
(self, instr, cycle_ID)
return folder
Method to generate a data folder from instrument name and the cycle start date (cycle ID) The agreement on the naming as currently in ISIS: e.g: /archive/NDXMERLIN/Instrument/data/cycle_08_1 Note: will fail if cycle numbers ever become a 2-digit numbers e.g. cycle_22_10
Method to generate a data folder from instrument name and the cycle start date (cycle ID) The agreement on the naming as currently in ISIS: e.g: /archive/NDXMERLIN/Instrument/data/cycle_08_1
[ "Method", "to", "generate", "a", "data", "folder", "from", "instrument", "name", "and", "the", "cycle", "start", "date", "(", "cycle", "ID", ")", "The", "agreement", "on", "the", "naming", "as", "currently", "in", "ISIS", ":", "e", ".", "g", ":", "/", "archive", "/", "NDXMERLIN", "/", "Instrument", "/", "data", "/", "cycle_08_1" ]
def get_data_folder_name(self, instr, cycle_ID): """Method to generate a data folder from instrument name and the cycle start date (cycle ID) The agreement on the naming as currently in ISIS: e.g: /archive/NDXMERLIN/Instrument/data/cycle_08_1 Note: will fail if cycle numbers ever become a 2-digit numbers e.g. cycle_22_10 """ # cycle folder have short form without leading numbers cycle_fold_n = int(cycle_ID[0]) - 2000 folder = os.path.join(self._root_data_folder, 'NDX' + instr.upper(), "Instrument/data/cycle_{0:02}_{1}".format(cycle_fold_n, str(cycle_ID[1][0]))) return folder
[ "def", "get_data_folder_name", "(", "self", ",", "instr", ",", "cycle_ID", ")", ":", "# cycle folder have short form without leading numbers", "cycle_fold_n", "=", "int", "(", "cycle_ID", "[", "0", "]", ")", "-", "2000", "folder", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_root_data_folder", ",", "'NDX'", "+", "instr", ".", "upper", "(", ")", ",", "\"Instrument/data/cycle_{0:02}_{1}\"", ".", "format", "(", "cycle_fold_n", ",", "str", "(", "cycle_ID", "[", "1", "]", "[", "0", "]", ")", ")", ")", "return", "folder" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py#L695-L707
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/ceph-volume/ceph_volume/util/lsmdisk.py
python
LSMDisk.led_ident_state
(self)
return "Unsupported"
Query a disks IDENT LED state to discover when it is On, Off or Unknown (str)
Query a disks IDENT LED state to discover when it is On, Off or Unknown (str)
[ "Query", "a", "disks", "IDENT", "LED", "state", "to", "discover", "when", "it", "is", "On", "Off", "or", "Unknown", "(", "str", ")" ]
def led_ident_state(self): """Query a disks IDENT LED state to discover when it is On, Off or Unknown (str)""" if self.led_status == 1: return "Unsupported" if self.led_status & lsm_Disk.LED_STATUS_IDENT_ON == lsm_Disk.LED_STATUS_IDENT_ON: return "On" elif self.led_status & lsm_Disk.LED_STATUS_IDENT_OFF == lsm_Disk.LED_STATUS_IDENT_OFF: return "Off" elif self.led_status & lsm_Disk.LED_STATUS_IDENT_UNKNOWN == lsm_Disk.LED_STATUS_IDENT_UNKNOWN: return "Unknown" return "Unsupported"
[ "def", "led_ident_state", "(", "self", ")", ":", "if", "self", ".", "led_status", "==", "1", ":", "return", "\"Unsupported\"", "if", "self", ".", "led_status", "&", "lsm_Disk", ".", "LED_STATUS_IDENT_ON", "==", "lsm_Disk", ".", "LED_STATUS_IDENT_ON", ":", "return", "\"On\"", "elif", "self", ".", "led_status", "&", "lsm_Disk", ".", "LED_STATUS_IDENT_OFF", "==", "lsm_Disk", ".", "LED_STATUS_IDENT_OFF", ":", "return", "\"Off\"", "elif", "self", ".", "led_status", "&", "lsm_Disk", ".", "LED_STATUS_IDENT_UNKNOWN", "==", "lsm_Disk", ".", "LED_STATUS_IDENT_UNKNOWN", ":", "return", "\"Unknown\"", "return", "\"Unsupported\"" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/util/lsmdisk.py#L91-L102
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
caffe-fast-rcnn/scripts/cpp_lint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "search", "(", "s", ")" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/scripts/cpp_lint.py#L547-L551
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
Path.__init
(self, path, absolute, virtual, volume)
Build a path. path -- The path, as a string or an other Path.
Build a path.
[ "Build", "a", "path", "." ]
def __init(self, path, absolute, virtual, volume): """Build a path. path -- The path, as a string or an other Path. """ self.__absolute = absolute self.__canonized = None self.__path = path self.__str = None self.__virtual = virtual self.__volume = volume self.__saved_cwd = []
[ "def", "__init", "(", "self", ",", "path", ",", "absolute", ",", "virtual", ",", "volume", ")", ":", "self", ".", "__absolute", "=", "absolute", "self", ".", "__canonized", "=", "None", "self", ".", "__path", "=", "path", "self", ".", "__str", "=", "None", "self", ".", "__virtual", "=", "virtual", "self", ".", "__volume", "=", "volume", "self", ".", "__saved_cwd", "=", "[", "]" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L589-L600
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/more-itertools/py3/more_itertools/more.py
python
sample
(iterable, k, weights=None)
Return a *k*-length list of elements chosen (without replacement) from the *iterable*. Like :func:`random.sample`, but works on iterables of unknown length. >>> iterable = range(100) >>> sample(iterable, 5) # doctest: +SKIP [81, 60, 96, 16, 4] An iterable with *weights* may also be given: >>> iterable = range(100) >>> weights = (i * i + 1 for i in range(100)) >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP [79, 67, 74, 66, 78] The algorithm can also be used to generate weighted random permutations. The relative weight of each item determines the probability that it appears late in the permutation. >>> data = "abcdefgh" >>> weights = range(1, len(data) + 1) >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']
Return a *k*-length list of elements chosen (without replacement) from the *iterable*. Like :func:`random.sample`, but works on iterables of unknown length.
[ "Return", "a", "*", "k", "*", "-", "length", "list", "of", "elements", "chosen", "(", "without", "replacement", ")", "from", "the", "*", "iterable", "*", ".", "Like", ":", "func", ":", "random", ".", "sample", "but", "works", "on", "iterables", "of", "unknown", "length", "." ]
def sample(iterable, k, weights=None): """Return a *k*-length list of elements chosen (without replacement) from the *iterable*. Like :func:`random.sample`, but works on iterables of unknown length. >>> iterable = range(100) >>> sample(iterable, 5) # doctest: +SKIP [81, 60, 96, 16, 4] An iterable with *weights* may also be given: >>> iterable = range(100) >>> weights = (i * i + 1 for i in range(100)) >>> sampled = sample(iterable, 5, weights=weights) # doctest: +SKIP [79, 67, 74, 66, 78] The algorithm can also be used to generate weighted random permutations. The relative weight of each item determines the probability that it appears late in the permutation. >>> data = "abcdefgh" >>> weights = range(1, len(data) + 1) >>> sample(data, k=len(data), weights=weights) # doctest: +SKIP ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f'] """ if k == 0: return [] iterable = iter(iterable) if weights is None: return _sample_unweighted(iterable, k) else: weights = iter(weights) return _sample_weighted(iterable, k, weights)
[ "def", "sample", "(", "iterable", ",", "k", ",", "weights", "=", "None", ")", ":", "if", "k", "==", "0", ":", "return", "[", "]", "iterable", "=", "iter", "(", "iterable", ")", "if", "weights", "is", "None", ":", "return", "_sample_unweighted", "(", "iterable", ",", "k", ")", "else", ":", "weights", "=", "iter", "(", "weights", ")", "return", "_sample_weighted", "(", "iterable", ",", "k", ",", "weights", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/more.py#L3535-L3568
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/six.py
python
with_metaclass
(meta, *bases)
return type.__new__(metaclass, 'temporary_class', (), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "meta", ")", ":", "def", "__new__", "(", "cls", ",", "name", ",", "this_bases", ",", "d", ")", ":", "return", "meta", "(", "name", ",", "bases", ",", "d", ")", "return", "type", ".", "__new__", "(", "metaclass", ",", "'temporary_class'", ",", "(", ")", ",", "{", "}", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/six.py#L800-L809
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py
python
easy_install.create_home_path
(self)
Create directories under ~.
Create directories under ~.
[ "Create", "directories", "under", "~", "." ]
def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in six.iteritems(self.config_vars): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700)
[ "def", "create_home_path", "(", "self", ")", ":", "if", "not", "self", ".", "user", ":", "return", "home", "=", "convert_path", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ")", "for", "name", ",", "path", "in", "six", ".", "iteritems", "(", "self", ".", "config_vars", ")", ":", "if", "path", ".", "startswith", "(", "home", ")", "and", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "self", ".", "debug_print", "(", "\"os.makedirs('%s', 0o700)\"", "%", "path", ")", "os", ".", "makedirs", "(", "path", ",", "0o700", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py#L1352-L1360
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/dep_extract.py
python
DependencyExtractor.expand_symlinks
(self, deps)
return expanded
ldd will often point to symlinks. Return a list including any symlink in the specified dependency list as well as whatever it's pointing to, recursively.
ldd will often point to symlinks. Return a list including any symlink in the specified dependency list as well as whatever it's pointing to, recursively.
[ "ldd", "will", "often", "point", "to", "symlinks", ".", "Return", "a", "list", "including", "any", "symlink", "in", "the", "specified", "dependency", "list", "as", "well", "as", "whatever", "it", "s", "pointing", "to", "recursively", "." ]
def expand_symlinks(self, deps): """ ldd will often point to symlinks. Return a list including any symlink in the specified dependency list as well as whatever it's pointing to, recursively. """ expanded = [] for path in deps: expanded.append(path) while os.path.islink(path): # TODO(mpercy): os.readlink() can return an absolute path. Should we more carefully handle # the path concatenation here? path = os.path.join(os.path.dirname(path), os.readlink(path)) expanded.append(path) return expanded
[ "def", "expand_symlinks", "(", "self", ",", "deps", ")", ":", "expanded", "=", "[", "]", "for", "path", "in", "deps", ":", "expanded", ".", "append", "(", "path", ")", "while", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "# TODO(mpercy): os.readlink() can return an absolute path. Should we more carefully handle", "# the path concatenation here?", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "os", ".", "readlink", "(", "path", ")", ")", "expanded", ".", "append", "(", "path", ")", "return", "expanded" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/dep_extract.py#L63-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/ops.py
python
_get_same_shape_values
( lblk: Block, rblk: Block, left_ea: bool, right_ea: bool )
return lvals, rvals
Slice lblk.values to align with rblk. Squeeze if we have EAs.
Slice lblk.values to align with rblk. Squeeze if we have EAs.
[ "Slice", "lblk", ".", "values", "to", "align", "with", "rblk", ".", "Squeeze", "if", "we", "have", "EAs", "." ]
def _get_same_shape_values( lblk: Block, rblk: Block, left_ea: bool, right_ea: bool ) -> tuple[ArrayLike, ArrayLike]: """ Slice lblk.values to align with rblk. Squeeze if we have EAs. """ lvals = lblk.values rvals = rblk.values # Require that the indexing into lvals be slice-like assert rblk.mgr_locs.is_slice_like, rblk.mgr_locs # TODO(EA2D): with 2D EAs only this first clause would be needed if not (left_ea or right_ea): # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray, # ExtensionArray]"; expected type "Union[int, slice, ndarray]" lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index] assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif left_ea and right_ea: assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif right_ea: # lvals are 2D, rvals are 1D # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray, # ExtensionArray]"; expected type "Union[int, slice, ndarray]" lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index] assert lvals.shape[0] == 1, lvals.shape # error: Invalid index type "Tuple[int, slice]" for "Union[Any, # ExtensionArray]"; expected type "Union[int, slice, ndarray]" lvals = lvals[0, :] # type: ignore[index] else: # lvals are 1D, rvals are 2D assert rvals.shape[0] == 1, rvals.shape # error: Invalid index type "Tuple[int, slice]" for "Union[ndarray, # ExtensionArray]"; expected type "Union[int, slice, ndarray]" rvals = rvals[0, :] # type: ignore[index] return lvals, rvals
[ "def", "_get_same_shape_values", "(", "lblk", ":", "Block", ",", "rblk", ":", "Block", ",", "left_ea", ":", "bool", ",", "right_ea", ":", "bool", ")", "->", "tuple", "[", "ArrayLike", ",", "ArrayLike", "]", ":", "lvals", "=", "lblk", ".", "values", "rvals", "=", "rblk", ".", "values", "# Require that the indexing into lvals be slice-like", "assert", "rblk", ".", "mgr_locs", ".", "is_slice_like", ",", "rblk", ".", "mgr_locs", "# TODO(EA2D): with 2D EAs only this first clause would be needed", "if", "not", "(", "left_ea", "or", "right_ea", ")", ":", "# error: Invalid index type \"Tuple[Any, slice]\" for \"Union[ndarray,", "# ExtensionArray]\"; expected type \"Union[int, slice, ndarray]\"", "lvals", "=", "lvals", "[", "rblk", ".", "mgr_locs", ".", "indexer", ",", ":", "]", "# type: ignore[index]", "assert", "lvals", ".", "shape", "==", "rvals", ".", "shape", ",", "(", "lvals", ".", "shape", ",", "rvals", ".", "shape", ")", "elif", "left_ea", "and", "right_ea", ":", "assert", "lvals", ".", "shape", "==", "rvals", ".", "shape", ",", "(", "lvals", ".", "shape", ",", "rvals", ".", "shape", ")", "elif", "right_ea", ":", "# lvals are 2D, rvals are 1D", "# error: Invalid index type \"Tuple[Any, slice]\" for \"Union[ndarray,", "# ExtensionArray]\"; expected type \"Union[int, slice, ndarray]\"", "lvals", "=", "lvals", "[", "rblk", ".", "mgr_locs", ".", "indexer", ",", ":", "]", "# type: ignore[index]", "assert", "lvals", ".", "shape", "[", "0", "]", "==", "1", ",", "lvals", ".", "shape", "# error: Invalid index type \"Tuple[int, slice]\" for \"Union[Any,", "# ExtensionArray]\"; expected type \"Union[int, slice, ndarray]\"", "lvals", "=", "lvals", "[", "0", ",", ":", "]", "# type: ignore[index]", "else", ":", "# lvals are 1D, rvals are 2D", "assert", "rvals", ".", "shape", "[", "0", "]", "==", "1", ",", "rvals", ".", "shape", "# error: Invalid index type \"Tuple[int, slice]\" for \"Union[ndarray,", "# ExtensionArray]\"; expected type \"Union[int, slice, ndarray]\"", "rvals", "=", "rvals", "[", "0", ",", ":", "]", "# type: ignore[index]", "return", "lvals", ",", "rvals" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/ops.py#L95-L132
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py
python
validate_per_replica_inputs
(distribution_strategy, x)
return x_values_list
Validates PerReplica dataset input list. Args: distribution_strategy: The current DistributionStrategy used to call `fit`, `evaluate` and `predict`. x: A list of PerReplica objects that represent the input or target values. Returns: List containing the first element of each of the PerReplica objects in the input list. Raises: ValueError: If any of the objects in the `per_replica_list` is not a tensor.
Validates PerReplica dataset input list.
[ "Validates", "PerReplica", "dataset", "input", "list", "." ]
def validate_per_replica_inputs(distribution_strategy, x): """Validates PerReplica dataset input list. Args: distribution_strategy: The current DistributionStrategy used to call `fit`, `evaluate` and `predict`. x: A list of PerReplica objects that represent the input or target values. Returns: List containing the first element of each of the PerReplica objects in the input list. Raises: ValueError: If any of the objects in the `per_replica_list` is not a tensor. """ # Convert the inputs and targets into a list of PerReplica objects. per_replica_list = nest.flatten(x, expand_composites=True) x_values_list = [] for x in per_replica_list: if not tensor_util.is_tensor(x): raise ValueError('Dataset input to the model should be tensors instead ' 'they are of type {}'.format(type(x))) # At this point both x and y contain tensors in the `DistributedValues` # structure. x_values = distribution_strategy.unwrap(x) if not context.executing_eagerly(): # Validate that the shape and dtype of all the elements in x are the same. validate_all_tensor_shapes(x, x_values) validate_all_tensor_types(x, x_values) x_values_list.append(x_values[0]) return x_values_list
[ "def", "validate_per_replica_inputs", "(", "distribution_strategy", ",", "x", ")", ":", "# Convert the inputs and targets into a list of PerReplica objects.", "per_replica_list", "=", "nest", ".", "flatten", "(", "x", ",", "expand_composites", "=", "True", ")", "x_values_list", "=", "[", "]", "for", "x", "in", "per_replica_list", ":", "if", "not", "tensor_util", ".", "is_tensor", "(", "x", ")", ":", "raise", "ValueError", "(", "'Dataset input to the model should be tensors instead '", "'they are of type {}'", ".", "format", "(", "type", "(", "x", ")", ")", ")", "# At this point both x and y contain tensors in the `DistributedValues`", "# structure.", "x_values", "=", "distribution_strategy", ".", "unwrap", "(", "x", ")", "if", "not", "context", ".", "executing_eagerly", "(", ")", ":", "# Validate that the shape and dtype of all the elements in x are the same.", "validate_all_tensor_shapes", "(", "x", ",", "x_values", ")", "validate_all_tensor_types", "(", "x", ",", "x_values", ")", "x_values_list", ".", "append", "(", "x_values", "[", "0", "]", ")", "return", "x_values_list" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py#L325-L360
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/optimizer.py
python
Optimizer.__init__
(self, use_locking, name)
Create a new Optimizer. This must be called by the constructors of subclasses. Args: use_locking: Bool. If True apply use locks to prevent concurrent updates to variables. name: A non-empty string. The name to use for accumulators created for the optimizer. Raises: ValueError: If name is malformed.
Create a new Optimizer.
[ "Create", "a", "new", "Optimizer", "." ]
def __init__(self, use_locking, name): """Create a new Optimizer. This must be called by the constructors of subclasses. Args: use_locking: Bool. If True apply use locks to prevent concurrent updates to variables. name: A non-empty string. The name to use for accumulators created for the optimizer. Raises: ValueError: If name is malformed. """ if not name: raise ValueError("Must specify the optimizer name") self._use_locking = use_locking self._name = name # Dictionary of slots. # {slot_name : { variable_to_train: slot_for_the_variable, ...}, ... } self._slots = {}
[ "def", "__init__", "(", "self", ",", "use_locking", ",", "name", ")", ":", "if", "not", "name", ":", "raise", "ValueError", "(", "\"Must specify the optimizer name\"", ")", "self", ".", "_use_locking", "=", "use_locking", "self", ".", "_name", "=", "name", "# Dictionary of slots.", "# {slot_name : { variable_to_train: slot_for_the_variable, ...}, ... }", "self", ".", "_slots", "=", "{", "}" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/optimizer.py#L133-L153
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
CollapsiblePaneEvent.SetCollapsed
(*args, **kwargs)
return _controls_.CollapsiblePaneEvent_SetCollapsed(*args, **kwargs)
SetCollapsed(self, bool c)
SetCollapsed(self, bool c)
[ "SetCollapsed", "(", "self", "bool", "c", ")" ]
def SetCollapsed(*args, **kwargs): """SetCollapsed(self, bool c)""" return _controls_.CollapsiblePaneEvent_SetCollapsed(*args, **kwargs)
[ "def", "SetCollapsed", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "CollapsiblePaneEvent_SetCollapsed", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7410-L7412
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
VListBox.GetFirstSelected
(*args, **kwargs)
return _windows_.VListBox_GetFirstSelected(*args, **kwargs)
GetFirstSelected(self) -> PyObject
GetFirstSelected(self) -> PyObject
[ "GetFirstSelected", "(", "self", ")", "-", ">", "PyObject" ]
def GetFirstSelected(*args, **kwargs): """GetFirstSelected(self) -> PyObject""" return _windows_.VListBox_GetFirstSelected(*args, **kwargs)
[ "def", "GetFirstSelected", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VListBox_GetFirstSelected", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L2628-L2630
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/MSVSSettings.py
python
ConvertVCMacrosToMSBuild
(s)
return s
Convert the the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed.
Convert the the MSVS macros found in the string to the MSBuild equivalent.
[ "Convert", "the", "the", "MSVS", "macros", "found", "in", "the", "string", "to", "the", "MSBuild", "equivalent", "." ]
def ConvertVCMacrosToMSBuild(s): """Convert the the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed. """ if '$' in s: replace_map = { '$(ConfigurationName)': '$(Configuration)', '$(InputDir)': '%(RootDir)%(Directory)', '$(InputExt)': '%(Extension)', '$(InputFileName)': '%(Filename)%(Extension)', '$(InputName)': '%(Filename)', '$(InputPath)': '%(FullPath)', '$(ParentName)': '$(ProjectFileName)', '$(PlatformName)': '$(Platform)', '$(SafeInputName)': '%(Filename)', } for old, new in replace_map.iteritems(): s = s.replace(old, new) s = FixVCMacroSlashes(s) return s
[ "def", "ConvertVCMacrosToMSBuild", "(", "s", ")", ":", "if", "'$'", "in", "s", ":", "replace_map", "=", "{", "'$(ConfigurationName)'", ":", "'$(Configuration)'", ",", "'$(InputDir)'", ":", "'%(RootDir)%(Directory)'", ",", "'$(InputExt)'", ":", "'%(Extension)'", ",", "'$(InputFileName)'", ":", "'%(Filename)%(Extension)'", ",", "'$(InputName)'", ":", "'%(Filename)'", ",", "'$(InputPath)'", ":", "'%(FullPath)'", ",", "'$(ParentName)'", ":", "'$(ProjectFileName)'", ",", "'$(PlatformName)'", ":", "'$(Platform)'", ",", "'$(SafeInputName)'", ":", "'%(Filename)'", ",", "}", "for", "old", ",", "new", "in", "replace_map", ".", "iteritems", "(", ")", ":", "s", "=", "s", ".", "replace", "(", "old", ",", "new", ")", "s", "=", "FixVCMacroSlashes", "(", "s", ")", "return", "s" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/MSVSSettings.py#L383-L403
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/BASIC/basiclex.py
python
t_ID
(t)
return t
r'[A-Z][A-Z0-9]*
r'[A-Z][A-Z0-9]*
[ "r", "[", "A", "-", "Z", "]", "[", "A", "-", "Z0", "-", "9", "]", "*" ]
def t_ID(t): r'[A-Z][A-Z0-9]*' if t.value in keywords: t.type = t.value return t
[ "def", "t_ID", "(", "t", ")", ":", "if", "t", ".", "value", "in", "keywords", ":", "t", ".", "type", "=", "t", ".", "value", "return", "t" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basiclex.py#L23-L27
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/uorb_graph/create.py
python
Graph._generate_print_lists
(self, use_topic_pubsub_union, merge_depends)
generate the set of scopes (modules + libraries) and topics to print to output
generate the set of scopes (modules + libraries) and topics to print to output
[ "generate", "the", "set", "of", "scopes", "(", "modules", "+", "libraries", ")", "and", "topics", "to", "print", "to", "output" ]
def _generate_print_lists(self, use_topic_pubsub_union, merge_depends): """ generate the set of scopes (modules + libraries) and topics to print to output """ subscribed_topics = set() published_topics = set() ambiguous_topics = set() # gather all found scopes: all_scopes = { **self._found_libraries, **self._found_modules } if 0 == len(self._scope_whitelist): select_scopes = self._found_modules else: select_scopes = {} for scope_name in self._scope_whitelist: if scope_name in all_scopes: select_scopes[scope_name] = all_scopes[scope_name] if not isinstance(select_scopes, dict) or 0 == len(select_scopes): log.error("!! No requested modules not found -- exiting.") sys.exit(0) log.debug('### Condensing found topics: scope -> total') for name,scope in select_scopes.items(): log.debug(' # Scope: '+ name ) log.debug(' ## Subs: ' + str(len(scope.subscriptions))) for topic in sorted(scope.subscriptions): log.debug(' - ' + topic) subscribed_topics.add(topic) log.debug(' ## Pubs: ' + str(len(scope.publications))) for topic in sorted(scope.publications): log.debug(' - ' + topic ) published_topics.add(topic) scope.reduce_ambiguities() log.debug(' ## Ambiguities: ' + str(len(scope.ambiguities))) for topic in sorted(scope.ambiguities): log.debug(' - ' + topic ) ambiguous_topics.add(topic) # filter modules iff they have at least a subscription or a publication scopes_with_topic = {} for name,scope in select_scopes.items(): if not scope.is_empty(): scopes_with_topic[name] = scope self._print_ambiguities = ambiguous_topics if use_topic_pubsub_union: self._print_topics = subscribed_topics | published_topics self._print_scopes = scopes_with_topic else: self._print_topics = subscribed_topics & published_topics # cull scopes to only those that pub or sub to a topic that has both intersect_scopes = {} for name,scope in scopes_with_topic.items(): all_scope_topics = scope.publications | scope.subscriptions for topic in all_scope_topics: if topic in self._print_topics: intersect_scopes[scope.name] = scope break self._print_scopes = intersect_scopes
[ "def", "_generate_print_lists", "(", "self", ",", "use_topic_pubsub_union", ",", "merge_depends", ")", ":", "subscribed_topics", "=", "set", "(", ")", "published_topics", "=", "set", "(", ")", "ambiguous_topics", "=", "set", "(", ")", "# gather all found scopes:", "all_scopes", "=", "{", "*", "*", "self", ".", "_found_libraries", ",", "*", "*", "self", ".", "_found_modules", "}", "if", "0", "==", "len", "(", "self", ".", "_scope_whitelist", ")", ":", "select_scopes", "=", "self", ".", "_found_modules", "else", ":", "select_scopes", "=", "{", "}", "for", "scope_name", "in", "self", ".", "_scope_whitelist", ":", "if", "scope_name", "in", "all_scopes", ":", "select_scopes", "[", "scope_name", "]", "=", "all_scopes", "[", "scope_name", "]", "if", "not", "isinstance", "(", "select_scopes", ",", "dict", ")", "or", "0", "==", "len", "(", "select_scopes", ")", ":", "log", ".", "error", "(", "\"!! No requested modules not found -- exiting.\"", ")", "sys", ".", "exit", "(", "0", ")", "log", ".", "debug", "(", "'### Condensing found topics: scope -> total'", ")", "for", "name", ",", "scope", "in", "select_scopes", ".", "items", "(", ")", ":", "log", ".", "debug", "(", "' # Scope: '", "+", "name", ")", "log", ".", "debug", "(", "' ## Subs: '", "+", "str", "(", "len", "(", "scope", ".", "subscriptions", ")", ")", ")", "for", "topic", "in", "sorted", "(", "scope", ".", "subscriptions", ")", ":", "log", ".", "debug", "(", "' - '", "+", "topic", ")", "subscribed_topics", ".", "add", "(", "topic", ")", "log", ".", "debug", "(", "' ## Pubs: '", "+", "str", "(", "len", "(", "scope", ".", "publications", ")", ")", ")", "for", "topic", "in", "sorted", "(", "scope", ".", "publications", ")", ":", "log", ".", "debug", "(", "' - '", "+", "topic", ")", "published_topics", ".", "add", "(", "topic", ")", "scope", ".", "reduce_ambiguities", "(", ")", "log", ".", "debug", "(", "' ## Ambiguities: '", "+", "str", "(", "len", "(", "scope", ".", "ambiguities", ")", ")", ")", "for", "topic", "in", "sorted", "(", "scope", ".", "ambiguities", ")", ":", "log", ".", "debug", "(", "' - '", "+", "topic", ")", "ambiguous_topics", ".", "add", "(", "topic", ")", "# filter modules iff they have at least a subscription or a publication", "scopes_with_topic", "=", "{", "}", "for", "name", ",", "scope", "in", "select_scopes", ".", "items", "(", ")", ":", "if", "not", "scope", ".", "is_empty", "(", ")", ":", "scopes_with_topic", "[", "name", "]", "=", "scope", "self", ".", "_print_ambiguities", "=", "ambiguous_topics", "if", "use_topic_pubsub_union", ":", "self", ".", "_print_topics", "=", "subscribed_topics", "|", "published_topics", "self", ".", "_print_scopes", "=", "scopes_with_topic", "else", ":", "self", ".", "_print_topics", "=", "subscribed_topics", "&", "published_topics", "# cull scopes to only those that pub or sub to a topic that has both", "intersect_scopes", "=", "{", "}", "for", "name", ",", "scope", "in", "scopes_with_topic", ".", "items", "(", ")", ":", "all_scope_topics", "=", "scope", ".", "publications", "|", "scope", ".", "subscriptions", "for", "topic", "in", "all_scope_topics", ":", "if", "topic", "in", "self", ".", "_print_topics", ":", "intersect_scopes", "[", "scope", ".", "name", "]", "=", "scope", "break", "self", ".", "_print_scopes", "=", "intersect_scopes" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/uorb_graph/create.py#L331-L394
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/build_tools/buildbot_common.py
python
MakeDir
(dst)
Create the path including all parent directories as needed.
Create the path including all parent directories as needed.
[ "Create", "the", "path", "including", "all", "parent", "directories", "as", "needed", "." ]
def MakeDir(dst): """Create the path including all parent directories as needed.""" print 'mkdir -p ' + dst oshelpers.Mkdir(['-p', dst])
[ "def", "MakeDir", "(", "dst", ")", ":", "print", "'mkdir -p '", "+", "dst", "oshelpers", ".", "Mkdir", "(", "[", "'-p'", ",", "dst", "]", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/buildbot_common.py#L161-L164
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlReg.regexpExec
(self, content)
return ret
Check if the regular expression generates the value
Check if the regular expression generates the value
[ "Check", "if", "the", "regular", "expression", "generates", "the", "value" ]
def regexpExec(self, content): """Check if the regular expression generates the value """ ret = libxml2mod.xmlRegexpExec(self._o, content) return ret
[ "def", "regexpExec", "(", "self", ",", "content", ")", ":", "ret", "=", "libxml2mod", ".", "xmlRegexpExec", "(", "self", ".", "_o", ",", "content", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L6200-L6203
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
Mailbox.keys
(self)
return list(self.iterkeys())
Return a list of keys.
Return a list of keys.
[ "Return", "a", "list", "of", "keys", "." ]
def keys(self): """Return a list of keys.""" return list(self.iterkeys())
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iterkeys", "(", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L102-L104
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/linalg/matfuncs.py
python
expm
(A)
return scipy.sparse.linalg.expm(A)
Compute the matrix exponential using Pade approximation. Parameters ---------- A : (N, N) array_like or sparse matrix Matrix to be exponentiated. Returns ------- expm : (N, N) ndarray Matrix exponential of `A`. References ---------- .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009) "A New Scaling and Squaring Algorithm for the Matrix Exponential." SIAM Journal on Matrix Analysis and Applications. 31 (3). pp. 970-989. ISSN 1095-7162 Examples -------- >>> from scipy.linalg import expm, sinm, cosm Matrix version of the formula exp(0) = 1: >>> expm(np.zeros((2,2))) array([[ 1., 0.], [ 0., 1.]]) Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) applied to a matrix: >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) >>> expm(1j*a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) >>> cosm(a) + 1j*sinm(a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
Compute the matrix exponential using Pade approximation.
[ "Compute", "the", "matrix", "exponential", "using", "Pade", "approximation", "." ]
def expm(A): """ Compute the matrix exponential using Pade approximation. Parameters ---------- A : (N, N) array_like or sparse matrix Matrix to be exponentiated. Returns ------- expm : (N, N) ndarray Matrix exponential of `A`. References ---------- .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009) "A New Scaling and Squaring Algorithm for the Matrix Exponential." SIAM Journal on Matrix Analysis and Applications. 31 (3). pp. 970-989. ISSN 1095-7162 Examples -------- >>> from scipy.linalg import expm, sinm, cosm Matrix version of the formula exp(0) = 1: >>> expm(np.zeros((2,2))) array([[ 1., 0.], [ 0., 1.]]) Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta)) applied to a matrix: >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]]) >>> expm(1j*a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) >>> cosm(a) + 1j*sinm(a) array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j], [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]]) """ # Input checking and conversion is provided by sparse.linalg.expm(). import scipy.sparse.linalg return scipy.sparse.linalg.expm(A)
[ "def", "expm", "(", "A", ")", ":", "# Input checking and conversion is provided by sparse.linalg.expm().", "import", "scipy", ".", "sparse", ".", "linalg", "return", "scipy", ".", "sparse", ".", "linalg", ".", "expm", "(", "A", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/matfuncs.py#L211-L256
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py
python
StateMachine.is_next_line_blank
(self)
Return 1 if the next line is blank or non-existant.
Return 1 if the next line is blank or non-existant.
[ "Return", "1", "if", "the", "next", "line", "is", "blank", "or", "non", "-", "existant", "." ]
def is_next_line_blank(self): """Return 1 if the next line is blank or non-existant.""" try: return not self.input_lines[self.line_offset + 1].strip() except IndexError: return 1
[ "def", "is_next_line_blank", "(", "self", ")", ":", "try", ":", "return", "not", "self", ".", "input_lines", "[", "self", ".", "line_offset", "+", "1", "]", ".", "strip", "(", ")", "except", "IndexError", ":", "return", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py#L315-L320
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiManager.SetAGWFlags
(self, agwFlags)
This method is used to specify :class:`AuiManager` 's settings flags. :param integer `agwFlags`: specifies options which allow the frame management behavior to be modified. `agwFlags` can be one of the following style bits: ==================================== ================================== Flag name Description ==================================== ================================== ``AUI_MGR_ALLOW_FLOATING`` Allow floating of panes ``AUI_MGR_ALLOW_ACTIVE_PANE`` If a pane becomes active, "highlight" it in the interface ``AUI_MGR_TRANSPARENT_DRAG`` If the platform supports it, set transparency on a floating pane while it is dragged by the user ``AUI_MGR_TRANSPARENT_HINT`` If the platform supports it, show a transparent hint window when the user is about to dock a floating pane ``AUI_MGR_VENETIAN_BLINDS_HINT`` Show a "venetian blind" effect when the user is about to dock a floating pane ``AUI_MGR_RECTANGLE_HINT`` Show a rectangle hint effect when the user is about to dock a floating pane ``AUI_MGR_HINT_FADE`` If the platform supports it, the hint window will fade in and out ``AUI_MGR_NO_VENETIAN_BLINDS_FADE`` Disables the "venetian blind" fade in and out ``AUI_MGR_LIVE_RESIZE`` Live resize when the user drag a sash ``AUI_MGR_ANIMATE_FRAMES`` Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only) ``AUI_MGR_AERO_DOCKING_GUIDES`` Use the new Aero-style bitmaps as docking guides ``AUI_MGR_PREVIEW_MINIMIZED_PANES`` Slide in and out minimized panes to preview them ``AUI_MGR_WHIDBEY_DOCKING_GUIDES`` Use the new Whidbey-style bitmaps as docking guides ``AUI_MGR_SMOOTH_DOCKING`` Performs a "smooth" docking of panes (a la PyQT) ``AUI_MGR_USE_NATIVE_MINIFRAMES`` Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMAC) ``AUI_MGR_AUTONB_NO_CAPTION`` Panes that merge into an automatic notebook will not have the pane caption visible ==================================== ================================== .. note:: If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a floating pane caption will not re-dock the pane, but simply maximize it (if :meth:`AuiPaneInfo.MaximizeButton` has been set to ``True``) or do nothing.
This method is used to specify :class:`AuiManager` 's settings flags.
[ "This", "method", "is", "used", "to", "specify", ":", "class", ":", "AuiManager", "s", "settings", "flags", "." ]
def SetAGWFlags(self, agwFlags): """ This method is used to specify :class:`AuiManager` 's settings flags. :param integer `agwFlags`: specifies options which allow the frame management behavior to be modified. `agwFlags` can be one of the following style bits: ==================================== ================================== Flag name Description ==================================== ================================== ``AUI_MGR_ALLOW_FLOATING`` Allow floating of panes ``AUI_MGR_ALLOW_ACTIVE_PANE`` If a pane becomes active, "highlight" it in the interface ``AUI_MGR_TRANSPARENT_DRAG`` If the platform supports it, set transparency on a floating pane while it is dragged by the user ``AUI_MGR_TRANSPARENT_HINT`` If the platform supports it, show a transparent hint window when the user is about to dock a floating pane ``AUI_MGR_VENETIAN_BLINDS_HINT`` Show a "venetian blind" effect when the user is about to dock a floating pane ``AUI_MGR_RECTANGLE_HINT`` Show a rectangle hint effect when the user is about to dock a floating pane ``AUI_MGR_HINT_FADE`` If the platform supports it, the hint window will fade in and out ``AUI_MGR_NO_VENETIAN_BLINDS_FADE`` Disables the "venetian blind" fade in and out ``AUI_MGR_LIVE_RESIZE`` Live resize when the user drag a sash ``AUI_MGR_ANIMATE_FRAMES`` Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only) ``AUI_MGR_AERO_DOCKING_GUIDES`` Use the new Aero-style bitmaps as docking guides ``AUI_MGR_PREVIEW_MINIMIZED_PANES`` Slide in and out minimized panes to preview them ``AUI_MGR_WHIDBEY_DOCKING_GUIDES`` Use the new Whidbey-style bitmaps as docking guides ``AUI_MGR_SMOOTH_DOCKING`` Performs a "smooth" docking of panes (a la PyQT) ``AUI_MGR_USE_NATIVE_MINIFRAMES`` Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMAC) ``AUI_MGR_AUTONB_NO_CAPTION`` Panes that merge into an automatic notebook will not have the pane caption visible ==================================== ================================== .. note:: If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a floating pane caption will not re-dock the pane, but simply maximize it (if :meth:`AuiPaneInfo.MaximizeButton` has been set to ``True``) or do nothing. """ self._agwFlags = agwFlags if len(self._guides) > 0: self.CreateGuideWindows() if self._hint_window and agwFlags & AUI_MGR_RECTANGLE_HINT == 0: self.CreateHintWindow()
[ "def", "SetAGWFlags", "(", "self", ",", "agwFlags", ")", ":", "self", ".", "_agwFlags", "=", "agwFlags", "if", "len", "(", "self", ".", "_guides", ")", ">", "0", ":", "self", ".", "CreateGuideWindows", "(", ")", "if", "self", ".", "_hint_window", "and", "agwFlags", "&", "AUI_MGR_RECTANGLE_HINT", "==", "0", ":", "self", ".", "CreateHintWindow", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L4392-L4435
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py
python
session
()
return Session()
Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session
Returns a :class:`Session` for context-management.
[ "Returns", "a", ":", "class", ":", "Session", "for", "context", "-", "management", "." ]
def session(): """ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session """ return Session()
[ "def", "session", "(", ")", ":", "return", "Session", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py#L755-L767
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/msvc.py
python
print_all_msvc_detected
(conf)
Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS*
Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS*
[ "Print", "the", "contents", "of", "*", "conf", ".", "env", ".", "MSVC_INSTALLED_VERSIONS", "*" ]
def print_all_msvc_detected(conf): """ Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS* """ for version,targets in conf.env['MSVC_INSTALLED_VERSIONS']: Logs.info(version) for target,l in targets: Logs.info("\t"+target)
[ "def", "print_all_msvc_detected", "(", "conf", ")", ":", "for", "version", ",", "targets", "in", "conf", ".", "env", "[", "'MSVC_INSTALLED_VERSIONS'", "]", ":", "Logs", ".", "info", "(", "version", ")", "for", "target", ",", "l", "in", "targets", ":", "Logs", ".", "info", "(", "\"\\t\"", "+", "target", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/msvc.py#L530-L537
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py
python
EntryProxy.__get_rsrcdir
(self)
return EntryProxy(self.get().srcnode().rfile().dir)
Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.
Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.
[ "Returns", "the", "directory", "containing", "the", "source", "node", "linked", "to", "this", "node", "via", "VariantDir", "()", "or", "the", "directory", "of", "this", "node", "if", "not", "linked", "." ]
def __get_rsrcdir(self): """Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.""" return EntryProxy(self.get().srcnode().rfile().dir)
[ "def", "__get_rsrcdir", "(", "self", ")", ":", "return", "EntryProxy", "(", "self", ".", "get", "(", ")", ".", "srcnode", "(", ")", ".", "rfile", "(", ")", ".", "dir", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L502-L505
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py
python
isscalar
(element)
return (isinstance(element, generic) or type(element) in ScalarType or isinstance(element, numbers.Number))
Returns True if the type of `element` is a scalar type. Parameters ---------- element : any Input argument, can be of any type and shape. Returns ------- val : bool True if `element` is a scalar type, False if it is not. See Also -------- ndim : Get the number of dimensions of an array Notes ----- If you need a stricter way to identify a *numerical* scalar, use ``isinstance(x, numbers.Number)``, as that returns ``False`` for most non-numerical elements such as strings. In most cases ``np.ndim(x) == 0`` should be used instead of this function, as that will also return true for 0d arrays. This is how numpy overloads functions in the style of the ``dx`` arguments to `gradient` and the ``bins`` argument to `histogram`. Some key differences: +--------------------------------------+---------------+-------------------+ | x |``isscalar(x)``|``np.ndim(x) == 0``| +======================================+===============+===================+ | PEP 3141 numeric objects (including | ``True`` | ``True`` | | builtins) | | | +--------------------------------------+---------------+-------------------+ | builtin string and buffer objects | ``True`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other builtin objects, like | ``False`` | ``True`` | | `pathlib.Path`, `Exception`, | | | | the result of `re.compile` | | | +--------------------------------------+---------------+-------------------+ | third-party objects like | ``False`` | ``True`` | | `matplotlib.figure.Figure` | | | +--------------------------------------+---------------+-------------------+ | zero-dimensional numpy arrays | ``False`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other numpy arrays | ``False`` | ``False`` | +--------------------------------------+---------------+-------------------+ | `list`, `tuple`, and other sequence | ``False`` | ``False`` | | objects | | | +--------------------------------------+---------------+-------------------+ Examples -------- >>> np.isscalar(3.1) True >>> np.isscalar(np.array(3.1)) False >>> np.isscalar([3.1]) False >>> np.isscalar(False) True >>> np.isscalar('numpy') True NumPy supports PEP 3141 numbers: >>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number >>> np.isscalar(Number()) True
Returns True if the type of `element` is a scalar type.
[ "Returns", "True", "if", "the", "type", "of", "element", "is", "a", "scalar", "type", "." ]
def isscalar(element): """ Returns True if the type of `element` is a scalar type. Parameters ---------- element : any Input argument, can be of any type and shape. Returns ------- val : bool True if `element` is a scalar type, False if it is not. See Also -------- ndim : Get the number of dimensions of an array Notes ----- If you need a stricter way to identify a *numerical* scalar, use ``isinstance(x, numbers.Number)``, as that returns ``False`` for most non-numerical elements such as strings. In most cases ``np.ndim(x) == 0`` should be used instead of this function, as that will also return true for 0d arrays. This is how numpy overloads functions in the style of the ``dx`` arguments to `gradient` and the ``bins`` argument to `histogram`. Some key differences: +--------------------------------------+---------------+-------------------+ | x |``isscalar(x)``|``np.ndim(x) == 0``| +======================================+===============+===================+ | PEP 3141 numeric objects (including | ``True`` | ``True`` | | builtins) | | | +--------------------------------------+---------------+-------------------+ | builtin string and buffer objects | ``True`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other builtin objects, like | ``False`` | ``True`` | | `pathlib.Path`, `Exception`, | | | | the result of `re.compile` | | | +--------------------------------------+---------------+-------------------+ | third-party objects like | ``False`` | ``True`` | | `matplotlib.figure.Figure` | | | +--------------------------------------+---------------+-------------------+ | zero-dimensional numpy arrays | ``False`` | ``True`` | +--------------------------------------+---------------+-------------------+ | other numpy arrays | ``False`` | ``False`` | +--------------------------------------+---------------+-------------------+ | `list`, `tuple`, and other sequence | ``False`` | ``False`` | | objects | | | +--------------------------------------+---------------+-------------------+ Examples -------- >>> np.isscalar(3.1) True >>> np.isscalar(np.array(3.1)) False >>> np.isscalar([3.1]) False >>> np.isscalar(False) True >>> np.isscalar('numpy') True NumPy supports PEP 3141 numbers: >>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number >>> np.isscalar(Number()) True """ return (isinstance(element, generic) or type(element) in ScalarType or isinstance(element, numbers.Number))
[ "def", "isscalar", "(", "element", ")", ":", "return", "(", "isinstance", "(", "element", ",", "generic", ")", "or", "type", "(", "element", ")", "in", "ScalarType", "or", "isinstance", "(", "element", ",", "numbers", ".", "Number", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py#L1787-L1864
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
KScriptGenerator.updateFunctionCallMap
(self, caller, callee)
Maintains a map of functions that are called from other functions
Maintains a map of functions that are called from other functions
[ "Maintains", "a", "map", "of", "functions", "that", "are", "called", "from", "other", "functions" ]
def updateFunctionCallMap(self, caller, callee): """Maintains a map of functions that are called from other functions""" if not caller in self.calledFunctionTable: self.calledFunctionTable[caller] = [] if not callee in self.calledFunctionTable[caller]: self.calledFunctionTable[caller].append(callee) if not caller in self.comprehensiveCalledFunctionTable: self.comprehensiveCalledFunctionTable[caller] = [] self.comprehensiveCalledFunctionTable[caller].append(callee)
[ "def", "updateFunctionCallMap", "(", "self", ",", "caller", ",", "callee", ")", ":", "if", "not", "caller", "in", "self", ".", "calledFunctionTable", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", "=", "[", "]", "if", "not", "callee", "in", "self", ".", "calledFunctionTable", "[", "caller", "]", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")", "if", "not", "caller", "in", "self", ".", "comprehensiveCalledFunctionTable", ":", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", "=", "[", "]", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L58-L66
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridPopulator.ParseChoices
(*args, **kwargs)
return _propgrid.PropertyGridPopulator_ParseChoices(*args, **kwargs)
ParseChoices(self, String choicesString, String idString) -> PGChoices
ParseChoices(self, String choicesString, String idString) -> PGChoices
[ "ParseChoices", "(", "self", "String", "choicesString", "String", "idString", ")", "-", ">", "PGChoices" ]
def ParseChoices(*args, **kwargs): """ParseChoices(self, String choicesString, String idString) -> PGChoices""" return _propgrid.PropertyGridPopulator_ParseChoices(*args, **kwargs)
[ "def", "ParseChoices", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridPopulator_ParseChoices", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2620-L2622
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py
python
VisualStudioVersion.Path
(self)
return self.path
Returns the path to Visual Studio installation.
Returns the path to Visual Studio installation.
[ "Returns", "the", "path", "to", "Visual", "Studio", "installation", "." ]
def Path(self): """Returns the path to Visual Studio installation.""" return self.path
[ "def", "Path", "(", "self", ")", ":", "return", "self", ".", "path" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L60-L62
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/checkperms/checkperms.py
python
is_ignored
(rel_path)
return ( os.path.basename(rel_path) in IGNORED_FILENAMES or rel_path.lower().startswith(IGNORED_PATHS))
Returns True if rel_path is in our whitelist of files to ignore.
Returns True if rel_path is in our whitelist of files to ignore.
[ "Returns", "True", "if", "rel_path", "is", "in", "our", "whitelist", "of", "files", "to", "ignore", "." ]
def is_ignored(rel_path): """Returns True if rel_path is in our whitelist of files to ignore.""" rel_path = rel_path.lower() return ( os.path.basename(rel_path) in IGNORED_FILENAMES or rel_path.lower().startswith(IGNORED_PATHS))
[ "def", "is_ignored", "(", "rel_path", ")", ":", "rel_path", "=", "rel_path", ".", "lower", "(", ")", "return", "(", "os", ".", "path", ".", "basename", "(", "rel_path", ")", "in", "IGNORED_FILENAMES", "or", "rel_path", ".", "lower", "(", ")", ".", "startswith", "(", "IGNORED_PATHS", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/checkperms/checkperms.py#L261-L266
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
tools/linter/mypy_wrapper.py
python
make_plan
( *, configs: Dict[str, Set[str]], files: List[str] )
return plan
Return a dict from config names to the files to run them with. The keys of the returned dict are a subset of the keys of `configs`. The list of files in each value of returned dict should contain a nonempty subset of the given `files`, in the same order as `files`.
Return a dict from config names to the files to run them with.
[ "Return", "a", "dict", "from", "config", "names", "to", "the", "files", "to", "run", "them", "with", "." ]
def make_plan( *, configs: Dict[str, Set[str]], files: List[str] ) -> Dict[str, List[str]]: """ Return a dict from config names to the files to run them with. The keys of the returned dict are a subset of the keys of `configs`. The list of files in each value of returned dict should contain a nonempty subset of the given `files`, in the same order as `files`. """ trie = make_trie(configs) plan = defaultdict(list) for filename in files: for config in lookup(trie, filename): plan[config].append(filename) return plan
[ "def", "make_plan", "(", "*", ",", "configs", ":", "Dict", "[", "str", ",", "Set", "[", "str", "]", "]", ",", "files", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "trie", "=", "make_trie", "(", "configs", ")", "plan", "=", "defaultdict", "(", "list", ")", "for", "filename", "in", "files", ":", "for", "config", "in", "lookup", "(", "trie", ",", "filename", ")", ":", "plan", "[", "config", "]", ".", "append", "(", "filename", ")", "return", "plan" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/linter/mypy_wrapper.py#L109-L126
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/encoder.py
python
_VarintEncoder
()
return EncodeVarint
Return an encoder for a basic varint value (does not include tag).
Return an encoder for a basic varint value (does not include tag).
[ "Return", "an", "encoder", "for", "a", "basic", "varint", "value", "(", "does", "not", "include", "tag", ")", "." ]
def _VarintEncoder(): """Return an encoder for a basic varint value (does not include tag).""" local_int2byte = six.int2byte def EncodeVarint(write, value, unused_deterministic=None): bits = value & 0x7f value >>= 7 while value: write(local_int2byte(0x80|bits)) bits = value & 0x7f value >>= 7 return write(local_int2byte(bits)) return EncodeVarint
[ "def", "_VarintEncoder", "(", ")", ":", "local_int2byte", "=", "six", ".", "int2byte", "def", "EncodeVarint", "(", "write", ",", "value", ",", "unused_deterministic", "=", "None", ")", ":", "bits", "=", "value", "&", "0x7f", "value", ">>=", "7", "while", "value", ":", "write", "(", "local_int2byte", "(", "0x80", "|", "bits", ")", ")", "bits", "=", "value", "&", "0x7f", "value", ">>=", "7", "return", "write", "(", "local_int2byte", "(", "bits", ")", ")", "return", "EncodeVarint" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/encoder.py#L372-L385
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/build/project.py
python
ProjectAttributes.dump
(self)
Prints the project attributes.
Prints the project attributes.
[ "Prints", "the", "project", "attributes", "." ]
def dump(self): """Prints the project attributes.""" id = self.get("id") if not id: id = "(none)" else: id = id[0] parent = self.get("parent") if not parent: parent = "(none)" else: parent = parent[0] print "'%s'" % id print "Parent project:%s", parent print "Requirements:%s", self.get("requirements") print "Default build:%s", string.join(self.get("debuild-build")) print "Source location:%s", string.join(self.get("source-location")) print "Projects to build:%s", string.join(self.get("projects-to-build").sort());
[ "def", "dump", "(", "self", ")", ":", "id", "=", "self", ".", "get", "(", "\"id\"", ")", "if", "not", "id", ":", "id", "=", "\"(none)\"", "else", ":", "id", "=", "id", "[", "0", "]", "parent", "=", "self", ".", "get", "(", "\"parent\"", ")", "if", "not", "parent", ":", "parent", "=", "\"(none)\"", "else", ":", "parent", "=", "parent", "[", "0", "]", "print", "\"'%s'\"", "%", "id", "print", "\"Parent project:%s\"", ",", "parent", "print", "\"Requirements:%s\"", ",", "self", ".", "get", "(", "\"requirements\"", ")", "print", "\"Default build:%s\"", ",", "string", ".", "join", "(", "self", ".", "get", "(", "\"debuild-build\"", ")", ")", "print", "\"Source location:%s\"", ",", "string", ".", "join", "(", "self", ".", "get", "(", "\"source-location\"", ")", ")", "print", "\"Projects to build:%s\"", ",", "string", ".", "join", "(", "self", ".", "get", "(", "\"projects-to-build\"", ")", ".", "sort", "(", ")", ")" ]
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/project.py#L818-L837
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/fromnumeric.py
python
prod
(a, axis=None, dtype=None, out=None, keepdims=False)
Return the product of array elements over a given axis. Parameters ---------- a : array_like Input data. axis : None or int or tuple of ints, optional Axis or axes along which a product is performed. The default (`axis` = `None`) is perform a product over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a product is performed on multiple axes, instead of a single axis or all the axes as before. dtype : data-type, optional The data-type of the returned array, as well as of the accumulator in which the elements are multiplied. By default, if `a` is of integer type, `dtype` is the default platform integer. (Note: if the type of `a` is unsigned, then so is `dtype`.) Otherwise, the dtype is the same as that of `a`. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- product_along_axis : ndarray, see `dtype` parameter above. An array shaped as `a` but with the specified axis removed. Returns a reference to `out` if specified. See Also -------- ndarray.prod : equivalent method numpy.doc.ufuncs : Section "Output arguments" Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform: >>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) #random 16 Examples -------- By default, calculate the product of all elements: >>> np.prod([1.,2.]) 2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]]) 24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.]) If the type of `x` is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True If `x` is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == np.int True
Return the product of array elements over a given axis.
[ "Return", "the", "product", "of", "array", "elements", "over", "a", "given", "axis", "." ]
def prod(a, axis=None, dtype=None, out=None, keepdims=False): """ Return the product of array elements over a given axis. Parameters ---------- a : array_like Input data. axis : None or int or tuple of ints, optional Axis or axes along which a product is performed. The default (`axis` = `None`) is perform a product over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a product is performed on multiple axes, instead of a single axis or all the axes as before. dtype : data-type, optional The data-type of the returned array, as well as of the accumulator in which the elements are multiplied. By default, if `a` is of integer type, `dtype` is the default platform integer. (Note: if the type of `a` is unsigned, then so is `dtype`.) Otherwise, the dtype is the same as that of `a`. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- product_along_axis : ndarray, see `dtype` parameter above. An array shaped as `a` but with the specified axis removed. Returns a reference to `out` if specified. See Also -------- ndarray.prod : equivalent method numpy.doc.ufuncs : Section "Output arguments" Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform: >>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) #random 16 Examples -------- By default, calculate the product of all elements: >>> np.prod([1.,2.]) 2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]]) 24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.]) If the type of `x` is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True If `x` is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == np.int True """ if type(a) is not mu.ndarray: try: prod = a.prod except AttributeError: return _methods._prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) return prod(axis=axis, dtype=dtype, out=out) else: return _methods._prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
[ "def", "prod", "(", "a", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "False", ")", ":", "if", "type", "(", "a", ")", "is", "not", "mu", ".", "ndarray", ":", "try", ":", "prod", "=", "a", ".", "prod", "except", "AttributeError", ":", "return", "_methods", ".", "_prod", "(", "a", ",", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ",", "keepdims", "=", "keepdims", ")", "return", "prod", "(", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ")", "else", ":", "return", "_methods", ".", "_prod", "(", "a", ",", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ",", "keepdims", "=", "keepdims", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/fromnumeric.py#L2249-L2343
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/control_flow_ops.py
python
_SwitchRefOrTensor
(data, pred, name="Switch")
Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. Raises: TypeError: if data is not a Tensor or IndexedSlices
Forwards `data` to an output determined by `pred`.
[ "Forwards", "data", "to", "an", "output", "determined", "by", "pred", "." ]
def _SwitchRefOrTensor(data, pred, name="Switch"): """Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. Raises: TypeError: if data is not a Tensor or IndexedSlices """ data = ops.convert_to_tensor_or_indexed_slices(data, name="data") # NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below # addresses the following scenario. # # Assume you execute Optimizer.apply_gradients() in a branch of a cond(). # # 1. The update op is created inside a `with ops.colocate(var):` block # # 2. Some tensor `data` is captured and a switch is created in a # `with ops.colocate_with(data):` block. # # with ops.colocate_with(var): # with ops.colocate_with(data): # op = ... # # var and data may be pinned to different devices, so we want to ops # created within ops.colocate_with(data) to ignore the existing stack. with ops.colocate_with(data, ignore_existing=True): if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return ref_switch(data, pred, name=name) return switch(data, pred, name=name)
[ "def", "_SwitchRefOrTensor", "(", "data", ",", "pred", ",", "name", "=", "\"Switch\"", ")", ":", "data", "=", "ops", ".", "convert_to_tensor_or_indexed_slices", "(", "data", ",", "name", "=", "\"data\"", ")", "# NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below", "# addresses the following scenario.", "#", "# Assume you execute Optimizer.apply_gradients() in a branch of a cond().", "#", "# 1. The update op is created inside a `with ops.colocate(var):` block", "#", "# 2. Some tensor `data` is captured and a switch is created in a", "# `with ops.colocate_with(data):` block.", "#", "# with ops.colocate_with(var):", "# with ops.colocate_with(data):", "# op = ...", "#", "# var and data may be pinned to different devices, so we want to ops", "# created within ops.colocate_with(data) to ignore the existing stack.", "with", "ops", ".", "colocate_with", "(", "data", ",", "ignore_existing", "=", "True", ")", ":", "if", "isinstance", "(", "data", ",", "ops", ".", "Tensor", ")", ":", "if", "data", ".", "dtype", ".", "_is_ref_dtype", ":", "# pylint: disable=protected-access", "return", "ref_switch", "(", "data", ",", "pred", ",", "name", "=", "name", ")", "return", "switch", "(", "data", ",", "pred", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L326-L367
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
python
Logger.getChild
(self, suffix)
return self.manager.getLogger(suffix)
Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string.
Get a logger which is a descendant to this one.
[ "Get", "a", "logger", "which", "is", "a", "descendant", "to", "this", "one", "." ]
def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
[ "def", "getChild", "(", "self", ",", "suffix", ")", ":", "if", "self", ".", "root", "is", "not", "self", ":", "suffix", "=", "'.'", ".", "join", "(", "(", "self", ".", "name", ",", "suffix", ")", ")", "return", "self", ".", "manager", ".", "getLogger", "(", "suffix", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L1350-L1367
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/utils/benchmark/mingw.py
python
find_7zip
(log = EmptyLogger())
return path[0]
Attempts to find 7zip for unpacking the mingw-build archives
Attempts to find 7zip for unpacking the mingw-build archives
[ "Attempts", "to", "find", "7zip", "for", "unpacking", "the", "mingw", "-", "build", "archives" ]
def find_7zip(log = EmptyLogger()): ''' Attempts to find 7zip for unpacking the mingw-build archives ''' log.info('finding 7zip') path = find_in_path('7z') if not path: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip') path, _ = winreg.QueryValueEx(key, 'Path') path = [os.path.join(path, '7z.exe')] log.debug('found \'%s\'', path[0]) return path[0]
[ "def", "find_7zip", "(", "log", "=", "EmptyLogger", "(", ")", ")", ":", "log", ".", "info", "(", "'finding 7zip'", ")", "path", "=", "find_in_path", "(", "'7z'", ")", "if", "not", "path", ":", "key", "=", "winreg", ".", "OpenKey", "(", "winreg", ".", "HKEY_LOCAL_MACHINE", ",", "r'SOFTWARE\\7-Zip'", ")", "path", ",", "_", "=", "winreg", ".", "QueryValueEx", "(", "key", ",", "'Path'", ")", "path", "=", "[", "os", ".", "path", ".", "join", "(", "path", ",", "'7z.exe'", ")", "]", "log", ".", "debug", "(", "'found \\'%s\\''", ",", "path", "[", "0", "]", ")", "return", "path", "[", "0", "]" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/benchmark/mingw.py#L99-L110
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/util/protoresources.py
python
_ProcessZip
(zip_path, process_func)
Filters a .zip file via: new_bytes = process_func(filename, data).
Filters a .zip file via: new_bytes = process_func(filename, data).
[ "Filters", "a", ".", "zip", "file", "via", ":", "new_bytes", "=", "process_func", "(", "filename", "data", ")", "." ]
def _ProcessZip(zip_path, process_func): """Filters a .zip file via: new_bytes = process_func(filename, data).""" has_changes = False zip_entries = [] with zipfile.ZipFile(zip_path) as src_zip: for info in src_zip.infolist(): data = src_zip.read(info) new_data = process_func(info.filename, data) if new_data is not data: has_changes = True data = new_data zip_entries.append((info, data)) # Overwrite the original zip file. if has_changes: with zipfile.ZipFile(zip_path, 'w') as f: for info, data in zip_entries: f.writestr(info, data)
[ "def", "_ProcessZip", "(", "zip_path", ",", "process_func", ")", ":", "has_changes", "=", "False", "zip_entries", "=", "[", "]", "with", "zipfile", ".", "ZipFile", "(", "zip_path", ")", "as", "src_zip", ":", "for", "info", "in", "src_zip", ".", "infolist", "(", ")", ":", "data", "=", "src_zip", ".", "read", "(", "info", ")", "new_data", "=", "process_func", "(", "info", ".", "filename", ",", "data", ")", "if", "new_data", "is", "not", "data", ":", "has_changes", "=", "True", "data", "=", "new_data", "zip_entries", ".", "append", "(", "(", "info", ",", "data", ")", ")", "# Overwrite the original zip file.", "if", "has_changes", ":", "with", "zipfile", ".", "ZipFile", "(", "zip_path", ",", "'w'", ")", "as", "f", ":", "for", "info", ",", "data", "in", "zip_entries", ":", "f", ".", "writestr", "(", "info", ",", "data", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/protoresources.py#L39-L56
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
UGRNNCell.__init__
(self, num_units, initializer=None, forget_bias=1.0, activation=math_ops.tanh, reuse=None)
Initialize the parameters for an UGRNN cell. Args: num_units: int, The number of units in the UGRNN cell initializer: (optional) The initializer to use for the weight matrices. forget_bias: (optional) float, default 1.0, The initial bias of the forget gate, used to reduce the scale of forgetting at the beginning of the training. activation: (optional) Activation function of the inner states. Default is `tf.tanh`. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised.
Initialize the parameters for an UGRNN cell.
[ "Initialize", "the", "parameters", "for", "an", "UGRNN", "cell", "." ]
def __init__(self, num_units, initializer=None, forget_bias=1.0, activation=math_ops.tanh, reuse=None): """Initialize the parameters for an UGRNN cell. Args: num_units: int, The number of units in the UGRNN cell initializer: (optional) The initializer to use for the weight matrices. forget_bias: (optional) float, default 1.0, The initial bias of the forget gate, used to reduce the scale of forgetting at the beginning of the training. activation: (optional) Activation function of the inner states. Default is `tf.tanh`. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. """ super(UGRNNCell, self).__init__(_reuse=reuse) self._num_units = num_units self._initializer = initializer self._forget_bias = forget_bias self._activation = activation self._reuse = reuse
[ "def", "__init__", "(", "self", ",", "num_units", ",", "initializer", "=", "None", ",", "forget_bias", "=", "1.0", ",", "activation", "=", "math_ops", ".", "tanh", ",", "reuse", "=", "None", ")", ":", "super", "(", "UGRNNCell", ",", "self", ")", ".", "__init__", "(", "_reuse", "=", "reuse", ")", "self", ".", "_num_units", "=", "num_units", "self", ".", "_initializer", "=", "initializer", "self", ".", "_forget_bias", "=", "forget_bias", "self", ".", "_activation", "=", "activation", "self", ".", "_reuse", "=", "reuse" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1517-L1538
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
libraries/vm/vm_cpython_ss/lib/abc.py
python
abstractmethod
(funcobj)
return funcobj
A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ...
A decorator indicating abstract methods.
[ "A", "decorator", "indicating", "abstract", "methods", "." ]
def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj
[ "def", "abstractmethod", "(", "funcobj", ")", ":", "funcobj", ".", "__isabstractmethod__", "=", "True", "return", "funcobj" ]
https://github.com/learnforpractice/pyeos/blob/4f04eb982c86c1fdb413084af77c713a6fda3070/libraries/vm/vm_cpython_ss/lib/abc.py#L9-L26
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/commands.py
python
Build.finalize_options
(self)
Finalize options
Finalize options
[ "Finalize", "options" ]
def finalize_options(self): """ Finalize options """ _build.build.finalize_options(self) if 'build' in _option_inherits: for parent, opt_name in _option_inherits['build']: self.set_undefined_options(parent, (opt_name, opt_name)) if 'build' in _option_finalizers: for func in list(_option_finalizers['build'].values()): func(self)
[ "def", "finalize_options", "(", "self", ")", ":", "_build", ".", "build", ".", "finalize_options", "(", "self", ")", "if", "'build'", "in", "_option_inherits", ":", "for", "parent", ",", "opt_name", "in", "_option_inherits", "[", "'build'", "]", ":", "self", ".", "set_undefined_options", "(", "parent", ",", "(", "opt_name", ",", "opt_name", ")", ")", "if", "'build'", "in", "_option_finalizers", ":", "for", "func", "in", "list", "(", "_option_finalizers", "[", "'build'", "]", ".", "values", "(", ")", ")", ":", "func", "(", "self", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/commands.py#L258-L266
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/api.py
python
patch
(url, data=None, **kwargs)
return request('patch', url, data=data, **kwargs)
r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
r"""Sends a PATCH request.
[ "r", "Sends", "a", "PATCH", "request", "." ]
def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('patch', url, data=data, **kwargs)
[ "def", "patch", "(", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "request", "(", "'patch'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/api.py#L137-L149
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/elb/loadbalancer.py
python
LoadBalancer.__init__
(self, connection=None, name=None, endpoints=None)
:ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions.
:ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions.
[ ":", "ivar", "boto", ".", "ec2", ".", "elb", ".", "ELBConnection", "connection", ":", "The", "connection", "this", "load", "balancer", "was", "instance", "was", "instantiated", "from", ".", ":", "ivar", "list", "listeners", ":", "A", "list", "of", "tuples", "in", "the", "form", "of", "(", "<Inbound", "port", ">", "<Outbound", "port", ">", "<Protocol", ">", ")", ":", "ivar", "boto", ".", "ec2", ".", "elb", ".", "healthcheck", ".", "HealthCheck", "health_check", ":", "The", "health", "check", "policy", "for", "this", "load", "balancer", ".", ":", "ivar", "boto", ".", "ec2", ".", "elb", ".", "policies", ".", "Policies", "policies", ":", "Cookie", "stickiness", "and", "other", "policies", ".", ":", "ivar", "str", "name", ":", "The", "name", "of", "the", "Load", "Balancer", ".", ":", "ivar", "str", "dns_name", ":", "The", "external", "DNS", "name", "for", "the", "balancer", ".", ":", "ivar", "str", "created_time", ":", "A", "date", "+", "time", "string", "showing", "when", "the", "load", "balancer", "was", "created", ".", ":", "ivar", "list", "instances", ":", "A", "list", "of", ":", "py", ":", "class", ":", "boto", ".", "ec2", ".", "instanceinfo", ".", "InstanceInfo", "instances", "representing", "the", "EC2", "instances", "this", "load", "balancer", "is", "distributing", "requests", "to", ".", ":", "ivar", "list", "availability_zones", ":", "The", "availability", "zones", "this", "balancer", "covers", ".", ":", "ivar", "str", "canonical_hosted_zone_name", ":", "Current", "CNAME", "for", "the", "balancer", ".", ":", "ivar", "str", "canonical_hosted_zone_name_id", ":", "The", "Route", "53", "hosted", "zone", "ID", "of", "this", "balancer", ".", "Needed", "when", "creating", "an", "Alias", "record", "in", "a", "Route", "53", "hosted", "zone", ".", ":", "ivar", "boto", ".", "ec2", ".", "elb", ".", "securitygroup", ".", "SecurityGroup", "source_security_group", ":", "The", "security", "group", "that", "you", "can", "use", "as", "part", "of", "your", "inbound", "rules", "for", "your", "load", "balancer", "back", "-", "end", "instances", "to", "disallow", "traffic", "from", "sources", "other", "than", "your", "load", "balancer", ".", ":", "ivar", "list", "subnets", ":", "A", "list", "of", "subnets", "this", "balancer", "is", "on", ".", ":", "ivar", "list", "security_groups", ":", "A", "list", "of", "additional", "security", "groups", "that", "have", "been", "applied", ".", ":", "ivar", "str", "vpc_id", ":", "The", "ID", "of", "the", "VPC", "that", "this", "ELB", "resides", "within", ".", ":", "ivar", "list", "backends", ":", "A", "list", "of", ":", "py", ":", "class", ":", "boto", ".", "ec2", ".", "elb", ".", "loadbalancer", ".", "Backend", "back", "-", "end", "server", "descriptions", "." ]
def __init__(self, connection=None, name=None, endpoints=None): """ :ivar boto.ec2.elb.ELBConnection connection: The connection this load balancer was instance was instantiated from. :ivar list listeners: A list of tuples in the form of ``(<Inbound port>, <Outbound port>, <Protocol>)`` :ivar boto.ec2.elb.healthcheck.HealthCheck health_check: The health check policy for this load balancer. :ivar boto.ec2.elb.policies.Policies policies: Cookie stickiness and other policies. :ivar str name: The name of the Load Balancer. :ivar str dns_name: The external DNS name for the balancer. :ivar str created_time: A date+time string showing when the load balancer was created. :ivar list instances: A list of :py:class:`boto.ec2.instanceinfo.InstanceInfo` instances, representing the EC2 instances this load balancer is distributing requests to. :ivar list availability_zones: The availability zones this balancer covers. :ivar str canonical_hosted_zone_name: Current CNAME for the balancer. :ivar str canonical_hosted_zone_name_id: The Route 53 hosted zone ID of this balancer. Needed when creating an Alias record in a Route 53 hosted zone. :ivar boto.ec2.elb.securitygroup.SecurityGroup source_security_group: The security group that you can use as part of your inbound rules for your load balancer back-end instances to disallow traffic from sources other than your load balancer. :ivar list subnets: A list of subnets this balancer is on. :ivar list security_groups: A list of additional security groups that have been applied. :ivar str vpc_id: The ID of the VPC that this ELB resides within. :ivar list backends: A list of :py:class:`boto.ec2.elb.loadbalancer.Backend back-end server descriptions. """ self.connection = connection self.name = name self.listeners = None self.health_check = None self.policies = None self.dns_name = None self.created_time = None self.instances = None self.availability_zones = ListElement() self.canonical_hosted_zone_name = None self.canonical_hosted_zone_name_id = None self.source_security_group = None self.subnets = ListElement() self.security_groups = ListElement() self.vpc_id = None self.scheme = None self.backends = None self._attributes = None
[ "def", "__init__", "(", "self", ",", "connection", "=", "None", ",", "name", "=", "None", ",", "endpoints", "=", "None", ")", ":", "self", ".", "connection", "=", "connection", "self", ".", "name", "=", "name", "self", ".", "listeners", "=", "None", "self", ".", "health_check", "=", "None", "self", ".", "policies", "=", "None", "self", ".", "dns_name", "=", "None", "self", ".", "created_time", "=", "None", "self", ".", "instances", "=", "None", "self", ".", "availability_zones", "=", "ListElement", "(", ")", "self", ".", "canonical_hosted_zone_name", "=", "None", "self", ".", "canonical_hosted_zone_name_id", "=", "None", "self", ".", "source_security_group", "=", "None", "self", ".", "subnets", "=", "ListElement", "(", ")", "self", ".", "security_groups", "=", "ListElement", "(", ")", "self", ".", "vpc_id", "=", "None", "self", ".", "scheme", "=", "None", "self", ".", "backends", "=", "None", "self", ".", "_attributes", "=", "None" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/elb/loadbalancer.py#L77-L128
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
GetPreviousNonBlankLine
(clean_lines, linenum)
return ('', -1)
Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line.
Return the most recent non-blank line and its line number.
[ "Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "." ]
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1)
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine", "(", "prevline", ")", ":", "# if not a blank line...", "return", "(", "prevline", ",", "prevlinenum", ")", "prevlinenum", "-=", "1", "return", "(", "''", ",", "-", "1", ")" ]
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L3867-L3887
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/EditorLib/PaintEffect.py
python
PaintEffectTool.paintPixel
(self, x, y)
paint with a single pixel (in label space)
paint with a single pixel (in label space)
[ "paint", "with", "a", "single", "pixel", "(", "in", "label", "space", ")" ]
def paintPixel(self, x, y): """ paint with a single pixel (in label space) """ sliceLogic = self.sliceWidget.sliceLogic() labelLogic = sliceLogic.GetLabelLayer() labelNode = labelLogic.GetVolumeNode() labelImage = labelNode.GetImageData() if not labelNode: # if there's no label, we can't paint return xyToIJK = labelLogic.GetXYToIJKTransform() ijkFloat = xyToIJK.TransformDoublePoint( (x, y, 0) ) ijk = [] for e in ijkFloat: try: index = int(round(e)) except ValueError: return ijk.append(index) dims = labelImage.GetDimensions() for e,d in zip(ijk,dims): # clamp to volume extent if e < 0 or e >= d: return parameterNode = EditUtil.getParameterNode() paintLabel = int(parameterNode.GetParameter("label")) labelImage.SetScalarComponentFromFloat(ijk[0],ijk[1],ijk[2],0, paintLabel) EditUtil.markVolumeNodeAsModified(labelNode)
[ "def", "paintPixel", "(", "self", ",", "x", ",", "y", ")", ":", "sliceLogic", "=", "self", ".", "sliceWidget", ".", "sliceLogic", "(", ")", "labelLogic", "=", "sliceLogic", ".", "GetLabelLayer", "(", ")", "labelNode", "=", "labelLogic", ".", "GetVolumeNode", "(", ")", "labelImage", "=", "labelNode", ".", "GetImageData", "(", ")", "if", "not", "labelNode", ":", "# if there's no label, we can't paint", "return", "xyToIJK", "=", "labelLogic", ".", "GetXYToIJKTransform", "(", ")", "ijkFloat", "=", "xyToIJK", ".", "TransformDoublePoint", "(", "(", "x", ",", "y", ",", "0", ")", ")", "ijk", "=", "[", "]", "for", "e", "in", "ijkFloat", ":", "try", ":", "index", "=", "int", "(", "round", "(", "e", ")", ")", "except", "ValueError", ":", "return", "ijk", ".", "append", "(", "index", ")", "dims", "=", "labelImage", ".", "GetDimensions", "(", ")", "for", "e", ",", "d", "in", "zip", "(", "ijk", ",", "dims", ")", ":", "# clamp to volume extent", "if", "e", "<", "0", "or", "e", ">=", "d", ":", "return", "parameterNode", "=", "EditUtil", ".", "getParameterNode", "(", ")", "paintLabel", "=", "int", "(", "parameterNode", ".", "GetParameter", "(", "\"label\"", ")", ")", "labelImage", ".", "SetScalarComponentFromFloat", "(", "ijk", "[", "0", "]", ",", "ijk", "[", "1", "]", ",", "ijk", "[", "2", "]", ",", "0", ",", "paintLabel", ")", "EditUtil", ".", "markVolumeNodeAsModified", "(", "labelNode", ")" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/PaintEffect.py#L530-L560
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/cpplint.py
python
CheckRedundantOverrideOrFinal
(filename, clean_lines, linenum, error)
Check if line contains a redundant "override" or "final" virt-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check if line contains a redundant "override" or "final" virt-specifier.
[ "Check", "if", "line", "contains", "a", "redundant", "override", "or", "final", "virt", "-", "specifier", "." ]
def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): """Check if line contains a redundant "override" or "final" virt-specifier. 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. """ # Look for closing parenthesis nearby. We need one to confirm where # the declarator ends and where the virt-specifier starts to avoid # false positives. line = clean_lines.elided[linenum] declarator_end = line.rfind(')') if declarator_end >= 0: fragment = line[declarator_end:] else: if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: fragment = line else: return # Check that at most one of "override" or "final" is present, not both if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): error(filename, linenum, 'readability/inheritance', 4, ('"override" is redundant since function is ' 'already declared as "final"'))
[ "def", "CheckRedundantOverrideOrFinal", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Look for closing parenthesis nearby. We need one to confirm where", "# the declarator ends and where the virt-specifier starts to avoid", "# false positives.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "declarator_end", "=", "line", ".", "rfind", "(", "')'", ")", "if", "declarator_end", ">=", "0", ":", "fragment", "=", "line", "[", "declarator_end", ":", "]", "else", ":", "if", "linenum", ">", "1", "and", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ".", "rfind", "(", "')'", ")", ">=", "0", ":", "fragment", "=", "line", "else", ":", "return", "# Check that at most one of \"override\" or \"final\" is present, not both", "if", "Search", "(", "r'\\boverride\\b'", ",", "fragment", ")", "and", "Search", "(", "r'\\bfinal\\b'", ",", "fragment", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/inheritance'", ",", "4", ",", "(", "'\"override\" is redundant since function is '", "'already declared as \"final\"'", ")", ")" ]
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L6242-L6268
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/examples/python/symbolication.py
python
Image.create_target
(self)
return None
Create a target using the information in this Image object.
Create a target using the information in this Image object.
[ "Create", "a", "target", "using", "the", "information", "in", "this", "Image", "object", "." ]
def create_target(self): '''Create a target using the information in this Image object.''' if self.unavailable: return None if self.locate_module_and_debug_symbols(): resolved_path = self.get_resolved_path() path_spec = lldb.SBFileSpec(resolved_path) #result.PutCString ('plist[%s] = %s' % (uuid, self.plist)) error = lldb.SBError() target = lldb.debugger.CreateTarget( resolved_path, self.arch, None, False, error) if target: self.module = target.FindModule(path_spec) if self.has_section_load_info(): err = self.load_module(target) if err: print 'ERROR: ', err return target else: print 'error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path) else: print 'error: unable to locate main executable (%s) "%s"' % (self.arch, self.path) return None
[ "def", "create_target", "(", "self", ")", ":", "if", "self", ".", "unavailable", ":", "return", "None", "if", "self", ".", "locate_module_and_debug_symbols", "(", ")", ":", "resolved_path", "=", "self", ".", "get_resolved_path", "(", ")", "path_spec", "=", "lldb", ".", "SBFileSpec", "(", "resolved_path", ")", "#result.PutCString ('plist[%s] = %s' % (uuid, self.plist))", "error", "=", "lldb", ".", "SBError", "(", ")", "target", "=", "lldb", ".", "debugger", ".", "CreateTarget", "(", "resolved_path", ",", "self", ".", "arch", ",", "None", ",", "False", ",", "error", ")", "if", "target", ":", "self", ".", "module", "=", "target", ".", "FindModule", "(", "path_spec", ")", "if", "self", ".", "has_section_load_info", "(", ")", ":", "err", "=", "self", ".", "load_module", "(", "target", ")", "if", "err", ":", "print", "'ERROR: '", ",", "err", "return", "target", "else", ":", "print", "'error: unable to create a valid target for (%s) \"%s\"'", "%", "(", "self", ".", "arch", ",", "self", ".", "path", ")", "else", ":", "print", "'error: unable to locate main executable (%s) \"%s\"'", "%", "(", "self", ".", "arch", ",", "self", ".", "path", ")", "return", "None" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/examples/python/symbolication.py#L414-L437
s5z/zsim
fb4d6e0475a25cffd23f0687ede2d43d96b4a99f
misc/cpplint.py
python
CheckLanguage
(filename, clean_lines, linenum, file_extension, include_state, error)
Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Checks rules from the 'C++ language rules' section of cppguide.html.
[ "Checks", "rules", "from", "the", "C", "++", "language", "rules", "section", "of", "cppguide", ".", "html", "." ]
def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Create an extended_line, which is the concatenation of the current and # next lines, for more effective checking of code that may span more than one # line. if linenum + 1 < clean_lines.NumLines(): extended_line = line + clean_lines.elided[linenum + 1] else: extended_line = line # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # TODO(unknown): figure out if they're using default arguments in fn proto. # Check for non-const references in functions. This is tricky because & # is also used to take the address of something. We allow <> for templates, # (ignoring whatever is between the braces) and : for classes. # These are complicated re's. They try to capture the following: # paren (for fn-prototype start), typename, &, varname. For the const # version, we're willing for const to be before typename or after # Don't check the implementation on same line. fnline = line.split('{', 1)[0] if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', fnline))): # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". We also filter # out for loops, which lint otherwise mistakenly thinks are functions. if not Search( r'(for|swap|Swap|operator[<>][<>])\s*\(\s*' r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&', fnline): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer.') # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) if match: # gMock methods are defined using some variant of MOCK_METHODx(name, type) # where type may be float(), int(string), etc. Without context they are # virtually indistinguishable from int(x) casts. Likewise, gMock's # MockCallback takes a template parameter of the form return_type(arg_type), # which looks much like the cast we're trying to detect. if (match.group(1) is None and # If new operator, then this isn't a cast not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or Match(r'^\s*MockCallback<.*>', line))): # Try a bit harder to catch gmock lines: the only place where # something looks like an old-style cast is where we declare the # return type of the mocked method, and the only time when we # are missing context is if MOCK_METHOD was split across # multiple lines (for example http://go/hrfhr ), so we only need # to check the previous line for MOCK_METHOD. if (linenum == 0 or not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$', clean_lines.elided[linenum - 1])): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % match.group(2)) CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. if Search( r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line): error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access. match = Match( r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', line) # Make sure it's not a function. # Function template specialization looks like: "string foo<Type>(...". # Class template definitions look like: "string Foo<Type>::Method(...". if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3)): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string instead: ' '"%schar %s[]".' % (match.group(1), match.group(2))) # Check that we're not using RTTI outside of testing code. if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename): error(filename, linenum, 'runtime/rtti', 5, 'Do not use dynamic_cast<>. If you need to cast within a class ' "hierarchy, use static_cast<> to upcast. Google doesn't support " 'RTTI.') if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\b', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\b', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) if Search(r'\bsscanf\b', line): error(filename, linenum, 'runtime/printf', 1, 'sscanf can be ok, but is slow and can overflow buffers.') # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(sugawarayu): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing # in the class declaration. match = Match( (r'\s*' r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' r'\(.*\);$'), line) if match and linenum + 1 < clean_lines.NumLines(): next_line = clean_lines.elided[linenum + 1] # We allow some, but not all, declarations of variables to be present # in the statement that defines the class. The [\w\*,\s]* fragment of # the regular expression below allows users to declare instances of # the class or pointers to instances, but not less common types such # as function pointers or arrays. It's a tradeoff between allowing # reasonable code and avoiding trying to parse more C++ using regexps. if not Search(r'^\s*}[\w\*,\s]*;', next_line): error(filename, linenum, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.')
[ "def", "CheckLanguage", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "include_state", ",", "error", ")", ":", "# If the line is empty or consists of entirely a comment, no need to", "# check it.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", ":", "return", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "line", ")", "if", "match", ":", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", "return", "# Create an extended_line, which is the concatenation of the current and", "# next lines, for more effective checking of code that may span more than one", "# line.", "if", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "extended_line", "=", "line", "+", "clean_lines", ".", "elided", "[", "linenum", "+", "1", "]", "else", ":", "extended_line", "=", "line", "# Make Windows paths like Unix.", "fullname", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "# TODO(unknown): figure out if they're using default arguments in fn proto.", "# Check for non-const references in functions. This is tricky because &", "# is also used to take the address of something. We allow <> for templates,", "# (ignoring whatever is between the braces) and : for classes.", "# These are complicated re's. They try to capture the following:", "# paren (for fn-prototype start), typename, &, varname. For the const", "# version, we're willing for const to be before typename or after", "# Don't check the implementation on same line.", "fnline", "=", "line", ".", "split", "(", "'{'", ",", "1", ")", "[", "0", "]", "if", "(", "len", "(", "re", ".", "findall", "(", "r'\\([^()]*\\b(?:[\\w:]|<[^()]*>)+(\\s?&|&\\s?)\\w+'", ",", "fnline", ")", ")", ">", "len", "(", "re", ".", "findall", "(", "r'\\([^()]*\\bconst\\s+(?:typename\\s+)?(?:struct\\s+)?'", "r'(?:[\\w:]|<[^()]*>)+(\\s?&|&\\s?)\\w+'", ",", "fnline", ")", ")", "+", "len", "(", "re", ".", "findall", "(", "r'\\([^()]*\\b(?:[\\w:]|<[^()]*>)+\\s+const(\\s?&|&\\s?)[\\w]+'", ",", "fnline", ")", ")", ")", ":", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". We also filter", "# out for loops, which lint otherwise mistakenly thinks are functions.", "if", "not", "Search", "(", "r'(for|swap|Swap|operator[<>][<>])\\s*\\(\\s*'", "r'(?:(?:typename\\s*)?[\\w:]|<.*>)+\\s*&'", ",", "fnline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer.'", ")", "# Check to see if they're using an conversion function cast.", "# I just try to capture the most common basic types, though there are more.", "# Parameterless conversion functions, such as bool(), are allowed as they are", "# probably a member operator declaration or default constructor.", "match", "=", "Search", "(", "r'(\\bnew\\s+)?\\b'", "# Grab 'new' operator, if it's there", "r'(int|float|double|bool|char|int32|uint32|int64|uint64)\\([^)]'", ",", "line", ")", "if", "match", ":", "# gMock methods are defined using some variant of MOCK_METHODx(name, type)", "# where type may be float(), int(string), etc. Without context they are", "# virtually indistinguishable from int(x) casts. Likewise, gMock's", "# MockCallback takes a template parameter of the form return_type(arg_type),", "# which looks much like the cast we're trying to detect.", "if", "(", "match", ".", "group", "(", "1", ")", "is", "None", "and", "# If new operator, then this isn't a cast", "not", "(", "Match", "(", "r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('", ",", "line", ")", "or", "Match", "(", "r'^\\s*MockCallback<.*>'", ",", "line", ")", ")", ")", ":", "# Try a bit harder to catch gmock lines: the only place where", "# something looks like an old-style cast is where we declare the", "# return type of the mocked method, and the only time when we", "# are missing context is if MOCK_METHOD was split across", "# multiple lines (for example http://go/hrfhr ), so we only need", "# to check the previous line for MOCK_METHOD.", "if", "(", "linenum", "==", "0", "or", "not", "Match", "(", "r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\(\\S+,\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using deprecated casting style. '", "'Use static_cast<%s>(...) instead'", "%", "match", ".", "group", "(", "2", ")", ")", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "clean_lines", ".", "raw_lines", "[", "linenum", "]", ",", "'static_cast'", ",", "r'\\((int|float|double|bool|char|u?int(16|32|64))\\)'", ",", "error", ")", "# This doesn't catch all cases. Consider (const char * const)\"hello\".", "#", "# (char *) \"foo\" should always be a const_cast (reinterpret_cast won't", "# compile).", "if", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "clean_lines", ".", "raw_lines", "[", "linenum", "]", ",", "'const_cast'", ",", "r'\\((char\\s?\\*+\\s?)\\)\\s*\"'", ",", "error", ")", ":", "pass", "else", ":", "# Check pointer casts for other than string constants", "CheckCStyleCast", "(", "filename", ",", "linenum", ",", "line", ",", "clean_lines", ".", "raw_lines", "[", "linenum", "]", ",", "'reinterpret_cast'", ",", "r'\\((\\w+\\s?\\*+\\s?)\\)'", ",", "error", ")", "# In addition, we look for people taking the address of a cast. This", "# is dangerous -- casts can assign to temporaries, so the pointer doesn't", "# point where you think.", "if", "Search", "(", "r'(&\\([^)]+\\)[\\w(])|(&(static|dynamic|reinterpret)_cast\\b)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/casting'", ",", "4", ",", "(", "'Are you taking an address of a cast? '", "'This is dangerous: could be a temp var. '", "'Take the address before doing the cast, rather than after'", ")", ")", "# Check for people declaring static/global STL strings at the top level.", "# This is dangerous because the C++ language does not guarantee that", "# globals with constructors are initialized before the first access.", "match", "=", "Match", "(", "r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)'", ",", "line", ")", "# Make sure it's not a function.", "# Function template specialization looks like: \"string foo<Type>(...\".", "# Class template definitions look like: \"string Foo<Type>::Method(...\".", "if", "match", "and", "not", "Match", "(", "r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)?\\s*\\(([^\"]|$)'", ",", "match", ".", "group", "(", "3", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/string'", ",", "4", ",", "'For a static/global string constant, use a C style string instead: '", "'\"%schar %s[]\".'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "# Check that we're not using RTTI outside of testing code.", "if", "Search", "(", "r'\\bdynamic_cast<'", ",", "line", ")", "and", "not", "_IsTestFilename", "(", "filename", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/rtti'", ",", "5", ",", "'Do not use dynamic_cast<>. If you need to cast within a class '", "\"hierarchy, use static_cast<> to upcast. Google doesn't support \"", "'RTTI.'", ")", "if", "Search", "(", "r'\\b([A-Za-z0-9_]*_)\\(\\1\\)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/init'", ",", "4", ",", "'You seem to be initializing a member variable with itself.'", ")", "if", "file_extension", "==", "'h'", ":", "# TODO(unknown): check that 1-arg constructors are explicit.", "# How to tell it's a constructor?", "# (handled in CheckForNonStandardConstructs for now)", "# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS", "# (level 1 error)", "pass", "# Check if people are using the verboten C basic types. The only exception", "# we regularly allow is \"unsigned short port\" for port.", "if", "Search", "(", "r'\\bshort port\\b'", ",", "line", ")", ":", "if", "not", "Search", "(", "r'\\bunsigned short port\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/int'", ",", "4", ",", "'Use \"unsigned short\" for ports, not \"short\"'", ")", "else", ":", "match", "=", "Search", "(", "r'\\b(short|long(?! +double)|long long)\\b'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/int'", ",", "4", ",", "'Use int16/int64/etc, rather than the C type %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# When snprintf is used, the second argument shouldn't be a literal.", "match", "=", "Search", "(", "r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'", ",", "line", ")", "if", "match", "and", "match", ".", "group", "(", "2", ")", "!=", "'0'", ":", "# If 2nd arg is zero, snprintf is used to calculate size.", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "3", ",", "'If you can, use sizeof(%s) instead of %s as the 2nd arg '", "'to snprintf.'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "# Check if some verboten C functions are being used.", "if", "Search", "(", "r'\\bsprintf\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "5", ",", "'Never use sprintf. Use snprintf instead.'", ")", "match", "=", "Search", "(", "r'\\b(strcpy|strcat)\\b'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "4", ",", "'Almost always, snprintf is better than %s'", "%", "match", ".", "group", "(", "1", ")", ")", "if", "Search", "(", "r'\\bsscanf\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "1", ",", "'sscanf can be ok, but is slow and can overflow buffers.'", ")", "# Check if some verboten operator overloading is going on", "# TODO(unknown): catch out-of-line unary operator&:", "# class X {};", "# int operator&(const X& x) { return 42; } // unary operator&", "# The trick is it's hard to tell apart from binary operator&:", "# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&", "if", "Search", "(", "r'\\boperator\\s*&\\s*\\(\\s*\\)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/operator'", ",", "4", ",", "'Unary operator& is dangerous. Do not use it.'", ")", "# Check for suspicious usage of \"if\" like", "# } if (a == b) {", "if", "Search", "(", "r'\\}\\s*if\\s*\\('", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "'Did you mean \"else if\"? If not, start a new line for \"if\".'", ")", "# Check for potential format string bugs like printf(foo).", "# We constrain the pattern not to pick things like DocidForPrintf(foo).", "# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())", "# TODO(sugawarayu): Catch the following case. Need to change the calling", "# convention of the whole function to process multiple line to handle it.", "# printf(", "# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);", "printf_args", "=", "_GetTextInside", "(", "line", ",", "r'(?i)\\b(string)?printf\\s*\\('", ")", "if", "printf_args", ":", "match", "=", "Match", "(", "r'([\\w.\\->()]+)$'", ",", "printf_args", ")", "if", "match", "and", "match", ".", "group", "(", "1", ")", "!=", "'__VA_ARGS__'", ":", "function_name", "=", "re", ".", "search", "(", "r'\\b((?:string)?printf)\\s*\\('", ",", "line", ",", "re", ".", "I", ")", ".", "group", "(", "1", ")", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "4", ",", "'Potential format string bug. Do %s(\"%%s\", %s) instead.'", "%", "(", "function_name", ",", "match", ".", "group", "(", "1", ")", ")", ")", "# Check for potential memset bugs like memset(buf, sizeof(buf), 0).", "match", "=", "Search", "(", "r'memset\\s*\\(([^,]*),\\s*([^,]*),\\s*0\\s*\\)'", ",", "line", ")", "if", "match", "and", "not", "Match", "(", "r\"^''|-?[0-9]+|0x[0-9A-Fa-f]$\"", ",", "match", ".", "group", "(", "2", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/memset'", ",", "4", ",", "'Did you mean \"memset(%s, 0, %s)\"?'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "if", "Search", "(", "r'\\busing namespace\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/namespaces'", ",", "5", ",", "'Do not use namespace using-directives. '", "'Use using-declarations instead.'", ")", "# Detect variable-length arrays.", "match", "=", "Match", "(", "r'\\s*(.+::)?(\\w+) [a-z]\\w*\\[(.+)];'", ",", "line", ")", "if", "(", "match", "and", "match", ".", "group", "(", "2", ")", "!=", "'return'", "and", "match", ".", "group", "(", "2", ")", "!=", "'delete'", "and", "match", ".", "group", "(", "3", ")", ".", "find", "(", "']'", ")", "==", "-", "1", ")", ":", "# Split the size using space and arithmetic operators as delimiters.", "# If any of the resulting tokens are not compile time constants then", "# report the error.", "tokens", "=", "re", ".", "split", "(", "r'\\s|\\+|\\-|\\*|\\/|<<|>>]'", ",", "match", ".", "group", "(", "3", ")", ")", "is_const", "=", "True", "skip_next", "=", "False", "for", "tok", "in", "tokens", ":", "if", "skip_next", ":", "skip_next", "=", "False", "continue", "if", "Search", "(", "r'sizeof\\(.+\\)'", ",", "tok", ")", ":", "continue", "if", "Search", "(", "r'arraysize\\(\\w+\\)'", ",", "tok", ")", ":", "continue", "tok", "=", "tok", ".", "lstrip", "(", "'('", ")", "tok", "=", "tok", ".", "rstrip", "(", "')'", ")", "if", "not", "tok", ":", "continue", "if", "Match", "(", "r'\\d+'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'0[xX][0-9a-fA-F]+'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'k[A-Z0-9]\\w*'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'(.+::)?k[A-Z0-9]\\w*'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'(.+::)?[A-Z][A-Z0-9_]*'", ",", "tok", ")", ":", "continue", "# A catch all for tricky sizeof cases, including 'sizeof expression',", "# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'", "# requires skipping the next token because we split on ' ' and '*'.", "if", "tok", ".", "startswith", "(", "'sizeof'", ")", ":", "skip_next", "=", "True", "continue", "is_const", "=", "False", "break", "if", "not", "is_const", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/arrays'", ",", "1", ",", "'Do not use variable-length arrays. Use an appropriately named '", "\"('k' followed by CamelCase) compile-time constant for the size.\"", ")", "# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or", "# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing", "# in the class declaration.", "match", "=", "Match", "(", "(", "r'\\s*'", "r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'", "r'\\(.*\\);$'", ")", ",", "line", ")", "if", "match", "and", "linenum", "+", "1", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "next_line", "=", "clean_lines", ".", "elided", "[", "linenum", "+", "1", "]", "# We allow some, but not all, declarations of variables to be present", "# in the statement that defines the class. The [\\w\\*,\\s]* fragment of", "# the regular expression below allows users to declare instances of", "# the class or pointers to instances, but not less common types such", "# as function pointers or arrays. It's a tradeoff between allowing", "# reasonable code and avoiding trying to parse more C++ using regexps.", "if", "not", "Search", "(", "r'^\\s*}[\\w\\*,\\s]*;'", ",", "next_line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/constructors'", ",", "3", ",", "match", ".", "group", "(", "1", ")", "+", "' should be the last thing in the class'", ")", "# Check for use of unnamed namespaces in header files. Registration", "# macros are typically OK, so we allow use of \"namespace {\" on lines", "# that end with backslashes.", "if", "(", "file_extension", "==", "'h'", "and", "Search", "(", "r'\\bnamespace\\s*{'", ",", "line", ")", "and", "line", "[", "-", "1", "]", "!=", "'\\\\'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/namespaces'", ",", "4", ",", "'Do not use unnamed namespaces in header files. See '", "'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'", "' for more information.'", ")" ]
https://github.com/s5z/zsim/blob/fb4d6e0475a25cffd23f0687ede2d43d96b4a99f/misc/cpplint.py#L3142-L3443
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
PyControl.DoGetVirtualSize
(*args, **kwargs)
return _controls_.PyControl_DoGetVirtualSize(*args, **kwargs)
DoGetVirtualSize(self) -> Size
DoGetVirtualSize(self) -> Size
[ "DoGetVirtualSize", "(", "self", ")", "-", ">", "Size" ]
def DoGetVirtualSize(*args, **kwargs): """DoGetVirtualSize(self) -> Size""" return _controls_.PyControl_DoGetVirtualSize(*args, **kwargs)
[ "def", "DoGetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "PyControl_DoGetVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5870-L5872
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/robotinterface.py
python
RobotInterfaceBase.beginStep
(self)
This is called before the commands sent at each time step
This is called before the commands sent at each time step
[ "This", "is", "called", "before", "the", "commands", "sent", "at", "each", "time", "step" ]
def beginStep(self) -> None: """This is called before the commands sent at each time step""" pass
[ "def", "beginStep", "(", "self", ")", "->", "None", ":", "pass" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L288-L290
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/jsontemplate/jsontemplate.py
python
_ScopedContext.__init__
(self, context, undefined_str)
Args: context: The root context undefined_str: See Template() constructor.
Args: context: The root context undefined_str: See Template() constructor.
[ "Args", ":", "context", ":", "The", "root", "context", "undefined_str", ":", "See", "Template", "()", "constructor", "." ]
def __init__(self, context, undefined_str): """ Args: context: The root context undefined_str: See Template() constructor. """ self.stack = [_Frame(context)] self.undefined_str = undefined_str
[ "def", "__init__", "(", "self", ",", "context", ",", "undefined_str", ")", ":", "self", ".", "stack", "=", "[", "_Frame", "(", "context", ")", "]", "self", ".", "undefined_str", "=", "undefined_str" ]
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/jsontemplate/jsontemplate.py#L445-L452
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/reconstruction.py
python
paint_reconstruction
(data, graph, reconstruction)
Set the color of the points from the color of the tracks.
Set the color of the points from the color of the tracks.
[ "Set", "the", "color", "of", "the", "points", "from", "the", "color", "of", "the", "tracks", "." ]
def paint_reconstruction(data, graph, reconstruction): """Set the color of the points from the color of the tracks.""" for k, point in iteritems(reconstruction.points): point.color = six.next(six.itervalues(graph[k]))['feature_color']
[ "def", "paint_reconstruction", "(", "data", ",", "graph", ",", "reconstruction", ")", ":", "for", "k", ",", "point", "in", "iteritems", "(", "reconstruction", ".", "points", ")", ":", "point", ".", "color", "=", "six", ".", "next", "(", "six", ".", "itervalues", "(", "graph", "[", "k", "]", ")", ")", "[", "'feature_color'", "]" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/reconstruction.py#L1014-L1017
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/tableparser.py
python
GridTableParser.scan_left
(self, top, left, bottom, right)
return None
Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point.
Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point.
[ "Noting", "column", "boundaries", "look", "for", "the", "bottom", "-", "left", "corner", "of", "the", "cell", ".", "It", "must", "line", "up", "with", "the", "starting", "point", "." ]
def scan_left(self, top, left, bottom, right): """ Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. """ colseps = {} line = self.block[bottom] for i in range(right - 1, left, -1): if line[i] == '+': colseps[i] = [bottom] elif line[i] != '-': return None if line[left] != '+': return None result = self.scan_up(top, left, bottom, right) if result is not None: rowseps = result return rowseps, colseps return None
[ "def", "scan_left", "(", "self", ",", "top", ",", "left", ",", "bottom", ",", "right", ")", ":", "colseps", "=", "{", "}", "line", "=", "self", ".", "block", "[", "bottom", "]", "for", "i", "in", "range", "(", "right", "-", "1", ",", "left", ",", "-", "1", ")", ":", "if", "line", "[", "i", "]", "==", "'+'", ":", "colseps", "[", "i", "]", "=", "[", "bottom", "]", "elif", "line", "[", "i", "]", "!=", "'-'", ":", "return", "None", "if", "line", "[", "left", "]", "!=", "'+'", ":", "return", "None", "result", "=", "self", ".", "scan_up", "(", "top", ",", "left", ",", "bottom", ",", "right", ")", "if", "result", "is", "not", "None", ":", "rowseps", "=", "result", "return", "rowseps", ",", "colseps", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/tableparser.py#L252-L270
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
__wxMemoryFSHandler_AddFile_Data
(*args, **kwargs)
return _core_.__wxMemoryFSHandler_AddFile_Data(*args, **kwargs)
__wxMemoryFSHandler_AddFile_Data(String filename, buffer data)
__wxMemoryFSHandler_AddFile_Data(String filename, buffer data)
[ "__wxMemoryFSHandler_AddFile_Data", "(", "String", "filename", "buffer", "data", ")" ]
def __wxMemoryFSHandler_AddFile_Data(*args, **kwargs): """__wxMemoryFSHandler_AddFile_Data(String filename, buffer data)""" return _core_.__wxMemoryFSHandler_AddFile_Data(*args, **kwargs)
[ "def", "__wxMemoryFSHandler_AddFile_Data", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "__wxMemoryFSHandler_AddFile_Data", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2535-L2537
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/wsgiref/simple_server.py
python
make_server
( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler )
return server
Create a new WSGI server listening on `host` and `port` for `app`
Create a new WSGI server listening on `host` and `port` for `app`
[ "Create", "a", "new", "WSGI", "server", "listening", "on", "host", "and", "port", "for", "app" ]
def make_server( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler ): """Create a new WSGI server listening on `host` and `port` for `app`""" server = server_class((host, port), handler_class) server.set_app(app) return server
[ "def", "make_server", "(", "host", ",", "port", ",", "app", ",", "server_class", "=", "WSGIServer", ",", "handler_class", "=", "WSGIRequestHandler", ")", ":", "server", "=", "server_class", "(", "(", "host", ",", "port", ")", ",", "handler_class", ")", "server", ".", "set_app", "(", "app", ")", "return", "server" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/wsgiref/simple_server.py#L150-L156
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/server.py
python
HTTPServer.server_bind
(self)
Override server_bind to store the server name.
Override server_bind to store the server name.
[ "Override", "server_bind", "to", "store", "the", "server", "name", "." ]
def server_bind(self): """Override server_bind to store the server name.""" socketserver.TCPServer.server_bind(self) host, port = self.server_address[:2] self.server_name = socket.getfqdn(host) self.server_port = port
[ "def", "server_bind", "(", "self", ")", ":", "socketserver", ".", "TCPServer", ".", "server_bind", "(", "self", ")", "host", ",", "port", "=", "self", ".", "server_address", "[", ":", "2", "]", "self", ".", "server_name", "=", "socket", ".", "getfqdn", "(", "host", ")", "self", ".", "server_port", "=", "port" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/server.py#L135-L140
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/model.py
python
_train_multi_device
(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_data, eval_data=None, eval_metric=None, epoch_end_callback=None, batch_end_callback=None, logger=None, work_load_list=None, monitor=None, eval_end_callback=None, eval_batch_end_callback=None, sym_gen=None)
return
Internal training function on multiple devices. This function will also work for single device as well. Parameters ---------- symbol : Symbol The network configuration. ctx : list of Context The training devices. arg_names: list of str Name of all arguments of the network. param_names: list of str Name of all trainable parameters of the network. aux_names: list of str Name of all auxiliary states of the network. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's auxiliary states. begin_epoch : int The begining training epoch. end_epoch : int The end training epoch. epoch_size : int, optional Number of batches in a epoch. In default, it is set to ``ceil(num_train_examples / batch_size)``. optimizer : Optimizer The optimization algorithm train_data : DataIter Training data iterator. eval_data : DataIter Validation data iterator. eval_metric : EvalMetric An evaluation function or a list of evaluation functions. epoch_end_callback : callable(epoch, symbol, arg_params, aux_states) A callback that is invoked at end of each epoch. This can be used to checkpoint model each epoch. batch_end_callback : callable(BatchEndParams) A callback that is invoked at end of each batch. This can be used to measure speed, get result from evaluation metric. etc. kvstore : KVStore The KVStore. update_on_kvstore : bool Whether or not perform weight updating on kvstore. logger : logging logger When not specified, default logger will be used. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as ``ctx``. monitor : Monitor, optional Monitor installed to executor, for monitoring outputs, weights, and gradients for debugging. Notes ----- - This function will inplace update the NDArrays in `arg_params` and `aux_states`.
Internal training function on multiple devices. This function will also work for single device as well.
[ "Internal", "training", "function", "on", "multiple", "devices", ".", "This", "function", "will", "also", "work", "for", "single", "device", "as", "well", "." ]
def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_data, eval_data=None, eval_metric=None, epoch_end_callback=None, batch_end_callback=None, logger=None, work_load_list=None, monitor=None, eval_end_callback=None, eval_batch_end_callback=None, sym_gen=None): """Internal training function on multiple devices. This function will also work for single device as well. Parameters ---------- symbol : Symbol The network configuration. ctx : list of Context The training devices. arg_names: list of str Name of all arguments of the network. param_names: list of str Name of all trainable parameters of the network. aux_names: list of str Name of all auxiliary states of the network. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's auxiliary states. begin_epoch : int The begining training epoch. end_epoch : int The end training epoch. epoch_size : int, optional Number of batches in a epoch. In default, it is set to ``ceil(num_train_examples / batch_size)``. optimizer : Optimizer The optimization algorithm train_data : DataIter Training data iterator. eval_data : DataIter Validation data iterator. eval_metric : EvalMetric An evaluation function or a list of evaluation functions. epoch_end_callback : callable(epoch, symbol, arg_params, aux_states) A callback that is invoked at end of each epoch. This can be used to checkpoint model each epoch. batch_end_callback : callable(BatchEndParams) A callback that is invoked at end of each batch. This can be used to measure speed, get result from evaluation metric. etc. kvstore : KVStore The KVStore. update_on_kvstore : bool Whether or not perform weight updating on kvstore. logger : logging logger When not specified, default logger will be used. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as ``ctx``. monitor : Monitor, optional Monitor installed to executor, for monitoring outputs, weights, and gradients for debugging. Notes ----- - This function will inplace update the NDArrays in `arg_params` and `aux_states`. """ if logger is None: logger = logging executor_manager = DataParallelExecutorManager(symbol=symbol, sym_gen=sym_gen, ctx=ctx, train_data=train_data, param_names=param_names, arg_names=arg_names, aux_names=aux_names, work_load_list=work_load_list, logger=logger) if monitor: executor_manager.install_monitor(monitor) executor_manager.set_params(arg_params, aux_params) if not update_on_kvstore: updater = get_updater(optimizer) if kvstore: _initialize_kvstore(kvstore=kvstore, param_arrays=executor_manager.param_arrays, arg_params=arg_params, param_names=executor_manager.param_names, update_on_kvstore=update_on_kvstore) if update_on_kvstore: kvstore.set_optimizer(optimizer) # Now start training train_data.reset() for epoch in range(begin_epoch, end_epoch): # Training phase tic = time.time() eval_metric.reset() nbatch = 0 # Iterate over training data. while True: do_reset = True for data_batch in train_data: executor_manager.load_data_batch(data_batch) if monitor is not None: monitor.tic() executor_manager.forward(is_train=True) executor_manager.backward() if update_on_kvstore: if 'nccl' in kvstore.type: _update_params_on_kvstore_nccl(executor_manager.param_arrays, executor_manager.grad_arrays, kvstore, executor_manager.param_names) else: _update_params_on_kvstore(executor_manager.param_arrays, executor_manager.grad_arrays, kvstore, executor_manager.param_names) else: _update_params(executor_manager.param_arrays, executor_manager.grad_arrays, updater=updater, num_device=len(ctx), kvstore=kvstore, param_names=executor_manager.param_names) if monitor is not None: monitor.toc_print() # evaluate at end, so we can lazy copy executor_manager.update_metric(eval_metric, data_batch.label) nbatch += 1 # batch callback (for print purpose) if batch_end_callback is not None: batch_end_params = BatchEndParam(epoch=epoch, nbatch=nbatch, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(batch_end_callback, batch_end_params) # this epoch is done possibly earlier if epoch_size is not None and nbatch >= epoch_size: do_reset = False break if do_reset: logger.info('Epoch[%d] Resetting Data Iterator', epoch) train_data.reset() # this epoch is done if epoch_size is None or nbatch >= epoch_size: break toc = time.time() logger.info('Epoch[%d] Time cost=%.3f', epoch, (toc - tic)) if epoch_end_callback or epoch + 1 == end_epoch: executor_manager.copy_to(arg_params, aux_params) _multiple_callbacks(epoch_end_callback, epoch, symbol, arg_params, aux_params) # evaluation if eval_data: eval_metric.reset() eval_data.reset() total_num_batch = 0 for i, eval_batch in enumerate(eval_data): executor_manager.load_data_batch(eval_batch) executor_manager.forward(is_train=False) executor_manager.update_metric(eval_metric, eval_batch.label) if eval_batch_end_callback is not None: batch_end_params = BatchEndParam(epoch=epoch, nbatch=i, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(eval_batch_end_callback, batch_end_params) total_num_batch += 1 if eval_end_callback is not None: eval_end_params = BatchEndParam(epoch=epoch, nbatch=total_num_batch, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(eval_end_callback, eval_end_params) eval_data.reset() # end of all epochs return
[ "def", "_train_multi_device", "(", "symbol", ",", "ctx", ",", "arg_names", ",", "param_names", ",", "aux_names", ",", "arg_params", ",", "aux_params", ",", "begin_epoch", ",", "end_epoch", ",", "epoch_size", ",", "optimizer", ",", "kvstore", ",", "update_on_kvstore", ",", "train_data", ",", "eval_data", "=", "None", ",", "eval_metric", "=", "None", ",", "epoch_end_callback", "=", "None", ",", "batch_end_callback", "=", "None", ",", "logger", "=", "None", ",", "work_load_list", "=", "None", ",", "monitor", "=", "None", ",", "eval_end_callback", "=", "None", ",", "eval_batch_end_callback", "=", "None", ",", "sym_gen", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "logging", "executor_manager", "=", "DataParallelExecutorManager", "(", "symbol", "=", "symbol", ",", "sym_gen", "=", "sym_gen", ",", "ctx", "=", "ctx", ",", "train_data", "=", "train_data", ",", "param_names", "=", "param_names", ",", "arg_names", "=", "arg_names", ",", "aux_names", "=", "aux_names", ",", "work_load_list", "=", "work_load_list", ",", "logger", "=", "logger", ")", "if", "monitor", ":", "executor_manager", ".", "install_monitor", "(", "monitor", ")", "executor_manager", ".", "set_params", "(", "arg_params", ",", "aux_params", ")", "if", "not", "update_on_kvstore", ":", "updater", "=", "get_updater", "(", "optimizer", ")", "if", "kvstore", ":", "_initialize_kvstore", "(", "kvstore", "=", "kvstore", ",", "param_arrays", "=", "executor_manager", ".", "param_arrays", ",", "arg_params", "=", "arg_params", ",", "param_names", "=", "executor_manager", ".", "param_names", ",", "update_on_kvstore", "=", "update_on_kvstore", ")", "if", "update_on_kvstore", ":", "kvstore", ".", "set_optimizer", "(", "optimizer", ")", "# Now start training", "train_data", ".", "reset", "(", ")", "for", "epoch", "in", "range", "(", "begin_epoch", ",", "end_epoch", ")", ":", "# Training phase", "tic", "=", "time", ".", "time", "(", ")", "eval_metric", ".", "reset", "(", ")", "nbatch", "=", "0", "# Iterate over training data.", "while", "True", ":", "do_reset", "=", "True", "for", "data_batch", "in", "train_data", ":", "executor_manager", ".", "load_data_batch", "(", "data_batch", ")", "if", "monitor", "is", "not", "None", ":", "monitor", ".", "tic", "(", ")", "executor_manager", ".", "forward", "(", "is_train", "=", "True", ")", "executor_manager", ".", "backward", "(", ")", "if", "update_on_kvstore", ":", "if", "'nccl'", "in", "kvstore", ".", "type", ":", "_update_params_on_kvstore_nccl", "(", "executor_manager", ".", "param_arrays", ",", "executor_manager", ".", "grad_arrays", ",", "kvstore", ",", "executor_manager", ".", "param_names", ")", "else", ":", "_update_params_on_kvstore", "(", "executor_manager", ".", "param_arrays", ",", "executor_manager", ".", "grad_arrays", ",", "kvstore", ",", "executor_manager", ".", "param_names", ")", "else", ":", "_update_params", "(", "executor_manager", ".", "param_arrays", ",", "executor_manager", ".", "grad_arrays", ",", "updater", "=", "updater", ",", "num_device", "=", "len", "(", "ctx", ")", ",", "kvstore", "=", "kvstore", ",", "param_names", "=", "executor_manager", ".", "param_names", ")", "if", "monitor", "is", "not", "None", ":", "monitor", ".", "toc_print", "(", ")", "# evaluate at end, so we can lazy copy", "executor_manager", ".", "update_metric", "(", "eval_metric", ",", "data_batch", ".", "label", ")", "nbatch", "+=", "1", "# batch callback (for print purpose)", "if", "batch_end_callback", "is", "not", "None", ":", "batch_end_params", "=", "BatchEndParam", "(", "epoch", "=", "epoch", ",", "nbatch", "=", "nbatch", ",", "eval_metric", "=", "eval_metric", ",", "locals", "=", "locals", "(", ")", ")", "_multiple_callbacks", "(", "batch_end_callback", ",", "batch_end_params", ")", "# this epoch is done possibly earlier", "if", "epoch_size", "is", "not", "None", "and", "nbatch", ">=", "epoch_size", ":", "do_reset", "=", "False", "break", "if", "do_reset", ":", "logger", ".", "info", "(", "'Epoch[%d] Resetting Data Iterator'", ",", "epoch", ")", "train_data", ".", "reset", "(", ")", "# this epoch is done", "if", "epoch_size", "is", "None", "or", "nbatch", ">=", "epoch_size", ":", "break", "toc", "=", "time", ".", "time", "(", ")", "logger", ".", "info", "(", "'Epoch[%d] Time cost=%.3f'", ",", "epoch", ",", "(", "toc", "-", "tic", ")", ")", "if", "epoch_end_callback", "or", "epoch", "+", "1", "==", "end_epoch", ":", "executor_manager", ".", "copy_to", "(", "arg_params", ",", "aux_params", ")", "_multiple_callbacks", "(", "epoch_end_callback", ",", "epoch", ",", "symbol", ",", "arg_params", ",", "aux_params", ")", "# evaluation", "if", "eval_data", ":", "eval_metric", ".", "reset", "(", ")", "eval_data", ".", "reset", "(", ")", "total_num_batch", "=", "0", "for", "i", ",", "eval_batch", "in", "enumerate", "(", "eval_data", ")", ":", "executor_manager", ".", "load_data_batch", "(", "eval_batch", ")", "executor_manager", ".", "forward", "(", "is_train", "=", "False", ")", "executor_manager", ".", "update_metric", "(", "eval_metric", ",", "eval_batch", ".", "label", ")", "if", "eval_batch_end_callback", "is", "not", "None", ":", "batch_end_params", "=", "BatchEndParam", "(", "epoch", "=", "epoch", ",", "nbatch", "=", "i", ",", "eval_metric", "=", "eval_metric", ",", "locals", "=", "locals", "(", ")", ")", "_multiple_callbacks", "(", "eval_batch_end_callback", ",", "batch_end_params", ")", "total_num_batch", "+=", "1", "if", "eval_end_callback", "is", "not", "None", ":", "eval_end_params", "=", "BatchEndParam", "(", "epoch", "=", "epoch", ",", "nbatch", "=", "total_num_batch", ",", "eval_metric", "=", "eval_metric", ",", "locals", "=", "locals", "(", ")", ")", "_multiple_callbacks", "(", "eval_end_callback", ",", "eval_end_params", ")", "eval_data", ".", "reset", "(", ")", "# end of all epochs", "return" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/model.py#L173-L363
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/configure.d/nodedownload.py
python
checkHash
(targetfile, hashAlgo)
return digest.hexdigest()
Check a file using hashAlgo. Return the hex digest.
Check a file using hashAlgo. Return the hex digest.
[ "Check", "a", "file", "using", "hashAlgo", ".", "Return", "the", "hex", "digest", "." ]
def checkHash(targetfile, hashAlgo): """Check a file using hashAlgo. Return the hex digest.""" digest = hashlib.new(hashAlgo) with open(targetfile, 'rb') as f: chunk = f.read(1024) while len(chunk) > 0: digest.update(chunk) chunk = f.read(1024) return digest.hexdigest()
[ "def", "checkHash", "(", "targetfile", ",", "hashAlgo", ")", ":", "digest", "=", "hashlib", ".", "new", "(", "hashAlgo", ")", "with", "open", "(", "targetfile", ",", "'rb'", ")", "as", "f", ":", "chunk", "=", "f", ".", "read", "(", "1024", ")", "while", "len", "(", "chunk", ")", ">", "0", ":", "digest", ".", "update", "(", "chunk", ")", "chunk", "=", "f", ".", "read", "(", "1024", ")", "return", "digest", ".", "hexdigest", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/configure.d/nodedownload.py#L61-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py
python
_GMMBase.score_samples
(self, X)
return logprob, responsibilities
Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- X: array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : array_like, shape (n_samples,) Log probabilities of each data point in X. responsibilities : array_like, shape (n_samples, n_components) Posterior probabilities of each mixture component for each observation
Return the per-sample likelihood of the data under the model.
[ "Return", "the", "per", "-", "sample", "likelihood", "of", "the", "data", "under", "the", "model", "." ]
def score_samples(self, X): """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- X: array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : array_like, shape (n_samples,) Log probabilities of each data point in X. responsibilities : array_like, shape (n_samples, n_components) Posterior probabilities of each mixture component for each observation """ check_is_fitted(self, 'means_') X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] if X.size == 0: return np.array([]), np.empty((0, self.n_components)) if X.shape[1] != self.means_.shape[1]: raise ValueError('The shape of X is not compatible with self') lpr = (log_multivariate_normal_density(X, self.means_, self.covars_, self.covariance_type) + np.log(self.weights_)) logprob = logsumexp(lpr, axis=1) responsibilities = np.exp(lpr - logprob[:, np.newaxis]) return logprob, responsibilities
[ "def", "score_samples", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "X", "=", "check_array", "(", "X", ")", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", ":", ",", "np", ".", "newaxis", "]", "if", "X", ".", "size", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "np", ".", "empty", "(", "(", "0", ",", "self", ".", "n_components", ")", ")", "if", "X", ".", "shape", "[", "1", "]", "!=", "self", ".", "means_", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'The shape of X is not compatible with self'", ")", "lpr", "=", "(", "log_multivariate_normal_density", "(", "X", ",", "self", ".", "means_", ",", "self", ".", "covars_", ",", "self", ".", "covariance_type", ")", "+", "np", ".", "log", "(", "self", ".", "weights_", ")", ")", "logprob", "=", "logsumexp", "(", "lpr", ",", "axis", "=", "1", ")", "responsibilities", "=", "np", ".", "exp", "(", "lpr", "-", "logprob", "[", ":", ",", "np", ".", "newaxis", "]", ")", "return", "logprob", ",", "responsibilities" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py#L302-L339
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/primitive/gen4controller.py
python
Gen4ControllerCommand.set_data_source
(self, source_id)
Sets the data source buffer :param source_id: data source buffer ID
Sets the data source buffer
[ "Sets", "the", "data", "source", "buffer" ]
def set_data_source(self, source_id): """ Sets the data source buffer :param source_id: data source buffer ID """ self.data_source = source_id
[ "def", "set_data_source", "(", "self", ",", "source_id", ")", ":", "self", ".", "data_source", "=", "source_id" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/primitive/gen4controller.py#L56-L62
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
urllib3/packages/six.py
python
remove_move
(name)
Remove item from six.moves.
Remove item from six.moves.
[ "Remove", "item", "from", "six", ".", "moves", "." ]
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
[ "def", "remove_move", "(", "name", ")", ":", "try", ":", "delattr", "(", "_MovedItems", ",", "name", ")", "except", "AttributeError", ":", "try", ":", "del", "moves", ".", "__dict__", "[", "name", "]", "except", "KeyError", ":", "raise", "AttributeError", "(", "\"no such move, %r\"", "%", "(", "name", ",", ")", ")" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/packages/six.py#L194-L202
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py
python
CodeGenerator.visit_Extends
(self, node, frame)
Calls the extender.
Calls the extender.
[ "Calls", "the", "extender", "." ]
def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1
[ "def", "visit_Extends", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "not", "frame", ".", "toplevel", ":", "self", ".", "fail", "(", "'cannot use extend from a non top-level scope'", ",", "node", ".", "lineno", ")", "# if the number of extends statements in general is zero so", "# far, we don't have to add a check if something extended", "# the template before this one.", "if", "self", ".", "extends_so_far", ">", "0", ":", "# if we have a known extends we just add a template runtime", "# error into the generated code. We could catch that at compile", "# time too, but i welcome it not to confuse users by throwing the", "# same error at different times just \"because we can\".", "if", "not", "self", ".", "has_known_extends", ":", "self", ".", "writeline", "(", "'if parent_template is not None:'", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(", "'raise TemplateRuntimeError(%r)'", "%", "'extended multiple times'", ")", "# if we have a known extends already we don't need that code here", "# as we know that the template execution will end here.", "if", "self", ".", "has_known_extends", ":", "raise", "CompilerExit", "(", ")", "else", ":", "self", ".", "outdent", "(", ")", "self", ".", "writeline", "(", "'parent_template = environment.get_template('", ",", "node", ")", "self", ".", "visit", "(", "node", ".", "template", ",", "frame", ")", "self", ".", "write", "(", "', %r)'", "%", "self", ".", "name", ")", "self", ".", "writeline", "(", "'for name, parent_block in parent_template.'", "'blocks.%s():'", "%", "dict_item_iter", ")", "self", ".", "indent", "(", ")", "self", ".", "writeline", "(", "'context.blocks.setdefault(name, []).'", "'append(parent_block)'", ")", "self", ".", "outdent", "(", ")", "# if this extends statement was in the root level we can take", "# advantage of that information and simplify the generated code", "# in the top level from this point onwards", "if", "frame", ".", "rootlevel", ":", "self", ".", "has_known_extends", "=", "True", "# and now we have one more", "self", ".", "extends_so_far", "+=", "1" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py#L843-L888
blakesmith/embedded
61d02c8feed34eff75fe64f29cc8997f1c480867
nome/hardware/KiBoM/KiBOM/netlist_reader.py
python
netlist.getVersion
(self)
return sheet.get("rev")
Return the verison of the sheet info
Return the verison of the sheet info
[ "Return", "the", "verison", "of", "the", "sheet", "info" ]
def getVersion(self): """Return the verison of the sheet info""" sheet = self.getSheet() if sheet == None: return "" return sheet.get("rev")
[ "def", "getVersion", "(", "self", ")", ":", "sheet", "=", "self", ".", "getSheet", "(", ")", "if", "sheet", "==", "None", ":", "return", "\"\"", "return", "sheet", ".", "get", "(", "\"rev\"", ")" ]
https://github.com/blakesmith/embedded/blob/61d02c8feed34eff75fe64f29cc8997f1c480867/nome/hardware/KiBoM/KiBOM/netlist_reader.py#L381-L385
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/scripts/cpp_lint.py
python
FileInfo.FullName
(self)
return os.path.abspath(self._filename).replace('\\', '/')
Make Windows paths like Unix.
Make Windows paths like Unix.
[ "Make", "Windows", "paths", "like", "Unix", "." ]
def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/')
[ "def", "FullName", "(", "self", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "_filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L881-L883
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/pysixd/transform.py
python
decompose_matrix
(matrix)
return scale, shear, angles, translate, perspective
Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix Raise ValueError if matrix is of wrong type or degenerative. >>> T0 = translation_matrix([1, 2, 3]) >>> scale, shear, angles, trans, persp = decompose_matrix(T0) >>> T1 = translation_matrix(trans) >>> numpy.allclose(T0, T1) True >>> S = scale_matrix(0.123) >>> scale, shear, angles, trans, persp = decompose_matrix(S) >>> scale[0] 0.123 >>> R0 = euler_matrix(1, 2, 3) >>> scale, shear, angles, trans, persp = decompose_matrix(R0) >>> R1 = euler_matrix(*angles) >>> numpy.allclose(R0, R1) True
Return sequence of transformations from transformation matrix.
[ "Return", "sequence", "of", "transformations", "from", "transformation", "matrix", "." ]
def decompose_matrix(matrix): """Return sequence of transformations from transformation matrix. matrix : array_like Non-degenerative homogeneous transformation matrix Return tuple of: scale : vector of 3 scaling factors shear : list of shear factors for x-y, x-z, y-z axes angles : list of Euler angles about static x, y, z axes translate : translation vector along x, y, z axes perspective : perspective partition of matrix Raise ValueError if matrix is of wrong type or degenerative. >>> T0 = translation_matrix([1, 2, 3]) >>> scale, shear, angles, trans, persp = decompose_matrix(T0) >>> T1 = translation_matrix(trans) >>> numpy.allclose(T0, T1) True >>> S = scale_matrix(0.123) >>> scale, shear, angles, trans, persp = decompose_matrix(S) >>> scale[0] 0.123 >>> R0 = euler_matrix(1, 2, 3) >>> scale, shear, angles, trans, persp = decompose_matrix(R0) >>> R1 = euler_matrix(*angles) >>> numpy.allclose(R0, R1) True """ M = numpy.array(matrix, dtype=numpy.float64, copy=True).T if abs(M[3, 3]) < _EPS: raise ValueError("M[3, 3] is zero") M /= M[3, 3] P = M.copy() P[:, 3] = 0.0, 0.0, 0.0, 1.0 if not numpy.linalg.det(P): raise ValueError("matrix is singular") scale = numpy.zeros((3, )) shear = [0.0, 0.0, 0.0] angles = [0.0, 0.0, 0.0] if any(abs(M[:3, 3]) > _EPS): perspective = numpy.dot(M[:, 3], numpy.linalg.inv(P.T)) M[:, 3] = 0.0, 0.0, 0.0, 1.0 else: perspective = numpy.array([0.0, 0.0, 0.0, 1.0]) translate = M[3, :3].copy() M[3, :3] = 0.0 row = M[:3, :3].copy() scale[0] = vector_norm(row[0]) row[0] /= scale[0] shear[0] = numpy.dot(row[0], row[1]) row[1] -= row[0] * shear[0] scale[1] = vector_norm(row[1]) row[1] /= scale[1] shear[0] /= scale[1] shear[1] = numpy.dot(row[0], row[2]) row[2] -= row[0] * shear[1] shear[2] = numpy.dot(row[1], row[2]) row[2] -= row[1] * shear[2] scale[2] = vector_norm(row[2]) row[2] /= scale[2] shear[1:] /= scale[2] if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0: numpy.negative(scale, scale) numpy.negative(row, row) angles[1] = math.asin(-row[0, 2]) if math.cos(angles[1]): angles[0] = math.atan2(row[1, 2], row[2, 2]) angles[2] = math.atan2(row[0, 1], row[0, 0]) else: #angles[0] = math.atan2(row[1, 0], row[1, 1]) angles[0] = math.atan2(-row[2, 1], row[1, 1]) angles[2] = 0.0 return scale, shear, angles, translate, perspective
[ "def", "decompose_matrix", "(", "matrix", ")", ":", "M", "=", "numpy", ".", "array", "(", "matrix", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", ".", "T", "if", "abs", "(", "M", "[", "3", ",", "3", "]", ")", "<", "_EPS", ":", "raise", "ValueError", "(", "\"M[3, 3] is zero\"", ")", "M", "/=", "M", "[", "3", ",", "3", "]", "P", "=", "M", ".", "copy", "(", ")", "P", "[", ":", ",", "3", "]", "=", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "if", "not", "numpy", ".", "linalg", ".", "det", "(", "P", ")", ":", "raise", "ValueError", "(", "\"matrix is singular\"", ")", "scale", "=", "numpy", ".", "zeros", "(", "(", "3", ",", ")", ")", "shear", "=", "[", "0.0", ",", "0.0", ",", "0.0", "]", "angles", "=", "[", "0.0", ",", "0.0", ",", "0.0", "]", "if", "any", "(", "abs", "(", "M", "[", ":", "3", ",", "3", "]", ")", ">", "_EPS", ")", ":", "perspective", "=", "numpy", ".", "dot", "(", "M", "[", ":", ",", "3", "]", ",", "numpy", ".", "linalg", ".", "inv", "(", "P", ".", "T", ")", ")", "M", "[", ":", ",", "3", "]", "=", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "else", ":", "perspective", "=", "numpy", ".", "array", "(", "[", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "]", ")", "translate", "=", "M", "[", "3", ",", ":", "3", "]", ".", "copy", "(", ")", "M", "[", "3", ",", ":", "3", "]", "=", "0.0", "row", "=", "M", "[", ":", "3", ",", ":", "3", "]", ".", "copy", "(", ")", "scale", "[", "0", "]", "=", "vector_norm", "(", "row", "[", "0", "]", ")", "row", "[", "0", "]", "/=", "scale", "[", "0", "]", "shear", "[", "0", "]", "=", "numpy", ".", "dot", "(", "row", "[", "0", "]", ",", "row", "[", "1", "]", ")", "row", "[", "1", "]", "-=", "row", "[", "0", "]", "*", "shear", "[", "0", "]", "scale", "[", "1", "]", "=", "vector_norm", "(", "row", "[", "1", "]", ")", "row", "[", "1", "]", "/=", "scale", "[", "1", "]", "shear", "[", "0", "]", "/=", "scale", "[", "1", "]", "shear", "[", "1", "]", "=", "numpy", ".", "dot", "(", "row", "[", "0", "]", ",", "row", "[", "2", "]", ")", "row", "[", "2", "]", "-=", "row", "[", "0", "]", "*", "shear", "[", "1", "]", "shear", "[", "2", "]", "=", "numpy", ".", "dot", "(", "row", "[", "1", "]", ",", "row", "[", "2", "]", ")", "row", "[", "2", "]", "-=", "row", "[", "1", "]", "*", "shear", "[", "2", "]", "scale", "[", "2", "]", "=", "vector_norm", "(", "row", "[", "2", "]", ")", "row", "[", "2", "]", "/=", "scale", "[", "2", "]", "shear", "[", "1", ":", "]", "/=", "scale", "[", "2", "]", "if", "numpy", ".", "dot", "(", "row", "[", "0", "]", ",", "numpy", ".", "cross", "(", "row", "[", "1", "]", ",", "row", "[", "2", "]", ")", ")", "<", "0", ":", "numpy", ".", "negative", "(", "scale", ",", "scale", ")", "numpy", ".", "negative", "(", "row", ",", "row", ")", "angles", "[", "1", "]", "=", "math", ".", "asin", "(", "-", "row", "[", "0", ",", "2", "]", ")", "if", "math", ".", "cos", "(", "angles", "[", "1", "]", ")", ":", "angles", "[", "0", "]", "=", "math", ".", "atan2", "(", "row", "[", "1", ",", "2", "]", ",", "row", "[", "2", ",", "2", "]", ")", "angles", "[", "2", "]", "=", "math", ".", "atan2", "(", "row", "[", "0", ",", "1", "]", ",", "row", "[", "0", ",", "0", "]", ")", "else", ":", "#angles[0] = math.atan2(row[1, 0], row[1, 1])", "angles", "[", "0", "]", "=", "math", ".", "atan2", "(", "-", "row", "[", "2", ",", "1", "]", ",", "row", "[", "1", ",", "1", "]", ")", "angles", "[", "2", "]", "=", "0.0", "return", "scale", ",", "shear", ",", "angles", ",", "translate", ",", "perspective" ]
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/pysixd/transform.py#L724-L806
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl_check_compatibility.py
python
check_param_or_command_type
(ctxt: IDLCompatibilityContext, field_pair: FieldCompatibilityPair, is_command_parameter: bool)
Check compatibility between old and new command parameter type or command type.
Check compatibility between old and new command parameter type or command type.
[ "Check", "compatibility", "between", "old", "and", "new", "command", "parameter", "type", "or", "command", "type", "." ]
def check_param_or_command_type(ctxt: IDLCompatibilityContext, field_pair: FieldCompatibilityPair, is_command_parameter: bool): """Check compatibility between old and new command parameter type or command type.""" # pylint: disable=too-many-branches old_field = field_pair.old new_field = field_pair.new array_check = check_array_type( ctxt, "command_parameter" if is_command_parameter else "command_namespace", old_field.field_type, new_field.field_type, field_pair.cmd_name, field_pair.field_name if is_command_parameter else "type", old_field.idl_file_path, new_field.idl_file_path, old_field.unstable) if array_check == ArrayTypeCheckResult.INVALID: return if array_check == ArrayTypeCheckResult.TRUE: old_field.field_type = old_field.field_type.element_type new_field.field_type = new_field.field_type.element_type old_type = old_field.field_type new_type = new_field.field_type if old_type is None: ctxt.add_command_or_param_type_invalid_error(field_pair.cmd_name, old_field.idl_file_path, field_pair.field_name, is_command_parameter) ctxt.errors.dump_errors() sys.exit(1) if new_type is None: ctxt.add_command_or_param_type_invalid_error(field_pair.cmd_name, new_field.idl_file_path, field_pair.field_name, is_command_parameter) ctxt.errors.dump_errors() sys.exit(1) if isinstance(old_type, syntax.Type): check_param_or_command_type_recursive(ctxt, field_pair, is_command_parameter) # Only add type errors if the old field is stable. elif isinstance(old_type, syntax.Enum) and not old_field.unstable: if isinstance(new_type, syntax.Enum): check_superset(ctxt, field_pair.cmd_name, new_type.name, new_type.values, old_type.values, new_field.idl_file_path, field_pair.field_name, is_command_parameter) else: ctxt.add_new_command_or_param_type_not_enum_error( field_pair.cmd_name, new_type.name, old_type.name, new_field.idl_file_path, field_pair.field_name, is_command_parameter) elif isinstance(old_type, syntax.Struct): if isinstance(new_type, syntax.Struct): check_command_params_or_type_struct_fields( ctxt, old_type, new_type, field_pair.cmd_name, old_field.idl_file, new_field.idl_file, old_field.idl_file_path, new_field.idl_file_path, is_command_parameter) else: if not old_field.unstable: ctxt.add_new_command_or_param_type_not_struct_error( field_pair.cmd_name, new_type.name, old_type.name, new_field.idl_file_path, field_pair.field_name, is_command_parameter)
[ "def", "check_param_or_command_type", "(", "ctxt", ":", "IDLCompatibilityContext", ",", "field_pair", ":", "FieldCompatibilityPair", ",", "is_command_parameter", ":", "bool", ")", ":", "# pylint: disable=too-many-branches", "old_field", "=", "field_pair", ".", "old", "new_field", "=", "field_pair", ".", "new", "array_check", "=", "check_array_type", "(", "ctxt", ",", "\"command_parameter\"", "if", "is_command_parameter", "else", "\"command_namespace\"", ",", "old_field", ".", "field_type", ",", "new_field", ".", "field_type", ",", "field_pair", ".", "cmd_name", ",", "field_pair", ".", "field_name", "if", "is_command_parameter", "else", "\"type\"", ",", "old_field", ".", "idl_file_path", ",", "new_field", ".", "idl_file_path", ",", "old_field", ".", "unstable", ")", "if", "array_check", "==", "ArrayTypeCheckResult", ".", "INVALID", ":", "return", "if", "array_check", "==", "ArrayTypeCheckResult", ".", "TRUE", ":", "old_field", ".", "field_type", "=", "old_field", ".", "field_type", ".", "element_type", "new_field", ".", "field_type", "=", "new_field", ".", "field_type", ".", "element_type", "old_type", "=", "old_field", ".", "field_type", "new_type", "=", "new_field", ".", "field_type", "if", "old_type", "is", "None", ":", "ctxt", ".", "add_command_or_param_type_invalid_error", "(", "field_pair", ".", "cmd_name", ",", "old_field", ".", "idl_file_path", ",", "field_pair", ".", "field_name", ",", "is_command_parameter", ")", "ctxt", ".", "errors", ".", "dump_errors", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "new_type", "is", "None", ":", "ctxt", ".", "add_command_or_param_type_invalid_error", "(", "field_pair", ".", "cmd_name", ",", "new_field", ".", "idl_file_path", ",", "field_pair", ".", "field_name", ",", "is_command_parameter", ")", "ctxt", ".", "errors", ".", "dump_errors", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "isinstance", "(", "old_type", ",", "syntax", ".", "Type", ")", ":", "check_param_or_command_type_recursive", "(", "ctxt", ",", "field_pair", ",", "is_command_parameter", ")", "# Only add type errors if the old field is stable.", "elif", "isinstance", "(", "old_type", ",", "syntax", ".", "Enum", ")", "and", "not", "old_field", ".", "unstable", ":", "if", "isinstance", "(", "new_type", ",", "syntax", ".", "Enum", ")", ":", "check_superset", "(", "ctxt", ",", "field_pair", ".", "cmd_name", ",", "new_type", ".", "name", ",", "new_type", ".", "values", ",", "old_type", ".", "values", ",", "new_field", ".", "idl_file_path", ",", "field_pair", ".", "field_name", ",", "is_command_parameter", ")", "else", ":", "ctxt", ".", "add_new_command_or_param_type_not_enum_error", "(", "field_pair", ".", "cmd_name", ",", "new_type", ".", "name", ",", "old_type", ".", "name", ",", "new_field", ".", "idl_file_path", ",", "field_pair", ".", "field_name", ",", "is_command_parameter", ")", "elif", "isinstance", "(", "old_type", ",", "syntax", ".", "Struct", ")", ":", "if", "isinstance", "(", "new_type", ",", "syntax", ".", "Struct", ")", ":", "check_command_params_or_type_struct_fields", "(", "ctxt", ",", "old_type", ",", "new_type", ",", "field_pair", ".", "cmd_name", ",", "old_field", ".", "idl_file", ",", "new_field", ".", "idl_file", ",", "old_field", ".", "idl_file_path", ",", "new_field", ".", "idl_file_path", ",", "is_command_parameter", ")", "else", ":", "if", "not", "old_field", ".", "unstable", ":", "ctxt", ".", "add_new_command_or_param_type_not_struct_error", "(", "field_pair", ".", "cmd_name", ",", "new_type", ".", "name", ",", "old_type", ".", "name", ",", "new_field", ".", "idl_file_path", ",", "field_pair", ".", "field_name", ",", "is_command_parameter", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_check_compatibility.py#L718-L773