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
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.links_entries_reset
(self)
Reset Global Links Variables
Reset Global Links Variables
[ "Reset", "Global", "Links", "Variables" ]
def links_entries_reset(self): """Reset Global Links Variables""" self.link_node_id = None self.links_entries['webs'] = "" self.links_entries['file'] = "" self.links_entries['fold'] = "" self.links_entries['anch'] = ""
[ "def", "links_entries_reset", "(", "self", ")", ":", "self", ".", "link_node_id", "=", "None", "self", ".", "links_entries", "[", "'webs'", "]", "=", "\"\"", "self", ".", "links_entries", "[", "'file'", "]", "=", "\"\"", "self", ".", "links_entries", "[", "'fold'", "]", "=", "\"\"", "self", ".", "links_entries", "[", "'anch'", "]", "=", "\"\"" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L4601-L4607
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Locale.GetLanguage
(*args, **kwargs)
return _gdi_.Locale_GetLanguage(*args, **kwargs)
GetLanguage(self) -> int
GetLanguage(self) -> int
[ "GetLanguage", "(", "self", ")", "-", ">", "int" ]
def GetLanguage(*args, **kwargs): """GetLanguage(self) -> int""" return _gdi_.Locale_GetLanguage(*args, **kwargs)
[ "def", "GetLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_GetLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L3029-L3031
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py
python
NetscapeSPKI.get_pubkey
(self)
return pkey
Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey`
Get the public key of this certificate.
[ "Get", "the", "public", "key", "of", "this", "certificate", "." ]
def get_pubkey(self): """ Get the public key of this certificate. :return: The public key. :rtype: :py:class:`PKey` """ pkey = PKey.__new__(PKey) pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki) _openssl_assert(pkey._pkey != _ffi.NULL) pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
[ "def", "get_pubkey", "(", "self", ")", ":", "pkey", "=", "PKey", ".", "__new__", "(", "PKey", ")", "pkey", ".", "_pkey", "=", "_lib", ".", "NETSCAPE_SPKI_get_pubkey", "(", "self", ".", "_spki", ")", "_openssl_assert", "(", "pkey", ".", "_pkey", "!=", "_ffi", ".", "NULL", ")", "pkey", ".", "_pkey", "=", "_ffi", ".", "gc", "(", "pkey", ".", "_pkey", ",", "_lib", ".", "EVP_PKEY_free", ")", "pkey", ".", "_only_public", "=", "True", "return", "pkey" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L2581-L2593
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
lib/datasets/imdb.py
python
imdb.evaluate_recall
(self, candidate_boxes=None, thresholds=None, area='all', limit=None)
return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps}
Evaluate detection proposal recall metrics. Returns: results: dictionary of results with keys 'ar': average recall 'recalls': vector recalls at each IoU overlap threshold 'thresholds': vector of IoU overlap thresholds 'gt_overlaps': vector of all ground-truth overlaps
Evaluate detection proposal recall metrics.
[ "Evaluate", "detection", "proposal", "recall", "metrics", "." ]
def evaluate_recall(self, candidate_boxes=None, thresholds=None, area='all', limit=None): """Evaluate detection proposal recall metrics. Returns: results: dictionary of results with keys 'ar': average recall 'recalls': vector recalls at each IoU overlap threshold 'thresholds': vector of IoU overlap thresholds 'gt_overlaps': vector of all ground-truth overlaps """ # Record max overlap value for each gt box # Return vector of overlap values areas = { 'all': 0, 'small': 1, 'medium': 2, 'large': 3, '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7} area_ranges = [ [0**2, 1e5**2], # all [0**2, 32**2], # small [32**2, 96**2], # medium [96**2, 1e5**2], # large [96**2, 128**2], # 96-128 [128**2, 256**2], # 128-256 [256**2, 512**2], # 256-512 [512**2, 1e5**2], # 512-inf ] assert areas.has_key(area), 'unknown area range: {}'.format(area) area_range = area_ranges[areas[area]] gt_overlaps = np.zeros(0) num_pos = 0 for i in xrange(self.num_images): # Checking for max_overlaps == 1 avoids including crowd annotations # (...pretty hacking :/) max_gt_overlaps = self.roidb[i]['gt_overlaps'].toarray().max(axis=1) gt_inds = np.where((self.roidb[i]['gt_classes'] > 0) & (max_gt_overlaps == 1))[0] gt_boxes = self.roidb[i]['boxes'][gt_inds, :] gt_areas = self.roidb[i]['seg_areas'][gt_inds] valid_gt_inds = np.where((gt_areas >= area_range[0]) & (gt_areas <= area_range[1]))[0] gt_boxes = gt_boxes[valid_gt_inds, :] num_pos += len(valid_gt_inds) if candidate_boxes is None: # If candidate_boxes is not supplied, the default is to use the # non-ground-truth boxes from this roidb non_gt_inds = np.where(self.roidb[i]['gt_classes'] == 0)[0] boxes = self.roidb[i]['boxes'][non_gt_inds, :] else: boxes = candidate_boxes[i] if boxes.shape[0] == 0: continue if limit is not None and boxes.shape[0] > limit: boxes = boxes[:limit, :] overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) _gt_overlaps = np.zeros((gt_boxes.shape[0])) for j in xrange(gt_boxes.shape[0]): # find which proposal box maximally covers each gt box argmax_overlaps = overlaps.argmax(axis=0) # and get the iou amount of coverage for each gt box max_overlaps = overlaps.max(axis=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ind = max_overlaps.argmax() gt_ovr = max_overlaps.max() assert(gt_ovr >= 0) # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert(_gt_overlaps[j] == gt_ovr) # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps = np.hstack((gt_overlaps, _gt_overlaps)) gt_overlaps = np.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = np.arange(0.5, 0.95 + 1e-5, step) recalls = np.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps}
[ "def", "evaluate_recall", "(", "self", ",", "candidate_boxes", "=", "None", ",", "thresholds", "=", "None", ",", "area", "=", "'all'", ",", "limit", "=", "None", ")", ":", "# Record max overlap value for each gt box", "# Return vector of overlap values", "areas", "=", "{", "'all'", ":", "0", ",", "'small'", ":", "1", ",", "'medium'", ":", "2", ",", "'large'", ":", "3", ",", "'96-128'", ":", "4", ",", "'128-256'", ":", "5", ",", "'256-512'", ":", "6", ",", "'512-inf'", ":", "7", "}", "area_ranges", "=", "[", "[", "0", "**", "2", ",", "1e5", "**", "2", "]", ",", "# all", "[", "0", "**", "2", ",", "32", "**", "2", "]", ",", "# small", "[", "32", "**", "2", ",", "96", "**", "2", "]", ",", "# medium", "[", "96", "**", "2", ",", "1e5", "**", "2", "]", ",", "# large", "[", "96", "**", "2", ",", "128", "**", "2", "]", ",", "# 96-128", "[", "128", "**", "2", ",", "256", "**", "2", "]", ",", "# 128-256", "[", "256", "**", "2", ",", "512", "**", "2", "]", ",", "# 256-512", "[", "512", "**", "2", ",", "1e5", "**", "2", "]", ",", "# 512-inf", "]", "assert", "areas", ".", "has_key", "(", "area", ")", ",", "'unknown area range: {}'", ".", "format", "(", "area", ")", "area_range", "=", "area_ranges", "[", "areas", "[", "area", "]", "]", "gt_overlaps", "=", "np", ".", "zeros", "(", "0", ")", "num_pos", "=", "0", "for", "i", "in", "xrange", "(", "self", ".", "num_images", ")", ":", "# Checking for max_overlaps == 1 avoids including crowd annotations", "# (...pretty hacking :/)", "max_gt_overlaps", "=", "self", ".", "roidb", "[", "i", "]", "[", "'gt_overlaps'", "]", ".", "toarray", "(", ")", ".", "max", "(", "axis", "=", "1", ")", "gt_inds", "=", "np", ".", "where", "(", "(", "self", ".", "roidb", "[", "i", "]", "[", "'gt_classes'", "]", ">", "0", ")", "&", "(", "max_gt_overlaps", "==", "1", ")", ")", "[", "0", "]", "gt_boxes", "=", "self", ".", "roidb", "[", "i", "]", "[", "'boxes'", "]", "[", "gt_inds", ",", ":", "]", "gt_areas", "=", "self", ".", "roidb", "[", "i", "]", "[", "'seg_areas'", "]", "[", "gt_inds", "]", "valid_gt_inds", "=", "np", ".", "where", "(", "(", "gt_areas", ">=", "area_range", "[", "0", "]", ")", "&", "(", "gt_areas", "<=", "area_range", "[", "1", "]", ")", ")", "[", "0", "]", "gt_boxes", "=", "gt_boxes", "[", "valid_gt_inds", ",", ":", "]", "num_pos", "+=", "len", "(", "valid_gt_inds", ")", "if", "candidate_boxes", "is", "None", ":", "# If candidate_boxes is not supplied, the default is to use the", "# non-ground-truth boxes from this roidb", "non_gt_inds", "=", "np", ".", "where", "(", "self", ".", "roidb", "[", "i", "]", "[", "'gt_classes'", "]", "==", "0", ")", "[", "0", "]", "boxes", "=", "self", ".", "roidb", "[", "i", "]", "[", "'boxes'", "]", "[", "non_gt_inds", ",", ":", "]", "else", ":", "boxes", "=", "candidate_boxes", "[", "i", "]", "if", "boxes", ".", "shape", "[", "0", "]", "==", "0", ":", "continue", "if", "limit", "is", "not", "None", "and", "boxes", ".", "shape", "[", "0", "]", ">", "limit", ":", "boxes", "=", "boxes", "[", ":", "limit", ",", ":", "]", "overlaps", "=", "bbox_overlaps", "(", "boxes", ".", "astype", "(", "np", ".", "float", ")", ",", "gt_boxes", ".", "astype", "(", "np", ".", "float", ")", ")", "_gt_overlaps", "=", "np", ".", "zeros", "(", "(", "gt_boxes", ".", "shape", "[", "0", "]", ")", ")", "for", "j", "in", "xrange", "(", "gt_boxes", ".", "shape", "[", "0", "]", ")", ":", "# find which proposal box maximally covers each gt box", "argmax_overlaps", "=", "overlaps", ".", "argmax", "(", "axis", "=", "0", ")", "# and get the iou amount of coverage for each gt box", "max_overlaps", "=", "overlaps", ".", "max", "(", "axis", "=", "0", ")", "# find which gt box is 'best' covered (i.e. 'best' = most iou)", "gt_ind", "=", "max_overlaps", ".", "argmax", "(", ")", "gt_ovr", "=", "max_overlaps", ".", "max", "(", ")", "assert", "(", "gt_ovr", ">=", "0", ")", "# find the proposal box that covers the best covered gt box", "box_ind", "=", "argmax_overlaps", "[", "gt_ind", "]", "# record the iou coverage of this gt box", "_gt_overlaps", "[", "j", "]", "=", "overlaps", "[", "box_ind", ",", "gt_ind", "]", "assert", "(", "_gt_overlaps", "[", "j", "]", "==", "gt_ovr", ")", "# mark the proposal box and the gt box as used", "overlaps", "[", "box_ind", ",", ":", "]", "=", "-", "1", "overlaps", "[", ":", ",", "gt_ind", "]", "=", "-", "1", "# append recorded iou coverage level", "gt_overlaps", "=", "np", ".", "hstack", "(", "(", "gt_overlaps", ",", "_gt_overlaps", ")", ")", "gt_overlaps", "=", "np", ".", "sort", "(", "gt_overlaps", ")", "if", "thresholds", "is", "None", ":", "step", "=", "0.05", "thresholds", "=", "np", ".", "arange", "(", "0.5", ",", "0.95", "+", "1e-5", ",", "step", ")", "recalls", "=", "np", ".", "zeros_like", "(", "thresholds", ")", "# compute recall for each iou threshold", "for", "i", ",", "t", "in", "enumerate", "(", "thresholds", ")", ":", "recalls", "[", "i", "]", "=", "(", "gt_overlaps", ">=", "t", ")", ".", "sum", "(", ")", "/", "float", "(", "num_pos", ")", "# ar = 2 * np.trapz(recalls, thresholds)", "ar", "=", "recalls", ".", "mean", "(", ")", "return", "{", "'ar'", ":", "ar", ",", "'recalls'", ":", "recalls", ",", "'thresholds'", ":", "thresholds", ",", "'gt_overlaps'", ":", "gt_overlaps", "}" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/datasets/imdb.py#L126-L214
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/hang_analyzer/dumper.py
python
LLDBDumper._find_debugger
(debugger)
return find_program(debugger, ['/usr/bin'])
Find the installed debugger.
Find the installed debugger.
[ "Find", "the", "installed", "debugger", "." ]
def _find_debugger(debugger): """Find the installed debugger.""" return find_program(debugger, ['/usr/bin'])
[ "def", "_find_debugger", "(", "debugger", ")", ":", "return", "find_program", "(", "debugger", ",", "[", "'/usr/bin'", "]", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/hang_analyzer/dumper.py#L211-L213
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
constrain
(n, min, max)
return n
This returns a number, n constrained to the min and max bounds.
This returns a number, n constrained to the min and max bounds.
[ "This", "returns", "a", "number", "n", "constrained", "to", "the", "min", "and", "max", "bounds", "." ]
def constrain (n, min, max): '''This returns a number, n constrained to the min and max bounds. ''' if n < min: return min if n > max: return max return n
[ "def", "constrain", "(", "n", ",", "min", ",", "max", ")", ":", "if", "n", "<", "min", ":", "return", "min", "if", "n", ">", "max", ":", "return", "max", "return", "n" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L60-L68
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/column.py
python
to_arrow
(self)
return libcudf.interop.to_arrow( cudf.core.frame.Frame( cudf.core.column_accessor.ColumnAccessor({"None": self}) ), [["None"]], keep_index=False, )["None"].chunk(0)
Convert to PyArrow Array Examples -------- >>> import cudf >>> col = cudf.core.column.as_column([1, 2, 3, 4]) >>> col.to_arrow() <pyarrow.lib.Int64Array object at 0x7f886547f830> [ 1, 2, 3, 4 ]
Convert to PyArrow Array
[ "Convert", "to", "PyArrow", "Array" ]
def to_arrow(self) -> pa.Array: """Convert to PyArrow Array Examples -------- >>> import cudf >>> col = cudf.core.column.as_column([1, 2, 3, 4]) >>> col.to_arrow() <pyarrow.lib.Int64Array object at 0x7f886547f830> [ 1, 2, 3, 4 ] """ return libcudf.interop.to_arrow( cudf.core.frame.Frame( cudf.core.column_accessor.ColumnAccessor({"None": self}) ), [["None"]], keep_index=False, )["None"].chunk(0)
[ "def", "to_arrow", "(", "self", ")", "->", "pa", ".", "Array", ":", "return", "libcudf", ".", "interop", ".", "to_arrow", "(", "cudf", ".", "core", ".", "frame", ".", "Frame", "(", "cudf", ".", "core", ".", "column_accessor", ".", "ColumnAccessor", "(", "{", "\"None\"", ":", "self", "}", ")", ")", ",", "[", "[", "\"None\"", "]", "]", ",", "keep_index", "=", "False", ",", ")", "[", "\"None\"", "]", ".", "chunk", "(", "0", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/column.py#L209-L231
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/data/_typing.py
python
issubtype
(left, right, recursive=True)
return all(_issubtype_with_constraints(variant, constraints, recursive) for variant in variants)
r""" Check if the left-side type is a subtype of the right-side type. If any of type is a composite type like `Union` and `TypeVar` with bounds, it would be expanded into a list of types and check all of left-side types are subtypes of either one from right-side types.
r""" Check if the left-side type is a subtype of the right-side type. If any of type is a composite type like `Union` and `TypeVar` with bounds, it would be expanded into a list of types and check all of left-side types are subtypes of either one from right-side types.
[ "r", "Check", "if", "the", "left", "-", "side", "type", "is", "a", "subtype", "of", "the", "right", "-", "side", "type", ".", "If", "any", "of", "type", "is", "a", "composite", "type", "like", "Union", "and", "TypeVar", "with", "bounds", "it", "would", "be", "expanded", "into", "a", "list", "of", "types", "and", "check", "all", "of", "left", "-", "side", "types", "are", "subtypes", "of", "either", "one", "from", "right", "-", "side", "types", "." ]
def issubtype(left, right, recursive=True): r""" Check if the left-side type is a subtype of the right-side type. If any of type is a composite type like `Union` and `TypeVar` with bounds, it would be expanded into a list of types and check all of left-side types are subtypes of either one from right-side types. """ left = TYPE2ABC.get(left, left) right = TYPE2ABC.get(right, right) if right is Any or left == right: return True if isinstance(right, _GenericAlias): if getattr(right, '__origin__', None) is Generic: return True if right == type(None): return False # Right-side type constraints = _decompose_type(right) if len(constraints) == 0 or Any in constraints: return True if left is Any: return False # Left-side type variants = _decompose_type(left) # all() will return True for empty variants if len(variants) == 0: return False return all(_issubtype_with_constraints(variant, constraints, recursive) for variant in variants)
[ "def", "issubtype", "(", "left", ",", "right", ",", "recursive", "=", "True", ")", ":", "left", "=", "TYPE2ABC", ".", "get", "(", "left", ",", "left", ")", "right", "=", "TYPE2ABC", ".", "get", "(", "right", ",", "right", ")", "if", "right", "is", "Any", "or", "left", "==", "right", ":", "return", "True", "if", "isinstance", "(", "right", ",", "_GenericAlias", ")", ":", "if", "getattr", "(", "right", ",", "'__origin__'", ",", "None", ")", "is", "Generic", ":", "return", "True", "if", "right", "==", "type", "(", "None", ")", ":", "return", "False", "# Right-side type", "constraints", "=", "_decompose_type", "(", "right", ")", "if", "len", "(", "constraints", ")", "==", "0", "or", "Any", "in", "constraints", ":", "return", "True", "if", "left", "is", "Any", ":", "return", "False", "# Left-side type", "variants", "=", "_decompose_type", "(", "left", ")", "# all() will return True for empty variants", "if", "len", "(", "variants", ")", "==", "0", ":", "return", "False", "return", "all", "(", "_issubtype_with_constraints", "(", "variant", ",", "constraints", ",", "recursive", ")", "for", "variant", "in", "variants", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/data/_typing.py#L51-L87
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/factory.py
python
ResourceFactory._create_waiter
(factory_self, resource_waiter_model, resource_name, service_context)
return do_waiter
Creates a new wait method for each resource where both a waiter and resource model is defined.
Creates a new wait method for each resource where both a waiter and resource model is defined.
[ "Creates", "a", "new", "wait", "method", "for", "each", "resource", "where", "both", "a", "waiter", "and", "resource", "model", "is", "defined", "." ]
def _create_waiter(factory_self, resource_waiter_model, resource_name, service_context): """ Creates a new wait method for each resource where both a waiter and resource model is defined. """ waiter = WaiterAction(resource_waiter_model, waiter_resource_name=resource_waiter_model.name) def do_waiter(self, *args, **kwargs): waiter(self, *args, **kwargs) do_waiter.__name__ = str(resource_waiter_model.name) do_waiter.__doc__ = docstring.ResourceWaiterDocstring( resource_name=resource_name, event_emitter=factory_self._emitter, service_model=service_context.service_model, resource_waiter_model=resource_waiter_model, service_waiter_model=service_context.service_waiter_model, include_signature=False ) return do_waiter
[ "def", "_create_waiter", "(", "factory_self", ",", "resource_waiter_model", ",", "resource_name", ",", "service_context", ")", ":", "waiter", "=", "WaiterAction", "(", "resource_waiter_model", ",", "waiter_resource_name", "=", "resource_waiter_model", ".", "name", ")", "def", "do_waiter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "waiter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "do_waiter", ".", "__name__", "=", "str", "(", "resource_waiter_model", ".", "name", ")", "do_waiter", ".", "__doc__", "=", "docstring", ".", "ResourceWaiterDocstring", "(", "resource_name", "=", "resource_name", ",", "event_emitter", "=", "factory_self", ".", "_emitter", ",", "service_model", "=", "service_context", ".", "service_model", ",", "resource_waiter_model", "=", "resource_waiter_model", ",", "service_waiter_model", "=", "service_context", ".", "service_waiter_model", ",", "include_signature", "=", "False", ")", "return", "do_waiter" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/factory.py#L359-L380
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/postgres_search.py
python
PostgresDatabase.KmlSearch
(self, search_term)
return self.Search(search_term, kml_start_template, kml_end_template, self.kml_placemark_)
Search all tables and return resuls as kml.
Search all tables and return resuls as kml.
[ "Search", "all", "tables", "and", "return", "resuls", "as", "kml", "." ]
def KmlSearch(self, search_term): """Search all tables and return resuls as kml.""" return self.Search(search_term, kml_start_template, kml_end_template, self.kml_placemark_)
[ "def", "KmlSearch", "(", "self", ",", "search_term", ")", ":", "return", "self", ".", "Search", "(", "search_term", ",", "kml_start_template", ",", "kml_end_template", ",", "self", ".", "kml_placemark_", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/postgres_search.py#L222-L225
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
VarScrollHelperBase.GetNonOrientationTargetSize
(*args, **kwargs)
return _windows_.VarScrollHelperBase_GetNonOrientationTargetSize(*args, **kwargs)
GetNonOrientationTargetSize(self) -> int
GetNonOrientationTargetSize(self) -> int
[ "GetNonOrientationTargetSize", "(", "self", ")", "-", ">", "int" ]
def GetNonOrientationTargetSize(*args, **kwargs): """GetNonOrientationTargetSize(self) -> int""" return _windows_.VarScrollHelperBase_GetNonOrientationTargetSize(*args, **kwargs)
[ "def", "GetNonOrientationTargetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VarScrollHelperBase_GetNonOrientationTargetSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L2258-L2260
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/playback_benchmark/playback_driver.py
python
PlaybackRequestHandler._GetBenchmarkResource
(self, resource, handler)
Sends requested resource to browser.
Sends requested resource to browser.
[ "Sends", "requested", "resource", "to", "browser", "." ]
def _GetBenchmarkResource(self, resource, handler): "Sends requested resource to browser." if resource in self.benchmark_resources: resource = self.benchmark_resources[resource] handler.send_response(200) handler.send_header('content-length', len(resource['data'])) handler.send_header('content-type', resource['type']) handler.end_headers() handler.wfile.write(resource['data']) else: handler.send_response(404) handler.end_headers()
[ "def", "_GetBenchmarkResource", "(", "self", ",", "resource", ",", "handler", ")", ":", "if", "resource", "in", "self", ".", "benchmark_resources", ":", "resource", "=", "self", ".", "benchmark_resources", "[", "resource", "]", "handler", ".", "send_response", "(", "200", ")", "handler", ".", "send_header", "(", "'content-length'", ",", "len", "(", "resource", "[", "'data'", "]", ")", ")", "handler", ".", "send_header", "(", "'content-type'", ",", "resource", "[", "'type'", "]", ")", "handler", ".", "end_headers", "(", ")", "handler", ".", "wfile", ".", "write", "(", "resource", "[", "'data'", "]", ")", "else", ":", "handler", ".", "send_response", "(", "404", ")", "handler", ".", "end_headers", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/playback_benchmark/playback_driver.py#L159-L171
balloonwj/TeamTalk
dc79c40687e4c9d7bec07ff5c9782be586fd9b41
win-client/3rdParty/src/json/devtools/tarball.py
python
decompress
( tarball_path, base_dir )
Decompress the gzipped tarball into directory base_dir.
Decompress the gzipped tarball into directory base_dir.
[ "Decompress", "the", "gzipped", "tarball", "into", "directory", "base_dir", "." ]
def decompress( tarball_path, base_dir ): """Decompress the gzipped tarball into directory base_dir. """ # !!! This class method is not documented in the online doc # nor is bz2open! tar = tarfile.TarFile.gzopen(tarball_path, mode='r') try: tar.extractall( base_dir ) finally: tar.close()
[ "def", "decompress", "(", "tarball_path", ",", "base_dir", ")", ":", "# !!! This class method is not documented in the online doc", "# nor is bz2open!", "tar", "=", "tarfile", ".", "TarFile", ".", "gzopen", "(", "tarball_path", ",", "mode", "=", "'r'", ")", "try", ":", "tar", ".", "extractall", "(", "base_dir", ")", "finally", ":", "tar", ".", "close", "(", ")" ]
https://github.com/balloonwj/TeamTalk/blob/dc79c40687e4c9d7bec07ff5c9782be586fd9b41/win-client/3rdParty/src/json/devtools/tarball.py#L44-L53
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
util/gerrit-bot/gerrit.py
python
GerritRestAPI.get_account
(self, account_id="self")
return self._get(f"/accounts/{account_id}")
get an account detail from an account_id
get an account detail from an account_id
[ "get", "an", "account", "detail", "from", "an", "account_id" ]
def get_account(self, account_id="self"): """ get an account detail from an account_id """ return self._get(f"/accounts/{account_id}")
[ "def", "get_account", "(", "self", ",", "account_id", "=", "\"self\"", ")", ":", "return", "self", ".", "_get", "(", "f\"/accounts/{account_id}\"", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/gerrit-bot/gerrit.py#L83-L85
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py
python
Parser.p_attribute_2
(self, p)
attribute : NAME
attribute : NAME
[ "attribute", ":", "NAME" ]
def p_attribute_2(self, p): """attribute : NAME""" p[0] = ast.Attribute(p[1], True, filename=self.filename, lineno=p.lineno(1))
[ "def", "p_attribute_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "Attribute", "(", "p", "[", "1", "]", ",", "True", ",", "filename", "=", "self", ".", "filename", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py#L142-L144
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
CleansedLines._CollapseStrings
(elided)
return collapsed
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
Collapses strings and chars on a line to simple "" or '' blocks.
[ "Collapses", "strings", "and", "chars", "on", "a", "line", "to", "simple", "or", "blocks", "." ]
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(elided): return elided # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) # Replace quoted strings and digit separators. Both single quotes # and double quotes are processed in the same loop, otherwise # nested quotes wouldn't work. collapsed = '' while True: # Find the first quote character match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == '"': # Collapse double quoted strings second_quote = tail.find('"') if second_quote >= 0: collapsed += head + '""' elided = tail[second_quote + 1:] else: # Unmatched double quote, don't bother processing the rest # of the line since this is probably a multiline string. collapsed += elided break else: # Found single quote, check nearby text to eliminate digit separators. # # There is no special handling for floating point here, because # the integer/fractional/exponent parts would all be parsed # correctly as long as there are digits on both sides of the # separator. So we are fine as long as we don't see something # like "0.'3" (gcc 4.9.0 will not allow this literal). if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) collapsed += head + match_literal.group(1).replace("'", '') elided = match_literal.group(2) else: second_quote = tail.find('\'') if second_quote >= 0: collapsed += head + "''" elided = tail[second_quote + 1:] else: # Unmatched single quote collapsed += elided break return collapsed
[ "def", "_CollapseStrings", "(", "elided", ")", ":", "if", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "return", "elided", "# Remove escaped characters first to make quote/single quote collapsing", "# basic. Things that look like escaped characters shouldn't occur", "# outside of strings and chars.", "elided", "=", "_RE_PATTERN_CLEANSE_LINE_ESCAPES", ".", "sub", "(", "''", ",", "elided", ")", "# Replace quoted strings and digit separators. Both single quotes", "# and double quotes are processed in the same loop, otherwise", "# nested quotes wouldn't work.", "collapsed", "=", "''", "while", "True", ":", "# Find the first quote character", "match", "=", "Match", "(", "r'^([^\\'\"]*)([\\'\"])(.*)$'", ",", "elided", ")", "if", "not", "match", ":", "collapsed", "+=", "elided", "break", "head", ",", "quote", ",", "tail", "=", "match", ".", "groups", "(", ")", "if", "quote", "==", "'\"'", ":", "# Collapse double quoted strings", "second_quote", "=", "tail", ".", "find", "(", "'\"'", ")", "if", "second_quote", ">=", "0", ":", "collapsed", "+=", "head", "+", "'\"\"'", "elided", "=", "tail", "[", "second_quote", "+", "1", ":", "]", "else", ":", "# Unmatched double quote, don't bother processing the rest", "# of the line since this is probably a multiline string.", "collapsed", "+=", "elided", "break", "else", ":", "# Found single quote, check nearby text to eliminate digit separators.", "#", "# There is no special handling for floating point here, because", "# the integer/fractional/exponent parts would all be parsed", "# correctly as long as there are digits on both sides of the", "# separator. So we are fine as long as we don't see something", "# like \"0.'3\" (gcc 4.9.0 will not allow this literal).", "if", "Search", "(", "r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$'", ",", "head", ")", ":", "match_literal", "=", "Match", "(", "r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$'", ",", "\"'\"", "+", "tail", ")", "collapsed", "+=", "head", "+", "match_literal", ".", "group", "(", "1", ")", ".", "replace", "(", "\"'\"", ",", "''", ")", "elided", "=", "match_literal", ".", "group", "(", "2", ")", "else", ":", "second_quote", "=", "tail", ".", "find", "(", "'\\''", ")", "if", "second_quote", ">=", "0", ":", "collapsed", "+=", "head", "+", "\"''\"", "elided", "=", "tail", "[", "second_quote", "+", "1", ":", "]", "else", ":", "# Unmatched single quote", "collapsed", "+=", "elided", "break", "return", "collapsed" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L1457-L1521
cocos2d/cocos2d-js
f0a7d4fa454de7076c054b677a36c5968a160901
build/android-build.py
python
check_environment_variables_sdk
()
return SDK_ROOT
Checking the environment ANDROID_SDK_ROOT, which will be used for building
Checking the environment ANDROID_SDK_ROOT, which will be used for building
[ "Checking", "the", "environment", "ANDROID_SDK_ROOT", "which", "will", "be", "used", "for", "building" ]
def check_environment_variables_sdk(): ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building ''' try: SDK_ROOT = os.environ['ANDROID_SDK_ROOT'] except Exception: print "ANDROID_SDK_ROOT not defined. Please define ANDROID_SDK_ROOT in your environment" sys.exit(1) return SDK_ROOT
[ "def", "check_environment_variables_sdk", "(", ")", ":", "try", ":", "SDK_ROOT", "=", "os", ".", "environ", "[", "'ANDROID_SDK_ROOT'", "]", "except", "Exception", ":", "print", "\"ANDROID_SDK_ROOT not defined. Please define ANDROID_SDK_ROOT in your environment\"", "sys", ".", "exit", "(", "1", ")", "return", "SDK_ROOT" ]
https://github.com/cocos2d/cocos2d-js/blob/f0a7d4fa454de7076c054b677a36c5968a160901/build/android-build.py#L40-L50
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
configs/example/arm/ruby_fs.py
python
create
(args)
return system
Create and configure the system object.
Create and configure the system object.
[ "Create", "and", "configure", "the", "system", "object", "." ]
def create(args): ''' Create and configure the system object. ''' if args.script and not os.path.isfile(args.script): print("Error: Bootscript %s does not exist" % args.script) sys.exit(1) cpu_class = cpu_types[args.cpu][0] mem_mode = cpu_class.memory_mode() system = devices.ArmRubySystem(args.mem_size, mem_mode=mem_mode, workload=ArmFsLinux( object_file= SysPaths.binary(args.kernel)), readfile=args.script) # Add CPU clusters to the system system.cpu_cluster = [ devices.CpuCluster(system, args.num_cpus, args.cpu_freq, "1.0V", *cpu_types[args.cpu]), ] # Add the PCI devices we need for this system. The base system # doesn't have any PCI devices by default since they are assumed # to be added by the configuration scripts needing them. system.pci_devices = [ # Create a VirtIO block device for the system's boot # disk. Attach the disk image using gem5's Copy-on-Write # functionality to avoid writing changes to the stored copy of # the disk image. PciVirtIO(vio=VirtIOBlock(image=create_cow_image(args.disk_image))), ] # Attach the PCI devices to the system. The helper method in the # system assigns a unique PCI bus ID to each of the devices and # connects them to the IO bus. for dev in system.pci_devices: system.attach_pci(dev) config_ruby(system, args) # Wire up the system's memory system system.connect() # Setup gem5's minimal Linux boot loader. system.realview.setupBootLoader(system, SysPaths.binary) if args.dtb: system.workload.dtb_filename = args.dtb else: # No DTB specified: autogenerate DTB system.workload.dtb_filename = \ os.path.join(m5.options.outdir, 'system.dtb') system.generateDtb(system.workload.dtb_filename) # Linux boot command flags kernel_cmd = [ # Tell Linux to use the simulated serial port as a console "console=ttyAMA0", # Hard-code timi "lpj=19988480", # Disable address space randomisation to get a consistent # memory layout. "norandmaps", # Tell Linux where to find the root disk image. "root=%s" % args.root_device, # Mount the root disk read-write by default. "rw", # Tell Linux about the amount of physical memory present. "mem=%s" % args.mem_size, ] system.workload.command_line = " ".join(kernel_cmd) return system
[ "def", "create", "(", "args", ")", ":", "if", "args", ".", "script", "and", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "script", ")", ":", "print", "(", "\"Error: Bootscript %s does not exist\"", "%", "args", ".", "script", ")", "sys", ".", "exit", "(", "1", ")", "cpu_class", "=", "cpu_types", "[", "args", ".", "cpu", "]", "[", "0", "]", "mem_mode", "=", "cpu_class", ".", "memory_mode", "(", ")", "system", "=", "devices", ".", "ArmRubySystem", "(", "args", ".", "mem_size", ",", "mem_mode", "=", "mem_mode", ",", "workload", "=", "ArmFsLinux", "(", "object_file", "=", "SysPaths", ".", "binary", "(", "args", ".", "kernel", ")", ")", ",", "readfile", "=", "args", ".", "script", ")", "# Add CPU clusters to the system", "system", ".", "cpu_cluster", "=", "[", "devices", ".", "CpuCluster", "(", "system", ",", "args", ".", "num_cpus", ",", "args", ".", "cpu_freq", ",", "\"1.0V\"", ",", "*", "cpu_types", "[", "args", ".", "cpu", "]", ")", ",", "]", "# Add the PCI devices we need for this system. The base system", "# doesn't have any PCI devices by default since they are assumed", "# to be added by the configuration scripts needing them.", "system", ".", "pci_devices", "=", "[", "# Create a VirtIO block device for the system's boot", "# disk. Attach the disk image using gem5's Copy-on-Write", "# functionality to avoid writing changes to the stored copy of", "# the disk image.", "PciVirtIO", "(", "vio", "=", "VirtIOBlock", "(", "image", "=", "create_cow_image", "(", "args", ".", "disk_image", ")", ")", ")", ",", "]", "# Attach the PCI devices to the system. The helper method in the", "# system assigns a unique PCI bus ID to each of the devices and", "# connects them to the IO bus.", "for", "dev", "in", "system", ".", "pci_devices", ":", "system", ".", "attach_pci", "(", "dev", ")", "config_ruby", "(", "system", ",", "args", ")", "# Wire up the system's memory system", "system", ".", "connect", "(", ")", "# Setup gem5's minimal Linux boot loader.", "system", ".", "realview", ".", "setupBootLoader", "(", "system", ",", "SysPaths", ".", "binary", ")", "if", "args", ".", "dtb", ":", "system", ".", "workload", ".", "dtb_filename", "=", "args", ".", "dtb", "else", ":", "# No DTB specified: autogenerate DTB", "system", ".", "workload", ".", "dtb_filename", "=", "os", ".", "path", ".", "join", "(", "m5", ".", "options", ".", "outdir", ",", "'system.dtb'", ")", "system", ".", "generateDtb", "(", "system", ".", "workload", ".", "dtb_filename", ")", "# Linux boot command flags", "kernel_cmd", "=", "[", "# Tell Linux to use the simulated serial port as a console", "\"console=ttyAMA0\"", ",", "# Hard-code timi", "\"lpj=19988480\"", ",", "# Disable address space randomisation to get a consistent", "# memory layout.", "\"norandmaps\"", ",", "# Tell Linux where to find the root disk image.", "\"root=%s\"", "%", "args", ".", "root_device", ",", "# Mount the root disk read-write by default.", "\"rw\"", ",", "# Tell Linux about the amount of physical memory present.", "\"mem=%s\"", "%", "args", ".", "mem_size", ",", "]", "system", ".", "workload", ".", "command_line", "=", "\" \"", ".", "join", "(", "kernel_cmd", ")", "return", "system" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/example/arm/ruby_fs.py#L96-L172
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/blocks.py
python
Block.coerce_to_target_dtype
(self, other)
coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block
coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise
[ "coerce", "the", "current", "block", "to", "a", "dtype", "compat", "for", "other", "we", "will", "return", "a", "block", "possibly", "object", "and", "not", "raise" ]
def coerce_to_target_dtype(self, other): """ coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block """ # if we cannot then coerce to object dtype, _ = infer_dtype_from(other, pandas_dtype=True) if is_dtype_equal(self.dtype, dtype): return self if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype): # we don't upcast to bool return self.astype(object) elif (self.is_float or self.is_complex) and ( is_integer_dtype(dtype) or is_float_dtype(dtype) ): # don't coerce float/complex to int return self elif ( self.is_datetime or is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) ): # not a datetime if not ( (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)) and self.is_datetime ): return self.astype(object) # don't upcast timezone with different timezone or no timezone mytz = getattr(self.dtype, "tz", None) othertz = getattr(dtype, "tz", None) if not tz_compare(mytz, othertz): return self.astype(object) raise AssertionError( f"possible recursion in coerce_to_target_dtype: {self} {other}" ) elif self.is_timedelta or is_timedelta64_dtype(dtype): # not a timedelta if not (is_timedelta64_dtype(dtype) and self.is_timedelta): return self.astype(object) raise AssertionError( f"possible recursion in coerce_to_target_dtype: {self} {other}" ) try: return self.astype(dtype) except (ValueError, TypeError, OverflowError): return self.astype(object)
[ "def", "coerce_to_target_dtype", "(", "self", ",", "other", ")", ":", "# if we cannot then coerce to object", "dtype", ",", "_", "=", "infer_dtype_from", "(", "other", ",", "pandas_dtype", "=", "True", ")", "if", "is_dtype_equal", "(", "self", ".", "dtype", ",", "dtype", ")", ":", "return", "self", "if", "self", ".", "is_bool", "or", "is_object_dtype", "(", "dtype", ")", "or", "is_bool_dtype", "(", "dtype", ")", ":", "# we don't upcast to bool", "return", "self", ".", "astype", "(", "object", ")", "elif", "(", "self", ".", "is_float", "or", "self", ".", "is_complex", ")", "and", "(", "is_integer_dtype", "(", "dtype", ")", "or", "is_float_dtype", "(", "dtype", ")", ")", ":", "# don't coerce float/complex to int", "return", "self", "elif", "(", "self", ".", "is_datetime", "or", "is_datetime64_dtype", "(", "dtype", ")", "or", "is_datetime64tz_dtype", "(", "dtype", ")", ")", ":", "# not a datetime", "if", "not", "(", "(", "is_datetime64_dtype", "(", "dtype", ")", "or", "is_datetime64tz_dtype", "(", "dtype", ")", ")", "and", "self", ".", "is_datetime", ")", ":", "return", "self", ".", "astype", "(", "object", ")", "# don't upcast timezone with different timezone or no timezone", "mytz", "=", "getattr", "(", "self", ".", "dtype", ",", "\"tz\"", ",", "None", ")", "othertz", "=", "getattr", "(", "dtype", ",", "\"tz\"", ",", "None", ")", "if", "not", "tz_compare", "(", "mytz", ",", "othertz", ")", ":", "return", "self", ".", "astype", "(", "object", ")", "raise", "AssertionError", "(", "f\"possible recursion in coerce_to_target_dtype: {self} {other}\"", ")", "elif", "self", ".", "is_timedelta", "or", "is_timedelta64_dtype", "(", "dtype", ")", ":", "# not a timedelta", "if", "not", "(", "is_timedelta64_dtype", "(", "dtype", ")", "and", "self", ".", "is_timedelta", ")", ":", "return", "self", ".", "astype", "(", "object", ")", "raise", "AssertionError", "(", "f\"possible recursion in coerce_to_target_dtype: {self} {other}\"", ")", "try", ":", "return", "self", ".", "astype", "(", "dtype", ")", "except", "(", "ValueError", ",", "TypeError", ",", "OverflowError", ")", ":", "return", "self", ".", "astype", "(", "object", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/blocks.py#L1043-L1105
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/framework/python/framework/tensor_util.py
python
with_shape
(expected_shape, tensor)
return tensor
Asserts tensor has expected shape. If tensor shape and expected_shape, are fully defined, assert they match. Otherwise, add assert op that will validate the shape when tensor is evaluated, and set shape on tensor. Args: expected_shape: Expected shape to assert, as a 1D array of ints, or tensor of same. tensor: Tensor whose shape we're validating. Returns: tensor, perhaps with a dependent assert operation. Raises: ValueError: if tensor has an invalid shape.
Asserts tensor has expected shape.
[ "Asserts", "tensor", "has", "expected", "shape", "." ]
def with_shape(expected_shape, tensor): """Asserts tensor has expected shape. If tensor shape and expected_shape, are fully defined, assert they match. Otherwise, add assert op that will validate the shape when tensor is evaluated, and set shape on tensor. Args: expected_shape: Expected shape to assert, as a 1D array of ints, or tensor of same. tensor: Tensor whose shape we're validating. Returns: tensor, perhaps with a dependent assert operation. Raises: ValueError: if tensor has an invalid shape. """ if isinstance(tensor, sparse_tensor.SparseTensor): raise ValueError('SparseTensor not supported.') # Shape type must be 1D int32. if tensor_util.is_tensor(expected_shape): if expected_shape.dtype.base_dtype != dtypes.int32: raise ValueError( 'Invalid dtype %s for shape %s expected of tensor %s.' % ( expected_shape.dtype, expected_shape, tensor.name)) if isinstance(expected_shape, (list, tuple)): if not expected_shape: expected_shape = np.asarray([], dtype=np.int32) else: np_expected_shape = np.asarray(expected_shape) expected_shape = ( np.asarray(expected_shape, dtype=np.int32) if np_expected_shape.dtype == np.int64 else np_expected_shape) if isinstance(expected_shape, np.ndarray): if expected_shape.ndim > 1: raise ValueError( 'Invalid rank %s for shape %s expected of tensor %s.' % ( expected_shape.ndim, expected_shape, tensor.name)) if expected_shape.dtype != np.int32: raise ValueError( 'Invalid dtype %s for shape %s expected of tensor %s.' % ( expected_shape.dtype, expected_shape, tensor.name)) actual_shape = tensor.get_shape() if (not actual_shape.is_fully_defined() or tensor_util.is_tensor(expected_shape)): with ops.name_scope('%s/' % tensor.op.name, values=[tensor]): if (not tensor_util.is_tensor(expected_shape) and (len(expected_shape) < 1)): # TODO(irving): Remove scalar special case return array_ops.reshape(tensor, []) with ops.control_dependencies([_assert_shape_op(expected_shape, tensor)]): result = array_ops.identity(tensor) if not tensor_util.is_tensor(expected_shape): result.set_shape(expected_shape) return result if (not tensor_util.is_tensor(expected_shape) and not actual_shape.is_compatible_with(expected_shape)): if (len(expected_shape) < 1) and actual_shape.is_compatible_with([1]): # TODO(irving): Remove scalar special case. with ops.name_scope('%s/' % tensor.op.name, values=[tensor]): return array_ops.reshape(tensor, []) raise ValueError('Invalid shape for tensor %s, expected %s, got %s.' % ( tensor.name, expected_shape, actual_shape)) return tensor
[ "def", "with_shape", "(", "expected_shape", ",", "tensor", ")", ":", "if", "isinstance", "(", "tensor", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "raise", "ValueError", "(", "'SparseTensor not supported.'", ")", "# Shape type must be 1D int32.", "if", "tensor_util", ".", "is_tensor", "(", "expected_shape", ")", ":", "if", "expected_shape", ".", "dtype", ".", "base_dtype", "!=", "dtypes", ".", "int32", ":", "raise", "ValueError", "(", "'Invalid dtype %s for shape %s expected of tensor %s.'", "%", "(", "expected_shape", ".", "dtype", ",", "expected_shape", ",", "tensor", ".", "name", ")", ")", "if", "isinstance", "(", "expected_shape", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "expected_shape", ":", "expected_shape", "=", "np", ".", "asarray", "(", "[", "]", ",", "dtype", "=", "np", ".", "int32", ")", "else", ":", "np_expected_shape", "=", "np", ".", "asarray", "(", "expected_shape", ")", "expected_shape", "=", "(", "np", ".", "asarray", "(", "expected_shape", ",", "dtype", "=", "np", ".", "int32", ")", "if", "np_expected_shape", ".", "dtype", "==", "np", ".", "int64", "else", "np_expected_shape", ")", "if", "isinstance", "(", "expected_shape", ",", "np", ".", "ndarray", ")", ":", "if", "expected_shape", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "'Invalid rank %s for shape %s expected of tensor %s.'", "%", "(", "expected_shape", ".", "ndim", ",", "expected_shape", ",", "tensor", ".", "name", ")", ")", "if", "expected_shape", ".", "dtype", "!=", "np", ".", "int32", ":", "raise", "ValueError", "(", "'Invalid dtype %s for shape %s expected of tensor %s.'", "%", "(", "expected_shape", ".", "dtype", ",", "expected_shape", ",", "tensor", ".", "name", ")", ")", "actual_shape", "=", "tensor", ".", "get_shape", "(", ")", "if", "(", "not", "actual_shape", ".", "is_fully_defined", "(", ")", "or", "tensor_util", ".", "is_tensor", "(", "expected_shape", ")", ")", ":", "with", "ops", ".", "name_scope", "(", "'%s/'", "%", "tensor", ".", "op", ".", "name", ",", "values", "=", "[", "tensor", "]", ")", ":", "if", "(", "not", "tensor_util", ".", "is_tensor", "(", "expected_shape", ")", "and", "(", "len", "(", "expected_shape", ")", "<", "1", ")", ")", ":", "# TODO(irving): Remove scalar special case", "return", "array_ops", ".", "reshape", "(", "tensor", ",", "[", "]", ")", "with", "ops", ".", "control_dependencies", "(", "[", "_assert_shape_op", "(", "expected_shape", ",", "tensor", ")", "]", ")", ":", "result", "=", "array_ops", ".", "identity", "(", "tensor", ")", "if", "not", "tensor_util", ".", "is_tensor", "(", "expected_shape", ")", ":", "result", ".", "set_shape", "(", "expected_shape", ")", "return", "result", "if", "(", "not", "tensor_util", ".", "is_tensor", "(", "expected_shape", ")", "and", "not", "actual_shape", ".", "is_compatible_with", "(", "expected_shape", ")", ")", ":", "if", "(", "len", "(", "expected_shape", ")", "<", "1", ")", "and", "actual_shape", ".", "is_compatible_with", "(", "[", "1", "]", ")", ":", "# TODO(irving): Remove scalar special case.", "with", "ops", ".", "name_scope", "(", "'%s/'", "%", "tensor", ".", "op", ".", "name", ",", "values", "=", "[", "tensor", "]", ")", ":", "return", "array_ops", ".", "reshape", "(", "tensor", ",", "[", "]", ")", "raise", "ValueError", "(", "'Invalid shape for tensor %s, expected %s, got %s.'", "%", "(", "tensor", ".", "name", ",", "expected_shape", ",", "actual_shape", ")", ")", "return", "tensor" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/framework/python/framework/tensor_util.py#L205-L272
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
PyGridCellAttrProvider._setCallbackInfo
(*args, **kwargs)
return _grid.PyGridCellAttrProvider__setCallbackInfo(*args, **kwargs)
_setCallbackInfo(self, PyObject self, PyObject _class)
_setCallbackInfo(self, PyObject self, PyObject _class)
[ "_setCallbackInfo", "(", "self", "PyObject", "self", "PyObject", "_class", ")" ]
def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _grid.PyGridCellAttrProvider__setCallbackInfo(*args, **kwargs)
[ "def", "_setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "PyGridCellAttrProvider__setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L721-L723
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
FieldDomain.SetSplitPolicy
(self, *args)
return _ogr.FieldDomain_SetSplitPolicy(self, *args)
r"""SetSplitPolicy(FieldDomain self, OGRFieldDomainSplitPolicy policy)
r"""SetSplitPolicy(FieldDomain self, OGRFieldDomainSplitPolicy policy)
[ "r", "SetSplitPolicy", "(", "FieldDomain", "self", "OGRFieldDomainSplitPolicy", "policy", ")" ]
def SetSplitPolicy(self, *args): r"""SetSplitPolicy(FieldDomain self, OGRFieldDomainSplitPolicy policy)""" return _ogr.FieldDomain_SetSplitPolicy(self, *args)
[ "def", "SetSplitPolicy", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "FieldDomain_SetSplitPolicy", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L7584-L7586
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
_OutputFormat
()
return _cpplint_state.output_format
Gets the module's output format.
Gets the module's output format.
[ "Gets", "the", "module", "s", "output", "format", "." ]
def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format
[ "def", "_OutputFormat", "(", ")", ":", "return", "_cpplint_state", ".", "output_format" ]
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L851-L853
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib2to3/pytree.py
python
WildcardPattern._iterative_matches
(self, nodes)
Helper to iteratively yield the matches.
Helper to iteratively yield the matches.
[ "Helper", "to", "iteratively", "yield", "the", "matches", "." ]
def _iterative_matches(self, nodes): """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results
[ "def", "_iterative_matches", "(", "self", ",", "nodes", ")", ":", "nodelen", "=", "len", "(", "nodes", ")", "if", "0", ">=", "self", ".", "min", ":", "yield", "0", ",", "{", "}", "results", "=", "[", "]", "# generate matches that use just one alt from self.content", "for", "alt", "in", "self", ".", "content", ":", "for", "c", ",", "r", "in", "generate_matches", "(", "alt", ",", "nodes", ")", ":", "yield", "c", ",", "r", "results", ".", "append", "(", "(", "c", ",", "r", ")", ")", "# for each match, iterate down the nodes", "while", "results", ":", "new_results", "=", "[", "]", "for", "c0", ",", "r0", "in", "results", ":", "# stop if the entire set of nodes has been matched", "if", "c0", "<", "nodelen", "and", "c0", "<=", "self", ".", "max", ":", "for", "alt", "in", "self", ".", "content", ":", "for", "c1", ",", "r1", "in", "generate_matches", "(", "alt", ",", "nodes", "[", "c0", ":", "]", ")", ":", "if", "c1", ">", "0", ":", "r", "=", "{", "}", "r", ".", "update", "(", "r0", ")", "r", ".", "update", "(", "r1", ")", "yield", "c0", "+", "c1", ",", "r", "new_results", ".", "append", "(", "(", "c0", "+", "c1", ",", "r", ")", ")", "results", "=", "new_results" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pytree.py#L767-L794
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/platform/tf_logging.py
python
log_if
(level, msg, condition, *args)
Log 'msg % args' at level 'level' only if condition is fulfilled.
Log 'msg % args' at level 'level' only if condition is fulfilled.
[ "Log", "msg", "%", "args", "at", "level", "level", "only", "if", "condition", "is", "fulfilled", "." ]
def log_if(level, msg, condition, *args): """Log 'msg % args' at level 'level' only if condition is fulfilled.""" if condition: vlog(level, msg, *args)
[ "def", "log_if", "(", "level", ",", "msg", ",", "condition", ",", "*", "args", ")", ":", "if", "condition", ":", "vlog", "(", "level", ",", "msg", ",", "*", "args", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/platform/tf_logging.py#L252-L255
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/utils/io.py
python
Tee.close
(self)
Close the file and restore the channel.
Close the file and restore the channel.
[ "Close", "the", "file", "and", "restore", "the", "channel", "." ]
def close(self): """Close the file and restore the channel.""" self.flush() setattr(sys, self.channel, self.ostream) self.file.close() self._closed = True
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "setattr", "(", "sys", ",", "self", ".", "channel", ",", "self", ".", "ostream", ")", "self", ".", "file", ".", "close", "(", ")", "self", ".", "_closed", "=", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/io.py#L134-L139
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/rj_gameplay/play/restart.py
python
DirectRestartPlay.__init__
(self)
self.pass_tactic = pass_tactic.Pass( self.target_point, pass_tactic.PasserCost(self.target_point), pass_tactic.PassToClosestReceiver(self.target_point)) self.seek_tactic = pass_seek.Seek( self.target_point, pass_seek.restart_seek, pass_seek.SeekCost(self.target_point))
self.pass_tactic = pass_tactic.Pass( self.target_point, pass_tactic.PasserCost(self.target_point), pass_tactic.PassToClosestReceiver(self.target_point)) self.seek_tactic = pass_seek.Seek( self.target_point, pass_seek.restart_seek, pass_seek.SeekCost(self.target_point))
[ "self", ".", "pass_tactic", "=", "pass_tactic", ".", "Pass", "(", "self", ".", "target_point", "pass_tactic", ".", "PasserCost", "(", "self", ".", "target_point", ")", "pass_tactic", ".", "PassToClosestReceiver", "(", "self", ".", "target_point", "))", "self", ".", "seek_tactic", "=", "pass_seek", ".", "Seek", "(", "self", ".", "target_point", "pass_seek", ".", "restart_seek", "pass_seek", ".", "SeekCost", "(", "self", ".", "target_point", "))" ]
def __init__(self): self.target_point = np.array([1.0, 4.0]) # TODO: simplify tactic with list (see basic_defense.py) self.goalie_tactic = goalie_tactic.GoalieTactic() self.clear_tactic = clear_tactic.Clear( np.array([0.0, 9.0]), chip=False, kick_speed=5.5 ) # TODO: make it pass """ self.pass_tactic = pass_tactic.Pass( self.target_point, pass_tactic.PasserCost(self.target_point), pass_tactic.PassToClosestReceiver(self.target_point)) self.seek_tactic = pass_seek.Seek( self.target_point, pass_seek.restart_seek, pass_seek.SeekCost(self.target_point)) """ self.wall_tactic_1 = wall_tactic.WallTactic(role.Priority.LOW, cost_scale=0.1) self.wall_tactic_2 = wall_tactic.WallTactic(role.Priority.LOW, cost_scale=0.1) # might need to change to for-loop self.num_wallers = 2 left_pt = np.array([1.5, 7.5]) self.seek_left = pass_seek.Seek( left_pt, pass_seek.build_seek_function(left_pt), pass_seek.SeekCost(left_pt), ) right_pt = np.array([-1.5, 7.5]) self.seek_right = pass_seek.Seek( right_pt, pass_seek.build_seek_function(right_pt), pass_seek.SeekCost(right_pt), ) self.role_assigner = NaiveRoleAssignment()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "target_point", "=", "np", ".", "array", "(", "[", "1.0", ",", "4.0", "]", ")", "# TODO: simplify tactic with list (see basic_defense.py)", "self", ".", "goalie_tactic", "=", "goalie_tactic", ".", "GoalieTactic", "(", ")", "self", ".", "clear_tactic", "=", "clear_tactic", ".", "Clear", "(", "np", ".", "array", "(", "[", "0.0", ",", "9.0", "]", ")", ",", "chip", "=", "False", ",", "kick_speed", "=", "5.5", ")", "# TODO: make it pass", "self", ".", "wall_tactic_1", "=", "wall_tactic", ".", "WallTactic", "(", "role", ".", "Priority", ".", "LOW", ",", "cost_scale", "=", "0.1", ")", "self", ".", "wall_tactic_2", "=", "wall_tactic", ".", "WallTactic", "(", "role", ".", "Priority", ".", "LOW", ",", "cost_scale", "=", "0.1", ")", "# might need to change to for-loop", "self", ".", "num_wallers", "=", "2", "left_pt", "=", "np", ".", "array", "(", "[", "1.5", ",", "7.5", "]", ")", "self", ".", "seek_left", "=", "pass_seek", ".", "Seek", "(", "left_pt", ",", "pass_seek", ".", "build_seek_function", "(", "left_pt", ")", ",", "pass_seek", ".", "SeekCost", "(", "left_pt", ")", ",", ")", "right_pt", "=", "np", ".", "array", "(", "[", "-", "1.5", ",", "7.5", "]", ")", "self", ".", "seek_right", "=", "pass_seek", ".", "Seek", "(", "right_pt", ",", "pass_seek", ".", "build_seek_function", "(", "right_pt", ")", ",", "pass_seek", ".", "SeekCost", "(", "right_pt", ")", ",", ")", "self", ".", "role_assigner", "=", "NaiveRoleAssignment", "(", ")" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/rj_gameplay/play/restart.py#L134-L171
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/bottle/bottle.py
python
_re_flatten
(p)
return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
Turn all capturing groups in a regular expression pattern into non-capturing groups.
Turn all capturing groups in a regular expression pattern into non-capturing groups.
[ "Turn", "all", "capturing", "groups", "in", "a", "regular", "expression", "pattern", "into", "non", "-", "capturing", "groups", "." ]
def _re_flatten(p): ''' Turn all capturing groups in a regular expression pattern into non-capturing groups. ''' if '(' not in p: return p return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
[ "def", "_re_flatten", "(", "p", ")", ":", "if", "'('", "not", "in", "p", ":", "return", "p", "return", "re", ".", "sub", "(", "r'(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))'", ",", "lambda", "m", ":", "m", ".", "group", "(", "0", ")", "if", "len", "(", "m", ".", "group", "(", "1", ")", ")", "%", "2", "else", "m", ".", "group", "(", "1", ")", "+", "'(?:'", ",", "p", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/bottle/bottle.py#L244-L249
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pickletools.py
python
genops
(pickle)
return _genops(pickle)
Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None.
Generate all the opcodes in a pickle.
[ "Generate", "all", "the", "opcodes", "in", "a", "pickle", "." ]
def genops(pickle): """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. """ return _genops(pickle)
[ "def", "genops", "(", "pickle", ")", ":", "return", "_genops", "(", "pickle", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pickletools.py#L2222-L2245
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/grpc_debug_server.py
python
EventListenerBaseServicer.SendSourceFiles
(self, request, context)
return debug_service_pb2.EventReply()
Base implementation of the handling of SendSourceFiles calls. The base implementation does nothing with the incoming request. Override in an implementation of the server if necessary. Args: request: A `DebuggedSourceFiles` proto, containing the path, content, size and last-modified timestamp of source files. context: Server context. Returns: A `EventReply` proto.
Base implementation of the handling of SendSourceFiles calls.
[ "Base", "implementation", "of", "the", "handling", "of", "SendSourceFiles", "calls", "." ]
def SendSourceFiles(self, request, context): """Base implementation of the handling of SendSourceFiles calls. The base implementation does nothing with the incoming request. Override in an implementation of the server if necessary. Args: request: A `DebuggedSourceFiles` proto, containing the path, content, size and last-modified timestamp of source files. context: Server context. Returns: A `EventReply` proto. """ return debug_service_pb2.EventReply()
[ "def", "SendSourceFiles", "(", "self", ",", "request", ",", "context", ")", ":", "return", "debug_service_pb2", ".", "EventReply", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/grpc_debug_server.py#L478-L492
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/frame.py
python
DataFrame.assign
(self, **kwargs)
return data
r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas doesn't check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned. Returns ------- DataFrame A new DataFrame with the new columns in addition to all the existing columns. Notes ----- Assigning multiple columns within the same ``assign`` is possible. Later items in '\*\*kwargs' may refer to newly created or modified columns in 'df'; items are computed and assigned into 'df' in order. Examples -------- >>> df = pd.DataFrame({'temp_c': [17.0, 25.0]}, ... index=['Portland', 'Berkeley']) >>> df temp_c Portland 17.0 Berkeley 25.0 Where the value is a callable, evaluated on `df`: >>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 Alternatively, the same behavior can be achieved by directly referencing an existing Series or sequence: >>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 You can create multiple columns within the same assign where one of the columns depends on another one defined within the same assign: >>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32, ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9) temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15
r""" Assign new columns to a DataFrame.
[ "r", "Assign", "new", "columns", "to", "a", "DataFrame", "." ]
def assign(self, **kwargs) -> DataFrame: r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas doesn't check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned. Returns ------- DataFrame A new DataFrame with the new columns in addition to all the existing columns. Notes ----- Assigning multiple columns within the same ``assign`` is possible. Later items in '\*\*kwargs' may refer to newly created or modified columns in 'df'; items are computed and assigned into 'df' in order. Examples -------- >>> df = pd.DataFrame({'temp_c': [17.0, 25.0]}, ... index=['Portland', 'Berkeley']) >>> df temp_c Portland 17.0 Berkeley 25.0 Where the value is a callable, evaluated on `df`: >>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 Alternatively, the same behavior can be achieved by directly referencing an existing Series or sequence: >>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32) temp_c temp_f Portland 17.0 62.6 Berkeley 25.0 77.0 You can create multiple columns within the same assign where one of the columns depends on another one defined within the same assign: >>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32, ... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9) temp_c temp_f temp_k Portland 17.0 62.6 290.15 Berkeley 25.0 77.0 298.15 """ data = self.copy() for k, v in kwargs.items(): data[k] = com.apply_if_callable(v, data) return data
[ "def", "assign", "(", "self", ",", "*", "*", "kwargs", ")", "->", "DataFrame", ":", "data", "=", "self", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "data", "[", "k", "]", "=", "com", ".", "apply_if_callable", "(", "v", ",", "data", ")", "return", "data" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/frame.py#L4421-L4487
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/ipc_messages_log.py
python
_ReadLines
(f)
Read from file f and generate right-stripped lines.
Read from file f and generate right-stripped lines.
[ "Read", "from", "file", "f", "and", "generate", "right", "-", "stripped", "lines", "." ]
def _ReadLines(f): """Read from file f and generate right-stripped lines.""" for line in f: yield line.rstrip()
[ "def", "_ReadLines", "(", "f", ")", ":", "for", "line", "in", "f", ":", "yield", "line", ".", "rstrip", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/ipc_messages_log.py#L34-L37
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/boringssl/src/util/bot/go/bootstrap.py
python
get_toolset_url
()
return '%s/%s.%s' % (DOWNLOAD_URL_PREFIX, TOOLSET_VERSION, variant)
URL of a platform specific Go toolset archive.
URL of a platform specific Go toolset archive.
[ "URL", "of", "a", "platform", "specific", "Go", "toolset", "archive", "." ]
def get_toolset_url(): """URL of a platform specific Go toolset archive.""" # TODO(vadimsh): Support toolset for cross-compilation. arch = { 'amd64': 'x86-64', 'x86_64': 'x86-64', 'i386': 'x86-32', 'x86': 'x86-32', }.get(platform.machine().lower()) variant = TOOLSET_VARIANTS.get((sys.platform, arch)) if not variant: # TODO(vadimsh): Compile go lang from source. raise Failure('Unrecognized platform') return '%s/%s.%s' % (DOWNLOAD_URL_PREFIX, TOOLSET_VERSION, variant)
[ "def", "get_toolset_url", "(", ")", ":", "# TODO(vadimsh): Support toolset for cross-compilation.", "arch", "=", "{", "'amd64'", ":", "'x86-64'", ",", "'x86_64'", ":", "'x86-64'", ",", "'i386'", ":", "'x86-32'", ",", "'x86'", ":", "'x86-32'", ",", "}", ".", "get", "(", "platform", ".", "machine", "(", ")", ".", "lower", "(", ")", ")", "variant", "=", "TOOLSET_VARIANTS", ".", "get", "(", "(", "sys", ".", "platform", ",", "arch", ")", ")", "if", "not", "variant", ":", "# TODO(vadimsh): Compile go lang from source.", "raise", "Failure", "(", "'Unrecognized platform'", ")", "return", "'%s/%s.%s'", "%", "(", "DOWNLOAD_URL_PREFIX", ",", "TOOLSET_VERSION", ",", "variant", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/boringssl/src/util/bot/go/bootstrap.py#L67-L80
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/nn_impl.py
python
batch_norm_with_global_normalization_v2
(input, mean, variance, beta, gamma, variance_epsilon, scale_after_normalization, name=None)
return batch_norm_with_global_normalization(t=input, m=mean, v=variance, beta=beta, gamma=gamma, variance_epsilon=variance_epsilon, scale_after_normalization=scale_after_normalization, name=name)
Batch normalization. This op is deprecated. See `tf.nn.batch_normalization`. Args: input: A 4D input Tensor. mean: A 1D mean Tensor with size matching the last dimension of t. This is the first output from tf.nn.moments, or a saved moving average thereof. variance: A 1D variance Tensor with size matching the last dimension of t. This is the second output from tf.nn.moments, or a saved moving average thereof. beta: A 1D beta Tensor with size matching the last dimension of t. An offset to be added to the normalized tensor. gamma: A 1D gamma Tensor with size matching the last dimension of t. If "scale_after_normalization" is true, this tensor will be multiplied with the normalized tensor. variance_epsilon: A small float number to avoid dividing by 0. scale_after_normalization: A bool indicating whether the resulted tensor needs to be multiplied with gamma. name: A name for this operation (optional). Returns: A batch-normalized `t`. References: Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))
Batch normalization.
[ "Batch", "normalization", "." ]
def batch_norm_with_global_normalization_v2(input, mean, variance, beta, gamma, variance_epsilon, scale_after_normalization, name=None): """Batch normalization. This op is deprecated. See `tf.nn.batch_normalization`. Args: input: A 4D input Tensor. mean: A 1D mean Tensor with size matching the last dimension of t. This is the first output from tf.nn.moments, or a saved moving average thereof. variance: A 1D variance Tensor with size matching the last dimension of t. This is the second output from tf.nn.moments, or a saved moving average thereof. beta: A 1D beta Tensor with size matching the last dimension of t. An offset to be added to the normalized tensor. gamma: A 1D gamma Tensor with size matching the last dimension of t. If "scale_after_normalization" is true, this tensor will be multiplied with the normalized tensor. variance_epsilon: A small float number to avoid dividing by 0. scale_after_normalization: A bool indicating whether the resulted tensor needs to be multiplied with gamma. name: A name for this operation (optional). Returns: A batch-normalized `t`. References: Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) """ return batch_norm_with_global_normalization(t=input, m=mean, v=variance, beta=beta, gamma=gamma, variance_epsilon=variance_epsilon, scale_after_normalization=scale_after_normalization, name=name)
[ "def", "batch_norm_with_global_normalization_v2", "(", "input", ",", "mean", ",", "variance", ",", "beta", ",", "gamma", ",", "variance_epsilon", ",", "scale_after_normalization", ",", "name", "=", "None", ")", ":", "return", "batch_norm_with_global_normalization", "(", "t", "=", "input", ",", "m", "=", "mean", ",", "v", "=", "variance", ",", "beta", "=", "beta", ",", "gamma", "=", "gamma", ",", "variance_epsilon", "=", "variance_epsilon", ",", "scale_after_normalization", "=", "scale_after_normalization", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_impl.py#L1759-L1804
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/slot_creator.py
python
_create_slot_var
(primary, val, scope)
return slot
Helper function for creating a slot variable.
Helper function for creating a slot variable.
[ "Helper", "function", "for", "creating", "a", "slot", "variable", "." ]
def _create_slot_var(primary, val, scope): """Helper function for creating a slot variable.""" slot = variables.Variable(val, name=scope, trainable=False) # pylint: disable=protected-access if isinstance(primary, variables.Variable) and primary._save_slice_info: # Primary is a partitioned variable, so we need to also indicate that # the slot is a partitioned variable. Slots have the same partitioning # as their primaries. real_slot_name = scope[len(primary.op.name + "/"):-1] slice_info = primary._save_slice_info slot._set_save_slice_info(variables.Variable.SaveSliceInfo( slice_info.full_name + "/" + real_slot_name, slice_info.full_shape[:], slice_info.var_offset[:], slice_info.var_shape[:])) # pylint: enable=protected-access return slot
[ "def", "_create_slot_var", "(", "primary", ",", "val", ",", "scope", ")", ":", "slot", "=", "variables", ".", "Variable", "(", "val", ",", "name", "=", "scope", ",", "trainable", "=", "False", ")", "# pylint: disable=protected-access", "if", "isinstance", "(", "primary", ",", "variables", ".", "Variable", ")", "and", "primary", ".", "_save_slice_info", ":", "# Primary is a partitioned variable, so we need to also indicate that", "# the slot is a partitioned variable. Slots have the same partitioning", "# as their primaries.", "real_slot_name", "=", "scope", "[", "len", "(", "primary", ".", "op", ".", "name", "+", "\"/\"", ")", ":", "-", "1", "]", "slice_info", "=", "primary", ".", "_save_slice_info", "slot", ".", "_set_save_slice_info", "(", "variables", ".", "Variable", ".", "SaveSliceInfo", "(", "slice_info", ".", "full_name", "+", "\"/\"", "+", "real_slot_name", ",", "slice_info", ".", "full_shape", "[", ":", "]", ",", "slice_info", ".", "var_offset", "[", ":", "]", ",", "slice_info", ".", "var_shape", "[", ":", "]", ")", ")", "# pylint: enable=protected-access", "return", "slot" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/slot_creator.py#L47-L64
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/eager/function.py
python
defun
(func)
return tf_decorator.make_decorator(func, named_defun(func, func.__name__))
Decorator to compile func into graph_mode. `defun` converts a function that constructs a TensorFlow graph into a function that executes the graph. TensorFlow graphs typically execute faster and with a lower memory-footprint than executing each of the operations that make up the function individually as the TensorFlow runtime can optimize the graph and execute sub-operations in parallel. func must be a Python function that constructs a TensorFlow graph, typically using functions in the tensorflow module. Arguments to func can be either Tensor objects or Python objects. Non-Tensor python objects are treated as constants, and new function definitions are created internally based on their values. func must return a tf.Tensor (NOT a Tensor) or a list of tf.Tensor (NOT a Tensor). Control flow constructs (e.g., `if`, `while`) are not yet compatible with `defun`. Example: ```python def f(x, y): return tf.reduce_mean(tf.multiply(x ** 2, 3) + y) @tfe.defun def g(x, y): return tf.reduce_mean(tf.multiply(x ** 2, 3) + y) x = tf.constant([[2.0, 3.0]]) y = tf.constant([[3.0, -2.0]]) # The plain function and defun-compiled function should return the same value. assert f(x, y).numpy() == g(x, y).numpy() # After the first invocation, the defun-compiled (graph) function runs faster # than the plain function because the defun-compiled function does not involve # Python interpreter overhead during the execution. %time print(f(x, y)) %time print(g(x, y)) ``` Args: func: function to be compiled. Returns: A callable that will execute the compiled function (and return zero or more Tensor objects).
Decorator to compile func into graph_mode.
[ "Decorator", "to", "compile", "func", "into", "graph_mode", "." ]
def defun(func): """Decorator to compile func into graph_mode. `defun` converts a function that constructs a TensorFlow graph into a function that executes the graph. TensorFlow graphs typically execute faster and with a lower memory-footprint than executing each of the operations that make up the function individually as the TensorFlow runtime can optimize the graph and execute sub-operations in parallel. func must be a Python function that constructs a TensorFlow graph, typically using functions in the tensorflow module. Arguments to func can be either Tensor objects or Python objects. Non-Tensor python objects are treated as constants, and new function definitions are created internally based on their values. func must return a tf.Tensor (NOT a Tensor) or a list of tf.Tensor (NOT a Tensor). Control flow constructs (e.g., `if`, `while`) are not yet compatible with `defun`. Example: ```python def f(x, y): return tf.reduce_mean(tf.multiply(x ** 2, 3) + y) @tfe.defun def g(x, y): return tf.reduce_mean(tf.multiply(x ** 2, 3) + y) x = tf.constant([[2.0, 3.0]]) y = tf.constant([[3.0, -2.0]]) # The plain function and defun-compiled function should return the same value. assert f(x, y).numpy() == g(x, y).numpy() # After the first invocation, the defun-compiled (graph) function runs faster # than the plain function because the defun-compiled function does not involve # Python interpreter overhead during the execution. %time print(f(x, y)) %time print(g(x, y)) ``` Args: func: function to be compiled. Returns: A callable that will execute the compiled function (and return zero or more Tensor objects). """ # TODO(apassos): deal with captured global state. Deal with control flow. return tf_decorator.make_decorator(func, named_defun(func, func.__name__))
[ "def", "defun", "(", "func", ")", ":", "# TODO(apassos): deal with captured global state. Deal with control flow.", "return", "tf_decorator", ".", "make_decorator", "(", "func", ",", "named_defun", "(", "func", ",", "func", ".", "__name__", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/function.py#L520-L571
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/scatter_nd_update.py
python
_scatter_nd_update_tbe
()
return
ScatterNdUpdate TBE register
ScatterNdUpdate TBE register
[ "ScatterNdUpdate", "TBE", "register" ]
def _scatter_nd_update_tbe(): """ScatterNdUpdate TBE register""" return
[ "def", "_scatter_nd_update_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/scatter_nd_update.py#L40-L42
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/tools/sanitizers/sancov_formatter.py
python
merge
(options)
Implements the 'merge' action of this tool.
Implements the 'merge' action of this tool.
[ "Implements", "the", "merge", "action", "of", "this", "tool", "." ]
def merge(options): """Implements the 'merge' action of this tool.""" # Check if folder with coverage output exists. assert (os.path.exists(options.coverage_dir) and os.path.isdir(options.coverage_dir)) # Inputs for multiprocessing. List of tuples of: # Coverage dir, absoluate path to executable, sancov file name. inputs = [] for sancov_file in os.listdir(options.coverage_dir): match = SANCOV_FILE_RE.match(sancov_file) if match: inputs.append(( options.coverage_dir, os.path.join(options.build_dir, match.group(1)), sancov_file, )) logging.info('Merging %d sancov files into %s', len(inputs), options.json_input) # Post-process covered lines in parallel. pool = Pool(CPUS) try: results = pool.imap_unordered(get_covered_lines, inputs) finally: pool.close() # Load existing json data file for merging the results. with open(options.json_input, 'r') as f: data = json.load(f) # Merge muliprocessing results. Mutates data. merge_covered_line_results(data, results) logging.info('Merged data from %d executables, which covers %d files.', len(data['tests']), len(data['files'])) logging.info('Writing results to %s', options.json_output) # Write merged results to file. with open(options.json_output, 'w') as f: json.dump(data, f, sort_keys=True)
[ "def", "merge", "(", "options", ")", ":", "# Check if folder with coverage output exists.", "assert", "(", "os", ".", "path", ".", "exists", "(", "options", ".", "coverage_dir", ")", "and", "os", ".", "path", ".", "isdir", "(", "options", ".", "coverage_dir", ")", ")", "# Inputs for multiprocessing. List of tuples of:", "# Coverage dir, absoluate path to executable, sancov file name.", "inputs", "=", "[", "]", "for", "sancov_file", "in", "os", ".", "listdir", "(", "options", ".", "coverage_dir", ")", ":", "match", "=", "SANCOV_FILE_RE", ".", "match", "(", "sancov_file", ")", "if", "match", ":", "inputs", ".", "append", "(", "(", "options", ".", "coverage_dir", ",", "os", ".", "path", ".", "join", "(", "options", ".", "build_dir", ",", "match", ".", "group", "(", "1", ")", ")", ",", "sancov_file", ",", ")", ")", "logging", ".", "info", "(", "'Merging %d sancov files into %s'", ",", "len", "(", "inputs", ")", ",", "options", ".", "json_input", ")", "# Post-process covered lines in parallel.", "pool", "=", "Pool", "(", "CPUS", ")", "try", ":", "results", "=", "pool", ".", "imap_unordered", "(", "get_covered_lines", ",", "inputs", ")", "finally", ":", "pool", ".", "close", "(", ")", "# Load existing json data file for merging the results.", "with", "open", "(", "options", ".", "json_input", ",", "'r'", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "# Merge muliprocessing results. Mutates data.", "merge_covered_line_results", "(", "data", ",", "results", ")", "logging", ".", "info", "(", "'Merged data from %d executables, which covers %d files.'", ",", "len", "(", "data", "[", "'tests'", "]", ")", ",", "len", "(", "data", "[", "'files'", "]", ")", ")", "logging", ".", "info", "(", "'Writing results to %s'", ",", "options", ".", "json_output", ")", "# Write merged results to file.", "with", "open", "(", "options", ".", "json_output", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "sort_keys", "=", "True", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/tools/sanitizers/sancov_formatter.py#L338-L380
tenzir/vast
ff450d61f35c721db1760339869085a89222386f
pyvast/pyvast/vast.py
python
VAST.test_connection
(self)
return proc.returncode == 0
Checks if the configured endpoint is reachable
Checks if the configured endpoint is reachable
[ "Checks", "if", "the", "configured", "endpoint", "is", "reachable" ]
async def test_connection(self): """Checks if the configured endpoint is reachable""" proc = await self.__spawn("status") await proc.wait() return proc.returncode == 0
[ "async", "def", "test_connection", "(", "self", ")", ":", "proc", "=", "await", "self", ".", "__spawn", "(", "\"status\"", ")", "await", "proc", ".", "wait", "(", ")", "return", "proc", ".", "returncode", "==", "0" ]
https://github.com/tenzir/vast/blob/ff450d61f35c721db1760339869085a89222386f/pyvast/pyvast/vast.py#L59-L63
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/input/vasploader.py
python
_to_text
(item: ElementTree.Element)
return item.text
Get an Element.text property, avoiding confusing type errors
Get an Element.text property, avoiding confusing type errors
[ "Get", "an", "Element", ".", "text", "property", "avoiding", "confusing", "type", "errors" ]
def _to_text(item: ElementTree.Element) -> str: """Get an Element.text property, avoiding confusing type errors""" if item.text is None: raise ValueError(f"XML Element {item} didn't contain expected text") return item.text
[ "def", "_to_text", "(", "item", ":", "ElementTree", ".", "Element", ")", "->", "str", ":", "if", "item", ".", "text", "is", "None", ":", "raise", "ValueError", "(", "f\"XML Element {item} didn't contain expected text\"", ")", "return", "item", ".", "text" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/vasploader.py#L360-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
PositionEnding.checkin
(self, pos)
return pos.checkfor(self.ending)
Check for the ending
Check for the ending
[ "Check", "for", "the", "ending" ]
def checkin(self, pos): "Check for the ending" return pos.checkfor(self.ending)
[ "def", "checkin", "(", "self", ",", "pos", ")", ":", "return", "pos", ".", "checkfor", "(", "self", ".", "ending", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2007-L2009
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/inputtransformer.py
python
_tr_system2
(line_info)
return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
Translate lines escaped with: !!
Translate lines escaped with: !!
[ "Translate", "lines", "escaped", "with", ":", "!!" ]
def _tr_system2(line_info): "Translate lines escaped with: !!" cmd = line_info.line.lstrip()[2:] return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
[ "def", "_tr_system2", "(", "line_info", ")", ":", "cmd", "=", "line_info", ".", "line", ".", "lstrip", "(", ")", "[", "2", ":", "]", "return", "'%sget_ipython().getoutput(%r)'", "%", "(", "line_info", ".", "pre", ",", "cmd", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/inputtransformer.py#L220-L223
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/base.py
python
BaseContext.pair_second
(self, builder, val, ty)
return pair.second
Extract the second element of a heterogeneous pair.
Extract the second element of a heterogeneous pair.
[ "Extract", "the", "second", "element", "of", "a", "heterogeneous", "pair", "." ]
def pair_second(self, builder, val, ty): """ Extract the second element of a heterogeneous pair. """ pair = self.make_helper(builder, ty, val) return pair.second
[ "def", "pair_second", "(", "self", ",", "builder", ",", "val", ",", "ty", ")", ":", "pair", "=", "self", ".", "make_helper", "(", "builder", ",", "ty", ",", "val", ")", "return", "pair", ".", "second" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/base.py#L685-L690
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/SU2/eval/gradients.py
python
findiff
( config, state=None )
return grads
vals = SU2.eval.findiff(config,state=None) Evaluates the aerodynamics gradients using finite differencing with: SU2.eval.func() SU2.run.deform() SU2.run.direct() Assumptions: Config is already setup for deformation. Mesh may or may not be deformed. Updates config and state by reference. Gradient Redundancy if state.GRADIENTS has the key func_name. Direct Redundancy if state.FUNCTIONS has key func_name. Executes in: ./FINDIFF Inputs: config - an SU2 config state - optional, an SU2 state Outputs: A Bunch() with keys of objective function names and values of list of floats of gradient values
vals = SU2.eval.findiff(config,state=None)
[ "vals", "=", "SU2", ".", "eval", ".", "findiff", "(", "config", "state", "=", "None", ")" ]
def findiff( config, state=None ): """ vals = SU2.eval.findiff(config,state=None) Evaluates the aerodynamics gradients using finite differencing with: SU2.eval.func() SU2.run.deform() SU2.run.direct() Assumptions: Config is already setup for deformation. Mesh may or may not be deformed. Updates config and state by reference. Gradient Redundancy if state.GRADIENTS has the key func_name. Direct Redundancy if state.FUNCTIONS has key func_name. Executes in: ./FINDIFF Inputs: config - an SU2 config state - optional, an SU2 state Outputs: A Bunch() with keys of objective function names and values of list of floats of gradient values """ # ---------------------------------------------------- # Initialize # ---------------------------------------------------- # initialize state = su2io.State(state) special_cases = su2io.get_specialCases(config) Definition_DV = config['DEFINITION_DV'] # console output if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: log_findiff = 'log_FinDiff.out' else: log_findiff = None # evaluate step length or set default value if 'FIN_DIFF_STEP' in config: step = float(config.FIN_DIFF_STEP) else: step = 0.001 opt_names = [] for i in range(config['NZONES']): for key in sorted(su2io.historyOutFields): if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': if (config['NZONES'] == 1): opt_names.append(key) else: opt_names.append(key + '[' + str(i) + ']') # ---------------------------------------------------- # Redundancy Check # ---------------------------------------------------- # master redundancy check findiff_todo = all([key in state.GRADIENTS for key in opt_names]) if findiff_todo: grads = state['GRADIENTS'] return copy.deepcopy(grads) # ---------------------------------------------------- # Zero Step # ---------------------------------------------------- # run func_base = function( 'ALL', config, state ) # ---------------------------------------------------- # Plot Setup # ---------------------------------------------------- grad_filename = config['GRAD_OBJFUNC_FILENAME'] grad_filename = os.path.splitext( grad_filename )[0] output_format = config['TABULAR_FORMAT'] plot_extension = su2io.get_extension(output_format) grad_filename = grad_filename + '_findiff' + plot_extension # ---------------------------------------------------- # Finite Difference Steps # ---------------------------------------------------- # local config konfig = copy.deepcopy(config) # check deformation setup n_dv = sum(Definition_DV['SIZE']) deform_set = konfig['DV_KIND'] == Definition_DV['KIND'] if not deform_set: dvs_base = [0.0] * n_dv konfig.unpack_dvs(dvs_base,dvs_base) else: dvs_base = konfig['DV_VALUE_NEW'] # initialize gradients func_keys = ['VARIABLE'] + opt_names + ['FINDIFF_STEP'] grads = su2util.ordered_bunch.fromkeys(func_keys) for key in grads.keys(): grads[key] = [] # step vector if isinstance(step,list): assert n_dv == len(step) , 'unexpected step vector length' else: step = [step] * n_dv # files to pull files = state['FILES'] pull = []; link = [] pull.extend(config.get('CONFIG_LIST',[])) # files: mesh name = files['MESH'] name = su2io.expand_part(name,konfig) link.extend(name) # files: direct solution if 'DIRECT' in files: name = files['DIRECT'] name = su2io.expand_time(name,config) link.extend(name) # files: restart solution for dual-time stepping first and second order if 'RESTART_FILE_1' in files: name = files['RESTART_FILE_1'] pull.append(name) if 'RESTART_FILE_2' in files: name = files['RESTART_FILE_2'] pull.append(name) # files: target equivarea distribution if 'EQUIV_AREA' in special_cases and 'TARGET_EA' in files: pull.append(files['TARGET_EA']) # files: target pressure distribution if 'INV_DESIGN_CP' in special_cases and 'TARGET_CP' in files: pull.append(files['TARGET_CP']) # files: target heat flux distribution if 'INV_DESIGN_HEATFLUX' in special_cases and 'TARGET_HEATFLUX' in files: pull.append(files['TARGET_HEATFLUX']) # output redirection with redirect_folder('FINDIFF',pull,link) as push: with redirect_output(log_findiff): # iterate each dv for i_dv in range(n_dv): this_step = step[i_dv] temp_config_name = 'config_FINDIFF_%i.cfg' % i_dv this_dvs = copy.deepcopy(dvs_base) this_konfig = copy.deepcopy(konfig) this_dvs[i_dv] = this_dvs[i_dv] + this_step this_state = su2io.State() this_state.FILES = copy.deepcopy( state.FILES ) this_konfig.unpack_dvs(this_dvs,dvs_base) this_konfig.dump(temp_config_name) # Direct Solution, findiff step func_step = function( 'ALL', this_konfig, this_state ) # remove deform step files meshfiles = this_state.FILES.MESH meshfiles = su2io.expand_part(meshfiles,this_konfig) for name in meshfiles: os.remove(name) for key in grads.keys(): if key == 'VARIABLE' or key == 'FINDIFF_STEP': pass elif not key in func_step: del grads[key] # calc finite difference and store for key in grads.keys(): if key == 'VARIABLE': grads[key].append(i_dv) elif key == 'FINDIFF_STEP': grads[key].append(this_step) else: this_grad = ( func_step[key] - func_base[key] ) / this_step grads[key].append(this_grad) #: for each grad name su2util.write_plot(grad_filename,output_format,grads) os.remove(temp_config_name) #: for each dv #: with output redirection # remove plot items del grads['VARIABLE'] del grads['FINDIFF_STEP'] state.GRADIENTS.update(grads) # return results grads = copy.deepcopy(grads) return grads
[ "def", "findiff", "(", "config", ",", "state", "=", "None", ")", ":", "# ----------------------------------------------------", "# Initialize ", "# ----------------------------------------------------", "# initialize", "state", "=", "su2io", ".", "State", "(", "state", ")", "special_cases", "=", "su2io", ".", "get_specialCases", "(", "config", ")", "Definition_DV", "=", "config", "[", "'DEFINITION_DV'", "]", "# console output", "if", "config", ".", "get", "(", "'CONSOLE'", ",", "'VERBOSE'", ")", "in", "[", "'QUIET'", ",", "'CONCISE'", "]", ":", "log_findiff", "=", "'log_FinDiff.out'", "else", ":", "log_findiff", "=", "None", "# evaluate step length or set default value", "if", "'FIN_DIFF_STEP'", "in", "config", ":", "step", "=", "float", "(", "config", ".", "FIN_DIFF_STEP", ")", "else", ":", "step", "=", "0.001", "opt_names", "=", "[", "]", "for", "i", "in", "range", "(", "config", "[", "'NZONES'", "]", ")", ":", "for", "key", "in", "sorted", "(", "su2io", ".", "historyOutFields", ")", ":", "if", "su2io", ".", "historyOutFields", "[", "key", "]", "[", "'TYPE'", "]", "==", "'COEFFICIENT'", ":", "if", "(", "config", "[", "'NZONES'", "]", "==", "1", ")", ":", "opt_names", ".", "append", "(", "key", ")", "else", ":", "opt_names", ".", "append", "(", "key", "+", "'['", "+", "str", "(", "i", ")", "+", "']'", ")", "# ----------------------------------------------------", "# Redundancy Check", "# ---------------------------------------------------- ", "# master redundancy check", "findiff_todo", "=", "all", "(", "[", "key", "in", "state", ".", "GRADIENTS", "for", "key", "in", "opt_names", "]", ")", "if", "findiff_todo", ":", "grads", "=", "state", "[", "'GRADIENTS'", "]", "return", "copy", ".", "deepcopy", "(", "grads", ")", "# ----------------------------------------------------", "# Zero Step ", "# ---------------------------------------------------- ", "# run", "func_base", "=", "function", "(", "'ALL'", ",", "config", ",", "state", ")", "# ----------------------------------------------------", "# Plot Setup", "# ---------------------------------------------------- ", "grad_filename", "=", "config", "[", "'GRAD_OBJFUNC_FILENAME'", "]", "grad_filename", "=", "os", ".", "path", ".", "splitext", "(", "grad_filename", ")", "[", "0", "]", "output_format", "=", "config", "[", "'TABULAR_FORMAT'", "]", "plot_extension", "=", "su2io", ".", "get_extension", "(", "output_format", ")", "grad_filename", "=", "grad_filename", "+", "'_findiff'", "+", "plot_extension", "# ----------------------------------------------------", "# Finite Difference Steps", "# ---------------------------------------------------- ", "# local config", "konfig", "=", "copy", ".", "deepcopy", "(", "config", ")", "# check deformation setup", "n_dv", "=", "sum", "(", "Definition_DV", "[", "'SIZE'", "]", ")", "deform_set", "=", "konfig", "[", "'DV_KIND'", "]", "==", "Definition_DV", "[", "'KIND'", "]", "if", "not", "deform_set", ":", "dvs_base", "=", "[", "0.0", "]", "*", "n_dv", "konfig", ".", "unpack_dvs", "(", "dvs_base", ",", "dvs_base", ")", "else", ":", "dvs_base", "=", "konfig", "[", "'DV_VALUE_NEW'", "]", "# initialize gradients", "func_keys", "=", "[", "'VARIABLE'", "]", "+", "opt_names", "+", "[", "'FINDIFF_STEP'", "]", "grads", "=", "su2util", ".", "ordered_bunch", ".", "fromkeys", "(", "func_keys", ")", "for", "key", "in", "grads", ".", "keys", "(", ")", ":", "grads", "[", "key", "]", "=", "[", "]", "# step vector", "if", "isinstance", "(", "step", ",", "list", ")", ":", "assert", "n_dv", "==", "len", "(", "step", ")", ",", "'unexpected step vector length'", "else", ":", "step", "=", "[", "step", "]", "*", "n_dv", "# files to pull", "files", "=", "state", "[", "'FILES'", "]", "pull", "=", "[", "]", "link", "=", "[", "]", "pull", ".", "extend", "(", "config", ".", "get", "(", "'CONFIG_LIST'", ",", "[", "]", ")", ")", "# files: mesh", "name", "=", "files", "[", "'MESH'", "]", "name", "=", "su2io", ".", "expand_part", "(", "name", ",", "konfig", ")", "link", ".", "extend", "(", "name", ")", "# files: direct solution", "if", "'DIRECT'", "in", "files", ":", "name", "=", "files", "[", "'DIRECT'", "]", "name", "=", "su2io", ".", "expand_time", "(", "name", ",", "config", ")", "link", ".", "extend", "(", "name", ")", "# files: restart solution for dual-time stepping first and second order", "if", "'RESTART_FILE_1'", "in", "files", ":", "name", "=", "files", "[", "'RESTART_FILE_1'", "]", "pull", ".", "append", "(", "name", ")", "if", "'RESTART_FILE_2'", "in", "files", ":", "name", "=", "files", "[", "'RESTART_FILE_2'", "]", "pull", ".", "append", "(", "name", ")", "# files: target equivarea distribution", "if", "'EQUIV_AREA'", "in", "special_cases", "and", "'TARGET_EA'", "in", "files", ":", "pull", ".", "append", "(", "files", "[", "'TARGET_EA'", "]", ")", "# files: target pressure distribution", "if", "'INV_DESIGN_CP'", "in", "special_cases", "and", "'TARGET_CP'", "in", "files", ":", "pull", ".", "append", "(", "files", "[", "'TARGET_CP'", "]", ")", "# files: target heat flux distribution", "if", "'INV_DESIGN_HEATFLUX'", "in", "special_cases", "and", "'TARGET_HEATFLUX'", "in", "files", ":", "pull", ".", "append", "(", "files", "[", "'TARGET_HEATFLUX'", "]", ")", "# output redirection", "with", "redirect_folder", "(", "'FINDIFF'", ",", "pull", ",", "link", ")", "as", "push", ":", "with", "redirect_output", "(", "log_findiff", ")", ":", "# iterate each dv ", "for", "i_dv", "in", "range", "(", "n_dv", ")", ":", "this_step", "=", "step", "[", "i_dv", "]", "temp_config_name", "=", "'config_FINDIFF_%i.cfg'", "%", "i_dv", "this_dvs", "=", "copy", ".", "deepcopy", "(", "dvs_base", ")", "this_konfig", "=", "copy", ".", "deepcopy", "(", "konfig", ")", "this_dvs", "[", "i_dv", "]", "=", "this_dvs", "[", "i_dv", "]", "+", "this_step", "this_state", "=", "su2io", ".", "State", "(", ")", "this_state", ".", "FILES", "=", "copy", ".", "deepcopy", "(", "state", ".", "FILES", ")", "this_konfig", ".", "unpack_dvs", "(", "this_dvs", ",", "dvs_base", ")", "this_konfig", ".", "dump", "(", "temp_config_name", ")", "# Direct Solution, findiff step", "func_step", "=", "function", "(", "'ALL'", ",", "this_konfig", ",", "this_state", ")", "# remove deform step files", "meshfiles", "=", "this_state", ".", "FILES", ".", "MESH", "meshfiles", "=", "su2io", ".", "expand_part", "(", "meshfiles", ",", "this_konfig", ")", "for", "name", "in", "meshfiles", ":", "os", ".", "remove", "(", "name", ")", "for", "key", "in", "grads", ".", "keys", "(", ")", ":", "if", "key", "==", "'VARIABLE'", "or", "key", "==", "'FINDIFF_STEP'", ":", "pass", "elif", "not", "key", "in", "func_step", ":", "del", "grads", "[", "key", "]", "# calc finite difference and store", "for", "key", "in", "grads", ".", "keys", "(", ")", ":", "if", "key", "==", "'VARIABLE'", ":", "grads", "[", "key", "]", ".", "append", "(", "i_dv", ")", "elif", "key", "==", "'FINDIFF_STEP'", ":", "grads", "[", "key", "]", ".", "append", "(", "this_step", ")", "else", ":", "this_grad", "=", "(", "func_step", "[", "key", "]", "-", "func_base", "[", "key", "]", ")", "/", "this_step", "grads", "[", "key", "]", ".", "append", "(", "this_grad", ")", "#: for each grad name", "su2util", ".", "write_plot", "(", "grad_filename", ",", "output_format", ",", "grads", ")", "os", ".", "remove", "(", "temp_config_name", ")", "#: for each dv", "#: with output redirection", "# remove plot items", "del", "grads", "[", "'VARIABLE'", "]", "del", "grads", "[", "'FINDIFF_STEP'", "]", "state", ".", "GRADIENTS", ".", "update", "(", "grads", ")", "# return results", "grads", "=", "copy", ".", "deepcopy", "(", "grads", ")", "return", "grads" ]
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/eval/gradients.py#L720-L928
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_FixPaths
(paths)
return [_FixPath(i) for i in paths]
Fix each of the paths of the list.
Fix each of the paths of the list.
[ "Fix", "each", "of", "the", "paths", "of", "the", "list", "." ]
def _FixPaths(paths): """Fix each of the paths of the list.""" return [_FixPath(i) for i in paths]
[ "def", "_FixPaths", "(", "paths", ")", ":", "return", "[", "_FixPath", "(", "i", ")", "for", "i", "in", "paths", "]" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L183-L185
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
_get_in_out_shape
(x_shape, y_shape, n_classes, batch_size=None)
return input_shape, output_shape, batch_size
Returns shape for input and output of the data feeder.
Returns shape for input and output of the data feeder.
[ "Returns", "shape", "for", "input", "and", "output", "of", "the", "data", "feeder", "." ]
def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None): """Returns shape for input and output of the data feeder.""" if batch_size is None: batch_size = x_shape[0] elif batch_size <= 0: raise ValueError('Invalid batch_size %d.' % batch_size) x_shape = list(x_shape[1:]) if len(x_shape) > 1 else [1] input_shape = [batch_size] + x_shape if y_shape is None: return input_shape, None, batch_size y_shape = list(y_shape[1:]) if len(y_shape) > 1 else [] # Skip first dimension if it is 1. if y_shape and y_shape[0] == 1: y_shape = y_shape[1:] if n_classes is not None and n_classes > 1: output_shape = [batch_size] + y_shape + [n_classes] else: output_shape = [batch_size] + y_shape return input_shape, output_shape, batch_size
[ "def", "_get_in_out_shape", "(", "x_shape", ",", "y_shape", ",", "n_classes", ",", "batch_size", "=", "None", ")", ":", "if", "batch_size", "is", "None", ":", "batch_size", "=", "x_shape", "[", "0", "]", "elif", "batch_size", "<=", "0", ":", "raise", "ValueError", "(", "'Invalid batch_size %d.'", "%", "batch_size", ")", "x_shape", "=", "list", "(", "x_shape", "[", "1", ":", "]", ")", "if", "len", "(", "x_shape", ")", ">", "1", "else", "[", "1", "]", "input_shape", "=", "[", "batch_size", "]", "+", "x_shape", "if", "y_shape", "is", "None", ":", "return", "input_shape", ",", "None", ",", "batch_size", "y_shape", "=", "list", "(", "y_shape", "[", "1", ":", "]", ")", "if", "len", "(", "y_shape", ")", ">", "1", "else", "[", "]", "# Skip first dimension if it is 1.", "if", "y_shape", "and", "y_shape", "[", "0", "]", "==", "1", ":", "y_shape", "=", "y_shape", "[", "1", ":", "]", "if", "n_classes", "is", "not", "None", "and", "n_classes", ">", "1", ":", "output_shape", "=", "[", "batch_size", "]", "+", "y_shape", "+", "[", "n_classes", "]", "else", ":", "output_shape", "=", "[", "batch_size", "]", "+", "y_shape", "return", "input_shape", ",", "output_shape", ",", "batch_size" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L41-L59
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/stack.py
python
parse_stack
(string, filename)
return s
Parse stack.xml string contents. :param string: stack.xml contents, ``str`` :param filename: full file path for debugging, ``str`` :returns: return parsed :class:`Stack`
Parse stack.xml string contents.
[ "Parse", "stack", ".", "xml", "string", "contents", "." ]
def parse_stack(string, filename): """ Parse stack.xml string contents. :param string: stack.xml contents, ``str`` :param filename: full file path for debugging, ``str`` :returns: return parsed :class:`Stack` """ # Create some classes to hold some members new_tuples = {} for key, members in LISTED_ATTRIBUTES.items(): new_tuples[key] = collections.namedtuple(key, members) try: d = dom.parseString(string) except Exception as e: raise InvalidStack("[%s] invalid XML: %s"%(filename, e)) s = Stack() p = _get_nodes_by_name(d, 'stack') if len(p) != 1: raise InvalidStack("stack.xml [%s] must have a single 'stack' element"%(filename)) p = p[0] for attr in [ 'name', 'version', 'description', 'license', 'copyright', 'url', 'build_type', 'message_generator' ]: val = _check(attr)(p, filename) if val: setattr(s, attr, val) try: tag = _get_nodes_by_name(p, 'description')[0] s.description_brief = tag.getAttribute('brief') or '' except: # means that 'description' tag is missing pass s.authors = _build_listed_attributes(p, 'author', new_tuples['Author']) s.maintainers = _build_listed_attributes(p, 'maintainer', new_tuples['Maintainer']) s.depends = _build_listed_attributes(p, 'depends', new_tuples['Depend']) s.build_depends = _build_listed_attributes(p, 'build_depends', new_tuples['Depend']) try: tag = _get_nodes_by_name(p, 'review')[0] s.review_status = tag.getAttribute('status') or '' except: pass #stack.xml is missing optional 'review status' tag try: tag = _get_nodes_by_name(p, 'review')[0] s.review_notes = tag.getAttribute('notes') or '' except: pass #stack.xml is missing optional 'review notes' tag try: tag = _get_nodes_by_name(p, 'build_type')[0] s.build_type_file = tag.getAttribute('file') or '' except: pass #stack.xml is missing optional 'build_type file' tag # store unrecognized tags s.unknown_tags = [e.nodeName for e in p.childNodes if e.nodeType == e.ELEMENT_NODE and e.tagName not in VALID] if s.unknown_tags: raise InvalidStack("stack.xml [%s] must be cleaned up from %s"%(filename, str(s.unknown_tags))) return s
[ "def", "parse_stack", "(", "string", ",", "filename", ")", ":", "# Create some classes to hold some members", "new_tuples", "=", "{", "}", "for", "key", ",", "members", "in", "LISTED_ATTRIBUTES", ".", "items", "(", ")", ":", "new_tuples", "[", "key", "]", "=", "collections", ".", "namedtuple", "(", "key", ",", "members", ")", "try", ":", "d", "=", "dom", ".", "parseString", "(", "string", ")", "except", "Exception", "as", "e", ":", "raise", "InvalidStack", "(", "\"[%s] invalid XML: %s\"", "%", "(", "filename", ",", "e", ")", ")", "s", "=", "Stack", "(", ")", "p", "=", "_get_nodes_by_name", "(", "d", ",", "'stack'", ")", "if", "len", "(", "p", ")", "!=", "1", ":", "raise", "InvalidStack", "(", "\"stack.xml [%s] must have a single 'stack' element\"", "%", "(", "filename", ")", ")", "p", "=", "p", "[", "0", "]", "for", "attr", "in", "[", "'name'", ",", "'version'", ",", "'description'", ",", "'license'", ",", "'copyright'", ",", "'url'", ",", "'build_type'", ",", "'message_generator'", "]", ":", "val", "=", "_check", "(", "attr", ")", "(", "p", ",", "filename", ")", "if", "val", ":", "setattr", "(", "s", ",", "attr", ",", "val", ")", "try", ":", "tag", "=", "_get_nodes_by_name", "(", "p", ",", "'description'", ")", "[", "0", "]", "s", ".", "description_brief", "=", "tag", ".", "getAttribute", "(", "'brief'", ")", "or", "''", "except", ":", "# means that 'description' tag is missing", "pass", "s", ".", "authors", "=", "_build_listed_attributes", "(", "p", ",", "'author'", ",", "new_tuples", "[", "'Author'", "]", ")", "s", ".", "maintainers", "=", "_build_listed_attributes", "(", "p", ",", "'maintainer'", ",", "new_tuples", "[", "'Maintainer'", "]", ")", "s", ".", "depends", "=", "_build_listed_attributes", "(", "p", ",", "'depends'", ",", "new_tuples", "[", "'Depend'", "]", ")", "s", ".", "build_depends", "=", "_build_listed_attributes", "(", "p", ",", "'build_depends'", ",", "new_tuples", "[", "'Depend'", "]", ")", "try", ":", "tag", "=", "_get_nodes_by_name", "(", "p", ",", "'review'", ")", "[", "0", "]", "s", ".", "review_status", "=", "tag", ".", "getAttribute", "(", "'status'", ")", "or", "''", "except", ":", "pass", "#stack.xml is missing optional 'review status' tag", "try", ":", "tag", "=", "_get_nodes_by_name", "(", "p", ",", "'review'", ")", "[", "0", "]", "s", ".", "review_notes", "=", "tag", ".", "getAttribute", "(", "'notes'", ")", "or", "''", "except", ":", "pass", "#stack.xml is missing optional 'review notes' tag", "try", ":", "tag", "=", "_get_nodes_by_name", "(", "p", ",", "'build_type'", ")", "[", "0", "]", "s", ".", "build_type_file", "=", "tag", ".", "getAttribute", "(", "'file'", ")", "or", "''", "except", ":", "pass", "#stack.xml is missing optional 'build_type file' tag", "# store unrecognized tags", "s", ".", "unknown_tags", "=", "[", "e", ".", "nodeName", "for", "e", "in", "p", ".", "childNodes", "if", "e", ".", "nodeType", "==", "e", ".", "ELEMENT_NODE", "and", "e", ".", "tagName", "not", "in", "VALID", "]", "if", "s", ".", "unknown_tags", ":", "raise", "InvalidStack", "(", "\"stack.xml [%s] must be cleaned up from %s\"", "%", "(", "filename", ",", "str", "(", "s", ".", "unknown_tags", ")", ")", ")", "return", "s" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/stack.py#L180-L243
include-what-you-use/include-what-you-use
208fbfffa5d69364b9f78e427caa443441279283
iwyu-check-license-header.py
python
format_file_error
(filename, *lines)
return os.linesep.join(lines)
Format an error message from filename and lines
Format an error message from filename and lines
[ "Format", "an", "error", "message", "from", "filename", "and", "lines" ]
def format_file_error(filename, *lines): """ Format an error message from filename and lines """ lines = list(lines) lines[0] = '%s: %s' % (filename, lines[0]) return os.linesep.join(lines)
[ "def", "format_file_error", "(", "filename", ",", "*", "lines", ")", ":", "lines", "=", "list", "(", "lines", ")", "lines", "[", "0", "]", "=", "'%s: %s'", "%", "(", "filename", ",", "lines", "[", "0", "]", ")", "return", "os", ".", "linesep", ".", "join", "(", "lines", ")" ]
https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/iwyu-check-license-header.py#L73-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/style_render.py
python
Tooltips._pseudo_css
(self, uuid: str, name: str, row: int, col: int, text: str)
return [ { "selector": selector_id + f":hover .{name}", "props": [("visibility", "visible")], }, { "selector": selector_id + f" .{name}::after", "props": [("content", f'"{text}"')], }, ]
For every table data-cell that has a valid tooltip (not None, NaN or empty string) must create two pseudo CSS entries for the specific <td> element id which are added to overall table styles: an on hover visibility change and a content change dependent upon the user's chosen display string. For example: [{"selector": "T__row1_col1:hover .pd-t", "props": [("visibility", "visible")]}, {"selector": "T__row1_col1 .pd-t::after", "props": [("content", "Some Valid Text String")]}] Parameters ---------- uuid: str The uuid of the Styler instance name: str The css-name of the class used for styling tooltips row : int The row index of the specified tooltip string data col : int The col index of the specified tooltip string data text : str The textual content of the tooltip to be displayed in HTML. Returns ------- pseudo_css : List
For every table data-cell that has a valid tooltip (not None, NaN or empty string) must create two pseudo CSS entries for the specific <td> element id which are added to overall table styles: an on hover visibility change and a content change dependent upon the user's chosen display string.
[ "For", "every", "table", "data", "-", "cell", "that", "has", "a", "valid", "tooltip", "(", "not", "None", "NaN", "or", "empty", "string", ")", "must", "create", "two", "pseudo", "CSS", "entries", "for", "the", "specific", "<td", ">", "element", "id", "which", "are", "added", "to", "overall", "table", "styles", ":", "an", "on", "hover", "visibility", "change", "and", "a", "content", "change", "dependent", "upon", "the", "user", "s", "chosen", "display", "string", "." ]
def _pseudo_css(self, uuid: str, name: str, row: int, col: int, text: str): """ For every table data-cell that has a valid tooltip (not None, NaN or empty string) must create two pseudo CSS entries for the specific <td> element id which are added to overall table styles: an on hover visibility change and a content change dependent upon the user's chosen display string. For example: [{"selector": "T__row1_col1:hover .pd-t", "props": [("visibility", "visible")]}, {"selector": "T__row1_col1 .pd-t::after", "props": [("content", "Some Valid Text String")]}] Parameters ---------- uuid: str The uuid of the Styler instance name: str The css-name of the class used for styling tooltips row : int The row index of the specified tooltip string data col : int The col index of the specified tooltip string data text : str The textual content of the tooltip to be displayed in HTML. Returns ------- pseudo_css : List """ selector_id = "#T_" + uuid + "row" + str(row) + "_col" + str(col) return [ { "selector": selector_id + f":hover .{name}", "props": [("visibility", "visible")], }, { "selector": selector_id + f" .{name}::after", "props": [("content", f'"{text}"')], }, ]
[ "def", "_pseudo_css", "(", "self", ",", "uuid", ":", "str", ",", "name", ":", "str", ",", "row", ":", "int", ",", "col", ":", "int", ",", "text", ":", "str", ")", ":", "selector_id", "=", "\"#T_\"", "+", "uuid", "+", "\"row\"", "+", "str", "(", "row", ")", "+", "\"_col\"", "+", "str", "(", "col", ")", "return", "[", "{", "\"selector\"", ":", "selector_id", "+", "f\":hover .{name}\"", ",", "\"props\"", ":", "[", "(", "\"visibility\"", ",", "\"visible\"", ")", "]", ",", "}", ",", "{", "\"selector\"", ":", "selector_id", "+", "f\" .{name}::after\"", ",", "\"props\"", ":", "[", "(", "\"content\"", ",", "f'\"{text}\"'", ")", "]", ",", "}", ",", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/style_render.py#L1138-L1179
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Script/Interactive.py
python
SConsInteractiveCmd.do_shell
(self, argv)
\ shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms.
\ shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms.
[ "\\", "shell", "[", "COMMANDLINE", "]", "Execute", "COMMANDLINE", "in", "a", "subshell", ".", "sh", "and", "!", "are", "synonyms", "." ]
def do_shell(self, argv): """\ shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms. """ import subprocess argv = argv[1:] if not argv: argv = os.environ[self.shell_variable] try: # Per "[Python-Dev] subprocess insufficiently platform-independent?" # http://mail.python.org/pipermail/python-dev/2008-August/081979.html "+ # Doing the right thing with an argument list currently # requires different shell= values on Windows and Linux. p = subprocess.Popen(argv, shell=(sys.platform=='win32')) except EnvironmentError as e: sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror)) else: p.wait()
[ "def", "do_shell", "(", "self", ",", "argv", ")", ":", "import", "subprocess", "argv", "=", "argv", "[", "1", ":", "]", "if", "not", "argv", ":", "argv", "=", "os", ".", "environ", "[", "self", ".", "shell_variable", "]", "try", ":", "# Per \"[Python-Dev] subprocess insufficiently platform-independent?\"", "# http://mail.python.org/pipermail/python-dev/2008-August/081979.html \"+", "# Doing the right thing with an argument list currently", "# requires different shell= values on Windows and Linux.", "p", "=", "subprocess", ".", "Popen", "(", "argv", ",", "shell", "=", "(", "sys", ".", "platform", "==", "'win32'", ")", ")", "except", "EnvironmentError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'scons: %s: %s\\n'", "%", "(", "argv", "[", "0", "]", ",", "e", ".", "strerror", ")", ")", "else", ":", "p", ".", "wait", "(", ")" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Script/Interactive.py#L333-L351
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_basinhopping.py
python
Metropolis.accept_reject
(self, energy_new, energy_old)
return w >= rand
If new energy is lower than old, it will always be accepted. If new is higher than old, there is a chance it will be accepted, less likely for larger differences.
If new energy is lower than old, it will always be accepted. If new is higher than old, there is a chance it will be accepted, less likely for larger differences.
[ "If", "new", "energy", "is", "lower", "than", "old", "it", "will", "always", "be", "accepted", ".", "If", "new", "is", "higher", "than", "old", "there", "is", "a", "chance", "it", "will", "be", "accepted", "less", "likely", "for", "larger", "differences", "." ]
def accept_reject(self, energy_new, energy_old): """ If new energy is lower than old, it will always be accepted. If new is higher than old, there is a chance it will be accepted, less likely for larger differences. """ w = math.exp(min(0, -float(energy_new - energy_old) * self.beta)) rand = self.random_state.rand() return w >= rand
[ "def", "accept_reject", "(", "self", ",", "energy_new", ",", "energy_old", ")", ":", "w", "=", "math", ".", "exp", "(", "min", "(", "0", ",", "-", "float", "(", "energy_new", "-", "energy_old", ")", "*", "self", ".", "beta", ")", ")", "rand", "=", "self", ".", "random_state", ".", "rand", "(", ")", "return", "w", ">=", "rand" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_basinhopping.py#L307-L315
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
python/cdec/configobj.py
python
ConfigObj.__init__
(self, infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)
Parse a config file or create a config file object. ``ConfigObj(infile=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)``
Parse a config file or create a config file object. ``ConfigObj(infile=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)``
[ "Parse", "a", "config", "file", "or", "create", "a", "config", "file", "object", ".", "ConfigObj", "(", "infile", "=", "None", "configspec", "=", "None", "encoding", "=", "None", "interpolation", "=", "True", "raise_errors", "=", "False", "list_values", "=", "True", "create_empty", "=", "False", "file_error", "=", "False", "stringify", "=", "True", "indent_type", "=", "None", "default_encoding", "=", "None", "unrepr", "=", "False", "write_empty_values", "=", "False", "_inspec", "=", "False", ")" ]
def __init__(self, infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False): """ Parse a config file or create a config file object. ``ConfigObj(infile=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)`` """ self._inspec = _inspec # init the superclass Section.__init__(self, self, 0, self) infile = infile or [] _options = {'configspec': configspec, 'encoding': encoding, 'interpolation': interpolation, 'raise_errors': raise_errors, 'list_values': list_values, 'create_empty': create_empty, 'file_error': file_error, 'stringify': stringify, 'indent_type': indent_type, 'default_encoding': default_encoding, 'unrepr': unrepr, 'write_empty_values': write_empty_values} if options is None: options = _options else: import warnings warnings.warn('Passing in an options dictionary to ConfigObj() is ' 'deprecated. Use **options instead.', DeprecationWarning, stacklevel=2) # TODO: check the values too. for entry in options: if entry not in OPTION_DEFAULTS: raise TypeError('Unrecognised option "%s".' % entry) for entry, value in OPTION_DEFAULTS.items(): if entry not in options: options[entry] = value keyword_value = _options[entry] if value != keyword_value: options[entry] = keyword_value # XXXX this ignores an explicit list_values = True in combination # with _inspec. The user should *never* do that anyway, but still... if _inspec: options['list_values'] = False self._initialise(options) configspec = options['configspec'] self._original_configspec = configspec self._load(infile, configspec)
[ "def", "__init__", "(", "self", ",", "infile", "=", "None", ",", "options", "=", "None", ",", "configspec", "=", "None", ",", "encoding", "=", "None", ",", "interpolation", "=", "True", ",", "raise_errors", "=", "False", ",", "list_values", "=", "True", ",", "create_empty", "=", "False", ",", "file_error", "=", "False", ",", "stringify", "=", "True", ",", "indent_type", "=", "None", ",", "default_encoding", "=", "None", ",", "unrepr", "=", "False", ",", "write_empty_values", "=", "False", ",", "_inspec", "=", "False", ")", ":", "self", ".", "_inspec", "=", "_inspec", "# init the superclass", "Section", ".", "__init__", "(", "self", ",", "self", ",", "0", ",", "self", ")", "infile", "=", "infile", "or", "[", "]", "_options", "=", "{", "'configspec'", ":", "configspec", ",", "'encoding'", ":", "encoding", ",", "'interpolation'", ":", "interpolation", ",", "'raise_errors'", ":", "raise_errors", ",", "'list_values'", ":", "list_values", ",", "'create_empty'", ":", "create_empty", ",", "'file_error'", ":", "file_error", ",", "'stringify'", ":", "stringify", ",", "'indent_type'", ":", "indent_type", ",", "'default_encoding'", ":", "default_encoding", ",", "'unrepr'", ":", "unrepr", ",", "'write_empty_values'", ":", "write_empty_values", "}", "if", "options", "is", "None", ":", "options", "=", "_options", "else", ":", "import", "warnings", "warnings", ".", "warn", "(", "'Passing in an options dictionary to ConfigObj() is '", "'deprecated. Use **options instead.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "# TODO: check the values too.", "for", "entry", "in", "options", ":", "if", "entry", "not", "in", "OPTION_DEFAULTS", ":", "raise", "TypeError", "(", "'Unrecognised option \"%s\".'", "%", "entry", ")", "for", "entry", ",", "value", "in", "OPTION_DEFAULTS", ".", "items", "(", ")", ":", "if", "entry", "not", "in", "options", ":", "options", "[", "entry", "]", "=", "value", "keyword_value", "=", "_options", "[", "entry", "]", "if", "value", "!=", "keyword_value", ":", "options", "[", "entry", "]", "=", "keyword_value", "# XXXX this ignores an explicit list_values = True in combination", "# with _inspec. The user should *never* do that anyway, but still...", "if", "_inspec", ":", "options", "[", "'list_values'", "]", "=", "False", "self", ".", "_initialise", "(", "options", ")", "configspec", "=", "options", "[", "'configspec'", "]", "self", ".", "_original_configspec", "=", "configspec", "self", ".", "_load", "(", "infile", ",", "configspec", ")" ]
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L1187-L1242
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/models.py
python
logistic_regression_zero_init
(x, y)
return logistic_regression(x, y, init_mean=0.0, init_stddev=0.0)
Logistic regression subgraph with zero-value initial weights and bias. Args: x: tensor or placeholder for input features. y: tensor or placeholder for labels. Returns: Predictions and loss tensors.
Logistic regression subgraph with zero-value initial weights and bias.
[ "Logistic", "regression", "subgraph", "with", "zero", "-", "value", "initial", "weights", "and", "bias", "." ]
def logistic_regression_zero_init(x, y): """Logistic regression subgraph with zero-value initial weights and bias. Args: x: tensor or placeholder for input features. y: tensor or placeholder for labels. Returns: Predictions and loss tensors. """ return logistic_regression(x, y, init_mean=0.0, init_stddev=0.0)
[ "def", "logistic_regression_zero_init", "(", "x", ",", "y", ")", ":", "return", "logistic_regression", "(", "x", ",", "y", ",", "init_mean", "=", "0.0", ",", "init_stddev", "=", "0.0", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/models.py#L54-L64
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/util/queue_channel.py
python
QueueListener.dequeue
(self, block)
return self.queue.get(block)
Dequeue a record and return it, optionally blocking. The base implementation uses :meth:`~queue.Queue.get`. You may want to override this method if you want to use timeouts or work with custom queue implementations. :param block: Whether to block if the queue is empty. If `False` and the queue is empty, an :class:`~queue.Empty` exception will be thrown.
Dequeue a record and return it, optionally blocking.
[ "Dequeue", "a", "record", "and", "return", "it", "optionally", "blocking", "." ]
def dequeue(self, block): """ Dequeue a record and return it, optionally blocking. The base implementation uses :meth:`~queue.Queue.get`. You may want to override this method if you want to use timeouts or work with custom queue implementations. :param block: Whether to block if the queue is empty. If `False` and the queue is empty, an :class:`~queue.Empty` exception will be thrown. """ return self.queue.get(block)
[ "def", "dequeue", "(", "self", ",", "block", ")", ":", "return", "self", ".", "queue", ".", "get", "(", "block", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/util/queue_channel.py#L145-L157
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/gluon/lipnet/utils/multi.py
python
test_worker
(from_idx, to_idx, params)
return (succ, fail)
the worker to test multi-process
the worker to test multi-process
[ "the", "worker", "to", "test", "multi", "-", "process" ]
def test_worker(from_idx, to_idx, params): """ the worker to test multi-process """ params = params succ = set() fail = set() for idx in range(from_idx, to_idx): try: succ.add(idx) except ValueError: fail.add(idx) return (succ, fail)
[ "def", "test_worker", "(", "from_idx", ",", "to_idx", ",", "params", ")", ":", "params", "=", "params", "succ", "=", "set", "(", ")", "fail", "=", "set", "(", ")", "for", "idx", "in", "range", "(", "from_idx", ",", "to_idx", ")", ":", "try", ":", "succ", ".", "add", "(", "idx", ")", "except", "ValueError", ":", "fail", ".", "add", "(", "idx", ")", "return", "(", "succ", ",", "fail", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/lipnet/utils/multi.py#L87-L99
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/runpy.py
python
_run_module_code
(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None)
return mod_globals.copy()
Helper to run code in new namespace with sys modified
Helper to run code in new namespace with sys modified
[ "Helper", "to", "run", "code", "in", "new", "namespace", "with", "sys", "modified" ]
def _run_module_code(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in new namespace with sys modified""" with _TempModule(mod_name) as temp_module, _ModifiedArgv0(mod_fname): mod_globals = temp_module.module.__dict__ _run_code(code, mod_globals, init_globals, mod_name, mod_fname, mod_loader, pkg_name) # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy()
[ "def", "_run_module_code", "(", "code", ",", "init_globals", "=", "None", ",", "mod_name", "=", "None", ",", "mod_fname", "=", "None", ",", "mod_loader", "=", "None", ",", "pkg_name", "=", "None", ")", ":", "with", "_TempModule", "(", "mod_name", ")", "as", "temp_module", ",", "_ModifiedArgv0", "(", "mod_fname", ")", ":", "mod_globals", "=", "temp_module", ".", "module", ".", "__dict__", "_run_code", "(", "code", ",", "mod_globals", ",", "init_globals", ",", "mod_name", ",", "mod_fname", ",", "mod_loader", ",", "pkg_name", ")", "# Copy the globals of the temporary module, as they", "# may be cleared when the temporary module goes away", "return", "mod_globals", ".", "copy", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/runpy.py#L75-L85
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
pylib/utils.py
python
top_path
(topdir, *path)
return os.path.join(topdir, *path)
Return a path relative to the directory in which the x tool or wrapper was invoked. This function is equivalent to base_path(), except when the x tool is invoked in a client repository through a wrapper. In that case, the specified path is not appended to the directory containing the core x.py file, but the directory containing the wrapper x.py file invoked by the user.
Return a path relative to the directory in which the x tool or wrapper was invoked.
[ "Return", "a", "path", "relative", "to", "the", "directory", "in", "which", "the", "x", "tool", "or", "wrapper", "was", "invoked", "." ]
def top_path(topdir, *path): """Return a path relative to the directory in which the x tool or wrapper was invoked. This function is equivalent to base_path(), except when the x tool is invoked in a client repository through a wrapper. In that case, the specified path is not appended to the directory containing the core x.py file, but the directory containing the wrapper x.py file invoked by the user. """ return os.path.join(topdir, *path)
[ "def", "top_path", "(", "topdir", ",", "*", "path", ")", ":", "return", "os", ".", "path", ".", "join", "(", "topdir", ",", "*", "path", ")" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/pylib/utils.py#L69-L78
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pswindows.py
python
net_if_addrs
()
return ret
Return the addresses associated to each NIC.
Return the addresses associated to each NIC.
[ "Return", "the", "addresses", "associated", "to", "each", "NIC", "." ]
def net_if_addrs(): """Return the addresses associated to each NIC.""" ret = [] for items in cext.net_if_addrs(): items = list(items) items[0] = py2_strencode(items[0]) ret.append(items) return ret
[ "def", "net_if_addrs", "(", ")", ":", "ret", "=", "[", "]", "for", "items", "in", "cext", ".", "net_if_addrs", "(", ")", ":", "items", "=", "list", "(", "items", ")", "items", "[", "0", "]", "=", "py2_strencode", "(", "items", "[", "0", "]", ")", "ret", ".", "append", "(", "items", ")", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pswindows.py#L392-L399
JumpingYang001/webrtc
c03d6e965e1f54aeadd670e491eabe5fdb8db968
tools_webrtc/autoroller/roll_deps.py
python
BuildDepsentryDict
(deps_dict)
return result
Builds a dict of paths to DepsEntry objects from a raw parsed deps dict.
Builds a dict of paths to DepsEntry objects from a raw parsed deps dict.
[ "Builds", "a", "dict", "of", "paths", "to", "DepsEntry", "objects", "from", "a", "raw", "parsed", "deps", "dict", "." ]
def BuildDepsentryDict(deps_dict): """Builds a dict of paths to DepsEntry objects from a raw parsed deps dict.""" result = {} def AddDepsEntries(deps_subdict): for path, dep in deps_subdict.iteritems(): if path in result: continue if not isinstance(dep, dict): dep = {'url': dep} if dep.get('dep_type') == 'cipd': result[path] = CipdDepsEntry(path, dep['packages']) else: if '@' not in dep['url']: continue url, revision = dep['url'].split('@') result[path] = DepsEntry(path, url, revision) AddDepsEntries(deps_dict['deps']) for deps_os in ['win', 'mac', 'unix', 'android', 'ios', 'unix']: AddDepsEntries(deps_dict.get('deps_os', {}).get(deps_os, {})) return result
[ "def", "BuildDepsentryDict", "(", "deps_dict", ")", ":", "result", "=", "{", "}", "def", "AddDepsEntries", "(", "deps_subdict", ")", ":", "for", "path", ",", "dep", "in", "deps_subdict", ".", "iteritems", "(", ")", ":", "if", "path", "in", "result", ":", "continue", "if", "not", "isinstance", "(", "dep", ",", "dict", ")", ":", "dep", "=", "{", "'url'", ":", "dep", "}", "if", "dep", ".", "get", "(", "'dep_type'", ")", "==", "'cipd'", ":", "result", "[", "path", "]", "=", "CipdDepsEntry", "(", "path", ",", "dep", "[", "'packages'", "]", ")", "else", ":", "if", "'@'", "not", "in", "dep", "[", "'url'", "]", ":", "continue", "url", ",", "revision", "=", "dep", "[", "'url'", "]", ".", "split", "(", "'@'", ")", "result", "[", "path", "]", "=", "DepsEntry", "(", "path", ",", "url", ",", "revision", ")", "AddDepsEntries", "(", "deps_dict", "[", "'deps'", "]", ")", "for", "deps_os", "in", "[", "'win'", ",", "'mac'", ",", "'unix'", ",", "'android'", ",", "'ios'", ",", "'unix'", "]", ":", "AddDepsEntries", "(", "deps_dict", ".", "get", "(", "'deps_os'", ",", "{", "}", ")", ".", "get", "(", "deps_os", ",", "{", "}", ")", ")", "return", "result" ]
https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/tools_webrtc/autoroller/roll_deps.py#L247-L268
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/generator.py
python
_CppSourceFileWriter.gen_op_msg_request_deserializer_methods
(self, struct)
Generate the C++ deserializer method definitions from OpMsgRequest.
Generate the C++ deserializer method definitions from OpMsgRequest.
[ "Generate", "the", "C", "++", "deserializer", "method", "definitions", "from", "OpMsgRequest", "." ]
def gen_op_msg_request_deserializer_methods(self, struct): # type: (ast.Struct) -> None """Generate the C++ deserializer method definitions from OpMsgRequest.""" # pylint: disable=invalid-name # Commands that have concatentate_with_db namespaces require db name as a parameter if not isinstance(struct, ast.Command): return struct_type_info = struct_types.get_struct_info(struct) self.get_bson_deserializer_static_common( struct, struct_type_info.get_op_msg_request_deserializer_static_method(), struct_type_info.get_op_msg_request_deserializer_method()) func_def = struct_type_info.get_op_msg_request_deserializer_method().get_definition() with self._block('%s {' % (func_def), '}'): # Deserialize all the fields field_usage_check = self._gen_fields_deserializer_common(struct, "request.body") # Iterate through the document sequences if we have any has_doc_sequence = len( [field for field in struct.fields if field.supports_doc_sequence]) if has_doc_sequence: with self._block('for (auto&& sequence : request.sequences) {', '}'): field_usage_check.add_store("sequence.name") self._writer.write_empty_line() first_field = True for field in struct.fields: # Only parse document sequence fields here if not field.supports_doc_sequence: continue field_predicate = 'sequence.name == %s' % (_get_field_constant_name(field)) with self._predicate(field_predicate, not first_field): field_usage_check.add(field, "sequence.name") if _is_required_serializer_field(field): self._writer.write_line('%s = true;' % (_get_has_field_member_name(field))) self.gen_doc_sequence_deserializer(field) if first_field: first_field = False # End of for fields # Generate strict check for extranous fields if struct.strict: with self._block('else {', '}'): self._writer.write_line('ctxt.throwUnknownField(sequence.name);') self._writer.write_empty_line() # Check for required fields field_usage_check.add_final_checks() self._writer.write_empty_line() # Generate namespace check now that "$db" has been read or defaulted struct_type_info.gen_namespace_check(self._writer, "_dbName", "commandElement")
[ "def", "gen_op_msg_request_deserializer_methods", "(", "self", ",", "struct", ")", ":", "# type: (ast.Struct) -> None", "# pylint: disable=invalid-name", "# Commands that have concatentate_with_db namespaces require db name as a parameter", "if", "not", "isinstance", "(", "struct", ",", "ast", ".", "Command", ")", ":", "return", "struct_type_info", "=", "struct_types", ".", "get_struct_info", "(", "struct", ")", "self", ".", "get_bson_deserializer_static_common", "(", "struct", ",", "struct_type_info", ".", "get_op_msg_request_deserializer_static_method", "(", ")", ",", "struct_type_info", ".", "get_op_msg_request_deserializer_method", "(", ")", ")", "func_def", "=", "struct_type_info", ".", "get_op_msg_request_deserializer_method", "(", ")", ".", "get_definition", "(", ")", "with", "self", ".", "_block", "(", "'%s {'", "%", "(", "func_def", ")", ",", "'}'", ")", ":", "# Deserialize all the fields", "field_usage_check", "=", "self", ".", "_gen_fields_deserializer_common", "(", "struct", ",", "\"request.body\"", ")", "# Iterate through the document sequences if we have any", "has_doc_sequence", "=", "len", "(", "[", "field", "for", "field", "in", "struct", ".", "fields", "if", "field", ".", "supports_doc_sequence", "]", ")", "if", "has_doc_sequence", ":", "with", "self", ".", "_block", "(", "'for (auto&& sequence : request.sequences) {'", ",", "'}'", ")", ":", "field_usage_check", ".", "add_store", "(", "\"sequence.name\"", ")", "self", ".", "_writer", ".", "write_empty_line", "(", ")", "first_field", "=", "True", "for", "field", "in", "struct", ".", "fields", ":", "# Only parse document sequence fields here", "if", "not", "field", ".", "supports_doc_sequence", ":", "continue", "field_predicate", "=", "'sequence.name == %s'", "%", "(", "_get_field_constant_name", "(", "field", ")", ")", "with", "self", ".", "_predicate", "(", "field_predicate", ",", "not", "first_field", ")", ":", "field_usage_check", ".", "add", "(", "field", ",", "\"sequence.name\"", ")", "if", "_is_required_serializer_field", "(", "field", ")", ":", "self", ".", "_writer", ".", "write_line", "(", "'%s = true;'", "%", "(", "_get_has_field_member_name", "(", "field", ")", ")", ")", "self", ".", "gen_doc_sequence_deserializer", "(", "field", ")", "if", "first_field", ":", "first_field", "=", "False", "# End of for fields", "# Generate strict check for extranous fields", "if", "struct", ".", "strict", ":", "with", "self", ".", "_block", "(", "'else {'", ",", "'}'", ")", ":", "self", ".", "_writer", ".", "write_line", "(", "'ctxt.throwUnknownField(sequence.name);'", ")", "self", ".", "_writer", ".", "write_empty_line", "(", ")", "# Check for required fields", "field_usage_check", ".", "add_final_checks", "(", ")", "self", ".", "_writer", ".", "write_empty_line", "(", ")", "# Generate namespace check now that \"$db\" has been read or defaulted", "struct_type_info", ".", "gen_namespace_check", "(", "self", ".", "_writer", ",", "\"_dbName\"", ",", "\"commandElement\"", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/generator.py#L1014-L1075
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.resolve
(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None)
return to_activate
List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required.
List all distributions needed to (recursively) meet `requirements`
[ "List", "all", "distributions", "needed", "to", "(", "recursively", ")", "meet", "requirements" ]
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False, extras=None): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. `extras` is a list of the extras to be used with these requirements. This is important because extra requirements may look like `my_req; extra = "my_extra"`, which would otherwise be interpreted as a purely optional requirement. Instead, we want to be able to assert that these requirements are truly required. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] req_extras = _ReqExtras() # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue if not req_extras.markers_pass(req, extras): continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match( req, ws, installer, replace_conflicting=replace_conflicting ) if dist is None: requirers = required_by.get(req, None) raise DistributionNotFound(req, requirers) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency dependent_req = required_by[req] raise VersionConflict(dist, req).with_context(dependent_req) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) req_extras[new_requirement] = req.extras processed[req] = True # return list of distros to activate return to_activate
[ "def", "resolve", "(", "self", ",", "requirements", ",", "env", "=", "None", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ",", "extras", "=", "None", ")", ":", "# set up the stack", "requirements", "=", "list", "(", "requirements", ")", "[", ":", ":", "-", "1", "]", "# set of processed requirements", "processed", "=", "{", "}", "# key -> dist", "best", "=", "{", "}", "to_activate", "=", "[", "]", "req_extras", "=", "_ReqExtras", "(", ")", "# Mapping of requirement to set of distributions that required it;", "# useful for reporting info about conflicts.", "required_by", "=", "collections", ".", "defaultdict", "(", "set", ")", "while", "requirements", ":", "# process dependencies breadth-first", "req", "=", "requirements", ".", "pop", "(", "0", ")", "if", "req", "in", "processed", ":", "# Ignore cyclic or redundant dependencies", "continue", "if", "not", "req_extras", ".", "markers_pass", "(", "req", ",", "extras", ")", ":", "continue", "dist", "=", "best", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", ":", "# Find the best distribution and add it to the map", "dist", "=", "self", ".", "by_key", ".", "get", "(", "req", ".", "key", ")", "if", "dist", "is", "None", "or", "(", "dist", "not", "in", "req", "and", "replace_conflicting", ")", ":", "ws", "=", "self", "if", "env", "is", "None", ":", "if", "dist", "is", "None", ":", "env", "=", "Environment", "(", "self", ".", "entries", ")", "else", ":", "# Use an empty environment and workingset to avoid", "# any further conflicts with the conflicting", "# distribution", "env", "=", "Environment", "(", "[", "]", ")", "ws", "=", "WorkingSet", "(", "[", "]", ")", "dist", "=", "best", "[", "req", ".", "key", "]", "=", "env", ".", "best_match", "(", "req", ",", "ws", ",", "installer", ",", "replace_conflicting", "=", "replace_conflicting", ")", "if", "dist", "is", "None", ":", "requirers", "=", "required_by", ".", "get", "(", "req", ",", "None", ")", "raise", "DistributionNotFound", "(", "req", ",", "requirers", ")", "to_activate", ".", "append", "(", "dist", ")", "if", "dist", "not", "in", "req", ":", "# Oops, the \"best\" so far conflicts with a dependency", "dependent_req", "=", "required_by", "[", "req", "]", "raise", "VersionConflict", "(", "dist", ",", "req", ")", ".", "with_context", "(", "dependent_req", ")", "# push the new requirements onto the stack", "new_requirements", "=", "dist", ".", "requires", "(", "req", ".", "extras", ")", "[", ":", ":", "-", "1", "]", "requirements", ".", "extend", "(", "new_requirements", ")", "# Register the new requirements needed by req", "for", "new_requirement", "in", "new_requirements", ":", "required_by", "[", "new_requirement", "]", ".", "add", "(", "req", ".", "project_name", ")", "req_extras", "[", "new_requirement", "]", "=", "req", ".", "extras", "processed", "[", "req", "]", "=", "True", "# return list of distros to activate", "return", "to_activate" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L715-L805
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/swift_build_support/swift_build_support/products/libdispatch.py
python
LibDispatch.is_before_build_script_impl_product
(cls)
return False
is_before_build_script_impl_product -> bool Whether this product is built before any build-script-impl products.
is_before_build_script_impl_product -> bool
[ "is_before_build_script_impl_product", "-", ">", "bool" ]
def is_before_build_script_impl_product(cls): """is_before_build_script_impl_product -> bool Whether this product is built before any build-script-impl products. """ return False
[ "def", "is_before_build_script_impl_product", "(", "cls", ")", ":", "return", "False" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/libdispatch.py#L30-L35
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/util.py
python
split_quoted
(s)
return words
Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words.
Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words.
[ "Split", "a", "string", "up", "according", "to", "Unix", "shell", "-", "like", "rules", "for", "quotes", "and", "backslashes", ".", "In", "short", ":", "words", "are", "delimited", "by", "spaces", "as", "long", "as", "those", "spaces", "are", "not", "escaped", "by", "a", "backslash", "or", "inside", "a", "quoted", "string", ".", "Single", "and", "double", "quotes", "are", "equivalent", "and", "the", "quote", "characters", "can", "be", "backslash", "-", "escaped", ".", "The", "backslash", "is", "stripped", "from", "any", "two", "-", "character", "escape", "sequence", "leaving", "only", "the", "escaped", "character", ".", "The", "quote", "characters", "are", "stripped", "from", "any", "quoted", "string", ".", "Returns", "a", "list", "of", "words", "." ]
def split_quoted (s): """Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words. """ # This is a nice algorithm for splitting up a single string, since it # doesn't require character-by-character examination. It was a little # bit of a brain-bender to get it working right, though... if _wordchars_re is None: _init_regex() s = string.strip(s) words = [] pos = 0 while s: m = _wordchars_re.match(s, pos) end = m.end() if end == len(s): words.append(s[:end]) break if s[end] in string.whitespace: # unescaped, unquoted whitespace: now words.append(s[:end]) # we definitely have a word delimiter s = string.lstrip(s[end:]) pos = 0 elif s[end] == '\\': # preserve whatever is being escaped; # will become part of the current word s = s[:end] + s[end+1:] pos = end+1 else: if s[end] == "'": # slurp singly-quoted string m = _squote_re.match(s, end) elif s[end] == '"': # slurp doubly-quoted string m = _dquote_re.match(s, end) else: raise RuntimeError, \ "this can't happen (bad char '%c')" % s[end] if m is None: raise ValueError, \ "bad string (mismatched %s quotes?)" % s[end] (beg, end) = m.span() s = s[:beg] + s[beg+1:end-1] + s[end:] pos = m.end() - 2 if pos >= len(s): words.append(s) break return words
[ "def", "split_quoted", "(", "s", ")", ":", "# This is a nice algorithm for splitting up a single string, since it", "# doesn't require character-by-character examination. It was a little", "# bit of a brain-bender to get it working right, though...", "if", "_wordchars_re", "is", "None", ":", "_init_regex", "(", ")", "s", "=", "string", ".", "strip", "(", "s", ")", "words", "=", "[", "]", "pos", "=", "0", "while", "s", ":", "m", "=", "_wordchars_re", ".", "match", "(", "s", ",", "pos", ")", "end", "=", "m", ".", "end", "(", ")", "if", "end", "==", "len", "(", "s", ")", ":", "words", ".", "append", "(", "s", "[", ":", "end", "]", ")", "break", "if", "s", "[", "end", "]", "in", "string", ".", "whitespace", ":", "# unescaped, unquoted whitespace: now", "words", ".", "append", "(", "s", "[", ":", "end", "]", ")", "# we definitely have a word delimiter", "s", "=", "string", ".", "lstrip", "(", "s", "[", "end", ":", "]", ")", "pos", "=", "0", "elif", "s", "[", "end", "]", "==", "'\\\\'", ":", "# preserve whatever is being escaped;", "# will become part of the current word", "s", "=", "s", "[", ":", "end", "]", "+", "s", "[", "end", "+", "1", ":", "]", "pos", "=", "end", "+", "1", "else", ":", "if", "s", "[", "end", "]", "==", "\"'\"", ":", "# slurp singly-quoted string", "m", "=", "_squote_re", ".", "match", "(", "s", ",", "end", ")", "elif", "s", "[", "end", "]", "==", "'\"'", ":", "# slurp doubly-quoted string", "m", "=", "_dquote_re", ".", "match", "(", "s", ",", "end", ")", "else", ":", "raise", "RuntimeError", ",", "\"this can't happen (bad char '%c')\"", "%", "s", "[", "end", "]", "if", "m", "is", "None", ":", "raise", "ValueError", ",", "\"bad string (mismatched %s quotes?)\"", "%", "s", "[", "end", "]", "(", "beg", ",", "end", ")", "=", "m", ".", "span", "(", ")", "s", "=", "s", "[", ":", "beg", "]", "+", "s", "[", "beg", "+", "1", ":", "end", "-", "1", "]", "+", "s", "[", "end", ":", "]", "pos", "=", "m", ".", "end", "(", ")", "-", "2", "if", "pos", ">=", "len", "(", "s", ")", ":", "words", ".", "append", "(", "s", ")", "break", "return", "words" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/util.py#L235-L293
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/platform/gfile.py
python
_GFileBase.read
(self, n=-1)
return self._fp.read(n)
Read n bytes from the underlying file handle. Args: n: Number of bytes to read (if negative, read to end of file handle.) Returns: A string of the bytes read, up to the end of file.
Read n bytes from the underlying file handle.
[ "Read", "n", "bytes", "from", "the", "underlying", "file", "handle", "." ]
def read(self, n=-1): """Read n bytes from the underlying file handle. Args: n: Number of bytes to read (if negative, read to end of file handle.) Returns: A string of the bytes read, up to the end of file. """ return self._fp.read(n)
[ "def", "read", "(", "self", ",", "n", "=", "-", "1", ")", ":", "return", "self", ".", "_fp", ".", "read", "(", "n", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/platform/gfile.py#L190-L199
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
PseudoDC.SetBrush
(*args, **kwargs)
return _gdi_.PseudoDC_SetBrush(*args, **kwargs)
SetBrush(self, Brush brush) Sets the current brush for the DC. If the argument is ``wx.NullBrush``, the current brush is selected out of the device context, and the original brush restored, allowing the current brush to be destroyed safely.
SetBrush(self, Brush brush)
[ "SetBrush", "(", "self", "Brush", "brush", ")" ]
def SetBrush(*args, **kwargs): """ SetBrush(self, Brush brush) Sets the current brush for the DC. If the argument is ``wx.NullBrush``, the current brush is selected out of the device context, and the original brush restored, allowing the current brush to be destroyed safely. """ return _gdi_.PseudoDC_SetBrush(*args, **kwargs)
[ "def", "SetBrush", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_SetBrush", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L8236-L8246
mapequation/infomap
5f56b94fe0f956483f61a03ef07e94d8def2205e
interfaces/python/infomap.py
python
Infomap.names
(self)
return super().getNames()
Get all node names. Short-hand for ``get_names``. See Also -------- get_names get_name Returns ------- dict of string A dict with node ids as keys and node names as values.
Get all node names.
[ "Get", "all", "node", "names", "." ]
def names(self): """Get all node names. Short-hand for ``get_names``. See Also -------- get_names get_name Returns ------- dict of string A dict with node ids as keys and node names as values. """ return super().getNames()
[ "def", "names", "(", "self", ")", ":", "return", "super", "(", ")", ".", "getNames", "(", ")" ]
https://github.com/mapequation/infomap/blob/5f56b94fe0f956483f61a03ef07e94d8def2205e/interfaces/python/infomap.py#L1853-L1868
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/slim/quantization/quantization_pass.py
python
QuantizationTransformPass._insert_channel_dequant_op
(self, graph, var_node, scale_var_nodes, quant_bits, quant_axis)
return dequant_var_node
Insert fake_channel_wise_dequantize_max_abs in the graph.
Insert fake_channel_wise_dequantize_max_abs in the graph.
[ "Insert", "fake_channel_wise_dequantize_max_abs", "in", "the", "graph", "." ]
def _insert_channel_dequant_op(self, graph, var_node, scale_var_nodes, quant_bits, quant_axis): """ Insert fake_channel_wise_dequantize_max_abs in the graph. """ assert var_node.is_var(), '{} is not a var'.format(var_node.name()) dequant_var_node = graph.create_var_node( name=self._dequantized_var_name(var_node.name()), var_type=var_node.type(), shape=var_node.shape(), var_dtype=var_node.dtype()) dequant_op_node = graph.create_op_node( op_type='fake_channel_wise_dequantize_max_abs', attrs={ 'quant_bits': quant_bits, 'quant_axis': quant_axis, 'op_role': core.op_proto_and_checker_maker.OpRole.Forward }, inputs={'X': var_node, 'Scales': scale_var_nodes}, outputs={'Out': dequant_var_node}) graph.link_to(var_node, dequant_op_node) for scale_n in scale_var_nodes: graph.link_to(scale_n, dequant_op_node) graph.link_to(dequant_op_node, dequant_var_node) return dequant_var_node
[ "def", "_insert_channel_dequant_op", "(", "self", ",", "graph", ",", "var_node", ",", "scale_var_nodes", ",", "quant_bits", ",", "quant_axis", ")", ":", "assert", "var_node", ".", "is_var", "(", ")", ",", "'{} is not a var'", ".", "format", "(", "var_node", ".", "name", "(", ")", ")", "dequant_var_node", "=", "graph", ".", "create_var_node", "(", "name", "=", "self", ".", "_dequantized_var_name", "(", "var_node", ".", "name", "(", ")", ")", ",", "var_type", "=", "var_node", ".", "type", "(", ")", ",", "shape", "=", "var_node", ".", "shape", "(", ")", ",", "var_dtype", "=", "var_node", ".", "dtype", "(", ")", ")", "dequant_op_node", "=", "graph", ".", "create_op_node", "(", "op_type", "=", "'fake_channel_wise_dequantize_max_abs'", ",", "attrs", "=", "{", "'quant_bits'", ":", "quant_bits", ",", "'quant_axis'", ":", "quant_axis", ",", "'op_role'", ":", "core", ".", "op_proto_and_checker_maker", ".", "OpRole", ".", "Forward", "}", ",", "inputs", "=", "{", "'X'", ":", "var_node", ",", "'Scales'", ":", "scale_var_nodes", "}", ",", "outputs", "=", "{", "'Out'", ":", "dequant_var_node", "}", ")", "graph", ".", "link_to", "(", "var_node", ",", "dequant_op_node", ")", "for", "scale_n", "in", "scale_var_nodes", ":", "graph", ".", "link_to", "(", "scale_n", ",", "dequant_op_node", ")", "graph", ".", "link_to", "(", "dequant_op_node", ",", "dequant_var_node", ")", "return", "dequant_var_node" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/quantization_pass.py#L870-L896
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/codecs.py
python
StreamReaderWriter.__getattr__
(self, name, getattr=getattr)
return getattr(self.stream, name)
Inherit all other methods from the underlying stream.
Inherit all other methods from the underlying stream.
[ "Inherit", "all", "other", "methods", "from", "the", "underlying", "stream", "." ]
def __getattr__(self, name, getattr=getattr): """ Inherit all other methods from the underlying stream. """ return getattr(self.stream, name)
[ "def", "__getattr__", "(", "self", ",", "name", ",", "getattr", "=", "getattr", ")", ":", "return", "getattr", "(", "self", ".", "stream", ",", "name", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/codecs.py#L697-L702
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
scripts/cpp_lint.py
python
_NestingState.CheckCompletedBlocks
(self, filename, error)
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes and namespaces have been completely parsed.
[ "Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", "." ]
def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name)
[ "def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj", "in", "self", ".", "stack", ":", "if", "isinstance", "(", "obj", ",", "_ClassInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/class'", ",", "5", ",", "'Failed to find complete declaration of class %s'", "%", "obj", ".", "name", ")", "elif", "isinstance", "(", "obj", ",", "_NamespaceInfo", ")", ":", "error", "(", "filename", ",", "obj", ".", "starting_linenum", ",", "'build/namespaces'", ",", "5", ",", "'Failed to find complete declaration of namespace %s'", "%", "obj", ".", "name", ")" ]
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/scripts/cpp_lint.py#L2176-L2195
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-server/gen-py/sdhashsrv/sdhashsrv.py
python
Iface.displaySet
(self, num1)
Parameters: - num1
Parameters: - num1
[ "Parameters", ":", "-", "num1" ]
def displaySet(self, num1): """ Parameters: - num1 """ pass
[ "def", "displaySet", "(", "self", ",", "num1", ")", ":", "pass" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-server/gen-py/sdhashsrv/sdhashsrv.py#L34-L39
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py
python
SymbolicEquivSet.define
(self, var, redefined, func_ir=None, typ=None)
Besides incrementing the definition count of the given variable name, it will also retrieve and simplify its definition from func_ir, and remember the result for later equivalence comparison. Supported operations are: 1. arithmetic plus and minus with constants 2. wrap_index (relative to some given size)
Besides incrementing the definition count of the given variable name, it will also retrieve and simplify its definition from func_ir, and remember the result for later equivalence comparison. Supported operations are: 1. arithmetic plus and minus with constants 2. wrap_index (relative to some given size)
[ "Besides", "incrementing", "the", "definition", "count", "of", "the", "given", "variable", "name", "it", "will", "also", "retrieve", "and", "simplify", "its", "definition", "from", "func_ir", "and", "remember", "the", "result", "for", "later", "equivalence", "comparison", ".", "Supported", "operations", "are", ":", "1", ".", "arithmetic", "plus", "and", "minus", "with", "constants", "2", ".", "wrap_index", "(", "relative", "to", "some", "given", "size", ")" ]
def define(self, var, redefined, func_ir=None, typ=None): """Besides incrementing the definition count of the given variable name, it will also retrieve and simplify its definition from func_ir, and remember the result for later equivalence comparison. Supported operations are: 1. arithmetic plus and minus with constants 2. wrap_index (relative to some given size) """ if isinstance(var, ir.Var): name = var.name else: name = var super(SymbolicEquivSet, self).define(name, redefined) if (func_ir and self.defs.get(name, 0) == 1 and isinstance(typ, types.Number)): value = guard(self._get_or_set_rel, name, func_ir) # turn constant definition into equivalence if isinstance(value, int): self._insert([name, value]) if isinstance(var, ir.Var): ind = self._get_or_add_ind(name) if not (ind in self.ind_to_obj): self.ind_to_obj[ind] = [name] self.obj_to_ind[name] = ind if ind in self.ind_to_var: self.ind_to_var[ind].append(var) else: self.ind_to_var[ind] = [var]
[ "def", "define", "(", "self", ",", "var", ",", "redefined", ",", "func_ir", "=", "None", ",", "typ", "=", "None", ")", ":", "if", "isinstance", "(", "var", ",", "ir", ".", "Var", ")", ":", "name", "=", "var", ".", "name", "else", ":", "name", "=", "var", "super", "(", "SymbolicEquivSet", ",", "self", ")", ".", "define", "(", "name", ",", "redefined", ")", "if", "(", "func_ir", "and", "self", ".", "defs", ".", "get", "(", "name", ",", "0", ")", "==", "1", "and", "isinstance", "(", "typ", ",", "types", ".", "Number", ")", ")", ":", "value", "=", "guard", "(", "self", ".", "_get_or_set_rel", ",", "name", ",", "func_ir", ")", "# turn constant definition into equivalence", "if", "isinstance", "(", "value", ",", "int", ")", ":", "self", ".", "_insert", "(", "[", "name", ",", "value", "]", ")", "if", "isinstance", "(", "var", ",", "ir", ".", "Var", ")", ":", "ind", "=", "self", ".", "_get_or_add_ind", "(", "name", ")", "if", "not", "(", "ind", "in", "self", ".", "ind_to_obj", ")", ":", "self", ".", "ind_to_obj", "[", "ind", "]", "=", "[", "name", "]", "self", ".", "obj_to_ind", "[", "name", "]", "=", "ind", "if", "ind", "in", "self", ".", "ind_to_var", ":", "self", ".", "ind_to_var", "[", "ind", "]", ".", "append", "(", "var", ")", "else", ":", "self", ".", "ind_to_var", "[", "ind", "]", "=", "[", "var", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py#L825-L852
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
doc/slihelp_generator/writers.py
python
write_helpindex
(helpdir)
Writes helpindex.html and helpindex.hlp ---------------------------------------
Writes helpindex.html and helpindex.hlp ---------------------------------------
[ "Writes", "helpindex", ".", "html", "and", "helpindex", ".", "hlp", "---------------------------------------" ]
def write_helpindex(helpdir): """ Writes helpindex.html and helpindex.hlp --------------------------------------- """ # We only have to generate a helpindex if the help directory exists if not os.path.exists(helpdir): print("Error: Help directory not found: " + helpdir) return filelist = glob.glob(os.path.join(helpdir, '*', '*.hlp')) html_list = [] hlp_list = [] # Loading Template for helpindex.html ftemplate = io.open(os.path.join('templates', 'helpindex.tpl.html'), encoding='utf-8') templ = ftemplate.read() ftemplate.close() # Loading Template for CSS cssf = io.open(os.path.join('templates', 'nest.tpl.css'), encoding='utf-8') csstempl = cssf.read() cssf.close() # Loading Template for footer footerf = io.open(os.path.join('templates', 'footer.tpl.html'), encoding='utf-8') footertempl = footerf.read() footerf.close() s = Template(templ) alpha = [('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd'), ('E', 'e'), ('F', 'f'), ('G', 'g'), ('H', 'h'), ('I', 'i'), ('J', 'j'), ('K', 'k'), ('L', 'l'), ('M', 'm'), ('N', 'n'), ('O', 'o'), ('P', 'p'), ('Q', 'q'), ('R', 'r'), ('S', 's'), ('T', 't'), ('U', 'u'), ('V', 'v'), ('W', 'w'), ('X', 'x'), ('Z', 'z'), '-', ':', '<', '='] for doubles in alpha: html_list.append('<center><table class="alpha">') html_list.append('<table class="letteridx"><tr>') for x in alpha: html_list.append('<td><a href="#%s">%s</a></td>' % (x[0], x[0])) html_list.append('</tr></table></center>') html_list.append('<center><table class="commands" id="%s">' % doubles[0]) for item in sorted(filelist, key=lambda name: name.lower().rsplit('/', 1)[1]): fitem = io.open(item, encoding='utf-8') itemtext = fitem.read() fitem.close() # only the basename of the file name = os.path.basename(item)[:-4] # only the first line of itemtext name_line = itemtext.splitlines()[0] # if name_line.rsplit(' - ')[0] == 'Name: ' + name: fullname = name_line.rsplit(' - ')[1] else: fullname = name # file extension itemext = item.rsplit('/')[-2] if name.startswith(doubles) and os.path.isfile(item): # check if 'name' is available in folder with os.path.isfile( # checkfile) html_list.append('<tr><td class="left">') html_list.append('<a href="%s/%s.html">%s</a></td>' % (itemext, name, name)) html_list.append('<td>%s</td></tr>' % fullname) # Better Format for the index.hlp c = len(name) hlp_list.append(name + '\t' * (16 - min(c, 60) // 4) + fullname) elif not os.path.isfile(item): print('WARNING: Checkfile ' + item + ' not exist.') html_list.append('</table></center>') html_list.append('</table></center>') # html_list.append(footer) htmlstring = (u'\n'.join(html_list)) indexstring = s.substitute(indexbody=htmlstring, css=csstempl, footer=footertempl) f_helpindex = io.open(os.path.join(helpdir, 'helpindex.html'), mode='w', encoding='utf-8') f_helpindex.write(indexstring) f_helpindex.write(u'\n') f_helpindex.close() # Todo: using string template for .hlp f_helphlpindex = io.open(os.path.join(helpdir, 'helpindex.hlp'), mode='w', encoding='utf-8') f_helphlpindex.write(u'\n'.join(hlp_list)) f_helphlpindex.write(u'\n') f_helphlpindex.close()
[ "def", "write_helpindex", "(", "helpdir", ")", ":", "# We only have to generate a helpindex if the help directory exists", "if", "not", "os", ".", "path", ".", "exists", "(", "helpdir", ")", ":", "print", "(", "\"Error: Help directory not found: \"", "+", "helpdir", ")", "return", "filelist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "helpdir", ",", "'*'", ",", "'*.hlp'", ")", ")", "html_list", "=", "[", "]", "hlp_list", "=", "[", "]", "# Loading Template for helpindex.html", "ftemplate", "=", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "'templates'", ",", "'helpindex.tpl.html'", ")", ",", "encoding", "=", "'utf-8'", ")", "templ", "=", "ftemplate", ".", "read", "(", ")", "ftemplate", ".", "close", "(", ")", "# Loading Template for CSS", "cssf", "=", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "'templates'", ",", "'nest.tpl.css'", ")", ",", "encoding", "=", "'utf-8'", ")", "csstempl", "=", "cssf", ".", "read", "(", ")", "cssf", ".", "close", "(", ")", "# Loading Template for footer", "footerf", "=", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "'templates'", ",", "'footer.tpl.html'", ")", ",", "encoding", "=", "'utf-8'", ")", "footertempl", "=", "footerf", ".", "read", "(", ")", "footerf", ".", "close", "(", ")", "s", "=", "Template", "(", "templ", ")", "alpha", "=", "[", "(", "'A'", ",", "'a'", ")", ",", "(", "'B'", ",", "'b'", ")", ",", "(", "'C'", ",", "'c'", ")", ",", "(", "'D'", ",", "'d'", ")", ",", "(", "'E'", ",", "'e'", ")", ",", "(", "'F'", ",", "'f'", ")", ",", "(", "'G'", ",", "'g'", ")", ",", "(", "'H'", ",", "'h'", ")", ",", "(", "'I'", ",", "'i'", ")", ",", "(", "'J'", ",", "'j'", ")", ",", "(", "'K'", ",", "'k'", ")", ",", "(", "'L'", ",", "'l'", ")", ",", "(", "'M'", ",", "'m'", ")", ",", "(", "'N'", ",", "'n'", ")", ",", "(", "'O'", ",", "'o'", ")", ",", "(", "'P'", ",", "'p'", ")", ",", "(", "'Q'", ",", "'q'", ")", ",", "(", "'R'", ",", "'r'", ")", ",", "(", "'S'", ",", "'s'", ")", ",", "(", "'T'", ",", "'t'", ")", ",", "(", "'U'", ",", "'u'", ")", ",", "(", "'V'", ",", "'v'", ")", ",", "(", "'W'", ",", "'w'", ")", ",", "(", "'X'", ",", "'x'", ")", ",", "(", "'Z'", ",", "'z'", ")", ",", "'-'", ",", "':'", ",", "'<'", ",", "'='", "]", "for", "doubles", "in", "alpha", ":", "html_list", ".", "append", "(", "'<center><table class=\"alpha\">'", ")", "html_list", ".", "append", "(", "'<table class=\"letteridx\"><tr>'", ")", "for", "x", "in", "alpha", ":", "html_list", ".", "append", "(", "'<td><a href=\"#%s\">%s</a></td>'", "%", "(", "x", "[", "0", "]", ",", "x", "[", "0", "]", ")", ")", "html_list", ".", "append", "(", "'</tr></table></center>'", ")", "html_list", ".", "append", "(", "'<center><table class=\"commands\" id=\"%s\">'", "%", "doubles", "[", "0", "]", ")", "for", "item", "in", "sorted", "(", "filelist", ",", "key", "=", "lambda", "name", ":", "name", ".", "lower", "(", ")", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "1", "]", ")", ":", "fitem", "=", "io", ".", "open", "(", "item", ",", "encoding", "=", "'utf-8'", ")", "itemtext", "=", "fitem", ".", "read", "(", ")", "fitem", ".", "close", "(", ")", "# only the basename of the file", "name", "=", "os", ".", "path", ".", "basename", "(", "item", ")", "[", ":", "-", "4", "]", "# only the first line of itemtext", "name_line", "=", "itemtext", ".", "splitlines", "(", ")", "[", "0", "]", "#", "if", "name_line", ".", "rsplit", "(", "' - '", ")", "[", "0", "]", "==", "'Name: '", "+", "name", ":", "fullname", "=", "name_line", ".", "rsplit", "(", "' - '", ")", "[", "1", "]", "else", ":", "fullname", "=", "name", "# file extension", "itemext", "=", "item", ".", "rsplit", "(", "'/'", ")", "[", "-", "2", "]", "if", "name", ".", "startswith", "(", "doubles", ")", "and", "os", ".", "path", ".", "isfile", "(", "item", ")", ":", "# check if 'name' is available in folder with os.path.isfile(", "# checkfile)", "html_list", ".", "append", "(", "'<tr><td class=\"left\">'", ")", "html_list", ".", "append", "(", "'<a href=\"%s/%s.html\">%s</a></td>'", "%", "(", "itemext", ",", "name", ",", "name", ")", ")", "html_list", ".", "append", "(", "'<td>%s</td></tr>'", "%", "fullname", ")", "# Better Format for the index.hlp", "c", "=", "len", "(", "name", ")", "hlp_list", ".", "append", "(", "name", "+", "'\\t'", "*", "(", "16", "-", "min", "(", "c", ",", "60", ")", "//", "4", ")", "+", "fullname", ")", "elif", "not", "os", ".", "path", ".", "isfile", "(", "item", ")", ":", "print", "(", "'WARNING: Checkfile '", "+", "item", "+", "' not exist.'", ")", "html_list", ".", "append", "(", "'</table></center>'", ")", "html_list", ".", "append", "(", "'</table></center>'", ")", "# html_list.append(footer)", "htmlstring", "=", "(", "u'\\n'", ".", "join", "(", "html_list", ")", ")", "indexstring", "=", "s", ".", "substitute", "(", "indexbody", "=", "htmlstring", ",", "css", "=", "csstempl", ",", "footer", "=", "footertempl", ")", "f_helpindex", "=", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "helpdir", ",", "'helpindex.html'", ")", ",", "mode", "=", "'w'", ",", "encoding", "=", "'utf-8'", ")", "f_helpindex", ".", "write", "(", "indexstring", ")", "f_helpindex", ".", "write", "(", "u'\\n'", ")", "f_helpindex", ".", "close", "(", ")", "# Todo: using string template for .hlp", "f_helphlpindex", "=", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "helpdir", ",", "'helpindex.hlp'", ")", ",", "mode", "=", "'w'", ",", "encoding", "=", "'utf-8'", ")", "f_helphlpindex", ".", "write", "(", "u'\\n'", ".", "join", "(", "hlp_list", ")", ")", "f_helphlpindex", ".", "write", "(", "u'\\n'", ")", "f_helphlpindex", ".", "close", "(", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/doc/slihelp_generator/writers.py#L152-L251
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WriteMacXCassets
(self, xcassets, bundle_depends)
return partial_info_plist
Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.
Writes ninja edges for 'mac_bundle_resources' .xcassets files.
[ "Writes", "ninja", "edges", "for", "mac_bundle_resources", ".", "xcassets", "files", "." ]
def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { 'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.iteritems(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( 'assetcatalog_generated_info.plist') extra_arguments['output-partial-info-plist'] = partial_info_plist outputs = [] outputs.append( os.path.join( self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend(self.ninja.build( outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)])) return partial_info_plist
[ "def", "WriteMacXCassets", "(", "self", ",", "xcassets", ",", "bundle_depends", ")", ":", "if", "not", "xcassets", ":", "return", "extra_arguments", "=", "{", "}", "settings_to_arg", "=", "{", "'XCASSETS_APP_ICON'", ":", "'app-icon'", ",", "'XCASSETS_LAUNCH_IMAGE'", ":", "'launch-image'", ",", "}", "settings", "=", "self", ".", "xcode_settings", ".", "xcode_settings", "[", "self", ".", "config_name", "]", "for", "settings_key", ",", "arg_name", "in", "settings_to_arg", ".", "iteritems", "(", ")", ":", "value", "=", "settings", ".", "get", "(", "settings_key", ")", "if", "value", ":", "extra_arguments", "[", "arg_name", "]", "=", "value", "partial_info_plist", "=", "None", "if", "extra_arguments", ":", "partial_info_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "'assetcatalog_generated_info.plist'", ")", "extra_arguments", "[", "'output-partial-info-plist'", "]", "=", "partial_info_plist", "outputs", "=", "[", "]", "outputs", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "xcode_settings", ".", "GetBundleResourceFolder", "(", ")", ",", "'Assets.car'", ")", ")", "if", "partial_info_plist", ":", "outputs", ".", "append", "(", "partial_info_plist", ")", "keys", "=", "QuoteShellArgument", "(", "json", ".", "dumps", "(", "extra_arguments", ")", ",", "self", ".", "flavor", ")", "extra_env", "=", "self", ".", "xcode_settings", ".", "GetPerTargetSettings", "(", ")", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "extra_env", ")", "env", "=", "self", ".", "ComputeExportEnvString", "(", "env", ")", "bundle_depends", ".", "extend", "(", "self", ".", "ninja", ".", "build", "(", "outputs", ",", "'compile_xcassets'", ",", "xcassets", ",", "variables", "=", "[", "(", "'env'", ",", "env", ")", ",", "(", "'keys'", ",", "keys", ")", "]", ")", ")", "return", "partial_info_plist" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/ninja.py#L824-L868
microsoft/AirSim
8057725712c0cd46979135396381784075ffc0f3
PythonClient/airsim/client.py
python
VehicleClient.simListAssets
(self)
return self.client.call('simListAssets')
Lists all the assets present in the Asset Registry Returns: list[str]: Names of all the assets
Lists all the assets present in the Asset Registry
[ "Lists", "all", "the", "assets", "present", "in", "the", "Asset", "Registry" ]
def simListAssets(self): """ Lists all the assets present in the Asset Registry Returns: list[str]: Names of all the assets """ return self.client.call('simListAssets')
[ "def", "simListAssets", "(", "self", ")", ":", "return", "self", ".", "client", ".", "call", "(", "'simListAssets'", ")" ]
https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L568-L575
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TreeCtrl.AppendItem
(*args, **kwargs)
return _controls_.TreeCtrl_AppendItem(*args, **kwargs)
AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId
AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId
[ "AppendItem", "(", "self", "TreeItemId", "parent", "String", "text", "int", "image", "=", "-", "1", "int", "selectedImage", "=", "-", "1", "TreeItemData", "data", "=", "None", ")", "-", ">", "TreeItemId" ]
def AppendItem(*args, **kwargs): """ AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId """ return _controls_.TreeCtrl_AppendItem(*args, **kwargs)
[ "def", "AppendItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_AppendItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5444-L5449
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/variable_scope.py
python
VariableScope.reuse_variables
(self)
Reuse variables in this scope.
Reuse variables in this scope.
[ "Reuse", "variables", "in", "this", "scope", "." ]
def reuse_variables(self): """Reuse variables in this scope.""" self._reuse = True
[ "def", "reuse_variables", "(", "self", ")", ":", "self", ".", "_reuse", "=", "True" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variable_scope.py#L636-L638
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
scripts/cpp_lint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and succesfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functional>': (1219, 'less<>') }", "for", "linenum", "in", "xrange", "(", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", "or", "line", "[", "0", "]", "==", "'#'", ":", "continue", "# String is special -- it is a non-templatized type in STL.", "matched", "=", "_RE_PATTERN_STRING", ".", "search", "(", "line", ")", "if", "matched", ":", "# Don't warn about strings in non-STL namespaces:", "# (We check only the first match per line; good enough.)", "prefix", "=", "line", "[", ":", "matched", ".", "start", "(", ")", "]", "if", "prefix", ".", "endswith", "(", "'std::'", ")", "or", "not", "prefix", ".", "endswith", "(", "'::'", ")", ":", "required", "[", "'<string>'", "]", "=", "(", "linenum", ",", "'string'", ")", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_algorithm_header", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The following function is just a speed up, no semantics are changed.", "if", "not", "'<'", "in", "line", ":", "# Reduces the cpu time usage by skipping lines.", "continue", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_templates", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The policy is that if you #include something in foo.h you don't need to", "# include it again in foo.cc. Here, we will look at possible includes.", "# Let's copy the include_state so it is only messed up within this function.", "include_state", "=", "include_state", ".", "copy", "(", ")", "# Did we find the header for this file (if any) and succesfully load it?", "header_found", "=", "False", "# Use the absolute path so that matching works properly.", "abs_filename", "=", "FileInfo", "(", "filename", ")", ".", "FullName", "(", ")", "# For Emacs's flymake.", "# If cpplint is invoked from Emacs's flymake, a temporary file is generated", "# by flymake and that file name might end with '_flymake.cc'. In that case,", "# restore original file name here so that the corresponding header file can be", "# found.", "# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'", "# instead of 'foo_flymake.h'", "abs_filename", "=", "re", ".", "sub", "(", "r'_flymake\\.cc$'", ",", "'.cc'", ",", "abs_filename", ")", "# include_state is modified during iteration, so we iterate over a copy of", "# the keys.", "header_keys", "=", "include_state", ".", "keys", "(", ")", "for", "header", "in", "header_keys", ":", "(", "same_module", ",", "common_path", ")", "=", "FilesBelongToSameModule", "(", "abs_filename", ",", "header", ")", "fullpath", "=", "common_path", "+", "header", "if", "same_module", "and", "UpdateIncludeState", "(", "fullpath", ",", "include_state", ",", "io", ")", ":", "header_found", "=", "True", "# If we can't find the header file for a .cc, assume it's because we don't", "# know where to look. In that case we'll give up as we're not sure they", "# didn't include it in the .h file.", "# TODO(unknown): Do a better job of finding .h files so we are confident that", "# not having the .h file means there isn't one.", "if", "filename", ".", "endswith", "(", "'.cc'", ")", "and", "not", "header_found", ":", "return", "# All the lines have been processed, report the errors found.", "for", "required_header_unstripped", "in", "required", ":", "template", "=", "required", "[", "required_header_unstripped", "]", "[", "1", "]", "if", "required_header_unstripped", ".", "strip", "(", "'<>\"'", ")", "not", "in", "include_state", ":", "error", "(", "filename", ",", "required", "[", "required_header_unstripped", "]", "[", "0", "]", ",", "'build/include_what_you_use'", ",", "4", ",", "'Add #include '", "+", "required_header_unstripped", "+", "' for '", "+", "template", ")" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L4483-L4573
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/conversion.py
python
convert_func_to_ast
(f, program_ctx, do_rename=True)
return (node,), new_name, entity_info
Specialization of `convert_entity_to_ast` for callable functions.
Specialization of `convert_entity_to_ast` for callable functions.
[ "Specialization", "of", "convert_entity_to_ast", "for", "callable", "functions", "." ]
def convert_func_to_ast(f, program_ctx, do_rename=True): """Specialization of `convert_entity_to_ast` for callable functions.""" future_features = inspect_utils.getfutureimports(f) node, source = parser.parse_entity(f, future_features=future_features) logging.log(3, 'Source code of %s:\n\n%s\n', f, source) # Parsed AST should contain future imports and one function def node. # In general, the output of inspect.getsource is inexact for lambdas because # it uses regex matching to adjust the exact location around the line number # that CPython records. Then, the entire containing line is returned, which # we may have trouble disambiguating. For example: # x, y = lambda: 1, lambda: 2 if f.__name__ == '<lambda>': nodes = ast_util.find_matching_definitions(node, f) if len(nodes) != 1: raise ValueError( 'Unable to identify source code of lambda function {}. It was' ' defined on this line: {}, which must contain a single lambda with' ' matching signature. To avoid ambiguity, define each lambda' ' in a separate expression.'.format(f, source)) node, = nodes # TODO(znado): Place inside standard_analysis. origin_info.resolve_entity(node, source, f) namespace = inspect_utils.getnamespace(f) _add_self_references(namespace, program_ctx.autograph_module) namer = naming.Namer(namespace) if isinstance(node, gast.Lambda): new_name = namer.new_symbol('tf__lambda', ()) elif do_rename: new_name = namer.function_name(f.__name__) else: new_name = f.__name__ entity_info = transformer.EntityInfo( source_code=source, source_file='<fragment>', future_features=future_features, namespace=namespace) context = converter.EntityContext(namer, entity_info, program_ctx, new_name) node = node_to_graph(node, context) if isinstance(node, gast.Lambda): node = gast.Assign( targets=[gast.Name(new_name, gast.Store(), None)], value=node) elif do_rename: node.name = new_name else: assert node.name == new_name return (node,), new_name, entity_info
[ "def", "convert_func_to_ast", "(", "f", ",", "program_ctx", ",", "do_rename", "=", "True", ")", ":", "future_features", "=", "inspect_utils", ".", "getfutureimports", "(", "f", ")", "node", ",", "source", "=", "parser", ".", "parse_entity", "(", "f", ",", "future_features", "=", "future_features", ")", "logging", ".", "log", "(", "3", ",", "'Source code of %s:\\n\\n%s\\n'", ",", "f", ",", "source", ")", "# Parsed AST should contain future imports and one function def node.", "# In general, the output of inspect.getsource is inexact for lambdas because", "# it uses regex matching to adjust the exact location around the line number", "# that CPython records. Then, the entire containing line is returned, which", "# we may have trouble disambiguating. For example:", "# x, y = lambda: 1, lambda: 2", "if", "f", ".", "__name__", "==", "'<lambda>'", ":", "nodes", "=", "ast_util", ".", "find_matching_definitions", "(", "node", ",", "f", ")", "if", "len", "(", "nodes", ")", "!=", "1", ":", "raise", "ValueError", "(", "'Unable to identify source code of lambda function {}. It was'", "' defined on this line: {}, which must contain a single lambda with'", "' matching signature. To avoid ambiguity, define each lambda'", "' in a separate expression.'", ".", "format", "(", "f", ",", "source", ")", ")", "node", ",", "=", "nodes", "# TODO(znado): Place inside standard_analysis.", "origin_info", ".", "resolve_entity", "(", "node", ",", "source", ",", "f", ")", "namespace", "=", "inspect_utils", ".", "getnamespace", "(", "f", ")", "_add_self_references", "(", "namespace", ",", "program_ctx", ".", "autograph_module", ")", "namer", "=", "naming", ".", "Namer", "(", "namespace", ")", "if", "isinstance", "(", "node", ",", "gast", ".", "Lambda", ")", ":", "new_name", "=", "namer", ".", "new_symbol", "(", "'tf__lambda'", ",", "(", ")", ")", "elif", "do_rename", ":", "new_name", "=", "namer", ".", "function_name", "(", "f", ".", "__name__", ")", "else", ":", "new_name", "=", "f", ".", "__name__", "entity_info", "=", "transformer", ".", "EntityInfo", "(", "source_code", "=", "source", ",", "source_file", "=", "'<fragment>'", ",", "future_features", "=", "future_features", ",", "namespace", "=", "namespace", ")", "context", "=", "converter", ".", "EntityContext", "(", "namer", ",", "entity_info", ",", "program_ctx", ",", "new_name", ")", "node", "=", "node_to_graph", "(", "node", ",", "context", ")", "if", "isinstance", "(", "node", ",", "gast", ".", "Lambda", ")", ":", "node", "=", "gast", ".", "Assign", "(", "targets", "=", "[", "gast", ".", "Name", "(", "new_name", ",", "gast", ".", "Store", "(", ")", ",", "None", ")", "]", ",", "value", "=", "node", ")", "elif", "do_rename", ":", "node", ".", "name", "=", "new_name", "else", ":", "assert", "node", ".", "name", "==", "new_name", "return", "(", "node", ",", ")", ",", "new_name", ",", "entity_info" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/conversion.py#L626-L679
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStrV.Sort
(self, Asc=True)
return _snap.TStrV_Sort(self, Asc)
Sort(TStrV self, bool const & Asc=True) Parameters: Asc: bool const & Sort(TStrV self) Parameters: self: TVec< TStr,int > *
Sort(TStrV self, bool const & Asc=True)
[ "Sort", "(", "TStrV", "self", "bool", "const", "&", "Asc", "=", "True", ")" ]
def Sort(self, Asc=True): """ Sort(TStrV self, bool const & Asc=True) Parameters: Asc: bool const & Sort(TStrV self) Parameters: self: TVec< TStr,int > * """ return _snap.TStrV_Sort(self, Asc)
[ "def", "Sort", "(", "self", ",", "Asc", "=", "True", ")", ":", "return", "_snap", ".", "TStrV_Sort", "(", "self", ",", "Asc", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19712-L19725
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
external/tools/build/v2/util/path.py
python
glob_in_parents
(dir, patterns, upper_limit=None)
return result
Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found
Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found
[ "Recursive", "version", "of", "GLOB", "which", "glob", "sall", "parent", "directories", "of", "dir", "until", "the", "first", "match", "is", "found", ".", "Returns", "an", "empty", "result", "if", "no", "match", "is", "found" ]
def glob_in_parents(dir, patterns, upper_limit=None): """Recursive version of GLOB which glob sall parent directories of dir until the first match is found. Returns an empty result if no match is found""" assert(isinstance(dir, str)) assert(isinstance(patterns, list)) result = [] absolute_dir = os.path.join(os.getcwd(), dir) absolute_dir = os.path.normpath(absolute_dir) while absolute_dir: new_dir = os.path.split(absolute_dir)[0] if new_dir == absolute_dir: break result = glob([new_dir], patterns) if result: break absolute_dir = new_dir return result
[ "def", "glob_in_parents", "(", "dir", ",", "patterns", ",", "upper_limit", "=", "None", ")", ":", "assert", "(", "isinstance", "(", "dir", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "patterns", ",", "list", ")", ")", "result", "=", "[", "]", "absolute_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "dir", ")", "absolute_dir", "=", "os", ".", "path", ".", "normpath", "(", "absolute_dir", ")", "while", "absolute_dir", ":", "new_dir", "=", "os", ".", "path", ".", "split", "(", "absolute_dir", ")", "[", "0", "]", "if", "new_dir", "==", "absolute_dir", ":", "break", "result", "=", "glob", "(", "[", "new_dir", "]", ",", "patterns", ")", "if", "result", ":", "break", "absolute_dir", "=", "new_dir", "return", "result" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/util/path.py#L857-L878
OpenGenus/quark
225ad96efdfcc66cb6584a756c17eb3871e6eb62
code/code/data_structures/src/tree/b_tree/b_tree/b_tree.py
python
BTree.search
(self, k, x=None)
Search the B-Tree for the key k. args ===================== k : Key to search for x : (optional) Node at which to begin search. Can be None, in which case the entire tree is searched.
Search the B-Tree for the key k. args ===================== k : Key to search for x : (optional) Node at which to begin search. Can be None, in which case the entire tree is searched.
[ "Search", "the", "B", "-", "Tree", "for", "the", "key", "k", ".", "args", "=====================", "k", ":", "Key", "to", "search", "for", "x", ":", "(", "optional", ")", "Node", "at", "which", "to", "begin", "search", ".", "Can", "be", "None", "in", "which", "case", "the", "entire", "tree", "is", "searched", "." ]
def search(self, k, x=None): """Search the B-Tree for the key k. args ===================== k : Key to search for x : (optional) Node at which to begin search. Can be None, in which case the entire tree is searched. """ if isinstance(x, BTreeNode): i = 0 while i < len(x.keys) and k > x.keys[i]: # look for index of k i += 1 if i < len(x.keys) and k == x.keys[i]: # found exact match return (x, i) elif x.leaf: # no match in keys, and is leaf ==> no match exists return None else: # search children return self.search(k, x.c[i]) else: # no node provided, search root of tree return self.search(k, self.root)
[ "def", "search", "(", "self", ",", "k", ",", "x", "=", "None", ")", ":", "if", "isinstance", "(", "x", ",", "BTreeNode", ")", ":", "i", "=", "0", "while", "i", "<", "len", "(", "x", ".", "keys", ")", "and", "k", ">", "x", ".", "keys", "[", "i", "]", ":", "# look for index of k", "i", "+=", "1", "if", "i", "<", "len", "(", "x", ".", "keys", ")", "and", "k", "==", "x", ".", "keys", "[", "i", "]", ":", "# found exact match", "return", "(", "x", ",", "i", ")", "elif", "x", ".", "leaf", ":", "# no match in keys, and is leaf ==> no match exists", "return", "None", "else", ":", "# search children", "return", "self", ".", "search", "(", "k", ",", "x", ".", "c", "[", "i", "]", ")", "else", ":", "# no node provided, search root of tree", "return", "self", ".", "search", "(", "k", ",", "self", ".", "root", ")" ]
https://github.com/OpenGenus/quark/blob/225ad96efdfcc66cb6584a756c17eb3871e6eb62/code/code/data_structures/src/tree/b_tree/b_tree/b_tree.py#L30-L50
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
ratings/cbt_ratings.py
python
current_run
(model_ids)
return 'v' + str(max_num)
Return the largest number run. If you want something different, feel free to extend with fsdb or something.
Return the largest number run.
[ "Return", "the", "largest", "number", "run", "." ]
def current_run(model_ids): """Return the largest number run. If you want something different, feel free to extend with fsdb or something. """ all_runs = set(run for run, name in model_ids) # TODO fix before submit return max(all_runs) # Assumption of the run format. assert all(re.match("v[0-9]+", run) for run in all_runs), all_runs # "Current" is defined as largest numbered run. max_num = max(int(r[1:] for r in all_runs)) return 'v' + str(max_num)
[ "def", "current_run", "(", "model_ids", ")", ":", "all_runs", "=", "set", "(", "run", "for", "run", ",", "name", "in", "model_ids", ")", "# TODO fix before submit", "return", "max", "(", "all_runs", ")", "# Assumption of the run format.", "assert", "all", "(", "re", ".", "match", "(", "\"v[0-9]+\"", ",", "run", ")", "for", "run", "in", "all_runs", ")", ",", "all_runs", "# \"Current\" is defined as largest numbered run.", "max_num", "=", "max", "(", "int", "(", "r", "[", "1", ":", "]", "for", "r", "in", "all_runs", ")", ")", "return", "'v'", "+", "str", "(", "max_num", ")" ]
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/ratings/cbt_ratings.py#L321-L336
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/sets.py
python
BaseSet.symmetric_difference
(self, other)
return result
Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.)
Return the symmetric difference of two sets as a new set.
[ "Return", "the", "symmetric", "difference", "of", "two", "sets", "as", "a", "new", "set", "." ]
def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ result = self.__class__() data = result._data value = True selfdata = self._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data for elt in ifilterfalse(otherdata.__contains__, selfdata): data[elt] = value for elt in ifilterfalse(selfdata.__contains__, otherdata): data[elt] = value return result
[ "def", "symmetric_difference", "(", "self", ",", "other", ")", ":", "result", "=", "self", ".", "__class__", "(", ")", "data", "=", "result", ".", "_data", "value", "=", "True", "selfdata", "=", "self", ".", "_data", "try", ":", "otherdata", "=", "other", ".", "_data", "except", "AttributeError", ":", "otherdata", "=", "Set", "(", "other", ")", ".", "_data", "for", "elt", "in", "ifilterfalse", "(", "otherdata", ".", "__contains__", ",", "selfdata", ")", ":", "data", "[", "elt", "]", "=", "value", "for", "elt", "in", "ifilterfalse", "(", "selfdata", ".", "__contains__", ",", "otherdata", ")", ":", "data", "[", "elt", "]", "=", "value", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/sets.py#L228-L245
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/tlslite/VerifierDB.py
python
VerifierDB.makeVerifier
(username, password, bits)
return mathtls.makeVerifier(username, password, bits)
Create a verifier entry which can be stored in a VerifierDB. @type username: str @param username: The username for this verifier. Must be less than 256 characters in length. @type password: str @param password: The password for this verifier. @type bits: int @param bits: This values specifies which SRP group parameters to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144, 8192). Larger values are more secure but slower. 2048 is a good compromise between safety and speed. @rtype: tuple @return: A tuple which may be stored in a VerifierDB.
Create a verifier entry which can be stored in a VerifierDB.
[ "Create", "a", "verifier", "entry", "which", "can", "be", "stored", "in", "a", "VerifierDB", "." ]
def makeVerifier(username, password, bits): """Create a verifier entry which can be stored in a VerifierDB. @type username: str @param username: The username for this verifier. Must be less than 256 characters in length. @type password: str @param password: The password for this verifier. @type bits: int @param bits: This values specifies which SRP group parameters to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144, 8192). Larger values are more secure but slower. 2048 is a good compromise between safety and speed. @rtype: tuple @return: A tuple which may be stored in a VerifierDB. """ return mathtls.makeVerifier(username, password, bits)
[ "def", "makeVerifier", "(", "username", ",", "password", ",", "bits", ")", ":", "return", "mathtls", ".", "makeVerifier", "(", "username", ",", "password", ",", "bits", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/VerifierDB.py#L70-L89
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/packages/six.py
python
iterkeys
(d)
return iter(getattr(d, _iterkeys)())
Return an iterator over the keys of a dictionary.
Return an iterator over the keys of a dictionary.
[ "Return", "an", "iterator", "over", "the", "keys", "of", "a", "dictionary", "." ]
def iterkeys(d): """Return an iterator over the keys of a dictionary.""" return iter(getattr(d, _iterkeys)())
[ "def", "iterkeys", "(", "d", ")", ":", "return", "iter", "(", "getattr", "(", "d", ",", "_iterkeys", ")", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/packages/six.py#L263-L265
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Tools/CryVersionSelector/cryselect.py
python
error_engine_path_not_found
(args, engine_id)
Error to specify that the engine path could not be found, because the engine was not registered.
Error to specify that the engine path could not be found, because the engine was not registered.
[ "Error", "to", "specify", "that", "the", "engine", "path", "could", "not", "be", "found", "because", "the", "engine", "was", "not", "registered", "." ]
def error_engine_path_not_found(args, engine_id): """ Error to specify that the engine path could not be found, because the engine was not registered. """ message = "CryEngine '{}' has not been registered locally.\n".format( engine_id) if not args.silent and HAS_WIN_MODULES: MESSAGEBOX(None, message, command_title(args), win32con.MB_OK | win32con.MB_ICONERROR) else: sys.stderr.write(message) sys.exit(602)
[ "def", "error_engine_path_not_found", "(", "args", ",", "engine_id", ")", ":", "message", "=", "\"CryEngine '{}' has not been registered locally.\\n\"", ".", "format", "(", "engine_id", ")", "if", "not", "args", ".", "silent", "and", "HAS_WIN_MODULES", ":", "MESSAGEBOX", "(", "None", ",", "message", ",", "command_title", "(", "args", ")", ",", "win32con", ".", "MB_OK", "|", "win32con", ".", "MB_ICONERROR", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "message", ")", "sys", ".", "exit", "(", "602", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/cryselect.py#L126-L138
martinrotter/textosaurus
4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8
src/libtextosaurus/3rd-party/scintilla-lt/scripts/Dependencies.py
python
InsertSynonym
(dependencies, current, additional)
return result
Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions.
Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions.
[ "Insert", "a", "copy", "of", "one", "object", "file", "with", "dependencies", "under", "a", "different", "name", ".", "Used", "when", "one", "source", "file", "is", "used", "to", "create", "two", "object", "files", "with", "different", "preprocessor", "definitions", "." ]
def InsertSynonym(dependencies, current, additional): """ Insert a copy of one object file with dependencies under a different name. Used when one source file is used to create two object files with different preprocessor definitions. """ result = [] for dep in dependencies: result.append(dep) if (dep[0] == current): depAdd = [additional, dep[1]] result.append(depAdd) return result
[ "def", "InsertSynonym", "(", "dependencies", ",", "current", ",", "additional", ")", ":", "result", "=", "[", "]", "for", "dep", "in", "dependencies", ":", "result", ".", "append", "(", "dep", ")", "if", "(", "dep", "[", "0", "]", "==", "current", ")", ":", "depAdd", "=", "[", "additional", ",", "dep", "[", "1", "]", "]", "result", ".", "append", "(", "depAdd", ")", "return", "result" ]
https://github.com/martinrotter/textosaurus/blob/4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8/src/libtextosaurus/3rd-party/scintilla-lt/scripts/Dependencies.py#L89-L99
jsupancic/deep_hand_pose
22cbeae1a8410ff5d37c060c7315719d0a5d608f
scripts/cpp_lint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'// dummy'" ]
https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L1143-L1148
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/backend.py
python
moving_average_update
(x, value, momentum)
return moving_averages.assign_moving_average( x, value, momentum, zero_debias=False)
Compute the moving average of a variable. Arguments: x: A Variable. value: A tensor with the same shape as `variable`. momentum: The moving average momentum. Returns: An Operation to update the variable.
Compute the moving average of a variable.
[ "Compute", "the", "moving", "average", "of", "a", "variable", "." ]
def moving_average_update(x, value, momentum): """Compute the moving average of a variable. Arguments: x: A Variable. value: A tensor with the same shape as `variable`. momentum: The moving average momentum. Returns: An Operation to update the variable. """ return moving_averages.assign_moving_average( x, value, momentum, zero_debias=False)
[ "def", "moving_average_update", "(", "x", ",", "value", ",", "momentum", ")", ":", "return", "moving_averages", ".", "assign_moving_average", "(", "x", ",", "value", ",", "momentum", ",", "zero_debias", "=", "False", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1125-L1137
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/sparse/compressed.py
python
_cs_matrix.sort_indices
(self)
Sort the indices of this matrix *in place*
Sort the indices of this matrix *in place*
[ "Sort", "the", "indices", "of", "this", "matrix", "*", "in", "place", "*" ]
def sort_indices(self): """Sort the indices of this matrix *in place* """ if not self.has_sorted_indices: _sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr, self.indices, self.data) self.has_sorted_indices = True
[ "def", "sort_indices", "(", "self", ")", ":", "if", "not", "self", ".", "has_sorted_indices", ":", "_sparsetools", ".", "csr_sort_indices", "(", "len", "(", "self", ".", "indptr", ")", "-", "1", ",", "self", ".", "indptr", ",", "self", ".", "indices", ",", "self", ".", "data", ")", "self", ".", "has_sorted_indices", "=", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/compressed.py#L1069-L1076
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/__init__.py
python
RegeneratableOptionParser.add_option
(self, *args, **kw)
Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth
Add an option to the parser.
[ "Add", "an", "option", "to", "the", "parser", "." ]
def add_option(self, *args, **kw): """Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth """ env_name = kw.pop('env_name', None) if 'dest' in kw and kw.pop('regenerate', True): dest = kw['dest'] # The path type is needed for regenerating, for optparse we can just treat # it as a string. type = kw.get('type') if type == 'path': kw['type'] = 'string' self.__regeneratable_options[dest] = { 'action': kw.get('action'), 'type': type, 'env_name': env_name, 'opt': args[0], } optparse.OptionParser.add_option(self, *args, **kw)
[ "def", "add_option", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "env_name", "=", "kw", ".", "pop", "(", "'env_name'", ",", "None", ")", "if", "'dest'", "in", "kw", "and", "kw", ".", "pop", "(", "'regenerate'", ",", "True", ")", ":", "dest", "=", "kw", "[", "'dest'", "]", "# The path type is needed for regenerating, for optparse we can just treat", "# it as a string.", "type", "=", "kw", ".", "get", "(", "'type'", ")", "if", "type", "==", "'path'", ":", "kw", "[", "'type'", "]", "=", "'string'", "self", ".", "__regeneratable_options", "[", "dest", "]", "=", "{", "'action'", ":", "kw", ".", "get", "(", "'action'", ")", ",", "'type'", ":", "type", ",", "'env_name'", ":", "env_name", ",", "'opt'", ":", "args", "[", "0", "]", ",", "}", "optparse", ".", "OptionParser", ".", "add_option", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/__init__.py#L242-L271
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Font.Smaller
(*args, **kwargs)
return _gdi_.Font_Smaller(*args, **kwargs)
Smaller(self) -> Font
Smaller(self) -> Font
[ "Smaller", "(", "self", ")", "-", ">", "Font" ]
def Smaller(*args, **kwargs): """Smaller(self) -> Font""" return _gdi_.Font_Smaller(*args, **kwargs)
[ "def", "Smaller", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_Smaller", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2488-L2490
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakeOsModule.close
(self, file_des)
Closes a file descriptor. Args: file_des: An integer file descriptor for the file object requested. Raises: OSError: bad file descriptor. TypeError: if file descriptor is not an integer.
Closes a file descriptor.
[ "Closes", "a", "file", "descriptor", "." ]
def close(self, file_des): """Closes a file descriptor. Args: file_des: An integer file descriptor for the file object requested. Raises: OSError: bad file descriptor. TypeError: if file descriptor is not an integer. """ fh = self.filesystem.GetOpenFile(file_des) fh.close()
[ "def", "close", "(", "self", ",", "file_des", ")", ":", "fh", "=", "self", ".", "filesystem", ".", "GetOpenFile", "(", "file_des", ")", "fh", ".", "close", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1259-L1270
s9xie/hed
94fb22f10cbfec8d84fbc0642b224022014b6bd6
scripts/cpp_lint.py
python
FindNextMatchingAngleBracket
(clean_lines, linenum, init_suffix)
return True
Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists.
Find the corresponding > to close a template.
[ "Find", "the", "corresponding", ">", "to", "close", "a", "template", "." ]
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments and other template expressions. match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True
[ "def", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_suffix", ")", ":", "line", "=", "init_suffix", "nesting_stack", "=", "[", "'<'", "]", "while", "True", ":", "# Find the next operator that can tell us whether < is used as an", "# opening bracket or as a less-than operator. We only want to", "# warn on the latter case.", "#", "# We could also check all other operators and terminate the search", "# early, e.g. if we got something like this \"a<b+c\", the \"<\" is", "# most likely a less-than operator, but then we will get false", "# positives for default arguments and other template expressions.", "match", "=", "Search", "(", "r'^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "1", ")", "line", "=", "match", ".", "group", "(", "2", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'<'", ":", "# Expecting closing angle bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'>'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma after a bracket, this is most likely a template", "# argument. We have not seen a closing angle bracket yet, but", "# it's probably a few lines later if we look for it, so just", "# return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting closing parenthesis or closing bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "')'", ",", "']'", ")", ":", "# We don't bother checking for matching () or []. If we got", "# something like (] or [), it would have been a syntax error.", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the next line", "linenum", "+=", "1", "if", "linenum", ">=", "len", "(", "clean_lines", ".", "elided", ")", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all remaining lines and still no matching angle bracket.", "# Most likely the input was incomplete, otherwise we should have", "# seen a semicolon and returned early.", "return", "True" ]
https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L2517-L2583
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/platformsettings.py
python
_LinuxPlatformSettings.setup_temporary_loopback_config
(self)
Setup Linux to temporarily use reasonably sized frames. Linux uses jumbo frames by default (16KB), using the combination of MTU probing and a base MSS makes it use normal sized packets. The reason this works is because tcp_base_mss is only used when MTU probing is enabled. And since we're using the max value, it will always use the reasonable size. This is relevant for server-side realism. The client-side will vary depending on the client TCP stack config.
Setup Linux to temporarily use reasonably sized frames.
[ "Setup", "Linux", "to", "temporarily", "use", "reasonably", "sized", "frames", "." ]
def setup_temporary_loopback_config(self): """Setup Linux to temporarily use reasonably sized frames. Linux uses jumbo frames by default (16KB), using the combination of MTU probing and a base MSS makes it use normal sized packets. The reason this works is because tcp_base_mss is only used when MTU probing is enabled. And since we're using the max value, it will always use the reasonable size. This is relevant for server-side realism. The client-side will vary depending on the client TCP stack config. """ ENABLE_MTU_PROBING = 2 original_probing = self.get_sysctl(self.TCP_MTU_PROBING) self.set_sysctl(self.TCP_MTU_PROBING, ENABLE_MTU_PROBING) atexit.register(self.set_sysctl, self.TCP_MTU_PROBING, original_probing) TCP_FULL_MSS = 1460 original_mss = self.get_sysctl(self.TCP_BASE_MSS) self.set_sysctl(self.TCP_BASE_MSS, TCP_FULL_MSS) atexit.register(self.set_sysctl, self.TCP_BASE_MSS, original_mss)
[ "def", "setup_temporary_loopback_config", "(", "self", ")", ":", "ENABLE_MTU_PROBING", "=", "2", "original_probing", "=", "self", ".", "get_sysctl", "(", "self", ".", "TCP_MTU_PROBING", ")", "self", ".", "set_sysctl", "(", "self", ".", "TCP_MTU_PROBING", ",", "ENABLE_MTU_PROBING", ")", "atexit", ".", "register", "(", "self", ".", "set_sysctl", ",", "self", ".", "TCP_MTU_PROBING", ",", "original_probing", ")", "TCP_FULL_MSS", "=", "1460", "original_mss", "=", "self", ".", "get_sysctl", "(", "self", ".", "TCP_BASE_MSS", ")", "self", ".", "set_sysctl", "(", "self", ".", "TCP_BASE_MSS", ",", "TCP_FULL_MSS", ")", "atexit", ".", "register", "(", "self", ".", "set_sysctl", ",", "self", ".", "TCP_BASE_MSS", ",", "original_mss", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/platformsettings.py#L542-L561
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_clone.py
python
Clone.GetResources
(self)
return {'Pixmap': 'Draft_Clone', 'Accel': "C,L", 'MenuText': QT_TRANSLATE_NOOP("Draft_Clone", "Clone"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Clone", "Creates a clone of the selected objects.\nThe resulting clone can be scaled in each of its three directions.")}
Set icon, menu and tooltip.
Set icon, menu and tooltip.
[ "Set", "icon", "menu", "and", "tooltip", "." ]
def GetResources(self): """Set icon, menu and tooltip.""" return {'Pixmap': 'Draft_Clone', 'Accel': "C,L", 'MenuText': QT_TRANSLATE_NOOP("Draft_Clone", "Clone"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Clone", "Creates a clone of the selected objects.\nThe resulting clone can be scaled in each of its three directions.")}
[ "def", "GetResources", "(", "self", ")", ":", "return", "{", "'Pixmap'", ":", "'Draft_Clone'", ",", "'Accel'", ":", "\"C,L\"", ",", "'MenuText'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Clone\"", ",", "\"Clone\"", ")", ",", "'ToolTip'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Clone\"", ",", "\"Creates a clone of the selected objects.\\nThe resulting clone can be scaled in each of its three directions.\"", ")", "}" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_clone.py#L65-L71
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html2.py
python
WebViewFactory.Create
(*args)
return _html2.WebViewFactory_Create(*args)
Create(self) -> WebView Create(self, Window parent, int id, String url=wxWebViewDefaultURLStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=wxWebViewNameStr) -> WebView
Create(self) -> WebView Create(self, Window parent, int id, String url=wxWebViewDefaultURLStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=wxWebViewNameStr) -> WebView
[ "Create", "(", "self", ")", "-", ">", "WebView", "Create", "(", "self", "Window", "parent", "int", "id", "String", "url", "=", "wxWebViewDefaultURLStr", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "String", "name", "=", "wxWebViewNameStr", ")", "-", ">", "WebView" ]
def Create(*args): """ Create(self) -> WebView Create(self, Window parent, int id, String url=wxWebViewDefaultURLStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=wxWebViewNameStr) -> WebView """ return _html2.WebViewFactory_Create(*args)
[ "def", "Create", "(", "*", "args", ")", ":", "return", "_html2", ".", "WebViewFactory_Create", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html2.py#L114-L121
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/common/walterWidgets/utils.py
python
toPyObject
(obj)
return obj
Call QVariant.toPyObject on the case we are in PyQt.
Call QVariant.toPyObject on the case we are in PyQt.
[ "Call", "QVariant", ".", "toPyObject", "on", "the", "case", "we", "are", "in", "PyQt", "." ]
def toPyObject(obj): """Call QVariant.toPyObject on the case we are in PyQt.""" # QAbstractItemModel.data() returns QVariant in PyQt and a python type in # PySide. The result of this function should be the same for all the Qts. if obj and qtBinding == "PyQt4": return obj.toPyObject() return obj
[ "def", "toPyObject", "(", "obj", ")", ":", "# QAbstractItemModel.data() returns QVariant in PyQt and a python type in", "# PySide. The result of this function should be the same for all the Qts.", "if", "obj", "and", "qtBinding", "==", "\"PyQt4\"", ":", "return", "obj", ".", "toPyObject", "(", ")", "return", "obj" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/utils.py#L21-L28
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/domain.py
python
TensorProductDomain.get_bounding_box
(self)
return copy.copy(self._domain_bounds)
Return a list of ClosedIntervals representing a bounding box for this domain.
Return a list of ClosedIntervals representing a bounding box for this domain.
[ "Return", "a", "list", "of", "ClosedIntervals", "representing", "a", "bounding", "box", "for", "this", "domain", "." ]
def get_bounding_box(self): """Return a list of ClosedIntervals representing a bounding box for this domain.""" return copy.copy(self._domain_bounds)
[ "def", "get_bounding_box", "(", "self", ")", ":", "return", "copy", ".", "copy", "(", "self", ".", "_domain_bounds", ")" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/domain.py#L74-L76
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_CppLintState.AddFilters
(self, filters)
Adds more filters to the existing list of error-message filters.
Adds more filters to the existing list of error-message filters.
[ "Adds", "more", "filters", "to", "the", "existing", "list", "of", "error", "-", "message", "filters", "." ]
def AddFilters(self, filters): """ Adds more filters to the existing list of error-message filters. """ for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "AddFilters", "(", "self", ",", "filters", ")", ":", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "clean_filt", "=", "filt", ".", "strip", "(", ")", "if", "clean_filt", ":", "self", ".", "filters", ".", "append", "(", "clean_filt", ")", "for", "filt", "in", "self", ".", "filters", ":", "if", "not", "(", "filt", ".", "startswith", "(", "'+'", ")", "or", "filt", ".", "startswith", "(", "'-'", ")", ")", ":", "raise", "ValueError", "(", "'Every filter in --filters must start with + or -'", "' (%s does not)'", "%", "filt", ")" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L919-L928