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
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_scene.py
python
shapenet_scene.gt_roidb
(self)
return gt_roidb
Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls.
Return the database of ground-truth regions of interest.
[ "Return", "the", "database", "of", "ground", "-", "truth", "regions", "of", "interest", "." ]
def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_shapenet_scene_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb
[ "def", "gt_roidb", "(", "self", ")", ":", "cache_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_path", ",", "self", ".", "name", "+", "'_gt_roidb.pkl'", ")", "if", "os", ".", "path", ".", "exists", "(", "cache_file", ")", ":", "with", "open", "(", "cache_file", ",", "'rb'", ")", "as", "fid", ":", "roidb", "=", "cPickle", ".", "load", "(", "fid", ")", "print", "'{} gt roidb loaded from {}'", ".", "format", "(", "self", ".", "name", ",", "cache_file", ")", "return", "roidb", "gt_roidb", "=", "[", "self", ".", "_load_shapenet_scene_annotation", "(", "index", ")", "for", "index", "in", "self", ".", "image_index", "]", "with", "open", "(", "cache_file", ",", "'wb'", ")", "as", "fid", ":", "cPickle", ".", "dump", "(", "gt_roidb", ",", "fid", ",", "cPickle", ".", "HIGHEST_PROTOCOL", ")", "print", "'wrote gt roidb to {}'", ".", "format", "(", "cache_file", ")", "return", "gt_roidb" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_scene.py#L118-L139
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Geometry3D.getVolumeGrid
(self)
return _robotsim.Geometry3D_getVolumeGrid(self)
r""" Returns a VolumeGrid if this geometry is of type VolumeGrid.
r""" Returns a VolumeGrid if this geometry is of type VolumeGrid.
[ "r", "Returns", "a", "VolumeGrid", "if", "this", "geometry", "is", "of", "type", "VolumeGrid", "." ]
def getVolumeGrid(self) -> "VolumeGrid": r""" Returns a VolumeGrid if this geometry is of type VolumeGrid. """ return _robotsim.Geometry3D_getVolumeGrid(self)
[ "def", "getVolumeGrid", "(", "self", ")", "->", "\"VolumeGrid\"", ":", "return", "_robotsim", ".", "Geometry3D_getVolumeGrid", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2117-L2122
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/expressions/expression.py
python
Expression.is_vector
(self)
return self.ndim <= 1 or (self.ndim == 2 and min(self.shape) == 1)
Is the expression a column or row vector?
Is the expression a column or row vector?
[ "Is", "the", "expression", "a", "column", "or", "row", "vector?" ]
def is_vector(self) -> bool: """Is the expression a column or row vector? """ return self.ndim <= 1 or (self.ndim == 2 and min(self.shape) == 1)
[ "def", "is_vector", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "ndim", "<=", "1", "or", "(", "self", ".", "ndim", "==", "2", "and", "min", "(", "self", ".", "shape", ")", "==", "1", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/expression.py#L410-L413
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/freetype/__init__.py
python
Outline.get_bbox
(self)
return bbox
Compute the exact bounding box of an outline. This is slower than computing the control box. However, it uses an advanced algorithm which returns very quickly when the two boxes coincide. Otherwise, the outline Bezier arcs are traversed to extract their extrema.
Compute the exact bounding box of an outline. This is slower than computing the control box. However, it uses an advanced algorithm which returns very quickly when the two boxes coincide. Otherwise, the outline Bezier arcs are traversed to extract their extrema.
[ "Compute", "the", "exact", "bounding", "box", "of", "an", "outline", ".", "This", "is", "slower", "than", "computing", "the", "control", "box", ".", "However", "it", "uses", "an", "advanced", "algorithm", "which", "returns", "very", "quickly", "when", "the", "two", "boxes", "coincide", ".", "Otherwise", "the", "outline", "Bezier", "arcs", "are", "traversed", "to", "extract", "their", "extrema", "." ]
def get_bbox(self): ''' Compute the exact bounding box of an outline. This is slower than computing the control box. However, it uses an advanced algorithm which returns very quickly when the two boxes coincide. Otherwise, the outline Bezier arcs are traversed to extract their extrema. ''' bbox = FT_BBox() error = FT_Outline_Get_BBox(byref(self._FT_Outline), byref(bbox)) if error: raise FT_Exception(error) return bbox
[ "def", "get_bbox", "(", "self", ")", ":", "bbox", "=", "FT_BBox", "(", ")", "error", "=", "FT_Outline_Get_BBox", "(", "byref", "(", "self", ".", "_FT_Outline", ")", ",", "byref", "(", "bbox", ")", ")", "if", "error", ":", "raise", "FT_Exception", "(", "error", ")", "return", "bbox" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/freetype/__init__.py#L725-L735
bh107/bohrium
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
thirdparty/pyratemp/pyratemp.py
python
Renderer.render
(self, parsetree, data)
return output
Render a parse-tree of a template. :Parameters: - `parsetree`: the parse-tree - `data`: the data to fill into the template (dictionary) :Returns: the rendered output-unicode-string :Exceptions: - `TemplateRenderError`
Render a parse-tree of a template.
[ "Render", "a", "parse", "-", "tree", "of", "a", "template", "." ]
def render(self, parsetree, data): """Render a parse-tree of a template. :Parameters: - `parsetree`: the parse-tree - `data`: the data to fill into the template (dictionary) :Returns: the rendered output-unicode-string :Exceptions: - `TemplateRenderError` """ _eval = self._eval # shortcut output = [] do_else = False # use else/elif-branch? if parsetree is None: return "" for elem in parsetree: if "str" == elem[0]: output.append(elem[1]) elif "sub" == elem[0]: output.append(unicode(_eval(elem[1], data))) elif "esc" == elem[0]: obj = _eval(elem[2], data) #prevent double-escape if isinstance(obj, _dontescape) or isinstance(obj, TemplateBase): output.append(unicode(obj)) else: output.append(self.escapefunc(unicode(obj), elem[1])) elif "for" == elem[0]: do_else = True (names, iterable) = elem[1:3] try: loop_iter = iter(_eval(iterable, data)) except TypeError: raise TemplateRenderError("Cannot loop over '%s'." % iterable) for i in loop_iter: do_else = False if len(names) == 1: data[names[0]] = i else: data.update(zip(names, i)) #"for a,b,.. in list" output.extend(self.render(elem[3], data)) elif "if" == elem[0]: do_else = True if _eval(elem[1], data): do_else = False output.extend(self.render(elem[2], data)) elif "elif" == elem[0]: if do_else and _eval(elem[1], data): do_else = False output.extend(self.render(elem[2], data)) elif "else" == elem[0]: if do_else: do_else = False output.extend(self.render(elem[1], data)) elif "macro" == elem[0]: data[elem[1]] = TemplateBase(elem[2], self.render, data) else: raise TemplateRenderError("Invalid parse-tree (%s)." %(elem)) return output
[ "def", "render", "(", "self", ",", "parsetree", ",", "data", ")", ":", "_eval", "=", "self", ".", "_eval", "# shortcut", "output", "=", "[", "]", "do_else", "=", "False", "# use else/elif-branch?", "if", "parsetree", "is", "None", ":", "return", "\"\"", "for", "elem", "in", "parsetree", ":", "if", "\"str\"", "==", "elem", "[", "0", "]", ":", "output", ".", "append", "(", "elem", "[", "1", "]", ")", "elif", "\"sub\"", "==", "elem", "[", "0", "]", ":", "output", ".", "append", "(", "unicode", "(", "_eval", "(", "elem", "[", "1", "]", ",", "data", ")", ")", ")", "elif", "\"esc\"", "==", "elem", "[", "0", "]", ":", "obj", "=", "_eval", "(", "elem", "[", "2", "]", ",", "data", ")", "#prevent double-escape", "if", "isinstance", "(", "obj", ",", "_dontescape", ")", "or", "isinstance", "(", "obj", ",", "TemplateBase", ")", ":", "output", ".", "append", "(", "unicode", "(", "obj", ")", ")", "else", ":", "output", ".", "append", "(", "self", ".", "escapefunc", "(", "unicode", "(", "obj", ")", ",", "elem", "[", "1", "]", ")", ")", "elif", "\"for\"", "==", "elem", "[", "0", "]", ":", "do_else", "=", "True", "(", "names", ",", "iterable", ")", "=", "elem", "[", "1", ":", "3", "]", "try", ":", "loop_iter", "=", "iter", "(", "_eval", "(", "iterable", ",", "data", ")", ")", "except", "TypeError", ":", "raise", "TemplateRenderError", "(", "\"Cannot loop over '%s'.\"", "%", "iterable", ")", "for", "i", "in", "loop_iter", ":", "do_else", "=", "False", "if", "len", "(", "names", ")", "==", "1", ":", "data", "[", "names", "[", "0", "]", "]", "=", "i", "else", ":", "data", ".", "update", "(", "zip", "(", "names", ",", "i", ")", ")", "#\"for a,b,.. in list\"", "output", ".", "extend", "(", "self", ".", "render", "(", "elem", "[", "3", "]", ",", "data", ")", ")", "elif", "\"if\"", "==", "elem", "[", "0", "]", ":", "do_else", "=", "True", "if", "_eval", "(", "elem", "[", "1", "]", ",", "data", ")", ":", "do_else", "=", "False", "output", ".", "extend", "(", "self", ".", "render", "(", "elem", "[", "2", "]", ",", "data", ")", ")", "elif", "\"elif\"", "==", "elem", "[", "0", "]", ":", "if", "do_else", "and", "_eval", "(", "elem", "[", "1", "]", ",", "data", ")", ":", "do_else", "=", "False", "output", ".", "extend", "(", "self", ".", "render", "(", "elem", "[", "2", "]", ",", "data", ")", ")", "elif", "\"else\"", "==", "elem", "[", "0", "]", ":", "if", "do_else", ":", "do_else", "=", "False", "output", ".", "extend", "(", "self", ".", "render", "(", "elem", "[", "1", "]", ",", "data", ")", ")", "elif", "\"macro\"", "==", "elem", "[", "0", "]", ":", "data", "[", "elem", "[", "1", "]", "]", "=", "TemplateBase", "(", "elem", "[", "2", "]", ",", "self", ".", "render", ",", "data", ")", "else", ":", "raise", "TemplateRenderError", "(", "\"Invalid parse-tree (%s).\"", "%", "(", "elem", ")", ")", "return", "output" ]
https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/thirdparty/pyratemp/pyratemp.py#L1110-L1170
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/AlignComponents.py
python
AlignComponents._extract_tofs
(self, table_tofs: TableWorkspace)
return np.transpose(peak_tofs)
r""" Extract the columns of the input table containing the peak centers, sorted by increasing value of the peak center in d-spacing units :param table_tofs: table of peak centers, in TOF units :return array of shape (detector_count, peak_count)
r""" Extract the columns of the input table containing the peak centers, sorted by increasing value of the peak center in d-spacing units
[ "r", "Extract", "the", "columns", "of", "the", "input", "table", "containing", "the", "peak", "centers", "sorted", "by", "increasing", "value", "of", "the", "peak", "center", "in", "d", "-", "spacing", "units" ]
def _extract_tofs(self, table_tofs: TableWorkspace) -> np.ndarray: r""" Extract the columns of the input table containing the peak centers, sorted by increasing value of the peak center in d-spacing units :param table_tofs: table of peak centers, in TOF units :return array of shape (detector_count, peak_count) """ # the title for the columns containing the peak centers begin with '@' indexes_and_titles = [(index, title) for index, title in enumerate(table_tofs.getColumnNames()) if '@' in title] column_indexes, titles = list(zip(*indexes_and_titles)) peak_tofs = np.array([table_tofs.column(i) for i in column_indexes]) # shape = (peak_count, detector_count) peak_centers = np.array([float(title.replace('@', '')) for title in titles]) permutation = np.argsort(peak_centers) # reorder of indices guarantee increase in d-spacing peak_tofs = peak_tofs[permutation] # sort by increasing d-spacing return np.transpose(peak_tofs)
[ "def", "_extract_tofs", "(", "self", ",", "table_tofs", ":", "TableWorkspace", ")", "->", "np", ".", "ndarray", ":", "# the title for the columns containing the peak centers begin with '@'", "indexes_and_titles", "=", "[", "(", "index", ",", "title", ")", "for", "index", ",", "title", "in", "enumerate", "(", "table_tofs", ".", "getColumnNames", "(", ")", ")", "if", "'@'", "in", "title", "]", "column_indexes", ",", "titles", "=", "list", "(", "zip", "(", "*", "indexes_and_titles", ")", ")", "peak_tofs", "=", "np", ".", "array", "(", "[", "table_tofs", ".", "column", "(", "i", ")", "for", "i", "in", "column_indexes", "]", ")", "# shape = (peak_count, detector_count)", "peak_centers", "=", "np", ".", "array", "(", "[", "float", "(", "title", ".", "replace", "(", "'@'", ",", "''", ")", ")", "for", "title", "in", "titles", "]", ")", "permutation", "=", "np", ".", "argsort", "(", "peak_centers", ")", "# reorder of indices guarantee increase in d-spacing", "peak_tofs", "=", "peak_tofs", "[", "permutation", "]", "# sort by increasing d-spacing", "return", "np", ".", "transpose", "(", "peak_tofs", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/AlignComponents.py#L567-L582
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/filelist.py
python
FileList.include_pattern
(self, pattern, anchor=1, prefix=None, is_regex=0)
return files_found
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return 1 if files are found.
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern.
[ "Select", "strings", "(", "presumably", "filenames", ")", "from", "self", ".", "files", "that", "match", "pattern", "a", "Unix", "-", "style", "wildcard", "(", "glob", ")", "pattern", "." ]
def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return 1 if files are found. """ # XXX docstring lying about what the special chars are? files_found = 0 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) self.debug_print("include_pattern: applying regex r'%s'" % pattern_re.pattern) # delayed loading of allfiles list if self.allfiles is None: self.findall() for name in self.allfiles: if pattern_re.search(name): self.debug_print(" adding " + name) self.files.append(name) files_found = 1 return files_found
[ "def", "include_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "1", ",", "prefix", "=", "None", ",", "is_regex", "=", "0", ")", ":", "# XXX docstring lying about what the special chars are?", "files_found", "=", "0", "pattern_re", "=", "translate_pattern", "(", "pattern", ",", "anchor", ",", "prefix", ",", "is_regex", ")", "self", ".", "debug_print", "(", "\"include_pattern: applying regex r'%s'\"", "%", "pattern_re", ".", "pattern", ")", "# delayed loading of allfiles list", "if", "self", ".", "allfiles", "is", "None", ":", "self", ".", "findall", "(", ")", "for", "name", "in", "self", ".", "allfiles", ":", "if", "pattern_re", ".", "search", "(", "name", ")", ":", "self", ".", "debug_print", "(", "\" adding \"", "+", "name", ")", "self", ".", "files", ".", "append", "(", "name", ")", "files_found", "=", "1", "return", "files_found" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/filelist.py#L187-L229
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGridInterface.GetPropertyValueAsString
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetPropertyValueAsString(*args, **kwargs)
GetPropertyValueAsString(self, PGPropArg id) -> String
GetPropertyValueAsString(self, PGPropArg id) -> String
[ "GetPropertyValueAsString", "(", "self", "PGPropArg", "id", ")", "-", ">", "String" ]
def GetPropertyValueAsString(*args, **kwargs): """GetPropertyValueAsString(self, PGPropArg id) -> String""" return _propgrid.PropertyGridInterface_GetPropertyValueAsString(*args, **kwargs)
[ "def", "GetPropertyValueAsString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetPropertyValueAsString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1249-L1251
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
scripts/cpp_lint.py
python
FileInfo.FullName
(self)
return os.path.abspath(self._filename).replace('\\', '/')
Make Windows paths like Unix.
Make Windows paths like Unix.
[ "Make", "Windows", "paths", "like", "Unix", "." ]
def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/')
[ "def", "FullName", "(", "self", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "_filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L881-L883
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/widgets/containers.py
python
Container._cloneChildren
(self, prefix)
return cloneList
Clones each child and return the clones in a list.
Clones each child and return the clones in a list.
[ "Clones", "each", "child", "and", "return", "the", "clones", "in", "a", "list", "." ]
def _cloneChildren(self, prefix): """ Clones each child and return the clones in a list. """ cloneList = [ child.clone(prefix) for child in self.children ] return cloneList
[ "def", "_cloneChildren", "(", "self", ",", "prefix", ")", ":", "cloneList", "=", "[", "child", ".", "clone", "(", "prefix", ")", "for", "child", "in", "self", ".", "children", "]", "return", "cloneList" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/containers.py#L426-L432
kevinlin311tw/caffe-cvprw15
45c2a1bf0368569c54e0be4edf8d34285cf79e70
scripts/cpp_lint.py
python
IsErrorSuppressedByNolint
(category, linenum)
return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment.
Returns true if the specified error category is suppressed on this line.
[ "Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "." ]
def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
[ "def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None", ",", "set", "(", ")", ")", ")" ]
https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L500-L513
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher.system_methodSignature
(self, method_name)
return 'signatures not supported'
system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.
system.methodSignature('add') => [double, int, int]
[ "system", ".", "methodSignature", "(", "add", ")", "=", ">", "[", "double", "int", "int", "]" ]
def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html return 'signatures not supported'
[ "def", "system_methodSignature", "(", "self", ",", "method_name", ")", ":", "# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html", "return", "'signatures not supported'" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/SimpleXMLRPCServer.py#L299-L310
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py
python
BaseChartEncoder.Img
(self, width, height)
return tag % (url, width, height)
Get an image tag for our graph.
Get an image tag for our graph.
[ "Get", "an", "image", "tag", "for", "our", "graph", "." ]
def Img(self, width, height): """Get an image tag for our graph.""" url = self.Url(width, height, use_html_entities=True) tag = '<img src="%s" width="%s" height="%s" alt="chart"/>' return tag % (url, width, height)
[ "def", "Img", "(", "self", ",", "width", ",", "height", ")", ":", "url", "=", "self", ".", "Url", "(", "width", ",", "height", ",", "use_html_entities", "=", "True", ")", "tag", "=", "'<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"chart\"/>'", "return", "tag", "%", "(", "url", ",", "width", ",", "height", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py#L67-L71
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/encoders.py
python
encode_base64
(msg)
Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header.
Encode the message's payload in Base64.
[ "Encode", "the", "message", "s", "payload", "in", "Base64", "." ]
def encode_base64(msg): """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload(decode=True) encdata = str(_bencode(orig), 'ascii') msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'base64'
[ "def", "encode_base64", "(", "msg", ")", ":", "orig", "=", "msg", ".", "get_payload", "(", "decode", "=", "True", ")", "encdata", "=", "str", "(", "_bencode", "(", "orig", ")", ",", "'ascii'", ")", "msg", ".", "set_payload", "(", "encdata", ")", "msg", "[", "'Content-Transfer-Encoding'", "]", "=", "'base64'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/encoders.py#L26-L34
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextBuffer.__init__
(self, *args, **kwargs)
__init__(self) -> RichTextBuffer This is a kind of box, used to represent the whole buffer.
__init__(self) -> RichTextBuffer
[ "__init__", "(", "self", ")", "-", ">", "RichTextBuffer" ]
def __init__(self, *args, **kwargs): """ __init__(self) -> RichTextBuffer This is a kind of box, used to represent the whole buffer. """ _richtext.RichTextBuffer_swiginit(self,_richtext.new_RichTextBuffer(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_richtext", ".", "RichTextBuffer_swiginit", "(", "self", ",", "_richtext", ".", "new_RichTextBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2200-L2206
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/cgi.py
python
MiniFieldStorage.__repr__
(self)
return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
Return printable representation.
Return printable representation.
[ "Return", "printable", "representation", "." ]
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"MiniFieldStorage(%r, %r)\"", "%", "(", "self", ".", "name", ",", "self", ".", "value", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/cgi.py#L271-L273
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/message.py
python
Message.SetInParent
(self)
Mark this as present in the parent. This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.
Mark this as present in the parent.
[ "Mark", "this", "as", "present", "in", "the", "parent", "." ]
def SetInParent(self): """Mark this as present in the parent. This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.""" raise NotImplementedError
[ "def", "SetInParent", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/message.py#L124-L131
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/rfcn/lib/datasets/luna.py
python
luna._load_luna_annotation
(self, index)
Load image and bounding boxes info from luna bbox file format
Load image and bounding boxes info from luna bbox file format
[ "Load", "image", "and", "bounding", "boxes", "info", "from", "luna", "bbox", "file", "format" ]
def _load_luna_annotation(self, index): """ Load image and bounding boxes info from luna bbox file format """ bb_directory = os.path.join(self._data_path, '1_1_1mm_slices_bbox') [subfolder, filename] = index.split('-') abs_filename = os.path.join(bb_directory, 'subset' + str(subfolder), filename) with gzip.open(abs_filename, 'rb') as f: [gt_boxes, im_info] = cPickle.load(f) num_objs = len(gt_boxes) boxes = np.zeros((num_objs, 4), dtype = np.uint16) gt_classes = np.zeros((num_objs), dtype = np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype = np.float32) # "Seg" area for luna is just the box area seg_areas = np.zeros((num_objs), dtype = np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(gt_boxes): # Make pixel indexes 0-based x1 = obj[0] y1 = obj[1] x2 = obj[2] y2 = obj[3] cls = int(obj[4]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False, 'seg_areas' : seg_areas}
[ "def", "_load_luna_annotation", "(", "self", ",", "index", ")", ":", "bb_directory", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "'1_1_1mm_slices_bbox'", ")", "[", "subfolder", ",", "filename", "]", "=", "index", ".", "split", "(", "'-'", ")", "abs_filename", "=", "os", ".", "path", ".", "join", "(", "bb_directory", ",", "'subset'", "+", "str", "(", "subfolder", ")", ",", "filename", ")", "with", "gzip", ".", "open", "(", "abs_filename", ",", "'rb'", ")", "as", "f", ":", "[", "gt_boxes", ",", "im_info", "]", "=", "cPickle", ".", "load", "(", "f", ")", "num_objs", "=", "len", "(", "gt_boxes", ")", "boxes", "=", "np", ".", "zeros", "(", "(", "num_objs", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "gt_classes", "=", "np", ".", "zeros", "(", "(", "num_objs", ")", ",", "dtype", "=", "np", ".", "int32", ")", "overlaps", "=", "np", ".", "zeros", "(", "(", "num_objs", ",", "self", ".", "num_classes", ")", ",", "dtype", "=", "np", ".", "float32", ")", "# \"Seg\" area for luna is just the box area", "seg_areas", "=", "np", ".", "zeros", "(", "(", "num_objs", ")", ",", "dtype", "=", "np", ".", "float32", ")", "# Load object bounding boxes into a data frame.", "for", "ix", ",", "obj", "in", "enumerate", "(", "gt_boxes", ")", ":", "# Make pixel indexes 0-based", "x1", "=", "obj", "[", "0", "]", "y1", "=", "obj", "[", "1", "]", "x2", "=", "obj", "[", "2", "]", "y2", "=", "obj", "[", "3", "]", "cls", "=", "int", "(", "obj", "[", "4", "]", ")", "boxes", "[", "ix", ",", ":", "]", "=", "[", "x1", ",", "y1", ",", "x2", ",", "y2", "]", "gt_classes", "[", "ix", "]", "=", "cls", "overlaps", "[", "ix", ",", "cls", "]", "=", "1.0", "seg_areas", "[", "ix", "]", "=", "(", "x2", "-", "x1", "+", "1", ")", "*", "(", "y2", "-", "y1", "+", "1", ")", "overlaps", "=", "scipy", ".", "sparse", ".", "csr_matrix", "(", "overlaps", ")", "return", "{", "'boxes'", ":", "boxes", ",", "'gt_classes'", ":", "gt_classes", ",", "'gt_overlaps'", ":", "overlaps", ",", "'flipped'", ":", "False", ",", "'seg_areas'", ":", "seg_areas", "}" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/datasets/luna.py#L122-L159
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/feature_extraction/image.py
python
reconstruct_from_patches_2d
(patches, image_size)
return img
Reconstruct the image from all of its patches. Patches are assumed to overlap and the image is constructed by filling in the patches from left to right, top to bottom, averaging the overlapping regions. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- patches : array, shape = (n_patches, patch_height, patch_width) or (n_patches, patch_height, patch_width, n_channels) The complete set of patches. If the patches contain colour information, channels are indexed along the last dimension: RGB patches would have `n_channels=3`. image_size : tuple of ints (image_height, image_width) or (image_height, image_width, n_channels) the size of the image that will be reconstructed Returns ------- image : array, shape = image_size the reconstructed image
Reconstruct the image from all of its patches.
[ "Reconstruct", "the", "image", "from", "all", "of", "its", "patches", "." ]
def reconstruct_from_patches_2d(patches, image_size): """Reconstruct the image from all of its patches. Patches are assumed to overlap and the image is constructed by filling in the patches from left to right, top to bottom, averaging the overlapping regions. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- patches : array, shape = (n_patches, patch_height, patch_width) or (n_patches, patch_height, patch_width, n_channels) The complete set of patches. If the patches contain colour information, channels are indexed along the last dimension: RGB patches would have `n_channels=3`. image_size : tuple of ints (image_height, image_width) or (image_height, image_width, n_channels) the size of the image that will be reconstructed Returns ------- image : array, shape = image_size the reconstructed image """ i_h, i_w = image_size[:2] p_h, p_w = patches.shape[1:3] img = np.zeros(image_size) # compute the dimensions of the patches array n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 for p, (i, j) in zip(patches, product(range(n_h), range(n_w))): img[i:i + p_h, j:j + p_w] += p for i in range(i_h): for j in range(i_w): # divide by the amount of overlap # XXX: is this the most efficient way? memory-wise yes, cpu wise? img[i, j] /= float(min(i + 1, p_h, i_h - i) * min(j + 1, p_w, i_w - j)) return img
[ "def", "reconstruct_from_patches_2d", "(", "patches", ",", "image_size", ")", ":", "i_h", ",", "i_w", "=", "image_size", "[", ":", "2", "]", "p_h", ",", "p_w", "=", "patches", ".", "shape", "[", "1", ":", "3", "]", "img", "=", "np", ".", "zeros", "(", "image_size", ")", "# compute the dimensions of the patches array", "n_h", "=", "i_h", "-", "p_h", "+", "1", "n_w", "=", "i_w", "-", "p_w", "+", "1", "for", "p", ",", "(", "i", ",", "j", ")", "in", "zip", "(", "patches", ",", "product", "(", "range", "(", "n_h", ")", ",", "range", "(", "n_w", ")", ")", ")", ":", "img", "[", "i", ":", "i", "+", "p_h", ",", "j", ":", "j", "+", "p_w", "]", "+=", "p", "for", "i", "in", "range", "(", "i_h", ")", ":", "for", "j", "in", "range", "(", "i_w", ")", ":", "# divide by the amount of overlap", "# XXX: is this the most efficient way? memory-wise yes, cpu wise?", "img", "[", "i", ",", "j", "]", "/=", "float", "(", "min", "(", "i", "+", "1", ",", "p_h", ",", "i_h", "-", "i", ")", "*", "min", "(", "j", "+", "1", ",", "p_w", ",", "i_w", "-", "j", ")", ")", "return", "img" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/feature_extraction/image.py#L393-L435
ucbrise/clipper
9f25e3fc7f8edc891615e81c5b80d3d8aed72608
clipper_admin/clipper_admin/clipper_admin.py
python
ClipperConnection.stop_inactive_model_versions
(self, model_names)
Stops all model containers serving stale versions of the specified models. For example, if you have deployed versions 1, 2, and 3 of model "music_recommender" and version 3 is the current version:: clipper_conn.stop_inactive_model_versions(["music_recommender"]) will stop any containers serving versions 1 and 2 but will leave containers serving version 3 untouched. Parameters ---------- model_names : list(str) The names of the models whose old containers you want to stop. Raises ------ :py:exc:`clipper.UnconnectedException`
Stops all model containers serving stale versions of the specified models.
[ "Stops", "all", "model", "containers", "serving", "stale", "versions", "of", "the", "specified", "models", "." ]
def stop_inactive_model_versions(self, model_names): """Stops all model containers serving stale versions of the specified models. For example, if you have deployed versions 1, 2, and 3 of model "music_recommender" and version 3 is the current version:: clipper_conn.stop_inactive_model_versions(["music_recommender"]) will stop any containers serving versions 1 and 2 but will leave containers serving version 3 untouched. Parameters ---------- model_names : list(str) The names of the models whose old containers you want to stop. Raises ------ :py:exc:`clipper.UnconnectedException` """ if not self.connected: raise UnconnectedException() model_info = self.get_all_models(verbose=True) model_dict = {} for m in model_info: if m["model_name"] in model_names and not m["is_current_version"]: if m["model_name"] in model_dict: model_dict[m["model_name"]].append(m["model_version"]) else: model_dict[m["model_name"]] = [m["model_version"]] self.cm.stop_models(model_dict) self._unregister_versioned_models(model_dict) pp = pprint.PrettyPrinter(indent=4) self.logger.info( "Stopped all containers for these models and versions:\n{}".format( pp.pformat(model_dict)))
[ "def", "stop_inactive_model_versions", "(", "self", ",", "model_names", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "UnconnectedException", "(", ")", "model_info", "=", "self", ".", "get_all_models", "(", "verbose", "=", "True", ")", "model_dict", "=", "{", "}", "for", "m", "in", "model_info", ":", "if", "m", "[", "\"model_name\"", "]", "in", "model_names", "and", "not", "m", "[", "\"is_current_version\"", "]", ":", "if", "m", "[", "\"model_name\"", "]", "in", "model_dict", ":", "model_dict", "[", "m", "[", "\"model_name\"", "]", "]", ".", "append", "(", "m", "[", "\"model_version\"", "]", ")", "else", ":", "model_dict", "[", "m", "[", "\"model_name\"", "]", "]", "=", "[", "m", "[", "\"model_version\"", "]", "]", "self", ".", "cm", ".", "stop_models", "(", "model_dict", ")", "self", ".", "_unregister_versioned_models", "(", "model_dict", ")", "pp", "=", "pprint", ".", "PrettyPrinter", "(", "indent", "=", "4", ")", "self", ".", "logger", ".", "info", "(", "\"Stopped all containers for these models and versions:\\n{}\"", ".", "format", "(", "pp", ".", "pformat", "(", "model_dict", ")", ")", ")" ]
https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/clipper_admin.py#L1348-L1383
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/io/io.py
python
NDArrayIter._getdata
(self, data_source, start=None, end=None)
return [ x[1][s] if isinstance(x[1], (np.ndarray, NDArray)) else # h5py (only supports indices in increasing order) array(x[1][sorted(self.idx[s])][[ list(self.idx[s]).index(i) for i in sorted(self.idx[s]) ]]) for x in data_source ]
Load data from underlying arrays.
Load data from underlying arrays.
[ "Load", "data", "from", "underlying", "arrays", "." ]
def _getdata(self, data_source, start=None, end=None): """Load data from underlying arrays.""" assert start is not None or end is not None, 'should at least specify start or end' start = start if start is not None else 0 if end is None: end = data_source[0][1].shape[0] if data_source else 0 s = slice(start, end) return [ x[1][s] if isinstance(x[1], (np.ndarray, NDArray)) else # h5py (only supports indices in increasing order) array(x[1][sorted(self.idx[s])][[ list(self.idx[s]).index(i) for i in sorted(self.idx[s]) ]]) for x in data_source ]
[ "def", "_getdata", "(", "self", ",", "data_source", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "assert", "start", "is", "not", "None", "or", "end", "is", "not", "None", ",", "'should at least specify start or end'", "start", "=", "start", "if", "start", "is", "not", "None", "else", "0", "if", "end", "is", "None", ":", "end", "=", "data_source", "[", "0", "]", "[", "1", "]", ".", "shape", "[", "0", "]", "if", "data_source", "else", "0", "s", "=", "slice", "(", "start", ",", "end", ")", "return", "[", "x", "[", "1", "]", "[", "s", "]", "if", "isinstance", "(", "x", "[", "1", "]", ",", "(", "np", ".", "ndarray", ",", "NDArray", ")", ")", "else", "# h5py (only supports indices in increasing order)", "array", "(", "x", "[", "1", "]", "[", "sorted", "(", "self", ".", "idx", "[", "s", "]", ")", "]", "[", "[", "list", "(", "self", ".", "idx", "[", "s", "]", ")", ".", "index", "(", "i", ")", "for", "i", "in", "sorted", "(", "self", ".", "idx", "[", "s", "]", ")", "]", "]", ")", "for", "x", "in", "data_source", "]" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/io/io.py#L692-L707
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/listobject.py
python
impl_allocated
(l)
list._allocated()
list._allocated()
[ "list", ".", "_allocated", "()" ]
def impl_allocated(l): """list._allocated() """ if isinstance(l, types.ListType): def impl(l): return _list_allocated(l) return impl
[ "def", "impl_allocated", "(", "l", ")", ":", "if", "isinstance", "(", "l", ",", "types", ".", "ListType", ")", ":", "def", "impl", "(", "l", ")", ":", "return", "_list_allocated", "(", "l", ")", "return", "impl" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/listobject.py#L408-L415
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGridInterface.GetPropertyImage
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetPropertyImage(*args, **kwargs)
GetPropertyImage(self, PGPropArg id) -> Bitmap
GetPropertyImage(self, PGPropArg id) -> Bitmap
[ "GetPropertyImage", "(", "self", "PGPropArg", "id", ")", "-", ">", "Bitmap" ]
def GetPropertyImage(*args, **kwargs): """GetPropertyImage(self, PGPropArg id) -> Bitmap""" return _propgrid.PropertyGridInterface_GetPropertyImage(*args, **kwargs)
[ "def", "GetPropertyImage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetPropertyImage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1225-L1227
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/utils/vim-lldb/python-vim-lldb/lldb_controller.py
python
LLDBController.getCommandOutput
(self, command, command_args="")
return (result.Succeeded(), result.GetOutput() if result.Succeeded() else result.GetError())
runs cmd in the command interpreter andreturns (status, result)
runs cmd in the command interpreter andreturns (status, result)
[ "runs", "cmd", "in", "the", "command", "interpreter", "andreturns", "(", "status", "result", ")" ]
def getCommandOutput(self, command, command_args=""): """ runs cmd in the command interpreter andreturns (status, result) """ result = lldb.SBCommandReturnObject() cmd = "%s %s" % (command, command_args) self.commandInterpreter.HandleCommand(cmd, result) return (result.Succeeded(), result.GetOutput() if result.Succeeded() else result.GetError())
[ "def", "getCommandOutput", "(", "self", ",", "command", ",", "command_args", "=", "\"\"", ")", ":", "result", "=", "lldb", ".", "SBCommandReturnObject", "(", ")", "cmd", "=", "\"%s %s\"", "%", "(", "command", ",", "command_args", ")", "self", ".", "commandInterpreter", ".", "HandleCommand", "(", "cmd", ",", "result", ")", "return", "(", "result", ".", "Succeeded", "(", ")", ",", "result", ".", "GetOutput", "(", ")", "if", "result", ".", "Succeeded", "(", ")", "else", "result", ".", "GetError", "(", ")", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L330-L336
CMU-Perceptual-Computing-Lab/caffe_rtpose
a4778bb1c3eb74d7250402016047216f77b4dba6
scripts/cpp_lint.py
python
_NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else case.", "self", ".", "pp_stack", ".", "append", "(", "_PreprocessorInfo", "(", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", ")", ")", "elif", "Match", "(", "r'^\\s*#\\s*(else|elif)\\b'", ",", "line", ")", ":", "# Beginning of #else block", "if", "self", ".", "pp_stack", ":", "if", "not", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# This is the first #else or #elif block. Remember the", "# whole nesting stack up to this point. This is what we", "# keep after the #endif.", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", "=", "True", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "=", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", "# Restore the stack to how it was before the #if", "self", ".", "stack", "=", "copy", ".", "deepcopy", "(", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_if", ")", "else", ":", "# TODO(unknown): unexpected #else, issue warning?", "pass", "elif", "Match", "(", "r'^\\s*#\\s*endif\\b'", ",", "line", ")", ":", "# End of #if or #else blocks.", "if", "self", ".", "pp_stack", ":", "# If we saw an #else, we will need to restore the nesting", "# stack to its former state before the #else, otherwise we", "# will just continue from where we left off.", "if", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# Here we can just use a shallow copy since we are the last", "# reference to it.", "self", ".", "stack", "=", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "# Drop the corresponding #if", "self", ".", "pp_stack", ".", "pop", "(", ")", "else", ":", "# TODO(unknown): unexpected #endif, issue warning?", "pass" ]
https://github.com/CMU-Perceptual-Computing-Lab/caffe_rtpose/blob/a4778bb1c3eb74d7250402016047216f77b4dba6/scripts/cpp_lint.py#L1948-L2002
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py
python
ParserElement.setParseAction
( self, *fns, **kwargs )
return self
Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value.
[ "Define", "one", "or", "more", "actions", "to", "perform", "when", "successfully", "matching", "parse", "element", "definition", ".", "Parse", "action", "fn", "is", "a", "callable", "method", "with", "0", "-", "3", "arguments", "called", "as", "C", "{", "fn", "(", "s", "loc", "toks", ")", "}", "C", "{", "fn", "(", "loc", "toks", ")", "}", "C", "{", "fn", "(", "toks", ")", "}", "or", "just", "C", "{", "fn", "()", "}", "where", ":", "-", "s", "=", "the", "original", "string", "being", "parsed", "(", "see", "note", "below", ")", "-", "loc", "=", "the", "location", "of", "the", "matching", "substring", "-", "toks", "=", "a", "list", "of", "the", "matched", "tokens", "packaged", "as", "a", "C", "{", "L", "{", "ParseResults", "}}", "object", "If", "the", "functions", "in", "fns", "modify", "the", "tokens", "they", "can", "return", "them", "as", "the", "return", "value", "from", "fn", "and", "the", "modified", "list", "of", "tokens", "will", "replace", "the", "original", ".", "Otherwise", "fn", "does", "not", "need", "to", "return", "any", "value", "." ]
def setParseAction( self, *fns, **kwargs ): """ Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = kwargs.get("callDuringTry", False) return self
[ "def", "setParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L1250-L1286
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "(", "'test.cc'", ",", "'regtest.cc'", ",", "'unittest.cc'", ",", "'inl.h'", ",", "'impl.h'", ",", "'internal.h'", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix", ")", "and", "len", "(", "filename", ")", ">", "len", "(", "suffix", ")", "and", "filename", "[", "-", "len", "(", "suffix", ")", "-", "1", "]", "in", "(", "'-'", ",", "'_'", ")", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "suffix", ")", "-", "1", "]", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L4439-L4463
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
DateTime.IsEarlierThan
(*args, **kwargs)
return _misc_.DateTime_IsEarlierThan(*args, **kwargs)
IsEarlierThan(self, DateTime datetime) -> bool
IsEarlierThan(self, DateTime datetime) -> bool
[ "IsEarlierThan", "(", "self", "DateTime", "datetime", ")", "-", ">", "bool" ]
def IsEarlierThan(*args, **kwargs): """IsEarlierThan(self, DateTime datetime) -> bool""" return _misc_.DateTime_IsEarlierThan(*args, **kwargs)
[ "def", "IsEarlierThan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_IsEarlierThan", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4029-L4031
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_VerifySourcesExist
(sources, root_dir)
return missing_sources
Verifies that all source files exist on disk. Checks that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation but no otherwise visible errors. Arguments: sources: A recursive list of Filter/file names. root_dir: The root directory for the relative path names. Returns: A list of source files that cannot be found on disk.
Verifies that all source files exist on disk.
[ "Verifies", "that", "all", "source", "files", "exist", "on", "disk", "." ]
def _VerifySourcesExist(sources, root_dir): """Verifies that all source files exist on disk. Checks that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation but no otherwise visible errors. Arguments: sources: A recursive list of Filter/file names. root_dir: The root directory for the relative path names. Returns: A list of source files that cannot be found on disk. """ missing_sources = [] for source in sources: if isinstance(source, MSVSProject.Filter): missing_sources.extend(_VerifySourcesExist(source.contents, root_dir)) else: if "$" not in source: full_path = os.path.join(root_dir, source) if not os.path.exists(full_path): missing_sources.append(full_path) return missing_sources
[ "def", "_VerifySourcesExist", "(", "sources", ",", "root_dir", ")", ":", "missing_sources", "=", "[", "]", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "source", ",", "MSVSProject", ".", "Filter", ")", ":", "missing_sources", ".", "extend", "(", "_VerifySourcesExist", "(", "source", ".", "contents", ",", "root_dir", ")", ")", "else", ":", "if", "\"$\"", "not", "in", "source", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "source", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "full_path", ")", ":", "missing_sources", ".", "append", "(", "full_path", ")", "return", "missing_sources" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L3474-L3496
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/mhlib.py
python
MH.setcontext
(self, context)
Set the name of the current folder.
Set the name of the current folder.
[ "Set", "the", "name", "of", "the", "current", "folder", "." ]
def setcontext(self, context): """Set the name of the current folder.""" fn = os.path.join(self.getpath(), 'context') f = open(fn, "w") f.write("Current-Folder: %s\n" % context) f.close()
[ "def", "setcontext", "(", "self", ",", "context", ")", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "self", ".", "getpath", "(", ")", ",", "'context'", ")", "f", "=", "open", "(", "fn", ",", "\"w\"", ")", "f", ".", "write", "(", "\"Current-Folder: %s\\n\"", "%", "context", ")", "f", ".", "close", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mhlib.py#L137-L142
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/google/protobuf/internal/encoder.py
python
Encoder.AppendSFixed32NoTag
(self, value)
Appends a signed 32-bit integer to our buffer, in little-endian byte-order.
Appends a signed 32-bit integer to our buffer, in little-endian byte-order.
[ "Appends", "a", "signed", "32", "-", "bit", "integer", "to", "our", "buffer", "in", "little", "-", "endian", "byte", "-", "order", "." ]
def AppendSFixed32NoTag(self, value): """Appends a signed 32-bit integer to our buffer, in little-endian byte-order. """ sign = (value & 0x80000000) and -1 or 0 if value >> 32 != sign: raise message.EncodeError('SFixed32 out of range: %d' % value) self._stream.AppendLittleEndian32(value & 0xffffffff)
[ "def", "AppendSFixed32NoTag", "(", "self", ",", "value", ")", ":", "sign", "=", "(", "value", "&", "0x80000000", ")", "and", "-", "1", "or", "0", "if", "value", ">>", "32", "!=", "sign", ":", "raise", "message", ".", "EncodeError", "(", "'SFixed32 out of range: %d'", "%", "value", ")", "self", ".", "_stream", ".", "AppendLittleEndian32", "(", "value", "&", "0xffffffff", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/encoder.py#L106-L113
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridInterface.GetPropertyValueAsDouble
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetPropertyValueAsDouble(*args, **kwargs)
GetPropertyValueAsDouble(self, PGPropArg id) -> double
GetPropertyValueAsDouble(self, PGPropArg id) -> double
[ "GetPropertyValueAsDouble", "(", "self", "PGPropArg", "id", ")", "-", ">", "double" ]
def GetPropertyValueAsDouble(*args, **kwargs): """GetPropertyValueAsDouble(self, PGPropArg id) -> double""" return _propgrid.PropertyGridInterface_GetPropertyValueAsDouble(*args, **kwargs)
[ "def", "GetPropertyValueAsDouble", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetPropertyValueAsDouble", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1264-L1266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/gtk/gizmos.py
python
LEDNumberCtrl.Create
(*args, **kwargs)
return _gizmos.LEDNumberCtrl_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxLED_ALIGN_LEFT|wxLED_DRAW_FADED) -> bool Do the 2nd phase and create the GUI control.
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxLED_ALIGN_LEFT|wxLED_DRAW_FADED) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "wxLED_ALIGN_LEFT|wxLED_DRAW_FADED", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxLED_ALIGN_LEFT|wxLED_DRAW_FADED) -> bool Do the 2nd phase and create the GUI control. """ return _gizmos.LEDNumberCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "LEDNumberCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L313-L320
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/last-moment-before-all-ants-fall-out-of-a-plank.py
python
Solution.getLastMoment
(self, n, left, right)
return max(max(left or [0]), n-min(right or [n]))
:type n: int :type left: List[int] :type right: List[int] :rtype: int
:type n: int :type left: List[int] :type right: List[int] :rtype: int
[ ":", "type", "n", ":", "int", ":", "type", "left", ":", "List", "[", "int", "]", ":", "type", "right", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def getLastMoment(self, n, left, right): """ :type n: int :type left: List[int] :type right: List[int] :rtype: int """ return max(max(left or [0]), n-min(right or [n]))
[ "def", "getLastMoment", "(", "self", ",", "n", ",", "left", ",", "right", ")", ":", "return", "max", "(", "max", "(", "left", "or", "[", "0", "]", ")", ",", "n", "-", "min", "(", "right", "or", "[", "n", "]", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/last-moment-before-all-ants-fall-out-of-a-plank.py#L5-L12
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
CheckBox.SetValue
(*args, **kwargs)
return _controls_.CheckBox_SetValue(*args, **kwargs)
SetValue(self, bool state) Set the state of a 2-state CheckBox. Pass True for checked, False for unchecked.
SetValue(self, bool state)
[ "SetValue", "(", "self", "bool", "state", ")" ]
def SetValue(*args, **kwargs): """ SetValue(self, bool state) Set the state of a 2-state CheckBox. Pass True for checked, False for unchecked. """ return _controls_.CheckBox_SetValue(*args, **kwargs)
[ "def", "SetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "CheckBox_SetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L385-L392
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.simple_qty
(self, simple_qty)
Sets the simple_qty of this Position. :param simple_qty: The simple_qty of this Position. # noqa: E501 :type: float
Sets the simple_qty of this Position.
[ "Sets", "the", "simple_qty", "of", "this", "Position", "." ]
def simple_qty(self, simple_qty): """Sets the simple_qty of this Position. :param simple_qty: The simple_qty of this Position. # noqa: E501 :type: float """ self._simple_qty = simple_qty
[ "def", "simple_qty", "(", "self", ",", "simple_qty", ")", ":", "self", ".", "_simple_qty", "=", "simple_qty" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L2131-L2139
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/method_count.py
python
DexStatsCollector.GetCountsByLabel
(self)
return self._counts_by_label
Returns dict of label -> {metric -> count}.
Returns dict of label -> {metric -> count}.
[ "Returns", "dict", "of", "label", "-", ">", "{", "metric", "-", ">", "count", "}", "." ]
def GetCountsByLabel(self): """Returns dict of label -> {metric -> count}.""" return self._counts_by_label
[ "def", "GetCountsByLabel", "(", "self", ")", ":", "return", "self", ".", "_counts_by_label" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/method_count.py#L63-L65
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
AcceleratorEntry.ToString
(*args, **kwargs)
return _core_.AcceleratorEntry_ToString(*args, **kwargs)
ToString(self) -> String Returns a string representation for the this accelerator. The string is formatted using the <flags>-<keycode> format where <flags> maybe a hyphen-separed list of "shift|alt|ctrl"
ToString(self) -> String
[ "ToString", "(", "self", ")", "-", ">", "String" ]
def ToString(*args, **kwargs): """ ToString(self) -> String Returns a string representation for the this accelerator. The string is formatted using the <flags>-<keycode> format where <flags> maybe a hyphen-separed list of "shift|alt|ctrl" """ return _core_.AcceleratorEntry_ToString(*args, **kwargs)
[ "def", "ToString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "AcceleratorEntry_ToString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L8960-L8969
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py
python
Style.theme_names
(self)
return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
Returns a list of all known themes.
Returns a list of all known themes.
[ "Returns", "a", "list", "of", "all", "known", "themes", "." ]
def theme_names(self): """Returns a list of all known themes.""" return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
[ "def", "theme_names", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_name", ",", "\"theme\"", ",", "\"names\"", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L512-L514
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py
python
usage
()
Print usage help and exit with an error code.
Print usage help and exit with an error code.
[ "Print", "usage", "help", "and", "exit", "with", "an", "error", "code", "." ]
def usage(): """Print usage help and exit with an error code.""" parser.print_help() sys.exit(2)
[ "def", "usage", "(", ")", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "2", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py#L42-L45
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
python/caffe/draw.py
python
get_edge_label
(layer)
return edge_label
Define edge label based on layer type.
Define edge label based on layer type.
[ "Define", "edge", "label", "based", "on", "layer", "type", "." ]
def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif layer.type == 'InnerProduct': edge_label = str(layer.inner_product_param.num_output) else: edge_label = '""' return edge_label
[ "def", "get_edge_label", "(", "layer", ")", ":", "if", "layer", ".", "type", "==", "'Data'", ":", "edge_label", "=", "'Batch '", "+", "str", "(", "layer", ".", "data_param", ".", "batch_size", ")", "elif", "layer", ".", "type", "==", "'Convolution'", "or", "layer", ".", "type", "==", "'Deconvolution'", ":", "edge_label", "=", "str", "(", "layer", ".", "convolution_param", ".", "num_output", ")", "elif", "layer", ".", "type", "==", "'InnerProduct'", ":", "edge_label", "=", "str", "(", "layer", ".", "inner_product_param", ".", "num_output", ")", "else", ":", "edge_label", "=", "'\"\"'", "return", "edge_label" ]
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/draw.py#L46-L59
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatToolbarItem.Enable
(self, enable=True)
Enables or disables the tool. :param bool `enable`: ``True`` to enable the tool, ``False`` to disable it.
Enables or disables the tool.
[ "Enables", "or", "disables", "the", "tool", "." ]
def Enable(self, enable=True): """ Enables or disables the tool. :param bool `enable`: ``True`` to enable the tool, ``False`` to disable it. """ self._enabled = enable
[ "def", "Enable", "(", "self", ",", "enable", "=", "True", ")", ":", "self", ".", "_enabled", "=", "enable" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4743-L4750
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/symtable.py
python
Symbol.is_namespace
(self)
return bool(self.__namespaces)
Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.
Returns true if name binding introduces new namespace.
[ "Returns", "true", "if", "name", "binding", "introduces", "new", "namespace", "." ]
def is_namespace(self): """Returns true if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. Note that a single name can be bound to multiple objects. If is_namespace() is true, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace. """ return bool(self.__namespaces)
[ "def", "is_namespace", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__namespaces", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/symtable.py#L210-L221
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
webvis/pydot.py
python
Graph.del_node
(self, name, index=None)
return False
Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False.
Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False.
[ "Delete", "a", "node", "from", "the", "graph", ".", "Given", "a", "node", "s", "name", "all", "node", "(", "s", ")", "with", "that", "same", "name", "will", "be", "deleted", "if", "index", "is", "not", "specified", "or", "set", "to", "None", ".", "If", "there", "are", "several", "nodes", "with", "that", "same", "name", "and", "index", "is", "given", "only", "the", "node", "in", "that", "position", "will", "be", "deleted", ".", "index", "should", "be", "an", "integer", "specifying", "the", "position", "of", "the", "node", "to", "delete", ".", "If", "index", "is", "larger", "than", "the", "number", "of", "nodes", "with", "that", "name", "no", "action", "is", "taken", ".", "If", "nodes", "are", "deleted", "it", "returns", "True", ".", "If", "no", "action", "is", "taken", "it", "returns", "False", "." ]
def del_node(self, name, index=None): """Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False. """ if isinstance(name, Node): name = name.get_name() if self.obj_dict['nodes'].has_key(name): if index is not None and index < len(self.obj_dict['nodes'][name]): del self.obj_dict['nodes'][name][index] return True else: del self.obj_dict['nodes'][name] return True return False
[ "def", "del_node", "(", "self", ",", "name", ",", "index", "=", "None", ")", ":", "if", "isinstance", "(", "name", ",", "Node", ")", ":", "name", "=", "name", ".", "get_name", "(", ")", "if", "self", ".", "obj_dict", "[", "'nodes'", "]", ".", "has_key", "(", "name", ")", ":", "if", "index", "is", "not", "None", "and", "index", "<", "len", "(", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", ")", ":", "del", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", "[", "index", "]", "return", "True", "else", ":", "del", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", "return", "True", "return", "False" ]
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/webvis/pydot.py#L1293-L1323
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/lite/tools/dataset/cropper/cropper_configure.py
python
extract_classname_data
(header_content)
return re.findall(r"(?<=class )[\w\d_]+(?=Operation : )", header_content)
Use regex to find class names in header files of data ops :param header_content: string containing header of a data op IR file :return: list of data ops found
Use regex to find class names in header files of data ops
[ "Use", "regex", "to", "find", "class", "names", "in", "header", "files", "of", "data", "ops" ]
def extract_classname_data(header_content): """ Use regex to find class names in header files of data ops :param header_content: string containing header of a data op IR file :return: list of data ops found """ return re.findall(r"(?<=class )[\w\d_]+(?=Operation : )", header_content)
[ "def", "extract_classname_data", "(", "header_content", ")", ":", "return", "re", ".", "findall", "(", "r\"(?<=class )[\\w\\d_]+(?=Operation : )\"", ",", "header_content", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/lite/tools/dataset/cropper/cropper_configure.py#L135-L142
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
SizeNotNegativeArgument.GetInvalidArg
(self, offset, index)
return ("-1", "kOutOfBounds", "GL_NO_ERROR")
overridden from SizeArgument.
overridden from SizeArgument.
[ "overridden", "from", "SizeArgument", "." ]
def GetInvalidArg(self, offset, index): """overridden from SizeArgument.""" return ("-1", "kOutOfBounds", "GL_NO_ERROR")
[ "def", "GetInvalidArg", "(", "self", ",", "offset", ",", "index", ")", ":", "return", "(", "\"-1\"", ",", "\"kOutOfBounds\"", ",", "\"GL_NO_ERROR\"", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4728-L4730
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py
python
ContentHandler.startPrefixMapping
(self, prefix, uri)
Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary. Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed.
Begin the scope of a prefix-URI Namespace mapping.
[ "Begin", "the", "scope", "of", "a", "prefix", "-", "URI", "Namespace", "mapping", "." ]
def startPrefixMapping(self, prefix, uri): """Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary. Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed."""
[ "def", "startPrefixMapping", "(", "self", ",", "prefix", ",", "uri", ")", ":" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py#L96-L117
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/feature_column_v2.py
python
make_parse_example_spec_v2
(feature_columns)
return result
Creates parsing spec dictionary from input feature_columns. The returned dictionary can be used as arg 'features' in `tf.io.parse_example`. Typical usage example: ```python # Define features and transformations feature_a = tf.feature_column.categorical_column_with_vocabulary_file(...) feature_b = tf.feature_column.numeric_column(...) feature_c_bucketized = tf.feature_column.bucketized_column( tf.feature_column.numeric_column("feature_c"), ...) feature_a_x_feature_c = tf.feature_column.crossed_column( columns=["feature_a", feature_c_bucketized], ...) feature_columns = set( [feature_b, feature_c_bucketized, feature_a_x_feature_c]) features = tf.io.parse_example( serialized=serialized_examples, features=tf.feature_column.make_parse_example_spec(feature_columns)) ``` For the above example, make_parse_example_spec would return the dict: ```python { "feature_a": parsing_ops.VarLenFeature(tf.string), "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) } ``` Args: feature_columns: An iterable containing all feature columns. All items should be instances of classes derived from `FeatureColumn`. Returns: A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` value. Raises: ValueError: If any of the given `feature_columns` is not a `FeatureColumn` instance.
Creates parsing spec dictionary from input feature_columns.
[ "Creates", "parsing", "spec", "dictionary", "from", "input", "feature_columns", "." ]
def make_parse_example_spec_v2(feature_columns): """Creates parsing spec dictionary from input feature_columns. The returned dictionary can be used as arg 'features' in `tf.io.parse_example`. Typical usage example: ```python # Define features and transformations feature_a = tf.feature_column.categorical_column_with_vocabulary_file(...) feature_b = tf.feature_column.numeric_column(...) feature_c_bucketized = tf.feature_column.bucketized_column( tf.feature_column.numeric_column("feature_c"), ...) feature_a_x_feature_c = tf.feature_column.crossed_column( columns=["feature_a", feature_c_bucketized], ...) feature_columns = set( [feature_b, feature_c_bucketized, feature_a_x_feature_c]) features = tf.io.parse_example( serialized=serialized_examples, features=tf.feature_column.make_parse_example_spec(feature_columns)) ``` For the above example, make_parse_example_spec would return the dict: ```python { "feature_a": parsing_ops.VarLenFeature(tf.string), "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) } ``` Args: feature_columns: An iterable containing all feature columns. All items should be instances of classes derived from `FeatureColumn`. Returns: A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` value. Raises: ValueError: If any of the given `feature_columns` is not a `FeatureColumn` instance. """ result = {} for column in feature_columns: if not isinstance(column, FeatureColumn): raise ValueError('All feature_columns must be FeatureColumn instances. ' 'Given: {}'.format(column)) config = column.parse_example_spec for key, value in six.iteritems(config): if key in result and value != result[key]: raise ValueError( 'feature_columns contain different parse_spec for key ' '{}. Given {} and {}'.format(key, value, result[key])) result.update(config) return result
[ "def", "make_parse_example_spec_v2", "(", "feature_columns", ")", ":", "result", "=", "{", "}", "for", "column", "in", "feature_columns", ":", "if", "not", "isinstance", "(", "column", ",", "FeatureColumn", ")", ":", "raise", "ValueError", "(", "'All feature_columns must be FeatureColumn instances. '", "'Given: {}'", ".", "format", "(", "column", ")", ")", "config", "=", "column", ".", "parse_example_spec", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "config", ")", ":", "if", "key", "in", "result", "and", "value", "!=", "result", "[", "key", "]", ":", "raise", "ValueError", "(", "'feature_columns contain different parse_spec for key '", "'{}. Given {} and {}'", ".", "format", "(", "key", ",", "value", ",", "result", "[", "key", "]", ")", ")", "result", ".", "update", "(", "config", ")", "return", "result" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L453-L511
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixer_util.py
python
is_list
(node)
return (isinstance(node, Node) and len(node.children) > 1 and isinstance(node.children[0], Leaf) and isinstance(node.children[-1], Leaf) and node.children[0].value == u"[" and node.children[-1].value == u"]")
Does the node represent a list literal?
Does the node represent a list literal?
[ "Does", "the", "node", "represent", "a", "list", "literal?" ]
def is_list(node): """Does the node represent a list literal?""" return (isinstance(node, Node) and len(node.children) > 1 and isinstance(node.children[0], Leaf) and isinstance(node.children[-1], Leaf) and node.children[0].value == u"[" and node.children[-1].value == u"]")
[ "def", "is_list", "(", "node", ")", ":", "return", "(", "isinstance", "(", "node", ",", "Node", ")", "and", "len", "(", "node", ".", "children", ")", ">", "1", "and", "isinstance", "(", "node", ".", "children", "[", "0", "]", ",", "Leaf", ")", "and", "isinstance", "(", "node", ".", "children", "[", "-", "1", "]", ",", "Leaf", ")", "and", "node", ".", "children", "[", "0", "]", ".", "value", "==", "u\"[\"", "and", "node", ".", "children", "[", "-", "1", "]", ".", "value", "==", "u\"]\"", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixer_util.py#L149-L156
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
BaseNode.makefile
(self, marks=None)
Print a Makefile for this node.
Print a Makefile for this node.
[ "Print", "a", "Makefile", "for", "this", "node", "." ]
def makefile(self, marks=None): """Print a Makefile for this node.""" from pipes import quote if self.builder is None: return if marks is None: marks = set() if str(self.name()) in marks: return else: marks.add(str(self.name())) print('%s: %s' % (self.makefile_name(), ' '.join(map(lambda n: n.makefile_name(), self.dependencies)))) cmd = self.builder.command if cmd is not None: if isinstance(self, Node): print('\t@mkdir -p %s' % self.path().dirname()) if not isinstance(cmd, tuple): cmd = (cmd,) for c in cmd: print('\t%s' % ' '.join( map(lambda a: quote(str(a)).replace('$', '$$'), c))) print('') for dependency in self.dependencies: dependency.makefile(marks)
[ "def", "makefile", "(", "self", ",", "marks", "=", "None", ")", ":", "from", "pipes", "import", "quote", "if", "self", ".", "builder", "is", "None", ":", "return", "if", "marks", "is", "None", ":", "marks", "=", "set", "(", ")", "if", "str", "(", "self", ".", "name", "(", ")", ")", "in", "marks", ":", "return", "else", ":", "marks", ".", "add", "(", "str", "(", "self", ".", "name", "(", ")", ")", ")", "print", "(", "'%s: %s'", "%", "(", "self", ".", "makefile_name", "(", ")", ",", "' '", ".", "join", "(", "map", "(", "lambda", "n", ":", "n", ".", "makefile_name", "(", ")", ",", "self", ".", "dependencies", ")", ")", ")", ")", "cmd", "=", "self", ".", "builder", ".", "command", "if", "cmd", "is", "not", "None", ":", "if", "isinstance", "(", "self", ",", "Node", ")", ":", "print", "(", "'\\t@mkdir -p %s'", "%", "self", ".", "path", "(", ")", ".", "dirname", "(", ")", ")", "if", "not", "isinstance", "(", "cmd", ",", "tuple", ")", ":", "cmd", "=", "(", "cmd", ",", ")", "for", "c", "in", "cmd", ":", "print", "(", "'\\t%s'", "%", "' '", ".", "join", "(", "map", "(", "lambda", "a", ":", "quote", "(", "str", "(", "a", ")", ")", ".", "replace", "(", "'$'", ",", "'$$'", ")", ",", "c", ")", ")", ")", "print", "(", "''", ")", "for", "dependency", "in", "self", ".", "dependencies", ":", "dependency", ".", "makefile", "(", "marks", ")" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L1528-L1553
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/ma/core.py
python
fix_invalid
(a, mask=nomask, copy=True, fill_value=None)
return a
Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data = [-- -1.0 nan inf], mask = [ True False False False], fill_value = 1e+20) >>> np.ma.fix_invalid(x) masked_array(data = [-- -1.0 -- --], mask = [ True False True True], fill_value = 1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.00000000e+00, -1.00000000e+00, 1.00000000e+20, 1.00000000e+20]) >>> x.data array([ 1., -1., NaN, Inf])
Return input with invalid data masked and replaced by a fill value.
[ "Return", "input", "with", "invalid", "data", "masked", "and", "replaced", "by", "a", "fill", "value", "." ]
def fix_invalid(a, mask=nomask, copy=True, fill_value=None): """ Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data = [-- -1.0 nan inf], mask = [ True False False False], fill_value = 1e+20) >>> np.ma.fix_invalid(x) masked_array(data = [-- -1.0 -- --], mask = [ True False True True], fill_value = 1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.00000000e+00, -1.00000000e+00, 1.00000000e+20, 1.00000000e+20]) >>> x.data array([ 1., -1., NaN, Inf]) """ a = masked_array(a, copy=copy, mask=mask, subok=True) #invalid = (numpy.isnan(a._data) | numpy.isinf(a._data)) invalid = np.logical_not(np.isfinite(a._data)) if not invalid.any(): return a a._mask |= invalid if fill_value is None: fill_value = a.fill_value a._data[invalid] = fill_value return a
[ "def", "fix_invalid", "(", "a", ",", "mask", "=", "nomask", ",", "copy", "=", "True", ",", "fill_value", "=", "None", ")", ":", "a", "=", "masked_array", "(", "a", ",", "copy", "=", "copy", ",", "mask", "=", "mask", ",", "subok", "=", "True", ")", "#invalid = (numpy.isnan(a._data) | numpy.isinf(a._data))", "invalid", "=", "np", ".", "logical_not", "(", "np", ".", "isfinite", "(", "a", ".", "_data", ")", ")", "if", "not", "invalid", ".", "any", "(", ")", ":", "return", "a", "a", ".", "_mask", "|=", "invalid", "if", "fill_value", "is", "None", ":", "fill_value", "=", "a", ".", "fill_value", "a", ".", "_data", "[", "invalid", "]", "=", "fill_value", "return", "a" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L658-L713
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/imports.py
python
PlainTextHandler.__init__
(self, dad)
Machine boot
Machine boot
[ "Machine", "boot" ]
def __init__(self, dad): """Machine boot""" self.dad = dad
[ "def", "__init__", "(", "self", ",", "dad", ")", ":", "self", ".", "dad", "=", "dad" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/imports.py#L2134-L2136
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
caffe/scripts/cpp_lint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "(", "'test.cc'", ",", "'regtest.cc'", ",", "'unittest.cc'", ",", "'inl.h'", ",", "'impl.h'", ",", "'internal.h'", ")", ":", "if", "(", "filename", ".", "endswith", "(", "suffix", ")", "and", "len", "(", "filename", ")", ">", "len", "(", "suffix", ")", "and", "filename", "[", "-", "len", "(", "suffix", ")", "-", "1", "]", "in", "(", "'-'", ",", "'_'", ")", ")", ":", "return", "filename", "[", ":", "-", "len", "(", "suffix", ")", "-", "1", "]", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]" ]
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/caffe/scripts/cpp_lint.py#L3576-L3600
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/gen_vehicle_protocol/gen_protocols.py
python
gen_report_value_offset_precision
(var, protocol)
return impl + " return ret;\n"
doc string:
doc string:
[ "doc", "string", ":" ]
def gen_report_value_offset_precision(var, protocol): """ doc string: """ impl = "" if var["is_signed_var"]: fmt = "\n x <<= %d;\n x >>= %d;\n" # x is an int32_t var shift_bit = 32 - var["len"] impl = impl + fmt % (shift_bit, shift_bit) returntype = var["type"] if var["type"] == "enum": returntype = protocol["name"].capitalize() + "::" + var["name"].capitalize( ) + "Type" impl = impl + "\n " + returntype + " ret = " if var["type"] == "enum": impl = impl + " static_cast<" + returntype + ">(x);\n" else: impl = impl + "x" if var["precision"] != 1.0: impl = impl + " * %f" % var["precision"] if var["offset"] != 0.0: impl = impl + " + %f" % (var["offset"]) impl = impl + ";\n" return impl + " return ret;\n"
[ "def", "gen_report_value_offset_precision", "(", "var", ",", "protocol", ")", ":", "impl", "=", "\"\"", "if", "var", "[", "\"is_signed_var\"", "]", ":", "fmt", "=", "\"\\n x <<= %d;\\n x >>= %d;\\n\"", "# x is an int32_t var", "shift_bit", "=", "32", "-", "var", "[", "\"len\"", "]", "impl", "=", "impl", "+", "fmt", "%", "(", "shift_bit", ",", "shift_bit", ")", "returntype", "=", "var", "[", "\"type\"", "]", "if", "var", "[", "\"type\"", "]", "==", "\"enum\"", ":", "returntype", "=", "protocol", "[", "\"name\"", "]", ".", "capitalize", "(", ")", "+", "\"::\"", "+", "var", "[", "\"name\"", "]", ".", "capitalize", "(", ")", "+", "\"Type\"", "impl", "=", "impl", "+", "\"\\n \"", "+", "returntype", "+", "\" ret = \"", "if", "var", "[", "\"type\"", "]", "==", "\"enum\"", ":", "impl", "=", "impl", "+", "\" static_cast<\"", "+", "returntype", "+", "\">(x);\\n\"", "else", ":", "impl", "=", "impl", "+", "\"x\"", "if", "var", "[", "\"precision\"", "]", "!=", "1.0", ":", "impl", "=", "impl", "+", "\" * %f\"", "%", "var", "[", "\"precision\"", "]", "if", "var", "[", "\"offset\"", "]", "!=", "0.0", ":", "impl", "=", "impl", "+", "\" + %f\"", "%", "(", "var", "[", "\"offset\"", "]", ")", "impl", "=", "impl", "+", "\";\\n\"", "return", "impl", "+", "\" return ret;\\n\"" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/gen_vehicle_protocol/gen_protocols.py#L108-L134
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/wire_format.py
python
ZigZagDecode
(value)
return (value >> 1) ^ (~0)
Inverse of ZigZagEncode().
Inverse of ZigZagEncode().
[ "Inverse", "of", "ZigZagEncode", "()", "." ]
def ZigZagDecode(value): """Inverse of ZigZagEncode().""" if not value & 0x1: return value >> 1 return (value >> 1) ^ (~0)
[ "def", "ZigZagDecode", "(", "value", ")", ":", "if", "not", "value", "&", "0x1", ":", "return", "value", ">>", "1", "return", "(", "value", ">>", "1", ")", "^", "(", "~", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/wire_format.py#L110-L114
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pep517/wrappers.py
python
Pep517HookCaller.get_requires_for_build_sdist
(self, config_settings=None)
return self._call_hook('get_requires_for_build_sdist', { 'config_settings': config_settings })
Identify packages required for building a wheel Returns a list of dependency specifications, e.g.: ["setuptools >= 26"] This does not include requirements specified in pyproject.toml. It returns the result of calling the equivalently named hook in a subprocess.
Identify packages required for building a wheel
[ "Identify", "packages", "required", "for", "building", "a", "wheel" ]
def get_requires_for_build_sdist(self, config_settings=None): """Identify packages required for building a wheel Returns a list of dependency specifications, e.g.: ["setuptools >= 26"] This does not include requirements specified in pyproject.toml. It returns the result of calling the equivalently named hook in a subprocess. """ return self._call_hook('get_requires_for_build_sdist', { 'config_settings': config_settings })
[ "def", "get_requires_for_build_sdist", "(", "self", ",", "config_settings", "=", "None", ")", ":", "return", "self", ".", "_call_hook", "(", "'get_requires_for_build_sdist'", ",", "{", "'config_settings'", ":", "config_settings", "}", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pep517/wrappers.py#L109-L121
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/tvm/contrib/rpc.py
python
RPCSession.metal
(self, dev_id=0)
return self.context(8, dev_id)
Construct remote Metal device.
Construct remote Metal device.
[ "Construct", "remote", "Metal", "device", "." ]
def metal(self, dev_id=0): """Construct remote Metal device.""" return self.context(8, dev_id)
[ "def", "metal", "(", "self", ",", "dev_id", "=", "0", ")", ":", "return", "self", ".", "context", "(", "8", ",", "dev_id", ")" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/contrib/rpc.py#L295-L297
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatnotebook.py
python
FNBRenderer.DrawDropDownArrow
(self, pageContainer, dc)
Draws the drop-down arrow in the navigation area. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`DC`.
Draws the drop-down arrow in the navigation area.
[ "Draws", "the", "drop", "-", "down", "arrow", "in", "the", "navigation", "area", "." ]
def DrawDropDownArrow(self, pageContainer, dc): """ Draws the drop-down arrow in the navigation area. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`DC`. """ pc = pageContainer # Check if this style is enabled agwStyle = pc.GetParent().GetAGWWindowStyleFlag() if not agwStyle & FNB_DROPDOWN_TABS_LIST: return # Make sure that there are pages in the container if not pc._pagesInfoVec: return if pc._nArrowDownButtonStatus == FNB_BTN_HOVER: downBmp = wx.BitmapFromXPMData(down_arrow_hilite_xpm) elif pc._nArrowDownButtonStatus == FNB_BTN_PRESSED: downBmp = wx.BitmapFromXPMData(down_arrow_pressed_xpm) else: downBmp = wx.BitmapFromXPMData(down_arrow_xpm) downBmp.SetMask(wx.Mask(downBmp, MASK_COLOUR)) # erase old bitmap posx = self.GetDropArrowButtonPos(pc) self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14)) # Draw the new bitmap dc.DrawBitmap(downBmp, posx, 6, True)
[ "def", "DrawDropDownArrow", "(", "self", ",", "pageContainer", ",", "dc", ")", ":", "pc", "=", "pageContainer", "# Check if this style is enabled", "agwStyle", "=", "pc", ".", "GetParent", "(", ")", ".", "GetAGWWindowStyleFlag", "(", ")", "if", "not", "agwStyle", "&", "FNB_DROPDOWN_TABS_LIST", ":", "return", "# Make sure that there are pages in the container", "if", "not", "pc", ".", "_pagesInfoVec", ":", "return", "if", "pc", ".", "_nArrowDownButtonStatus", "==", "FNB_BTN_HOVER", ":", "downBmp", "=", "wx", ".", "BitmapFromXPMData", "(", "down_arrow_hilite_xpm", ")", "elif", "pc", ".", "_nArrowDownButtonStatus", "==", "FNB_BTN_PRESSED", ":", "downBmp", "=", "wx", ".", "BitmapFromXPMData", "(", "down_arrow_pressed_xpm", ")", "else", ":", "downBmp", "=", "wx", ".", "BitmapFromXPMData", "(", "down_arrow_xpm", ")", "downBmp", ".", "SetMask", "(", "wx", ".", "Mask", "(", "downBmp", ",", "MASK_COLOUR", ")", ")", "# erase old bitmap", "posx", "=", "self", ".", "GetDropArrowButtonPos", "(", "pc", ")", "self", ".", "DrawArrowAccordingToState", "(", "dc", ",", "pc", ",", "wx", ".", "Rect", "(", "posx", ",", "6", ",", "16", ",", "14", ")", ")", "# Draw the new bitmap", "dc", ".", "DrawBitmap", "(", "downBmp", ",", "posx", ",", "6", ",", "True", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L1931-L1964
blockchain-foundry/gcoin-community
c8da4d550efd5f6eb9c54af4fdfdc0451689f94f
contrib/devtools/update-translations.py
python
remove_invalid_characters
(s)
return FIX_RE.sub(b'', s)
Remove invalid characters from translation string
Remove invalid characters from translation string
[ "Remove", "invalid", "characters", "from", "translation", "string" ]
def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s)
[ "def", "remove_invalid_characters", "(", "s", ")", ":", "return", "FIX_RE", ".", "sub", "(", "b''", ",", "s", ")" ]
https://github.com/blockchain-foundry/gcoin-community/blob/c8da4d550efd5f6eb9c54af4fdfdc0451689f94f/contrib/devtools/update-translations.py#L105-L107
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
AuiToolBar.GetArtProvider
(self)
return self._art
Returns the current art provider being used.
Returns the current art provider being used.
[ "Returns", "the", "current", "art", "provider", "being", "used", "." ]
def GetArtProvider(self): """ Returns the current art provider being used. """ return self._art
[ "def", "GetArtProvider", "(", "self", ")", ":", "return", "self", ".", "_art" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L1713-L1716
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/sponge_ops.py
python
PMEExcludedForce.__init__
(self, atom_numbers, excluded_numbers, beta)
Initialize PMEExcludedForce.
Initialize PMEExcludedForce.
[ "Initialize", "PMEExcludedForce", "." ]
def __init__(self, atom_numbers, excluded_numbers, beta): """Initialize PMEExcludedForce.""" validator.check_value_type('atom_numbers', atom_numbers, int, self.name) validator.check_value_type('excluded_numbers', excluded_numbers, int, self.name) validator.check_value_type('beta', beta, float, self.name) self.atom_numbers = atom_numbers self.excluded_numbers = excluded_numbers self.beta = beta self.init_prim_io_names( inputs=['uint_crd', 'sacler', 'charge', 'excluded_list_start', 'excluded_list', 'excluded_atom_numbers'], outputs=['force']) self.add_prim_attr('atom_numbers', self.atom_numbers) self.add_prim_attr('excluded_numbers', self.excluded_numbers) self.add_prim_attr('beta', self.beta)
[ "def", "__init__", "(", "self", ",", "atom_numbers", ",", "excluded_numbers", ",", "beta", ")", ":", "validator", ".", "check_value_type", "(", "'atom_numbers'", ",", "atom_numbers", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'excluded_numbers'", ",", "excluded_numbers", ",", "int", ",", "self", ".", "name", ")", "validator", ".", "check_value_type", "(", "'beta'", ",", "beta", ",", "float", ",", "self", ".", "name", ")", "self", ".", "atom_numbers", "=", "atom_numbers", "self", ".", "excluded_numbers", "=", "excluded_numbers", "self", ".", "beta", "=", "beta", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'uint_crd'", ",", "'sacler'", ",", "'charge'", ",", "'excluded_list_start'", ",", "'excluded_list'", ",", "'excluded_atom_numbers'", "]", ",", "outputs", "=", "[", "'force'", "]", ")", "self", ".", "add_prim_attr", "(", "'atom_numbers'", ",", "self", ".", "atom_numbers", ")", "self", ".", "add_prim_attr", "(", "'excluded_numbers'", ",", "self", ".", "excluded_numbers", ")", "self", ".", "add_prim_attr", "(", "'beta'", ",", "self", ".", "beta", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/sponge_ops.py#L2078-L2091
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_PolicyNameHash_REQUEST.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ buf.writeSizedByteBuf(self.nameHash)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "nameHash", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L14821-L14823
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/pygments.py
python
style_from_pygments_cls
(pygments_style_cls: Type["PygmentsStyle"])
return style_from_pygments_dict(pygments_style_cls.styles)
Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary. Example:: from prompt_toolkit.styles.from_pygments import style_from_pygments_cls from pygments.styles import get_style_by_name style = style_from_pygments_cls(get_style_by_name('monokai')) :param pygments_style_cls: Pygments style class to start from.
Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary.
[ "Shortcut", "to", "create", "a", ":", "class", ":", ".", "Style", "instance", "from", "a", "Pygments", "style", "class", "and", "a", "style", "dictionary", "." ]
def style_from_pygments_cls(pygments_style_cls: Type["PygmentsStyle"]) -> Style: """ Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary. Example:: from prompt_toolkit.styles.from_pygments import style_from_pygments_cls from pygments.styles import get_style_by_name style = style_from_pygments_cls(get_style_by_name('monokai')) :param pygments_style_cls: Pygments style class to start from. """ # Import inline. from pygments.style import Style as PygmentsStyle assert issubclass(pygments_style_cls, PygmentsStyle) return style_from_pygments_dict(pygments_style_cls.styles)
[ "def", "style_from_pygments_cls", "(", "pygments_style_cls", ":", "Type", "[", "\"PygmentsStyle\"", "]", ")", "->", "Style", ":", "# Import inline.", "from", "pygments", ".", "style", "import", "Style", "as", "PygmentsStyle", "assert", "issubclass", "(", "pygments_style_cls", ",", "PygmentsStyle", ")", "return", "style_from_pygments_dict", "(", "pygments_style_cls", ".", "styles", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/pygments.py#L25-L43
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.local_position_ned_encode
(self, time_boot_ms, x, y, z, vx, vy, vz)
return msg
The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) vx : X Speed (float) vy : Y Speed (float) vz : Z Speed (float)
The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention)
[ "The", "filtered", "local", "position", "(", "e", ".", "g", ".", "fused", "computer", "vision", "and", "accelerometers", ")", ".", "Coordinate", "frame", "is", "right", "-", "handed", "Z", "-", "axis", "down", "(", "aeronautical", "frame", "NED", "/", "north", "-", "east", "-", "down", "convention", ")" ]
def local_position_ned_encode(self, time_boot_ms, x, y, z, vx, vy, vz): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east-down convention) time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) x : X Position (float) y : Y Position (float) z : Z Position (float) vx : X Speed (float) vy : Y Speed (float) vz : Z Speed (float) ''' msg = MAVLink_local_position_ned_message(time_boot_ms, x, y, z, vx, vy, vz) msg.pack(self) return msg
[ "def", "local_position_ned_encode", "(", "self", ",", "time_boot_ms", ",", "x", ",", "y", ",", "z", ",", "vx", ",", "vy", ",", "vz", ")", ":", "msg", "=", "MAVLink_local_position_ned_message", "(", "time_boot_ms", ",", "x", ",", "y", ",", "z", ",", "vx", ",", "vy", ",", "vz", ")", "msg", ".", "pack", "(", "self", ")", "return", "msg" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3113-L3131
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/FluidDynamicsApplication/python_scripts/cube_mesher.py
python
box_data.get_id
(self, ix, iy, iz)
return 1 + ix + (self.nx() + 1) * iy + (self.nx() + 1) * (self.ny() + 1)*iz
Id for the nth node in each direction (starting from 1).
Id for the nth node in each direction (starting from 1).
[ "Id", "for", "the", "nth", "node", "in", "each", "direction", "(", "starting", "from", "1", ")", "." ]
def get_id(self, ix, iy, iz): """ Id for the nth node in each direction (starting from 1).""" return 1 + ix + (self.nx() + 1) * iy + (self.nx() + 1) * (self.ny() + 1)*iz
[ "def", "get_id", "(", "self", ",", "ix", ",", "iy", ",", "iz", ")", ":", "return", "1", "+", "ix", "+", "(", "self", ".", "nx", "(", ")", "+", "1", ")", "*", "iy", "+", "(", "self", ".", "nx", "(", ")", "+", "1", ")", "*", "(", "self", ".", "ny", "(", ")", "+", "1", ")", "*", "iz" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/FluidDynamicsApplication/python_scripts/cube_mesher.py#L58-L60
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/pubsub.py
python
_WeakMethod.__hash__
(self)
return hash(self.fun)
Hash is an optimization for dict searches, it need not return different numbers for every different object. Some objects are not hashable (eg objects of classes derived from dict) so no hash(objRef()) in there, and hash(self.cls) would only be useful in the rare case where instance method was rebound.
Hash is an optimization for dict searches, it need not return different numbers for every different object. Some objects are not hashable (eg objects of classes derived from dict) so no hash(objRef()) in there, and hash(self.cls) would only be useful in the rare case where instance method was rebound.
[ "Hash", "is", "an", "optimization", "for", "dict", "searches", "it", "need", "not", "return", "different", "numbers", "for", "every", "different", "object", ".", "Some", "objects", "are", "not", "hashable", "(", "eg", "objects", "of", "classes", "derived", "from", "dict", ")", "so", "no", "hash", "(", "objRef", "()", ")", "in", "there", "and", "hash", "(", "self", ".", "cls", ")", "would", "only", "be", "useful", "in", "the", "rare", "case", "where", "instance", "method", "was", "rebound", "." ]
def __hash__(self): """Hash is an optimization for dict searches, it need not return different numbers for every different object. Some objects are not hashable (eg objects of classes derived from dict) so no hash(objRef()) in there, and hash(self.cls) would only be useful in the rare case where instance method was rebound. """ return hash(self.fun)
[ "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "self", ".", "fun", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pubsub.py#L178-L184
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
maximum
(left, right)
Returns element-wise maximum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Parameters --------- left : Symbol or scalar First symbol to be compared. right : Symbol or scalar Second symbol to be compared. Returns ------- Symbol or scalar The element-wise maximum of the input symbols. Examples -------- >>> mx.sym.maximum(2, 3.5) 3.5 >>> x = mx.sym.Variable('x') >>> y = mx.sym.Variable('y') >>> z = mx.sym.maximum(x, 4) >>> z.eval(x=mx.nd.array([3,5,2,10]))[0].asnumpy() array([ 4., 5., 4., 10.], dtype=float32) >>> z = mx.sym.maximum(x, y) >>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy() array([ 10., 4.], dtype=float32)
Returns element-wise maximum of the input elements.
[ "Returns", "element", "-", "wise", "maximum", "of", "the", "input", "elements", "." ]
def maximum(left, right): """Returns element-wise maximum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Parameters --------- left : Symbol or scalar First symbol to be compared. right : Symbol or scalar Second symbol to be compared. Returns ------- Symbol or scalar The element-wise maximum of the input symbols. Examples -------- >>> mx.sym.maximum(2, 3.5) 3.5 >>> x = mx.sym.Variable('x') >>> y = mx.sym.Variable('y') >>> z = mx.sym.maximum(x, 4) >>> z.eval(x=mx.nd.array([3,5,2,10]))[0].asnumpy() array([ 4., 5., 4., 10.], dtype=float32) >>> z = mx.sym.maximum(x, y) >>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy() array([ 10., 4.], dtype=float32) """ if isinstance(left, Symbol) and isinstance(right, Symbol): return _internal._Maximum(left, right) if isinstance(left, Symbol) and isinstance(right, Number): return _internal._MaximumScalar(left, scalar=right) if isinstance(left, Number) and isinstance(right, Symbol): return _internal._MaximumScalar(right, scalar=left) if isinstance(left, Number) and isinstance(right, Number): return left if left > right else right else: raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right))))
[ "def", "maximum", "(", "left", ",", "right", ")", ":", "if", "isinstance", "(", "left", ",", "Symbol", ")", "and", "isinstance", "(", "right", ",", "Symbol", ")", ":", "return", "_internal", ".", "_Maximum", "(", "left", ",", "right", ")", "if", "isinstance", "(", "left", ",", "Symbol", ")", "and", "isinstance", "(", "right", ",", "Number", ")", ":", "return", "_internal", ".", "_MaximumScalar", "(", "left", ",", "scalar", "=", "right", ")", "if", "isinstance", "(", "left", ",", "Number", ")", "and", "isinstance", "(", "right", ",", "Symbol", ")", ":", "return", "_internal", ".", "_MaximumScalar", "(", "right", ",", "scalar", "=", "left", ")", "if", "isinstance", "(", "left", ",", "Number", ")", "and", "isinstance", "(", "right", ",", "Number", ")", ":", "return", "left", "if", "left", ">", "right", "else", "right", "else", ":", "raise", "TypeError", "(", "'types (%s, %s) not supported'", "%", "(", "str", "(", "type", "(", "left", ")", ")", ",", "str", "(", "type", "(", "right", ")", ")", ")", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L2956-L2995
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageChops.py
python
duplicate
(image)
return image.copy()
Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. :rtype: :py:class:`~PIL.Image.Image`
Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
[ "Copy", "a", "channel", ".", "Alias", "for", ":", "py", ":", "meth", ":", "PIL", ".", "Image", ".", "Image", ".", "copy", "." ]
def duplicate(image): """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. :rtype: :py:class:`~PIL.Image.Image` """ return image.copy()
[ "def", "duplicate", "(", "image", ")", ":", "return", "image", ".", "copy", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageChops.py#L30-L36
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py
python
PlatformInfo.target_is_x86
(self)
return self.target_cpu == 'x86'
Return True if target CPU is x86 32 bits.. Return ------ bool CPU is x86 32 bits
Return True if target CPU is x86 32 bits..
[ "Return", "True", "if", "target", "CPU", "is", "x86", "32", "bits", ".." ]
def target_is_x86(self): """ Return True if target CPU is x86 32 bits.. Return ------ bool CPU is x86 32 bits """ return self.target_cpu == 'x86'
[ "def", "target_is_x86", "(", "self", ")", ":", "return", "self", ".", "target_cpu", "==", "'x86'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py#L395-L404
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/compiler/xla/python/xla_client.py
python
execute_with_python_values
(executable, arguments, backend)
return [x.to_py() for x in outputs]
Execute on one replica with Python values as arguments and output.
Execute on one replica with Python values as arguments and output.
[ "Execute", "on", "one", "replica", "with", "Python", "values", "as", "arguments", "and", "output", "." ]
def execute_with_python_values(executable, arguments, backend): """Execute on one replica with Python values as arguments and output.""" def put(arg): return backend.buffer_from_pyval(arg, device=executable.local_devices()[0]) arguments = [put(arg) for arg in arguments] outputs = executable.execute(arguments) return [x.to_py() for x in outputs]
[ "def", "execute_with_python_values", "(", "executable", ",", "arguments", ",", "backend", ")", ":", "def", "put", "(", "arg", ")", ":", "return", "backend", ".", "buffer_from_pyval", "(", "arg", ",", "device", "=", "executable", ".", "local_devices", "(", ")", "[", "0", "]", ")", "arguments", "=", "[", "put", "(", "arg", ")", "for", "arg", "in", "arguments", "]", "outputs", "=", "executable", ".", "execute", "(", "arguments", ")", "return", "[", "x", ".", "to_py", "(", ")", "for", "x", "in", "outputs", "]" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/compiler/xla/python/xla_client.py#L306-L314
jeog/TOSDataBridge
6a5a08ca5cf3883db1f12e9bc89ef374d098df5a
python/tosdb/_common.py
python
_TOSDB_DataBlock.topics
()
Returns the topics currently in the block (and not pre-cached). topics(self, str_max=MAX_STR_SZ) str_max :: int :: maximum length of topic strings returned returns -> list of str throws TOSDB_CLibError
Returns the topics currently in the block (and not pre-cached). topics(self, str_max=MAX_STR_SZ) str_max :: int :: maximum length of topic strings returned returns -> list of str
[ "Returns", "the", "topics", "currently", "in", "the", "block", "(", "and", "not", "pre", "-", "cached", ")", ".", "topics", "(", "self", "str_max", "=", "MAX_STR_SZ", ")", "str_max", "::", "int", "::", "maximum", "length", "of", "topic", "strings", "returned", "returns", "-", ">", "list", "of", "str" ]
def topics(): """ Returns the topics currently in the block (and not pre-cached). topics(self, str_max=MAX_STR_SZ) str_max :: int :: maximum length of topic strings returned returns -> list of str throws TOSDB_CLibError """ pass
[ "def", "topics", "(", ")", ":", "pass" ]
https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/_common.py#L139-L150
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
python
Logger.findCaller
(self)
return rv
Find the stack frame of the caller so that we can note the source file name, line number and function name.
Find the stack frame of the caller so that we can note the source file name, line number and function name.
[ "Find", "the", "stack", "frame", "of", "the", "caller", "so", "that", "we", "can", "note", "the", "source", "file", "name", "line", "number", "and", "function", "name", "." ]
def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue rv = (co.co_filename, f.f_lineno, co.co_name) break return rv
[ "def", "findCaller", "(", "self", ")", ":", "f", "=", "currentframe", "(", ")", "#On some versions of IronPython, currentframe() returns None if", "#IronPython isn't run with -X:Frames.", "if", "f", "is", "not", "None", ":", "f", "=", "f", ".", "f_back", "rv", "=", "\"(unknown file)\"", ",", "0", ",", "\"(unknown function)\"", "while", "hasattr", "(", "f", ",", "\"f_code\"", ")", ":", "co", "=", "f", ".", "f_code", "filename", "=", "os", ".", "path", ".", "normcase", "(", "co", ".", "co_filename", ")", "if", "filename", "==", "_srcfile", ":", "f", "=", "f", ".", "f_back", "continue", "rv", "=", "(", "co", ".", "co_filename", ",", "f", ".", "f_lineno", ",", "co", ".", "co_name", ")", "break", "return", "rv" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L1215-L1234
google/iree
1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76
llvm-external-projects/iree-dialects/python/iree/compiler/dialects/iree_pydm/importer/intrinsic_def.py
python
def_pattern_call_intrinsic
(match_generic: Sequence[Any] = (), match_specific: Sequence[Any] = ())
return IrPatternCallIntrinsic()
Defines a multi-function call intrinsic.
Defines a multi-function call intrinsic.
[ "Defines", "a", "multi", "-", "function", "call", "intrinsic", "." ]
def def_pattern_call_intrinsic(match_generic: Sequence[Any] = (), match_specific: Sequence[Any] = ()): """Defines a multi-function call intrinsic.""" def _extract_symbol_intrinsics( matches: Sequence[Any]) -> Sequence[FuncProvidingIntrinsic]: names = [] for m in matches: assert isinstance(m, FuncProvidingIntrinsic), ( f"Match functions for a def_multi_func_intrinsic must be " f"a FuncProvidingIntrinsic. Got: {m}") names.append(m) return names generic_intrinsics = _extract_symbol_intrinsics(match_generic) specific_intrinsics = _extract_symbol_intrinsics(match_specific) class IrPatternCallIntrinsic(Intrinsic): def emit_call(self, stage: ImportStage, args: Sequence[ir.Value], keywords: Sequence[Any]) -> ir.Value: ic = stage.ic if keywords: ic.abort(f"{self} only supports positional arguments") generic_symbol_names = [ i.get_or_create_provided_func_symbol(stage) for i in generic_intrinsics ] specific_symbol_names = [ i.get_or_create_provided_func_symbol(stage) for i in specific_intrinsics ] with ic.ip, ic.loc: generic_attrs = ir.ArrayAttr.get( [ir.FlatSymbolRefAttr.get(s) for s in generic_symbol_names]) specific_attrs = ir.ArrayAttr.get( [ir.FlatSymbolRefAttr.get(s) for s in specific_symbol_names]) exc_result, call_result = d.PatternMatchCallOp( d.ExceptionResultType.get(), d.ObjectType.get(), generic_attrs, specific_attrs, args).results d.RaiseOnFailureOp(exc_result) return call_result def __repr__(self): return (f"<pattern call generic={generic_intrinsics}, " f"specific={specific_intrinsics}>") return IrPatternCallIntrinsic()
[ "def", "def_pattern_call_intrinsic", "(", "match_generic", ":", "Sequence", "[", "Any", "]", "=", "(", ")", ",", "match_specific", ":", "Sequence", "[", "Any", "]", "=", "(", ")", ")", ":", "def", "_extract_symbol_intrinsics", "(", "matches", ":", "Sequence", "[", "Any", "]", ")", "->", "Sequence", "[", "FuncProvidingIntrinsic", "]", ":", "names", "=", "[", "]", "for", "m", "in", "matches", ":", "assert", "isinstance", "(", "m", ",", "FuncProvidingIntrinsic", ")", ",", "(", "f\"Match functions for a def_multi_func_intrinsic must be \"", "f\"a FuncProvidingIntrinsic. Got: {m}\"", ")", "names", ".", "append", "(", "m", ")", "return", "names", "generic_intrinsics", "=", "_extract_symbol_intrinsics", "(", "match_generic", ")", "specific_intrinsics", "=", "_extract_symbol_intrinsics", "(", "match_specific", ")", "class", "IrPatternCallIntrinsic", "(", "Intrinsic", ")", ":", "def", "emit_call", "(", "self", ",", "stage", ":", "ImportStage", ",", "args", ":", "Sequence", "[", "ir", ".", "Value", "]", ",", "keywords", ":", "Sequence", "[", "Any", "]", ")", "->", "ir", ".", "Value", ":", "ic", "=", "stage", ".", "ic", "if", "keywords", ":", "ic", ".", "abort", "(", "f\"{self} only supports positional arguments\"", ")", "generic_symbol_names", "=", "[", "i", ".", "get_or_create_provided_func_symbol", "(", "stage", ")", "for", "i", "in", "generic_intrinsics", "]", "specific_symbol_names", "=", "[", "i", ".", "get_or_create_provided_func_symbol", "(", "stage", ")", "for", "i", "in", "specific_intrinsics", "]", "with", "ic", ".", "ip", ",", "ic", ".", "loc", ":", "generic_attrs", "=", "ir", ".", "ArrayAttr", ".", "get", "(", "[", "ir", ".", "FlatSymbolRefAttr", ".", "get", "(", "s", ")", "for", "s", "in", "generic_symbol_names", "]", ")", "specific_attrs", "=", "ir", ".", "ArrayAttr", ".", "get", "(", "[", "ir", ".", "FlatSymbolRefAttr", ".", "get", "(", "s", ")", "for", "s", "in", "specific_symbol_names", "]", ")", "exc_result", ",", "call_result", "=", "d", ".", "PatternMatchCallOp", "(", "d", ".", "ExceptionResultType", ".", "get", "(", ")", ",", "d", ".", "ObjectType", ".", "get", "(", ")", ",", "generic_attrs", ",", "specific_attrs", ",", "args", ")", ".", "results", "d", ".", "RaiseOnFailureOp", "(", "exc_result", ")", "return", "call_result", "def", "__repr__", "(", "self", ")", ":", "return", "(", "f\"<pattern call generic={generic_intrinsics}, \"", "f\"specific={specific_intrinsics}>\"", ")", "return", "IrPatternCallIntrinsic", "(", ")" ]
https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/llvm-external-projects/iree-dialects/python/iree/compiler/dialects/iree_pydm/importer/intrinsic_def.py#L104-L153
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/gluon/utils.py
python
check_sha1
(filename, sha1_hash)
return sha1.hexdigest() == sha1_hash
Check whether the sha1 hash of the file content matches the expected hash. Parameters ---------- filename : str Path to the file. sha1_hash : str Expected sha1 hash in hexadecimal digits. Returns ------- bool Whether the file content matches the expected hash.
Check whether the sha1 hash of the file content matches the expected hash.
[ "Check", "whether", "the", "sha1", "hash", "of", "the", "file", "content", "matches", "the", "expected", "hash", "." ]
def check_sha1(filename, sha1_hash): """Check whether the sha1 hash of the file content matches the expected hash. Parameters ---------- filename : str Path to the file. sha1_hash : str Expected sha1 hash in hexadecimal digits. Returns ------- bool Whether the file content matches the expected hash. """ sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) return sha1.hexdigest() == sha1_hash
[ "def", "check_sha1", "(", "filename", ",", "sha1_hash", ")", ":", "sha1", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "1048576", ")", "if", "not", "data", ":", "break", "sha1", ".", "update", "(", "data", ")", "return", "sha1", ".", "hexdigest", "(", ")", "==", "sha1_hash" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/utils.py#L145-L168
vmware/concord-bft
ec036a384b4c81be0423d4b429bd37900b13b864
util/pyclient/bft_client.py
python
BftClient._comm_prepare
(self)
Call before sending or receiving data. Some clients need to prepare their communication stack.
Call before sending or receiving data. Some clients need to prepare their communication stack.
[ "Call", "before", "sending", "or", "receiving", "data", ".", "Some", "clients", "need", "to", "prepare", "their", "communication", "stack", "." ]
async def _comm_prepare(self): """ Call before sending or receiving data. Some clients need to prepare their communication stack. """ pass
[ "async", "def", "_comm_prepare", "(", "self", ")", ":", "pass" ]
https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/util/pyclient/bft_client.py#L117-L119
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py
python
get_extra_vars
()
Returns the captured variables by the function. Returns: If the default graph is being used to define a function, the returned list of variables are those created inside the function body so far. Otherwise, returns an empty list.
Returns the captured variables by the function.
[ "Returns", "the", "captured", "variables", "by", "the", "function", "." ]
def get_extra_vars(): """Returns the captured variables by the function. Returns: If the default graph is being used to define a function, the returned list of variables are those created inside the function body so far. Otherwise, returns an empty list. """ g = ops.get_default_graph() if isinstance(g, _FuncGraph): return g.extra_vars else: return []
[ "def", "get_extra_vars", "(", ")", ":", "g", "=", "ops", ".", "get_default_graph", "(", ")", "if", "isinstance", "(", "g", ",", "_FuncGraph", ")", ":", "return", "g", ".", "extra_vars", "else", ":", "return", "[", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py#L1240-L1252
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py
python
TransferFuture.cancel
(self)
Cancels the request associated with the TransferFuture
Cancels the request associated with the TransferFuture
[ "Cancels", "the", "request", "associated", "with", "the", "TransferFuture" ]
def cancel(self): """Cancels the request associated with the TransferFuture""" self._coordinator.cancel()
[ "def", "cancel", "(", "self", ")", ":", "self", ".", "_coordinator", ".", "cancel", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py#L78-L80
pybox2d/pybox2d
09643321fd363f0850087d1bde8af3f4afd82163
library/Box2D/examples/backends/opencv_framework.py
python
OpencvFramework.run
(self)
Main loop. Continues to run while checkEvents indicates the user has requested to quit. Updates the screen and tells the GUI to paint itself.
Main loop.
[ "Main", "loop", "." ]
def run(self): """ Main loop. Continues to run while checkEvents indicates the user has requested to quit. Updates the screen and tells the GUI to paint itself. """ while True: self._t1 = time.time() dt = 1.0 / self.settings.hz key = 0xFF & cv2.waitKey(int(dt * 1000.0)) if key == 27: break elif key != 255: if key == 32: # Space self.LaunchRandomBomb() elif key == 81: # Left self.viewCenter -= (0.5, 0) elif key == 83: # Right self.viewCenter += (0.5, 0) elif key == 82: # Up self.viewCenter += (0, 0.5) elif key == 84: # Down self.viewCenter -= (0, 0.5) elif key == 80: # Home self.viewZoom = 1.0 self.viewCenter = (0.0, 20.0) elif key == ord('z'): # Zoom in self.viewZoom = min(1.1 * self.viewZoom, 50.0) elif key == ord('x'): # Zoom out self.viewZoom = max(0.9 * self.viewZoom, 0.02) else: self.Keyboard(key) self.screen.fill(0) self.SimulationLoop() cv2.imshow(self.name, self.screen) dt = self._t1 - self._t0 self._t0 = self._t1 self.fps = 1 / dt self.world.contactListener = None self.world.destructionListener = None self.world.renderer = None
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "self", ".", "_t1", "=", "time", ".", "time", "(", ")", "dt", "=", "1.0", "/", "self", ".", "settings", ".", "hz", "key", "=", "0xFF", "&", "cv2", ".", "waitKey", "(", "int", "(", "dt", "*", "1000.0", ")", ")", "if", "key", "==", "27", ":", "break", "elif", "key", "!=", "255", ":", "if", "key", "==", "32", ":", "# Space", "self", ".", "LaunchRandomBomb", "(", ")", "elif", "key", "==", "81", ":", "# Left", "self", ".", "viewCenter", "-=", "(", "0.5", ",", "0", ")", "elif", "key", "==", "83", ":", "# Right", "self", ".", "viewCenter", "+=", "(", "0.5", ",", "0", ")", "elif", "key", "==", "82", ":", "# Up", "self", ".", "viewCenter", "+=", "(", "0", ",", "0.5", ")", "elif", "key", "==", "84", ":", "# Down", "self", ".", "viewCenter", "-=", "(", "0", ",", "0.5", ")", "elif", "key", "==", "80", ":", "# Home", "self", ".", "viewZoom", "=", "1.0", "self", ".", "viewCenter", "=", "(", "0.0", ",", "20.0", ")", "elif", "key", "==", "ord", "(", "'z'", ")", ":", "# Zoom in", "self", ".", "viewZoom", "=", "min", "(", "1.1", "*", "self", ".", "viewZoom", ",", "50.0", ")", "elif", "key", "==", "ord", "(", "'x'", ")", ":", "# Zoom out", "self", ".", "viewZoom", "=", "max", "(", "0.9", "*", "self", ".", "viewZoom", ",", "0.02", ")", "else", ":", "self", ".", "Keyboard", "(", "key", ")", "self", ".", "screen", ".", "fill", "(", "0", ")", "self", ".", "SimulationLoop", "(", ")", "cv2", ".", "imshow", "(", "self", ".", "name", ",", "self", ".", "screen", ")", "dt", "=", "self", ".", "_t1", "-", "self", ".", "_t0", "self", ".", "_t0", "=", "self", ".", "_t1", "self", ".", "fps", "=", "1", "/", "dt", "self", ".", "world", ".", "contactListener", "=", "None", "self", ".", "world", ".", "destructionListener", "=", "None", "self", ".", "world", ".", "renderer", "=", "None" ]
https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/backends/opencv_framework.py#L276-L323
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridInterface_GetEditorByName
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetEditorByName(*args, **kwargs)
PropertyGridInterface_GetEditorByName(String editorName) -> PGEditor
PropertyGridInterface_GetEditorByName(String editorName) -> PGEditor
[ "PropertyGridInterface_GetEditorByName", "(", "String", "editorName", ")", "-", ">", "PGEditor" ]
def PropertyGridInterface_GetEditorByName(*args, **kwargs): """PropertyGridInterface_GetEditorByName(String editorName) -> PGEditor""" return _propgrid.PropertyGridInterface_GetEditorByName(*args, **kwargs)
[ "def", "PropertyGridInterface_GetEditorByName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetEditorByName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L1815-L1817
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/packaging/msi.py
python
gen_dos_short_file_name
(file, filename_set)
return shortname
See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982 These are no complete 8.3 dos short names. The ~ char is missing and replaced with one character from the filename. WiX warns about such filenames, since a collision might occur. Google for "CNDL1014" for more information.
See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982
[ "See", "http", ":", "//", "support", ".", "microsoft", ".", "com", "/", "default", ".", "aspx?scid", "=", "kb", ";", "en", "-", "us", ";", "Q142982" ]
def gen_dos_short_file_name(file, filename_set): """ See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982 These are no complete 8.3 dos short names. The ~ char is missing and replaced with one character from the filename. WiX warns about such filenames, since a collision might occur. Google for "CNDL1014" for more information. """ # guard this to not confuse the generation if is_dos_short_file_name(file): return file fname, ext = os.path.splitext(file) # ext contains the dot # first try if it suffices to convert to upper file = file.upper() if is_dos_short_file_name(file): return file # strip forbidden characters. forbidden = '."/[]:;=, ' fname = ''.join([c for c in fname if c not in forbidden]) # check if we already generated a filename with the same number: # thisis1.txt, thisis2.txt etc. duplicate, num = not None, 1 while duplicate: shortname = "%s%s" % (fname[:8-len(str(num))].upper(), str(num)) if len(ext) >= 2: shortname = "%s%s" % (shortname, ext[:4].upper()) duplicate, num = shortname in filename_set, num+1 assert( is_dos_short_file_name(shortname) ), 'shortname is %s, longname is %s' % (shortname, file) filename_set.append(shortname) return shortname
[ "def", "gen_dos_short_file_name", "(", "file", ",", "filename_set", ")", ":", "# guard this to not confuse the generation", "if", "is_dos_short_file_name", "(", "file", ")", ":", "return", "file", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "file", ")", "# ext contains the dot", "# first try if it suffices to convert to upper", "file", "=", "file", ".", "upper", "(", ")", "if", "is_dos_short_file_name", "(", "file", ")", ":", "return", "file", "# strip forbidden characters.", "forbidden", "=", "'.\"/[]:;=, '", "fname", "=", "''", ".", "join", "(", "[", "c", "for", "c", "in", "fname", "if", "c", "not", "in", "forbidden", "]", ")", "# check if we already generated a filename with the same number:", "# thisis1.txt, thisis2.txt etc.", "duplicate", ",", "num", "=", "not", "None", ",", "1", "while", "duplicate", ":", "shortname", "=", "\"%s%s\"", "%", "(", "fname", "[", ":", "8", "-", "len", "(", "str", "(", "num", ")", ")", "]", ".", "upper", "(", ")", ",", "str", "(", "num", ")", ")", "if", "len", "(", "ext", ")", ">=", "2", ":", "shortname", "=", "\"%s%s\"", "%", "(", "shortname", ",", "ext", "[", ":", "4", "]", ".", "upper", "(", ")", ")", "duplicate", ",", "num", "=", "shortname", "in", "filename_set", ",", "num", "+", "1", "assert", "(", "is_dos_short_file_name", "(", "shortname", ")", ")", ",", "'shortname is %s, longname is %s'", "%", "(", "shortname", ",", "file", ")", "filename_set", ".", "append", "(", "shortname", ")", "return", "shortname" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/packaging/msi.py#L90-L125
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/spirv-tools/utils/generate_grammar_tables.py
python
convert_max_required_version
(version)
return 'SPV_SPIRV_VERSION_WORD({})'.format(version.replace('.', ','))
Converts the maximum required SPIR-V version encoded in the grammar to the symbol in SPIRV-Tools.
Converts the maximum required SPIR-V version encoded in the grammar to the symbol in SPIRV-Tools.
[ "Converts", "the", "maximum", "required", "SPIR", "-", "V", "version", "encoded", "in", "the", "grammar", "to", "the", "symbol", "in", "SPIRV", "-", "Tools", "." ]
def convert_max_required_version(version): """Converts the maximum required SPIR-V version encoded in the grammar to the symbol in SPIRV-Tools.""" if version is None: return '0xffffffffu' return 'SPV_SPIRV_VERSION_WORD({})'.format(version.replace('.', ','))
[ "def", "convert_max_required_version", "(", "version", ")", ":", "if", "version", "is", "None", ":", "return", "'0xffffffffu'", "return", "'SPV_SPIRV_VERSION_WORD({})'", ".", "format", "(", "version", ".", "replace", "(", "'.'", ",", "','", ")", ")" ]
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/spirv-tools/utils/generate_grammar_tables.py#L64-L69
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/ext.py
python
Extension.attr
(self, name, lineno=None)
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code.
[ "Return", "an", "attribute", "node", "for", "the", "current", "extension", ".", "This", "is", "useful", "to", "pass", "constants", "on", "extensions", "to", "generated", "template", "code", "." ]
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/ext.py#L107-L115
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
python/caffe/pycaffe.py
python
_Net_forward
(self, blobs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].data for out in outputs}
Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict.
Forward pass: prepare inputs and run the net forward.
[ "Forward", "pass", ":", "prepare", "inputs", "and", "run", "the", "net", "forward", "." ]
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs): """ Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict. """ if blobs is None: blobs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = 0 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + blobs) else: end_ind = len(self.layers) - 1 outputs = set(self.outputs + blobs) if kwargs: if set(kwargs.keys()) != set(self.inputs): raise Exception('Input blob arguments do not match net inputs.') # Set input according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for in_, blob in six.iteritems(kwargs): if blob.shape[0] != self.blobs[in_].shape[0]: raise Exception('Input is not batch sized') self.blobs[in_].data[...] = blob self._forward(start_ind, end_ind) # Unpack blobs to extract return {out: self.blobs[out].data for out in outputs}
[ "def", "_Net_forward", "(", "self", ",", "blobs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "blobs", "is", "None", ":", "blobs", "=", "[", "]", "if", "start", "is", "not", "None", ":", "start_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "start", ")", "else", ":", "start_ind", "=", "0", "if", "end", "is", "not", "None", ":", "end_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "end", ")", "outputs", "=", "set", "(", "[", "end", "]", "+", "blobs", ")", "else", ":", "end_ind", "=", "len", "(", "self", ".", "layers", ")", "-", "1", "outputs", "=", "set", "(", "self", ".", "outputs", "+", "blobs", ")", "if", "kwargs", ":", "if", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "!=", "set", "(", "self", ".", "inputs", ")", ":", "raise", "Exception", "(", "'Input blob arguments do not match net inputs.'", ")", "# Set input according to defined shapes and make arrays single and", "# C-contiguous as Caffe expects.", "for", "in_", ",", "blob", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "blob", ".", "shape", "[", "0", "]", "!=", "self", ".", "blobs", "[", "in_", "]", ".", "shape", "[", "0", "]", ":", "raise", "Exception", "(", "'Input is not batch sized'", ")", "self", ".", "blobs", "[", "in_", "]", ".", "data", "[", "...", "]", "=", "blob", "self", ".", "_forward", "(", "start_ind", ",", "end_ind", ")", "# Unpack blobs to extract", "return", "{", "out", ":", "self", ".", "blobs", "[", "out", "]", ".", "data", "for", "out", "in", "outputs", "}" ]
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/python/caffe/pycaffe.py#L78-L124
geemaple/leetcode
68bc5032e1ee52c22ef2f2e608053484c487af54
leetcode/295.find-median-from-data-stream.py
python
MedianFinder.addNum
(self, num)
:type num: int :rtype: void
:type num: int :rtype: void
[ ":", "type", "num", ":", "int", ":", "rtype", ":", "void" ]
def addNum(self, num): """ :type num: int :rtype: void """ if len(self.leftHeap) <= len(self.rightHeap): heapq.heappush(self.leftHeap, -num) else: heapq.heappush(self.rightHeap, num) if len(self.rightHeap) > 0: left = -self.leftHeap[0] right = self.rightHeap[0] if left > right: heapq.heappop(self.leftHeap) heapq.heappop(self.rightHeap) heapq.heappush(self.leftHeap, -right) heapq.heappush(self.rightHeap, left)
[ "def", "addNum", "(", "self", ",", "num", ")", ":", "if", "len", "(", "self", ".", "leftHeap", ")", "<=", "len", "(", "self", ".", "rightHeap", ")", ":", "heapq", ".", "heappush", "(", "self", ".", "leftHeap", ",", "-", "num", ")", "else", ":", "heapq", ".", "heappush", "(", "self", ".", "rightHeap", ",", "num", ")", "if", "len", "(", "self", ".", "rightHeap", ")", ">", "0", ":", "left", "=", "-", "self", ".", "leftHeap", "[", "0", "]", "right", "=", "self", ".", "rightHeap", "[", "0", "]", "if", "left", ">", "right", ":", "heapq", ".", "heappop", "(", "self", ".", "leftHeap", ")", "heapq", ".", "heappop", "(", "self", ".", "rightHeap", ")", "heapq", ".", "heappush", "(", "self", ".", "leftHeap", ",", "-", "right", ")", "heapq", ".", "heappush", "(", "self", ".", "rightHeap", ",", "left", ")" ]
https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/295.find-median-from-data-stream.py#L12-L31
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
Treeview.item
(self, item, option=None, **kw)
return _val_or_dict(kw, self.tk.call, self._w, "item", item)
Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.
Query or modify the options for the specified item.
[ "Query", "or", "modify", "the", "options", "for", "the", "specified", "item", "." ]
def item(self, item, option=None, **kw): """Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.""" if option is not None: kw[option] = None return _val_or_dict(kw, self.tk.call, self._w, "item", item)
[ "def", "item", "(", "self", ",", "item", ",", "option", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "option", "is", "not", "None", ":", "kw", "[", "option", "]", "=", "None", "return", "_val_or_dict", "(", "kw", ",", "self", ".", "tk", ".", "call", ",", "self", ".", "_w", ",", "\"item\"", ",", "item", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L1340-L1349
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/so2.py
python
apply
(a,pt)
return [c*pt[0]-s*pt[1],s*pt[0]+c*pt[1]]
Applies a rotation of the angle a about the origin to the point pt
Applies a rotation of the angle a about the origin to the point pt
[ "Applies", "a", "rotation", "of", "the", "angle", "a", "about", "the", "origin", "to", "the", "point", "pt" ]
def apply(a,pt): """Applies a rotation of the angle a about the origin to the point pt""" c = math.cos(a) s = math.sin(a) return [c*pt[0]-s*pt[1],s*pt[0]+c*pt[1]]
[ "def", "apply", "(", "a", ",", "pt", ")", ":", "c", "=", "math", ".", "cos", "(", "a", ")", "s", "=", "math", ".", "sin", "(", "a", ")", "return", "[", "c", "*", "pt", "[", "0", "]", "-", "s", "*", "pt", "[", "1", "]", ",", "s", "*", "pt", "[", "0", "]", "+", "c", "*", "pt", "[", "1", "]", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/so2.py#L17-L21
dmlc/treelite
df56babb6a4a2d7c29d719c28ce53acfa7dbab3c
python/treelite/util.py
python
numpy_type_to_type_info
(type_info)
return _NUMPY_TYPE_TABLE_INV[type_info]
Obtain TypeInfo corresponding to a given NumPy type
Obtain TypeInfo corresponding to a given NumPy type
[ "Obtain", "TypeInfo", "corresponding", "to", "a", "given", "NumPy", "type" ]
def numpy_type_to_type_info(type_info): """Obtain TypeInfo corresponding to a given NumPy type""" return _NUMPY_TYPE_TABLE_INV[type_info]
[ "def", "numpy_type_to_type_info", "(", "type_info", ")", ":", "return", "_NUMPY_TYPE_TABLE_INV", "[", "type_info", "]" ]
https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/util.py#L77-L79
bnosac/image
1dd70d07fdc8638ca1b57769372ea1d67995af58
image.dlib/inst/dlib-19.20/setup.py
python
read_entire_file
(fname)
return open(os.path.join(fname)).read()
Read text out of a file relative to setup.py.
Read text out of a file relative to setup.py.
[ "Read", "text", "out", "of", "a", "file", "relative", "to", "setup", ".", "py", "." ]
def read_entire_file(fname): """Read text out of a file relative to setup.py. """ return open(os.path.join(fname)).read()
[ "def", "read_entire_file", "(", "fname", ")", ":", "return", "open", "(", "os", ".", "path", ".", "join", "(", "fname", ")", ")", ".", "read", "(", ")" ]
https://github.com/bnosac/image/blob/1dd70d07fdc8638ca1b57769372ea1d67995af58/image.dlib/inst/dlib-19.20/setup.py#L218-L221
takemaru/graphillion
51879f92bb96b53ef8f914ef37a05252ce383617
graphillion/graphset.py
python
GraphSet.larger
(self, size)
return GraphSet(self._ss.larger(size))
Returns a new GraphSet with graphs that have more than `size` edges. The `self` is not changed. Examples: >>> graph1 = [(1, 2)] >>> graph2 = [(1, 2), (1, 4)] >>> graph3 = [(1, 2), (1, 4), (2, 3)] >>> gs = GraphSet([graph1, graph2, graph3]) >>> gs.larger(2) GraphSet([[(1, 2), (1, 4), (2, 3)]]) Args: size: The number of edges in a graph. Returns: A new GraphSet object. See Also: smaller(), graph_size()
Returns a new GraphSet with graphs that have more than `size` edges.
[ "Returns", "a", "new", "GraphSet", "with", "graphs", "that", "have", "more", "than", "size", "edges", "." ]
def larger(self, size): """Returns a new GraphSet with graphs that have more than `size` edges. The `self` is not changed. Examples: >>> graph1 = [(1, 2)] >>> graph2 = [(1, 2), (1, 4)] >>> graph3 = [(1, 2), (1, 4), (2, 3)] >>> gs = GraphSet([graph1, graph2, graph3]) >>> gs.larger(2) GraphSet([[(1, 2), (1, 4), (2, 3)]]) Args: size: The number of edges in a graph. Returns: A new GraphSet object. See Also: smaller(), graph_size() """ return GraphSet(self._ss.larger(size))
[ "def", "larger", "(", "self", ",", "size", ")", ":", "return", "GraphSet", "(", "self", ".", "_ss", ".", "larger", "(", "size", ")", ")" ]
https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L1094-L1116
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py
python
DataSetAttributes.PassData
(self, other)
A wrapper for vtkDataSet.PassData.
A wrapper for vtkDataSet.PassData.
[ "A", "wrapper", "for", "vtkDataSet", ".", "PassData", "." ]
def PassData(self, other): "A wrapper for vtkDataSet.PassData." try: self.VTKObject.PassData(other) except TypeError: self.VTKObject.PassData(other.VTKObject)
[ "def", "PassData", "(", "self", ",", "other", ")", ":", "try", ":", "self", ".", "VTKObject", ".", "PassData", "(", "other", ")", "except", "TypeError", ":", "self", ".", "VTKObject", ".", "PassData", "(", "other", ".", "VTKObject", ")" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py#L679-L684
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
Builder.dependencies
(self)
Recompute dynamic dependencies. Reimplemented by subclasses. This implementation does nothing.
Recompute dynamic dependencies.
[ "Recompute", "dynamic", "dependencies", "." ]
def dependencies(self): """Recompute dynamic dependencies. Reimplemented by subclasses. This implementation does nothing. """ pass
[ "def", "dependencies", "(", "self", ")", ":", "pass" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L2123-L2128
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/value/__init__.py
python
Value.FromDict
(value_dict, page_dict)
return Value.ListOfValuesFromListOfDicts([value_dict], page_dict)[0]
Produces a value from a value dict and a page dict. Value dicts are produced by serialization to JSON, and must be accompanied by a dict mapping page IDs to pages, also produced by serialization, in order to be completely deserialized. If deserializing multiple values, use ListOfValuesFromListOfDicts instead. value_dict: a dictionary produced by AsDict() on a value subclass. page_dict: a dictionary mapping IDs to page objects.
Produces a value from a value dict and a page dict.
[ "Produces", "a", "value", "from", "a", "value", "dict", "and", "a", "page", "dict", "." ]
def FromDict(value_dict, page_dict): """Produces a value from a value dict and a page dict. Value dicts are produced by serialization to JSON, and must be accompanied by a dict mapping page IDs to pages, also produced by serialization, in order to be completely deserialized. If deserializing multiple values, use ListOfValuesFromListOfDicts instead. value_dict: a dictionary produced by AsDict() on a value subclass. page_dict: a dictionary mapping IDs to page objects. """ return Value.ListOfValuesFromListOfDicts([value_dict], page_dict)[0]
[ "def", "FromDict", "(", "value_dict", ",", "page_dict", ")", ":", "return", "Value", ".", "ListOfValuesFromListOfDicts", "(", "[", "value_dict", "]", ",", "page_dict", ")", "[", "0", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/value/__init__.py#L229-L240
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py
python
class_t.get_members
(self, access=None)
return all_members
returns list of members according to access type If access equals to None, then returned list will contain all members. You should not modify the list content, otherwise different optimization data will stop work and may to give you wrong results. :param access: describes desired members :type access: :class:ACCESS_TYPES :rtype: [ members ]
returns list of members according to access type
[ "returns", "list", "of", "members", "according", "to", "access", "type" ]
def get_members(self, access=None): """ returns list of members according to access type If access equals to None, then returned list will contain all members. You should not modify the list content, otherwise different optimization data will stop work and may to give you wrong results. :param access: describes desired members :type access: :class:ACCESS_TYPES :rtype: [ members ] """ if access == ACCESS_TYPES.PUBLIC: return self.public_members elif access == ACCESS_TYPES.PROTECTED: return self.protected_members elif access == ACCESS_TYPES.PRIVATE: return self.private_members all_members = [] all_members.extend(self.public_members) all_members.extend(self.protected_members) all_members.extend(self.private_members) return all_members
[ "def", "get_members", "(", "self", ",", "access", "=", "None", ")", ":", "if", "access", "==", "ACCESS_TYPES", ".", "PUBLIC", ":", "return", "self", ".", "public_members", "elif", "access", "==", "ACCESS_TYPES", ".", "PROTECTED", ":", "return", "self", ".", "protected_members", "elif", "access", "==", "ACCESS_TYPES", ".", "PRIVATE", ":", "return", "self", ".", "private_members", "all_members", "=", "[", "]", "all_members", ".", "extend", "(", "self", ".", "public_members", ")", "all_members", ".", "extend", "(", "self", ".", "protected_members", ")", "all_members", ".", "extend", "(", "self", ".", "private_members", ")", "return", "all_members" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py#L363-L387
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Utilities/Maintenance/vtk_generate_pyi.py
python
push_signature
(o, l, signature)
Process a method signature and add it to the list.
Process a method signature and add it to the list.
[ "Process", "a", "method", "signature", "and", "add", "it", "to", "the", "list", "." ]
def push_signature(o, l, signature): """Process a method signature and add it to the list. """ signature = re.sub(r"\s+", " ", signature) if signature.startswith('C++:'): # if C++ method is static, mark Python signature static if isvtkmethod(o) and signature.find(" static ") != -1 and len(l) > 0: if not l[-1].startswith("@staticmethod"): l[-1] = "@staticmethod\n" + l[-1] elif signature.startswith(o.__name__ + "("): if isvtkmethod(o) and not has_self.search(signature): if not signature.startswith("@staticmethod"): signature = "@staticmethod\n" + signature l.append(signature)
[ "def", "push_signature", "(", "o", ",", "l", ",", "signature", ")", ":", "signature", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "signature", ")", "if", "signature", ".", "startswith", "(", "'C++:'", ")", ":", "# if C++ method is static, mark Python signature static", "if", "isvtkmethod", "(", "o", ")", "and", "signature", ".", "find", "(", "\" static \"", ")", "!=", "-", "1", "and", "len", "(", "l", ")", ">", "0", ":", "if", "not", "l", "[", "-", "1", "]", ".", "startswith", "(", "\"@staticmethod\"", ")", ":", "l", "[", "-", "1", "]", "=", "\"@staticmethod\\n\"", "+", "l", "[", "-", "1", "]", "elif", "signature", ".", "startswith", "(", "o", ".", "__name__", "+", "\"(\"", ")", ":", "if", "isvtkmethod", "(", "o", ")", "and", "not", "has_self", ".", "search", "(", "signature", ")", ":", "if", "not", "signature", ".", "startswith", "(", "\"@staticmethod\"", ")", ":", "signature", "=", "\"@staticmethod\\n\"", "+", "signature", "l", ".", "append", "(", "signature", ")" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Utilities/Maintenance/vtk_generate_pyi.py#L176-L189
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/colourchooser/pycolourchooser.py
python
PyColourChooser.onScroll
(self, event)
Updates the solid colour display to reflect the changing slider.
Updates the solid colour display to reflect the changing slider.
[ "Updates", "the", "solid", "colour", "display", "to", "reflect", "the", "changing", "slider", "." ]
def onScroll(self, event): """Updates the solid colour display to reflect the changing slider.""" value = self.slider.GetValue() colour = self.colour_slider.GetValue(value) self.solid.SetColour(colour) self.UpdateEntries(colour)
[ "def", "onScroll", "(", "self", ",", "event", ")", ":", "value", "=", "self", ".", "slider", ".", "GetValue", "(", ")", "colour", "=", "self", ".", "colour_slider", ".", "GetValue", "(", "value", ")", "self", ".", "solid", ".", "SetColour", "(", "colour", ")", "self", ".", "UpdateEntries", "(", "colour", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/colourchooser/pycolourchooser.py#L372-L377
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
CheckBox.GetValue
(*args, **kwargs)
return _controls_.CheckBox_GetValue(*args, **kwargs)
GetValue(self) -> bool Gets the state of a 2-state CheckBox. Returns True if it is checked, False otherwise.
GetValue(self) -> bool
[ "GetValue", "(", "self", ")", "-", ">", "bool" ]
def GetValue(*args, **kwargs): """ GetValue(self) -> bool Gets the state of a 2-state CheckBox. Returns True if it is checked, False otherwise. """ return _controls_.CheckBox_GetValue(*args, **kwargs)
[ "def", "GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "CheckBox_GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L367-L374
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/ccompiler.py
python
CCompiler.add_link_object
(self, object)
Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object.
Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object.
[ "Add", "object", "to", "the", "list", "of", "object", "files", "(", "or", "analogues", "such", "as", "explicitly", "named", "library", "files", "or", "the", "output", "of", "resource", "compilers", ")", "to", "be", "included", "in", "every", "link", "driven", "by", "this", "compiler", "object", "." ]
def add_link_object(self, object): """Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object. """ self.objects.append(object)
[ "def", "add_link_object", "(", "self", ",", "object", ")", ":", "self", ".", "objects", ".", "append", "(", "object", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/ccompiler.py#L288-L294
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBData.GetUnsignedInt64
(self, error, offset)
return _lldb.SBData_GetUnsignedInt64(self, error, offset)
GetUnsignedInt64(SBData self, SBError error, lldb::offset_t offset) -> uint64_t
GetUnsignedInt64(SBData self, SBError error, lldb::offset_t offset) -> uint64_t
[ "GetUnsignedInt64", "(", "SBData", "self", "SBError", "error", "lldb", "::", "offset_t", "offset", ")", "-", ">", "uint64_t" ]
def GetUnsignedInt64(self, error, offset): """GetUnsignedInt64(SBData self, SBError error, lldb::offset_t offset) -> uint64_t""" return _lldb.SBData_GetUnsignedInt64(self, error, offset)
[ "def", "GetUnsignedInt64", "(", "self", ",", "error", ",", "offset", ")", ":", "return", "_lldb", ".", "SBData_GetUnsignedInt64", "(", "self", ",", "error", ",", "offset", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L3377-L3379
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/feature_column.py
python
_create_dense_column_weighted_sum
(column, builder, units, weight_collections, trainable, weight_var=None)
return math_ops.matmul(tensor, weight, name='weighted_sum')
Create a weighted sum of a dense column for linear_model.
Create a weighted sum of a dense column for linear_model.
[ "Create", "a", "weighted", "sum", "of", "a", "dense", "column", "for", "linear_model", "." ]
def _create_dense_column_weighted_sum(column, builder, units, weight_collections, trainable, weight_var=None): """Create a weighted sum of a dense column for linear_model.""" tensor = column._get_dense_tensor( # pylint: disable=protected-access builder, weight_collections=weight_collections, trainable=trainable) num_elements = column._variable_shape.num_elements() # pylint: disable=protected-access batch_size = array_ops.shape(tensor)[0] tensor = array_ops.reshape(tensor, shape=(batch_size, num_elements)) if weight_var is not None: weight = weight_var else: weight = variable_scope.get_variable( name='weights', shape=[num_elements, units], initializer=init_ops.zeros_initializer(), trainable=trainable, collections=weight_collections) return math_ops.matmul(tensor, weight, name='weighted_sum')
[ "def", "_create_dense_column_weighted_sum", "(", "column", ",", "builder", ",", "units", ",", "weight_collections", ",", "trainable", ",", "weight_var", "=", "None", ")", ":", "tensor", "=", "column", ".", "_get_dense_tensor", "(", "# pylint: disable=protected-access", "builder", ",", "weight_collections", "=", "weight_collections", ",", "trainable", "=", "trainable", ")", "num_elements", "=", "column", ".", "_variable_shape", ".", "num_elements", "(", ")", "# pylint: disable=protected-access", "batch_size", "=", "array_ops", ".", "shape", "(", "tensor", ")", "[", "0", "]", "tensor", "=", "array_ops", ".", "reshape", "(", "tensor", ",", "shape", "=", "(", "batch_size", ",", "num_elements", ")", ")", "if", "weight_var", "is", "not", "None", ":", "weight", "=", "weight_var", "else", ":", "weight", "=", "variable_scope", ".", "get_variable", "(", "name", "=", "'weights'", ",", "shape", "=", "[", "num_elements", ",", "units", "]", ",", "initializer", "=", "init_ops", ".", "zeros_initializer", "(", ")", ",", "trainable", "=", "trainable", ",", "collections", "=", "weight_collections", ")", "return", "math_ops", ".", "matmul", "(", "tensor", ",", "weight", ",", "name", "=", "'weighted_sum'", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column.py#L1960-L1983
ros-controls/ros_control
53c2487d1b56a40f1d00b06c49512aa7fd2bf465
controller_manager_msgs/src/controller_manager_msgs/utils.py
python
filter_by_hardware_interface
(ctrl_list, hardware_interface, match_substring=False)
return list_out
Filter controller state list by controller hardware interface. @param ctrl_list: Controller state list @type ctrl_list: [controller_manager_msgs/ControllerState] @param hardware_interface: Controller hardware interface @type hardware_interface: str @param match_substring: Set to True to allow substring matching @type match_substring: bool @return: Controllers matching the specified hardware interface @rtype: [controller_manager_msgs/ControllerState]
Filter controller state list by controller hardware interface.
[ "Filter", "controller", "state", "list", "by", "controller", "hardware", "interface", "." ]
def filter_by_hardware_interface(ctrl_list, hardware_interface, match_substring=False): """ Filter controller state list by controller hardware interface. @param ctrl_list: Controller state list @type ctrl_list: [controller_manager_msgs/ControllerState] @param hardware_interface: Controller hardware interface @type hardware_interface: str @param match_substring: Set to True to allow substring matching @type match_substring: bool @return: Controllers matching the specified hardware interface @rtype: [controller_manager_msgs/ControllerState] """ list_out = [] for ctrl in ctrl_list: for resource_set in ctrl.claimed_resources: if match_substring: if hardware_interface in resource_set.hardware_interface: list_out.append(ctrl) break else: if resource_set.hardware_interface == hardware_interface: list_out.append(ctrl) break return list_out
[ "def", "filter_by_hardware_interface", "(", "ctrl_list", ",", "hardware_interface", ",", "match_substring", "=", "False", ")", ":", "list_out", "=", "[", "]", "for", "ctrl", "in", "ctrl_list", ":", "for", "resource_set", "in", "ctrl", ".", "claimed_resources", ":", "if", "match_substring", ":", "if", "hardware_interface", "in", "resource_set", ".", "hardware_interface", ":", "list_out", ".", "append", "(", "ctrl", ")", "break", "else", ":", "if", "resource_set", ".", "hardware_interface", "==", "hardware_interface", ":", "list_out", ".", "append", "(", "ctrl", ")", "break", "return", "list_out" ]
https://github.com/ros-controls/ros_control/blob/53c2487d1b56a40f1d00b06c49512aa7fd2bf465/controller_manager_msgs/src/controller_manager_msgs/utils.py#L304-L330