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
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/ops/dct/dct.py
python
dct
(x, expk, algorithm)
return output.view(x.size())
compute discrete cosine transformation, DCT II, using N-FFT or 2N-FFT yk = \sum_{n=0}^{N-1} x_n cos(pi/N*n*(k+1/2)) @param x sequence @param expk coefficients for post-processing @param algorithm algorithm type N | 2N
compute discrete cosine transformation, DCT II, using N-FFT or 2N-FFT yk = \sum_{n=0}^{N-1} x_n cos(pi/N*n*(k+1/2))
[ "compute", "discrete", "cosine", "transformation", "DCT", "II", "using", "N", "-", "FFT", "or", "2N", "-", "FFT", "yk", "=", "\\", "sum_", "{", "n", "=", "0", "}", "^", "{", "N", "-", "1", "}", "x_n", "cos", "(", "pi", "/", "N", "*", "n", "*", "(", "k", "+", "1", "/", "2", "))" ]
def dct(x, expk, algorithm): """compute discrete cosine transformation, DCT II, using N-FFT or 2N-FFT yk = \sum_{n=0}^{N-1} x_n cos(pi/N*n*(k+1/2)) @param x sequence @param expk coefficients for post-processing @param algorithm algorithm type N | 2N """ if x.is_cuda: if algorithm == 'N': output = dct_cuda.dct(x.view([-1, x.size(-1)]), expk) elif algorithm == '2N': output = dct_cuda.dct_2N(x.view([-1, x.size(-1)]), expk) else: if algorithm == 'N': output = dct_cpp.dct(x.view([-1, x.size(-1)]), expk, torch.get_num_threads()) elif algorithm == '2N': output = dct_cpp.dct_2N(x.view([-1, x.size(-1)]), expk, torch.get_num_threads()) return output.view(x.size())
[ "def", "dct", "(", "x", ",", "expk", ",", "algorithm", ")", ":", "if", "x", ".", "is_cuda", ":", "if", "algorithm", "==", "'N'", ":", "output", "=", "dct_cuda", ".", "dct", "(", "x", ".", "view", "(", "[", "-", "1", ",", "x", ".", "size", "(", "-", "1", ")", "]", ")", ",", "expk", ")", "elif", "algorithm", "==", "'2N'", ":", "output", "=", "dct_cuda", ".", "dct_2N", "(", "x", ".", "view", "(", "[", "-", "1", ",", "x", ".", "size", "(", "-", "1", ")", "]", ")", ",", "expk", ")", "else", ":", "if", "algorithm", "==", "'N'", ":", "output", "=", "dct_cpp", ".", "dct", "(", "x", ".", "view", "(", "[", "-", "1", ",", "x", ".", "size", "(", "-", "1", ")", "]", ")", ",", "expk", ",", "torch", ".", "get_num_threads", "(", ")", ")", "elif", "algorithm", "==", "'2N'", ":", "output", "=", "dct_cpp", ".", "dct_2N", "(", "x", ".", "view", "(", "[", "-", "1", ",", "x", ".", "size", "(", "-", "1", ")", "]", ")", ",", "expk", ",", "torch", ".", "get_num_threads", "(", ")", ")", "return", "output", ".", "view", "(", "x", ".", "size", "(", ")", ")" ]
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/ops/dct/dct.py#L21-L39
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame._convert
(self, datetime=False, numeric=False, timedelta=False, coerce=False, copy=True)
return self._constructor( self._data.convert(datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=copy)).__finalize__(self)
Attempt to infer better dtype for object columns Parameters ---------- datetime : boolean, default False If True, convert to date where possible. numeric : boolean, default False If True, attempt to convert to numbers (including strings), with unconvertible values becoming NaN. timedelta : boolean, default False If True, convert to timedelta where possible. coerce : boolean, default False If True, force conversion with unconvertible values converted to nulls (NaN or NaT) copy : boolean, default True If True, return a copy even if no copy is necessary (e.g. no conversion was done). Note: This is meant for internal use, and should not be confused with inplace. Returns ------- converted : same as input object
Attempt to infer better dtype for object columns
[ "Attempt", "to", "infer", "better", "dtype", "for", "object", "columns" ]
def _convert(self, datetime=False, numeric=False, timedelta=False, coerce=False, copy=True): """ Attempt to infer better dtype for object columns Parameters ---------- datetime : boolean, default False If True, convert to date where possible. numeric : boolean, default False If True, attempt to convert to numbers (including strings), with unconvertible values becoming NaN. timedelta : boolean, default False If True, convert to timedelta where possible. coerce : boolean, default False If True, force conversion with unconvertible values converted to nulls (NaN or NaT) copy : boolean, default True If True, return a copy even if no copy is necessary (e.g. no conversion was done). Note: This is meant for internal use, and should not be confused with inplace. Returns ------- converted : same as input object """ return self._constructor( self._data.convert(datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=copy)).__finalize__(self)
[ "def", "_convert", "(", "self", ",", "datetime", "=", "False", ",", "numeric", "=", "False", ",", "timedelta", "=", "False", ",", "coerce", "=", "False", ",", "copy", "=", "True", ")", ":", "return", "self", ".", "_constructor", "(", "self", ".", "_data", ".", "convert", "(", "datetime", "=", "datetime", ",", "numeric", "=", "numeric", ",", "timedelta", "=", "timedelta", ",", "coerce", "=", "coerce", ",", "copy", "=", "copy", ")", ")", ".", "__finalize__", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L5821-L5850
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py
python
IdleConf.GetExtensions
(self, active_only=True, editor_only=False, shell_only=False)
Return extensions in default and user config-extensions files. If active_only True, only return active (enabled) extensions and optionally only editor or shell extensions. If active_only False, return all extensions.
Return extensions in default and user config-extensions files.
[ "Return", "extensions", "in", "default", "and", "user", "config", "-", "extensions", "files", "." ]
def GetExtensions(self, active_only=True, editor_only=False, shell_only=False): """Return extensions in default and user config-extensions files. If active_only True, only return active (enabled) extensions and optionally only editor or shell extensions. If active_only False, return all extensions. """ extns = self.RemoveKeyBindNames( self.GetSectionList('default', 'extensions')) userExtns = self.RemoveKeyBindNames( self.GetSectionList('user', 'extensions')) for extn in userExtns: if extn not in extns: #user has added own extension extns.append(extn) for extn in ('AutoComplete','CodeContext', 'FormatParagraph','ParenMatch'): extns.remove(extn) # specific exclusions because we are storing config for mainlined old # extensions in config-extensions.def for backward compatibility if active_only: activeExtns = [] for extn in extns: if self.GetOption('extensions', extn, 'enable', default=True, type='bool'): #the extension is enabled if editor_only or shell_only: # TODO both True contradict if editor_only: option = "enable_editor" else: option = "enable_shell" if self.GetOption('extensions', extn,option, default=True, type='bool', warn_on_default=False): activeExtns.append(extn) else: activeExtns.append(extn) return activeExtns else: return extns
[ "def", "GetExtensions", "(", "self", ",", "active_only", "=", "True", ",", "editor_only", "=", "False", ",", "shell_only", "=", "False", ")", ":", "extns", "=", "self", ".", "RemoveKeyBindNames", "(", "self", ".", "GetSectionList", "(", "'default'", ",", "'extensions'", ")", ")", "userExtns", "=", "self", ".", "RemoveKeyBindNames", "(", "self", ".", "GetSectionList", "(", "'user'", ",", "'extensions'", ")", ")", "for", "extn", "in", "userExtns", ":", "if", "extn", "not", "in", "extns", ":", "#user has added own extension", "extns", ".", "append", "(", "extn", ")", "for", "extn", "in", "(", "'AutoComplete'", ",", "'CodeContext'", ",", "'FormatParagraph'", ",", "'ParenMatch'", ")", ":", "extns", ".", "remove", "(", "extn", ")", "# specific exclusions because we are storing config for mainlined old", "# extensions in config-extensions.def for backward compatibility", "if", "active_only", ":", "activeExtns", "=", "[", "]", "for", "extn", "in", "extns", ":", "if", "self", ".", "GetOption", "(", "'extensions'", ",", "extn", ",", "'enable'", ",", "default", "=", "True", ",", "type", "=", "'bool'", ")", ":", "#the extension is enabled", "if", "editor_only", "or", "shell_only", ":", "# TODO both True contradict", "if", "editor_only", ":", "option", "=", "\"enable_editor\"", "else", ":", "option", "=", "\"enable_shell\"", "if", "self", ".", "GetOption", "(", "'extensions'", ",", "extn", ",", "option", ",", "default", "=", "True", ",", "type", "=", "'bool'", ",", "warn_on_default", "=", "False", ")", ":", "activeExtns", ".", "append", "(", "extn", ")", "else", ":", "activeExtns", ".", "append", "(", "extn", ")", "return", "activeExtns", "else", ":", "return", "extns" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py#L412-L451
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/cluster/hierarchy.py
python
from_mlab_linkage
(Z)
return np.hstack([Zpart, CS.reshape(Zs[0], 1)])
Convert a linkage matrix generated by MATLAB(TM) to a new linkage matrix compatible with this module. The conversion does two things: * the indices are converted from ``1..N`` to ``0..(N-1)`` form, and * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the number of original observations (leaves) in the non-singleton cluster ``i``. This function is useful when loading in linkages from legacy data files generated by MATLAB. Parameters ---------- Z : ndarray A linkage matrix generated by MATLAB(TM). Returns ------- ZS : ndarray A linkage matrix compatible with ``scipy.cluster.hierarchy``. See Also -------- linkage: for a description of what a linkage matrix is. to_mlab_linkage: transform from Scipy to MATLAB format. Examples -------- >>> import numpy as np >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage Given a linkage matrix in MATLAB format ``mZ``, we can use `scipy.cluster.hierarchy.from_mlab_linkage` to import it into Scipy format: >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1], ... [10, 11, 1], [3, 13, 1.29099445], ... [6, 14, 1.29099445], ... [9, 15, 1.29099445], ... [12, 16, 1.29099445], ... [17, 18, 5.77350269], ... [19, 20, 5.77350269], ... [21, 22, 8.16496581]]) >>> Z = from_mlab_linkage(mZ) >>> Z array([[ 0. , 1. , 1. , 2. ], [ 3. , 4. , 1. , 2. ], [ 6. , 7. , 1. , 2. ], [ 9. , 10. , 1. , 2. ], [ 2. , 12. , 1.29099445, 3. ], [ 5. , 13. , 1.29099445, 3. ], [ 8. , 14. , 1.29099445, 3. ], [ 11. , 15. , 1.29099445, 3. ], [ 16. , 17. , 5.77350269, 6. ], [ 18. , 19. , 5.77350269, 6. ], [ 20. , 21. , 8.16496581, 12. ]]) As expected, the linkage matrix ``Z`` returned includes an additional column counting the number of original samples in each cluster. Also, all cluster indexes are reduced by 1 (MATLAB format uses 1-indexing, whereas Scipy uses 0-indexing).
Convert a linkage matrix generated by MATLAB(TM) to a new linkage matrix compatible with this module.
[ "Convert", "a", "linkage", "matrix", "generated", "by", "MATLAB", "(", "TM", ")", "to", "a", "new", "linkage", "matrix", "compatible", "with", "this", "module", "." ]
def from_mlab_linkage(Z): """ Convert a linkage matrix generated by MATLAB(TM) to a new linkage matrix compatible with this module. The conversion does two things: * the indices are converted from ``1..N`` to ``0..(N-1)`` form, and * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the number of original observations (leaves) in the non-singleton cluster ``i``. This function is useful when loading in linkages from legacy data files generated by MATLAB. Parameters ---------- Z : ndarray A linkage matrix generated by MATLAB(TM). Returns ------- ZS : ndarray A linkage matrix compatible with ``scipy.cluster.hierarchy``. See Also -------- linkage: for a description of what a linkage matrix is. to_mlab_linkage: transform from Scipy to MATLAB format. Examples -------- >>> import numpy as np >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage Given a linkage matrix in MATLAB format ``mZ``, we can use `scipy.cluster.hierarchy.from_mlab_linkage` to import it into Scipy format: >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1], ... [10, 11, 1], [3, 13, 1.29099445], ... [6, 14, 1.29099445], ... [9, 15, 1.29099445], ... [12, 16, 1.29099445], ... [17, 18, 5.77350269], ... [19, 20, 5.77350269], ... [21, 22, 8.16496581]]) >>> Z = from_mlab_linkage(mZ) >>> Z array([[ 0. , 1. , 1. , 2. ], [ 3. , 4. , 1. , 2. ], [ 6. , 7. , 1. , 2. ], [ 9. , 10. , 1. , 2. ], [ 2. , 12. , 1.29099445, 3. ], [ 5. , 13. , 1.29099445, 3. ], [ 8. , 14. , 1.29099445, 3. ], [ 11. , 15. , 1.29099445, 3. ], [ 16. , 17. , 5.77350269, 6. ], [ 18. , 19. , 5.77350269, 6. ], [ 20. , 21. , 8.16496581, 12. ]]) As expected, the linkage matrix ``Z`` returned includes an additional column counting the number of original samples in each cluster. Also, all cluster indexes are reduced by 1 (MATLAB format uses 1-indexing, whereas Scipy uses 0-indexing). """ Z = np.asarray(Z, dtype=np.double, order='c') Zs = Z.shape # If it's empty, return it. if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): return Z.copy() if len(Zs) != 2: raise ValueError("The linkage array must be rectangular.") # If it contains no rows, return it. if Zs[0] == 0: return Z.copy() Zpart = Z.copy() if Zpart[:, 0:2].min() != 1.0 and Zpart[:, 0:2].max() != 2 * Zs[0]: raise ValueError('The format of the indices is not 1..N') Zpart[:, 0:2] -= 1.0 CS = np.zeros((Zs[0],), dtype=np.double) _hierarchy.calculate_cluster_sizes(Zpart, CS, int(Zs[0]) + 1) return np.hstack([Zpart, CS.reshape(Zs[0], 1)])
[ "def", "from_mlab_linkage", "(", "Z", ")", ":", "Z", "=", "np", ".", "asarray", "(", "Z", ",", "dtype", "=", "np", ".", "double", ",", "order", "=", "'c'", ")", "Zs", "=", "Z", ".", "shape", "# If it's empty, return it.", "if", "len", "(", "Zs", ")", "==", "0", "or", "(", "len", "(", "Zs", ")", "==", "1", "and", "Zs", "[", "0", "]", "==", "0", ")", ":", "return", "Z", ".", "copy", "(", ")", "if", "len", "(", "Zs", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"The linkage array must be rectangular.\"", ")", "# If it contains no rows, return it.", "if", "Zs", "[", "0", "]", "==", "0", ":", "return", "Z", ".", "copy", "(", ")", "Zpart", "=", "Z", ".", "copy", "(", ")", "if", "Zpart", "[", ":", ",", "0", ":", "2", "]", ".", "min", "(", ")", "!=", "1.0", "and", "Zpart", "[", ":", ",", "0", ":", "2", "]", ".", "max", "(", ")", "!=", "2", "*", "Zs", "[", "0", "]", ":", "raise", "ValueError", "(", "'The format of the indices is not 1..N'", ")", "Zpart", "[", ":", ",", "0", ":", "2", "]", "-=", "1.0", "CS", "=", "np", ".", "zeros", "(", "(", "Zs", "[", "0", "]", ",", ")", ",", "dtype", "=", "np", ".", "double", ")", "_hierarchy", ".", "calculate_cluster_sizes", "(", "Zpart", ",", "CS", ",", "int", "(", "Zs", "[", "0", "]", ")", "+", "1", ")", "return", "np", ".", "hstack", "(", "[", "Zpart", ",", "CS", ".", "reshape", "(", "Zs", "[", "0", "]", ",", "1", ")", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/cluster/hierarchy.py#L1825-L1916
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> DataViewEvent
__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> DataViewEvent
[ "__init__", "(", "self", "EventType", "commandType", "=", "wxEVT_NULL", "int", "winid", "=", "0", ")", "-", ">", "DataViewEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> DataViewEvent""" _dataview.DataViewEvent_swiginit(self,_dataview.new_DataViewEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_dataview", ".", "DataViewEvent_swiginit", "(", "self", ",", "_dataview", ".", "new_DataViewEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1896-L1898
chuckcho/video-caffe
fc232b3e3a90ea22dd041b9fc5c542f170581f20
scripts/cpp_lint.py
python
_NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/scripts/cpp_lint.py#L1946-L1952
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/implementations/webhdfs.py
python
WebHDFile._initiate_upload
(self)
Create remote file/upload
Create remote file/upload
[ "Create", "remote", "file", "/", "upload" ]
def _initiate_upload(self): """ Create remote file/upload """ if "a" in self.mode: op, method = "APPEND", "POST" else: op, method = "CREATE", "PUT" if self.fs.exists(self.path): # no "truncate" or "create empty" self.fs.rm(self.path) out = self.fs._call(op, method, self.path, redirect=False, **self.kwargs) location = self.fs._apply_proxy(out.headers["Location"]) if "w" in self.mode: # create empty file to append to out2 = self.fs.session.put(location) out2.raise_for_status() self.location = location.replace("CREATE", "APPEND")
[ "def", "_initiate_upload", "(", "self", ")", ":", "if", "\"a\"", "in", "self", ".", "mode", ":", "op", ",", "method", "=", "\"APPEND\"", ",", "\"POST\"", "else", ":", "op", ",", "method", "=", "\"CREATE\"", ",", "\"PUT\"", "if", "self", ".", "fs", ".", "exists", "(", "self", ".", "path", ")", ":", "# no \"truncate\" or \"create empty\"", "self", ".", "fs", ".", "rm", "(", "self", ".", "path", ")", "out", "=", "self", ".", "fs", ".", "_call", "(", "op", ",", "method", ",", "self", ".", "path", ",", "redirect", "=", "False", ",", "*", "*", "self", ".", "kwargs", ")", "location", "=", "self", ".", "fs", ".", "_apply_proxy", "(", "out", ".", "headers", "[", "\"Location\"", "]", ")", "if", "\"w\"", "in", "self", ".", "mode", ":", "# create empty file to append to", "out2", "=", "self", ".", "fs", ".", "session", ".", "put", "(", "location", ")", "out2", ".", "raise_for_status", "(", ")", "self", ".", "location", "=", "location", ".", "replace", "(", "\"CREATE\"", ",", "\"APPEND\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/fsspec/implementations/webhdfs.py#L359-L374
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/bccache.py
python
BytecodeCache.dump_bytecode
(self, bucket)
Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.
Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception.
[ "Subclasses", "have", "to", "override", "this", "method", "to", "write", "the", "bytecode", "from", "a", "bucket", "back", "to", "the", "cache", ".", "If", "it", "unable", "to", "do", "so", "it", "must", "not", "fail", "silently", "but", "raise", "an", "exception", "." ]
def dump_bytecode(self, bucket): """Subclasses have to override this method to write the bytecode from a bucket back to the cache. If it unable to do so it must not fail silently but raise an exception. """ raise NotImplementedError()
[ "def", "dump_bytecode", "(", "self", ",", "bucket", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/bccache.py#L153-L158
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.MoveHome
(*args, **kwargs)
return _richtext.RichTextCtrl_MoveHome(*args, **kwargs)
MoveHome(self, int flags=0) -> bool Move to the start of the buffer
MoveHome(self, int flags=0) -> bool
[ "MoveHome", "(", "self", "int", "flags", "=", "0", ")", "-", ">", "bool" ]
def MoveHome(*args, **kwargs): """ MoveHome(self, int flags=0) -> bool Move to the start of the buffer """ return _richtext.RichTextCtrl_MoveHome(*args, **kwargs)
[ "def", "MoveHome", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_MoveHome", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3788-L3794
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
PageSetupDialog.GetPageSetupData
(*args, **kwargs)
return _windows_.PageSetupDialog_GetPageSetupData(*args, **kwargs)
GetPageSetupData(self) -> PageSetupDialogData
GetPageSetupData(self) -> PageSetupDialogData
[ "GetPageSetupData", "(", "self", ")", "-", ">", "PageSetupDialogData" ]
def GetPageSetupData(*args, **kwargs): """GetPageSetupData(self) -> PageSetupDialogData""" return _windows_.PageSetupDialog_GetPageSetupData(*args, **kwargs)
[ "def", "GetPageSetupData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PageSetupDialog_GetPageSetupData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5020-L5022
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
FindNextMultiLineCommentEnd
(lines, lineix)
return len(lines)
We are inside a comment, find the end marker.
We are inside a comment, find the end marker.
[ "We", "are", "inside", "a", "comment", "find", "the", "end", "marker", "." ]
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "endswith", "(", "'*/'", ")", ":", "return", "lineix", "lineix", "+=", "1", "return", "len", "(", "lines", ")" ]
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L1591-L1597
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/App/FreeCADInit.py
python
FCADLogger.isEnabledFor
(self,level)
return self._isEnabledFor(level)
To check for an integer or text log level. * level: integer or text log level
To check for an integer or text log level.
[ "To", "check", "for", "an", "integer", "or", "text", "log", "level", "." ]
def isEnabledFor(self,level): '''To check for an integer or text log level. * level: integer or text log level ''' if not isinstance(level,int): level = self.__class__._levels[level] return self._isEnabledFor(level)
[ "def", "isEnabledFor", "(", "self", ",", "level", ")", ":", "if", "not", "isinstance", "(", "level", ",", "int", ")", ":", "level", "=", "self", ".", "__class__", ".", "_levels", "[", "level", "]", "return", "self", ".", "_isEnabledFor", "(", "level", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/App/FreeCADInit.py#L388-L395
zhuli19901106/leetcode-zhuli
0f8fc29ccb8c33ea91149ecb2d4e961024c11db7
algorithms/0501-1000/0981_time-based-key-value-store_1_AC.py
python
TimeMap.__init__
(self)
Initialize your data structure here.
Initialize your data structure here.
[ "Initialize", "your", "data", "structure", "here", "." ]
def __init__(self): """ Initialize your data structure here. """ self.ds = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ds", "=", "{", "}" ]
https://github.com/zhuli19901106/leetcode-zhuli/blob/0f8fc29ccb8c33ea91149ecb2d4e961024c11db7/algorithms/0501-1000/0981_time-based-key-value-store_1_AC.py#L7-L11
BTCPrivate/BTCP-Rebase
c8c7fe6ac26b6fba71eae1c89cdc0d924f5c6d82
contrib/devtools/update-translations.py
python
sanitize_string
(s)
return s.replace('\n',' ')
Sanitize string for printing
Sanitize string for printing
[ "Sanitize", "string", "for", "printing" ]
def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ')
[ "def", "sanitize_string", "(", "s", ")", ":", "return", "s", ".", "replace", "(", "'\\n'", ",", "' '", ")" ]
https://github.com/BTCPrivate/BTCP-Rebase/blob/c8c7fe6ac26b6fba71eae1c89cdc0d924f5c6d82/contrib/devtools/update-translations.py#L80-L82
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/pimp.py
python
main
()
Minimal commandline tool to drive pimp.
Minimal commandline tool to drive pimp.
[ "Minimal", "commandline", "tool", "to", "drive", "pimp", "." ]
def main(): """Minimal commandline tool to drive pimp.""" import getopt def _help(): print "Usage: pimp [options] -s [package ...] List installed status" print " pimp [options] -l [package ...] Show package information" print " pimp [options] -i package ... Install packages" print " pimp -d Dump database to stdout" print " pimp -V Print version number" print "Options:" print " -v Verbose" print " -f Force installation" print " -D dir Set destination directory" print " (default: %s)" % DEFAULT_INSTALLDIR print " -u url URL for database" sys.exit(1) class _Watcher: def update(self, msg): sys.stderr.write(msg + '\r') return 1 try: opts, args = getopt.getopt(sys.argv[1:], "slifvdD:Vu:") except getopt.GetoptError: _help() if not opts and not args: _help() mode = None force = 0 verbose = 0 prefargs = {} watcher = None for o, a in opts: if o == '-s': if mode: _help() mode = 'status' if o == '-l': if mode: _help() mode = 'list' if o == '-d': if mode: _help() mode = 'dump' if o == '-V': if mode: _help() mode = 'version' if o == '-i': mode = 'install' if o == '-f': force = 1 if o == '-v': verbose = 1 watcher = _Watcher() if o == '-D': prefargs['installDir'] = a if o == '-u': prefargs['pimpDatabase'] = a if not mode: _help() if mode == 'version': print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__) else: _run(mode, verbose, force, args, prefargs, watcher)
[ "def", "main", "(", ")", ":", "import", "getopt", "def", "_help", "(", ")", ":", "print", "\"Usage: pimp [options] -s [package ...] List installed status\"", "print", "\" pimp [options] -l [package ...] Show package information\"", "print", "\" pimp [options] -i package ... Install packages\"", "print", "\" pimp -d Dump database to stdout\"", "print", "\" pimp -V Print version number\"", "print", "\"Options:\"", "print", "\" -v Verbose\"", "print", "\" -f Force installation\"", "print", "\" -D dir Set destination directory\"", "print", "\" (default: %s)\"", "%", "DEFAULT_INSTALLDIR", "print", "\" -u url URL for database\"", "sys", ".", "exit", "(", "1", ")", "class", "_Watcher", ":", "def", "update", "(", "self", ",", "msg", ")", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "'\\r'", ")", "return", "1", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "\"slifvdD:Vu:\"", ")", "except", "getopt", ".", "GetoptError", ":", "_help", "(", ")", "if", "not", "opts", "and", "not", "args", ":", "_help", "(", ")", "mode", "=", "None", "force", "=", "0", "verbose", "=", "0", "prefargs", "=", "{", "}", "watcher", "=", "None", "for", "o", ",", "a", "in", "opts", ":", "if", "o", "==", "'-s'", ":", "if", "mode", ":", "_help", "(", ")", "mode", "=", "'status'", "if", "o", "==", "'-l'", ":", "if", "mode", ":", "_help", "(", ")", "mode", "=", "'list'", "if", "o", "==", "'-d'", ":", "if", "mode", ":", "_help", "(", ")", "mode", "=", "'dump'", "if", "o", "==", "'-V'", ":", "if", "mode", ":", "_help", "(", ")", "mode", "=", "'version'", "if", "o", "==", "'-i'", ":", "mode", "=", "'install'", "if", "o", "==", "'-f'", ":", "force", "=", "1", "if", "o", "==", "'-v'", ":", "verbose", "=", "1", "watcher", "=", "_Watcher", "(", ")", "if", "o", "==", "'-D'", ":", "prefargs", "[", "'installDir'", "]", "=", "a", "if", "o", "==", "'-u'", ":", "prefargs", "[", "'pimpDatabase'", "]", "=", "a", "if", "not", "mode", ":", "_help", "(", ")", "if", "mode", "==", "'version'", ":", "print", "'Pimp version %s; module name is %s'", "%", "(", "PIMP_VERSION", ",", "__name__", ")", "else", ":", "_run", "(", "mode", ",", "verbose", ",", "force", ",", "args", ",", "prefargs", ",", "watcher", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/pimp.py#L1095-L1162
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/config/apple/sdk_info.py
python
FillXcodeVersion
(settings, developer_dir)
Fills the Xcode version and build number into |settings|.
Fills the Xcode version and build number into |settings|.
[ "Fills", "the", "Xcode", "version", "and", "build", "number", "into", "|settings|", "." ]
def FillXcodeVersion(settings, developer_dir): """Fills the Xcode version and build number into |settings|.""" if developer_dir: xcode_version_plist_path = os.path.join(developer_dir, 'Contents/version.plist') version_plist = LoadPList(xcode_version_plist_path) settings['xcode_version'] = FormatVersion( version_plist['CFBundleShortVersionString']) settings['xcode_version_int'] = int(settings['xcode_version'], 10) settings['xcode_build'] = version_plist['ProductBuildVersion'] return lines = subprocess.check_output(['xcodebuild', '-version']).decode('UTF-8').splitlines() settings['xcode_version'] = FormatVersion(lines[0].split()[-1]) settings['xcode_version_int'] = int(settings['xcode_version'], 10) settings['xcode_build'] = lines[-1].split()[-1]
[ "def", "FillXcodeVersion", "(", "settings", ",", "developer_dir", ")", ":", "if", "developer_dir", ":", "xcode_version_plist_path", "=", "os", ".", "path", ".", "join", "(", "developer_dir", ",", "'Contents/version.plist'", ")", "version_plist", "=", "LoadPList", "(", "xcode_version_plist_path", ")", "settings", "[", "'xcode_version'", "]", "=", "FormatVersion", "(", "version_plist", "[", "'CFBundleShortVersionString'", "]", ")", "settings", "[", "'xcode_version_int'", "]", "=", "int", "(", "settings", "[", "'xcode_version'", "]", ",", "10", ")", "settings", "[", "'xcode_build'", "]", "=", "version_plist", "[", "'ProductBuildVersion'", "]", "return", "lines", "=", "subprocess", ".", "check_output", "(", "[", "'xcodebuild'", ",", "'-version'", "]", ")", ".", "decode", "(", "'UTF-8'", ")", ".", "splitlines", "(", ")", "settings", "[", "'xcode_version'", "]", "=", "FormatVersion", "(", "lines", "[", "0", "]", ".", "split", "(", ")", "[", "-", "1", "]", ")", "settings", "[", "'xcode_version_int'", "]", "=", "int", "(", "settings", "[", "'xcode_version'", "]", ",", "10", ")", "settings", "[", "'xcode_build'", "]", "=", "lines", "[", "-", "1", "]", ".", "split", "(", ")", "[", "-", "1", "]" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/config/apple/sdk_info.py#L68-L84
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBType.GetVectorElementType
(self)
return _lldb.SBType_GetVectorElementType(self)
GetVectorElementType(SBType self) -> SBType
GetVectorElementType(SBType self) -> SBType
[ "GetVectorElementType", "(", "SBType", "self", ")", "-", ">", "SBType" ]
def GetVectorElementType(self): """GetVectorElementType(SBType self) -> SBType""" return _lldb.SBType_GetVectorElementType(self)
[ "def", "GetVectorElementType", "(", "self", ")", ":", "return", "_lldb", ".", "SBType_GetVectorElementType", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12712-L12714
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py
python
read_hdf
( path_or_buf, key=None, mode: str = "r", errors: str = "strict", where=None, start: Optional[int] = None, stop: Optional[int] = None, columns=None, iterator=False, chunksize: Optional[int] = None, **kwargs, )
Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : str, path object, pandas.HDFStore or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.h5``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. Alternatively, pandas accepts an open :class:`pandas.HDFStore` object. By file-like object, we refer to objects with a ``read()`` method, such as a file handler (e.g. via builtin ``open`` function) or ``StringIO``. .. versionadded:: 0.21.0 support for __fspath__ protocol. key : object, optional The group identifier in the store. Can be omitted if the HDF file contains a single pandas object. mode : {'r', 'r+', 'a'}, default 'r' Mode to use when opening the file. Ignored if path_or_buf is a :class:`pandas.HDFStore`. Default is 'r'. where : list, optional A list of Term (or convertible) objects. start : int, optional Row number to start selection. stop : int, optional Row number to stop selection. columns : list, optional A list of columns names to return. iterator : bool, optional Return an iterator object. chunksize : int, optional Number of rows to include in an iteration when using an iterator. errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. **kwargs Additional keyword arguments passed to HDFStore. Returns ------- item : object The selected object. Return type depends on the object stored. See Also -------- DataFrame.to_hdf : Write a HDF file from a DataFrame. HDFStore : Low-level access to HDF files. Examples -------- >>> df = pd.DataFrame([[1, 1.0, 'a']], columns=['x', 'y', 'z']) >>> df.to_hdf('./store.h5', 'data') >>> reread = pd.read_hdf('./store.h5')
Read from the store, close it if we opened it.
[ "Read", "from", "the", "store", "close", "it", "if", "we", "opened", "it", "." ]
def read_hdf( path_or_buf, key=None, mode: str = "r", errors: str = "strict", where=None, start: Optional[int] = None, stop: Optional[int] = None, columns=None, iterator=False, chunksize: Optional[int] = None, **kwargs, ): """ Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : str, path object, pandas.HDFStore or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.h5``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. Alternatively, pandas accepts an open :class:`pandas.HDFStore` object. By file-like object, we refer to objects with a ``read()`` method, such as a file handler (e.g. via builtin ``open`` function) or ``StringIO``. .. versionadded:: 0.21.0 support for __fspath__ protocol. key : object, optional The group identifier in the store. Can be omitted if the HDF file contains a single pandas object. mode : {'r', 'r+', 'a'}, default 'r' Mode to use when opening the file. Ignored if path_or_buf is a :class:`pandas.HDFStore`. Default is 'r'. where : list, optional A list of Term (or convertible) objects. start : int, optional Row number to start selection. stop : int, optional Row number to stop selection. columns : list, optional A list of columns names to return. iterator : bool, optional Return an iterator object. chunksize : int, optional Number of rows to include in an iteration when using an iterator. errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list of options. **kwargs Additional keyword arguments passed to HDFStore. Returns ------- item : object The selected object. Return type depends on the object stored. See Also -------- DataFrame.to_hdf : Write a HDF file from a DataFrame. HDFStore : Low-level access to HDF files. Examples -------- >>> df = pd.DataFrame([[1, 1.0, 'a']], columns=['x', 'y', 'z']) >>> df.to_hdf('./store.h5', 'data') >>> reread = pd.read_hdf('./store.h5') """ if mode not in ["r", "r+", "a"]: raise ValueError( f"mode {mode} is not allowed while performing a read. " f"Allowed modes are r, r+ and a." ) # grab the scope if where is not None: where = _ensure_term(where, scope_level=1) if isinstance(path_or_buf, HDFStore): if not path_or_buf.is_open: raise IOError("The HDFStore must be open for reading.") store = path_or_buf auto_close = False else: path_or_buf = stringify_path(path_or_buf) if not isinstance(path_or_buf, str): raise NotImplementedError( "Support for generic buffers has not been implemented." ) try: exists = os.path.exists(path_or_buf) # if filepath is too long except (TypeError, ValueError): exists = False if not exists: raise FileNotFoundError(f"File {path_or_buf} does not exist") store = HDFStore(path_or_buf, mode=mode, errors=errors, **kwargs) # can't auto open/close if we are using an iterator # so delegate to the iterator auto_close = True try: if key is None: groups = store.groups() if len(groups) == 0: raise ValueError("No dataset in HDF5 file.") candidate_only_group = groups[0] # For the HDF file to have only one dataset, all other groups # should then be metadata groups for that candidate group. (This # assumes that the groups() method enumerates parent groups # before their children.) for group_to_check in groups[1:]: if not _is_metadata_of(group_to_check, candidate_only_group): raise ValueError( "key must be provided when HDF5 file " "contains multiple datasets." ) key = candidate_only_group._v_pathname return store.select( key, where=where, start=start, stop=stop, columns=columns, iterator=iterator, chunksize=chunksize, auto_close=auto_close, ) except (ValueError, TypeError, KeyError): if not isinstance(path_or_buf, HDFStore): # if there is an error, close the store if we opened it. try: store.close() except AttributeError: pass raise
[ "def", "read_hdf", "(", "path_or_buf", ",", "key", "=", "None", ",", "mode", ":", "str", "=", "\"r\"", ",", "errors", ":", "str", "=", "\"strict\"", ",", "where", "=", "None", ",", "start", ":", "Optional", "[", "int", "]", "=", "None", ",", "stop", ":", "Optional", "[", "int", "]", "=", "None", ",", "columns", "=", "None", ",", "iterator", "=", "False", ",", "chunksize", ":", "Optional", "[", "int", "]", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "if", "mode", "not", "in", "[", "\"r\"", ",", "\"r+\"", ",", "\"a\"", "]", ":", "raise", "ValueError", "(", "f\"mode {mode} is not allowed while performing a read. \"", "f\"Allowed modes are r, r+ and a.\"", ")", "# grab the scope", "if", "where", "is", "not", "None", ":", "where", "=", "_ensure_term", "(", "where", ",", "scope_level", "=", "1", ")", "if", "isinstance", "(", "path_or_buf", ",", "HDFStore", ")", ":", "if", "not", "path_or_buf", ".", "is_open", ":", "raise", "IOError", "(", "\"The HDFStore must be open for reading.\"", ")", "store", "=", "path_or_buf", "auto_close", "=", "False", "else", ":", "path_or_buf", "=", "stringify_path", "(", "path_or_buf", ")", "if", "not", "isinstance", "(", "path_or_buf", ",", "str", ")", ":", "raise", "NotImplementedError", "(", "\"Support for generic buffers has not been implemented.\"", ")", "try", ":", "exists", "=", "os", ".", "path", ".", "exists", "(", "path_or_buf", ")", "# if filepath is too long", "except", "(", "TypeError", ",", "ValueError", ")", ":", "exists", "=", "False", "if", "not", "exists", ":", "raise", "FileNotFoundError", "(", "f\"File {path_or_buf} does not exist\"", ")", "store", "=", "HDFStore", "(", "path_or_buf", ",", "mode", "=", "mode", ",", "errors", "=", "errors", ",", "*", "*", "kwargs", ")", "# can't auto open/close if we are using an iterator", "# so delegate to the iterator", "auto_close", "=", "True", "try", ":", "if", "key", "is", "None", ":", "groups", "=", "store", ".", "groups", "(", ")", "if", "len", "(", "groups", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No dataset in HDF5 file.\"", ")", "candidate_only_group", "=", "groups", "[", "0", "]", "# For the HDF file to have only one dataset, all other groups", "# should then be metadata groups for that candidate group. (This", "# assumes that the groups() method enumerates parent groups", "# before their children.)", "for", "group_to_check", "in", "groups", "[", "1", ":", "]", ":", "if", "not", "_is_metadata_of", "(", "group_to_check", ",", "candidate_only_group", ")", ":", "raise", "ValueError", "(", "\"key must be provided when HDF5 file \"", "\"contains multiple datasets.\"", ")", "key", "=", "candidate_only_group", ".", "_v_pathname", "return", "store", ".", "select", "(", "key", ",", "where", "=", "where", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "columns", "=", "columns", ",", "iterator", "=", "iterator", ",", "chunksize", "=", "chunksize", ",", "auto_close", "=", "auto_close", ",", ")", "except", "(", "ValueError", ",", "TypeError", ",", "KeyError", ")", ":", "if", "not", "isinstance", "(", "path_or_buf", ",", "HDFStore", ")", ":", "# if there is an error, close the store if we opened it.", "try", ":", "store", ".", "close", "(", ")", "except", "AttributeError", ":", "pass", "raise" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L287-L438
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
bindings/python/htcondor/compat_enum/__init__.py
python
unique
(enumeration)
return enumeration
Class decorator that ensures only unique members exist in an enumeration.
Class decorator that ensures only unique members exist in an enumeration.
[ "Class", "decorator", "that", "ensures", "only", "unique", "members", "exist", "in", "an", "enumeration", "." ]
def unique(enumeration): """Class decorator that ensures only unique members exist in an enumeration.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.join( ["%s -> %s" % (alias, name) for (alias, name) in duplicates] ) raise ValueError('duplicate names found in %r: %s' % (enumeration, duplicate_names) ) return enumeration
[ "def", "unique", "(", "enumeration", ")", ":", "duplicates", "=", "[", "]", "for", "name", ",", "member", "in", "enumeration", ".", "__members__", ".", "items", "(", ")", ":", "if", "name", "!=", "member", ".", "name", ":", "duplicates", ".", "append", "(", "(", "name", ",", "member", ".", "name", ")", ")", "if", "duplicates", ":", "duplicate_names", "=", "', '", ".", "join", "(", "[", "\"%s -> %s\"", "%", "(", "alias", ",", "name", ")", "for", "(", "alias", ",", "name", ")", "in", "duplicates", "]", ")", "raise", "ValueError", "(", "'duplicate names found in %r: %s'", "%", "(", "enumeration", ",", "duplicate_names", ")", ")", "return", "enumeration" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/compat_enum/__init__.py#L825-L838
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/decoder.py
python
MessageDecoder
(field_number, is_repeated, is_packed, key, new_default)
Returns a decoder for a message field.
Returns a decoder for a message field.
[ "Returns", "a", "decoder", "for", "a", "message", "field", "." ]
def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a message field.""" local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) def DecodeRepeatedField(buffer, pos, end, message, field_dict): value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. if value.add()._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise _DecodeError('Unexpected end-group tag.') # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeRepeatedField else: def DecodeField(buffer, pos, end, message, field_dict): value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. if value._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it encountered # an end-group tag. raise _DecodeError('Unexpected end-group tag.') return new_pos return DecodeField
[ "def", "MessageDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "local_DecodeVarint", "=", "_DecodeVarint", "assert", "not", "is_packed", "if", "is_repeated", ":", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "tag_len", "=", "len", "(", "tag_bytes", ")", "def", "DecodeRepeatedField", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "value", "=", "field_dict", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "key", ",", "new_default", "(", "message", ")", ")", "while", "1", ":", "value", "=", "field_dict", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "key", ",", "new_default", "(", "message", ")", ")", "# Read length.", "(", "size", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "new_pos", "=", "pos", "+", "size", "if", "new_pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "# Read sub-message.", "if", "value", ".", "add", "(", ")", ".", "_InternalParse", "(", "buffer", ",", "pos", ",", "new_pos", ")", "!=", "new_pos", ":", "# The only reason _InternalParse would return early is if it", "# encountered an end-group tag.", "raise", "_DecodeError", "(", "'Unexpected end-group tag.'", ")", "# Predict that the next tag is another copy of the same repeated field.", "pos", "=", "new_pos", "+", "tag_len", "if", "buffer", "[", "new_pos", ":", "pos", "]", "!=", "tag_bytes", "or", "new_pos", "==", "end", ":", "# Prediction failed. Return.", "return", "new_pos", "return", "DecodeRepeatedField", "else", ":", "def", "DecodeField", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "value", "=", "field_dict", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "key", ",", "new_default", "(", "message", ")", ")", "# Read length.", "(", "size", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "new_pos", "=", "pos", "+", "size", "if", "new_pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "# Read sub-message.", "if", "value", ".", "_InternalParse", "(", "buffer", ",", "pos", ",", "new_pos", ")", "!=", "new_pos", ":", "# The only reason _InternalParse would return early is if it encountered", "# an end-group tag.", "raise", "_DecodeError", "(", "'Unexpected end-group tag.'", ")", "return", "new_pos", "return", "DecodeField" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/decoder.py#L499-L549
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Loadable/Annotations/SubjectHierarchyPlugins/AnnotationsSubjectHierarchyPlugin.py
python
AnnotationsSubjectHierarchyPlugin.viewContextMenuActions
(self)
return []
Important note: In order to use view menus in scripted plugins, it needs to be registered differently, so that the Python API can be fully built by the time this function is called. The following changes are necessary: 1. Remove or comment out the following line from constructor AbstractScriptedSubjectHierarchyPlugin.__init__(self, scriptedPlugin) 2. In addition to the initialization where the scripted plugin is instantialized and the source set, the plugin also needs to be registered manually: pluginHandler = slicer.qSlicerSubjectHierarchyPluginHandler.instance() pluginHandler.registerPlugin(scriptedPlugin)
Important note: In order to use view menus in scripted plugins, it needs to be registered differently, so that the Python API can be fully built by the time this function is called.
[ "Important", "note", ":", "In", "order", "to", "use", "view", "menus", "in", "scripted", "plugins", "it", "needs", "to", "be", "registered", "differently", "so", "that", "the", "Python", "API", "can", "be", "fully", "built", "by", "the", "time", "this", "function", "is", "called", "." ]
def viewContextMenuActions(self): """ Important note: In order to use view menus in scripted plugins, it needs to be registered differently, so that the Python API can be fully built by the time this function is called. The following changes are necessary: 1. Remove or comment out the following line from constructor AbstractScriptedSubjectHierarchyPlugin.__init__(self, scriptedPlugin) 2. In addition to the initialization where the scripted plugin is instantialized and the source set, the plugin also needs to be registered manually: pluginHandler = slicer.qSlicerSubjectHierarchyPluginHandler.instance() pluginHandler.registerPlugin(scriptedPlugin) """ return []
[ "def", "viewContextMenuActions", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Loadable/Annotations/SubjectHierarchyPlugins/AnnotationsSubjectHierarchyPlugin.py#L95-L108
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/image.py
python
Image.height
(self)
return self._height
Returns the height of the image stored in the Image object. Returns ------- out : int The height of the image stored in the Image object. See Also -------- width, channels, pixel_data Examples -------- >>> img = graphlab.Image('https://static.turi.com/datasets/images/sample.jpg') >>> img.height
Returns the height of the image stored in the Image object.
[ "Returns", "the", "height", "of", "the", "image", "stored", "in", "the", "Image", "object", "." ]
def height(self): """ Returns the height of the image stored in the Image object. Returns ------- out : int The height of the image stored in the Image object. See Also -------- width, channels, pixel_data Examples -------- >>> img = graphlab.Image('https://static.turi.com/datasets/images/sample.jpg') >>> img.height """ return self._height
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "_height" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/image.py#L80-L100
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_busstop.py
python
BusStopDomain.getName
(self, stopID)
return self._getUniversal(tc.VAR_NAME, stopID)
getName(string) -> string Returns the name of this stop
getName(string) -> string
[ "getName", "(", "string", ")", "-", ">", "string" ]
def getName(self, stopID): """getName(string) -> string Returns the name of this stop """ return self._getUniversal(tc.VAR_NAME, stopID)
[ "def", "getName", "(", "self", ",", "stopID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_NAME", ",", "stopID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_busstop.py#L50-L55
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/availability_finder.py
python
AvailabilityFinder._GetApiSchema
(self, api_name, file_system, version)
return matching_schemas or None
Searches |file_system| for |api_name|'s API schema data, and processes and returns it if found.
Searches |file_system| for |api_name|'s API schema data, and processes and returns it if found.
[ "Searches", "|file_system|", "for", "|api_name|", "s", "API", "schema", "data", "and", "processes", "and", "returns", "it", "if", "found", "." ]
def _GetApiSchema(self, api_name, file_system, version): '''Searches |file_system| for |api_name|'s API schema data, and processes and returns it if found. ''' api_filename = self._GetApiSchemaFilename(api_name, file_system, version) if api_filename is None: # No file for the API could be found in the given |file_system|. return None schema_fs = self._compiled_fs_factory.ForApiSchema(file_system) api_schemas = schema_fs.GetFromFile(api_filename).Get() matching_schemas = [api for api in api_schemas if api['namespace'] == api_name] # There should only be a single matching schema per file, or zero in the # case of no API data being found in _EXTENSION_API. assert len(matching_schemas) <= 1 return matching_schemas or None
[ "def", "_GetApiSchema", "(", "self", ",", "api_name", ",", "file_system", ",", "version", ")", ":", "api_filename", "=", "self", ".", "_GetApiSchemaFilename", "(", "api_name", ",", "file_system", ",", "version", ")", "if", "api_filename", "is", "None", ":", "# No file for the API could be found in the given |file_system|.", "return", "None", "schema_fs", "=", "self", ".", "_compiled_fs_factory", ".", "ForApiSchema", "(", "file_system", ")", "api_schemas", "=", "schema_fs", ".", "GetFromFile", "(", "api_filename", ")", ".", "Get", "(", ")", "matching_schemas", "=", "[", "api", "for", "api", "in", "api_schemas", "if", "api", "[", "'namespace'", "]", "==", "api_name", "]", "# There should only be a single matching schema per file, or zero in the", "# case of no API data being found in _EXTENSION_API.", "assert", "len", "(", "matching_schemas", ")", "<=", "1", "return", "matching_schemas", "or", "None" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/availability_finder.py#L117-L133
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/multiprocessing/pool.py
python
Pool._repopulate_pool
(self)
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
[ "Bring", "the", "number", "of", "pool", "processes", "up", "to", "the", "specified", "number", "for", "use", "after", "reaping", "workers", "which", "have", "exited", "." ]
def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): # changed worker -> clean_worker args = (self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild) if hasattr(self, '_wrap_exception'): args += (self._wrap_exception,) w = self.Process(target=clean_worker, args=args) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() util.debug('added worker')
[ "def", "_repopulate_pool", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "_processes", "-", "len", "(", "self", ".", "_pool", ")", ")", ":", "# changed worker -> clean_worker", "args", "=", "(", "self", ".", "_inqueue", ",", "self", ".", "_outqueue", ",", "self", ".", "_initializer", ",", "self", ".", "_initargs", ",", "self", ".", "_maxtasksperchild", ")", "if", "hasattr", "(", "self", ",", "'_wrap_exception'", ")", ":", "args", "+=", "(", "self", ".", "_wrap_exception", ",", ")", "w", "=", "self", ".", "Process", "(", "target", "=", "clean_worker", ",", "args", "=", "args", ")", "self", ".", "_pool", ".", "append", "(", "w", ")", "w", ".", "name", "=", "w", ".", "name", ".", "replace", "(", "'Process'", ",", "'PoolWorker'", ")", "w", ".", "daemon", "=", "True", "w", ".", "start", "(", ")", "util", ".", "debug", "(", "'added worker'", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/multiprocessing/pool.py#L27-L43
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
VarScrollHelperBase.EnablePhysicalScrolling
(*args, **kwargs)
return _windows_.VarScrollHelperBase_EnablePhysicalScrolling(*args, **kwargs)
EnablePhysicalScrolling(self, bool scrolling=True)
EnablePhysicalScrolling(self, bool scrolling=True)
[ "EnablePhysicalScrolling", "(", "self", "bool", "scrolling", "=", "True", ")" ]
def EnablePhysicalScrolling(*args, **kwargs): """EnablePhysicalScrolling(self, bool scrolling=True)""" return _windows_.VarScrollHelperBase_EnablePhysicalScrolling(*args, **kwargs)
[ "def", "EnablePhysicalScrolling", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VarScrollHelperBase_EnablePhysicalScrolling", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2206-L2208
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
MenuBar.IsAttached
(*args, **kwargs)
return _core_.MenuBar_IsAttached(*args, **kwargs)
IsAttached(self) -> bool
IsAttached(self) -> bool
[ "IsAttached", "(", "self", ")", "-", ">", "bool" ]
def IsAttached(*args, **kwargs): """IsAttached(self) -> bool""" return _core_.MenuBar_IsAttached(*args, **kwargs)
[ "def", "IsAttached", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuBar_IsAttached", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L12367-L12369
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
tools/scan-build-py/libscanbuild/intercept.py
python
format_entry
(exec_trace)
Generate the desired fields for compilation database entries.
Generate the desired fields for compilation database entries.
[ "Generate", "the", "desired", "fields", "for", "compilation", "database", "entries", "." ]
def format_entry(exec_trace): """ Generate the desired fields for compilation database entries. """ def abspath(cwd, name): """ Create normalized absolute path from input filename. """ fullname = name if os.path.isabs(name) else os.path.join(cwd, name) return os.path.normpath(fullname) logging.debug('format this command: %s', exec_trace['command']) compilation = split_command(exec_trace['command']) if compilation: for source in compilation.files: compiler = 'c++' if compilation.compiler == 'c++' else 'cc' command = [compiler, '-c'] + compilation.flags + [source] logging.debug('formated as: %s', command) yield { 'directory': exec_trace['directory'], 'command': encode(command), 'file': abspath(exec_trace['directory'], source) }
[ "def", "format_entry", "(", "exec_trace", ")", ":", "def", "abspath", "(", "cwd", ",", "name", ")", ":", "\"\"\" Create normalized absolute path from input filename. \"\"\"", "fullname", "=", "name", "if", "os", ".", "path", ".", "isabs", "(", "name", ")", "else", "os", ".", "path", ".", "join", "(", "cwd", ",", "name", ")", "return", "os", ".", "path", ".", "normpath", "(", "fullname", ")", "logging", ".", "debug", "(", "'format this command: %s'", ",", "exec_trace", "[", "'command'", "]", ")", "compilation", "=", "split_command", "(", "exec_trace", "[", "'command'", "]", ")", "if", "compilation", ":", "for", "source", "in", "compilation", ".", "files", ":", "compiler", "=", "'c++'", "if", "compilation", ".", "compiler", "==", "'c++'", "else", "'cc'", "command", "=", "[", "compiler", ",", "'-c'", "]", "+", "compilation", ".", "flags", "+", "[", "source", "]", "logging", ".", "debug", "(", "'formated as: %s'", ",", "command", ")", "yield", "{", "'directory'", ":", "exec_trace", "[", "'directory'", "]", ",", "'command'", ":", "encode", "(", "command", ")", ",", "'file'", ":", "abspath", "(", "exec_trace", "[", "'directory'", "]", ",", "source", ")", "}" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/tools/scan-build-py/libscanbuild/intercept.py#L204-L223
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/complete/genk-timing.py
python
TimingScriptGenerator.writeTimingCall
(self, filename, numFuncs, funcsCalled, totalCalls)
Echo some comments and invoke both versions of toy
Echo some comments and invoke both versions of toy
[ "Echo", "some", "comments", "and", "invoke", "both", "versions", "of", "toy" ]
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls): """Echo some comments and invoke both versions of toy""" rootname = filename if '.' in filename: rootname = filename[:filename.rfind('.')] self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT (original)\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=false < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With MCJIT (lazy)\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true < %s > %s-mcjit-lazy.out 2> %s-mcjit-lazy.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile) self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"") self.shfile.write(" -o %s -a " % self.timeFile) self.shfile.write("./toy -suppress-prompts -use-mcjit=false < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname)) self.shfile.write("echo \"\" >> %s\n" % self.timeFile) self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
[ "def", "writeTimingCall", "(", "self", ",", "filename", ",", "numFuncs", ",", "funcsCalled", ",", "totalCalls", ")", ":", "rootname", "=", "filename", "if", "'.'", "in", "filename", ":", "rootname", "=", "filename", "[", ":", "filename", ".", "rfind", "(", "'.'", ")", "]", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"%s: Calls %d of %d functions, %d total\\\" >> %s\\n\"", "%", "(", "filename", ",", "funcsCalled", ",", "numFuncs", ",", "totalCalls", ",", "self", ".", "timeFile", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT (original)\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=false < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With MCJIT (lazy)\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true < %s > %s-mcjit-lazy.out 2> %s-mcjit-lazy.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"With JIT\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"", ")", "self", ".", "shfile", ".", "write", "(", "\" -o %s -a \"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"./toy -suppress-prompts -use-mcjit=false < %s > %s-jit.out 2> %s-jit.err\\n\"", "%", "(", "filename", ",", "rootname", ",", "rootname", ")", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")", "self", ".", "shfile", ".", "write", "(", "\"echo \\\"\\\" >> %s\\n\"", "%", "self", ".", "timeFile", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L13-L35
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/common.py
python
stringify_path
( filepath_or_buffer: FilePathOrBuffer[AnyStr], convert_file_like: bool = False, )
return _expand_user(filepath_or_buffer)
Attempt to convert a path-like object to a string. Parameters ---------- filepath_or_buffer : object to be converted Returns ------- str_filepath_or_buffer : maybe a string version of the object Notes ----- Objects supporting the fspath protocol (python 3.6+) are coerced according to its __fspath__ method. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like.
Attempt to convert a path-like object to a string.
[ "Attempt", "to", "convert", "a", "path", "-", "like", "object", "to", "a", "string", "." ]
def stringify_path( filepath_or_buffer: FilePathOrBuffer[AnyStr], convert_file_like: bool = False, ) -> FileOrBuffer[AnyStr]: """ Attempt to convert a path-like object to a string. Parameters ---------- filepath_or_buffer : object to be converted Returns ------- str_filepath_or_buffer : maybe a string version of the object Notes ----- Objects supporting the fspath protocol (python 3.6+) are coerced according to its __fspath__ method. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. """ if not convert_file_like and is_file_like(filepath_or_buffer): # GH 38125: some fsspec objects implement os.PathLike but have already opened a # file. This prevents opening the file a second time. infer_compression calls # this function with convert_file_like=True to infer the compression. return cast(FileOrBuffer[AnyStr], filepath_or_buffer) if isinstance(filepath_or_buffer, os.PathLike): filepath_or_buffer = filepath_or_buffer.__fspath__() return _expand_user(filepath_or_buffer)
[ "def", "stringify_path", "(", "filepath_or_buffer", ":", "FilePathOrBuffer", "[", "AnyStr", "]", ",", "convert_file_like", ":", "bool", "=", "False", ",", ")", "->", "FileOrBuffer", "[", "AnyStr", "]", ":", "if", "not", "convert_file_like", "and", "is_file_like", "(", "filepath_or_buffer", ")", ":", "# GH 38125: some fsspec objects implement os.PathLike but have already opened a", "# file. This prevents opening the file a second time. infer_compression calls", "# this function with convert_file_like=True to infer the compression.", "return", "cast", "(", "FileOrBuffer", "[", "AnyStr", "]", ",", "filepath_or_buffer", ")", "if", "isinstance", "(", "filepath_or_buffer", ",", "os", ".", "PathLike", ")", ":", "filepath_or_buffer", "=", "filepath_or_buffer", ".", "__fspath__", "(", ")", "return", "_expand_user", "(", "filepath_or_buffer", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/common.py#L171-L202
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
RobotModelDriver.getVelocity
(self)
return _robotsim.RobotModelDriver_getVelocity(self)
r""" getVelocity(RobotModelDriver self) -> double Returns the current driver velocity value from the robot's velocity.
r""" getVelocity(RobotModelDriver self) -> double
[ "r", "getVelocity", "(", "RobotModelDriver", "self", ")", "-", ">", "double" ]
def getVelocity(self) -> "double": r""" getVelocity(RobotModelDriver self) -> double Returns the current driver velocity value from the robot's velocity. """ return _robotsim.RobotModelDriver_getVelocity(self)
[ "def", "getVelocity", "(", "self", ")", "->", "\"double\"", ":", "return", "_robotsim", ".", "RobotModelDriver_getVelocity", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4697-L4705
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
PreAuiMDIClientWindow
(*args, **kwargs)
return val
PreAuiMDIClientWindow() -> AuiMDIClientWindow
PreAuiMDIClientWindow() -> AuiMDIClientWindow
[ "PreAuiMDIClientWindow", "()", "-", ">", "AuiMDIClientWindow" ]
def PreAuiMDIClientWindow(*args, **kwargs): """PreAuiMDIClientWindow() -> AuiMDIClientWindow""" val = _aui.new_PreAuiMDIClientWindow(*args, **kwargs) val._setOORInfo(val) return val
[ "def", "PreAuiMDIClientWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_aui", ".", "new_PreAuiMDIClientWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", "val", ".", "_setOORInfo", "(", "val", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1649-L1653
SpaceNetChallenge/BuildingDetectors
3def3c44b5847c744cd2f3356182892d92496579
qinhaifang/src/caffe-mnc/scripts/cpp_lint.py
python
FileInfo.IsSource
(self)
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
File has a source file extension.
File has a source file extension.
[ "File", "has", "a", "source", "file", "extension", "." ]
def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
[ "def", "IsSource", "(", "self", ")", ":", "return", "self", ".", "Extension", "(", ")", "[", "1", ":", "]", "in", "(", "'c'", ",", "'cc'", ",", "'cpp'", ",", "'cxx'", ")" ]
https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/caffe-mnc/scripts/cpp_lint.py#L956-L958
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
PascalMultilabelDataLayerSync.backward
(self, top, propagate_down, bottom)
These layers does not back propagate
These layers does not back propagate
[ "These", "layers", "does", "not", "back", "propagate" ]
def backward(self, top, propagate_down, bottom): """ These layers does not back propagate """ pass
[ "def", "backward", "(", "self", ",", "top", ",", "propagate_down", ",", "bottom", ")", ":", "pass" ]
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L74-L78
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/perf_insights/third_party/cloudstorage/common.py
python
validate_bucket_name
(name)
Validate a Google Storage bucket name. Args: name: a Google Storage bucket name with no prefix or suffix. Raises: ValueError: if name is invalid.
Validate a Google Storage bucket name.
[ "Validate", "a", "Google", "Storage", "bucket", "name", "." ]
def validate_bucket_name(name): """Validate a Google Storage bucket name. Args: name: a Google Storage bucket name with no prefix or suffix. Raises: ValueError: if name is invalid. """ _validate_path(name) if not _GCS_BUCKET_REGEX.match(name): raise ValueError('Bucket should be 3-63 characters long using only a-z,' '0-9, underscore, dash or dot but got %s' % name)
[ "def", "validate_bucket_name", "(", "name", ")", ":", "_validate_path", "(", "name", ")", "if", "not", "_GCS_BUCKET_REGEX", ".", "match", "(", "name", ")", ":", "raise", "ValueError", "(", "'Bucket should be 3-63 characters long using only a-z,'", "'0-9, underscore, dash or dot but got %s'", "%", "name", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/perf_insights/third_party/cloudstorage/common.py#L201-L213
vmware/concord-bft
ec036a384b4c81be0423d4b429bd37900b13b864
util/pyclient/bft_client.py
python
BftClient.__enter__
(self)
Context manager method for 'with' statements
Context manager method for 'with' statements
[ "Context", "manager", "method", "for", "with", "statements" ]
def __enter__(self): """ Context manager method for 'with' statements """ pass
[ "def", "__enter__", "(", "self", ")", ":", "pass" ]
https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/util/pyclient/bft_client.py#L102-L104
happynear/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
examples/pycaffe/tools.py
python
CaffeSolver.add_from_file
(self, filepath)
Reads a caffe solver prototxt file and updates the Caffesolver instance parameters.
Reads a caffe solver prototxt file and updates the Caffesolver instance parameters.
[ "Reads", "a", "caffe", "solver", "prototxt", "file", "and", "updates", "the", "Caffesolver", "instance", "parameters", "." ]
def add_from_file(self, filepath): """ Reads a caffe solver prototxt file and updates the Caffesolver instance parameters. """ with open(filepath, 'r') as f: for line in f: if line[0] == '#': continue splitLine = line.split(':') self.sp[splitLine[0].strip()] = splitLine[1].strip()
[ "def", "add_from_file", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", "[", "0", "]", "==", "'#'", ":", "continue", "splitLine", "=", "line", ".", "split", "(", "':'", ")", "self", ".", "sp", "[", "splitLine", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "splitLine", "[", "1", "]", ".", "strip", "(", ")" ]
https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/examples/pycaffe/tools.py#L101-L111
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Iface.get_row_as_arrays
(self, name, row)
Alternative interface using array as cell Parameters: - name - row
Alternative interface using array as cell Parameters: - name - row
[ "Alternative", "interface", "using", "array", "as", "cell", "Parameters", ":", "-", "name", "-", "row" ]
def get_row_as_arrays(self, name, row): """ Alternative interface using array as cell Parameters: - name - row """ pass
[ "def", "get_row_as_arrays", "(", "self", ",", "name", ",", "row", ")", ":", "pass" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L120-L128
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py
python
isalnum
(a)
return _vec_string(a, bool_, 'isalnum')
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.isalnum
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.
[ "Returns", "true", "for", "each", "element", "if", "all", "characters", "in", "the", "string", "are", "alphanumeric", "and", "there", "is", "at", "least", "one", "character", "false", "otherwise", "." ]
def isalnum(a): """ Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.isalnum """ return _vec_string(a, bool_, 'isalnum')
[ "def", "isalnum", "(", "a", ")", ":", "return", "_vec_string", "(", "a", ",", "bool_", ",", "'isalnum'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py#L755-L777
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
Cursor.result_type
(self)
return self._result_type
Retrieve the Type of the result for this Cursor.
Retrieve the Type of the result for this Cursor.
[ "Retrieve", "the", "Type", "of", "the", "result", "for", "this", "Cursor", "." ]
def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getCursorResultType(self) return self._result_type
[ "def", "result_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_result_type'", ")", ":", "self", ".", "_result_type", "=", "conf", ".", "lib", ".", "clang_getCursorResultType", "(", "self", ")", "return", "self", ".", "_result_type" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L1668-L1673
toggl-open-source/toggldesktop
91865205885531cc8fd9e8d613dad49d625d56e7
third_party/cpplint/cpplint.py
python
GetIndentLevel
(line)
Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero.
Return the number of leading spaces in line.
[ "Return", "the", "number", "of", "leading", "spaces", "in", "line", "." ]
def GetIndentLevel(line): """Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero. """ indent = Match(r'^( *)\S', line) if indent: return len(indent.group(1)) else: return 0
[ "def", "GetIndentLevel", "(", "line", ")", ":", "indent", "=", "Match", "(", "r'^( *)\\S'", ",", "line", ")", "if", "indent", ":", "return", "len", "(", "indent", ".", "group", "(", "1", ")", ")", "else", ":", "return", "0" ]
https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/cpplint/cpplint.py#L1635-L1648
espressomd/espresso
7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a
src/python/espressomd/rotation.py
python
diagonalized_inertia_tensor
(positions, masses)
return eig, eigv
Calculate the diagonalized inertia tensor with respect to the center of mass for given point masses at given positions. Parameters ---------- positions : (N,3) array_like of :obj:`float` Positions of the masses. masses : (N,) array_like of :obj:`float` Returns ------- (3,) array_like of :obj:`float` Principal moments of inertia. (3,3) array_like of :obj:`float` Principal axes of inertia. Note that the second axis is the coordinate axis (same as input).
Calculate the diagonalized inertia tensor with respect to the center of mass for given point masses at given positions.
[ "Calculate", "the", "diagonalized", "inertia", "tensor", "with", "respect", "to", "the", "center", "of", "mass", "for", "given", "point", "masses", "at", "given", "positions", "." ]
def diagonalized_inertia_tensor(positions, masses): """ Calculate the diagonalized inertia tensor with respect to the center of mass for given point masses at given positions. Parameters ---------- positions : (N,3) array_like of :obj:`float` Positions of the masses. masses : (N,) array_like of :obj:`float` Returns ------- (3,) array_like of :obj:`float` Principal moments of inertia. (3,3) array_like of :obj:`float` Principal axes of inertia. Note that the second axis is the coordinate axis (same as input). """ assert np.array(masses).shape[0] == np.array(positions).shape[0] def center_of_mass(positions, masses): return np.average( positions, axis=0, weights=masses) positions = np.array(np.copy(positions)) - \ center_of_mass(positions, masses) inertia = inertia_tensor(positions, masses) eig, eigv = np.linalg.eig(inertia) eigv = np.transpose(eigv) # check for right-handedness if not np.allclose(np.cross(eigv[0], eigv[1]), eigv[2]): eigv[[0, 1], :] = eigv[[1, 0], :] return eig, eigv
[ "def", "diagonalized_inertia_tensor", "(", "positions", ",", "masses", ")", ":", "assert", "np", ".", "array", "(", "masses", ")", ".", "shape", "[", "0", "]", "==", "np", ".", "array", "(", "positions", ")", ".", "shape", "[", "0", "]", "def", "center_of_mass", "(", "positions", ",", "masses", ")", ":", "return", "np", ".", "average", "(", "positions", ",", "axis", "=", "0", ",", "weights", "=", "masses", ")", "positions", "=", "np", ".", "array", "(", "np", ".", "copy", "(", "positions", ")", ")", "-", "center_of_mass", "(", "positions", ",", "masses", ")", "inertia", "=", "inertia_tensor", "(", "positions", ",", "masses", ")", "eig", ",", "eigv", "=", "np", ".", "linalg", ".", "eig", "(", "inertia", ")", "eigv", "=", "np", ".", "transpose", "(", "eigv", ")", "# check for right-handedness", "if", "not", "np", ".", "allclose", "(", "np", ".", "cross", "(", "eigv", "[", "0", "]", ",", "eigv", "[", "1", "]", ")", ",", "eigv", "[", "2", "]", ")", ":", "eigv", "[", "[", "0", ",", "1", "]", ",", ":", "]", "=", "eigv", "[", "[", "1", ",", "0", "]", ",", ":", "]", "return", "eig", ",", "eigv" ]
https://github.com/espressomd/espresso/blob/7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a/src/python/espressomd/rotation.py#L105-L138
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/conv_utils.py
python
conv_input_length
(output_length, filter_size, padding, stride)
return (output_length - 1) * stride - 2 * pad + filter_size
Determines input length of a convolution given output length. Args: output_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. Returns: The input length (integer).
Determines input length of a convolution given output length.
[ "Determines", "input", "length", "of", "a", "convolution", "given", "output", "length", "." ]
def conv_input_length(output_length, filter_size, padding, stride): """Determines input length of a convolution given output length. Args: output_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. Returns: The input length (integer). """ if output_length is None: return None assert padding in {'same', 'valid', 'full'} if padding == 'same': pad = filter_size // 2 elif padding == 'valid': pad = 0 elif padding == 'full': pad = filter_size - 1 return (output_length - 1) * stride - 2 * pad + filter_size
[ "def", "conv_input_length", "(", "output_length", ",", "filter_size", ",", "padding", ",", "stride", ")", ":", "if", "output_length", "is", "None", ":", "return", "None", "assert", "padding", "in", "{", "'same'", ",", "'valid'", ",", "'full'", "}", "if", "padding", "==", "'same'", ":", "pad", "=", "filter_size", "//", "2", "elif", "padding", "==", "'valid'", ":", "pad", "=", "0", "elif", "padding", "==", "'full'", ":", "pad", "=", "filter_size", "-", "1", "return", "(", "output_length", "-", "1", ")", "*", "stride", "-", "2", "*", "pad", "+", "filter_size" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/conv_utils.py#L115-L136
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntIntVH.BegI
(self)
return _snap.TIntIntVH_BegI(self)
BegI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter Parameters: self: THash< TInt,TVec< TInt,int > > const *
BegI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter
[ "BegI", "(", "TIntIntVH", "self", ")", "-", ">", "THash<", "TInt", "TVec<", "TInt", "int", ">", ">", "::", "TIter" ]
def BegI(self): """ BegI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter Parameters: self: THash< TInt,TVec< TInt,int > > const * """ return _snap.TIntIntVH_BegI(self)
[ "def", "BegI", "(", "self", ")", ":", "return", "_snap", ".", "TIntIntVH_BegI", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L17751-L17759
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Graph.unique_name
(self, name, mark_as_used=True)
return name
Return a unique operation name for `name`. Note: You rarely need to call `unique_name()` directly. Most of the time you just need to create `with g.name_scope()` blocks to generate structured names. `unique_name` is used to generate structured names, separated by `"/"`, to help identify operations when debugging a graph. Operation names are displayed in error messages reported by the TensorFlow runtime, and in various visualization tools such as TensorBoard. If `mark_as_used` is set to `True`, which is the default, a new unique name is created and marked as in use. If it's set to `False`, the unique name is returned without actually being marked as used. This is useful when the caller simply wants to know what the name to be created will be. Args: name: The name for an operation. mark_as_used: Whether to mark this name as being used. Returns: A string to be passed to `create_op()` that will be used to name the operation being created.
Return a unique operation name for `name`.
[ "Return", "a", "unique", "operation", "name", "for", "name", "." ]
def unique_name(self, name, mark_as_used=True): """Return a unique operation name for `name`. Note: You rarely need to call `unique_name()` directly. Most of the time you just need to create `with g.name_scope()` blocks to generate structured names. `unique_name` is used to generate structured names, separated by `"/"`, to help identify operations when debugging a graph. Operation names are displayed in error messages reported by the TensorFlow runtime, and in various visualization tools such as TensorBoard. If `mark_as_used` is set to `True`, which is the default, a new unique name is created and marked as in use. If it's set to `False`, the unique name is returned without actually being marked as used. This is useful when the caller simply wants to know what the name to be created will be. Args: name: The name for an operation. mark_as_used: Whether to mark this name as being used. Returns: A string to be passed to `create_op()` that will be used to name the operation being created. """ if self._name_stack: name = self._name_stack + "/" + name i = self._names_in_use.get(name, 0) # Increment the number for "name". if mark_as_used: self._names_in_use[name] = i + 1 if i > 0: base_name = name # Make sure the composed name is not already used. while name in self._names_in_use: name = "%s_%d" % (base_name, i) i += 1 # Mark the composed name as used in case someone wants # to call unique_name("name_1"). if mark_as_used: self._names_in_use[name] = 1 return name
[ "def", "unique_name", "(", "self", ",", "name", ",", "mark_as_used", "=", "True", ")", ":", "if", "self", ".", "_name_stack", ":", "name", "=", "self", ".", "_name_stack", "+", "\"/\"", "+", "name", "i", "=", "self", ".", "_names_in_use", ".", "get", "(", "name", ",", "0", ")", "# Increment the number for \"name\".", "if", "mark_as_used", ":", "self", ".", "_names_in_use", "[", "name", "]", "=", "i", "+", "1", "if", "i", ">", "0", ":", "base_name", "=", "name", "# Make sure the composed name is not already used.", "while", "name", "in", "self", ".", "_names_in_use", ":", "name", "=", "\"%s_%d\"", "%", "(", "base_name", ",", "i", ")", "i", "+=", "1", "# Mark the composed name as used in case someone wants", "# to call unique_name(\"name_1\").", "if", "mark_as_used", ":", "self", ".", "_names_in_use", "[", "name", "]", "=", "1", "return", "name" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L3187-L3230
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/search.py
python
index_sample
(x, index)
return out
**IndexSample Layer** IndexSample OP returns the element of the specified location of X, and the location is specified by Index. .. code-block:: text Given: X = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] Index = [[0, 1, 3], [0, 2, 4]] Then: Out = [[1, 2, 4], [6, 8, 10]] Args: x (Tensor): The source input tensor with 2-D shape. Supported data type is int32, int64, float32, float64. index (Tensor): The index input tensor with 2-D shape, first dimension should be same with X. Data type is int32 or int64. Returns: output (Tensor): The output is a tensor with the same shape as index. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]], dtype='float32') index = paddle.to_tensor([[0, 1, 2], [1, 2, 3], [0, 0, 0]], dtype='int32') target = paddle.to_tensor([[100, 200, 300, 400], [500, 600, 700, 800], [900, 1000, 1100, 1200]], dtype='int32') out_z1 = paddle.index_sample(x, index) print(out_z1) #[[1. 2. 3.] # [6. 7. 8.] # [9. 9. 9.]] # Use the index of the maximum value by topk op # get the value of the element of the corresponding index in other tensors top_value, top_index = paddle.topk(x, k=2) out_z2 = paddle.index_sample(target, top_index) print(top_value) #[[ 4. 3.] # [ 8. 7.] # [12. 11.]] print(top_index) #[[3 2] # [3 2] # [3 2]] print(out_z2) #[[ 400 300] # [ 800 700] # [1200 1100]]
**IndexSample Layer**
[ "**", "IndexSample", "Layer", "**" ]
def index_sample(x, index): """ **IndexSample Layer** IndexSample OP returns the element of the specified location of X, and the location is specified by Index. .. code-block:: text Given: X = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] Index = [[0, 1, 3], [0, 2, 4]] Then: Out = [[1, 2, 4], [6, 8, 10]] Args: x (Tensor): The source input tensor with 2-D shape. Supported data type is int32, int64, float32, float64. index (Tensor): The index input tensor with 2-D shape, first dimension should be same with X. Data type is int32 or int64. Returns: output (Tensor): The output is a tensor with the same shape as index. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]], dtype='float32') index = paddle.to_tensor([[0, 1, 2], [1, 2, 3], [0, 0, 0]], dtype='int32') target = paddle.to_tensor([[100, 200, 300, 400], [500, 600, 700, 800], [900, 1000, 1100, 1200]], dtype='int32') out_z1 = paddle.index_sample(x, index) print(out_z1) #[[1. 2. 3.] # [6. 7. 8.] # [9. 9. 9.]] # Use the index of the maximum value by topk op # get the value of the element of the corresponding index in other tensors top_value, top_index = paddle.topk(x, k=2) out_z2 = paddle.index_sample(target, top_index) print(top_value) #[[ 4. 3.] # [ 8. 7.] # [12. 11.]] print(top_index) #[[3 2] # [3 2] # [3 2]] print(out_z2) #[[ 400 300] # [ 800 700] # [1200 1100]] """ if in_dygraph_mode(): return _C_ops.index_sample(x, index) helper = LayerHelper("index_sample", **locals()) check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'paddle.tensor.search.index_sample') check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'paddle.tensor.search.index_sample') out = helper.create_variable_for_type_inference(dtype=x.dtype) helper.append_op( type='index_sample', inputs={'X': x, 'Index': index}, outputs={'Out': out}) return out
[ "def", "index_sample", "(", "x", ",", "index", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "return", "_C_ops", ".", "index_sample", "(", "x", ",", "index", ")", "helper", "=", "LayerHelper", "(", "\"index_sample\"", ",", "*", "*", "locals", "(", ")", ")", "check_variable_and_dtype", "(", "x", ",", "'x'", ",", "[", "'float32'", ",", "'float64'", ",", "'int32'", ",", "'int64'", "]", ",", "'paddle.tensor.search.index_sample'", ")", "check_variable_and_dtype", "(", "index", ",", "'index'", ",", "[", "'int32'", ",", "'int64'", "]", ",", "'paddle.tensor.search.index_sample'", ")", "out", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "x", ".", "dtype", ")", "helper", ".", "append_op", "(", "type", "=", "'index_sample'", ",", "inputs", "=", "{", "'X'", ":", "x", ",", "'Index'", ":", "index", "}", ",", "outputs", "=", "{", "'Out'", ":", "out", "}", ")", "return", "out" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/search.py#L634-L722
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py
python
ismethod
(object)
return isinstance(object, types.MethodType)
Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None
Return true if the object is an instance method.
[ "Return", "true", "if", "the", "object", "is", "an", "instance", "method", "." ]
def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None""" return isinstance(object, types.MethodType)
[ "def", "ismethod", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "MethodType", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py#L67-L76
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.after_cancel
(self, id)
Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter.
Cancel scheduling of function identified with ID.
[ "Cancel", "scheduling", "of", "function", "identified", "with", "ID", "." ]
def after_cancel(self, id): """Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter.""" try: data = self.tk.call('after', 'info', id) # In Tk 8.3, splitlist returns: (script, type) # In Tk 8.4, splitlist may return (script, type) or (script,) script = self.tk.splitlist(data)[0] self.deletecommand(script) except TclError: pass self.tk.call('after', 'cancel', id)
[ "def", "after_cancel", "(", "self", ",", "id", ")", ":", "try", ":", "data", "=", "self", ".", "tk", ".", "call", "(", "'after'", ",", "'info'", ",", "id", ")", "# In Tk 8.3, splitlist returns: (script, type)", "# In Tk 8.4, splitlist may return (script, type) or (script,)", "script", "=", "self", ".", "tk", ".", "splitlist", "(", "data", ")", "[", "0", "]", "self", ".", "deletecommand", "(", "script", ")", "except", "TclError", ":", "pass", "self", ".", "tk", ".", "call", "(", "'after'", ",", "'cancel'", ",", "id", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L546-L559
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/mixed_norm.py
python
mixed_norm
(X, p: Union[int, str] = 2, q: Union[int, str] = 1)
return norm(vecnorms, q)
Lp,q norm; :math:`(\\sum_k (\\sum_l \\lvert x_{k,l} \\rvert^p)^{q/p})^{1/q}`. Parameters ---------- X : Expression or numeric constant The matrix to take the l_{p,q} norm of. p : int or str, optional The type of inner norm. q : int or str, optional The type of outer norm. Returns ------- Expression An Expression representing the mixed norm.
Lp,q norm; :math:`(\\sum_k (\\sum_l \\lvert x_{k,l} \\rvert^p)^{q/p})^{1/q}`.
[ "Lp", "q", "norm", ";", ":", "math", ":", "(", "\\\\", "sum_k", "(", "\\\\", "sum_l", "\\\\", "lvert", "x_", "{", "k", "l", "}", "\\\\", "rvert^p", ")", "^", "{", "q", "/", "p", "}", ")", "^", "{", "1", "/", "q", "}", "." ]
def mixed_norm(X, p: Union[int, str] = 2, q: Union[int, str] = 1): """Lp,q norm; :math:`(\\sum_k (\\sum_l \\lvert x_{k,l} \\rvert^p)^{q/p})^{1/q}`. Parameters ---------- X : Expression or numeric constant The matrix to take the l_{p,q} norm of. p : int or str, optional The type of inner norm. q : int or str, optional The type of outer norm. Returns ------- Expression An Expression representing the mixed norm. """ X = Expression.cast_to_const(X) # inner norms vecnorms = norm(X, p, axis=1) # outer norm return norm(vecnorms, q)
[ "def", "mixed_norm", "(", "X", ",", "p", ":", "Union", "[", "int", ",", "str", "]", "=", "2", ",", "q", ":", "Union", "[", "int", ",", "str", "]", "=", "1", ")", ":", "X", "=", "Expression", ".", "cast_to_const", "(", "X", ")", "# inner norms", "vecnorms", "=", "norm", "(", "X", ",", "p", ",", "axis", "=", "1", ")", "# outer norm", "return", "norm", "(", "vecnorms", ",", "q", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/mixed_norm.py#L23-L45
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
_BlockInfo.CheckBegin
(self, filename, clean_lines, linenum, error)
Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text up to the opening brace.
[ "Run", "checks", "that", "applies", "to", "text", "up", "to", "the", "opening", "brace", "." ]
def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckBegin", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L2099-L2112
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBSymbolContext.SetCompileUnit
(self, compile_unit)
return _lldb.SBSymbolContext_SetCompileUnit(self, compile_unit)
SetCompileUnit(SBSymbolContext self, SBCompileUnit compile_unit)
SetCompileUnit(SBSymbolContext self, SBCompileUnit compile_unit)
[ "SetCompileUnit", "(", "SBSymbolContext", "self", "SBCompileUnit", "compile_unit", ")" ]
def SetCompileUnit(self, compile_unit): """SetCompileUnit(SBSymbolContext self, SBCompileUnit compile_unit)""" return _lldb.SBSymbolContext_SetCompileUnit(self, compile_unit)
[ "def", "SetCompileUnit", "(", "self", ",", "compile_unit", ")", ":", "return", "_lldb", ".", "SBSymbolContext_SetCompileUnit", "(", "self", ",", "compile_unit", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L10013-L10015
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/cpplint.py
python
_CppLintState.BackupFilters
(self)
Saves the current filter list to backup storage.
Saves the current filter list to backup storage.
[ "Saves", "the", "current", "filter", "list", "to", "backup", "storage", "." ]
def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:]
[ "def", "BackupFilters", "(", "self", ")", ":", "self", ".", "_filters_backup", "=", "self", ".", "filters", "[", ":", "]" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L1048-L1050
apple/foundationdb
f7118ad406f44ab7a33970fc8370647ed0085e18
layers/containers/vector.py
python
Vector.empty
(self, tr=None)
return self._size(self._to_transaction(tr)) == 0
Test whether the Vector is empty.
Test whether the Vector is empty.
[ "Test", "whether", "the", "Vector", "is", "empty", "." ]
def empty(self, tr=None): """Test whether the Vector is empty.""" return self._size(self._to_transaction(tr)) == 0
[ "def", "empty", "(", "self", ",", "tr", "=", "None", ")", ":", "return", "self", ".", "_size", "(", "self", ".", "_to_transaction", "(", "tr", ")", ")", "==", "0" ]
https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/layers/containers/vector.py#L170-L172
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph_manager.py
python
CephManager.do_rados
(self, cmd, pool=None, namespace=None, remote=None, **kwargs)
return proc
Execute a remote rados command.
Execute a remote rados command.
[ "Execute", "a", "remote", "rados", "command", "." ]
def do_rados(self, cmd, pool=None, namespace=None, remote=None, **kwargs): """ Execute a remote rados command. """ if remote is None: remote = self.controller pre = [ 'adjust-ulimits', 'ceph-coverage', f'{self.testdir}/archive/coverage', 'rados', '--cluster', self.cluster, ] if pool is not None: pre += ['--pool', pool] if namespace is not None: pre += ['--namespace', namespace] pre.extend(cmd) proc = remote.run( args=pre, wait=True, **kwargs ) return proc
[ "def", "do_rados", "(", "self", ",", "cmd", ",", "pool", "=", "None", ",", "namespace", "=", "None", ",", "remote", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "remote", "is", "None", ":", "remote", "=", "self", ".", "controller", "pre", "=", "[", "'adjust-ulimits'", ",", "'ceph-coverage'", ",", "f'{self.testdir}/archive/coverage'", ",", "'rados'", ",", "'--cluster'", ",", "self", ".", "cluster", ",", "]", "if", "pool", "is", "not", "None", ":", "pre", "+=", "[", "'--pool'", ",", "pool", "]", "if", "namespace", "is", "not", "None", ":", "pre", "+=", "[", "'--namespace'", ",", "namespace", "]", "pre", ".", "extend", "(", "cmd", ")", "proc", "=", "remote", ".", "run", "(", "args", "=", "pre", ",", "wait", "=", "True", ",", "*", "*", "kwargs", ")", "return", "proc" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L1715-L1740
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/glslang/update_glslang_sources.py
python
GoodCommit.GetUrl
(self)
return '{host}{subrepo}'.format( host=host, subrepo=self.subrepo)
Returns the URL for the repository.
Returns the URL for the repository.
[ "Returns", "the", "URL", "for", "the", "repository", "." ]
def GetUrl(self): """Returns the URL for the repository.""" host = SITE_TO_HOST[self.site] return '{host}{subrepo}'.format( host=host, subrepo=self.subrepo)
[ "def", "GetUrl", "(", "self", ")", ":", "host", "=", "SITE_TO_HOST", "[", "self", ".", "site", "]", "return", "'{host}{subrepo}'", ".", "format", "(", "host", "=", "host", ",", "subrepo", "=", "self", ".", "subrepo", ")" ]
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/glslang/update_glslang_sources.py#L89-L94
yue/yue
619d62c191b13c51c01be451dc48917c34a5aefc
building/tools/cpplint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L995-L1005
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/tools/scan-build-py/libscanbuild/analyze.py
python
require
(required)
return decorator
Decorator for checking the required values in state. It checks the required attributes in the passed state and stop when any of those is missing.
Decorator for checking the required values in state.
[ "Decorator", "for", "checking", "the", "required", "values", "in", "state", "." ]
def require(required): """ Decorator for checking the required values in state. It checks the required attributes in the passed state and stop when any of those is missing. """ def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): for key in required: if key not in args[0]: raise KeyError('{0} not passed to {1}'.format( key, function.__name__)) return function(*args, **kwargs) return wrapper return decorator
[ "def", "require", "(", "required", ")", ":", "def", "decorator", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "required", ":", "if", "key", "not", "in", "args", "[", "0", "]", ":", "raise", "KeyError", "(", "'{0} not passed to {1}'", ".", "format", "(", "key", ",", "function", ".", "__name__", ")", ")", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L269-L287
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/win32pdhquery.py
python
Query.addperfcounter
(self, object, counter, machine=None)
A "Performance Counter" is a stable, known, common counter, such as Memory, or Processor. The use of addperfcounter by end-users is deprecated, since the use of addcounterbybrowsing is considerably more flexible and general. It is provided here to allow the easy development of scripts which need to access variables so common we know them by name (such as Memory|Available Bytes), and to provide symmetry with the add inst counter method. usage: query.addperfcounter('Memory', 'Available Bytes') It is just as easy to access addcounter directly, the following has an identicle effect. query.addcounter('Memory', 'Available Bytes')
A "Performance Counter" is a stable, known, common counter, such as Memory, or Processor. The use of addperfcounter by end-users is deprecated, since the use of addcounterbybrowsing is considerably more flexible and general. It is provided here to allow the easy development of scripts which need to access variables so common we know them by name (such as Memory|Available Bytes), and to provide symmetry with the add inst counter method. usage: query.addperfcounter('Memory', 'Available Bytes') It is just as easy to access addcounter directly, the following has an identicle effect. query.addcounter('Memory', 'Available Bytes')
[ "A", "Performance", "Counter", "is", "a", "stable", "known", "common", "counter", "such", "as", "Memory", "or", "Processor", ".", "The", "use", "of", "addperfcounter", "by", "end", "-", "users", "is", "deprecated", "since", "the", "use", "of", "addcounterbybrowsing", "is", "considerably", "more", "flexible", "and", "general", ".", "It", "is", "provided", "here", "to", "allow", "the", "easy", "development", "of", "scripts", "which", "need", "to", "access", "variables", "so", "common", "we", "know", "them", "by", "name", "(", "such", "as", "Memory|Available", "Bytes", ")", "and", "to", "provide", "symmetry", "with", "the", "add", "inst", "counter", "method", ".", "usage", ":", "query", ".", "addperfcounter", "(", "Memory", "Available", "Bytes", ")", "It", "is", "just", "as", "easy", "to", "access", "addcounter", "directly", "the", "following", "has", "an", "identicle", "effect", ".", "query", ".", "addcounter", "(", "Memory", "Available", "Bytes", ")" ]
def addperfcounter(self, object, counter, machine=None): ''' A "Performance Counter" is a stable, known, common counter, such as Memory, or Processor. The use of addperfcounter by end-users is deprecated, since the use of addcounterbybrowsing is considerably more flexible and general. It is provided here to allow the easy development of scripts which need to access variables so common we know them by name (such as Memory|Available Bytes), and to provide symmetry with the add inst counter method. usage: query.addperfcounter('Memory', 'Available Bytes') It is just as easy to access addcounter directly, the following has an identicle effect. query.addcounter('Memory', 'Available Bytes') ''' BaseQuery.addcounter(self, object=object, counter=counter, machine=machine)
[ "def", "addperfcounter", "(", "self", ",", "object", ",", "counter", ",", "machine", "=", "None", ")", ":", "BaseQuery", ".", "addcounter", "(", "self", ",", "object", "=", "object", ",", "counter", "=", "counter", ",", "machine", "=", "machine", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/win32pdhquery.py#L348-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py
python
tzfile.fromutc
(self, dt)
return enfold(dt_out, fold=int(fold))
The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone.
The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.
[ "The", "tzfile", "implementation", "of", ":", "py", ":", "func", ":", "datetime", ".", "tzinfo", ".", "fromutc", "." ]
def fromutc(self, dt): """ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. :param dt: A :py:class:`datetime.datetime` object. :raises TypeError: Raised if ``dt`` is not a :py:class:`datetime.datetime` object. :raises ValueError: Raised if this is called with a ``dt`` which does not have this ``tzinfo`` attached. :return: Returns a :py:class:`datetime.datetime` object representing the wall time in ``self``'s time zone. """ # These isinstance checks are in datetime.tzinfo, so we'll preserve # them, even if we don't care about duck typing. if not isinstance(dt, datetime.datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") # First treat UTC as wall time and get the transition we're in. idx = self._find_last_transition(dt, in_utc=True) tti = self._get_ttinfo(idx) dt_out = dt + datetime.timedelta(seconds=tti.offset) fold = self.is_ambiguous(dt_out, idx=idx) return enfold(dt_out, fold=int(fold))
[ "def", "fromutc", "(", "self", ",", "dt", ")", ":", "# These isinstance checks are in datetime.tzinfo, so we'll preserve", "# them, even if we don't care about duck typing.", "if", "not", "isinstance", "(", "dt", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"fromutc() requires a datetime argument\"", ")", "if", "dt", ".", "tzinfo", "is", "not", "self", ":", "raise", "ValueError", "(", "\"dt.tzinfo is not self\"", ")", "# First treat UTC as wall time and get the transition we're in.", "idx", "=", "self", ".", "_find_last_transition", "(", "dt", ",", "in_utc", "=", "True", ")", "tti", "=", "self", ".", "_get_ttinfo", "(", "idx", ")", "dt_out", "=", "dt", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "tti", ".", "offset", ")", "fold", "=", "self", ".", "is_ambiguous", "(", "dt_out", ",", "idx", "=", "idx", ")", "return", "enfold", "(", "dt_out", ",", "fold", "=", "int", "(", "fold", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py#L637-L671
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
parserCtxt.htmlCtxtReadFd
(self, fd, URL, encoding, options)
return __tmp
parse an XML from a file descriptor and build a tree. This reuses the existing @ctxt parser context
parse an XML from a file descriptor and build a tree. This reuses the existing
[ "parse", "an", "XML", "from", "a", "file", "descriptor", "and", "build", "a", "tree", ".", "This", "reuses", "the", "existing" ]
def htmlCtxtReadFd(self, fd, URL, encoding, options): """parse an XML from a file descriptor and build a tree. This reuses the existing @ctxt parser context """ ret = libxml2mod.htmlCtxtReadFd(self._o, fd, URL, encoding, options) if ret is None:raise treeError('htmlCtxtReadFd() failed') __tmp = xmlDoc(_obj=ret) return __tmp
[ "def", "htmlCtxtReadFd", "(", "self", ",", "fd", ",", "URL", ",", "encoding", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "htmlCtxtReadFd", "(", "self", ".", "_o", ",", "fd", ",", "URL", ",", "encoding", ",", "options", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'htmlCtxtReadFd() failed'", ")", "__tmp", "=", "xmlDoc", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4905-L4911
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py
python
Scope.get_code
(self, first_indent=False, indention=' ')
return string
:return: Returns the code of the current scope. :rtype: str
:return: Returns the code of the current scope. :rtype: str
[ ":", "return", ":", "Returns", "the", "code", "of", "the", "current", "scope", ".", ":", "rtype", ":", "str" ]
def get_code(self, first_indent=False, indention=' '): """ :return: Returns the code of the current scope. :rtype: str """ string = "" if len(self.docstr) > 0: string += '"""' + self.docstr + '"""\n' objs = self.subscopes + self.imports + self.statements + self.returns for obj in sorted(objs, key=lambda x: x.start_pos): if isinstance(obj, Scope): string += obj.get_code(first_indent=True, indention=indention) else: if obj in self.returns and not isinstance(self, Lambda): string += 'yield ' if self.is_generator else 'return ' string += obj.get_code() if first_indent: string = common.indent_block(string, indention=indention) return string
[ "def", "get_code", "(", "self", ",", "first_indent", "=", "False", ",", "indention", "=", "' '", ")", ":", "string", "=", "\"\"", "if", "len", "(", "self", ".", "docstr", ")", ">", "0", ":", "string", "+=", "'\"\"\"'", "+", "self", ".", "docstr", "+", "'\"\"\"\\n'", "objs", "=", "self", ".", "subscopes", "+", "self", ".", "imports", "+", "self", ".", "statements", "+", "self", ".", "returns", "for", "obj", "in", "sorted", "(", "objs", ",", "key", "=", "lambda", "x", ":", "x", ".", "start_pos", ")", ":", "if", "isinstance", "(", "obj", ",", "Scope", ")", ":", "string", "+=", "obj", ".", "get_code", "(", "first_indent", "=", "True", ",", "indention", "=", "indention", ")", "else", ":", "if", "obj", "in", "self", ".", "returns", "and", "not", "isinstance", "(", "self", ",", "Lambda", ")", ":", "string", "+=", "'yield '", "if", "self", ".", "is_generator", "else", "'return '", "string", "+=", "obj", ".", "get_code", "(", ")", "if", "first_indent", ":", "string", "=", "common", ".", "indent_block", "(", "string", ",", "indention", "=", "indention", ")", "return", "string" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py#L194-L214
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py
python
Context.to_integral_exact
(self, a)
return a.to_integral_exact(context=self)
Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting; Inexact and Rounded flags are allowed in this operation. The rounding mode is taken from the context. >>> ExtendedContext.to_integral_exact(Decimal('2.1')) Decimal('2') >>> ExtendedContext.to_integral_exact(Decimal('100')) Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('100.0')) Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('101.5')) Decimal('102') >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) Decimal('-102') >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) Decimal('1.0E+6') >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) Decimal('7.89E+77') >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) Decimal('-Infinity')
Rounds to an integer.
[ "Rounds", "to", "an", "integer", "." ]
def to_integral_exact(self, a): """Rounds to an integer. When the operand has a negative exponent, the result is the same as using the quantize() operation using the given operand as the left-hand-operand, 1E+0 as the right-hand-operand, and the precision of the operand as the precision setting; Inexact and Rounded flags are allowed in this operation. The rounding mode is taken from the context. >>> ExtendedContext.to_integral_exact(Decimal('2.1')) Decimal('2') >>> ExtendedContext.to_integral_exact(Decimal('100')) Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('100.0')) Decimal('100') >>> ExtendedContext.to_integral_exact(Decimal('101.5')) Decimal('102') >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) Decimal('-102') >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) Decimal('1.0E+6') >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) Decimal('7.89E+77') >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) Decimal('-Infinity') """ a = _convert_other(a, raiseit=True) return a.to_integral_exact(context=self)
[ "def", "to_integral_exact", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "to_integral_exact", "(", "context", "=", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L5356-L5384
scylladb/scylla
00a6fda7b98438184024fc4683b0accf1852e30c
scylla-gdb.py
python
histogram.__init__
(self, counts = None, print_indicators = True, formatter=None)
Constructor. Params: * counts: initial counts (default to empty). * print_indicators: print the '+' characters to illustrate relative count. Can be turned off when the item names are very long and would thus make indicators unreadable. * formatter: a callable that receives the item as its argument and is expected to return the string to be printed in the second column. By default, items are printed verbatim.
Constructor.
[ "Constructor", "." ]
def __init__(self, counts = None, print_indicators = True, formatter=None): """Constructor. Params: * counts: initial counts (default to empty). * print_indicators: print the '+' characters to illustrate relative count. Can be turned off when the item names are very long and would thus make indicators unreadable. * formatter: a callable that receives the item as its argument and is expected to return the string to be printed in the second column. By default, items are printed verbatim. """ if counts is None: self._counts = defaultdict(int) else: self._counts = counts self._print_indicators = print_indicators def default_formatter(value): return str(value) if formatter is None: self._formatter = default_formatter else: self._formatter = formatter
[ "def", "__init__", "(", "self", ",", "counts", "=", "None", ",", "print_indicators", "=", "True", ",", "formatter", "=", "None", ")", ":", "if", "counts", "is", "None", ":", "self", ".", "_counts", "=", "defaultdict", "(", "int", ")", "else", ":", "self", ".", "_counts", "=", "counts", "self", ".", "_print_indicators", "=", "print_indicators", "def", "default_formatter", "(", "value", ")", ":", "return", "str", "(", "value", ")", "if", "formatter", "is", "None", ":", "self", ".", "_formatter", "=", "default_formatter", "else", ":", "self", ".", "_formatter", "=", "formatter" ]
https://github.com/scylladb/scylla/blob/00a6fda7b98438184024fc4683b0accf1852e30c/scylla-gdb.py#L1078-L1101
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/linalg.py
python
call_xxdot
(context, builder, conjugate, dtype, n, a_data, b_data, out_data)
Call the BLAS vector * vector product function for the given arguments.
Call the BLAS vector * vector product function for the given arguments.
[ "Call", "the", "BLAS", "vector", "*", "vector", "product", "function", "for", "the", "given", "arguments", "." ]
def call_xxdot(context, builder, conjugate, dtype, n, a_data, b_data, out_data): """ Call the BLAS vector * vector product function for the given arguments. """ fnty = ir.FunctionType(ir.IntType(32), [ll_char, ll_char, intp_t, # kind, conjugate, n ll_void_p, ll_void_p, ll_void_p, # a, b, out ]) fn = builder.module.get_or_insert_function(fnty, name="numba_xxdot") kind = get_blas_kind(dtype) kind_val = ir.Constant(ll_char, ord(kind)) conjugate = ir.Constant(ll_char, int(conjugate)) res = builder.call(fn, (kind_val, conjugate, n, builder.bitcast(a_data, ll_void_p), builder.bitcast(b_data, ll_void_p), builder.bitcast(out_data, ll_void_p))) check_blas_return(context, builder, res)
[ "def", "call_xxdot", "(", "context", ",", "builder", ",", "conjugate", ",", "dtype", ",", "n", ",", "a_data", ",", "b_data", ",", "out_data", ")", ":", "fnty", "=", "ir", ".", "FunctionType", "(", "ir", ".", "IntType", "(", "32", ")", ",", "[", "ll_char", ",", "ll_char", ",", "intp_t", ",", "# kind, conjugate, n", "ll_void_p", ",", "ll_void_p", ",", "ll_void_p", ",", "# a, b, out", "]", ")", "fn", "=", "builder", ".", "module", ".", "get_or_insert_function", "(", "fnty", ",", "name", "=", "\"numba_xxdot\"", ")", "kind", "=", "get_blas_kind", "(", "dtype", ")", "kind_val", "=", "ir", ".", "Constant", "(", "ll_char", ",", "ord", "(", "kind", ")", ")", "conjugate", "=", "ir", ".", "Constant", "(", "ll_char", ",", "int", "(", "conjugate", ")", ")", "res", "=", "builder", ".", "call", "(", "fn", ",", "(", "kind_val", ",", "conjugate", ",", "n", ",", "builder", ".", "bitcast", "(", "a_data", ",", "ll_void_p", ")", ",", "builder", ".", "bitcast", "(", "b_data", ",", "ll_void_p", ")", ",", "builder", ".", "bitcast", "(", "out_data", ",", "ll_void_p", ")", ")", ")", "check_blas_return", "(", "context", ",", "builder", ",", "res", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/linalg.py#L344-L363
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/legendre.py
python
legfit
(x, y, deg, rcond=None, full=False, w=None)
return pu._fit(legvander, x, y, deg, rcond, full, w)
Least squares fit of Legendre series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x), where `n` is `deg`. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. deg : int or 1-D array_like Degree(s) of the fitting polynomials. If `deg` is a single integer all terms up to and including the `deg`'th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (`M`,), optional Weights. If not None, the contribution of each point ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. The default value is None. .. versionadded:: 1.5.0 Returns ------- coef : ndarray, shape (M,) or (M, K) Legendre coefficients ordered from low to high. If `y` was 2-D, the coefficients for the data in column k of `y` are in column `k`. If `deg` is specified as a list, coefficients for terms not included in the fit are set equal to zero in the returned `coef`. [residuals, rank, singular_values, rcond] : list These values are only returned if `full` = True resid -- sum of squared residuals of the least squares fit rank -- the numerical rank of the scaled Vandermonde matrix sv -- singular values of the scaled Vandermonde matrix rcond -- value of `rcond`. For more details, see `linalg.lstsq`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', np.RankWarning) See Also -------- chebfit, polyfit, lagfit, hermfit, hermefit legval : Evaluates a Legendre series. legvander : Vandermonde matrix of Legendre series. legweight : Legendre weight function (= 1). linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Legendre series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Legendre series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", https://en.wikipedia.org/wiki/Curve_fitting Examples --------
Least squares fit of Legendre series to data.
[ "Least", "squares", "fit", "of", "Legendre", "series", "to", "data", "." ]
def legfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Legendre series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x), where `n` is `deg`. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) or (M, K) y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column. deg : int or 1-D array_like Degree(s) of the fitting polynomials. If `deg` is a single integer all terms up to and including the `deg`'th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (`M`,), optional Weights. If not None, the contribution of each point ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. The default value is None. .. versionadded:: 1.5.0 Returns ------- coef : ndarray, shape (M,) or (M, K) Legendre coefficients ordered from low to high. If `y` was 2-D, the coefficients for the data in column k of `y` are in column `k`. If `deg` is specified as a list, coefficients for terms not included in the fit are set equal to zero in the returned `coef`. [residuals, rank, singular_values, rcond] : list These values are only returned if `full` = True resid -- sum of squared residuals of the least squares fit rank -- the numerical rank of the scaled Vandermonde matrix sv -- singular values of the scaled Vandermonde matrix rcond -- value of `rcond`. For more details, see `linalg.lstsq`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', np.RankWarning) See Also -------- chebfit, polyfit, lagfit, hermfit, hermefit legval : Evaluates a Legendre series. legvander : Vandermonde matrix of Legendre series. legweight : Legendre weight function (= 1). linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Legendre series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Legendre series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", https://en.wikipedia.org/wiki/Curve_fitting Examples -------- """ return pu._fit(legvander, x, y, deg, rcond, full, w)
[ "def", "legfit", "(", "x", ",", "y", ",", "deg", ",", "rcond", "=", "None", ",", "full", "=", "False", ",", "w", "=", "None", ")", ":", "return", "pu", ".", "_fit", "(", "legvander", ",", "x", ",", "y", ",", "deg", ",", "rcond", ",", "full", ",", "w", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/legendre.py#L1289-L1410
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/verilogtags.py
python
GenerateTags
(buff)
return rtags
Create a DocStruct object that represents a Verilog document @param buff: a file like buffer object (StringIO) @todo: add support for parsing module definitions / class variables
Create a DocStruct object that represents a Verilog document @param buff: a file like buffer object (StringIO) @todo: add support for parsing module definitions / class variables
[ "Create", "a", "DocStruct", "object", "that", "represents", "a", "Verilog", "document", "@param", "buff", ":", "a", "file", "like", "buffer", "object", "(", "StringIO", ")", "@todo", ":", "add", "support", "for", "parsing", "module", "definitions", "/", "class", "variables" ]
def GenerateTags(buff): """Create a DocStruct object that represents a Verilog document @param buff: a file like buffer object (StringIO) @todo: add support for parsing module definitions / class variables """ rtags = taglib.DocStruct() rtags.SetElementDescription('class', "Class Definitions") rtags.SetElementDescription('task', "Task Definitions") rtags.SetElementDescription('function', "Function Definitions") rtags.SetElementPriority('class', 3) rtags.SetElementPriority('task', 2) rtags.SetElementPriority('function', 1) # Variables to track parse state inclass = False # Inside a class defintion incomment = False # Inside a comment intask = False # Inside a task definition infunction = False # Inside a function definition # Parse the text for lnum, line in enumerate(buff): line = line.strip() llen = len(line) idx = 0 while idx < len(line): # Skip any leading Whitespace idx = parselib.SkipWhitespace(line, idx) # Check for coments if line[idx:].startswith(u'/*'): idx += 2 incomment = True elif line[idx:].startswith(u'//'): break # go to next line elif line[idx:].startswith(u'*/'): idx += 2 incomment = False # At end of line if idx >= llen: break # Look for tags if incomment: idx += 1 elif parselib.IsToken(line, idx, u'class'): idx = parselib.SkipWhitespace(line, idx + 5) cname = parselib.GetFirstIdentifier(line[idx:]) if cname is not None: inclass = True rtags.AddClass(taglib.Class(cname, lnum)) break # go to next line elif inclass and parselib.IsToken(line, idx, u'endclass'): inclass = False break # go to next line elif parselib.IsToken(line, idx, u'task'): idx += 4 tname = parselib.GetTokenParenLeft(line[idx:]) if tname is not None: intask = True if inclass: lclass = rtags.GetLastClass() task = taglib.Function(tname, lnum, 'task', lclass.GetName()) lclass.AddElement('task', task) else: task = taglib.Function(tname, lnum, 'task') rtags.AddElement('task', task) break # goto next line elif parselib.IsToken(line, idx, u'function'): idx += 8 fname = parselib.GetTokenParenLeft(line[idx:]) if fname is not None: infunction = True if inclass: lclass = rtags.GetLastClass() lclass.AddMethod(taglib.Method(fname, lnum)) else: rtags.AddFunction(taglib.Function(fname, lnum)) break elif intask and parselib.IsToken(line, idx, u'endtask'): intask = False break # go to next line elif infunction and parselib.IsToken(line, idx, 'endfunction'): infunction = False break else: idx += 1 return rtags
[ "def", "GenerateTags", "(", "buff", ")", ":", "rtags", "=", "taglib", ".", "DocStruct", "(", ")", "rtags", ".", "SetElementDescription", "(", "'class'", ",", "\"Class Definitions\"", ")", "rtags", ".", "SetElementDescription", "(", "'task'", ",", "\"Task Definitions\"", ")", "rtags", ".", "SetElementDescription", "(", "'function'", ",", "\"Function Definitions\"", ")", "rtags", ".", "SetElementPriority", "(", "'class'", ",", "3", ")", "rtags", ".", "SetElementPriority", "(", "'task'", ",", "2", ")", "rtags", ".", "SetElementPriority", "(", "'function'", ",", "1", ")", "# Variables to track parse state", "inclass", "=", "False", "# Inside a class defintion", "incomment", "=", "False", "# Inside a comment", "intask", "=", "False", "# Inside a task definition", "infunction", "=", "False", "# Inside a function definition", "# Parse the text", "for", "lnum", ",", "line", "in", "enumerate", "(", "buff", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "llen", "=", "len", "(", "line", ")", "idx", "=", "0", "while", "idx", "<", "len", "(", "line", ")", ":", "# Skip any leading Whitespace", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", ")", "# Check for coments", "if", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'/*'", ")", ":", "idx", "+=", "2", "incomment", "=", "True", "elif", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'//'", ")", ":", "break", "# go to next line", "elif", "line", "[", "idx", ":", "]", ".", "startswith", "(", "u'*/'", ")", ":", "idx", "+=", "2", "incomment", "=", "False", "# At end of line", "if", "idx", ">=", "llen", ":", "break", "# Look for tags", "if", "incomment", ":", "idx", "+=", "1", "elif", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'class'", ")", ":", "idx", "=", "parselib", ".", "SkipWhitespace", "(", "line", ",", "idx", "+", "5", ")", "cname", "=", "parselib", ".", "GetFirstIdentifier", "(", "line", "[", "idx", ":", "]", ")", "if", "cname", "is", "not", "None", ":", "inclass", "=", "True", "rtags", ".", "AddClass", "(", "taglib", ".", "Class", "(", "cname", ",", "lnum", ")", ")", "break", "# go to next line", "elif", "inclass", "and", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'endclass'", ")", ":", "inclass", "=", "False", "break", "# go to next line", "elif", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'task'", ")", ":", "idx", "+=", "4", "tname", "=", "parselib", ".", "GetTokenParenLeft", "(", "line", "[", "idx", ":", "]", ")", "if", "tname", "is", "not", "None", ":", "intask", "=", "True", "if", "inclass", ":", "lclass", "=", "rtags", ".", "GetLastClass", "(", ")", "task", "=", "taglib", ".", "Function", "(", "tname", ",", "lnum", ",", "'task'", ",", "lclass", ".", "GetName", "(", ")", ")", "lclass", ".", "AddElement", "(", "'task'", ",", "task", ")", "else", ":", "task", "=", "taglib", ".", "Function", "(", "tname", ",", "lnum", ",", "'task'", ")", "rtags", ".", "AddElement", "(", "'task'", ",", "task", ")", "break", "# goto next line", "elif", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'function'", ")", ":", "idx", "+=", "8", "fname", "=", "parselib", ".", "GetTokenParenLeft", "(", "line", "[", "idx", ":", "]", ")", "if", "fname", "is", "not", "None", ":", "infunction", "=", "True", "if", "inclass", ":", "lclass", "=", "rtags", ".", "GetLastClass", "(", ")", "lclass", ".", "AddMethod", "(", "taglib", ".", "Method", "(", "fname", ",", "lnum", ")", ")", "else", ":", "rtags", ".", "AddFunction", "(", "taglib", ".", "Function", "(", "fname", ",", "lnum", ")", ")", "break", "elif", "intask", "and", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "u'endtask'", ")", ":", "intask", "=", "False", "break", "# go to next line", "elif", "infunction", "and", "parselib", ".", "IsToken", "(", "line", ",", "idx", ",", "'endfunction'", ")", ":", "infunction", "=", "False", "break", "else", ":", "idx", "+=", "1", "return", "rtags" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/verilogtags.py#L30-L120
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/response.py
python
Response.set_cookie
(self, name, value, path="/", domain=None, max_age=None, expires=None, secure=False, httponly=False, comment=None)
Set a cookie to be sent with a Set-Cookie header in the response :param name: String name of the cookie :param value: String value of the cookie :param max_age: datetime.timedelta int representing the time (in seconds) until the cookie expires :param path: String path to which the cookie applies :param domain: String domain to which the cookie applies :param secure: Boolean indicating whether the cookie is marked as secure :param httponly: Boolean indicating whether the cookie is marked as HTTP Only :param comment: String comment :param expires: datetime.datetime or datetime.timedelta indicating a time or interval from now when the cookie expires
Set a cookie to be sent with a Set-Cookie header in the response
[ "Set", "a", "cookie", "to", "be", "sent", "with", "a", "Set", "-", "Cookie", "header", "in", "the", "response" ]
def set_cookie(self, name, value, path="/", domain=None, max_age=None, expires=None, secure=False, httponly=False, comment=None): """Set a cookie to be sent with a Set-Cookie header in the response :param name: String name of the cookie :param value: String value of the cookie :param max_age: datetime.timedelta int representing the time (in seconds) until the cookie expires :param path: String path to which the cookie applies :param domain: String domain to which the cookie applies :param secure: Boolean indicating whether the cookie is marked as secure :param httponly: Boolean indicating whether the cookie is marked as HTTP Only :param comment: String comment :param expires: datetime.datetime or datetime.timedelta indicating a time or interval from now when the cookie expires """ days = dict((i+1, name) for i, name in enumerate(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])) if value is None: value = '' max_age = 0 expires = timedelta(days=-1) if isinstance(expires, timedelta): expires = datetime.utcnow() + expires if expires is not None: expires_str = expires.strftime("%d %%s %Y %H:%M:%S GMT") expires_str = expires_str % days[expires.month] expires = expires_str if max_age is not None: if hasattr(max_age, "total_seconds"): max_age = int(max_age.total_seconds()) max_age = "%.0d" % max_age m = Cookie.Morsel() def maybe_set(key, value): if value is not None and value is not False: m[key] = value m.set(name, value, value) maybe_set("path", path) maybe_set("domain", domain) maybe_set("comment", comment) maybe_set("expires", expires) maybe_set("max-age", max_age) maybe_set("secure", secure) maybe_set("httponly", httponly) self.headers.append("Set-Cookie", m.OutputString())
[ "def", "set_cookie", "(", "self", ",", "name", ",", "value", ",", "path", "=", "\"/\"", ",", "domain", "=", "None", ",", "max_age", "=", "None", ",", "expires", "=", "None", ",", "secure", "=", "False", ",", "httponly", "=", "False", ",", "comment", "=", "None", ")", ":", "days", "=", "dict", "(", "(", "i", "+", "1", ",", "name", ")", "for", "i", ",", "name", "in", "enumerate", "(", "[", "\"jan\"", ",", "\"feb\"", ",", "\"mar\"", ",", "\"apr\"", ",", "\"may\"", ",", "\"jun\"", ",", "\"jul\"", ",", "\"aug\"", ",", "\"sep\"", ",", "\"oct\"", ",", "\"nov\"", ",", "\"dec\"", "]", ")", ")", "if", "value", "is", "None", ":", "value", "=", "''", "max_age", "=", "0", "expires", "=", "timedelta", "(", "days", "=", "-", "1", ")", "if", "isinstance", "(", "expires", ",", "timedelta", ")", ":", "expires", "=", "datetime", ".", "utcnow", "(", ")", "+", "expires", "if", "expires", "is", "not", "None", ":", "expires_str", "=", "expires", ".", "strftime", "(", "\"%d %%s %Y %H:%M:%S GMT\"", ")", "expires_str", "=", "expires_str", "%", "days", "[", "expires", ".", "month", "]", "expires", "=", "expires_str", "if", "max_age", "is", "not", "None", ":", "if", "hasattr", "(", "max_age", ",", "\"total_seconds\"", ")", ":", "max_age", "=", "int", "(", "max_age", ".", "total_seconds", "(", ")", ")", "max_age", "=", "\"%.0d\"", "%", "max_age", "m", "=", "Cookie", ".", "Morsel", "(", ")", "def", "maybe_set", "(", "key", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "value", "is", "not", "False", ":", "m", "[", "key", "]", "=", "value", "m", ".", "set", "(", "name", ",", "value", ",", "value", ")", "maybe_set", "(", "\"path\"", ",", "path", ")", "maybe_set", "(", "\"domain\"", ",", "domain", ")", "maybe_set", "(", "\"comment\"", ",", "comment", ")", "maybe_set", "(", "\"expires\"", ",", "expires", ")", "maybe_set", "(", "\"max-age\"", ",", "max_age", ")", "maybe_set", "(", "\"secure\"", ",", "secure", ")", "maybe_set", "(", "\"httponly\"", ",", "httponly", ")", "self", ".", "headers", ".", "append", "(", "\"Set-Cookie\"", ",", "m", ".", "OutputString", "(", ")", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/response.py#L94-L150
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/code_coverage/croc.py
python
Coverage.ParseLcovFile
(self, input_filename)
Adds coverage data from a .lcov file. Args: input_filename: Input filename.
Adds coverage data from a .lcov file.
[ "Adds", "coverage", "data", "from", "a", ".", "lcov", "file", "." ]
def ParseLcovFile(self, input_filename): """Adds coverage data from a .lcov file. Args: input_filename: Input filename. """ # TODO: All manner of error checking lcov_file = None try: lcov_file = open(input_filename, 'rt') self.ParseLcovData(lcov_file) finally: if lcov_file: lcov_file.close()
[ "def", "ParseLcovFile", "(", "self", ",", "input_filename", ")", ":", "# TODO: All manner of error checking", "lcov_file", "=", "None", "try", ":", "lcov_file", "=", "open", "(", "input_filename", ",", "'rt'", ")", "self", ".", "ParseLcovData", "(", "lcov_file", ")", "finally", ":", "if", "lcov_file", ":", "lcov_file", ".", "close", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/code_coverage/croc.py#L358-L371
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/ops/checkpoint_ops.py
python
load_variable_slot_initializer
(ckpt_path, old_tensor_name, primary_partition_info, new_row_vocab_size, new_col_vocab_size, old_row_vocab_file=None, new_row_vocab_file=None, old_col_vocab_file=None, new_col_vocab_file=None, num_row_oov_buckets=0, num_col_oov_buckets=0, initializer=None, max_rows_in_memory=-1)
return _initializer
Loads pre-trained multi-class slots for linear models from checkpoint. Wrapper around `load_and_remap_matrix_initializer()` specialized for loading multi-class slots (such as optimizer accumulators) and remapping them according to the provided vocab files. See docs for `load_and_remap_matrix_initializer()` for more details. Takes in a `variable_scope._PartitionInfo` representing the slot's primary `Variable`'s partitioning. This is necessary since accumulator `Variable` creation ignores primary scoping and partitioning information. Args: ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from which the old matrix `Tensor` will be loaded. old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. primary_partition_info: A `variable_scope._PartitionInfo` containing this slot's primary `Variable`'s partitioning information. This is used to calculate the offset and override the partition_info passed to the call to _initialize. new_row_vocab_size: `int` specifying the number of entries in `new_row_vocab_file`. If no row remapping is needed (no row vocab provided), this should be equal to the number of rows to load from the old matrix (which can theoretically be smaller than the number of rows in the old matrix). new_col_vocab_size: `int` specifying the number of entries in `new_col_vocab_file`. If no column remapping is needed (no column vocab provided), this should be equal to the number of columns in the old matrix. old_row_vocab_file: A scalar `Tensor` of type `string` containing the path to the old row vocabulary file. Can be None, which represents no remapping on the row axis. new_row_vocab_file: A scalar `Tensor` of type `string` containing the path to the new row vocabulary file. Can be None, which represents no remapping on the row axis. old_col_vocab_file: A scalar `Tensor` of type `string` containing the path to the old column vocabulary file. Can be None, which represents no remapping on the column axis. new_col_vocab_file: A scalar `Tensor` of type `string` containing the path to the new column vocabulary file. Can be None, which represents no remapping on the column axis. num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows to append. Must be >= 0. num_col_oov_buckets: `int` specifying the number of out-of-vocabulary columns to append. Must be >= 0. initializer: Initializer function to initialize missing values. Accepts a 1-D tensor as the arg to specify the shape of the returned tensor. If `None`, defaults to using `zeros_initializer()`. max_rows_in_memory: `int` specifying the maximum number of rows to load from the checkpoint at once. If less than or equal to 0, the entire matrix will be loaded into memory. Setting this arg trades increased disk reads for lower memory usage. Returns: A variable initializer function that should be used to initialize a (potentially partitioned) `Variable` whose complete shape is `[new_row_vocab_size + num_row_oov_buckets, new_col_vocab_size + num_col_oov_buckets]`. Raises: TypeError: If `initializer` is specified but not callable.
Loads pre-trained multi-class slots for linear models from checkpoint.
[ "Loads", "pre", "-", "trained", "multi", "-", "class", "slots", "for", "linear", "models", "from", "checkpoint", "." ]
def load_variable_slot_initializer(ckpt_path, old_tensor_name, primary_partition_info, new_row_vocab_size, new_col_vocab_size, old_row_vocab_file=None, new_row_vocab_file=None, old_col_vocab_file=None, new_col_vocab_file=None, num_row_oov_buckets=0, num_col_oov_buckets=0, initializer=None, max_rows_in_memory=-1): """Loads pre-trained multi-class slots for linear models from checkpoint. Wrapper around `load_and_remap_matrix_initializer()` specialized for loading multi-class slots (such as optimizer accumulators) and remapping them according to the provided vocab files. See docs for `load_and_remap_matrix_initializer()` for more details. Takes in a `variable_scope._PartitionInfo` representing the slot's primary `Variable`'s partitioning. This is necessary since accumulator `Variable` creation ignores primary scoping and partitioning information. Args: ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from which the old matrix `Tensor` will be loaded. old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint. primary_partition_info: A `variable_scope._PartitionInfo` containing this slot's primary `Variable`'s partitioning information. This is used to calculate the offset and override the partition_info passed to the call to _initialize. new_row_vocab_size: `int` specifying the number of entries in `new_row_vocab_file`. If no row remapping is needed (no row vocab provided), this should be equal to the number of rows to load from the old matrix (which can theoretically be smaller than the number of rows in the old matrix). new_col_vocab_size: `int` specifying the number of entries in `new_col_vocab_file`. If no column remapping is needed (no column vocab provided), this should be equal to the number of columns in the old matrix. old_row_vocab_file: A scalar `Tensor` of type `string` containing the path to the old row vocabulary file. Can be None, which represents no remapping on the row axis. new_row_vocab_file: A scalar `Tensor` of type `string` containing the path to the new row vocabulary file. Can be None, which represents no remapping on the row axis. old_col_vocab_file: A scalar `Tensor` of type `string` containing the path to the old column vocabulary file. Can be None, which represents no remapping on the column axis. new_col_vocab_file: A scalar `Tensor` of type `string` containing the path to the new column vocabulary file. Can be None, which represents no remapping on the column axis. num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows to append. Must be >= 0. num_col_oov_buckets: `int` specifying the number of out-of-vocabulary columns to append. Must be >= 0. initializer: Initializer function to initialize missing values. Accepts a 1-D tensor as the arg to specify the shape of the returned tensor. If `None`, defaults to using `zeros_initializer()`. max_rows_in_memory: `int` specifying the maximum number of rows to load from the checkpoint at once. If less than or equal to 0, the entire matrix will be loaded into memory. Setting this arg trades increased disk reads for lower memory usage. Returns: A variable initializer function that should be used to initialize a (potentially partitioned) `Variable` whose complete shape is `[new_row_vocab_size + num_row_oov_buckets, new_col_vocab_size + num_col_oov_buckets]`. Raises: TypeError: If `initializer` is specified but not callable. """ initializer_fn = load_and_remap_matrix_initializer( ckpt_path=ckpt_path, old_tensor_name=old_tensor_name, new_row_vocab_size=new_row_vocab_size, new_col_vocab_size=new_col_vocab_size, old_row_vocab_file=old_row_vocab_file, new_row_vocab_file=new_row_vocab_file, old_col_vocab_file=old_col_vocab_file, new_col_vocab_file=new_col_vocab_file, num_row_oov_buckets=num_row_oov_buckets, num_col_oov_buckets=num_col_oov_buckets, initializer=initializer, max_rows_in_memory=max_rows_in_memory) def _initializer(shape, dtype=dtypes.float32, partition_info=None): del partition_info # Unused by this override. return initializer_fn(shape, dtype, partition_info=primary_partition_info) return _initializer
[ "def", "load_variable_slot_initializer", "(", "ckpt_path", ",", "old_tensor_name", ",", "primary_partition_info", ",", "new_row_vocab_size", ",", "new_col_vocab_size", ",", "old_row_vocab_file", "=", "None", ",", "new_row_vocab_file", "=", "None", ",", "old_col_vocab_file", "=", "None", ",", "new_col_vocab_file", "=", "None", ",", "num_row_oov_buckets", "=", "0", ",", "num_col_oov_buckets", "=", "0", ",", "initializer", "=", "None", ",", "max_rows_in_memory", "=", "-", "1", ")", ":", "initializer_fn", "=", "load_and_remap_matrix_initializer", "(", "ckpt_path", "=", "ckpt_path", ",", "old_tensor_name", "=", "old_tensor_name", ",", "new_row_vocab_size", "=", "new_row_vocab_size", ",", "new_col_vocab_size", "=", "new_col_vocab_size", ",", "old_row_vocab_file", "=", "old_row_vocab_file", ",", "new_row_vocab_file", "=", "new_row_vocab_file", ",", "old_col_vocab_file", "=", "old_col_vocab_file", ",", "new_col_vocab_file", "=", "new_col_vocab_file", ",", "num_row_oov_buckets", "=", "num_row_oov_buckets", ",", "num_col_oov_buckets", "=", "num_col_oov_buckets", ",", "initializer", "=", "initializer", ",", "max_rows_in_memory", "=", "max_rows_in_memory", ")", "def", "_initializer", "(", "shape", ",", "dtype", "=", "dtypes", ".", "float32", ",", "partition_info", "=", "None", ")", ":", "del", "partition_info", "# Unused by this override.", "return", "initializer_fn", "(", "shape", ",", "dtype", ",", "partition_info", "=", "primary_partition_info", ")", "return", "_initializer" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/ops/checkpoint_ops.py#L89-L180
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/engines/utils.py
python
cast_friendly_names
(nodes)
Process nGraph nodes and sets POT-friendly tensor name based on friendly_name
Process nGraph nodes and sets POT-friendly tensor name based on friendly_name
[ "Process", "nGraph", "nodes", "and", "sets", "POT", "-", "friendly", "tensor", "name", "based", "on", "friendly_name" ]
def cast_friendly_names(nodes): """ Process nGraph nodes and sets POT-friendly tensor name based on friendly_name """ for ng_node in nodes: names = ng_node.get_tensor().get_names() names.add(ng_node.get_node().friendly_name) ng_node.get_tensor().set_names(names)
[ "def", "cast_friendly_names", "(", "nodes", ")", ":", "for", "ng_node", "in", "nodes", ":", "names", "=", "ng_node", ".", "get_tensor", "(", ")", ".", "get_names", "(", ")", "names", ".", "add", "(", "ng_node", ".", "get_node", "(", ")", ".", "friendly_name", ")", "ng_node", ".", "get_tensor", "(", ")", ".", "set_names", "(", "names", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/engines/utils.py#L160-L167
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_stc.py
python
EditraStc.GotoBraceMatch
(self)
Jump the caret to the brace opposite of the one the caret is currently at. If there is no match or the caret currently is not next to a brace no action is taken. @return: bool
Jump the caret to the brace opposite of the one the caret is currently at. If there is no match or the caret currently is not next to a brace no action is taken. @return: bool
[ "Jump", "the", "caret", "to", "the", "brace", "opposite", "of", "the", "one", "the", "caret", "is", "currently", "at", ".", "If", "there", "is", "no", "match", "or", "the", "caret", "currently", "is", "not", "next", "to", "a", "brace", "no", "action", "is", "taken", ".", "@return", ":", "bool" ]
def GotoBraceMatch(self): """Jump the caret to the brace opposite of the one the caret is currently at. If there is no match or the caret currently is not next to a brace no action is taken. @return: bool """ cbrace, brace_opposite = self.GetBracePair() if -1 in (cbrace, brace_opposite): return False else: self.GotoPos(brace_opposite) return True
[ "def", "GotoBraceMatch", "(", "self", ")", ":", "cbrace", ",", "brace_opposite", "=", "self", ".", "GetBracePair", "(", ")", "if", "-", "1", "in", "(", "cbrace", ",", "brace_opposite", ")", ":", "return", "False", "else", ":", "self", ".", "GotoPos", "(", "brace_opposite", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L506-L518
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/request.py
python
path_info_split
(path_info)
Splits off the first segment of the path. Returns (first_part, rest_of_path). first_part can be None (if PATH_INFO is empty), '' (if PATH_INFO is '/'), or a name without any /'s. rest_of_path can be '' or a string starting with /.
Splits off the first segment of the path. Returns (first_part, rest_of_path). first_part can be None (if PATH_INFO is empty), '' (if PATH_INFO is '/'), or a name without any /'s. rest_of_path can be '' or a string starting with /.
[ "Splits", "off", "the", "first", "segment", "of", "the", "path", ".", "Returns", "(", "first_part", "rest_of_path", ")", ".", "first_part", "can", "be", "None", "(", "if", "PATH_INFO", "is", "empty", ")", "(", "if", "PATH_INFO", "is", "/", ")", "or", "a", "name", "without", "any", "/", "s", ".", "rest_of_path", "can", "be", "or", "a", "string", "starting", "with", "/", "." ]
def path_info_split(path_info): """ Splits off the first segment of the path. Returns (first_part, rest_of_path). first_part can be None (if PATH_INFO is empty), '' (if PATH_INFO is '/'), or a name without any /'s. rest_of_path can be '' or a string starting with /. """ if not path_info: return None, '' assert path_info.startswith('/'), ( "PATH_INFO should start with /: %r" % path_info) path_info = path_info.lstrip('/') if '/' in path_info: first, rest = path_info.split('/', 1) return first, '/' + rest else: return path_info, ''
[ "def", "path_info_split", "(", "path_info", ")", ":", "if", "not", "path_info", ":", "return", "None", ",", "''", "assert", "path_info", ".", "startswith", "(", "'/'", ")", ",", "(", "\"PATH_INFO should start with /: %r\"", "%", "path_info", ")", "path_info", "=", "path_info", ".", "lstrip", "(", "'/'", ")", "if", "'/'", "in", "path_info", ":", "first", ",", "rest", "=", "path_info", ".", "split", "(", "'/'", ",", "1", ")", "return", "first", ",", "'/'", "+", "rest", "else", ":", "return", "path_info", ",", "''" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/request.py#L269-L286
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTypeSynthetic.IsValid
(self)
return _lldb.SBTypeSynthetic_IsValid(self)
IsValid(self) -> bool
IsValid(self) -> bool
[ "IsValid", "(", "self", ")", "-", ">", "bool" ]
def IsValid(self): """IsValid(self) -> bool""" return _lldb.SBTypeSynthetic_IsValid(self)
[ "def", "IsValid", "(", "self", ")", ":", "return", "_lldb", ".", "SBTypeSynthetic_IsValid", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11582-L11584
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/io/vcf.py
python
_create_get_fn_cache
(fields)
return { field.id: vcf_constants.create_get_fn(field.type, field.number) for field in fields }
Returns a dictionary from field to a callable that extracts its value.
Returns a dictionary from field to a callable that extracts its value.
[ "Returns", "a", "dictionary", "from", "field", "to", "a", "callable", "that", "extracts", "its", "value", "." ]
def _create_get_fn_cache(fields): """Returns a dictionary from field to a callable that extracts its value.""" return { field.id: vcf_constants.create_get_fn(field.type, field.number) for field in fields }
[ "def", "_create_get_fn_cache", "(", "fields", ")", ":", "return", "{", "field", ".", "id", ":", "vcf_constants", ".", "create_get_fn", "(", "field", ".", "type", ",", "field", ".", "number", ")", "for", "field", "in", "fields", "}" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/vcf.py#L74-L79
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/auto_parallel/process_mesh.py
python
ProcessMesh.ndim
(self)
return len(self._topology)
r""" Get the number of dimension of ProcessMesh.
r""" Get the number of dimension of ProcessMesh.
[ "r", "Get", "the", "number", "of", "dimension", "of", "ProcessMesh", "." ]
def ndim(self): r""" Get the number of dimension of ProcessMesh. """ return len(self._topology)
[ "def", "ndim", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_topology", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/auto_parallel/process_mesh.py#L121-L125
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/io/transforms.py
python
color
(brightness_radius=0.0, contrast_radius=0.0, saturation_radius=0.0)
return cntk_py.reader_color(brightness_radius, contrast_radius, saturation_radius)
Color transform that can be used to pass to `map_features` for data augmentation. Args: brightness_radius (float, default 0.0): Radius for brightness change. Must be set within [0.0, 1.0]. For example, assume brightness_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's value is added by `x*meanVal`, where meanVal is the mean of the image pixel intensity combining all color channels. contrast_radius (float, default 0.0): Radius for contrast change. Must be set within [0.0, 1.0]. For example, assume contrast_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's value is multiplied by `1+x`. saturation_radius (float, default 0.0): Radius for saturation change. Only for color images and must be set within [0.0, 1.0]. For example, assume saturation_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's saturation is multiplied by `1+x`. Returns: A dictionary-like object describing the mean transform
Color transform that can be used to pass to `map_features` for data augmentation.
[ "Color", "transform", "that", "can", "be", "used", "to", "pass", "to", "map_features", "for", "data", "augmentation", "." ]
def color(brightness_radius=0.0, contrast_radius=0.0, saturation_radius=0.0): ''' Color transform that can be used to pass to `map_features` for data augmentation. Args: brightness_radius (float, default 0.0): Radius for brightness change. Must be set within [0.0, 1.0]. For example, assume brightness_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's value is added by `x*meanVal`, where meanVal is the mean of the image pixel intensity combining all color channels. contrast_radius (float, default 0.0): Radius for contrast change. Must be set within [0.0, 1.0]. For example, assume contrast_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's value is multiplied by `1+x`. saturation_radius (float, default 0.0): Radius for saturation change. Only for color images and must be set within [0.0, 1.0]. For example, assume saturation_radius = 0.2, a random number `x` is uniformly drawn from [-0.2, 0.2], and every pixel's saturation is multiplied by `1+x`. Returns: A dictionary-like object describing the mean transform ''' return cntk_py.reader_color(brightness_radius, contrast_radius, saturation_radius)
[ "def", "color", "(", "brightness_radius", "=", "0.0", ",", "contrast_radius", "=", "0.0", ",", "saturation_radius", "=", "0.0", ")", ":", "return", "cntk_py", ".", "reader_color", "(", "brightness_radius", ",", "contrast_radius", ",", "saturation_radius", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/io/transforms.py#L112-L134
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
MDArray.GetStatistics
(self, *args, **kwargs)
return _gdal.MDArray_GetStatistics(self, *args, **kwargs)
r"""GetStatistics(MDArray self, bool approx_ok=FALSE, bool force=TRUE, GDALProgressFunc callback=0, void * callback_data=None) -> Statistics
r"""GetStatistics(MDArray self, bool approx_ok=FALSE, bool force=TRUE, GDALProgressFunc callback=0, void * callback_data=None) -> Statistics
[ "r", "GetStatistics", "(", "MDArray", "self", "bool", "approx_ok", "=", "FALSE", "bool", "force", "=", "TRUE", "GDALProgressFunc", "callback", "=", "0", "void", "*", "callback_data", "=", "None", ")", "-", ">", "Statistics" ]
def GetStatistics(self, *args, **kwargs): r"""GetStatistics(MDArray self, bool approx_ok=FALSE, bool force=TRUE, GDALProgressFunc callback=0, void * callback_data=None) -> Statistics""" return _gdal.MDArray_GetStatistics(self, *args, **kwargs)
[ "def", "GetStatistics", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdal", ".", "MDArray_GetStatistics", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2847-L2849
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/collection.py
python
ResourceCollection.page_size
(self, count)
return self._clone(page_size=count)
Fetch at most this many resources per service request. >>> for obj in s3.Bucket('boto3').objects.page_size(100): ... print(obj.key) :type count: int :param count: Fetch this many items per request :rtype: :py:class:`ResourceCollection`
Fetch at most this many resources per service request.
[ "Fetch", "at", "most", "this", "many", "resources", "per", "service", "request", "." ]
def page_size(self, count): """ Fetch at most this many resources per service request. >>> for obj in s3.Bucket('boto3').objects.page_size(100): ... print(obj.key) :type count: int :param count: Fetch this many items per request :rtype: :py:class:`ResourceCollection` """ return self._clone(page_size=count)
[ "def", "page_size", "(", "self", ",", "count", ")", ":", "return", "self", ".", "_clone", "(", "page_size", "=", "count", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/collection.py#L246-L257
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/collective/__init__.py
python
CollectiveOptimizer.minimize
(self, loss, startup_program=None, parameter_list=None, no_grad_set=None)
return optimize_ops, param_grads
minimize a program through loss Args: loss (Variable|Variable List): loss variable or loss variable list to run optimization. startup_program (Program): startup_program for initializing parameters in `parameter_list`. parameter_list (list): list of Variables to update. no_grad_set (set|None): set of Variables should be ignored. Returns: tuple: (optimize_ops, params_grads) which are, list of operators appended; and list of (param, grad) Variables pair for optimization. Note that in parameter server mode, a worker will not get anything about optimize_os Because optimizer algorithms run on pserver side. We will make this usable in pserver process, but currently the optimization part is written into Fleet(). A user does not need to care about how to startup a pserver node.
minimize a program through loss Args: loss (Variable|Variable List): loss variable or loss variable list to run optimization. startup_program (Program): startup_program for initializing parameters in `parameter_list`. parameter_list (list): list of Variables to update. no_grad_set (set|None): set of Variables should be ignored. Returns: tuple: (optimize_ops, params_grads) which are, list of operators appended; and list of (param, grad) Variables pair for optimization. Note that in parameter server mode, a worker will not get anything about optimize_os Because optimizer algorithms run on pserver side. We will make this usable in pserver process, but currently the optimization part is written into Fleet(). A user does not need to care about how to startup a pserver node.
[ "minimize", "a", "program", "through", "loss", "Args", ":", "loss", "(", "Variable|Variable", "List", ")", ":", "loss", "variable", "or", "loss", "variable", "list", "to", "run", "optimization", ".", "startup_program", "(", "Program", ")", ":", "startup_program", "for", "initializing", "parameters", "in", "parameter_list", ".", "parameter_list", "(", "list", ")", ":", "list", "of", "Variables", "to", "update", ".", "no_grad_set", "(", "set|None", ")", ":", "set", "of", "Variables", "should", "be", "ignored", ".", "Returns", ":", "tuple", ":", "(", "optimize_ops", "params_grads", ")", "which", "are", "list", "of", "operators", "appended", ";", "and", "list", "of", "(", "param", "grad", ")", "Variables", "pair", "for", "optimization", ".", "Note", "that", "in", "parameter", "server", "mode", "a", "worker", "will", "not", "get", "anything", "about", "optimize_os", "Because", "optimizer", "algorithms", "run", "on", "pserver", "side", ".", "We", "will", "make", "this", "usable", "in", "pserver", "process", "but", "currently", "the", "optimization", "part", "is", "written", "into", "Fleet", "()", ".", "A", "user", "does", "not", "need", "to", "care", "about", "how", "to", "startup", "a", "pserver", "node", "." ]
def minimize(self, loss, startup_program=None, parameter_list=None, no_grad_set=None): """ minimize a program through loss Args: loss (Variable|Variable List): loss variable or loss variable list to run optimization. startup_program (Program): startup_program for initializing parameters in `parameter_list`. parameter_list (list): list of Variables to update. no_grad_set (set|None): set of Variables should be ignored. Returns: tuple: (optimize_ops, params_grads) which are, list of operators appended; and list of (param, grad) Variables pair for optimization. Note that in parameter server mode, a worker will not get anything about optimize_os Because optimizer algorithms run on pserver side. We will make this usable in pserver process, but currently the optimization part is written into Fleet(). A user does not need to care about how to startup a pserver node. """ # check optimizer conflicts if self._forward_recompute: if self._recompute_checkpoints == []: raise ValueError("please set strategy.recompute_checkpoints" "when set strategy.forward_recompute as True") if self._optimizer.__class__.__name__ in [ "RecomputeOptimizer", "OptimizerWithMixedPrecision" ]: self.raiseOptimizeError("forward_recompute", self._optimizer.__class__.__name__) self._optimizer = \ fluid.optimizer.RecomputeOptimizer(self._optimizer) self._optimizer._set_checkpoints(self._recompute_checkpoints) if self._use_amp: if self._optimizer.__class__.__name__ in [ "OptimizerWithMixedPrecision", "DGCMomentumOptimizer" ]: self.raiseOptimizeError("mixed_precision", self._optimizer.__class__.__name__) self._optimizer = fluid.contrib.mixed_precision.decorate( self._optimizer, init_loss_scaling=self._amp_loss_scaling, use_dynamic_loss_scaling=True) main_program = loss.block.program if startup_program is None: startup_program = fluid.default_startup_program() fleet.startup_program = startup_program self._loss = loss self._check_collective_mode(main_program, self._optimizer, self._strategy) optimize_ops, param_grads = self._optimizer.minimize( loss, startup_program, parameter_list, no_grad_set=no_grad_set) fleet._origin_program = main_program.clone(for_test=False) fleet._transpiled_program = main_program fleet.main_program = self._try_to_compile(startup_program, main_program) return optimize_ops, param_grads
[ "def", "minimize", "(", "self", ",", "loss", ",", "startup_program", "=", "None", ",", "parameter_list", "=", "None", ",", "no_grad_set", "=", "None", ")", ":", "# check optimizer conflicts", "if", "self", ".", "_forward_recompute", ":", "if", "self", ".", "_recompute_checkpoints", "==", "[", "]", ":", "raise", "ValueError", "(", "\"please set strategy.recompute_checkpoints\"", "\"when set strategy.forward_recompute as True\"", ")", "if", "self", ".", "_optimizer", ".", "__class__", ".", "__name__", "in", "[", "\"RecomputeOptimizer\"", ",", "\"OptimizerWithMixedPrecision\"", "]", ":", "self", ".", "raiseOptimizeError", "(", "\"forward_recompute\"", ",", "self", ".", "_optimizer", ".", "__class__", ".", "__name__", ")", "self", ".", "_optimizer", "=", "fluid", ".", "optimizer", ".", "RecomputeOptimizer", "(", "self", ".", "_optimizer", ")", "self", ".", "_optimizer", ".", "_set_checkpoints", "(", "self", ".", "_recompute_checkpoints", ")", "if", "self", ".", "_use_amp", ":", "if", "self", ".", "_optimizer", ".", "__class__", ".", "__name__", "in", "[", "\"OptimizerWithMixedPrecision\"", ",", "\"DGCMomentumOptimizer\"", "]", ":", "self", ".", "raiseOptimizeError", "(", "\"mixed_precision\"", ",", "self", ".", "_optimizer", ".", "__class__", ".", "__name__", ")", "self", ".", "_optimizer", "=", "fluid", ".", "contrib", ".", "mixed_precision", ".", "decorate", "(", "self", ".", "_optimizer", ",", "init_loss_scaling", "=", "self", ".", "_amp_loss_scaling", ",", "use_dynamic_loss_scaling", "=", "True", ")", "main_program", "=", "loss", ".", "block", ".", "program", "if", "startup_program", "is", "None", ":", "startup_program", "=", "fluid", ".", "default_startup_program", "(", ")", "fleet", ".", "startup_program", "=", "startup_program", "self", ".", "_loss", "=", "loss", "self", ".", "_check_collective_mode", "(", "main_program", ",", "self", ".", "_optimizer", ",", "self", ".", "_strategy", ")", "optimize_ops", ",", "param_grads", "=", "self", ".", "_optimizer", ".", "minimize", "(", "loss", ",", "startup_program", ",", "parameter_list", ",", "no_grad_set", "=", "no_grad_set", ")", "fleet", ".", "_origin_program", "=", "main_program", ".", "clone", "(", "for_test", "=", "False", ")", "fleet", ".", "_transpiled_program", "=", "main_program", "fleet", ".", "main_program", "=", "self", ".", "_try_to_compile", "(", "startup_program", ",", "main_program", ")", "return", "optimize_ops", ",", "param_grads" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/collective/__init__.py#L451-L516
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/snap_rounding.py
python
snap_rounding
(points, segments, pixel_size, use_iterative=True)
return vertices, edges
2D snap rounding. Args: points (``numpy.ndarray``): Input points. segments (``numpy.ndarray``): Input segments. pixel_size (``float``): Pixel size. use_iterative (``bool``): Whether to use iterative snap rounding. Returns: 2 values are returned. * ``vertices``: Snap rounded vertices. * ``edges``: Edge connecting vertices.
2D snap rounding.
[ "2D", "snap", "rounding", "." ]
def snap_rounding(points, segments, pixel_size, use_iterative=True): """ 2D snap rounding. Args: points (``numpy.ndarray``): Input points. segments (``numpy.ndarray``): Input segments. pixel_size (``float``): Pixel size. use_iterative (``bool``): Whether to use iterative snap rounding. Returns: 2 values are returned. * ``vertices``: Snap rounded vertices. * ``edges``: Edge connecting vertices. """ engine = PyMesh.SnapRounding2() engine.points = points engine.segments = segments engine.run(pixel_size, use_iterative) vertices = engine.vertices edges = engine.edges vertices, edges, __ = remove_duplicated_vertices_raw( vertices, edges, tol=pixel_size/2) return vertices, edges
[ "def", "snap_rounding", "(", "points", ",", "segments", ",", "pixel_size", ",", "use_iterative", "=", "True", ")", ":", "engine", "=", "PyMesh", ".", "SnapRounding2", "(", ")", "engine", ".", "points", "=", "points", "engine", ".", "segments", "=", "segments", "engine", ".", "run", "(", "pixel_size", ",", "use_iterative", ")", "vertices", "=", "engine", ".", "vertices", "edges", "=", "engine", ".", "edges", "vertices", ",", "edges", ",", "__", "=", "remove_duplicated_vertices_raw", "(", "vertices", ",", "edges", ",", "tol", "=", "pixel_size", "/", "2", ")", "return", "vertices", ",", "edges" ]
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/snap_rounding.py#L6-L31
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pdb.py
python
Pdb.lookupmodule
(self, filename)
return None
Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name.
Helper function for break/clear parsing -- may be overridden.
[ "Helper", "function", "for", "break", "/", "clear", "parsing", "--", "may", "be", "overridden", "." ]
def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
[ "def", "lookupmodule", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "filename", ")", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "filename", "f", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "path", "[", "0", "]", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "f", ")", "and", "self", ".", "canonic", "(", "f", ")", "==", "self", ".", "mainpyfile", ":", "return", "f", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "==", "''", ":", "filename", "=", "filename", "+", "'.py'", "if", "os", ".", "path", ".", "isabs", "(", "filename", ")", ":", "return", "filename", "for", "dirname", "in", "sys", ".", "path", ":", "while", "os", ".", "path", ".", "islink", "(", "dirname", ")", ":", "dirname", "=", "os", ".", "readlink", "(", "dirname", ")", "fullname", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "return", "fullname", "return", "None" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pdb.py#L1187-L1209
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py
python
Base._eq
(self, other)
Compare two nodes for equality. This is called by __eq__ and __ne__. It is only called if the two nodes have the same type. This must be implemented by the concrete subclass. Nodes should be considered equal if they have the same structure, ignoring the prefix string and other context information.
Compare two nodes for equality.
[ "Compare", "two", "nodes", "for", "equality", "." ]
def _eq(self, other): """ Compare two nodes for equality. This is called by __eq__ and __ne__. It is only called if the two nodes have the same type. This must be implemented by the concrete subclass. Nodes should be considered equal if they have the same structure, ignoring the prefix string and other context information. """ raise NotImplementedError
[ "def", "_eq", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py#L77-L86
uzh-rpg/rpg_svo
d6161063b47f36ce78252ee4c4fedf3f6d8f2898
svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_rpe.py
python
percentile
(seq,q)
return seq_sorted[int((len(seq_sorted)-1)*q)]
Return the q-percentile of a list
Return the q-percentile of a list
[ "Return", "the", "q", "-", "percentile", "of", "a", "list" ]
def percentile(seq,q): """ Return the q-percentile of a list """ seq_sorted = list(seq) seq_sorted.sort() return seq_sorted[int((len(seq_sorted)-1)*q)]
[ "def", "percentile", "(", "seq", ",", "q", ")", ":", "seq_sorted", "=", "list", "(", "seq", ")", "seq_sorted", ".", "sort", "(", ")", "return", "seq_sorted", "[", "int", "(", "(", "len", "(", "seq_sorted", ")", "-", "1", ")", "*", "q", ")", "]" ]
https://github.com/uzh-rpg/rpg_svo/blob/d6161063b47f36ce78252ee4c4fedf3f6d8f2898/svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_rpe.py#L299-L305
cluebotng/cluebotng
2ed38a518c1019f6b7b03e33b487f96f8df617b0
fabfile.py
python
_stop
()
Internal function, calls jstop on the grid jobs
Internal function, calls jstop on the grid jobs
[ "Internal", "function", "calls", "jstop", "on", "the", "grid", "jobs" ]
def _stop(): ''' Internal function, calls jstop on the grid jobs ''' sudo('jstop cbng_bot | true') sudo('jstop cbng_core | true')
[ "def", "_stop", "(", ")", ":", "sudo", "(", "'jstop cbng_bot | true'", ")", "sudo", "(", "'jstop cbng_core | true'", ")" ]
https://github.com/cluebotng/cluebotng/blob/2ed38a518c1019f6b7b03e33b487f96f8df617b0/fabfile.py#L109-L114
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/functional.py
python
_map_graph_network
(inputs, outputs)
return network_nodes, nodes_by_depth, layers, layers_by_depth
Validates a network's topology and gather its layers and nodes. Args: inputs: List of input tensors. outputs: List of outputs tensors. Returns: A tuple `(nodes, nodes_by_depth, layers, layers_by_depth)`. - nodes: list of Node instances. - nodes_by_depth: dict mapping ints (depth) to lists of node instances. - layers: list of Layer instances. - layers_by_depth: dict mapping ints (depth) to lists of layer instances. Raises: ValueError: In case the network is not valid (e.g. disconnected graph).
Validates a network's topology and gather its layers and nodes.
[ "Validates", "a", "network", "s", "topology", "and", "gather", "its", "layers", "and", "nodes", "." ]
def _map_graph_network(inputs, outputs): """Validates a network's topology and gather its layers and nodes. Args: inputs: List of input tensors. outputs: List of outputs tensors. Returns: A tuple `(nodes, nodes_by_depth, layers, layers_by_depth)`. - nodes: list of Node instances. - nodes_by_depth: dict mapping ints (depth) to lists of node instances. - layers: list of Layer instances. - layers_by_depth: dict mapping ints (depth) to lists of layer instances. Raises: ValueError: In case the network is not valid (e.g. disconnected graph). """ # "depth" is number of layers between output Node and the Node. # Nodes are ordered from inputs -> outputs. nodes_in_decreasing_depth, layer_indices = _build_map(outputs) network_nodes = { _make_node_key(node.layer.name, node.layer._inbound_nodes.index(node)) for node in nodes_in_decreasing_depth } nodes_depths = {} # dict {node: depth value} layers_depths = {} # dict {layer: depth value} for node in reversed(nodes_in_decreasing_depth): # If the depth is not set, the node has no outbound nodes (depth 0). depth = nodes_depths.setdefault(node, 0) # Update the depth of the corresponding layer previous_depth = layers_depths.get(node.layer, 0) # If we've seen this layer before at a higher depth, # we should use that depth instead of the node depth. # This is necessary for shared layers that have inputs at different # depth levels in the graph. depth = max(depth, previous_depth) layers_depths[node.layer] = depth nodes_depths[node] = depth # Update the depth of inbound nodes. # The "depth" of a node is the max of the depths # of all nodes it is connected to + 1. for node_dep in node.parent_nodes: previous_depth = nodes_depths.get(node_dep, 0) nodes_depths[node_dep] = max(depth + 1, previous_depth) # Handle inputs that are not connected to outputs. # We do not error out here because the inputs may be used to compute losses # and metrics. for input_t in inputs: input_layer = input_t._keras_history[0] if input_layer not in layers_depths: layers_depths[input_layer] = 0 layer_indices[input_layer] = -1 nodes_depths[input_layer._inbound_nodes[0]] = 0 network_nodes.add(_make_node_key(input_layer.name, 0)) # Build a dict {depth: list of nodes with this depth} nodes_by_depth = collections.defaultdict(list) for node, depth in nodes_depths.items(): nodes_by_depth[depth].append(node) # Build a dict {depth: list of layers with this depth} layers_by_depth = collections.defaultdict(list) for layer, depth in layers_depths.items(): layers_by_depth[depth].append(layer) # Get sorted list of layer depths. depth_keys = list(layers_by_depth.keys()) depth_keys.sort(reverse=True) # Set self.layers ordered by depth. layers = [] for depth in depth_keys: layers_for_depth = layers_by_depth[depth] # Network.layers needs to have a deterministic order: # here we order them by traversal order. layers_for_depth.sort(key=lambda x: layer_indices[x]) layers.extend(layers_for_depth) # Get sorted list of node depths. depth_keys = list(nodes_by_depth.keys()) depth_keys.sort(reverse=True) # Check that all tensors required are computable. # computable_tensors: all tensors in the graph # that can be computed from the inputs provided. computable_tensors = set() for x in inputs: computable_tensors.add(id(x)) layers_with_complete_input = [] # To provide a better error msg. for depth in depth_keys: for node in nodes_by_depth[depth]: layer = node.layer if layer and not node.is_input: for x in nest.flatten(node.keras_inputs): if id(x) not in computable_tensors: raise ValueError('Graph disconnected: ' 'cannot obtain value for tensor ' + str(x) + ' at layer "' + layer.name + '". ' 'The following previous layers ' 'were accessed without issue: ' + str(layers_with_complete_input)) for x in nest.flatten(node.outputs): computable_tensors.add(id(x)) layers_with_complete_input.append(layer.name) # Ensure name unicity, which will be crucial for serialization # (since serialized nodes refer to layers by their name). all_names = [layer.name for layer in layers] for name in all_names: if all_names.count(name) != 1: raise ValueError('The name "' + name + '" is used ' + str(all_names.count(name)) + ' times in the model. ' 'All layer names should be unique.') return network_nodes, nodes_by_depth, layers, layers_by_depth
[ "def", "_map_graph_network", "(", "inputs", ",", "outputs", ")", ":", "# \"depth\" is number of layers between output Node and the Node.", "# Nodes are ordered from inputs -> outputs.", "nodes_in_decreasing_depth", ",", "layer_indices", "=", "_build_map", "(", "outputs", ")", "network_nodes", "=", "{", "_make_node_key", "(", "node", ".", "layer", ".", "name", ",", "node", ".", "layer", ".", "_inbound_nodes", ".", "index", "(", "node", ")", ")", "for", "node", "in", "nodes_in_decreasing_depth", "}", "nodes_depths", "=", "{", "}", "# dict {node: depth value}", "layers_depths", "=", "{", "}", "# dict {layer: depth value}", "for", "node", "in", "reversed", "(", "nodes_in_decreasing_depth", ")", ":", "# If the depth is not set, the node has no outbound nodes (depth 0).", "depth", "=", "nodes_depths", ".", "setdefault", "(", "node", ",", "0", ")", "# Update the depth of the corresponding layer", "previous_depth", "=", "layers_depths", ".", "get", "(", "node", ".", "layer", ",", "0", ")", "# If we've seen this layer before at a higher depth,", "# we should use that depth instead of the node depth.", "# This is necessary for shared layers that have inputs at different", "# depth levels in the graph.", "depth", "=", "max", "(", "depth", ",", "previous_depth", ")", "layers_depths", "[", "node", ".", "layer", "]", "=", "depth", "nodes_depths", "[", "node", "]", "=", "depth", "# Update the depth of inbound nodes.", "# The \"depth\" of a node is the max of the depths", "# of all nodes it is connected to + 1.", "for", "node_dep", "in", "node", ".", "parent_nodes", ":", "previous_depth", "=", "nodes_depths", ".", "get", "(", "node_dep", ",", "0", ")", "nodes_depths", "[", "node_dep", "]", "=", "max", "(", "depth", "+", "1", ",", "previous_depth", ")", "# Handle inputs that are not connected to outputs.", "# We do not error out here because the inputs may be used to compute losses", "# and metrics.", "for", "input_t", "in", "inputs", ":", "input_layer", "=", "input_t", ".", "_keras_history", "[", "0", "]", "if", "input_layer", "not", "in", "layers_depths", ":", "layers_depths", "[", "input_layer", "]", "=", "0", "layer_indices", "[", "input_layer", "]", "=", "-", "1", "nodes_depths", "[", "input_layer", ".", "_inbound_nodes", "[", "0", "]", "]", "=", "0", "network_nodes", ".", "add", "(", "_make_node_key", "(", "input_layer", ".", "name", ",", "0", ")", ")", "# Build a dict {depth: list of nodes with this depth}", "nodes_by_depth", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "node", ",", "depth", "in", "nodes_depths", ".", "items", "(", ")", ":", "nodes_by_depth", "[", "depth", "]", ".", "append", "(", "node", ")", "# Build a dict {depth: list of layers with this depth}", "layers_by_depth", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "layer", ",", "depth", "in", "layers_depths", ".", "items", "(", ")", ":", "layers_by_depth", "[", "depth", "]", ".", "append", "(", "layer", ")", "# Get sorted list of layer depths.", "depth_keys", "=", "list", "(", "layers_by_depth", ".", "keys", "(", ")", ")", "depth_keys", ".", "sort", "(", "reverse", "=", "True", ")", "# Set self.layers ordered by depth.", "layers", "=", "[", "]", "for", "depth", "in", "depth_keys", ":", "layers_for_depth", "=", "layers_by_depth", "[", "depth", "]", "# Network.layers needs to have a deterministic order:", "# here we order them by traversal order.", "layers_for_depth", ".", "sort", "(", "key", "=", "lambda", "x", ":", "layer_indices", "[", "x", "]", ")", "layers", ".", "extend", "(", "layers_for_depth", ")", "# Get sorted list of node depths.", "depth_keys", "=", "list", "(", "nodes_by_depth", ".", "keys", "(", ")", ")", "depth_keys", ".", "sort", "(", "reverse", "=", "True", ")", "# Check that all tensors required are computable.", "# computable_tensors: all tensors in the graph", "# that can be computed from the inputs provided.", "computable_tensors", "=", "set", "(", ")", "for", "x", "in", "inputs", ":", "computable_tensors", ".", "add", "(", "id", "(", "x", ")", ")", "layers_with_complete_input", "=", "[", "]", "# To provide a better error msg.", "for", "depth", "in", "depth_keys", ":", "for", "node", "in", "nodes_by_depth", "[", "depth", "]", ":", "layer", "=", "node", ".", "layer", "if", "layer", "and", "not", "node", ".", "is_input", ":", "for", "x", "in", "nest", ".", "flatten", "(", "node", ".", "keras_inputs", ")", ":", "if", "id", "(", "x", ")", "not", "in", "computable_tensors", ":", "raise", "ValueError", "(", "'Graph disconnected: '", "'cannot obtain value for tensor '", "+", "str", "(", "x", ")", "+", "' at layer \"'", "+", "layer", ".", "name", "+", "'\". '", "'The following previous layers '", "'were accessed without issue: '", "+", "str", "(", "layers_with_complete_input", ")", ")", "for", "x", "in", "nest", ".", "flatten", "(", "node", ".", "outputs", ")", ":", "computable_tensors", ".", "add", "(", "id", "(", "x", ")", ")", "layers_with_complete_input", ".", "append", "(", "layer", ".", "name", ")", "# Ensure name unicity, which will be crucial for serialization", "# (since serialized nodes refer to layers by their name).", "all_names", "=", "[", "layer", ".", "name", "for", "layer", "in", "layers", "]", "for", "name", "in", "all_names", ":", "if", "all_names", ".", "count", "(", "name", ")", "!=", "1", ":", "raise", "ValueError", "(", "'The name \"'", "+", "name", "+", "'\" is used '", "+", "str", "(", "all_names", ".", "count", "(", "name", ")", ")", "+", "' times in the model. '", "'All layer names should be unique.'", ")", "return", "network_nodes", ",", "nodes_by_depth", ",", "layers", ",", "layers_by_depth" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/functional.py#L883-L1002
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py
python
Distribution.get_command_class
(self, command)
Return the class that implements the Distutils command named by 'command'. First we check the 'cmdclass' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in 'cmdclass' to speed future calls to 'get_command_class()'. Raises DistutilsModuleError if the expected module could not be found, or if that module does not define the expected class.
Return the class that implements the Distutils command named by 'command'. First we check the 'cmdclass' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in 'cmdclass' to speed future calls to 'get_command_class()'.
[ "Return", "the", "class", "that", "implements", "the", "Distutils", "command", "named", "by", "command", ".", "First", "we", "check", "the", "cmdclass", "dictionary", ";", "if", "the", "command", "is", "mentioned", "there", "we", "fetch", "the", "class", "object", "from", "the", "dictionary", "and", "return", "it", ".", "Otherwise", "we", "load", "the", "command", "module", "(", "distutils", ".", "command", ".", "+", "command", ")", "and", "fetch", "the", "command", "class", "from", "the", "module", ".", "The", "loaded", "class", "is", "also", "stored", "in", "cmdclass", "to", "speed", "future", "calls", "to", "get_command_class", "()", "." ]
def get_command_class(self, command): """Return the class that implements the Distutils command named by 'command'. First we check the 'cmdclass' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in 'cmdclass' to speed future calls to 'get_command_class()'. Raises DistutilsModuleError if the expected module could not be found, or if that module does not define the expected class. """ klass = self.cmdclass.get(command) if klass: return klass for pkgname in self.get_command_packages(): module_name = "%s.%s" % (pkgname, command) klass_name = command try: __import__ (module_name) module = sys.modules[module_name] except ImportError: continue try: klass = getattr(module, klass_name) except AttributeError: raise DistutilsModuleError, \ "invalid command '%s' (no class '%s' in module '%s')" \ % (command, klass_name, module_name) self.cmdclass[command] = klass return klass raise DistutilsModuleError("invalid command '%s'" % command)
[ "def", "get_command_class", "(", "self", ",", "command", ")", ":", "klass", "=", "self", ".", "cmdclass", ".", "get", "(", "command", ")", "if", "klass", ":", "return", "klass", "for", "pkgname", "in", "self", ".", "get_command_packages", "(", ")", ":", "module_name", "=", "\"%s.%s\"", "%", "(", "pkgname", ",", "command", ")", "klass_name", "=", "command", "try", ":", "__import__", "(", "module_name", ")", "module", "=", "sys", ".", "modules", "[", "module_name", "]", "except", "ImportError", ":", "continue", "try", ":", "klass", "=", "getattr", "(", "module", ",", "klass_name", ")", "except", "AttributeError", ":", "raise", "DistutilsModuleError", ",", "\"invalid command '%s' (no class '%s' in module '%s')\"", "%", "(", "command", ",", "klass_name", ",", "module_name", ")", "self", ".", "cmdclass", "[", "command", "]", "=", "klass", "return", "klass", "raise", "DistutilsModuleError", "(", "\"invalid command '%s'\"", "%", "command", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py#L794-L830
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/combo.py
python
ComboCtrl.GetBitmapNormal
(*args, **kwargs)
return _combo.ComboCtrl_GetBitmapNormal(*args, **kwargs)
GetBitmapNormal(self) -> Bitmap
GetBitmapNormal(self) -> Bitmap
[ "GetBitmapNormal", "(", "self", ")", "-", ">", "Bitmap" ]
def GetBitmapNormal(*args, **kwargs): """GetBitmapNormal(self) -> Bitmap""" return _combo.ComboCtrl_GetBitmapNormal(*args, **kwargs)
[ "def", "GetBitmapNormal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_GetBitmapNormal", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/combo.py#L446-L448
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/datasets/pascal_voc.py
python
pascal_voc.image_path_from_index
(self, index)
return image_path
Construct an image path from the image's "index" identifier.
Construct an image path from the image's "index" identifier.
[ "Construct", "an", "image", "path", "from", "the", "image", "s", "index", "identifier", "." ]
def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._data_path, 'JPEGImages', index + self._image_ext) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path
[ "def", "image_path_from_index", "(", "self", ",", "index", ")", ":", "image_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "'JPEGImages'", ",", "index", "+", "self", ".", "_image_ext", ")", "assert", "os", ".", "path", ".", "exists", "(", "image_path", ")", ",", "'Path does not exist: {}'", ".", "format", "(", "image_path", ")", "return", "image_path" ]
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/datasets/pascal_voc.py#L63-L71
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FloatParser.Convert
(self, argument)
return float(argument)
Converts argument to a float; raises ValueError on errors.
Converts argument to a float; raises ValueError on errors.
[ "Converts", "argument", "to", "a", "float", ";", "raises", "ValueError", "on", "errors", "." ]
def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument)
[ "def", "Convert", "(", "self", ",", "argument", ")", ":", "return", "float", "(", "argument", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L2499-L2501
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
TerrainModel.getName
(self)
return _robotsim.TerrainModel_getName(self)
getName(TerrainModel self) -> char const *
getName(TerrainModel self) -> char const *
[ "getName", "(", "TerrainModel", "self", ")", "-", ">", "char", "const", "*" ]
def getName(self): """ getName(TerrainModel self) -> char const * """ return _robotsim.TerrainModel_getName(self)
[ "def", "getName", "(", "self", ")", ":", "return", "_robotsim", ".", "TerrainModel_getName", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L5618-L5625
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Image.IsTransparent
(*args, **kwargs)
return _core_.Image_IsTransparent(*args, **kwargs)
IsTransparent(self, int x, int y, byte threshold=IMAGE_ALPHA_THRESHOLD) -> bool Returns ``True`` if this pixel is masked or has an alpha value less than the spcified threshold.
IsTransparent(self, int x, int y, byte threshold=IMAGE_ALPHA_THRESHOLD) -> bool
[ "IsTransparent", "(", "self", "int", "x", "int", "y", "byte", "threshold", "=", "IMAGE_ALPHA_THRESHOLD", ")", "-", ">", "bool" ]
def IsTransparent(*args, **kwargs): """ IsTransparent(self, int x, int y, byte threshold=IMAGE_ALPHA_THRESHOLD) -> bool Returns ``True`` if this pixel is masked or has an alpha value less than the spcified threshold. """ return _core_.Image_IsTransparent(*args, **kwargs)
[ "def", "IsTransparent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_IsTransparent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L3091-L3098
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py
python
_AddSlots
(message_descriptor, dictionary)
Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type. Args: message_descriptor: A Descriptor instance describing this message type. dictionary: Class dictionary to which we'll add a '__slots__' entry.
Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type.
[ "Adds", "a", "__slots__", "entry", "to", "dictionary", "containing", "the", "names", "of", "all", "valid", "attributes", "for", "this", "message", "type", "." ]
def _AddSlots(message_descriptor, dictionary): """Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type. Args: message_descriptor: A Descriptor instance describing this message type. dictionary: Class dictionary to which we'll add a '__slots__' entry. """ dictionary['__slots__'] = ['_cached_byte_size', '_cached_byte_size_dirty', '_fields', '_is_present_in_parent', '_listener', '_listener_for_children', '__weakref__']
[ "def", "_AddSlots", "(", "message_descriptor", ",", "dictionary", ")", ":", "dictionary", "[", "'__slots__'", "]", "=", "[", "'_cached_byte_size'", ",", "'_cached_byte_size_dirty'", ",", "'_fields'", ",", "'_is_present_in_parent'", ",", "'_listener'", ",", "'_listener_for_children'", ",", "'__weakref__'", "]" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L156-L170
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/sequence_lod.py
python
sequence_expand
(x, y, ref_level=-1, name=None)
return tmp
r""" :api_attr: Static Graph Sequence Expand Layer. This layer will expand the input variable ``x`` \ according to specified level ``ref_level`` lod of ``y``. Please note that \ the lod level of ``x`` is at most 1. If the lod level of ``x`` is 1, than \ the size of lod of ``x`` must be equal to the length of ``ref_level`` lod \ of ``y``. If the lod level of ``x`` is 0, then the first dim of ``x`` should \ be equal to the size of ``ref_level`` of ``y``. The rank of **x** is at least 2. \ When rank of ``x`` is greater than 2, then it would be viewed as a 2-D tensor. Please note that the input ``x`` should be LodTensor or Tensor, \ and input ``y`` must be LodTensor. Following examples will explain how sequence_expand works: .. code-block:: text Case 1 Consider 2 sequences [a][b] and [c][d], now we want to expand them to [a][b], [a][b], [c][d] and [c][d]. Sequence [a][b] expand twice and [c][d] expands twice, so the lod which according to is [2, 2]. Input x is a 1-level LoDTensor: x.lod = [[2, 2]] #lod based on length may be easier to understand x.data = [[a], [b], [c], [d]] x.dims = [4, 1] input y is a LoDTensor: y.lod = [[2, 2], #the 0th level lod, according to this level [3, 3, 1, 1]] #the 1st level lod, it has nothing to do with this level ref_level: 0 then output is a 1-level LoDTensor out: out.lod = [[2, 2, 2, 2]] #lod based on offset out.data = [[a], [b], [a], [b], [c], [d], [c], [d]] out.dims = [8, 1] Case 2 Consider 3 sequences [a], [b], [c], now we want to expand them to [a][a], [c][c][c]. It's obvious that the lod info of expanded sequences is [2, 0, 3]. x is a Tensor: x.data = [[a], [b], [c]] x.dims = [3, 1] y is a LoDTensor: y.lod = [[2, 0, 3]] ref_level: -1 then output is a 1-level LodTensor: out.data = [[a], [a], [c], [c], [c]] out.dims = [5, 1] Args: x (Variable): The input variable which is a Tensor or LoDTensor, with the \ dims ``[M, K]``. The lod level is at most 1. The data type should be \ float32, float64, int32 or int64. y (Variable): The input variable which is a LoDTensor, the lod level is \ at least 1. ref_level (int): Lod level of ``y`` to be referred by ``x``. If set to -1, \ refer the last level of lod. name(str, optional): For detailed information, please refer \ to :ref:`api_guide_Name`. Usually name is no need to set and \ None by default. Returns: The expanded variable which is a LoDTensor, with dims ``[N, K]``. \ ``N`` depends on the lod info of ``x`` and ``y``. \ The data type is same as input. Return Type: Variable Examples: .. code-block:: python import paddle from paddle import fluid paddle.enable_static() import numpy as np x = paddle.static.data(name='x', shape=[4, 1], dtype='float32') y = paddle.static.data(name='y', shape=[8, 1], dtype='float32', lod_level=1) out = paddle.static.nn.sequence_expand(x=x, y=y, ref_level=0) exe = paddle.static.Executor(fluid.CPUPlace()) place = paddle.CPUPlace() np_data = np.array([[1], [2], [3], [4]]).astype('float32') x_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2]], place) print(x_lod_tensor) #lod: [[0, 2, 4]] # dim: 4, 1 # layout: NCHW # dtype: float # data: [1 2 3 4] np_data = np.array([[1], [2], [3], [4], [5], [6], [7], [8]]).astype('float32') y_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2], [3,3,1,1]], place) print(y_lod_tensor) #lod: [[0, 2, 4][0, 3, 6, 7, 8]] # dim: 8, 1 # layout: NCHW # dtype: int64_t # data: [0 0 1 1 1 1 1 0] out_main = exe.run(fluid.default_main_program(), feed={'x': x_lod_tensor, 'y': y_lod_tensor}, fetch_list=[out], return_numpy=False) print(out_main[0]) #lod: [[0, 2, 4, 6, 8]] # dim: 8, 1 # layout: NCHW # dtype: float # data: [1 2 1 2 3 4 3 4]
r""" :api_attr: Static Graph
[ "r", ":", "api_attr", ":", "Static", "Graph" ]
def sequence_expand(x, y, ref_level=-1, name=None): r""" :api_attr: Static Graph Sequence Expand Layer. This layer will expand the input variable ``x`` \ according to specified level ``ref_level`` lod of ``y``. Please note that \ the lod level of ``x`` is at most 1. If the lod level of ``x`` is 1, than \ the size of lod of ``x`` must be equal to the length of ``ref_level`` lod \ of ``y``. If the lod level of ``x`` is 0, then the first dim of ``x`` should \ be equal to the size of ``ref_level`` of ``y``. The rank of **x** is at least 2. \ When rank of ``x`` is greater than 2, then it would be viewed as a 2-D tensor. Please note that the input ``x`` should be LodTensor or Tensor, \ and input ``y`` must be LodTensor. Following examples will explain how sequence_expand works: .. code-block:: text Case 1 Consider 2 sequences [a][b] and [c][d], now we want to expand them to [a][b], [a][b], [c][d] and [c][d]. Sequence [a][b] expand twice and [c][d] expands twice, so the lod which according to is [2, 2]. Input x is a 1-level LoDTensor: x.lod = [[2, 2]] #lod based on length may be easier to understand x.data = [[a], [b], [c], [d]] x.dims = [4, 1] input y is a LoDTensor: y.lod = [[2, 2], #the 0th level lod, according to this level [3, 3, 1, 1]] #the 1st level lod, it has nothing to do with this level ref_level: 0 then output is a 1-level LoDTensor out: out.lod = [[2, 2, 2, 2]] #lod based on offset out.data = [[a], [b], [a], [b], [c], [d], [c], [d]] out.dims = [8, 1] Case 2 Consider 3 sequences [a], [b], [c], now we want to expand them to [a][a], [c][c][c]. It's obvious that the lod info of expanded sequences is [2, 0, 3]. x is a Tensor: x.data = [[a], [b], [c]] x.dims = [3, 1] y is a LoDTensor: y.lod = [[2, 0, 3]] ref_level: -1 then output is a 1-level LodTensor: out.data = [[a], [a], [c], [c], [c]] out.dims = [5, 1] Args: x (Variable): The input variable which is a Tensor or LoDTensor, with the \ dims ``[M, K]``. The lod level is at most 1. The data type should be \ float32, float64, int32 or int64. y (Variable): The input variable which is a LoDTensor, the lod level is \ at least 1. ref_level (int): Lod level of ``y`` to be referred by ``x``. If set to -1, \ refer the last level of lod. name(str, optional): For detailed information, please refer \ to :ref:`api_guide_Name`. Usually name is no need to set and \ None by default. Returns: The expanded variable which is a LoDTensor, with dims ``[N, K]``. \ ``N`` depends on the lod info of ``x`` and ``y``. \ The data type is same as input. Return Type: Variable Examples: .. code-block:: python import paddle from paddle import fluid paddle.enable_static() import numpy as np x = paddle.static.data(name='x', shape=[4, 1], dtype='float32') y = paddle.static.data(name='y', shape=[8, 1], dtype='float32', lod_level=1) out = paddle.static.nn.sequence_expand(x=x, y=y, ref_level=0) exe = paddle.static.Executor(fluid.CPUPlace()) place = paddle.CPUPlace() np_data = np.array([[1], [2], [3], [4]]).astype('float32') x_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2]], place) print(x_lod_tensor) #lod: [[0, 2, 4]] # dim: 4, 1 # layout: NCHW # dtype: float # data: [1 2 3 4] np_data = np.array([[1], [2], [3], [4], [5], [6], [7], [8]]).astype('float32') y_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2], [3,3,1,1]], place) print(y_lod_tensor) #lod: [[0, 2, 4][0, 3, 6, 7, 8]] # dim: 8, 1 # layout: NCHW # dtype: int64_t # data: [0 0 1 1 1 1 1 0] out_main = exe.run(fluid.default_main_program(), feed={'x': x_lod_tensor, 'y': y_lod_tensor}, fetch_list=[out], return_numpy=False) print(out_main[0]) #lod: [[0, 2, 4, 6, 8]] # dim: 8, 1 # layout: NCHW # dtype: float # data: [1 2 1 2 3 4 3 4] """ assert not in_dygraph_mode(), ( "sequence layer is not supported in dygraph mode yet.") check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'sequence_expand') helper = LayerHelper('sequence_expand', **locals()) dtype = helper.input_dtype(input_param_name='x') tmp = helper.create_variable_for_type_inference(dtype) helper.append_op( type='sequence_expand', inputs={'X': x, 'Y': y}, outputs={'Out': tmp}, attrs={'ref_level': ref_level}) return tmp
[ "def", "sequence_expand", "(", "x", ",", "y", ",", "ref_level", "=", "-", "1", ",", "name", "=", "None", ")", ":", "assert", "not", "in_dygraph_mode", "(", ")", ",", "(", "\"sequence layer is not supported in dygraph mode yet.\"", ")", "check_variable_and_dtype", "(", "x", ",", "'x'", ",", "[", "'float32'", ",", "'float64'", ",", "'int32'", ",", "'int64'", "]", ",", "'sequence_expand'", ")", "helper", "=", "LayerHelper", "(", "'sequence_expand'", ",", "*", "*", "locals", "(", ")", ")", "dtype", "=", "helper", ".", "input_dtype", "(", "input_param_name", "=", "'x'", ")", "tmp", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", ")", "helper", ".", "append_op", "(", "type", "=", "'sequence_expand'", ",", "inputs", "=", "{", "'X'", ":", "x", ",", "'Y'", ":", "y", "}", ",", "outputs", "=", "{", "'Out'", ":", "tmp", "}", ",", "attrs", "=", "{", "'ref_level'", ":", "ref_level", "}", ")", "return", "tmp" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/sequence_lod.py#L650-L784
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/resources/find_unused_resources.py
python
FindFilesWithContents
(string_a, string_b)
return files_list
Returns list of paths of files that contain |string_a| or |string_b|. Uses --name-only to print the file paths. The default behavior of git grep is to OR together multiple patterns. Args: string_a: A string to search for (not a regular expression). string_b: As above. Returns: A list of file paths as strings.
Returns list of paths of files that contain |string_a| or |string_b|.
[ "Returns", "list", "of", "paths", "of", "files", "that", "contain", "|string_a|", "or", "|string_b|", "." ]
def FindFilesWithContents(string_a, string_b): """Returns list of paths of files that contain |string_a| or |string_b|. Uses --name-only to print the file paths. The default behavior of git grep is to OR together multiple patterns. Args: string_a: A string to search for (not a regular expression). string_b: As above. Returns: A list of file paths as strings. """ matching_files = subprocess.check_output([ 'git', 'grep', '--name-only', '--fixed-strings', '-e', string_a, '-e', string_b]) files_list = matching_files.split('\n') # The output ends in a newline, so slice that off. files_list = files_list[:-1] return files_list
[ "def", "FindFilesWithContents", "(", "string_a", ",", "string_b", ")", ":", "matching_files", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'grep'", ",", "'--name-only'", ",", "'--fixed-strings'", ",", "'-e'", ",", "string_a", ",", "'-e'", ",", "string_b", "]", ")", "files_list", "=", "matching_files", ".", "split", "(", "'\\n'", ")", "# The output ends in a newline, so slice that off.", "files_list", "=", "files_list", "[", ":", "-", "1", "]", "return", "files_list" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/resources/find_unused_resources.py#L54-L73
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/cpplint.py
python
NestingState.Update
(self, filename, clean_lines, linenum, error)
Update nesting state with current line. 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.
Update nesting state with current line.
[ "Update", "nesting", "state", "with", "current", "line", "." ]
def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo(linenum)) else: self.stack.append(_BlockInfo(linenum, True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2)
[ "def", "Update", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remember top of the previous nesting stack.", "#", "# The stack is always pushed/popped and not modified in place, so", "# we can just do a shallow copy instead of copy.deepcopy. Using", "# deepcopy would slow down cpplint by ~28%.", "if", "self", ".", "stack", ":", "self", ".", "previous_stack_top", "=", "self", ".", "stack", "[", "-", "1", "]", "else", ":", "self", ".", "previous_stack_top", "=", "None", "# Update pp_stack", "self", ".", "UpdatePreprocessor", "(", "line", ")", "# Count parentheses. This is to avoid adding struct arguments to", "# the nesting stack.", "if", "self", ".", "stack", ":", "inner_block", "=", "self", ".", "stack", "[", "-", "1", "]", "depth_change", "=", "line", ".", "count", "(", "'('", ")", "-", "line", ".", "count", "(", "')'", ")", "inner_block", ".", "open_parentheses", "+=", "depth_change", "# Also check if we are starting or ending an inline assembly block.", "if", "inner_block", ".", "inline_asm", "in", "(", "_NO_ASM", ",", "_END_ASM", ")", ":", "if", "(", "depth_change", "!=", "0", "and", "inner_block", ".", "open_parentheses", "==", "1", "and", "_MATCH_ASM", ".", "match", "(", "line", ")", ")", ":", "# Enter assembly block", "inner_block", ".", "inline_asm", "=", "_INSIDE_ASM", "else", ":", "# Not entering assembly block. If previous line was _END_ASM,", "# we will now shift to _NO_ASM state.", "inner_block", ".", "inline_asm", "=", "_NO_ASM", "elif", "(", "inner_block", ".", "inline_asm", "==", "_INSIDE_ASM", "and", "inner_block", ".", "open_parentheses", "==", "0", ")", ":", "# Exit assembly block", "inner_block", ".", "inline_asm", "=", "_END_ASM", "# Consume namespace declaration at the beginning of the line. Do", "# this in a loop so that we catch same line declarations like this:", "# namespace proto2 { namespace bridge { class MessageSet; } }", "while", "True", ":", "# Match start of namespace. The \"\\b\\s*\" below catches namespace", "# declarations even if it weren't followed by a whitespace, this", "# is so that we don't confuse our namespace checker. The", "# missing spaces will be flagged by CheckSpacing.", "namespace_decl_match", "=", "Match", "(", "r'^\\s*namespace\\b\\s*([:\\w]+)?(.*)$'", ",", "line", ")", "if", "not", "namespace_decl_match", ":", "break", "new_namespace", "=", "_NamespaceInfo", "(", "namespace_decl_match", ".", "group", "(", "1", ")", ",", "linenum", ")", "self", ".", "stack", ".", "append", "(", "new_namespace", ")", "line", "=", "namespace_decl_match", ".", "group", "(", "2", ")", "if", "line", ".", "find", "(", "'{'", ")", "!=", "-", "1", ":", "new_namespace", ".", "seen_open_brace", "=", "True", "line", "=", "line", "[", "line", ".", "find", "(", "'{'", ")", "+", "1", ":", "]", "# Look for a class declaration in whatever is left of the line", "# after parsing namespaces. The regexp accounts for decorated classes", "# such as in:", "# class LOCKABLE API Object {", "# };", "class_decl_match", "=", "Match", "(", "r'^(\\s*(?:template\\s*<[\\w\\s<>,:=]*>\\s*)?'", "r'(class|struct)\\s+(?:[A-Z_]+\\s+)*(\\w+(?:::\\w+)*))'", "r'(.*)$'", ",", "line", ")", "if", "(", "class_decl_match", "and", "(", "not", "self", ".", "stack", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "open_parentheses", "==", "0", ")", ")", ":", "# We do not want to accept classes that are actually template arguments:", "# template <class Ignore1,", "# class Ignore2 = Default<Args>,", "# template <Args> class Ignore3>", "# void Function() {};", "#", "# To avoid template argument cases, we scan forward and look for", "# an unmatched '>'. If we see one, assume we are inside a", "# template argument list.", "end_declaration", "=", "len", "(", "class_decl_match", ".", "group", "(", "1", ")", ")", "if", "not", "self", ".", "InTemplateArgumentList", "(", "clean_lines", ",", "linenum", ",", "end_declaration", ")", ":", "self", ".", "stack", ".", "append", "(", "_ClassInfo", "(", "class_decl_match", ".", "group", "(", "3", ")", ",", "class_decl_match", ".", "group", "(", "2", ")", ",", "clean_lines", ",", "linenum", ")", ")", "line", "=", "class_decl_match", ".", "group", "(", "4", ")", "# If we have not yet seen the opening brace for the innermost block,", "# run checks here.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckBegin", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "# Update access control if we are inside a class/struct", "if", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "-", "1", "]", "access_match", "=", "Match", "(", "r'^(.*)\\b(public|private|protected|signals)(\\s+(?:slots\\s*)?)?'", "r':(?:[^:]|$)'", ",", "line", ")", "if", "access_match", ":", "classinfo", ".", "access", "=", "access_match", ".", "group", "(", "2", ")", "# Check that access keywords are indented +1 space. Skip this", "# check if the keywords are not preceded by whitespaces.", "indent", "=", "access_match", ".", "group", "(", "1", ")", "if", "(", "len", "(", "indent", ")", "!=", "classinfo", ".", "class_indent", "+", "1", "and", "Match", "(", "r'^\\s*$'", ",", "indent", ")", ")", ":", "if", "classinfo", ".", "is_struct", ":", "parent", "=", "'struct '", "+", "classinfo", ".", "name", "else", ":", "parent", "=", "'class '", "+", "classinfo", ".", "name", "slots", "=", "''", "if", "access_match", ".", "group", "(", "3", ")", ":", "slots", "=", "access_match", ".", "group", "(", "3", ")", "error", "(", "filename", ",", "linenum", ",", "'whitespace/indent'", ",", "3", ",", "'%s%s: should be indented +1 space inside %s'", "%", "(", "access_match", ".", "group", "(", "2", ")", ",", "slots", ",", "parent", ")", ")", "# Consume braces or semicolons from what's left of the line", "while", "True", ":", "# Match first brace, semicolon, or closed parenthesis.", "matched", "=", "Match", "(", "r'^[^{;)}]*([{;)}])(.*)$'", ",", "line", ")", "if", "not", "matched", ":", "break", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'{'", ":", "# If namespace or class hasn't seen a opening brace yet, mark", "# namespace/class head as complete. Push a new block onto the", "# stack otherwise.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace", "=", "True", "elif", "Match", "(", "r'^extern\\s*\"[^\"]*\"\\s*\\{'", ",", "line", ")", ":", "self", ".", "stack", ".", "append", "(", "_ExternCInfo", "(", "linenum", ")", ")", "else", ":", "self", ".", "stack", ".", "append", "(", "_BlockInfo", "(", "linenum", ",", "True", ")", ")", "if", "_MATCH_ASM", ".", "match", "(", "line", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "inline_asm", "=", "_BLOCK_ASM", "elif", "token", "==", "';'", "or", "token", "==", "')'", ":", "# If we haven't seen an opening brace yet, but we already saw", "# a semicolon, this is probably a forward declaration. Pop", "# the stack for these.", "#", "# Similarly, if we haven't seen an opening brace yet, but we", "# already saw a closing parenthesis, then these are probably", "# function arguments with extra \"class\" or \"struct\" keywords.", "# Also pop these stack for these.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", ".", "pop", "(", ")", "else", ":", "# token == '}'", "# Perform end of block checks and pop the stack.", "if", "self", ".", "stack", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckEnd", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "self", ".", "stack", ".", "pop", "(", ")", "line", "=", "matched", ".", "group", "(", "2", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L2684-L2846
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
libVeles/cpplint.py
python
ReplaceableCheck
(operator, macro, line)
return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
Determine whether a basic CHECK can be replaced with a more specific one. For example suggest using CHECK_EQ instead of CHECK(a == b) and similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. Args: operator: The C++ operator used in the CHECK. macro: The CHECK or EXPECT macro being called. line: The current source line. Returns: True if the CHECK can be replaced with a more specific one.
Determine whether a basic CHECK can be replaced with a more specific one.
[ "Determine", "whether", "a", "basic", "CHECK", "can", "be", "replaced", "with", "a", "more", "specific", "one", "." ]
def ReplaceableCheck(operator, macro, line): """Determine whether a basic CHECK can be replaced with a more specific one. For example suggest using CHECK_EQ instead of CHECK(a == b) and similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. Args: operator: The C++ operator used in the CHECK. macro: The CHECK or EXPECT macro being called. line: The current source line. Returns: True if the CHECK can be replaced with a more specific one. """ # This matches decimal and hex integers, strings, and chars (in that order). match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')' # Expression to match two sides of the operator with something that # looks like a literal, since CHECK(x == iterator) won't compile. # This means we can't catch all the cases where a more specific # CHECK is possible, but it's less annoying than dealing with # extraneous warnings. match_this = (r'\s*' + macro + r'\((\s*' + match_constant + r'\s*' + operator + r'[^<>].*|' r'.*[^<>]' + operator + r'\s*' + match_constant + r'\s*\))') # Don't complain about CHECK(x == NULL) or similar because # CHECK_EQ(x, NULL) won't compile (requires a cast). # Also, don't complain about more complex boolean expressions # involving && or || such as CHECK(a == b || c == d). return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
[ "def", "ReplaceableCheck", "(", "operator", ",", "macro", ",", "line", ")", ":", "# This matches decimal and hex integers, strings, and chars (in that order).", "match_constant", "=", "r'([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')'", "# Expression to match two sides of the operator with something that", "# looks like a literal, since CHECK(x == iterator) won't compile.", "# This means we can't catch all the cases where a more specific", "# CHECK is possible, but it's less annoying than dealing with", "# extraneous warnings.", "match_this", "=", "(", "r'\\s*'", "+", "macro", "+", "r'\\((\\s*'", "+", "match_constant", "+", "r'\\s*'", "+", "operator", "+", "r'[^<>].*|'", "r'.*[^<>]'", "+", "operator", "+", "r'\\s*'", "+", "match_constant", "+", "r'\\s*\\))'", ")", "# Don't complain about CHECK(x == NULL) or similar because", "# CHECK_EQ(x, NULL) won't compile (requires a cast).", "# Also, don't complain about more complex boolean expressions", "# involving && or || such as CHECK(a == b || c == d).", "return", "Match", "(", "match_this", ",", "line", ")", "and", "not", "Search", "(", "r'NULL|&&|\\|\\|'", ",", "line", ")" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L2672-L2704
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/fileinput.py
python
fileno
()
return _state.fileno()
Return the file number of the current file. When no file is currently opened, returns -1.
Return the file number of the current file. When no file is currently opened, returns -1.
[ "Return", "the", "file", "number", "of", "the", "current", "file", ".", "When", "no", "file", "is", "currently", "opened", "returns", "-", "1", "." ]
def fileno(): """ Return the file number of the current file. When no file is currently opened, returns -1. """ if not _state: raise RuntimeError("no active input()") return _state.fileno()
[ "def", "fileno", "(", ")", ":", "if", "not", "_state", ":", "raise", "RuntimeError", "(", "\"no active input()\"", ")", "return", "_state", ".", "fileno", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/fileinput.py#L148-L155
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
screen.pretty
(self)
return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box.
This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box.
[ "This", "returns", "a", "copy", "of", "the", "screen", "as", "a", "unicode", "string", "with", "an", "ASCII", "text", "box", "around", "the", "screen", "border", ".", "This", "is", "similar", "to", "__str__", "/", "__unicode__", "except", "that", "it", "adds", "a", "box", "." ]
def pretty (self): '''This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box.''' top_bot = u'+' + u'-'*self.cols + u'+\n' return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
[ "def", "pretty", "(", "self", ")", ":", "top_bot", "=", "u'+'", "+", "u'-'", "*", "self", ".", "cols", "+", "u'+\\n'", "return", "top_bot", "+", "u'\\n'", ".", "join", "(", "[", "u'|'", "+", "line", "+", "u'|'", "for", "line", "in", "unicode", "(", "self", ")", ".", "split", "(", "u'\\n'", ")", "]", ")", "+", "u'\\n'", "+", "top_bot" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L138-L144
shedskin/shedskin
ae88dbca7b1d9671cd8be448cb0b497122758936
examples/block.py
python
easytest
()
Tests block code with N=3, f=0.01 on a tiny example. >>> easytest() # doctest:+NORMALIZE_WHITESPACE #Symbol Count Codeword 000 (0.97) 1 001 (0.0098) 001 010 (0.0098) 010 011 (9.9e-05) 00001 100 (0.0098) 011 101 (9.9e-05) 00010 110 (9.9e-05) 00011 111 (1e-06) 00000 zipped = 1001010000010110111 decoded = ['000', '001', '010', '011', '100', '100', '000'] OK!
Tests block code with N=3, f=0.01 on a tiny example. >>> easytest() # doctest:+NORMALIZE_WHITESPACE #Symbol Count Codeword 000 (0.97) 1 001 (0.0098) 001 010 (0.0098) 010 011 (9.9e-05) 00001 100 (0.0098) 011 101 (9.9e-05) 00010 110 (9.9e-05) 00011 111 (1e-06) 00000 zipped = 1001010000010110111 decoded = ['000', '001', '010', '011', '100', '100', '000'] OK!
[ "Tests", "block", "code", "with", "N", "=", "3", "f", "=", "0", ".", "01", "on", "a", "tiny", "example", ".", ">>>", "easytest", "()", "#", "doctest", ":", "+", "NORMALIZE_WHITESPACE", "#Symbol", "Count", "Codeword", "000", "(", "0", ".", "97", ")", "1", "001", "(", "0", ".", "0098", ")", "001", "010", "(", "0", ".", "0098", ")", "010", "011", "(", "9", ".", "9e", "-", "05", ")", "00001", "100", "(", "0", ".", "0098", ")", "011", "101", "(", "9", ".", "9e", "-", "05", ")", "00010", "110", "(", "9", ".", "9e", "-", "05", ")", "00011", "111", "(", "1e", "-", "06", ")", "00000", "zipped", "=", "1001010000010110111", "decoded", "=", "[", "000", "001", "010", "011", "100", "100", "000", "]", "OK!" ]
def easytest(): """ Tests block code with N=3, f=0.01 on a tiny example. >>> easytest() # doctest:+NORMALIZE_WHITESPACE #Symbol Count Codeword 000 (0.97) 1 001 (0.0098) 001 010 (0.0098) 010 011 (9.9e-05) 00001 100 (0.0098) 011 101 (9.9e-05) 00010 110 (9.9e-05) 00011 111 (1e-06) 00000 zipped = 1001010000010110111 decoded = ['000', '001', '010', '011', '100', '100', '000'] OK! """ N=3 f=0.01 probs = findprobs(f,N) # if len(probs) > 999 : # sys.setrecursionlimit( len(probs)+100 ) symbols = makenodes(probs) # makenodes is defined at the bottom of Huffman3 package root = iterate(symbols) # make huffman code and put it into the symbols' nodes, and return the root of the decoding tree symbols.sort(lambda x, y: cmp(x.index, y.index)) # sort by index for co in symbols : # and write the answer co.report() source = ['000','001','010','011','100','100','000'] zipped = encode(source, symbols) print "zipped =",zipped answer = decode( zipped, root ) print "decoded =",answer if ( source != answer ): print "ERROR" else: print "OK!" pass
[ "def", "easytest", "(", ")", ":", "N", "=", "3", "f", "=", "0.01", "probs", "=", "findprobs", "(", "f", ",", "N", ")", "# if len(probs) > 999 :", "# sys.setrecursionlimit( len(probs)+100 )", "symbols", "=", "makenodes", "(", "probs", ")", "# makenodes is defined at the bottom of Huffman3 package", "root", "=", "iterate", "(", "symbols", ")", "# make huffman code and put it into the symbols' nodes, and return the root of the decoding tree", "symbols", ".", "sort", "(", "lambda", "x", ",", "y", ":", "cmp", "(", "x", ".", "index", ",", "y", ".", "index", ")", ")", "# sort by index ", "for", "co", "in", "symbols", ":", "# and write the answer", "co", ".", "report", "(", ")", "source", "=", "[", "'000'", ",", "'001'", ",", "'010'", ",", "'011'", ",", "'100'", ",", "'100'", ",", "'000'", "]", "zipped", "=", "encode", "(", "source", ",", "symbols", ")", "print", "\"zipped =\"", ",", "zipped", "answer", "=", "decode", "(", "zipped", ",", "root", ")", "print", "\"decoded =\"", ",", "answer", "if", "(", "source", "!=", "answer", ")", ":", "print", "\"ERROR\"", "else", ":", "print", "\"OK!\"", "pass" ]
https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/block.py#L332-L370
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py
python
TNavigator.back
(self, distance)
Move the turtle backward by distance. Aliases: back | backward | bk Argument: distance -- a number Move the turtle backward by distance ,opposite to the direction the turtle is headed. Do not change the turtle's heading. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00, 0.00)
Move the turtle backward by distance.
[ "Move", "the", "turtle", "backward", "by", "distance", "." ]
def back(self, distance): """Move the turtle backward by distance. Aliases: back | backward | bk Argument: distance -- a number Move the turtle backward by distance ,opposite to the direction the turtle is headed. Do not change the turtle's heading. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00, 0.00) """ self._go(-distance)
[ "def", "back", "(", "self", ",", "distance", ")", ":", "self", ".", "_go", "(", "-", "distance", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L1554-L1572