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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
FilePosition.__init__
(self, filename)
Create the position from a file.
Create the position from a file.
[ "Create", "the", "position", "from", "a", "file", "." ]
def __init__(self, filename): "Create the position from a file." Position.__init__(self) self.reader = LineReader(filename) self.pos = 0 self.checkbytemark()
[ "def", "__init__", "(", "self", ",", "filename", ")", ":", "Position", ".", "__init__", "(", "self", ")", "self", ".", "reader", "=", "LineReader", "(", "filename", ")", "self", ".", "pos", "=", "0", "self", ".", "checkbytemark", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2114-L2119
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
toolkit/crashreporter/tools/symbolstore.py
python
Dumper_Mac.ProcessFilesWorkMac
(self, file)
return result
dump_syms on Mac needs to be run on a dSYM bundle produced by dsymutil(1), so run dsymutil here and pass the bundle name down to the superclass method instead.
dump_syms on Mac needs to be run on a dSYM bundle produced by dsymutil(1), so run dsymutil here and pass the bundle name down to the superclass method instead.
[ "dump_syms", "on", "Mac", "needs", "to", "be", "run", "on", "a", "dSYM", "bundle", "produced", "by", "dsymutil", "(", "1", ")", "so", "run", "dsymutil", "here", "and", "pass", "the", "bundle", "name", "down", "to", "the", "superclass", "method", "instead", "." ]
def ProcessFilesWorkMac(self, file): """dump_syms on Mac needs to be run on a dSYM bundle produced by dsymutil(1), so run dsymutil here and pass the bundle name down to the superclass method instead.""" self.output_pid(sys.stderr, "Worker running Mac pre-processing on file: %s" % (file,)) # our return is a status and a tuple of files to dump symbols for # the extra files are fallbacks; as soon as one is dumped successfully, we stop result = { 'status' : False, 'files' : None, 'file_key' : file } dsymbundle = file + ".dSYM" if os.path.exists(dsymbundle): shutil.rmtree(dsymbundle) # dsymutil takes --arch=foo instead of -a foo like everything else subprocess.call(["dsymutil"] + [a.replace('-a ', '--arch=') for a in self.archs if a] + [file], stdout=open("/dev/null","w")) if not os.path.exists(dsymbundle): # dsymutil won't produce a .dSYM for files without symbols self.output_pid(sys.stderr, "No symbols found in file: %s" % (file,)) result['status'] = False result['files'] = (file, ) return result result['status'] = True result['files'] = (dsymbundle, file) return result
[ "def", "ProcessFilesWorkMac", "(", "self", ",", "file", ")", ":", "self", ".", "output_pid", "(", "sys", ".", "stderr", ",", "\"Worker running Mac pre-processing on file: %s\"", "%", "(", "file", ",", ")", ")", "# our return is a status and a tuple of files to dump symbols for", "# the extra files are fallbacks; as soon as one is dumped successfully, we stop", "result", "=", "{", "'status'", ":", "False", ",", "'files'", ":", "None", ",", "'file_key'", ":", "file", "}", "dsymbundle", "=", "file", "+", "\".dSYM\"", "if", "os", ".", "path", ".", "exists", "(", "dsymbundle", ")", ":", "shutil", ".", "rmtree", "(", "dsymbundle", ")", "# dsymutil takes --arch=foo instead of -a foo like everything else", "subprocess", ".", "call", "(", "[", "\"dsymutil\"", "]", "+", "[", "a", ".", "replace", "(", "'-a '", ",", "'--arch='", ")", "for", "a", "in", "self", ".", "archs", "if", "a", "]", "+", "[", "file", "]", ",", "stdout", "=", "open", "(", "\"/dev/null\"", ",", "\"w\"", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dsymbundle", ")", ":", "# dsymutil won't produce a .dSYM for files without symbols", "self", ".", "output_pid", "(", "sys", ".", "stderr", ",", "\"No symbols found in file: %s\"", "%", "(", "file", ",", ")", ")", "result", "[", "'status'", "]", "=", "False", "result", "[", "'files'", "]", "=", "(", "file", ",", ")", "return", "result", "result", "[", "'status'", "]", "=", "True", "result", "[", "'files'", "]", "=", "(", "dsymbundle", ",", "file", ")", "return", "result" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/crashreporter/tools/symbolstore.py#L854-L879
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/utils.py
python
get_output_shape
(auto_pad, input_spatial_shape, kernel_spatial_shape, strides_spatial)
return out_shape
return output shape of conv2d or pooling, ! borrow from onnx Args: auto_pad: string input_spatial_shape: list[int] kernel_spatial_shape: list[int] strides_spatial: list[int] output_spatial_shape: list[int] Returns: list[int
return output shape of conv2d or pooling, ! borrow from onnx Args: auto_pad: string input_spatial_shape: list[int] kernel_spatial_shape: list[int] strides_spatial: list[int] output_spatial_shape: list[int] Returns: list[int
[ "return", "output", "shape", "of", "conv2d", "or", "pooling", "!", "borrow", "from", "onnx", "Args", ":", "auto_pad", ":", "string", "input_spatial_shape", ":", "list", "[", "int", "]", "kernel_spatial_shape", ":", "list", "[", "int", "]", "strides_spatial", ":", "list", "[", "int", "]", "output_spatial_shape", ":", "list", "[", "int", "]", "Returns", ":", "list", "[", "int" ]
def get_output_shape(auto_pad, input_spatial_shape, kernel_spatial_shape, strides_spatial): """ return output shape of conv2d or pooling, ! borrow from onnx Args: auto_pad: string input_spatial_shape: list[int] kernel_spatial_shape: list[int] strides_spatial: list[int] output_spatial_shape: list[int] Returns: list[int """ out_shape = [0] * len(input_spatial_shape) if auto_pad in ('SAME_UPPER', 'SAME_LOWER'): for i in range(len(input_spatial_shape)): out_shape[i] = int( np.ceil( float(input_spatial_shape[i]) / float(strides_spatial[i]))) elif auto_pad == 'VALID': for i in range(len(input_spatial_shape)): out_shape[i] = int( np.ceil( float(input_spatial_shape[i] - (kernel_spatial_shape[i] - 1)) / float(strides_spatial[i]))) return out_shape
[ "def", "get_output_shape", "(", "auto_pad", ",", "input_spatial_shape", ",", "kernel_spatial_shape", ",", "strides_spatial", ")", ":", "out_shape", "=", "[", "0", "]", "*", "len", "(", "input_spatial_shape", ")", "if", "auto_pad", "in", "(", "'SAME_UPPER'", ",", "'SAME_LOWER'", ")", ":", "for", "i", "in", "range", "(", "len", "(", "input_spatial_shape", ")", ")", ":", "out_shape", "[", "i", "]", "=", "int", "(", "np", ".", "ceil", "(", "float", "(", "input_spatial_shape", "[", "i", "]", ")", "/", "float", "(", "strides_spatial", "[", "i", "]", ")", ")", ")", "elif", "auto_pad", "==", "'VALID'", ":", "for", "i", "in", "range", "(", "len", "(", "input_spatial_shape", ")", ")", ":", "out_shape", "[", "i", "]", "=", "int", "(", "np", ".", "ceil", "(", "float", "(", "input_spatial_shape", "[", "i", "]", "-", "(", "kernel_spatial_shape", "[", "i", "]", "-", "1", ")", ")", "/", "float", "(", "strides_spatial", "[", "i", "]", ")", ")", ")", "return", "out_shape" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/utils.py#L189-L216
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/google/protobuf/reflection.py
python
GeneratedProtocolMessageType.__new__
(cls, name, bases, dictionary)
return superclass.__new__(cls, name, bases, dictionary)
Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we're creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. Returns: Newly-allocated class.
Custom allocation for runtime-generated class types.
[ "Custom", "allocation", "for", "runtime", "-", "generated", "class", "types", "." ]
def __new__(cls, name, bases, dictionary): """Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we're creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. Returns: Newly-allocated class. """ descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] _AddSlots(descriptor, dictionary) _AddClassAttributesForNestedExtensions(descriptor, dictionary) superclass = super(GeneratedProtocolMessageType, cls) return superclass.__new__(cls, name, bases, dictionary)
[ "def", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "descriptor", "=", "dictionary", "[", "GeneratedProtocolMessageType", ".", "_DESCRIPTOR_KEY", "]", "_AddSlots", "(", "descriptor", ",", "dictionary", ")", "_AddClassAttributesForNestedExtensions", "(", "descriptor", ",", "dictionary", ")", "superclass", "=", "super", "(", "GeneratedProtocolMessageType", ",", "cls", ")", "return", "superclass", ".", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/reflection.py#L97-L122
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/combo.py
python
ComboCtrl.GetTextRect
(*args, **kwargs)
return _combo.ComboCtrl_GetTextRect(*args, **kwargs)
GetTextRect(self) -> Rect Returns area covered by the text field (includes everything except borders and the dropdown button).
GetTextRect(self) -> Rect
[ "GetTextRect", "(", "self", ")", "-", ">", "Rect" ]
def GetTextRect(*args, **kwargs): """ GetTextRect(self) -> Rect Returns area covered by the text field (includes everything except borders and the dropdown button). """ return _combo.ComboCtrl_GetTextRect(*args, **kwargs)
[ "def", "GetTextRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_GetTextRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/combo.py#L377-L384
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py
python
convert_max
(node, **kwargs)
Map MXNet's max operator attributes to onnx's ReduceMax operator and return the created node.
Map MXNet's max operator attributes to onnx's ReduceMax operator and return the created node.
[ "Map", "MXNet", "s", "max", "operator", "attributes", "to", "onnx", "s", "ReduceMax", "operator", "and", "return", "the", "created", "node", "." ]
def convert_max(node, **kwargs): """Map MXNet's max operator attributes to onnx's ReduceMax operator and return the created node. """ from onnx.helper import make_node name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = str(attrs.get("axis", 'None')) axes = convert_string_to_list(mx_axis) if mx_axis != 'None' else None keepdims = get_boolean_attribute_value(attrs, "keepdims") if axes is not None: if keepdims: node = make_node('ReduceMax', input_nodes, [name], axes=axes, keepdims=keepdims) return [node] else: create_tensor([1], name+'_1', kwargs['initializer']) create_tensor([0], name+'_0', kwargs['initializer']) create_tensor([len(axes)], name+'_axes_dim', kwargs['initializer']) nodes = [ make_node('ReduceMax', input_nodes, [name+'_rmax'], axes=axes, keepdims=keepdims), make_node('Shape', [name+'_rmax'], [name+'_rmax_shape']), make_node('Shape', [name+'_rmax_shape'], [name+'_rmax_dim']), make_node('Shape', [input_nodes[0]], [name+'_in_shape']), make_node('Shape', [name+'_in_shape'], [name+'_in_dim']), make_node('Equal', [name+'_axes_dim', name+'_in_dim'], [name+'_equal']), make_node('Where', [name+'_equal', name+'_1', name+'_rmax_dim'], [name+'_where0']), make_node('Tile', [name+'_0', name+'_where0'], [name+'_tile']), make_node('Unsqueeze', [name+'_0', name+'_0'], [name+'_unsqueeze']), make_node('Where', [name+'_equal', name+'_1', name+'_0'], [name+'_where1']), make_node('ScatterND', [name+'_tile', name+'_unsqueeze', name+'_where1'], [name+'_SND']), make_node('Reshape', [name+'_rmax', name+'_SND'], [name]), ] return nodes else: if keepdims: node = make_node('ReduceMax', input_nodes, [name], keepdims=keepdims) return [node] else: create_tensor([1], name+'_1', kwargs['initializer']) nodes = [ make_node('ReduceMax', input_nodes, [name+'_rmax'], keepdims=keepdims), make_node('Reshape', [name+'_rmax', name+'_1'], [name]) ] return nodes
[ "def", "convert_max", "(", "node", ",", "*", "*", "kwargs", ")", ":", "from", "onnx", ".", "helper", "import", "make_node", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "mx_axis", "=", "str", "(", "attrs", ".", "get", "(", "\"axis\"", ",", "'None'", ")", ")", "axes", "=", "convert_string_to_list", "(", "mx_axis", ")", "if", "mx_axis", "!=", "'None'", "else", "None", "keepdims", "=", "get_boolean_attribute_value", "(", "attrs", ",", "\"keepdims\"", ")", "if", "axes", "is", "not", "None", ":", "if", "keepdims", ":", "node", "=", "make_node", "(", "'ReduceMax'", ",", "input_nodes", ",", "[", "name", "]", ",", "axes", "=", "axes", ",", "keepdims", "=", "keepdims", ")", "return", "[", "node", "]", "else", ":", "create_tensor", "(", "[", "1", "]", ",", "name", "+", "'_1'", ",", "kwargs", "[", "'initializer'", "]", ")", "create_tensor", "(", "[", "0", "]", ",", "name", "+", "'_0'", ",", "kwargs", "[", "'initializer'", "]", ")", "create_tensor", "(", "[", "len", "(", "axes", ")", "]", ",", "name", "+", "'_axes_dim'", ",", "kwargs", "[", "'initializer'", "]", ")", "nodes", "=", "[", "make_node", "(", "'ReduceMax'", ",", "input_nodes", ",", "[", "name", "+", "'_rmax'", "]", ",", "axes", "=", "axes", ",", "keepdims", "=", "keepdims", ")", ",", "make_node", "(", "'Shape'", ",", "[", "name", "+", "'_rmax'", "]", ",", "[", "name", "+", "'_rmax_shape'", "]", ")", ",", "make_node", "(", "'Shape'", ",", "[", "name", "+", "'_rmax_shape'", "]", ",", "[", "name", "+", "'_rmax_dim'", "]", ")", ",", "make_node", "(", "'Shape'", ",", "[", "input_nodes", "[", "0", "]", "]", ",", "[", "name", "+", "'_in_shape'", "]", ")", ",", "make_node", "(", "'Shape'", ",", "[", "name", "+", "'_in_shape'", "]", ",", "[", "name", "+", "'_in_dim'", "]", ")", ",", "make_node", "(", "'Equal'", ",", "[", "name", "+", "'_axes_dim'", ",", "name", "+", "'_in_dim'", "]", ",", "[", "name", "+", "'_equal'", "]", ")", ",", "make_node", "(", "'Where'", ",", "[", "name", "+", "'_equal'", ",", "name", "+", "'_1'", ",", "name", "+", "'_rmax_dim'", "]", ",", "[", "name", "+", "'_where0'", "]", ")", ",", "make_node", "(", "'Tile'", ",", "[", "name", "+", "'_0'", ",", "name", "+", "'_where0'", "]", ",", "[", "name", "+", "'_tile'", "]", ")", ",", "make_node", "(", "'Unsqueeze'", ",", "[", "name", "+", "'_0'", ",", "name", "+", "'_0'", "]", ",", "[", "name", "+", "'_unsqueeze'", "]", ")", ",", "make_node", "(", "'Where'", ",", "[", "name", "+", "'_equal'", ",", "name", "+", "'_1'", ",", "name", "+", "'_0'", "]", ",", "[", "name", "+", "'_where1'", "]", ")", ",", "make_node", "(", "'ScatterND'", ",", "[", "name", "+", "'_tile'", ",", "name", "+", "'_unsqueeze'", ",", "name", "+", "'_where1'", "]", ",", "[", "name", "+", "'_SND'", "]", ")", ",", "make_node", "(", "'Reshape'", ",", "[", "name", "+", "'_rmax'", ",", "name", "+", "'_SND'", "]", ",", "[", "name", "]", ")", ",", "]", "return", "nodes", "else", ":", "if", "keepdims", ":", "node", "=", "make_node", "(", "'ReduceMax'", ",", "input_nodes", ",", "[", "name", "]", ",", "keepdims", "=", "keepdims", ")", "return", "[", "node", "]", "else", ":", "create_tensor", "(", "[", "1", "]", ",", "name", "+", "'_1'", ",", "kwargs", "[", "'initializer'", "]", ")", "nodes", "=", "[", "make_node", "(", "'ReduceMax'", ",", "input_nodes", ",", "[", "name", "+", "'_rmax'", "]", ",", "keepdims", "=", "keepdims", ")", ",", "make_node", "(", "'Reshape'", ",", "[", "name", "+", "'_rmax'", ",", "name", "+", "'_1'", "]", ",", "[", "name", "]", ")", "]", "return", "nodes" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py#L1470-L1515
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM_HANDLE.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM_HANDLE)
Returns new TPM_HANDLE object constructed from its marshaled representation in the given byte buffer
Returns new TPM_HANDLE object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM_HANDLE", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM_HANDLE object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM_HANDLE)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM_HANDLE", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L3455-L3459
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_typesymbol_this
(p)
typesymbol : THIS
typesymbol : THIS
[ "typesymbol", ":", "THIS" ]
def p_typesymbol_this(p): 'typesymbol : THIS' p[0] = This() p[0].lineno = get_lineno(p,1)
[ "def", "p_typesymbol_this", "(", "p", ")", ":", "p", "[", "0", "]", "=", "This", "(", ")", "p", "[", "0", "]", ".", "lineno", "=", "get_lineno", "(", "p", ",", "1", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1313-L1316
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/base.py
python
StringMixin.__bytes__
(self)
return self.__unicode__().encode(encoding, 'replace')
Return a string representation for a particular object. Invoked by bytes(obj) in py3 only. Yields a bytestring in both py2/py3.
Return a string representation for a particular object.
[ "Return", "a", "string", "representation", "for", "a", "particular", "object", "." ]
def __bytes__(self): """ Return a string representation for a particular object. Invoked by bytes(obj) in py3 only. Yields a bytestring in both py2/py3. """ from pandas.core.config import get_option encoding = get_option("display.encoding") return self.__unicode__().encode(encoding, 'replace')
[ "def", "__bytes__", "(", "self", ")", ":", "from", "pandas", ".", "core", ".", "config", "import", "get_option", "encoding", "=", "get_option", "(", "\"display.encoding\"", ")", "return", "self", ".", "__unicode__", "(", ")", ".", "encode", "(", "encoding", ",", "'replace'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/base.py#L60-L70
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/util/set.py
python
equal
(a, b)
return contains (a, b) and contains (b, a)
Returns True iff 'a' contains the same elements as 'b', irrespective of their order. # TODO: Python 2.4 has a proper set class.
Returns True iff 'a' contains the same elements as 'b', irrespective of their order. # TODO: Python 2.4 has a proper set class.
[ "Returns", "True", "iff", "a", "contains", "the", "same", "elements", "as", "b", "irrespective", "of", "their", "order", ".", "#", "TODO", ":", "Python", "2", ".", "4", "has", "a", "proper", "set", "class", "." ]
def equal (a, b): """ Returns True iff 'a' contains the same elements as 'b', irrespective of their order. # TODO: Python 2.4 has a proper set class. """ return contains (a, b) and contains (b, a)
[ "def", "equal", "(", "a", ",", "b", ")", ":", "return", "contains", "(", "a", ",", "b", ")", "and", "contains", "(", "b", ",", "a", ")" ]
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/util/set.py#L38-L42
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
array/min_max_arr.py
python
getminmax_linear_search
(arr)
return min_num, max_num
Linear method Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly
Linear method Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly
[ "Linear", "method", "Initialize", "values", "of", "min", "and", "max", "as", "minimum", "and", "maximum", "of", "the", "first", "two", "elements", "respectively", ".", "Starting", "from", "3rd", "compare", "each", "element", "with", "max", "and", "min", "and", "change", "max", "and", "min", "accordingly" ]
def getminmax_linear_search(arr): """ Linear method Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly """ if len(arr) == 0: return None, None if len(arr) == 1: return arr[0], arr[0] min_num = None max_num = None if arr[0] > arr[1]: max_num = arr[0] min_num = arr[1] else: max_num = arr[1] min_num = arr[0] for idx in range(2, len(arr)): if min_num > arr[idx]: min_num = arr[idx] if max_num < arr[idx]: max_num = arr[idx] return min_num, max_num
[ "def", "getminmax_linear_search", "(", "arr", ")", ":", "if", "len", "(", "arr", ")", "==", "0", ":", "return", "None", ",", "None", "if", "len", "(", "arr", ")", "==", "1", ":", "return", "arr", "[", "0", "]", ",", "arr", "[", "0", "]", "min_num", "=", "None", "max_num", "=", "None", "if", "arr", "[", "0", "]", ">", "arr", "[", "1", "]", ":", "max_num", "=", "arr", "[", "0", "]", "min_num", "=", "arr", "[", "1", "]", "else", ":", "max_num", "=", "arr", "[", "1", "]", "min_num", "=", "arr", "[", "0", "]", "for", "idx", "in", "range", "(", "2", ",", "len", "(", "arr", ")", ")", ":", "if", "min_num", ">", "arr", "[", "idx", "]", ":", "min_num", "=", "arr", "[", "idx", "]", "if", "max_num", "<", "arr", "[", "idx", "]", ":", "max_num", "=", "arr", "[", "idx", "]", "return", "min_num", ",", "max_num" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/array/min_max_arr.py#L8-L35
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_options_view.py
python
GeneralFittingOptionsView.simultaneous_fit_by_specifier
(self)
return self.simul_fit_by_specifier.currentText()
Returns the run, group or pair name.
Returns the run, group or pair name.
[ "Returns", "the", "run", "group", "or", "pair", "name", "." ]
def simultaneous_fit_by_specifier(self) -> str: """Returns the run, group or pair name.""" return self.simul_fit_by_specifier.currentText()
[ "def", "simultaneous_fit_by_specifier", "(", "self", ")", "->", "str", ":", "return", "self", ".", "simul_fit_by_specifier", ".", "currentText", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_options_view.py#L62-L64
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/thewb/thewb_api.py
python
Videos.getSeasonEpisode
(self, title)
return s_e
Check is there is any season or episode number information in an item's title return array of season and/or episode numbers plus any duration in minutes and seconds return array with None values
Check is there is any season or episode number information in an item's title return array of season and/or episode numbers plus any duration in minutes and seconds return array with None values
[ "Check", "is", "there", "is", "any", "season", "or", "episode", "number", "information", "in", "an", "item", "s", "title", "return", "array", "of", "season", "and", "/", "or", "episode", "numbers", "plus", "any", "duration", "in", "minutes", "and", "seconds", "return", "array", "with", "None", "values" ]
def getSeasonEpisode(self, title): ''' Check is there is any season or episode number information in an item's title return array of season and/or episode numbers plus any duration in minutes and seconds return array with None values ''' s_e = [] for index in range(len(self.s_e_Patterns)): match = self.s_e_Patterns[index].match(title) if not match: continue return match.groups() return s_e
[ "def", "getSeasonEpisode", "(", "self", ",", "title", ")", ":", "s_e", "=", "[", "]", "for", "index", "in", "range", "(", "len", "(", "self", ".", "s_e_Patterns", ")", ")", ":", "match", "=", "self", ".", "s_e_Patterns", "[", "index", "]", ".", "match", "(", "title", ")", "if", "not", "match", ":", "continue", "return", "match", ".", "groups", "(", ")", "return", "s_e" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/thewb/thewb_api.py#L205-L216
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py
python
Location.offset
(self, s, start, end)
return Location(self.path, line, column)
Returns a new location offset by the specified string.
Returns a new location offset by the specified string.
[ "Returns", "a", "new", "location", "offset", "by", "the", "specified", "string", "." ]
def offset(self, s, start, end): """ Returns a new location offset by the specified string. """ if start == end: return self skiplines = s.count('\n', start, end) line = self.line + skiplines if skiplines: lastnl = s.rfind('\n', start, end) assert lastnl != -1 start = lastnl + 1 column = 0 else: column = self.column while True: j = s.find('\t', start, end) if j == -1: column += end - start break column += j - start column += _tabwidth column -= column % _tabwidth start = j + 1 return Location(self.path, line, column)
[ "def", "offset", "(", "self", ",", "s", ",", "start", ",", "end", ")", ":", "if", "start", "==", "end", ":", "return", "self", "skiplines", "=", "s", ".", "count", "(", "'\\n'", ",", "start", ",", "end", ")", "line", "=", "self", ".", "line", "+", "skiplines", "if", "skiplines", ":", "lastnl", "=", "s", ".", "rfind", "(", "'\\n'", ",", "start", ",", "end", ")", "assert", "lastnl", "!=", "-", "1", "start", "=", "lastnl", "+", "1", "column", "=", "0", "else", ":", "column", "=", "self", ".", "column", "while", "True", ":", "j", "=", "s", ".", "find", "(", "'\\t'", ",", "start", ",", "end", ")", "if", "j", "==", "-", "1", ":", "column", "+=", "end", "-", "start", "break", "column", "+=", "j", "-", "start", "column", "+=", "_tabwidth", "column", "-=", "column", "%", "_tabwidth", "start", "=", "j", "+", "1", "return", "Location", "(", "self", ".", "path", ",", "line", ",", "column", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py#L24-L54
p4lang/PI
38d87e81253feff9fff0660d662c885be78fb719
tools/cpplint.py
python
CheckForNonStandardConstructs
(filename, clean_lines, linenum, nesting_state, error)
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
[ "r", "Logs", "an", "error", "if", "we", "see", "certain", "non", "-", "ANSI", "constructs", "ignored", "by", "gcc", "-", "2", "." ]
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage-class specifier (static, extern, typedef, etc) should be ' 'at the beginning of the declaration.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. explicit_constructor_match = Match( r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?' r'(?:(?:inline|constexpr)\s+)*%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 variadic_args = [arg for arg in constructor_args if '&&...' in arg] defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1) or # variadic arguments with zero or one argument (len(constructor_args) <= 2 and len(variadic_args) >= 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'((const\s+(volatile\s+)?)?|(volatile\s+(const\s+)?))?' r'%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args or variadic_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.')
[ "def", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Remove comments from the line, but leave in strings for now.", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "if", "Search", "(", "r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf_format'", ",", "3", ",", "'%q in format strings is deprecated. Use %ll instead.'", ")", "if", "Search", "(", "r'printf\\s*\\(.*\".*%\\d+\\$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf_format'", ",", "2", ",", "'%N$ formats are unconventional. Try rewriting to avoid them.'", ")", "# Remove escaped backslashes before looking for undefined escapes.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "Search", "(", "r'(\"|\\').*\\\\(%|\\[|\\(|{)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/printf_format'", ",", "3", ",", "'%, [, (, and { are undefined character escapes. Unescape them.'", ")", "# For the rest, work with both comments and strings removed.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\b(const|volatile|void|char|short|int|long'", "r'|float|double|signed|unsigned'", "r'|schar|u?int8|u?int16|u?int32|u?int64)'", "r'\\s+(register|static|extern|typedef)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/storage_class'", ",", "5", ",", "'Storage-class specifier (static, extern, typedef, etc) should be '", "'at the beginning of the declaration.'", ")", "if", "Match", "(", "r'\\s*#\\s*endif\\s*[^/\\s]+'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/endif_comment'", ",", "5", ",", "'Uncommented text after #endif is non-standard. Use a comment.'", ")", "if", "Match", "(", "r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/forward_decl'", ",", "5", ",", "'Inner-style forward declarations are invalid. Remove this line.'", ")", "if", "Search", "(", "r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/deprecated'", ",", "3", ",", "'>? and <? (max and min) operators are non-standard and deprecated.'", ")", "if", "Search", "(", "r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'", ",", "line", ")", ":", "# TODO(unknown): Could it be expanded safely to arbitrary references,", "# without triggering too many false positives? The first", "# attempt triggered 5 warnings for mostly benign code in the regtest, hence", "# the restriction.", "# Here's the original regexp, for the reference:", "# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'", "# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'", "error", "(", "filename", ",", "linenum", ",", "'runtime/member_string_references'", ",", "2", ",", "'const string& members are dangerous. It is much better to use '", "'alternatives, such as pointers or simple constants.'", ")", "# Everything else in this function operates on class declarations.", "# Return early if the top of the nesting stack is not a class, or if", "# the class head is not completed yet.", "classinfo", "=", "nesting_state", ".", "InnermostClass", "(", ")", "if", "not", "classinfo", "or", "not", "classinfo", ".", "seen_open_brace", ":", "return", "# The class may have been declared with namespace or classname qualifiers.", "# The constructor and destructor will not have those qualifiers.", "base_classname", "=", "classinfo", ".", "name", ".", "split", "(", "'::'", ")", "[", "-", "1", "]", "# Look for single-argument constructors that aren't marked explicit.", "# Technically a valid construct, but against style.", "explicit_constructor_match", "=", "Match", "(", "r'\\s+(?:(?:inline|constexpr)\\s+)*(explicit\\s+)?'", "r'(?:(?:inline|constexpr)\\s+)*%s\\s*'", "r'\\(((?:[^()]|\\([^()]*\\))*)\\)'", "%", "re", ".", "escape", "(", "base_classname", ")", ",", "line", ")", "if", "explicit_constructor_match", ":", "is_marked_explicit", "=", "explicit_constructor_match", ".", "group", "(", "1", ")", "if", "not", "explicit_constructor_match", ".", "group", "(", "2", ")", ":", "constructor_args", "=", "[", "]", "else", ":", "constructor_args", "=", "explicit_constructor_match", ".", "group", "(", "2", ")", ".", "split", "(", "','", ")", "# collapse arguments so that commas in template parameter lists and function", "# argument parameter lists don't split arguments in two", "i", "=", "0", "while", "i", "<", "len", "(", "constructor_args", ")", ":", "constructor_arg", "=", "constructor_args", "[", "i", "]", "while", "(", "constructor_arg", ".", "count", "(", "'<'", ")", ">", "constructor_arg", ".", "count", "(", "'>'", ")", "or", "constructor_arg", ".", "count", "(", "'('", ")", ">", "constructor_arg", ".", "count", "(", "')'", ")", ")", ":", "constructor_arg", "+=", "','", "+", "constructor_args", "[", "i", "+", "1", "]", "del", "constructor_args", "[", "i", "+", "1", "]", "constructor_args", "[", "i", "]", "=", "constructor_arg", "i", "+=", "1", "variadic_args", "=", "[", "arg", "for", "arg", "in", "constructor_args", "if", "'&&...'", "in", "arg", "]", "defaulted_args", "=", "[", "arg", "for", "arg", "in", "constructor_args", "if", "'='", "in", "arg", "]", "noarg_constructor", "=", "(", "not", "constructor_args", "or", "# empty arg list", "# 'void' arg specifier", "(", "len", "(", "constructor_args", ")", "==", "1", "and", "constructor_args", "[", "0", "]", ".", "strip", "(", ")", "==", "'void'", ")", ")", "onearg_constructor", "=", "(", "(", "len", "(", "constructor_args", ")", "==", "1", "and", "# exactly one arg", "not", "noarg_constructor", ")", "or", "# all but at most one arg defaulted", "(", "len", "(", "constructor_args", ")", ">=", "1", "and", "not", "noarg_constructor", "and", "len", "(", "defaulted_args", ")", ">=", "len", "(", "constructor_args", ")", "-", "1", ")", "or", "# variadic arguments with zero or one argument", "(", "len", "(", "constructor_args", ")", "<=", "2", "and", "len", "(", "variadic_args", ")", ">=", "1", ")", ")", "initializer_list_constructor", "=", "bool", "(", "onearg_constructor", "and", "Search", "(", "r'\\bstd\\s*::\\s*initializer_list\\b'", ",", "constructor_args", "[", "0", "]", ")", ")", "copy_constructor", "=", "bool", "(", "onearg_constructor", "and", "Match", "(", "r'((const\\s+(volatile\\s+)?)?|(volatile\\s+(const\\s+)?))?'", "r'%s(\\s*<[^>]*>)?(\\s+const)?\\s*(?:<\\w+>\\s*)?&'", "%", "re", ".", "escape", "(", "base_classname", ")", ",", "constructor_args", "[", "0", "]", ".", "strip", "(", ")", ")", ")", "if", "(", "not", "is_marked_explicit", "and", "onearg_constructor", "and", "not", "initializer_list_constructor", "and", "not", "copy_constructor", ")", ":", "if", "defaulted_args", "or", "variadic_args", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/explicit'", ",", "5", ",", "'Constructors callable with one argument '", "'should be marked explicit.'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/explicit'", ",", "5", ",", "'Single-parameter constructors should be marked explicit.'", ")", "elif", "is_marked_explicit", "and", "not", "onearg_constructor", ":", "if", "noarg_constructor", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/explicit'", ",", "5", ",", "'Zero-parameter constructors should not be marked explicit.'", ")" ]
https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/tools/cpplint.py#L3271-L3433
dartsim/dart
495c82120c836005f2d136d4a50c8cc997fb879b
tools/cpplint.py
python
GetHeaderGuardCPPVariable
(filename)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file.
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "." ]
def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
[ "def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "# Restores original filename in case that cpplint is invoked from Emacs's", "# flymake.", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "filename", "=", "re", ".", "sub", "(", "r'/\\.flymake/([^/]*)$'", ",", "r'/\\1'", ",", "filename", ")", "fileinfo", "=", "FileInfo", "(", "filename", ")", "file_path_from_root", "=", "fileinfo", ".", "RepositoryName", "(", ")", "if", "_root", ":", "file_path_from_root", "=", "re", ".", "sub", "(", "'^'", "+", "_root", "+", "os", ".", "sep", ",", "''", ",", "file_path_from_root", ")", "return", "re", ".", "sub", "(", "r'[-./\\s]'", ",", "'_'", ",", "file_path_from_root", ")", ".", "upper", "(", ")", "+", "'_'" ]
https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L1362-L1383
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mock-1.0.0/mock.py
python
NonCallableMagicMock.mock_add_spec
(self, spec, spec_set=False)
Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.
Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock.
[ "Add", "a", "spec", "to", "a", "mock", ".", "spec", "can", "either", "be", "an", "object", "or", "a", "list", "of", "strings", ".", "Only", "attributes", "on", "the", "spec", "can", "be", "fetched", "as", "attributes", "from", "the", "mock", "." ]
def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics()
[ "def", "mock_add_spec", "(", "self", ",", "spec", ",", "spec_set", "=", "False", ")", ":", "self", ".", "_mock_add_spec", "(", "spec", ",", "spec_set", ")", "self", ".", "_mock_set_magics", "(", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mock-1.0.0/mock.py#L1868-L1875
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/framebuffer.py
python
Framebuffer.size
(self)
return self._size
tuple: The size of the framebuffer. Framebuffers created by a window will only report its initial size. It's better get size information from the window itself.
tuple: The size of the framebuffer.
[ "tuple", ":", "The", "size", "of", "the", "framebuffer", "." ]
def size(self) -> tuple: ''' tuple: The size of the framebuffer. Framebuffers created by a window will only report its initial size. It's better get size information from the window itself. ''' return self._size
[ "def", "size", "(", "self", ")", "->", "tuple", ":", "return", "self", ".", "_size" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/framebuffer.py#L177-L185
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/cmake.py
python
NormjoinPathForceCMakeSource
(base_path, rel_path)
return os.path.join('${CMAKE_CURRENT_LIST_DIR}', os.path.normpath(os.path.join(base_path, rel_path)))
Resolves rel_path against base_path and returns the result. If rel_path is an absolute path it is returned unchanged. Otherwise it is resolved against base_path and normalized. If the result is a relative path, it is forced to be relative to the CMakeLists.txt.
Resolves rel_path against base_path and returns the result.
[ "Resolves", "rel_path", "against", "base_path", "and", "returns", "the", "result", "." ]
def NormjoinPathForceCMakeSource(base_path, rel_path): """Resolves rel_path against base_path and returns the result. If rel_path is an absolute path it is returned unchanged. Otherwise it is resolved against base_path and normalized. If the result is a relative path, it is forced to be relative to the CMakeLists.txt. """ if os.path.isabs(rel_path): return rel_path if any([rel_path.startswith(var) for var in FULL_PATH_VARS]): return rel_path # TODO: do we need to check base_path for absolute variables as well? return os.path.join('${CMAKE_CURRENT_LIST_DIR}', os.path.normpath(os.path.join(base_path, rel_path)))
[ "def", "NormjoinPathForceCMakeSource", "(", "base_path", ",", "rel_path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "rel_path", ")", ":", "return", "rel_path", "if", "any", "(", "[", "rel_path", ".", "startswith", "(", "var", ")", "for", "var", "in", "FULL_PATH_VARS", "]", ")", ":", "return", "rel_path", "# TODO: do we need to check base_path for absolute variables as well?", "return", "os", ".", "path", ".", "join", "(", "'${CMAKE_CURRENT_LIST_DIR}'", ",", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "base_path", ",", "rel_path", ")", ")", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/cmake.py#L94-L108
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
python
error
(msg, *args, **kwargs)
Log a message with severity 'ERROR' on the root logger.
Log a message with severity 'ERROR' on the root logger.
[ "Log", "a", "message", "with", "severity", "ERROR", "on", "the", "root", "logger", "." ]
def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs)
[ "def", "error", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "root", ".", "handlers", ")", "==", "0", ":", "basicConfig", "(", ")", "root", ".", "error", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L1579-L1585
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/tcpserver.py
python
TCPServer.add_sockets
(self, sockets: Iterable[socket.socket])
Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server.
Makes this server start accepting connections on the given sockets.
[ "Makes", "this", "server", "start", "accepting", "connections", "on", "the", "given", "sockets", "." ]
def add_sockets(self, sockets: Iterable[socket.socket]) -> None: """Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server. """ for sock in sockets: self._sockets[sock.fileno()] = sock self._handlers[sock.fileno()] = add_accept_handler( sock, self._handle_connection )
[ "def", "add_sockets", "(", "self", ",", "sockets", ":", "Iterable", "[", "socket", ".", "socket", "]", ")", "->", "None", ":", "for", "sock", "in", "sockets", ":", "self", ".", "_sockets", "[", "sock", ".", "fileno", "(", ")", "]", "=", "sock", "self", ".", "_handlers", "[", "sock", ".", "fileno", "(", ")", "]", "=", "add_accept_handler", "(", "sock", ",", "self", ".", "_handle_connection", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/tcpserver.py#L154-L167
9miao/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
SourceLocation.offset
(self)
return self._get_instantiation()[3]
Get the file offset represented by this source location.
Get the file offset represented by this source location.
[ "Get", "the", "file", "offset", "represented", "by", "this", "source", "location", "." ]
def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3]
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "3", "]" ]
https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L213-L215
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/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/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py#L824-L868
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/parameter.py
python
Parameter.initialize
(self, init=None, device=None, default_init=initializer.Uniform(), force_reinit=False)
Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrides :py:meth:`Parameter.init` and default_init. device : Device or list of Device, default :py:meth:`device.current_device()`. Assign Parameter to given device. If device is a list of Device, a copy will be made for each device. .. note:: Copies are independent arrays. User is responsible for keeping their values consistent when updating. Normally :py:class:`gluon.Trainer` does this for you. default_init : Initializer Default initializer is used when both :py:func:`init` and :py:meth:`Parameter.init` are ``None``. force_reinit : bool, default False Whether to force re-initialization if parameter is already initialized. Examples -------- >>> weight = mx.gluon.Parameter('weight', shape=(2, 2)) >>> weight.initialize(device=mx.cpu(0)) >>> weight.data() [[-0.01068833 0.01729892] [ 0.02042518 -0.01618656]] <NDArray 2x2 @cpu(0)> >>> weight.grad() [[ 0. 0.] [ 0. 0.]] <NDArray 2x2 @cpu(0)> >>> weight.initialize(device=[mx.gpu(0), mx.gpu(1)]) >>> weight.data(mx.gpu(0)) [[-0.00873779 -0.02834515] [ 0.05484822 -0.06206018]] <NDArray 2x2 @gpu(0)> >>> weight.data(mx.gpu(1)) [[-0.00873779 -0.02834515] [ 0.05484822 -0.06206018]] <NDArray 2x2 @gpu(1)>
Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API.
[ "Initializes", "parameter", "and", "gradient", "arrays", ".", "Only", "used", "for", ":", "py", ":", "class", ":", "NDArray", "API", "." ]
def initialize(self, init=None, device=None, default_init=initializer.Uniform(), force_reinit=False): """Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrides :py:meth:`Parameter.init` and default_init. device : Device or list of Device, default :py:meth:`device.current_device()`. Assign Parameter to given device. If device is a list of Device, a copy will be made for each device. .. note:: Copies are independent arrays. User is responsible for keeping their values consistent when updating. Normally :py:class:`gluon.Trainer` does this for you. default_init : Initializer Default initializer is used when both :py:func:`init` and :py:meth:`Parameter.init` are ``None``. force_reinit : bool, default False Whether to force re-initialization if parameter is already initialized. Examples -------- >>> weight = mx.gluon.Parameter('weight', shape=(2, 2)) >>> weight.initialize(device=mx.cpu(0)) >>> weight.data() [[-0.01068833 0.01729892] [ 0.02042518 -0.01618656]] <NDArray 2x2 @cpu(0)> >>> weight.grad() [[ 0. 0.] [ 0. 0.]] <NDArray 2x2 @cpu(0)> >>> weight.initialize(device=[mx.gpu(0), mx.gpu(1)]) >>> weight.data(mx.gpu(0)) [[-0.00873779 -0.02834515] [ 0.05484822 -0.06206018]] <NDArray 2x2 @gpu(0)> >>> weight.data(mx.gpu(1)) [[-0.00873779 -0.02834515] [ 0.05484822 -0.06206018]] <NDArray 2x2 @gpu(1)> """ if self._data is not None and not force_reinit: warnings.warn("Parameter '%s' is already initialized, ignoring. " \ "Set force_reinit=True to re-initialize."%self.name, stacklevel=2) return self._data = self._grad = None if device is None: device = [_device.current_device()] if isinstance(device, Device): device = [device] if isinstance(self.init, initializer.RNNFused): self.init.set_initializer(init if init else default_init) init = default_init = self.init if init is None: init = default_init if self.init is None else self.init if not shape_is_known(self.shape): if self._allow_deferred_init: self._deferred_init = (init, device, default_init, None) return raise ValueError("Cannot initialize Parameter '%s' because it has " \ "invalid shape: %s."%(self.name, str(self.shape))) self._deferred_init = (init, device, default_init, None) self._finish_deferred_init()
[ "def", "initialize", "(", "self", ",", "init", "=", "None", ",", "device", "=", "None", ",", "default_init", "=", "initializer", ".", "Uniform", "(", ")", ",", "force_reinit", "=", "False", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and", "not", "force_reinit", ":", "warnings", ".", "warn", "(", "\"Parameter '%s' is already initialized, ignoring. \"", "\"Set force_reinit=True to re-initialize.\"", "%", "self", ".", "name", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "_data", "=", "self", ".", "_grad", "=", "None", "if", "device", "is", "None", ":", "device", "=", "[", "_device", ".", "current_device", "(", ")", "]", "if", "isinstance", "(", "device", ",", "Device", ")", ":", "device", "=", "[", "device", "]", "if", "isinstance", "(", "self", ".", "init", ",", "initializer", ".", "RNNFused", ")", ":", "self", ".", "init", ".", "set_initializer", "(", "init", "if", "init", "else", "default_init", ")", "init", "=", "default_init", "=", "self", ".", "init", "if", "init", "is", "None", ":", "init", "=", "default_init", "if", "self", ".", "init", "is", "None", "else", "self", ".", "init", "if", "not", "shape_is_known", "(", "self", ".", "shape", ")", ":", "if", "self", ".", "_allow_deferred_init", ":", "self", ".", "_deferred_init", "=", "(", "init", ",", "device", ",", "default_init", ",", "None", ")", "return", "raise", "ValueError", "(", "\"Cannot initialize Parameter '%s' because it has \"", "\"invalid shape: %s.\"", "%", "(", "self", ".", "name", ",", "str", "(", "self", ".", "shape", ")", ")", ")", "self", ".", "_deferred_init", "=", "(", "init", ",", "device", ",", "default_init", ",", "None", ")", "self", ".", "_finish_deferred_init", "(", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/parameter.py#L425-L492
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1271-L1285
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/_string_helpers.py
python
english_lower
(s)
return lowered
Apply English case rules to convert ASCII strings to all lower case. This is an internal utility function to replace calls to str.lower() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale. Parameters ---------- s : str Returns ------- lowered : str Examples -------- >>> from numpy.core.numerictypes import english_lower >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_' >>> english_lower('') ''
Apply English case rules to convert ASCII strings to all lower case.
[ "Apply", "English", "case", "rules", "to", "convert", "ASCII", "strings", "to", "all", "lower", "case", "." ]
def english_lower(s): """ Apply English case rules to convert ASCII strings to all lower case. This is an internal utility function to replace calls to str.lower() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale. Parameters ---------- s : str Returns ------- lowered : str Examples -------- >>> from numpy.core.numerictypes import english_lower >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_' >>> english_lower('') '' """ lowered = s.translate(LOWER_TABLE) return lowered
[ "def", "english_lower", "(", "s", ")", ":", "lowered", "=", "s", ".", "translate", "(", "LOWER_TABLE", ")", "return", "lowered" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/_string_helpers.py#L16-L41
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py
python
tril
(m, k=0)
return where(mask, m, zeros(1, m.dtype))
Lower triangle of an array. Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- m : array_like, shape (M, N) Input array. k : int, optional Diagonal above which to zero elements. `k = 0` (the default) is the main diagonal, `k < 0` is below it and `k > 0` is above. Returns ------- tril : ndarray, shape (M, N) Lower triangle of `m`, of same shape and data-type as `m`. See Also -------- triu : same thing, only for the upper triangle Examples -------- >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 0, 0, 0], [ 4, 0, 0], [ 7, 8, 0], [10, 11, 12]])
Lower triangle of an array.
[ "Lower", "triangle", "of", "an", "array", "." ]
def tril(m, k=0): """ Lower triangle of an array. Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- m : array_like, shape (M, N) Input array. k : int, optional Diagonal above which to zero elements. `k = 0` (the default) is the main diagonal, `k < 0` is below it and `k > 0` is above. Returns ------- tril : ndarray, shape (M, N) Lower triangle of `m`, of same shape and data-type as `m`. See Also -------- triu : same thing, only for the upper triangle Examples -------- >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 0, 0, 0], [ 4, 0, 0], [ 7, 8, 0], [10, 11, 12]]) """ m = asanyarray(m) mask = tri(*m.shape[-2:], k=k, dtype=bool) return where(mask, m, zeros(1, m.dtype))
[ "def", "tril", "(", "m", ",", "k", "=", "0", ")", ":", "m", "=", "asanyarray", "(", "m", ")", "mask", "=", "tri", "(", "*", "m", ".", "shape", "[", "-", "2", ":", "]", ",", "k", "=", "k", ",", "dtype", "=", "bool", ")", "return", "where", "(", "mask", ",", "m", ",", "zeros", "(", "1", ",", "m", ".", "dtype", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py#L403-L438
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
StaticBox.Create
(*args, **kwargs)
return _controls_.StaticBox_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBoxNameStr) -> bool
Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBoxNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "label", "=", "EmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "String", "name", "=", "StaticBoxNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBoxNameStr) -> bool """ return _controls_.StaticBox_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "StaticBox_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L849-L855
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/bindings/scripts/v8_interface.py
python
resolution_tests_methods
(effective_overloads)
Yields resolution test and associated method, in resolution order, for effective overloads of a given length. This is the heart of the resolution algorithm. http://heycam.github.io/webidl/#dfn-overload-resolution-algorithm Note that a given method can be listed multiple times, with different tests! This is to handle implicit type conversion. Returns: [(test, method)]
Yields resolution test and associated method, in resolution order, for effective overloads of a given length.
[ "Yields", "resolution", "test", "and", "associated", "method", "in", "resolution", "order", "for", "effective", "overloads", "of", "a", "given", "length", "." ]
def resolution_tests_methods(effective_overloads): """Yields resolution test and associated method, in resolution order, for effective overloads of a given length. This is the heart of the resolution algorithm. http://heycam.github.io/webidl/#dfn-overload-resolution-algorithm Note that a given method can be listed multiple times, with different tests! This is to handle implicit type conversion. Returns: [(test, method)] """ methods = [effective_overload[0] for effective_overload in effective_overloads] if len(methods) == 1: # If only one method with a given length, no test needed yield 'true', methods[0] return # 6. If there is more than one entry in S, then set d to be the # distinguishing argument index for the entries of S. index = distinguishing_argument_index(effective_overloads) # (7-9 are for handling |undefined| values for optional arguments before # the distinguishing argument (as “missing”), so you can specify only some # optional arguments. We don’t support this, so we skip these steps.) # 10. If i = d, then: # (d is the distinguishing argument index) # 1. Let V be argi. # Note: This is the argument that will be used to resolve which # overload is selected. cpp_value = 'info[%s]' % index # Extract argument and IDL type to simplify accessing these in each loop. arguments = [method['arguments'][index] for method in methods] arguments_methods = zip(arguments, methods) idl_types = [argument['idl_type_object'] for argument in arguments] idl_types_methods = zip(idl_types, methods) # We can’t do a single loop through all methods or simply sort them, because # a method may be listed in multiple steps of the resolution algorithm, and # which test to apply differs depending on the step. # # Instead, we need to go through all methods at each step, either finding # first match (if only one test is allowed) or filtering to matches (if # multiple tests are allowed), and generating an appropriate tests. # 2. If V is undefined, and there is an entry in S whose list of # optionality values has “optional” at index i, then remove from S all # other entries. try: method = next(method for argument, method in arguments_methods if argument['is_optional']) test = '%s->IsUndefined()' % cpp_value yield test, method except StopIteration: pass # 3. Otherwise: if V is null or undefined, and there is an entry in S that # has one of the following types at position i of its type list, # • a nullable type try: method = next(method for idl_type, method in idl_types_methods if idl_type.is_nullable) test = 'isUndefinedOrNull(%s)' % cpp_value yield test, method except StopIteration: pass # 4. Otherwise: if V is a platform object – but not a platform array # object – and there is an entry in S that has one of the following # types at position i of its type list, # • an interface type that V implements # (Unlike most of these tests, this can return multiple methods, since we # test if it implements an interface. Thus we need a for loop, not a next.) # (We distinguish wrapper types from built-in interface types.) for idl_type, method in ((idl_type, method) for idl_type, method in idl_types_methods if idl_type.is_wrapper_type): test = 'V8{idl_type}::hasInstance({cpp_value}, info.GetIsolate())'.format(idl_type=idl_type.base_type, cpp_value=cpp_value) yield test, method # 13. Otherwise: if IsCallable(V) is true, and there is an entry in S that # has one of the following types at position i of its type list, # • a callback function type # ... # # FIXME: # We test for functions rather than callability, which isn't strictly the # same thing. try: method = next(method for idl_type, method in idl_types_methods if idl_type.is_callback_function) test = '%s->IsFunction()' % cpp_value yield test, method except StopIteration: pass # 14. Otherwise: if V is any kind of object except for a native Date object, # a native RegExp object, and there is an entry in S that has one of the # following types at position i of its type list, # • a sequence type # ... # # 15. Otherwise: if V is any kind of object except for a native Date object, # a native RegExp object, and there is an entry in S that has one of the # following types at position i of its type list, # • an array type # ... # • a dictionary # # FIXME: # We don't strictly follow the algorithm here. The algorithm says "remove # all other entries" if there is "one entry" matching, but we yield all # entries to support following constructors: # [constructor(sequence<DOMString> arg), constructor(Dictionary arg)] # interface I { ... } # (Need to check array types before objects because an array is an object) for idl_type, method in idl_types_methods: if idl_type.native_array_element_type: # (We test for Array instead of generic Object to type-check.) # FIXME: test for Object during resolution, then have type check for # Array in overloaded method: http://crbug.com/262383 yield '%s->IsArray()' % cpp_value, method for idl_type, method in idl_types_methods: if idl_type.is_dictionary or idl_type.name == 'Dictionary': # FIXME: should be '{1}->IsObject() && !{1}->IsDate() && !{1}->IsRegExp()'.format(cpp_value) # FIXME: the IsDate and IsRegExp checks can be skipped if we've # already generated tests for them. yield '%s->IsObject()' % cpp_value, method # (Check for exact type matches before performing automatic type conversion; # only needed if distinguishing between primitive types.) if len([idl_type.is_primitive_type for idl_type in idl_types]) > 1: # (Only needed if match in step 11, otherwise redundant.) if any(idl_type.is_string_type or idl_type.is_enum for idl_type in idl_types): # 10. Otherwise: if V is a Number value, and there is an entry in S # that has one of the following types at position i of its type # list, # • a numeric type try: method = next(method for idl_type, method in idl_types_methods if idl_type.is_numeric_type) test = '%s->IsNumber()' % cpp_value yield test, method except StopIteration: pass # (Perform automatic type conversion, in order. If any of these match, # that’s the end, and no other tests are needed.) To keep this code simple, # we rely on the C++ compiler's dead code elimination to deal with the # redundancy if both cases below trigger. # 11. Otherwise: if there is an entry in S that has one of the following # types at position i of its type list, # • DOMString # • ByteString # • USVString # • an enumeration type try: method = next(method for idl_type, method in idl_types_methods if idl_type.is_string_type or idl_type.is_enum) yield 'true', method except StopIteration: pass # 12. Otherwise: if there is an entry in S that has one of the following # types at position i of its type list, # • a numeric type try: method = next(method for idl_type, method in idl_types_methods if idl_type.is_numeric_type) yield 'true', method except StopIteration: pass
[ "def", "resolution_tests_methods", "(", "effective_overloads", ")", ":", "methods", "=", "[", "effective_overload", "[", "0", "]", "for", "effective_overload", "in", "effective_overloads", "]", "if", "len", "(", "methods", ")", "==", "1", ":", "# If only one method with a given length, no test needed", "yield", "'true'", ",", "methods", "[", "0", "]", "return", "# 6. If there is more than one entry in S, then set d to be the", "# distinguishing argument index for the entries of S.", "index", "=", "distinguishing_argument_index", "(", "effective_overloads", ")", "# (7-9 are for handling |undefined| values for optional arguments before", "# the distinguishing argument (as “missing”), so you can specify only some", "# optional arguments. We don’t support this, so we skip these steps.)", "# 10. If i = d, then:", "# (d is the distinguishing argument index)", "# 1. Let V be argi.", "# Note: This is the argument that will be used to resolve which", "# overload is selected.", "cpp_value", "=", "'info[%s]'", "%", "index", "# Extract argument and IDL type to simplify accessing these in each loop.", "arguments", "=", "[", "method", "[", "'arguments'", "]", "[", "index", "]", "for", "method", "in", "methods", "]", "arguments_methods", "=", "zip", "(", "arguments", ",", "methods", ")", "idl_types", "=", "[", "argument", "[", "'idl_type_object'", "]", "for", "argument", "in", "arguments", "]", "idl_types_methods", "=", "zip", "(", "idl_types", ",", "methods", ")", "# We can’t do a single loop through all methods or simply sort them, because", "# a method may be listed in multiple steps of the resolution algorithm, and", "# which test to apply differs depending on the step.", "#", "# Instead, we need to go through all methods at each step, either finding", "# first match (if only one test is allowed) or filtering to matches (if", "# multiple tests are allowed), and generating an appropriate tests.", "# 2. If V is undefined, and there is an entry in S whose list of", "# optionality values has “optional” at index i, then remove from S all", "# other entries.", "try", ":", "method", "=", "next", "(", "method", "for", "argument", ",", "method", "in", "arguments_methods", "if", "argument", "[", "'is_optional'", "]", ")", "test", "=", "'%s->IsUndefined()'", "%", "cpp_value", "yield", "test", ",", "method", "except", "StopIteration", ":", "pass", "# 3. Otherwise: if V is null or undefined, and there is an entry in S that", "# has one of the following types at position i of its type list,", "# • a nullable type", "try", ":", "method", "=", "next", "(", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_nullable", ")", "test", "=", "'isUndefinedOrNull(%s)'", "%", "cpp_value", "yield", "test", ",", "method", "except", "StopIteration", ":", "pass", "# 4. Otherwise: if V is a platform object – but not a platform array", "# object – and there is an entry in S that has one of the following", "# types at position i of its type list,", "# • an interface type that V implements", "# (Unlike most of these tests, this can return multiple methods, since we", "# test if it implements an interface. Thus we need a for loop, not a next.)", "# (We distinguish wrapper types from built-in interface types.)", "for", "idl_type", ",", "method", "in", "(", "(", "idl_type", ",", "method", ")", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_wrapper_type", ")", ":", "test", "=", "'V8{idl_type}::hasInstance({cpp_value}, info.GetIsolate())'", ".", "format", "(", "idl_type", "=", "idl_type", ".", "base_type", ",", "cpp_value", "=", "cpp_value", ")", "yield", "test", ",", "method", "# 13. Otherwise: if IsCallable(V) is true, and there is an entry in S that", "# has one of the following types at position i of its type list,", "# • a callback function type", "# ...", "#", "# FIXME:", "# We test for functions rather than callability, which isn't strictly the", "# same thing.", "try", ":", "method", "=", "next", "(", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_callback_function", ")", "test", "=", "'%s->IsFunction()'", "%", "cpp_value", "yield", "test", ",", "method", "except", "StopIteration", ":", "pass", "# 14. Otherwise: if V is any kind of object except for a native Date object,", "# a native RegExp object, and there is an entry in S that has one of the", "# following types at position i of its type list,", "# • a sequence type", "# ...", "#", "# 15. Otherwise: if V is any kind of object except for a native Date object,", "# a native RegExp object, and there is an entry in S that has one of the", "# following types at position i of its type list,", "# • an array type", "# ...", "# • a dictionary", "#", "# FIXME:", "# We don't strictly follow the algorithm here. The algorithm says \"remove", "# all other entries\" if there is \"one entry\" matching, but we yield all", "# entries to support following constructors:", "# [constructor(sequence<DOMString> arg), constructor(Dictionary arg)]", "# interface I { ... }", "# (Need to check array types before objects because an array is an object)", "for", "idl_type", ",", "method", "in", "idl_types_methods", ":", "if", "idl_type", ".", "native_array_element_type", ":", "# (We test for Array instead of generic Object to type-check.)", "# FIXME: test for Object during resolution, then have type check for", "# Array in overloaded method: http://crbug.com/262383", "yield", "'%s->IsArray()'", "%", "cpp_value", ",", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", ":", "if", "idl_type", ".", "is_dictionary", "or", "idl_type", ".", "name", "==", "'Dictionary'", ":", "# FIXME: should be '{1}->IsObject() && !{1}->IsDate() && !{1}->IsRegExp()'.format(cpp_value)", "# FIXME: the IsDate and IsRegExp checks can be skipped if we've", "# already generated tests for them.", "yield", "'%s->IsObject()'", "%", "cpp_value", ",", "method", "# (Check for exact type matches before performing automatic type conversion;", "# only needed if distinguishing between primitive types.)", "if", "len", "(", "[", "idl_type", ".", "is_primitive_type", "for", "idl_type", "in", "idl_types", "]", ")", ">", "1", ":", "# (Only needed if match in step 11, otherwise redundant.)", "if", "any", "(", "idl_type", ".", "is_string_type", "or", "idl_type", ".", "is_enum", "for", "idl_type", "in", "idl_types", ")", ":", "# 10. Otherwise: if V is a Number value, and there is an entry in S", "# that has one of the following types at position i of its type", "# list,", "# • a numeric type", "try", ":", "method", "=", "next", "(", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_numeric_type", ")", "test", "=", "'%s->IsNumber()'", "%", "cpp_value", "yield", "test", ",", "method", "except", "StopIteration", ":", "pass", "# (Perform automatic type conversion, in order. If any of these match,", "# that’s the end, and no other tests are needed.) To keep this code simple,", "# we rely on the C++ compiler's dead code elimination to deal with the", "# redundancy if both cases below trigger.", "# 11. Otherwise: if there is an entry in S that has one of the following", "# types at position i of its type list,", "# • DOMString", "# • ByteString", "# • USVString", "# • an enumeration type", "try", ":", "method", "=", "next", "(", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_string_type", "or", "idl_type", ".", "is_enum", ")", "yield", "'true'", ",", "method", "except", "StopIteration", ":", "pass", "# 12. Otherwise: if there is an entry in S that has one of the following", "# types at position i of its type list,", "# • a numeric type", "try", ":", "method", "=", "next", "(", "method", "for", "idl_type", ",", "method", "in", "idl_types_methods", "if", "idl_type", ".", "is_numeric_type", ")", "yield", "'true'", ",", "method", "except", "StopIteration", ":", "pass" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_interface.py#L963-L1137
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._get_coordinates_at_time
(self, timestep)
return [(x + dx, y + dy, z + dz) for (x, y, z), dx, dy, dz in zip(self.nodes, *displacement_values)]
Return the node coordinates list at the given timestep. This includes the displacement if it exists.
Return the node coordinates list at the given timestep.
[ "Return", "the", "node", "coordinates", "list", "at", "the", "given", "timestep", "." ]
def _get_coordinates_at_time(self, timestep): """ Return the node coordinates list at the given timestep. This includes the displacement if it exists. """ timestep = self._format_id_list(timestep, self.get_timesteps(), 'timestep') if len(timestep) > 1: self._error( 'Ambiguous timestep.', 'More than one timestep was specified. We expected ' 'one or zero timesteps.') if not timestep: return [tuple(x) for x in self.nodes] timestep_index = self.timesteps.index(timestep[0]) displacement_values = [ x[timestep_index] for x in self._get_displacement_field_values() ] return [(x + dx, y + dy, z + dz) for (x, y, z), dx, dy, dz in zip(self.nodes, *displacement_values)]
[ "def", "_get_coordinates_at_time", "(", "self", ",", "timestep", ")", ":", "timestep", "=", "self", ".", "_format_id_list", "(", "timestep", ",", "self", ".", "get_timesteps", "(", ")", ",", "'timestep'", ")", "if", "len", "(", "timestep", ")", ">", "1", ":", "self", ".", "_error", "(", "'Ambiguous timestep.'", ",", "'More than one timestep was specified. We expected '", "'one or zero timesteps.'", ")", "if", "not", "timestep", ":", "return", "[", "tuple", "(", "x", ")", "for", "x", "in", "self", ".", "nodes", "]", "timestep_index", "=", "self", ".", "timesteps", ".", "index", "(", "timestep", "[", "0", "]", ")", "displacement_values", "=", "[", "x", "[", "timestep_index", "]", "for", "x", "in", "self", ".", "_get_displacement_field_values", "(", ")", "]", "return", "[", "(", "x", "+", "dx", ",", "y", "+", "dy", ",", "z", "+", "dz", ")", "for", "(", "x", ",", "y", ",", "z", ")", ",", "dx", ",", "dy", ",", "dz", "in", "zip", "(", "self", ".", "nodes", ",", "*", "displacement_values", ")", "]" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L1611-L1633
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/data/python/ops/dataset_ops.py
python
TensorDataset.__init__
(self, tensors)
See `Dataset.from_tensors()` for details.
See `Dataset.from_tensors()` for details.
[ "See", "Dataset", ".", "from_tensors", "()", "for", "details", "." ]
def __init__(self, tensors): """See `Dataset.from_tensors()` for details.""" super(TensorDataset, self).__init__() with ops.name_scope("tensors"): self._tensors = nest.pack_sequence_as(tensors, [ ops.convert_to_tensor(t, name="component_%d" % i) for i, t in enumerate(nest.flatten(tensors)) ])
[ "def", "__init__", "(", "self", ",", "tensors", ")", ":", "super", "(", "TensorDataset", ",", "self", ")", ".", "__init__", "(", ")", "with", "ops", ".", "name_scope", "(", "\"tensors\"", ")", ":", "self", ".", "_tensors", "=", "nest", ".", "pack_sequence_as", "(", "tensors", ",", "[", "ops", ".", "convert_to_tensor", "(", "t", ",", "name", "=", "\"component_%d\"", "%", "i", ")", "for", "i", ",", "t", "in", "enumerate", "(", "nest", ".", "flatten", "(", "tensors", ")", ")", "]", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/data/python/ops/dataset_ops.py#L1078-L1085
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/metrics_impl.py
python
specificity_at_sensitivity
( labels, predictions, sensitivity, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None)
Computes the specificity at a given sensitivity. The `specificity_at_sensitivity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the specificity at the given sensitivity value. The threshold for the given sensitivity value is computed and used to evaluate the corresponding specificity. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `specificity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about specificity and sensitivity, see the following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. sensitivity: A scalar value in range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use for matching the given sensitivity. metrics_collections: An optional list of collections that `specificity` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: specificity: A scalar `Tensor` representing the specificity at the given `specificity` value. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `specificity`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `sensitivity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Computes the specificity at a given sensitivity.
[ "Computes", "the", "specificity", "at", "a", "given", "sensitivity", "." ]
def specificity_at_sensitivity( labels, predictions, sensitivity, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None): """Computes the specificity at a given sensitivity. The `specificity_at_sensitivity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the specificity at the given sensitivity value. The threshold for the given sensitivity value is computed and used to evaluate the corresponding specificity. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `specificity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about specificity and sensitivity, see the following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. sensitivity: A scalar value in range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use for matching the given sensitivity. metrics_collections: An optional list of collections that `specificity` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: specificity: A scalar `Tensor` representing the specificity at the given `specificity` value. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `specificity`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `sensitivity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ if sensitivity < 0 or sensitivity > 1: raise ValueError('`sensitivity` must be in the range [0, 1].') with variable_scope.variable_scope(name, 'specificity_at_sensitivity', (predictions, labels, weights)): kepsilon = 1e-7 # to account for floating point imprecisions thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds-2)] thresholds = [0.0 - kepsilon] + thresholds + [1.0 - kepsilon] values, update_ops = _confusion_matrix_at_thresholds( labels, predictions, thresholds, weights) def compute_specificity_at_sensitivity(tp, tn, fp, fn, name): """Computes the specificity at the given sensitivity. Args: tp: True positives. tn: True negatives. fp: False positives. fn: False negatives. name: The name of the operation. Returns: The specificity using the aggregated values. """ sensitivities = math_ops.div(tp, tp + fn + kepsilon) # We'll need to use this trick until tf.argmax allows us to specify # whether we should use the first or last index in case of ties. min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity)) indices_at_minval = math_ops.equal( math_ops.abs(sensitivities - sensitivity), min_val) indices_at_minval = math_ops.to_int64(indices_at_minval) indices_at_minval = math_ops.cumsum(indices_at_minval) tf_index = math_ops.argmax(indices_at_minval, 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the specificity: return math_ops.div(tn[tf_index], tn[tf_index] + fp[tf_index] + kepsilon, name) specificity = compute_specificity_at_sensitivity( values['tp'], values['tn'], values['fp'], values['fn'], 'value') update_op = compute_specificity_at_sensitivity( update_ops['tp'], update_ops['tn'], update_ops['fp'], update_ops['fn'], 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, specificity) if updates_collections: ops.add_to_collections(updates_collections, update_op) return specificity, update_op
[ "def", "specificity_at_sensitivity", "(", "labels", ",", "predictions", ",", "sensitivity", ",", "weights", "=", "None", ",", "num_thresholds", "=", "200", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "if", "sensitivity", "<", "0", "or", "sensitivity", ">", "1", ":", "raise", "ValueError", "(", "'`sensitivity` must be in the range [0, 1].'", ")", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "'specificity_at_sensitivity'", ",", "(", "predictions", ",", "labels", ",", "weights", ")", ")", ":", "kepsilon", "=", "1e-7", "# to account for floating point imprecisions", "thresholds", "=", "[", "(", "i", "+", "1", ")", "*", "1.0", "/", "(", "num_thresholds", "-", "1", ")", "for", "i", "in", "range", "(", "num_thresholds", "-", "2", ")", "]", "thresholds", "=", "[", "0.0", "-", "kepsilon", "]", "+", "thresholds", "+", "[", "1.0", "-", "kepsilon", "]", "values", ",", "update_ops", "=", "_confusion_matrix_at_thresholds", "(", "labels", ",", "predictions", ",", "thresholds", ",", "weights", ")", "def", "compute_specificity_at_sensitivity", "(", "tp", ",", "tn", ",", "fp", ",", "fn", ",", "name", ")", ":", "\"\"\"Computes the specificity at the given sensitivity.\n\n Args:\n tp: True positives.\n tn: True negatives.\n fp: False positives.\n fn: False negatives.\n name: The name of the operation.\n\n Returns:\n The specificity using the aggregated values.\n \"\"\"", "sensitivities", "=", "math_ops", ".", "div", "(", "tp", ",", "tp", "+", "fn", "+", "kepsilon", ")", "# We'll need to use this trick until tf.argmax allows us to specify", "# whether we should use the first or last index in case of ties.", "min_val", "=", "math_ops", ".", "reduce_min", "(", "math_ops", ".", "abs", "(", "sensitivities", "-", "sensitivity", ")", ")", "indices_at_minval", "=", "math_ops", ".", "equal", "(", "math_ops", ".", "abs", "(", "sensitivities", "-", "sensitivity", ")", ",", "min_val", ")", "indices_at_minval", "=", "math_ops", ".", "to_int64", "(", "indices_at_minval", ")", "indices_at_minval", "=", "math_ops", ".", "cumsum", "(", "indices_at_minval", ")", "tf_index", "=", "math_ops", ".", "argmax", "(", "indices_at_minval", ",", "0", ")", "tf_index", "=", "math_ops", ".", "cast", "(", "tf_index", ",", "dtypes", ".", "int32", ")", "# Now, we have the implicit threshold, so compute the specificity:", "return", "math_ops", ".", "div", "(", "tn", "[", "tf_index", "]", ",", "tn", "[", "tf_index", "]", "+", "fp", "[", "tf_index", "]", "+", "kepsilon", ",", "name", ")", "specificity", "=", "compute_specificity_at_sensitivity", "(", "values", "[", "'tp'", "]", ",", "values", "[", "'tn'", "]", ",", "values", "[", "'fp'", "]", ",", "values", "[", "'fn'", "]", ",", "'value'", ")", "update_op", "=", "compute_specificity_at_sensitivity", "(", "update_ops", "[", "'tp'", "]", ",", "update_ops", "[", "'tn'", "]", ",", "update_ops", "[", "'fp'", "]", ",", "update_ops", "[", "'fn'", "]", ",", "'update_op'", ")", "if", "metrics_collections", ":", "ops", ".", "add_to_collections", "(", "metrics_collections", ",", "specificity", ")", "if", "updates_collections", ":", "ops", ".", "add_to_collections", "(", "updates_collections", ",", "update_op", ")", "return", "specificity", ",", "update_op" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/metrics_impl.py#L3066-L3173
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/third_party/abseil-cpp/absl/abseil.podspec.gen.py
python
generate
(args)
Generates a podspec file from all BUILD files under absl directory.
Generates a podspec file from all BUILD files under absl directory.
[ "Generates", "a", "podspec", "file", "from", "all", "BUILD", "files", "under", "absl", "directory", "." ]
def generate(args): """Generates a podspec file from all BUILD files under absl directory.""" rules = filter(relevant_rule, collect_rules("absl")) with open(args.output, "wt") as f: write_podspec(f, rules, vars(args))
[ "def", "generate", "(", "args", ")", ":", "rules", "=", "filter", "(", "relevant_rule", ",", "collect_rules", "(", "\"absl\"", ")", ")", "with", "open", "(", "args", ".", "output", ",", "\"wt\"", ")", "as", "f", ":", "write_podspec", "(", "f", ",", "rules", ",", "vars", "(", "args", ")", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/abseil-cpp/absl/abseil.podspec.gen.py#L200-L204
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/pytorch/resnet50/main.py
python
adjust_learning_rate
(optimizer, epoch, step, len_epoch)
LR schedule that should yield 76% converged accuracy with batch size 256
LR schedule that should yield 76% converged accuracy with batch size 256
[ "LR", "schedule", "that", "should", "yield", "76%", "converged", "accuracy", "with", "batch", "size", "256" ]
def adjust_learning_rate(optimizer, epoch, step, len_epoch): """LR schedule that should yield 76% converged accuracy with batch size 256""" factor = epoch // 30 if epoch >= 80: factor = factor + 1 lr = args.lr*(0.1**factor) """Warmup""" if epoch < 5: lr = lr*float(1 + step + epoch*len_epoch)/(5.*len_epoch) for param_group in optimizer.param_groups: param_group['lr'] = lr
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ",", "step", ",", "len_epoch", ")", ":", "factor", "=", "epoch", "//", "30", "if", "epoch", ">=", "80", ":", "factor", "=", "factor", "+", "1", "lr", "=", "args", ".", "lr", "*", "(", "0.1", "**", "factor", ")", "\"\"\"Warmup\"\"\"", "if", "epoch", "<", "5", ":", "lr", "=", "lr", "*", "float", "(", "1", "+", "step", "+", "epoch", "*", "len_epoch", ")", "/", "(", "5.", "*", "len_epoch", ")", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'lr'", "]", "=", "lr" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/pytorch/resnet50/main.py#L536-L550
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBWatchpoint.GetWatchpointEventTypeFromEvent
(event)
return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event)
GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType
GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType
[ "GetWatchpointEventTypeFromEvent", "(", "SBEvent", "event", ")", "-", ">", "lldb", "::", "WatchpointEventType" ]
def GetWatchpointEventTypeFromEvent(event): """GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType""" return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event)
[ "def", "GetWatchpointEventTypeFromEvent", "(", "event", ")", ":", "return", "_lldb", ".", "SBWatchpoint_GetWatchpointEventTypeFromEvent", "(", "event", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15257-L15259
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
EntryProxy.__get_windows_path
(self)
r"""Return the path with \ as the path separator, regardless of platform.
r"""Return the path with \ as the path separator, regardless of platform.
[ "r", "Return", "the", "path", "with", "\\", "as", "the", "path", "separator", "regardless", "of", "platform", "." ]
def __get_windows_path(self): r"""Return the path with \ as the path separator, regardless of platform.""" if OS_SEP == '\\': return self else: entry = self.get() r = entry.get_path().replace(OS_SEP, '\\') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows")
[ "def", "__get_windows_path", "(", "self", ")", ":", "if", "OS_SEP", "==", "'\\\\'", ":", "return", "self", "else", ":", "entry", "=", "self", ".", "get", "(", ")", "r", "=", "entry", ".", "get_path", "(", ")", ".", "replace", "(", "OS_SEP", ",", "'\\\\'", ")", "return", "SCons", ".", "Subst", ".", "SpecialAttrWrapper", "(", "r", ",", "entry", ".", "name", "+", "\"_windows\"", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L476-L484
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp2/ctptd.py
python
CtpTd.onRspQryTransferBank
(self, TransferBankField, RspInfoField, requestId, final)
请求查询转帐银行响应
请求查询转帐银行响应
[ "请求查询转帐银行响应" ]
def onRspQryTransferBank(self, TransferBankField, RspInfoField, requestId, final): """请求查询转帐银行响应""" pass
[ "def", "onRspQryTransferBank", "(", "self", ",", "TransferBankField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp2/ctptd.py#L245-L247
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenu.GetLabel
(self, itemId)
return item.GetText()
Returns the label of a :class:`FlatMenuItem`. :param integer `id`: the menu item identifier; :see: :meth:`~FlatMenu.SetLabel`.
Returns the label of a :class:`FlatMenuItem`.
[ "Returns", "the", "label", "of", "a", ":", "class", ":", "FlatMenuItem", "." ]
def GetLabel(self, itemId): """ Returns the label of a :class:`FlatMenuItem`. :param integer `id`: the menu item identifier; :see: :meth:`~FlatMenu.SetLabel`. """ item = self.FindItem(itemId) return item.GetText()
[ "def", "GetLabel", "(", "self", ",", "itemId", ")", ":", "item", "=", "self", ".", "FindItem", "(", "itemId", ")", "return", "item", ".", "GetText", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L6881-L6891
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/path.py/path.py
python
Path.write_bytes
(self, bytes, append=False)
Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call ``p.write_bytes(bytes, append=True)`` to append instead.
Open this file and write the given bytes to it.
[ "Open", "this", "file", "and", "write", "the", "given", "bytes", "to", "it", "." ]
def write_bytes(self, bytes, append=False): """ Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call ``p.write_bytes(bytes, append=True)`` to append instead. """ if append: mode = 'ab' else: mode = 'wb' with self.open(mode) as f: f.write(bytes)
[ "def", "write_bytes", "(", "self", ",", "bytes", ",", "append", "=", "False", ")", ":", "if", "append", ":", "mode", "=", "'ab'", "else", ":", "mode", "=", "'wb'", "with", "self", ".", "open", "(", "mode", ")", "as", "f", ":", "f", ".", "write", "(", "bytes", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/path.py/path.py#L767-L778
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py
python
InstalledDistribution.read_exports
(self)
return result
Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
[]
def read_exports(self): """ Read exports data from a file in .ini format. :return: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. """ result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
[ "def", "read_exports", "(", "self", ")", ":", "result", "=", "{", "}", "r", "=", "self", ".", "get_distinfo_resource", "(", "EXPORTS_FILENAME", ")", "if", "r", ":", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "result", "=", "read_exports", "(", "stream", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L1233-L1259
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/gauth.py
python
AuthSubToken.from_url
(str_or_uri)
return AuthSubToken(token_and_scopes[0], token_and_scopes[1])
Creates a new AuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL.
Creates a new AuthSubToken using information in the URL.
[ "Creates", "a", "new", "AuthSubToken", "using", "information", "in", "the", "URL", "." ]
def from_url(str_or_uri): """Creates a new AuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. """ token_and_scopes = auth_sub_string_from_url(str_or_uri) return AuthSubToken(token_and_scopes[0], token_and_scopes[1])
[ "def", "from_url", "(", "str_or_uri", ")", ":", "token_and_scopes", "=", "auth_sub_string_from_url", "(", "str_or_uri", ")", "return", "AuthSubToken", "(", "token_and_scopes", "[", "0", "]", ",", "token_and_scopes", "[", "1", "]", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/gauth.py#L335-L347
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/_config/config.py
python
register_option
(key: str, defval: object, doc="", validator=None, cb=None)
Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb - a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Returns ------- Nothing. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value.
Register an option in the package-wide pandas config object
[ "Register", "an", "option", "in", "the", "package", "-", "wide", "pandas", "config", "object" ]
def register_option(key: str, defval: object, doc="", validator=None, cb=None): """Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the option validator - a function of a single argument, should raise `ValueError` if called with a value which is not a legal value for the option. cb - a function of a single argument "key", which is called immediately after an option value is set/reset. key is the full name of the option. Returns ------- Nothing. Raises ------ ValueError if `validator` is specified and `defval` is not a valid value. """ import tokenize import keyword key = key.lower() if key in _registered_options: raise OptionError(f"Option '{key}' has already been registered") if key in _reserved_keys: raise OptionError(f"Option '{key}' is a reserved key") # the default value should be legal if validator: validator(defval) # walk the nested dict, creating dicts as needed along the path path = key.split(".") for k in path: # NOTE: tokenize.Name is not a public constant # error: Module has no attribute "Name" [attr-defined] if not re.match("^" + tokenize.Name + "$", k): # type: ignore raise ValueError(f"{k} is not a valid identifier") if keyword.iskeyword(k): raise ValueError(f"{k} is a python keyword") cursor = _global_config msg = "Path prefix to option '{option}' is already an option" for i, p in enumerate(path[:-1]): if not isinstance(cursor, dict): raise OptionError(msg.format(option=".".join(path[:i]))) if p not in cursor: cursor[p] = {} cursor = cursor[p] if not isinstance(cursor, dict): raise OptionError(msg.format(option=".".join(path[:-1]))) cursor[path[-1]] = defval # initialize # save the option metadata _registered_options[key] = RegisteredOption( key=key, defval=defval, doc=doc, validator=validator, cb=cb )
[ "def", "register_option", "(", "key", ":", "str", ",", "defval", ":", "object", ",", "doc", "=", "\"\"", ",", "validator", "=", "None", ",", "cb", "=", "None", ")", ":", "import", "tokenize", "import", "keyword", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "in", "_registered_options", ":", "raise", "OptionError", "(", "f\"Option '{key}' has already been registered\"", ")", "if", "key", "in", "_reserved_keys", ":", "raise", "OptionError", "(", "f\"Option '{key}' is a reserved key\"", ")", "# the default value should be legal", "if", "validator", ":", "validator", "(", "defval", ")", "# walk the nested dict, creating dicts as needed along the path", "path", "=", "key", ".", "split", "(", "\".\"", ")", "for", "k", "in", "path", ":", "# NOTE: tokenize.Name is not a public constant", "# error: Module has no attribute \"Name\" [attr-defined]", "if", "not", "re", ".", "match", "(", "\"^\"", "+", "tokenize", ".", "Name", "+", "\"$\"", ",", "k", ")", ":", "# type: ignore", "raise", "ValueError", "(", "f\"{k} is not a valid identifier\"", ")", "if", "keyword", ".", "iskeyword", "(", "k", ")", ":", "raise", "ValueError", "(", "f\"{k} is a python keyword\"", ")", "cursor", "=", "_global_config", "msg", "=", "\"Path prefix to option '{option}' is already an option\"", "for", "i", ",", "p", "in", "enumerate", "(", "path", "[", ":", "-", "1", "]", ")", ":", "if", "not", "isinstance", "(", "cursor", ",", "dict", ")", ":", "raise", "OptionError", "(", "msg", ".", "format", "(", "option", "=", "\".\"", ".", "join", "(", "path", "[", ":", "i", "]", ")", ")", ")", "if", "p", "not", "in", "cursor", ":", "cursor", "[", "p", "]", "=", "{", "}", "cursor", "=", "cursor", "[", "p", "]", "if", "not", "isinstance", "(", "cursor", ",", "dict", ")", ":", "raise", "OptionError", "(", "msg", ".", "format", "(", "option", "=", "\".\"", ".", "join", "(", "path", "[", ":", "-", "1", "]", ")", ")", ")", "cursor", "[", "path", "[", "-", "1", "]", "]", "=", "defval", "# initialize", "# save the option metadata", "_registered_options", "[", "key", "]", "=", "RegisteredOption", "(", "key", "=", "key", ",", "defval", "=", "defval", ",", "doc", "=", "doc", ",", "validator", "=", "validator", ",", "cb", "=", "cb", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/_config/config.py#L413-L479
OkCupid/okws
1c337392c676ccb4e9a4c92d11d5d2fada6427d2
contrib/pub2-upgrade.py
python
PubParser.p_pub_block
(self, p)
pub_block : LBP block_inner RBP
pub_block : LBP block_inner RBP
[ "pub_block", ":", "LBP", "block_inner", "RBP" ]
def p_pub_block (self, p): '''pub_block : LBP block_inner RBP''' p[0] = PubBlock (p[2], p[1], p[3])
[ "def", "p_pub_block", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "PubBlock", "(", "p", "[", "2", "]", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub2-upgrade.py#L274-L276
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/optim/_multi_tensor/_functional.py
python
adamax
(params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_infs: List[Tensor], state_steps: List[Tensor], *, beta1: float, beta2: float, lr: float, weight_decay: float, eps: float)
r"""Functional API that performs Adamax algorithm computation. See :class:`~torch.optim.Adamax` for details.
r"""Functional API that performs Adamax algorithm computation.
[ "r", "Functional", "API", "that", "performs", "Adamax", "algorithm", "computation", "." ]
def adamax(params: List[Tensor], grads: List[Tensor], exp_avgs: List[Tensor], exp_infs: List[Tensor], state_steps: List[Tensor], *, beta1: float, beta2: float, lr: float, weight_decay: float, eps: float): r"""Functional API that performs Adamax algorithm computation. See :class:`~torch.optim.Adamax` for details. """ if not all([isinstance(t, torch.Tensor) for t in state_steps]): raise RuntimeError("API has changed, `state_steps` argument must contain a list of singleton tensors") # Update steps torch._foreach_add_(state_steps, 1) if weight_decay != 0: torch._foreach_add_(grads, params, alpha=weight_decay) # Update biased first moment estimate. torch._foreach_mul_(exp_avgs, beta1) torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1) # Update the exponentially weighted infinity norm. torch._foreach_mul_(exp_infs, beta2) for exp_inf, grad in zip(exp_infs, grads): norm_buf = torch.cat([ exp_inf.unsqueeze(0), grad.abs().add_(eps).unsqueeze_(0) ], 0) torch.max(norm_buf, 0, keepdim=False, out=(exp_inf, exp_inf.new().long())) bias_corrections = [1 - beta1 ** step.item() for step in state_steps] clr = [-1 * (lr / bias_correction) for bias_correction in bias_corrections] torch._foreach_addcdiv_(params, exp_avgs, exp_infs, clr)
[ "def", "adamax", "(", "params", ":", "List", "[", "Tensor", "]", ",", "grads", ":", "List", "[", "Tensor", "]", ",", "exp_avgs", ":", "List", "[", "Tensor", "]", ",", "exp_infs", ":", "List", "[", "Tensor", "]", ",", "state_steps", ":", "List", "[", "Tensor", "]", ",", "*", ",", "beta1", ":", "float", ",", "beta2", ":", "float", ",", "lr", ":", "float", ",", "weight_decay", ":", "float", ",", "eps", ":", "float", ")", ":", "if", "not", "all", "(", "[", "isinstance", "(", "t", ",", "torch", ".", "Tensor", ")", "for", "t", "in", "state_steps", "]", ")", ":", "raise", "RuntimeError", "(", "\"API has changed, `state_steps` argument must contain a list of singleton tensors\"", ")", "# Update steps", "torch", ".", "_foreach_add_", "(", "state_steps", ",", "1", ")", "if", "weight_decay", "!=", "0", ":", "torch", ".", "_foreach_add_", "(", "grads", ",", "params", ",", "alpha", "=", "weight_decay", ")", "# Update biased first moment estimate.", "torch", ".", "_foreach_mul_", "(", "exp_avgs", ",", "beta1", ")", "torch", ".", "_foreach_add_", "(", "exp_avgs", ",", "grads", ",", "alpha", "=", "1", "-", "beta1", ")", "# Update the exponentially weighted infinity norm.", "torch", ".", "_foreach_mul_", "(", "exp_infs", ",", "beta2", ")", "for", "exp_inf", ",", "grad", "in", "zip", "(", "exp_infs", ",", "grads", ")", ":", "norm_buf", "=", "torch", ".", "cat", "(", "[", "exp_inf", ".", "unsqueeze", "(", "0", ")", ",", "grad", ".", "abs", "(", ")", ".", "add_", "(", "eps", ")", ".", "unsqueeze_", "(", "0", ")", "]", ",", "0", ")", "torch", ".", "max", "(", "norm_buf", ",", "0", ",", "keepdim", "=", "False", ",", "out", "=", "(", "exp_inf", ",", "exp_inf", ".", "new", "(", ")", ".", "long", "(", ")", ")", ")", "bias_corrections", "=", "[", "1", "-", "beta1", "**", "step", ".", "item", "(", ")", "for", "step", "in", "state_steps", "]", "clr", "=", "[", "-", "1", "*", "(", "lr", "/", "bias_correction", ")", "for", "bias_correction", "in", "bias_corrections", "]", "torch", ".", "_foreach_addcdiv_", "(", "params", ",", "exp_avgs", ",", "exp_infs", ",", "clr", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/optim/_multi_tensor/_functional.py#L75-L116
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/ops/spc/spc.py
python
unbatched_query
(octree, exsum, query_points, level)
return _C.ops.spc.query_cuda(octree.contiguous(), exsum.contiguous(), query_points.contiguous(), level).long()
r"""Query point indices from the octree. Given a point hierarchy, this function will efficiently find the corresponding indices of the points in the points tensor. For each input in query_points, returns a index to the points tensor. Returns -1 if the point does not exist. Args: octree (torch.ByteTensor): The octree, of shape :math:`(\text{num_bytes})`. exsum (torch.IntTensor): The exclusive sum of the octree bytes, of shape :math:`(\text{num_bytes} + 1)`. See :ref:`spc_pyramids` for more details. query_points (torch.ShortTensor): A collection of query indices, of shape :math:`(\text{num_query}, 3)`. level (int): The level of the octree to query from.
r"""Query point indices from the octree.
[ "r", "Query", "point", "indices", "from", "the", "octree", "." ]
def unbatched_query(octree, exsum, query_points, level): r"""Query point indices from the octree. Given a point hierarchy, this function will efficiently find the corresponding indices of the points in the points tensor. For each input in query_points, returns a index to the points tensor. Returns -1 if the point does not exist. Args: octree (torch.ByteTensor): The octree, of shape :math:`(\text{num_bytes})`. exsum (torch.IntTensor): The exclusive sum of the octree bytes, of shape :math:`(\text{num_bytes} + 1)`. See :ref:`spc_pyramids` for more details. query_points (torch.ShortTensor): A collection of query indices, of shape :math:`(\text{num_query}, 3)`. level (int): The level of the octree to query from. """ return _C.ops.spc.query_cuda(octree.contiguous(), exsum.contiguous(), query_points.contiguous(), level).long()
[ "def", "unbatched_query", "(", "octree", ",", "exsum", ",", "query_points", ",", "level", ")", ":", "return", "_C", ".", "ops", ".", "spc", ".", "query_cuda", "(", "octree", ".", "contiguous", "(", ")", ",", "exsum", ".", "contiguous", "(", ")", ",", "query_points", ".", "contiguous", "(", ")", ",", "level", ")", ".", "long", "(", ")" ]
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/spc/spc.py#L242-L259
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py
python
VocabularyFileCategoricalColumn.transform_feature
(self, transformation_cache, state_manager)
return self._transform_input_tensor(input_tensor, state_manager)
Creates a lookup table for the vocabulary.
Creates a lookup table for the vocabulary.
[ "Creates", "a", "lookup", "table", "for", "the", "vocabulary", "." ]
def transform_feature(self, transformation_cache, state_manager): """Creates a lookup table for the vocabulary.""" input_tensor = _to_sparse_input_and_drop_ignore_values( transformation_cache.get(self.key, state_manager)) return self._transform_input_tensor(input_tensor, state_manager)
[ "def", "transform_feature", "(", "self", ",", "transformation_cache", ",", "state_manager", ")", ":", "input_tensor", "=", "_to_sparse_input_and_drop_ignore_values", "(", "transformation_cache", ".", "get", "(", "self", ".", "key", ",", "state_manager", ")", ")", "return", "self", ".", "_transform_input_tensor", "(", "input_tensor", ",", "state_manager", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3621-L3625
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/problems/problem.py
python
Problem._sort_candidate_solvers
(solvers)
Sorts candidate solvers lists according to slv_def.CONIC_SOLVERS/QP_SOLVERS Arguments --------- candidates : dict Dictionary of candidate solvers divided in qp_solvers and conic_solvers Returns ------- None
Sorts candidate solvers lists according to slv_def.CONIC_SOLVERS/QP_SOLVERS
[ "Sorts", "candidate", "solvers", "lists", "according", "to", "slv_def", ".", "CONIC_SOLVERS", "/", "QP_SOLVERS" ]
def _sort_candidate_solvers(solvers) -> None: """Sorts candidate solvers lists according to slv_def.CONIC_SOLVERS/QP_SOLVERS Arguments --------- candidates : dict Dictionary of candidate solvers divided in qp_solvers and conic_solvers Returns ------- None """ if len(solvers['conic_solvers']) > 1: solvers['conic_solvers'] = sorted( solvers['conic_solvers'], key=lambda s: slv_def.CONIC_SOLVERS.index(s) ) if len(solvers['qp_solvers']) > 1: solvers['qp_solvers'] = sorted( solvers['qp_solvers'], key=lambda s: slv_def.QP_SOLVERS.index(s) )
[ "def", "_sort_candidate_solvers", "(", "solvers", ")", "->", "None", ":", "if", "len", "(", "solvers", "[", "'conic_solvers'", "]", ")", ">", "1", ":", "solvers", "[", "'conic_solvers'", "]", "=", "sorted", "(", "solvers", "[", "'conic_solvers'", "]", ",", "key", "=", "lambda", "s", ":", "slv_def", ".", "CONIC_SOLVERS", ".", "index", "(", "s", ")", ")", "if", "len", "(", "solvers", "[", "'qp_solvers'", "]", ")", ">", "1", ":", "solvers", "[", "'qp_solvers'", "]", "=", "sorted", "(", "solvers", "[", "'qp_solvers'", "]", ",", "key", "=", "lambda", "s", ":", "slv_def", ".", "QP_SOLVERS", ".", "index", "(", "s", ")", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/problems/problem.py#L815-L834
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/finddlg.py
python
FindBox.__init__
(self, parent, fdata, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=AFR_STYLE_FINDDIALOG, name=FindBoxName)
Create the container box @param fdata: wx.FindReplaceData
Create the container box @param fdata: wx.FindReplaceData
[ "Create", "the", "container", "box", "@param", "fdata", ":", "wx", ".", "FindReplaceData" ]
def __init__(self, parent, fdata, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=AFR_STYLE_FINDDIALOG, name=FindBoxName): """Create the container box @param fdata: wx.FindReplaceData """ super(FindBox, self).__init__(parent, id, pos, size, wx.TAB_TRAVERSAL|wx.NO_BORDER, name) # Attributes self._fpanel = FindPanel(self, fdata, style=style) ctrlbar = ctrlbox.ControlBar(self, style=ctrlbox.CTRLBAR_STYLE_GRADIENT) bmp = wx.ArtProvider.GetBitmap(wx.ART_FIND, wx.ART_MENU) self.find = platebtn.PlateButton(ctrlbar, label=_("Find"), bmp=bmp, style=platebtn.PB_STYLE_NOBG) bmp = wx.ArtProvider.GetBitmap(wx.ART_FIND_AND_REPLACE, wx.ART_MENU) self.replace = platebtn.PlateButton(ctrlbar, label=_("Replace"), bmp=bmp, style=platebtn.PB_STYLE_NOBG) # Setup if wx.Platform == '__WXGTK__': ctrlbar.SetWindowStyle(ctrlbox.CTRLBAR_STYLE_BORDER_BOTTOM) ctrlbar.SetVMargin(2, 2) ctrlbar.AddControl(self.find, wx.ALIGN_LEFT) ctrlbar.AddControl(self.replace, wx.ALIGN_LEFT) self.SetControlBar(ctrlbar) self.SetWindow(self._fpanel) if style & AFR_STYLE_NO_MODE_SELECT: self.GetControlBar().Hide() # Event Handlers self.Bind(wx.EVT_BUTTON, self.OnButton)
[ "def", "__init__", "(", "self", ",", "parent", ",", "fdata", ",", "id", "=", "wx", ".", "ID_ANY", ",", "pos", "=", "wx", ".", "DefaultPosition", ",", "size", "=", "wx", ".", "DefaultSize", ",", "style", "=", "AFR_STYLE_FINDDIALOG", ",", "name", "=", "FindBoxName", ")", ":", "super", "(", "FindBox", ",", "self", ")", ".", "__init__", "(", "parent", ",", "id", ",", "pos", ",", "size", ",", "wx", ".", "TAB_TRAVERSAL", "|", "wx", ".", "NO_BORDER", ",", "name", ")", "# Attributes", "self", ".", "_fpanel", "=", "FindPanel", "(", "self", ",", "fdata", ",", "style", "=", "style", ")", "ctrlbar", "=", "ctrlbox", ".", "ControlBar", "(", "self", ",", "style", "=", "ctrlbox", ".", "CTRLBAR_STYLE_GRADIENT", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_FIND", ",", "wx", ".", "ART_MENU", ")", "self", ".", "find", "=", "platebtn", ".", "PlateButton", "(", "ctrlbar", ",", "label", "=", "_", "(", "\"Find\"", ")", ",", "bmp", "=", "bmp", ",", "style", "=", "platebtn", ".", "PB_STYLE_NOBG", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_FIND_AND_REPLACE", ",", "wx", ".", "ART_MENU", ")", "self", ".", "replace", "=", "platebtn", ".", "PlateButton", "(", "ctrlbar", ",", "label", "=", "_", "(", "\"Replace\"", ")", ",", "bmp", "=", "bmp", ",", "style", "=", "platebtn", ".", "PB_STYLE_NOBG", ")", "# Setup", "if", "wx", ".", "Platform", "==", "'__WXGTK__'", ":", "ctrlbar", ".", "SetWindowStyle", "(", "ctrlbox", ".", "CTRLBAR_STYLE_BORDER_BOTTOM", ")", "ctrlbar", ".", "SetVMargin", "(", "2", ",", "2", ")", "ctrlbar", ".", "AddControl", "(", "self", ".", "find", ",", "wx", ".", "ALIGN_LEFT", ")", "ctrlbar", ".", "AddControl", "(", "self", ".", "replace", ",", "wx", ".", "ALIGN_LEFT", ")", "self", ".", "SetControlBar", "(", "ctrlbar", ")", "self", ".", "SetWindow", "(", "self", ".", "_fpanel", ")", "if", "style", "&", "AFR_STYLE_NO_MODE_SELECT", ":", "self", ".", "GetControlBar", "(", ")", ".", "Hide", "(", ")", "# Event Handlers", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "OnButton", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L637-L672
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/devices.py
python
device_to_str
(dtype)
Convert a device type to string format. Parameters ---------- dtype : Device or str The device type to be converted Returns ------- str The converted device type in string format.
Convert a device type to string format.
[ "Convert", "a", "device", "type", "to", "string", "format", "." ]
def device_to_str(dtype): """Convert a device type to string format. Parameters ---------- dtype : Device or str The device type to be converted Returns ------- str The converted device type in string format. """ if isinstance(dtype, Device): if isinstance(dtype, CPU): return "cpu_" + str(dtype.model) elif isinstance(dtype, FPGA): return "fpga_" + str(dtype.model) else: if not isinstance(dtype, str): raise DeviceError("Unsupported device type format") return dtype
[ "def", "device_to_str", "(", "dtype", ")", ":", "if", "isinstance", "(", "dtype", ",", "Device", ")", ":", "if", "isinstance", "(", "dtype", ",", "CPU", ")", ":", "return", "\"cpu_\"", "+", "str", "(", "dtype", ".", "model", ")", "elif", "isinstance", "(", "dtype", ",", "FPGA", ")", ":", "return", "\"fpga_\"", "+", "str", "(", "dtype", ".", "model", ")", "else", ":", "if", "not", "isinstance", "(", "dtype", ",", "str", ")", ":", "raise", "DeviceError", "(", "\"Unsupported device type format\"", ")", "return", "dtype" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/devices.py#L328-L349
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/histograms.py
python
_hist_bin_scott
(x, range)
return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x)
Scott histogram bin estimator. The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data.
Scott histogram bin estimator.
[ "Scott", "histogram", "bin", "estimator", "." ]
def _hist_bin_scott(x, range): """ Scott histogram bin estimator. The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ del range # unused return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x)
[ "def", "_hist_bin_scott", "(", "x", ",", "range", ")", ":", "del", "range", "# unused", "return", "(", "24.0", "*", "np", ".", "pi", "**", "0.5", "/", "x", ".", "size", ")", "**", "(", "1.0", "/", "3.0", ")", "*", "np", ".", "std", "(", "x", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/histograms.py#L103-L122
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/closurizednamespacesinfo.py
python
ClosurizedNamespacesInfo.IsFirstProvide
(self, token)
return self._provide_tokens and token == self._provide_tokens[0]
Returns whether token is the first provide token.
Returns whether token is the first provide token.
[ "Returns", "whether", "token", "is", "the", "first", "provide", "token", "." ]
def IsFirstProvide(self, token): """Returns whether token is the first provide token.""" return self._provide_tokens and token == self._provide_tokens[0]
[ "def", "IsFirstProvide", "(", "self", ",", "token", ")", ":", "return", "self", ".", "_provide_tokens", "and", "token", "==", "self", ".", "_provide_tokens", "[", "0", "]" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/closurizednamespacesinfo.py#L264-L266
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/ML/Descriptors/Descriptors.py
python
DescriptorCalculator.ShowDescriptors
(self)
prints out a list of the descriptors
prints out a list of the descriptors
[ "prints", "out", "a", "list", "of", "the", "descriptors" ]
def ShowDescriptors(self): """ prints out a list of the descriptors """ if self.simpleList is None: raise NotImplementedError('Need to have a simpleList defined') print('#---------') print('Simple:') for desc in self.simpleList: print(desc) if self.compoundList: print('#---------') print('Compound:') for desc in self.compoundList: print(desc)
[ "def", "ShowDescriptors", "(", "self", ")", ":", "if", "self", ".", "simpleList", "is", "None", ":", "raise", "NotImplementedError", "(", "'Need to have a simpleList defined'", ")", "print", "(", "'#---------'", ")", "print", "(", "'Simple:'", ")", "for", "desc", "in", "self", ".", "simpleList", ":", "print", "(", "desc", ")", "if", "self", ".", "compoundList", ":", "print", "(", "'#---------'", ")", "print", "(", "'Compound:'", ")", "for", "desc", "in", "self", ".", "compoundList", ":", "print", "(", "desc", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Descriptors/Descriptors.py#L28-L42
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
ppapi/generators/idl_parser.py
python
IDLParser.p_label_cont
(self, p)
label_cont : ',' label_list |
label_cont : ',' label_list |
[ "label_cont", ":", "label_list", "|" ]
def p_label_cont(self, p): """label_cont : ',' label_list |""" if len(p) > 1: p[0] = p[2] if self.parse_debug: DumpReduction('label_cont', p)
[ "def", "p_label_cont", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", ">", "1", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]", "if", "self", ".", "parse_debug", ":", "DumpReduction", "(", "'label_cont'", ",", "p", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_parser.py#L717-L721
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/info.py
python
TableBuilderAbstract.add_dtypes_line
(self)
Add summary line with dtypes present in dataframe.
Add summary line with dtypes present in dataframe.
[ "Add", "summary", "line", "with", "dtypes", "present", "in", "dataframe", "." ]
def add_dtypes_line(self) -> None: """Add summary line with dtypes present in dataframe.""" collected_dtypes = [ f"{key}({val:d})" for key, val in sorted(self.dtype_counts.items()) ] self._lines.append(f"dtypes: {', '.join(collected_dtypes)}")
[ "def", "add_dtypes_line", "(", "self", ")", "->", "None", ":", "collected_dtypes", "=", "[", "f\"{key}({val:d})\"", "for", "key", ",", "val", "in", "sorted", "(", "self", ".", "dtype_counts", ".", "items", "(", ")", ")", "]", "self", ".", "_lines", ".", "append", "(", "f\"dtypes: {', '.join(collected_dtypes)}\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L451-L456
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/fractions.py
python
gcd
(a, b)
return a
Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive).
Calculate the Greatest Common Divisor of a and b.
[ "Calculate", "the", "Greatest", "Common", "Divisor", "of", "a", "and", "b", "." ]
def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a, b = b, a%b return a
[ "def", "gcd", "(", "a", ",", "b", ")", ":", "while", "b", ":", "a", ",", "b", "=", "b", ",", "a", "%", "b", "return", "a" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/fractions.py#L18-L26
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/signal/filter_design.py
python
cheby2
(N, rs, Wn, btype='low', analog=False, output='ba')
return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog, output=output, ftype='cheby2')
Chebyshev type II digital and analog filter design. Design an Nth-order digital or analog Chebyshev type II filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. rs : float The minimum attenuation required in the stop band. Specified in decibels, as a positive number. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For Type II filters, this is the point in the transition band at which the gain first reaches -`rs`. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- cheb2ord, cheb2ap Notes ----- The Chebyshev type II filter maximizes the rate of cutoff between the frequency response's passband and stopband, at the expense of ripple in the stopband and increased ringing in the step response. Type II filters do not roll off as fast as Type I (`cheby1`). The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev Type II frequency response (rs=40)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-40, color='green') # rs >>> plt.show()
Chebyshev type II digital and analog filter design.
[ "Chebyshev", "type", "II", "digital", "and", "analog", "filter", "design", "." ]
def cheby2(N, rs, Wn, btype='low', analog=False, output='ba'): """ Chebyshev type II digital and analog filter design. Design an Nth-order digital or analog Chebyshev type II filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. rs : float The minimum attenuation required in the stop band. Specified in decibels, as a positive number. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For Type II filters, this is the point in the transition band at which the gain first reaches -`rs`. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- cheb2ord, cheb2ap Notes ----- The Chebyshev type II filter maximizes the rate of cutoff between the frequency response's passband and stopband, at the expense of ripple in the stopband and increased ringing in the step response. Type II filters do not roll off as fast as Type I (`cheby1`). The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev Type II frequency response (rs=40)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-40, color='green') # rs >>> plt.show() """ return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog, output=output, ftype='cheby2')
[ "def", "cheby2", "(", "N", ",", "rs", ",", "Wn", ",", "btype", "=", "'low'", ",", "analog", "=", "False", ",", "output", "=", "'ba'", ")", ":", "return", "iirfilter", "(", "N", ",", "Wn", ",", "rs", "=", "rs", ",", "btype", "=", "btype", ",", "analog", "=", "analog", ",", "output", "=", "output", ",", "ftype", "=", "'cheby2'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/filter_design.py#L2203-L2281
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
src/EnergyPlus/api/datatransfer.py
python
DataExchange.today_weather_outdoor_relative_humidity_at_time
(self, state: c_void_p, hour: int, time_step_number: int)
return self.api.todayWeatherOutRelativeHumidityAtTime(state, hour, time_step_number)
Gets the specified weather data at the specified hour and time step index within that hour :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`. :param hour: Integer hour of day (0 to 23) :param time_step_number: Time step index in hour, from 1 to the number of zone time steps per hour :return: Value of the weather condition at the specified time
Gets the specified weather data at the specified hour and time step index within that hour
[ "Gets", "the", "specified", "weather", "data", "at", "the", "specified", "hour", "and", "time", "step", "index", "within", "that", "hour" ]
def today_weather_outdoor_relative_humidity_at_time(self, state: c_void_p, hour: int, time_step_number: int) -> float: """ Gets the specified weather data at the specified hour and time step index within that hour :param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`. :param hour: Integer hour of day (0 to 23) :param time_step_number: Time step index in hour, from 1 to the number of zone time steps per hour :return: Value of the weather condition at the specified time """ return self.api.todayWeatherOutRelativeHumidityAtTime(state, hour, time_step_number)
[ "def", "today_weather_outdoor_relative_humidity_at_time", "(", "self", ",", "state", ":", "c_void_p", ",", "hour", ":", "int", ",", "time_step_number", ":", "int", ")", "->", "float", ":", "return", "self", ".", "api", ".", "todayWeatherOutRelativeHumidityAtTime", "(", "state", ",", "hour", ",", "time_step_number", ")" ]
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/datatransfer.py#L1175-L1185
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/saving/saved_model/save.py
python
_reset_layer_losses
(parent_layer)
return losses_dict
Resets losses of layer and its sublayers, and returns original losses.
Resets losses of layer and its sublayers, and returns original losses.
[ "Resets", "losses", "of", "layer", "and", "its", "sublayers", "and", "returns", "original", "losses", "." ]
def _reset_layer_losses(parent_layer): """Resets losses of layer and its sublayers, and returns original losses.""" losses_dict = {} for layer in _list_all_layers(parent_layer) + [parent_layer]: losses_dict[layer] = {'losses': layer._losses[:], 'eager_losses': layer._eager_losses[:]} with trackable.no_automatic_dependency_tracking_scope(layer): layer._losses = [] layer._eager_losses = [] return losses_dict
[ "def", "_reset_layer_losses", "(", "parent_layer", ")", ":", "losses_dict", "=", "{", "}", "for", "layer", "in", "_list_all_layers", "(", "parent_layer", ")", "+", "[", "parent_layer", "]", ":", "losses_dict", "[", "layer", "]", "=", "{", "'losses'", ":", "layer", ".", "_losses", "[", ":", "]", ",", "'eager_losses'", ":", "layer", ".", "_eager_losses", "[", ":", "]", "}", "with", "trackable", ".", "no_automatic_dependency_tracking_scope", "(", "layer", ")", ":", "layer", ".", "_losses", "=", "[", "]", "layer", ".", "_eager_losses", "=", "[", "]", "return", "losses_dict" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/saving/saved_model/save.py#L372-L381
NERSC/timemory
431912b360ff50d1a160d7826e2eea04fbd1037f
scripts/gprof2dot.py
python
Profile._tarjan
(self, function, order, stack, data)
return order
Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
Tarjan's strongly connected components algorithm.
[ "Tarjan", "s", "strongly", "connected", "components", "algorithm", "." ]
def _tarjan(self, function, order, stack, data): """Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm """ try: func_data = data[function.id] return order except KeyError: func_data = self._TarjanData(order) data[function.id] = func_data order += 1 pos = len(stack) stack.append(function) func_data.onstack = True for call in compat_itervalues(function.calls): try: callee_data = data[call.callee_id] if callee_data.onstack: func_data.lowlink = min(func_data.lowlink, callee_data.order) except KeyError: callee = self.functions[call.callee_id] order = self._tarjan(callee, order, stack, data) callee_data = data[call.callee_id] func_data.lowlink = min(func_data.lowlink, callee_data.lowlink) if func_data.lowlink == func_data.order: # Strongly connected component found members = stack[pos:] del stack[pos:] if len(members) > 1: cycle = Cycle() for member in members: cycle.add_function(member) data[member.id].onstack = False else: for member in members: data[member.id].onstack = False return order
[ "def", "_tarjan", "(", "self", ",", "function", ",", "order", ",", "stack", ",", "data", ")", ":", "try", ":", "func_data", "=", "data", "[", "function", ".", "id", "]", "return", "order", "except", "KeyError", ":", "func_data", "=", "self", ".", "_TarjanData", "(", "order", ")", "data", "[", "function", ".", "id", "]", "=", "func_data", "order", "+=", "1", "pos", "=", "len", "(", "stack", ")", "stack", ".", "append", "(", "function", ")", "func_data", ".", "onstack", "=", "True", "for", "call", "in", "compat_itervalues", "(", "function", ".", "calls", ")", ":", "try", ":", "callee_data", "=", "data", "[", "call", ".", "callee_id", "]", "if", "callee_data", ".", "onstack", ":", "func_data", ".", "lowlink", "=", "min", "(", "func_data", ".", "lowlink", ",", "callee_data", ".", "order", ")", "except", "KeyError", ":", "callee", "=", "self", ".", "functions", "[", "call", ".", "callee_id", "]", "order", "=", "self", ".", "_tarjan", "(", "callee", ",", "order", ",", "stack", ",", "data", ")", "callee_data", "=", "data", "[", "call", ".", "callee_id", "]", "func_data", ".", "lowlink", "=", "min", "(", "func_data", ".", "lowlink", ",", "callee_data", ".", "lowlink", ")", "if", "func_data", ".", "lowlink", "==", "func_data", ".", "order", ":", "# Strongly connected component found", "members", "=", "stack", "[", "pos", ":", "]", "del", "stack", "[", "pos", ":", "]", "if", "len", "(", "members", ")", ">", "1", ":", "cycle", "=", "Cycle", "(", ")", "for", "member", "in", "members", ":", "cycle", ".", "add_function", "(", "member", ")", "data", "[", "member", ".", "id", "]", ".", "onstack", "=", "False", "else", ":", "for", "member", "in", "members", ":", "data", "[", "member", ".", "id", "]", ".", "onstack", "=", "False", "return", "order" ]
https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/scripts/gprof2dot.py#L402-L441
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py
python
GraphRewriter.remove_redundant_quantization
(self, old_graph)
return self.output_graph
Removes unneeded pairs of quantize/dequantize ops from the graph. This is a bit of a tricky function, because it's attempting to spot the pattern of dequantizing from eight-bit up to float, and then immediately quantizing back down to eight bits again, that's introduced by previous passes that do 'key-hole' conversions of individual nodes but have to convert back to float to match the previous output interface, since they don't know that the next op can handle quantized tensors. It works by: - Looking for Quantize nodes. - Checking to see if their first input is a Dequantize node. - Seeing if their min/max inputs come from Min/Max nodes. - Making sure those Min/Max nodes are being fed from the same Dequantize. - Or that the Min is indirectly being fed from the same Dequantize as Max. - Making sure the Dequantize is going through a Reshape (which we add during the previous pass when we create the quantize sub-graph). - Looking for the dims Const op for the Min/Max dims. If all of these conditions are met, then it's a sub-graph pattern that we know how to optimize out (and is likely the common one we've introduced). We then rewire the graph to skip it entirely, and then rely on the dead node removal pass to get rid of any nodes that are no longer needed. Args: old_graph: The model we'll be stripping redundant nodes from. Returns: A graph with the unnecessary nodes removed. Raises: ValueError: Two nodes with the same name were found in the graph.
Removes unneeded pairs of quantize/dequantize ops from the graph.
[ "Removes", "unneeded", "pairs", "of", "quantize", "/", "dequantize", "ops", "from", "the", "graph", "." ]
def remove_redundant_quantization(self, old_graph): """Removes unneeded pairs of quantize/dequantize ops from the graph. This is a bit of a tricky function, because it's attempting to spot the pattern of dequantizing from eight-bit up to float, and then immediately quantizing back down to eight bits again, that's introduced by previous passes that do 'key-hole' conversions of individual nodes but have to convert back to float to match the previous output interface, since they don't know that the next op can handle quantized tensors. It works by: - Looking for Quantize nodes. - Checking to see if their first input is a Dequantize node. - Seeing if their min/max inputs come from Min/Max nodes. - Making sure those Min/Max nodes are being fed from the same Dequantize. - Or that the Min is indirectly being fed from the same Dequantize as Max. - Making sure the Dequantize is going through a Reshape (which we add during the previous pass when we create the quantize sub-graph). - Looking for the dims Const op for the Min/Max dims. If all of these conditions are met, then it's a sub-graph pattern that we know how to optimize out (and is likely the common one we've introduced). We then rewire the graph to skip it entirely, and then rely on the dead node removal pass to get rid of any nodes that are no longer needed. Args: old_graph: The model we'll be stripping redundant nodes from. Returns: A graph with the unnecessary nodes removed. Raises: ValueError: Two nodes with the same name were found in the graph. """ old_nodes_map = self.create_nodes_map(old_graph) self.output_graph = tf.GraphDef() inputs_to_rename = {} # We go through all the nodes, looking for any that match the patterns we # know how to optimize away. for node in old_graph.node: # We always start with a Quantize node, and examine its inputs to see if # they are in a form that can be removed. if node.op not in ["Quantize", "QuantizeV2"]: continue dequantize_node_name = node_name_from_input(node.input[0]) if dequantize_node_name not in old_nodes_map: raise ValueError("Input node name '" + dequantize_node_name + "' not found in node '" + node.name + "'") dequantize_node = old_nodes_map[dequantize_node_name] # Do we have a Dequantize feeding in, with the same type as the Quantize? if dequantize_node.op != "Dequantize": continue if node.attr["T"] != dequantize_node.attr["T"]: continue # Now look at the other inputs, and ensure they're Min/Max nodes. min_node_name = node_name_from_input(node.input[1]) max_node_name = node_name_from_input(node.input[2]) min_node = old_nodes_map[min_node_name] max_node = old_nodes_map[max_node_name] is_min_right_type = (min_node.op in ["Min", "Dequantize"]) is_max_right_type = (max_node.op in ["Max", "Dequantize"]) if not is_min_right_type or not is_max_right_type: print("Didn't find expected types on inputs : %s, %s." % ( min_node.op, max_node.op)) continue min_node_input_name = node_name_from_input(min_node.input[0]) max_node_input_name = node_name_from_input(max_node.input[0]) # There are two different patterns for Min nodes we can recognize, one # where the input comes directly from the same one as the Max, and # another where we run it through another Min first, so check for both. is_same_input = False if min_node_input_name == max_node_input_name: is_same_input = True else: first_min_node_input = old_nodes_map[min_node_input_name] if first_min_node_input.op == "Concat": second_min_node_name = node_name_from_input( first_min_node_input.input[1]) second_min_node = old_nodes_map[second_min_node_name] if second_min_node.op == "Min": second_min_node_input_name = node_name_from_input( second_min_node.input[0]) is_same_input = (second_min_node_input_name == max_node_input_name) if not is_same_input: print("Different min/max inputs: " + min_node_input_name) continue # We recognize this pattern, so mark the graph edges to be rewired to # route around it entirely, since we know it's a no-op. dequantize_source_name = node_name_from_input(dequantize_node.input[0]) node_tensor_name = ensure_tensor_name_has_port(node.name) min_tensor_name = node.name + ":1" max_tensor_name = node.name + ":2" inputs_to_rename[node_tensor_name] = dequantize_source_name inputs_to_rename[min_tensor_name] = dequantize_node.input[1] inputs_to_rename[max_tensor_name] = dequantize_node.input[2] # Finally we apply all the rewiring we've marked to the graph. for node in old_graph.node: for index, input_full_name in enumerate(node.input): input_name = ensure_tensor_name_has_port(input_full_name) if input_name in inputs_to_rename: node.input[index] = inputs_to_rename[input_name] self.add_output_graph_node(node) return self.output_graph
[ "def", "remove_redundant_quantization", "(", "self", ",", "old_graph", ")", ":", "old_nodes_map", "=", "self", ".", "create_nodes_map", "(", "old_graph", ")", "self", ".", "output_graph", "=", "tf", ".", "GraphDef", "(", ")", "inputs_to_rename", "=", "{", "}", "# We go through all the nodes, looking for any that match the patterns we", "# know how to optimize away.", "for", "node", "in", "old_graph", ".", "node", ":", "# We always start with a Quantize node, and examine its inputs to see if", "# they are in a form that can be removed.", "if", "node", ".", "op", "not", "in", "[", "\"Quantize\"", ",", "\"QuantizeV2\"", "]", ":", "continue", "dequantize_node_name", "=", "node_name_from_input", "(", "node", ".", "input", "[", "0", "]", ")", "if", "dequantize_node_name", "not", "in", "old_nodes_map", ":", "raise", "ValueError", "(", "\"Input node name '\"", "+", "dequantize_node_name", "+", "\"' not found in node '\"", "+", "node", ".", "name", "+", "\"'\"", ")", "dequantize_node", "=", "old_nodes_map", "[", "dequantize_node_name", "]", "# Do we have a Dequantize feeding in, with the same type as the Quantize?", "if", "dequantize_node", ".", "op", "!=", "\"Dequantize\"", ":", "continue", "if", "node", ".", "attr", "[", "\"T\"", "]", "!=", "dequantize_node", ".", "attr", "[", "\"T\"", "]", ":", "continue", "# Now look at the other inputs, and ensure they're Min/Max nodes.", "min_node_name", "=", "node_name_from_input", "(", "node", ".", "input", "[", "1", "]", ")", "max_node_name", "=", "node_name_from_input", "(", "node", ".", "input", "[", "2", "]", ")", "min_node", "=", "old_nodes_map", "[", "min_node_name", "]", "max_node", "=", "old_nodes_map", "[", "max_node_name", "]", "is_min_right_type", "=", "(", "min_node", ".", "op", "in", "[", "\"Min\"", ",", "\"Dequantize\"", "]", ")", "is_max_right_type", "=", "(", "max_node", ".", "op", "in", "[", "\"Max\"", ",", "\"Dequantize\"", "]", ")", "if", "not", "is_min_right_type", "or", "not", "is_max_right_type", ":", "print", "(", "\"Didn't find expected types on inputs : %s, %s.\"", "%", "(", "min_node", ".", "op", ",", "max_node", ".", "op", ")", ")", "continue", "min_node_input_name", "=", "node_name_from_input", "(", "min_node", ".", "input", "[", "0", "]", ")", "max_node_input_name", "=", "node_name_from_input", "(", "max_node", ".", "input", "[", "0", "]", ")", "# There are two different patterns for Min nodes we can recognize, one", "# where the input comes directly from the same one as the Max, and", "# another where we run it through another Min first, so check for both.", "is_same_input", "=", "False", "if", "min_node_input_name", "==", "max_node_input_name", ":", "is_same_input", "=", "True", "else", ":", "first_min_node_input", "=", "old_nodes_map", "[", "min_node_input_name", "]", "if", "first_min_node_input", ".", "op", "==", "\"Concat\"", ":", "second_min_node_name", "=", "node_name_from_input", "(", "first_min_node_input", ".", "input", "[", "1", "]", ")", "second_min_node", "=", "old_nodes_map", "[", "second_min_node_name", "]", "if", "second_min_node", ".", "op", "==", "\"Min\"", ":", "second_min_node_input_name", "=", "node_name_from_input", "(", "second_min_node", ".", "input", "[", "0", "]", ")", "is_same_input", "=", "(", "second_min_node_input_name", "==", "max_node_input_name", ")", "if", "not", "is_same_input", ":", "print", "(", "\"Different min/max inputs: \"", "+", "min_node_input_name", ")", "continue", "# We recognize this pattern, so mark the graph edges to be rewired to", "# route around it entirely, since we know it's a no-op.", "dequantize_source_name", "=", "node_name_from_input", "(", "dequantize_node", ".", "input", "[", "0", "]", ")", "node_tensor_name", "=", "ensure_tensor_name_has_port", "(", "node", ".", "name", ")", "min_tensor_name", "=", "node", ".", "name", "+", "\":1\"", "max_tensor_name", "=", "node", ".", "name", "+", "\":2\"", "inputs_to_rename", "[", "node_tensor_name", "]", "=", "dequantize_source_name", "inputs_to_rename", "[", "min_tensor_name", "]", "=", "dequantize_node", ".", "input", "[", "1", "]", "inputs_to_rename", "[", "max_tensor_name", "]", "=", "dequantize_node", ".", "input", "[", "2", "]", "# Finally we apply all the rewiring we've marked to the graph.", "for", "node", "in", "old_graph", ".", "node", ":", "for", "index", ",", "input_full_name", "in", "enumerate", "(", "node", ".", "input", ")", ":", "input_name", "=", "ensure_tensor_name_has_port", "(", "input_full_name", ")", "if", "input_name", "in", "inputs_to_rename", ":", "node", ".", "input", "[", "index", "]", "=", "inputs_to_rename", "[", "input_name", "]", "self", ".", "add_output_graph_node", "(", "node", ")", "return", "self", ".", "output_graph" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L804-L904
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
PPOCRLabel/PPOCRLabel.py
python
MainWindow.newShape
(self, value=True)
Pop-up and give focus to the label editor. position MUST be in global coordinates.
Pop-up and give focus to the label editor.
[ "Pop", "-", "up", "and", "give", "focus", "to", "the", "label", "editor", "." ]
def newShape(self, value=True): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if len(self.labelHist) > 0: self.labelDialog = LabelDialog( parent=self, listItem=self.labelHist) if value: text = self.labelDialog.popUp(text=self.prevLabelText) self.lastLabel = text else: text = self.prevLabelText if text is not None: self.prevLabelText = self.stringBundle.getString('tempLabel') # generate_color = generateColorByText(text) shape = self.canvas.setLastLabel(text, None, None)#generate_color, generate_color self.addLabel(shape) if self.beginner(): # Switch to edit mode. self.canvas.setEditing(True) self.actions.create.setEnabled(True) self.actions.undoLastPoint.setEnabled(False) self.actions.undo.setEnabled(True) else: self.actions.editMode.setEnabled(True) self.setDirty() else: # self.canvas.undoLastLine() self.canvas.resetAllLines()
[ "def", "newShape", "(", "self", ",", "value", "=", "True", ")", ":", "if", "len", "(", "self", ".", "labelHist", ")", ">", "0", ":", "self", ".", "labelDialog", "=", "LabelDialog", "(", "parent", "=", "self", ",", "listItem", "=", "self", ".", "labelHist", ")", "if", "value", ":", "text", "=", "self", ".", "labelDialog", ".", "popUp", "(", "text", "=", "self", ".", "prevLabelText", ")", "self", ".", "lastLabel", "=", "text", "else", ":", "text", "=", "self", ".", "prevLabelText", "if", "text", "is", "not", "None", ":", "self", ".", "prevLabelText", "=", "self", ".", "stringBundle", ".", "getString", "(", "'tempLabel'", ")", "# generate_color = generateColorByText(text)", "shape", "=", "self", ".", "canvas", ".", "setLastLabel", "(", "text", ",", "None", ",", "None", ")", "#generate_color, generate_color", "self", ".", "addLabel", "(", "shape", ")", "if", "self", ".", "beginner", "(", ")", ":", "# Switch to edit mode.", "self", ".", "canvas", ".", "setEditing", "(", "True", ")", "self", ".", "actions", ".", "create", ".", "setEnabled", "(", "True", ")", "self", ".", "actions", ".", "undoLastPoint", ".", "setEnabled", "(", "False", ")", "self", ".", "actions", ".", "undo", ".", "setEnabled", "(", "True", ")", "else", ":", "self", ".", "actions", ".", "editMode", ".", "setEnabled", "(", "True", ")", "self", ".", "setDirty", "(", ")", "else", ":", "# self.canvas.undoLastLine()", "self", ".", "canvas", ".", "resetAllLines", "(", ")" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/PPOCRLabel/PPOCRLabel.py#L1185-L1216
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
PyApp.WakeUpIdle
(*args, **kwargs)
return _core_.PyApp_WakeUpIdle(*args, **kwargs)
WakeUpIdle(self) Make sure that idle events are sent again. :see: `wx.WakeUpIdle`
WakeUpIdle(self)
[ "WakeUpIdle", "(", "self", ")" ]
def WakeUpIdle(*args, **kwargs): """ WakeUpIdle(self) Make sure that idle events are sent again. :see: `wx.WakeUpIdle` """ return _core_.PyApp_WakeUpIdle(*args, **kwargs)
[ "def", "WakeUpIdle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_WakeUpIdle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L7926-L7933
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Simulator.getTime
(self)
return _robotsim.Simulator_getTime(self)
r""" Returns the simulation time.
r""" Returns the simulation time.
[ "r", "Returns", "the", "simulation", "time", "." ]
def getTime(self) ->float: r""" Returns the simulation time. """ return _robotsim.Simulator_getTime(self)
[ "def", "getTime", "(", "self", ")", "->", "float", ":", "return", "_robotsim", ".", "Simulator_getTime", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7864-L7869
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/http/cookiejar.py
python
CookiePolicy.set_ok
(self, cookie, request)
Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself.
Return true if (and only if) cookie should be accepted from server.
[ "Return", "true", "if", "(", "and", "only", "if", ")", "cookie", "should", "be", "accepted", "from", "server", "." ]
def set_ok(self, cookie, request): """Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself. """ raise NotImplementedError()
[ "def", "set_ok", "(", "self", ",", "cookie", ",", "request", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/cookiejar.py#L843-L850
fasiondog/hikyuu
842751aa25283f9fdafc6f560ea262f79e67a307
hikyuu/draw/drawplot/bokeh_draw.py
python
mkplot
(kdata, new=True, axes=None, colorup='r', colordown='g', ticksize=3)
return None
绘制美式K线图 :param KData kdata: K线数据 :param bool new: 是否在新窗口中显示,只在没有指定axes时生效 :param axes: 指定的坐标轴 :param colorup: the color of the lines where close >= open :param colordown: the color of the lines where close < open :param ticksize: open/close tick marker in points
绘制美式K线图 :param KData kdata: K线数据 :param bool new: 是否在新窗口中显示,只在没有指定axes时生效 :param axes: 指定的坐标轴 :param colorup: the color of the lines where close >= open :param colordown: the color of the lines where close < open :param ticksize: open/close tick marker in points
[ "绘制美式K线图", ":", "param", "KData", "kdata", ":", "K线数据", ":", "param", "bool", "new", ":", "是否在新窗口中显示,只在没有指定axes时生效", ":", "param", "axes", ":", "指定的坐标轴", ":", "param", "colorup", ":", "the", "color", "of", "the", "lines", "where", "close", ">", "=", "open", ":", "param", "colordown", ":", "the", "color", "of", "the", "lines", "where", "close", "<", "open", ":", "param", "ticksize", ":", "open", "/", "close", "tick", "marker", "in", "points" ]
def mkplot(kdata, new=True, axes=None, colorup='r', colordown='g', ticksize=3): """绘制美式K线图 :param KData kdata: K线数据 :param bool new: 是否在新窗口中显示,只在没有指定axes时生效 :param axes: 指定的坐标轴 :param colorup: the color of the lines where close >= open :param colordown: the color of the lines where close < open :param ticksize: open/close tick marker in points """ print("Bokeh 暂不支持绘制美式K线图, 请使用 matplotlib") return None
[ "def", "mkplot", "(", "kdata", ",", "new", "=", "True", ",", "axes", "=", "None", ",", "colorup", "=", "'r'", ",", "colordown", "=", "'g'", ",", "ticksize", "=", "3", ")", ":", "print", "(", "\"Bokeh 暂不支持绘制美式K线图, 请使用 matplotlib\")", "", "return", "None" ]
https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/draw/drawplot/bokeh_draw.py#L212-L223
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/distributed_c10d.py
python
all_reduce
(tensor, op=ReduceOp.SUM, group=None, async_op=False)
Reduces the tensor data across all machines in such a way that all get the final result. After the call ``tensor`` is going to be bitwise identical in all processes. Complex tensors are supported. Args: tensor (Tensor): Input and output of the collective. The function operates in-place. op (optional): One of the values from ``torch.distributed.ReduceOp`` enum. Specifies an operation used for element-wise reductions. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group Examples: >>> # All tensors below are of torch.int64 type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank >>> tensor tensor([1, 2]) # Rank 0 tensor([3, 4]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4, 6]) # Rank 0 tensor([4, 6]) # Rank 1 >>> # All tensors below are of torch.cfloat type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j) >>> tensor tensor([1.+1.j, 2.+2.j]) # Rank 0 tensor([3.+3.j, 4.+4.j]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4.+4.j, 6.+6.j]) # Rank 0 tensor([4.+4.j, 6.+6.j]) # Rank 1
Reduces the tensor data across all machines in such a way that all get the final result.
[ "Reduces", "the", "tensor", "data", "across", "all", "machines", "in", "such", "a", "way", "that", "all", "get", "the", "final", "result", "." ]
def all_reduce(tensor, op=ReduceOp.SUM, group=None, async_op=False): """ Reduces the tensor data across all machines in such a way that all get the final result. After the call ``tensor`` is going to be bitwise identical in all processes. Complex tensors are supported. Args: tensor (Tensor): Input and output of the collective. The function operates in-place. op (optional): One of the values from ``torch.distributed.ReduceOp`` enum. Specifies an operation used for element-wise reductions. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. async_op (bool, optional): Whether this op should be an async op Returns: Async work handle, if async_op is set to True. None, if not async_op or if not part of the group Examples: >>> # All tensors below are of torch.int64 type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank >>> tensor tensor([1, 2]) # Rank 0 tensor([3, 4]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4, 6]) # Rank 0 tensor([4, 6]) # Rank 1 >>> # All tensors below are of torch.cfloat type. >>> # We have 2 process groups, 2 ranks. >>> tensor = torch.tensor([1+1j, 2+2j], dtype=torch.cfloat) + 2 * rank * (1+1j) >>> tensor tensor([1.+1.j, 2.+2.j]) # Rank 0 tensor([3.+3.j, 4.+4.j]) # Rank 1 >>> dist.all_reduce(tensor, op=ReduceOp.SUM) >>> tensor tensor([4.+4.j, 6.+6.j]) # Rank 0 tensor([4.+4.j, 6.+6.j]) # Rank 1 """ _check_single_tensor(tensor, "tensor") if _rank_not_in_group(group): _warn_not_in_group("all_reduce") return if tensor.is_complex(): if not supports_complex(op): raise RuntimeError(f"all_reduce does not support {op} on complex tensors") tensor = torch.view_as_real(tensor) opts = AllreduceOptions() opts.reduceOp = op if group is None: default_pg = _get_default_group() work = default_pg.allreduce([tensor], opts) else: work = group.allreduce([tensor], opts) if async_op: return work else: work.wait()
[ "def", "all_reduce", "(", "tensor", ",", "op", "=", "ReduceOp", ".", "SUM", ",", "group", "=", "None", ",", "async_op", "=", "False", ")", ":", "_check_single_tensor", "(", "tensor", ",", "\"tensor\"", ")", "if", "_rank_not_in_group", "(", "group", ")", ":", "_warn_not_in_group", "(", "\"all_reduce\"", ")", "return", "if", "tensor", ".", "is_complex", "(", ")", ":", "if", "not", "supports_complex", "(", "op", ")", ":", "raise", "RuntimeError", "(", "f\"all_reduce does not support {op} on complex tensors\"", ")", "tensor", "=", "torch", ".", "view_as_real", "(", "tensor", ")", "opts", "=", "AllreduceOptions", "(", ")", "opts", ".", "reduceOp", "=", "op", "if", "group", "is", "None", ":", "default_pg", "=", "_get_default_group", "(", ")", "work", "=", "default_pg", ".", "allreduce", "(", "[", "tensor", "]", ",", "opts", ")", "else", ":", "work", "=", "group", ".", "allreduce", "(", "[", "tensor", "]", ",", "opts", ")", "if", "async_op", ":", "return", "work", "else", ":", "work", ".", "wait", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L1253-L1321
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/tools/grokdump.py
python
InspectionShell.do_disassemble
(self, args)
Unassemble memory in the region [address, address + size). If the size is not specified, a default value of 32 bytes is used. Synopsis: u 0x<address> 0x<size>
Unassemble memory in the region [address, address + size).
[ "Unassemble", "memory", "in", "the", "region", "[", "address", "address", "+", "size", ")", "." ]
def do_disassemble(self, args): """ Unassemble memory in the region [address, address + size). If the size is not specified, a default value of 32 bytes is used. Synopsis: u 0x<address> 0x<size> """ if len(args) != 0: args = args.split(' ') self.u_start = self.ParseAddressExpr(args[0]) self.u_size = self.ParseAddressExpr(args[1]) if len(args) > 1 else 0x20 skip = False else: # Skip the first instruction if we reuse the last address. skip = True if not self.reader.IsValidAddress(self.u_start): print("Address %s is not contained within the minidump!" % ( self.reader.FormatIntPtr(self.u_start))) return lines = self.reader.GetDisasmLines(self.u_start, self.u_size) if len(lines) == 0: print("Address %s could not be disassembled!" % ( self.reader.FormatIntPtr(self.u_start))) print(" Could not disassemble using %s." % OBJDUMP_BIN) print(" Pass path to architecture specific objdump via --objdump?") return for line in lines: if skip: skip = False continue print(FormatDisasmLine(self.u_start, self.heap, line)) # Set the next start address = last line self.u_start += lines[-1][0] print()
[ "def", "do_disassemble", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "0", ":", "args", "=", "args", ".", "split", "(", "' '", ")", "self", ".", "u_start", "=", "self", ".", "ParseAddressExpr", "(", "args", "[", "0", "]", ")", "self", ".", "u_size", "=", "self", ".", "ParseAddressExpr", "(", "args", "[", "1", "]", ")", "if", "len", "(", "args", ")", ">", "1", "else", "0x20", "skip", "=", "False", "else", ":", "# Skip the first instruction if we reuse the last address.", "skip", "=", "True", "if", "not", "self", ".", "reader", ".", "IsValidAddress", "(", "self", ".", "u_start", ")", ":", "print", "(", "\"Address %s is not contained within the minidump!\"", "%", "(", "self", ".", "reader", ".", "FormatIntPtr", "(", "self", ".", "u_start", ")", ")", ")", "return", "lines", "=", "self", ".", "reader", ".", "GetDisasmLines", "(", "self", ".", "u_start", ",", "self", ".", "u_size", ")", "if", "len", "(", "lines", ")", "==", "0", ":", "print", "(", "\"Address %s could not be disassembled!\"", "%", "(", "self", ".", "reader", ".", "FormatIntPtr", "(", "self", ".", "u_start", ")", ")", ")", "print", "(", "\" Could not disassemble using %s.\"", "%", "OBJDUMP_BIN", ")", "print", "(", "\" Pass path to architecture specific objdump via --objdump?\"", ")", "return", "for", "line", "in", "lines", ":", "if", "skip", ":", "skip", "=", "False", "continue", "print", "(", "FormatDisasmLine", "(", "self", ".", "u_start", ",", "self", ".", "heap", ",", "line", ")", ")", "# Set the next start address = last line", "self", ".", "u_start", "+=", "lines", "[", "-", "1", "]", "[", "0", "]", "print", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/grokdump.py#L3740-L3774
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/integrate/_ivp/base.py
python
check_arguments
(fun, y0, support_complex)
return fun_wrapped, y0
Helper function for checking arguments common to all solvers.
Helper function for checking arguments common to all solvers.
[ "Helper", "function", "for", "checking", "arguments", "common", "to", "all", "solvers", "." ]
def check_arguments(fun, y0, support_complex): """Helper function for checking arguments common to all solvers.""" y0 = np.asarray(y0) if np.issubdtype(y0.dtype, np.complexfloating): if not support_complex: raise ValueError("`y0` is complex, but the chosen solver does " "not support integration in a complex domain.") dtype = complex else: dtype = float y0 = y0.astype(dtype, copy=False) if y0.ndim != 1: raise ValueError("`y0` must be 1-dimensional.") def fun_wrapped(t, y): return np.asarray(fun(t, y), dtype=dtype) return fun_wrapped, y0
[ "def", "check_arguments", "(", "fun", ",", "y0", ",", "support_complex", ")", ":", "y0", "=", "np", ".", "asarray", "(", "y0", ")", "if", "np", ".", "issubdtype", "(", "y0", ".", "dtype", ",", "np", ".", "complexfloating", ")", ":", "if", "not", "support_complex", ":", "raise", "ValueError", "(", "\"`y0` is complex, but the chosen solver does \"", "\"not support integration in a complex domain.\"", ")", "dtype", "=", "complex", "else", ":", "dtype", "=", "float", "y0", "=", "y0", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", "if", "y0", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"`y0` must be 1-dimensional.\"", ")", "def", "fun_wrapped", "(", "t", ",", "y", ")", ":", "return", "np", ".", "asarray", "(", "fun", "(", "t", ",", "y", ")", ",", "dtype", "=", "dtype", ")", "return", "fun_wrapped", ",", "y0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/integrate/_ivp/base.py#L5-L23
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py
python
CodeGenerator.pop_parameter_definitions
(self)
Pops the current parameter definitions set.
Pops the current parameter definitions set.
[ "Pops", "the", "current", "parameter", "definitions", "set", "." ]
def pop_parameter_definitions(self): """Pops the current parameter definitions set.""" self._param_def_block.pop()
[ "def", "pop_parameter_definitions", "(", "self", ")", ":", "self", ".", "_param_def_block", ".", "pop", "(", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py#L623-L625
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xpathParserContext.xpathRoundFunction
(self, nargs)
Implement the round() XPath function number round(number) The round function returns the number that is closest to the argument and that is an integer. If there are two such numbers, then the one that is even is returned.
Implement the round() XPath function number round(number) The round function returns the number that is closest to the argument and that is an integer. If there are two such numbers, then the one that is even is returned.
[ "Implement", "the", "round", "()", "XPath", "function", "number", "round", "(", "number", ")", "The", "round", "function", "returns", "the", "number", "that", "is", "closest", "to", "the", "argument", "and", "that", "is", "an", "integer", ".", "If", "there", "are", "two", "such", "numbers", "then", "the", "one", "that", "is", "even", "is", "returned", "." ]
def xpathRoundFunction(self, nargs): """Implement the round() XPath function number round(number) The round function returns the number that is closest to the argument and that is an integer. If there are two such numbers, then the one that is even is returned. """ libxml2mod.xmlXPathRoundFunction(self._o, nargs)
[ "def", "xpathRoundFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathRoundFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7772-L7777
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/parfor.py
python
ParforDiagnostics.sort_pf_by_line
(self, pf_id, parfors_simple)
return line
pd_id - the parfors id parfors_simple - the simple parfors map
pd_id - the parfors id parfors_simple - the simple parfors map
[ "pd_id", "-", "the", "parfors", "id", "parfors_simple", "-", "the", "simple", "parfors", "map" ]
def sort_pf_by_line(self, pf_id, parfors_simple): """ pd_id - the parfors id parfors_simple - the simple parfors map """ # this sorts parfors by source line number pf = parfors_simple[pf_id][0] pattern = pf.patterns[0] line = max(0, pf.loc.line - 1) # why are these out by 1 ?! filename = self.func_ir.loc.filename nadj, nroots = self.compute_graph_info(self.nested_fusion_info) fadj, froots = self.compute_graph_info(self.fusion_info) graphs = [nadj, fadj] # If the parfor is internal, like internal prange, then the # default line number is from its location in the numba source # To get a more accurate line number, this first checks the # adjacency graph for fused parfors that might not be internal # and uses the minimum line number from there. If that fails # (case where there's just a single internal parfor) the IR # is walked backwards from the parfor location and the first non # parfor statement line number is used. if isinstance(pattern, tuple): if pattern[1] == 'internal': reported_loc = pattern[2][1] if reported_loc.filename == filename: return max(0, reported_loc.line - 1) else: # first recurse and check the adjacency list for # something that is not an in internal parfor tmp = [] for adj in graphs: if adj: # graph may be empty, e.g. no nesting for k in adj[pf_id]: tmp.append(self.sort_pf_by_line(k, parfors_simple)) if tmp: return max(0, min(tmp) - 1) # second run through the parfor block to see if there's # and reference to a line number in the user source for blk in pf.loop_body.values(): for stmt in blk.body: if stmt.loc.filename == filename: return max(0, stmt.loc.line - 1) # finally run through the func_ir and look for the # first non-parfor statement prior to this one and # grab the line from that for blk in self.func_ir.blocks.values(): try: idx = blk.body.index(pf) for i in range(idx - 1, 0, -1): stmt = blk.body[i] if not isinstance(stmt, Parfor): line = max(0, stmt.loc.line - 1) break except ValueError: pass return line
[ "def", "sort_pf_by_line", "(", "self", ",", "pf_id", ",", "parfors_simple", ")", ":", "# this sorts parfors by source line number", "pf", "=", "parfors_simple", "[", "pf_id", "]", "[", "0", "]", "pattern", "=", "pf", ".", "patterns", "[", "0", "]", "line", "=", "max", "(", "0", ",", "pf", ".", "loc", ".", "line", "-", "1", ")", "# why are these out by 1 ?!", "filename", "=", "self", ".", "func_ir", ".", "loc", ".", "filename", "nadj", ",", "nroots", "=", "self", ".", "compute_graph_info", "(", "self", ".", "nested_fusion_info", ")", "fadj", ",", "froots", "=", "self", ".", "compute_graph_info", "(", "self", ".", "fusion_info", ")", "graphs", "=", "[", "nadj", ",", "fadj", "]", "# If the parfor is internal, like internal prange, then the", "# default line number is from its location in the numba source", "# To get a more accurate line number, this first checks the", "# adjacency graph for fused parfors that might not be internal", "# and uses the minimum line number from there. If that fails", "# (case where there's just a single internal parfor) the IR", "# is walked backwards from the parfor location and the first non", "# parfor statement line number is used.", "if", "isinstance", "(", "pattern", ",", "tuple", ")", ":", "if", "pattern", "[", "1", "]", "==", "'internal'", ":", "reported_loc", "=", "pattern", "[", "2", "]", "[", "1", "]", "if", "reported_loc", ".", "filename", "==", "filename", ":", "return", "max", "(", "0", ",", "reported_loc", ".", "line", "-", "1", ")", "else", ":", "# first recurse and check the adjacency list for", "# something that is not an in internal parfor", "tmp", "=", "[", "]", "for", "adj", "in", "graphs", ":", "if", "adj", ":", "# graph may be empty, e.g. no nesting", "for", "k", "in", "adj", "[", "pf_id", "]", ":", "tmp", ".", "append", "(", "self", ".", "sort_pf_by_line", "(", "k", ",", "parfors_simple", ")", ")", "if", "tmp", ":", "return", "max", "(", "0", ",", "min", "(", "tmp", ")", "-", "1", ")", "# second run through the parfor block to see if there's", "# and reference to a line number in the user source", "for", "blk", "in", "pf", ".", "loop_body", ".", "values", "(", ")", ":", "for", "stmt", "in", "blk", ".", "body", ":", "if", "stmt", ".", "loc", ".", "filename", "==", "filename", ":", "return", "max", "(", "0", ",", "stmt", ".", "loc", ".", "line", "-", "1", ")", "# finally run through the func_ir and look for the", "# first non-parfor statement prior to this one and", "# grab the line from that", "for", "blk", "in", "self", ".", "func_ir", ".", "blocks", ".", "values", "(", ")", ":", "try", ":", "idx", "=", "blk", ".", "body", ".", "index", "(", "pf", ")", "for", "i", "in", "range", "(", "idx", "-", "1", ",", "0", ",", "-", "1", ")", ":", "stmt", "=", "blk", ".", "body", "[", "i", "]", "if", "not", "isinstance", "(", "stmt", ",", "Parfor", ")", ":", "line", "=", "max", "(", "0", ",", "stmt", ".", "loc", ".", "line", "-", "1", ")", "break", "except", "ValueError", ":", "pass", "return", "line" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/parfor.py#L776-L832
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/extern/tclib.py
python
Message.SetIsHidden
(self, is_hidden)
Sets whether this message should be hidden. Args: is_hidden : 0 or 1 - if the message should be hidden, 0 otherwise
Sets whether this message should be hidden.
[ "Sets", "whether", "this", "message", "should", "be", "hidden", "." ]
def SetIsHidden(self, is_hidden): """Sets whether this message should be hidden. Args: is_hidden : 0 or 1 - if the message should be hidden, 0 otherwise """ if is_hidden not in [0, 1]: raise MessageTranslationError, "is_hidden must be 0 or 1, got %s" self.__is_hidden = is_hidden
[ "def", "SetIsHidden", "(", "self", ",", "is_hidden", ")", ":", "if", "is_hidden", "not", "in", "[", "0", ",", "1", "]", ":", "raise", "MessageTranslationError", ",", "\"is_hidden must be 0 or 1, got %s\"", "self", ".", "__is_hidden", "=", "is_hidden" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/extern/tclib.py#L439-L447
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/machines.py
python
get_encoded_buffer_from_pixbuf
(pixbuf)
return encoded_buffer
Pixbuf To Encoded Buffer
Pixbuf To Encoded Buffer
[ "Pixbuf", "To", "Encoded", "Buffer" ]
def get_encoded_buffer_from_pixbuf(pixbuf): """Pixbuf To Encoded Buffer""" io = StringIO.StringIO() pixbuf.save_to_callback(io.write, "png") encoded_buffer = base64.b64encode(io.getvalue()) return encoded_buffer
[ "def", "get_encoded_buffer_from_pixbuf", "(", "pixbuf", ")", ":", "io", "=", "StringIO", ".", "StringIO", "(", ")", "pixbuf", ".", "save_to_callback", "(", "io", ".", "write", ",", "\"png\"", ")", "encoded_buffer", "=", "base64", ".", "b64encode", "(", "io", ".", "getvalue", "(", ")", ")", "return", "encoded_buffer" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/machines.py#L56-L61
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/period.py
python
_period_array_cmp
(cls, op)
return compat.set_function_name(wrapper, opname, cls)
Wrap comparison operations to convert Period-like to PeriodDtype
Wrap comparison operations to convert Period-like to PeriodDtype
[ "Wrap", "comparison", "operations", "to", "convert", "Period", "-", "like", "to", "PeriodDtype" ]
def _period_array_cmp(cls, op): """ Wrap comparison operations to convert Period-like to PeriodDtype """ opname = '__{name}__'.format(name=op.__name__) nat_result = True if opname == '__ne__' else False def wrapper(self, other): op = getattr(self.asi8, opname) if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): return NotImplemented if is_list_like(other) and len(other) != len(self): raise ValueError("Lengths must match") if isinstance(other, Period): self._check_compatible_with(other) result = op(other.ordinal) elif isinstance(other, cls): self._check_compatible_with(other) result = op(other.asi8) mask = self._isnan | other._isnan if mask.any(): result[mask] = nat_result return result elif other is NaT: result = np.empty(len(self.asi8), dtype=bool) result.fill(nat_result) else: other = Period(other, freq=self.freq) result = op(other.ordinal) if self._hasnans: result[self._isnan] = nat_result return result return compat.set_function_name(wrapper, opname, cls)
[ "def", "_period_array_cmp", "(", "cls", ",", "op", ")", ":", "opname", "=", "'__{name}__'", ".", "format", "(", "name", "=", "op", ".", "__name__", ")", "nat_result", "=", "True", "if", "opname", "==", "'__ne__'", "else", "False", "def", "wrapper", "(", "self", ",", "other", ")", ":", "op", "=", "getattr", "(", "self", ".", "asi8", ",", "opname", ")", "if", "isinstance", "(", "other", ",", "(", "ABCDataFrame", ",", "ABCSeries", ",", "ABCIndexClass", ")", ")", ":", "return", "NotImplemented", "if", "is_list_like", "(", "other", ")", "and", "len", "(", "other", ")", "!=", "len", "(", "self", ")", ":", "raise", "ValueError", "(", "\"Lengths must match\"", ")", "if", "isinstance", "(", "other", ",", "Period", ")", ":", "self", ".", "_check_compatible_with", "(", "other", ")", "result", "=", "op", "(", "other", ".", "ordinal", ")", "elif", "isinstance", "(", "other", ",", "cls", ")", ":", "self", ".", "_check_compatible_with", "(", "other", ")", "result", "=", "op", "(", "other", ".", "asi8", ")", "mask", "=", "self", ".", "_isnan", "|", "other", ".", "_isnan", "if", "mask", ".", "any", "(", ")", ":", "result", "[", "mask", "]", "=", "nat_result", "return", "result", "elif", "other", "is", "NaT", ":", "result", "=", "np", ".", "empty", "(", "len", "(", "self", ".", "asi8", ")", ",", "dtype", "=", "bool", ")", "result", ".", "fill", "(", "nat_result", ")", "else", ":", "other", "=", "Period", "(", "other", ",", "freq", "=", "self", ".", "freq", ")", "result", "=", "op", "(", "other", ".", "ordinal", ")", "if", "self", ".", "_hasnans", ":", "result", "[", "self", ".", "_isnan", "]", "=", "nat_result", "return", "result", "return", "compat", ".", "set_function_name", "(", "wrapper", ",", "opname", ",", "cls", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/period.py#L44-L86
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.winfo_height
(self)
return self.tk.getint( self.tk.call('winfo', 'height', self._w))
Return height of this widget.
Return height of this widget.
[ "Return", "height", "of", "this", "widget", "." ]
def winfo_height(self): """Return height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'height', self._w))
[ "def", "winfo_height", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "getint", "(", "self", ".", "tk", ".", "call", "(", "'winfo'", ",", "'height'", ",", "self", ".", "_w", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L997-L1000
0ad/0ad
f58db82e0e925016d83f4e3fa7ca599e3866e2af
source/tools/i18n/updateTemplates.py
python
warnAboutUntouchedMods
()
Warn about mods that are not properly configured to get their messages extracted.
Warn about mods that are not properly configured to get their messages extracted.
[ "Warn", "about", "mods", "that", "are", "not", "properly", "configured", "to", "get", "their", "messages", "extracted", "." ]
def warnAboutUntouchedMods(): """ Warn about mods that are not properly configured to get their messages extracted. """ modsRootFolder = os.path.join(projectRootDirectory, "binaries", "data", "mods") untouchedMods = {} for modFolder in os.listdir(modsRootFolder): if modFolder[0] != "_" and modFolder[0] != '.': if not os.path.exists(os.path.join(modsRootFolder, modFolder, l10nFolderName)): untouchedMods[modFolder] = "There is no '{folderName}' folder in the root folder of this mod.".format(folderName=l10nFolderName) elif not os.path.exists(os.path.join(modsRootFolder, modFolder, l10nFolderName, messagesFilename)): untouchedMods[modFolder] = "There is no '{filename}' file within the '{folderName}' folder in the root folder of this mod.".format(folderName=l10nFolderName, filename=messagesFilename) if untouchedMods: print("" "Warning: No messages were extracted from the following mods:" "") for mod in untouchedMods: print("• {modName}: {warningMessage}".format(modName=mod, warningMessage=untouchedMods[mod])) print("" f"For this script to extract messages from a mod folder, this mod folder must contain a '{l10nFolderName}' " f"folder, and this folder must contain a '{messagesFilename}' file that describes how to extract messages for the " f"mod. See the folder of the main mod ('public') for an example, and see the documentation for more " f"information." )
[ "def", "warnAboutUntouchedMods", "(", ")", ":", "modsRootFolder", "=", "os", ".", "path", ".", "join", "(", "projectRootDirectory", ",", "\"binaries\"", ",", "\"data\"", ",", "\"mods\"", ")", "untouchedMods", "=", "{", "}", "for", "modFolder", "in", "os", ".", "listdir", "(", "modsRootFolder", ")", ":", "if", "modFolder", "[", "0", "]", "!=", "\"_\"", "and", "modFolder", "[", "0", "]", "!=", "'.'", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "modsRootFolder", ",", "modFolder", ",", "l10nFolderName", ")", ")", ":", "untouchedMods", "[", "modFolder", "]", "=", "\"There is no '{folderName}' folder in the root folder of this mod.\"", ".", "format", "(", "folderName", "=", "l10nFolderName", ")", "elif", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "modsRootFolder", ",", "modFolder", ",", "l10nFolderName", ",", "messagesFilename", ")", ")", ":", "untouchedMods", "[", "modFolder", "]", "=", "\"There is no '{filename}' file within the '{folderName}' folder in the root folder of this mod.\"", ".", "format", "(", "folderName", "=", "l10nFolderName", ",", "filename", "=", "messagesFilename", ")", "if", "untouchedMods", ":", "print", "(", "\"\"", "\"Warning: No messages were extracted from the following mods:\"", "\"\"", ")", "for", "mod", "in", "untouchedMods", ":", "print", "(", "\"• {modName}: {warningMessage}\".f", "o", "rmat(m", "o", "dName=m", "o", "d, ", "w", "rningMessage=u", "n", "touchedMods[m", "o", "d])", ")", "", "", "print", "(", "\"\"", "f\"For this script to extract messages from a mod folder, this mod folder must contain a '{l10nFolderName}' \"", "f\"folder, and this folder must contain a '{messagesFilename}' file that describes how to extract messages for the \"", "f\"mod. See the folder of the main mod ('public') for an example, and see the documentation for more \"", "f\"information.\"", ")" ]
https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/i18n/updateTemplates.py#L31-L54
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/operators/control_flow.py
python
_is_none_or_undef
(value)
return ((value is None) or isinstance(value, variables.UndefinedReturnValue) or isinstance(value, variables.Undefined))
Tests whether a value is None or undefined. AutoGraph represents undefined symbols using special objects of type Undefined or UndefinedReturnValue. Args: value: value to test Returns: Boolean
Tests whether a value is None or undefined.
[ "Tests", "whether", "a", "value", "is", "None", "or", "undefined", "." ]
def _is_none_or_undef(value): """Tests whether a value is None or undefined. AutoGraph represents undefined symbols using special objects of type Undefined or UndefinedReturnValue. Args: value: value to test Returns: Boolean """ return ((value is None) or isinstance(value, variables.UndefinedReturnValue) or isinstance(value, variables.Undefined))
[ "def", "_is_none_or_undef", "(", "value", ")", ":", "return", "(", "(", "value", "is", "None", ")", "or", "isinstance", "(", "value", ",", "variables", ".", "UndefinedReturnValue", ")", "or", "isinstance", "(", "value", ",", "variables", ".", "Undefined", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/control_flow.py#L100-L114
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unsafe/numbers.py
python
leading_zeros
(typeingctx, src)
return src(src), codegen
Counts leading zeros in the binary representation of an integer.
Counts leading zeros in the binary representation of an integer.
[ "Counts", "leading", "zeros", "in", "the", "binary", "representation", "of", "an", "integer", "." ]
def leading_zeros(typeingctx, src): """Counts leading zeros in the binary representation of an integer.""" if not isinstance(src, types.Integer): raise TypeError( "leading_zeros is only defined for integers, but passed value was " "'{}'.".format(src) ) def codegen(context, builder, signature, args): [src] = args return builder.ctlz(src, ir.Constant(ir.IntType(1), 0)) return src(src), codegen
[ "def", "leading_zeros", "(", "typeingctx", ",", "src", ")", ":", "if", "not", "isinstance", "(", "src", ",", "types", ".", "Integer", ")", ":", "raise", "TypeError", "(", "\"leading_zeros is only defined for integers, but passed value was \"", "\"'{}'.\"", ".", "format", "(", "src", ")", ")", "def", "codegen", "(", "context", ",", "builder", ",", "signature", ",", "args", ")", ":", "[", "src", "]", "=", "args", "return", "builder", ".", "ctlz", "(", "src", ",", "ir", ".", "Constant", "(", "ir", ".", "IntType", "(", "1", ")", ",", "0", ")", ")", "return", "src", "(", "src", ")", ",", "codegen" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unsafe/numbers.py#L44-L55
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_anneal.py
python
Solver.init_vars
(self, num_strats, num_players)
return (init_dist, init_y, init_anneal_steps)
Initialize solver parameters.
Initialize solver parameters.
[ "Initialize", "solver", "parameters", "." ]
def init_vars(self, num_strats, num_players): """Initialize solver parameters.""" self.num_players = num_players if len(num_strats) != num_players: raise ValueError('Must specify num strategies for each player') init_dist = [] for num_strats_i in num_strats: if self.rnd_init: init_dist_i = self.random.rand(num_strats_i) else: init_dist_i = np.ones(num_strats_i) init_dist_i /= init_dist_i.sum() init_dist.append(init_dist_i) init_y = [np.zeros_like(dist_i) for dist_i in init_dist] init_anneal_steps = 0 return (init_dist, init_y, init_anneal_steps)
[ "def", "init_vars", "(", "self", ",", "num_strats", ",", "num_players", ")", ":", "self", ".", "num_players", "=", "num_players", "if", "len", "(", "num_strats", ")", "!=", "num_players", ":", "raise", "ValueError", "(", "'Must specify num strategies for each player'", ")", "init_dist", "=", "[", "]", "for", "num_strats_i", "in", "num_strats", ":", "if", "self", ".", "rnd_init", ":", "init_dist_i", "=", "self", ".", "random", ".", "rand", "(", "num_strats_i", ")", "else", ":", "init_dist_i", "=", "np", ".", "ones", "(", "num_strats_i", ")", "init_dist_i", "/=", "init_dist_i", ".", "sum", "(", ")", "init_dist", ".", "append", "(", "init_dist_i", ")", "init_y", "=", "[", "np", ".", "zeros_like", "(", "dist_i", ")", "for", "dist_i", "in", "init_dist", "]", "init_anneal_steps", "=", "0", "return", "(", "init_dist", ",", "init_y", ",", "init_anneal_steps", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_anneal.py#L58-L73
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/subprocess32/subprocess32.py
python
Popen.communicate
(self, input=None, timeout=None)
return (stdout, stderr)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.
[ "Interact", "with", "process", ":", "Send", "data", "to", "stdin", ".", "Read", "data", "from", "stdout", "and", "stderr", "until", "end", "-", "of", "-", "file", "is", "reached", ".", "Wait", "for", "process", "to", "terminate", ".", "The", "optional", "input", "argument", "should", "be", "a", "string", "to", "be", "sent", "to", "the", "child", "process", "or", "None", "if", "no", "data", "should", "be", "sent", "to", "the", "child", "." ]
def communicate(self, input=None, timeout=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" if self._communication_started and input: raise ValueError("Cannot send input after starting communication") if timeout is not None: endtime = time.time() + timeout else: endtime = None # Optimization: If we are not worried about timeouts, we haven't # started communicating, and we have one or zero pipes, using select() # or threads is unnecessary. if (endtime is None and not self._communication_started and [self.stdin, self.stdout, self.stderr].count(None) >= 2): stdout = None stderr = None if self.stdin: self._stdin_write(input) elif self.stdout: stdout = _eintr_retry_call(self.stdout.read) self.stdout.close() elif self.stderr: stderr = _eintr_retry_call(self.stderr.read) self.stderr.close() self.wait() return (stdout, stderr) try: stdout, stderr = self._communicate(input, endtime, timeout) finally: self._communication_started = True sts = self.wait(timeout=self._remaining_time(endtime)) return (stdout, stderr)
[ "def", "communicate", "(", "self", ",", "input", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_communication_started", "and", "input", ":", "raise", "ValueError", "(", "\"Cannot send input after starting communication\"", ")", "if", "timeout", "is", "not", "None", ":", "endtime", "=", "time", ".", "time", "(", ")", "+", "timeout", "else", ":", "endtime", "=", "None", "# Optimization: If we are not worried about timeouts, we haven't", "# started communicating, and we have one or zero pipes, using select()", "# or threads is unnecessary.", "if", "(", "endtime", "is", "None", "and", "not", "self", ".", "_communication_started", "and", "[", "self", ".", "stdin", ",", "self", ".", "stdout", ",", "self", ".", "stderr", "]", ".", "count", "(", "None", ")", ">=", "2", ")", ":", "stdout", "=", "None", "stderr", "=", "None", "if", "self", ".", "stdin", ":", "self", ".", "_stdin_write", "(", "input", ")", "elif", "self", ".", "stdout", ":", "stdout", "=", "_eintr_retry_call", "(", "self", ".", "stdout", ".", "read", ")", "self", ".", "stdout", ".", "close", "(", ")", "elif", "self", ".", "stderr", ":", "stderr", "=", "_eintr_retry_call", "(", "self", ".", "stderr", ".", "read", ")", "self", ".", "stderr", ".", "close", "(", ")", "self", ".", "wait", "(", ")", "return", "(", "stdout", ",", "stderr", ")", "try", ":", "stdout", ",", "stderr", "=", "self", ".", "_communicate", "(", "input", ",", "endtime", ",", "timeout", ")", "finally", ":", "self", ".", "_communication_started", "=", "True", "sts", "=", "self", ".", "wait", "(", "timeout", "=", "self", ".", "_remaining_time", "(", "endtime", ")", ")", "return", "(", "stdout", ",", "stderr", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/subprocess32/subprocess32.py#L712-L754
GrammaTech/gtirb
415dd72e1e3c475004d013723c16cdcb29c0826e
python/gtirb/symbol.py
python
Symbol.__init__
( self, name: str, uuid: typing.Optional[UUID] = None, payload: typing.Optional[Payload] = None, at_end: bool = False, module: typing.Optional["Module"] = None, )
:param name: The name of this symbol. :param uuid: The UUID of this ``Symbol``, or None if a new UUID needs generated via :func:`uuid.uuid4`. Defaults to None. :param payload: The value this symbol points to. May be an address, a Node, or None. :param at_end: True if this symbol is at the end of its referent, rather than at the beginning. :param module: The :class:`Module` this symbol belongs to.
:param name: The name of this symbol. :param uuid: The UUID of this ``Symbol``, or None if a new UUID needs generated via :func:`uuid.uuid4`. Defaults to None. :param payload: The value this symbol points to. May be an address, a Node, or None. :param at_end: True if this symbol is at the end of its referent, rather than at the beginning. :param module: The :class:`Module` this symbol belongs to.
[ ":", "param", "name", ":", "The", "name", "of", "this", "symbol", ".", ":", "param", "uuid", ":", "The", "UUID", "of", "this", "Symbol", "or", "None", "if", "a", "new", "UUID", "needs", "generated", "via", ":", "func", ":", "uuid", ".", "uuid4", ".", "Defaults", "to", "None", ".", ":", "param", "payload", ":", "The", "value", "this", "symbol", "points", "to", ".", "May", "be", "an", "address", "a", "Node", "or", "None", ".", ":", "param", "at_end", ":", "True", "if", "this", "symbol", "is", "at", "the", "end", "of", "its", "referent", "rather", "than", "at", "the", "beginning", ".", ":", "param", "module", ":", "The", ":", "class", ":", "Module", "this", "symbol", "belongs", "to", "." ]
def __init__( self, name: str, uuid: typing.Optional[UUID] = None, payload: typing.Optional[Payload] = None, at_end: bool = False, module: typing.Optional["Module"] = None, ): """ :param name: The name of this symbol. :param uuid: The UUID of this ``Symbol``, or None if a new UUID needs generated via :func:`uuid.uuid4`. Defaults to None. :param payload: The value this symbol points to. May be an address, a Node, or None. :param at_end: True if this symbol is at the end of its referent, rather than at the beginning. :param module: The :class:`Module` this symbol belongs to. """ super().__init__(uuid) self._module: typing.Optional["Module"] = None self.name = name self.at_end = at_end self._payload = payload # Use the property setter to ensure correct invariants. self.module = module
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "uuid", ":", "typing", ".", "Optional", "[", "UUID", "]", "=", "None", ",", "payload", ":", "typing", ".", "Optional", "[", "Payload", "]", "=", "None", ",", "at_end", ":", "bool", "=", "False", ",", "module", ":", "typing", ".", "Optional", "[", "\"Module\"", "]", "=", "None", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "uuid", ")", "self", ".", "_module", ":", "typing", ".", "Optional", "[", "\"Module\"", "]", "=", "None", "self", ".", "name", "=", "name", "self", ".", "at_end", "=", "at_end", "self", ".", "_payload", "=", "payload", "# Use the property setter to ensure correct invariants.", "self", ".", "module", "=", "module" ]
https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/symbol.py#L29-L55
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/special/basic.py
python
assoc_laguerre
(x, n, k=0.0)
return orthogonal.eval_genlaguerre(n, k, x)
Compute the generalized (associated) Laguerre polynomial of degree n and order k. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``, with weighting function ``exp(-x) * x**k`` with ``k > -1``. Notes ----- `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
Compute the generalized (associated) Laguerre polynomial of degree n and order k.
[ "Compute", "the", "generalized", "(", "associated", ")", "Laguerre", "polynomial", "of", "degree", "n", "and", "order", "k", "." ]
def assoc_laguerre(x, n, k=0.0): """Compute the generalized (associated) Laguerre polynomial of degree n and order k. The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``, with weighting function ``exp(-x) * x**k`` with ``k > -1``. Notes ----- `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with reversed argument order ``(x, n, k=0.0) --> (n, k, x)``. """ return orthogonal.eval_genlaguerre(n, k, x)
[ "def", "assoc_laguerre", "(", "x", ",", "n", ",", "k", "=", "0.0", ")", ":", "return", "orthogonal", ".", "eval_genlaguerre", "(", "n", ",", "k", ",", "x", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/special/basic.py#L922-L934
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridSizeEvent.__init__
(self, *args, **kwargs)
__init__(self, int id, EventType type, Grid obj, int rowOrCol=-1, int x=-1, int y=-1, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridSizeEvent
__init__(self, int id, EventType type, Grid obj, int rowOrCol=-1, int x=-1, int y=-1, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridSizeEvent
[ "__init__", "(", "self", "int", "id", "EventType", "type", "Grid", "obj", "int", "rowOrCol", "=", "-", "1", "int", "x", "=", "-", "1", "int", "y", "=", "-", "1", "bool", "control", "=", "False", "bool", "shift", "=", "False", "bool", "alt", "=", "False", "bool", "meta", "=", "False", ")", "-", ">", "GridSizeEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, int id, EventType type, Grid obj, int rowOrCol=-1, int x=-1, int y=-1, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridSizeEvent """ _grid.GridSizeEvent_swiginit(self,_grid.new_GridSizeEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_grid", ".", "GridSizeEvent_swiginit", "(", "self", ",", "_grid", ".", "new_GridSizeEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L2350-L2356
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/examples/thermo/isentropic.py
python
soundspeed
(gas)
return math.sqrt(gamma * ct.gas_constant * gas.T / gas.mean_molecular_weight)
The speed of sound. Assumes an ideal gas.
The speed of sound. Assumes an ideal gas.
[ "The", "speed", "of", "sound", ".", "Assumes", "an", "ideal", "gas", "." ]
def soundspeed(gas): """The speed of sound. Assumes an ideal gas.""" gamma = gas.cp / gas.cv return math.sqrt(gamma * ct.gas_constant * gas.T / gas.mean_molecular_weight)
[ "def", "soundspeed", "(", "gas", ")", ":", "gamma", "=", "gas", ".", "cp", "/", "gas", ".", "cv", "return", "math", ".", "sqrt", "(", "gamma", "*", "ct", ".", "gas_constant", "*", "gas", ".", "T", "/", "gas", ".", "mean_molecular_weight", ")" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/examples/thermo/isentropic.py#L12-L17
christinaa/LLVM-VideoCore4
7773c3c9e5d22b785d4b96ed0acea37c8aa9c183
examples/Kaleidoscope/MCJIT/complete/genk-timing.py
python
KScriptGenerator.updateFunctionCallMap
(self, caller, callee)
Maintains a map of functions that are called from other functions
Maintains a map of functions that are called from other functions
[ "Maintains", "a", "map", "of", "functions", "that", "are", "called", "from", "other", "functions" ]
def updateFunctionCallMap(self, caller, callee): """Maintains a map of functions that are called from other functions""" if not caller in self.calledFunctionTable: self.calledFunctionTable[caller] = [] if not callee in self.calledFunctionTable[caller]: self.calledFunctionTable[caller].append(callee) if not caller in self.comprehensiveCalledFunctionTable: self.comprehensiveCalledFunctionTable[caller] = [] self.comprehensiveCalledFunctionTable[caller].append(callee)
[ "def", "updateFunctionCallMap", "(", "self", ",", "caller", ",", "callee", ")", ":", "if", "not", "caller", "in", "self", ".", "calledFunctionTable", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", "=", "[", "]", "if", "not", "callee", "in", "self", ".", "calledFunctionTable", "[", "caller", "]", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")", "if", "not", "caller", "in", "self", ".", "comprehensiveCalledFunctionTable", ":", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", "=", "[", "]", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")" ]
https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L61-L69
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/m5/ext/pyfdt/pyfdt.py
python
FdtPropertyStrings.__getitem__
(self, index)
return self.strings[index]
Get strings, returns a string
Get strings, returns a string
[ "Get", "strings", "returns", "a", "string" ]
def __getitem__(self, index): """Get strings, returns a string""" return self.strings[index]
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "return", "self", ".", "strings", "[", "index", "]" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/ext/pyfdt/pyfdt.py#L226-L228
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py
python
Resolution._backtrack
(self)
return False
Perform backtracking. When we enter here, the stack is like this:: [ state Z ] [ state Y ] [ state X ] .... earlier states are irrelevant. 1. No pins worked for Z, so it does not have a pin. 2. We want to reset state Y to unpinned, and pin another candidate. 3. State X holds what state Y was before the pin, but does not have the incompatibility information gathered in state Y. Each iteration of the loop will: 1. Discard Z. 2. Discard Y but remember its incompatibility information gathered previously, and the failure we're dealing with right now. 3. Push a new state Y' based on X, and apply the incompatibility information from Y to Y'. 4a. If this causes Y' to conflict, we need to backtrack again. Make Y' the new Z and go back to step 2. 4b. If the incompatibilities apply cleanly, end backtracking.
Perform backtracking.
[ "Perform", "backtracking", "." ]
def _backtrack(self): """Perform backtracking. When we enter here, the stack is like this:: [ state Z ] [ state Y ] [ state X ] .... earlier states are irrelevant. 1. No pins worked for Z, so it does not have a pin. 2. We want to reset state Y to unpinned, and pin another candidate. 3. State X holds what state Y was before the pin, but does not have the incompatibility information gathered in state Y. Each iteration of the loop will: 1. Discard Z. 2. Discard Y but remember its incompatibility information gathered previously, and the failure we're dealing with right now. 3. Push a new state Y' based on X, and apply the incompatibility information from Y to Y'. 4a. If this causes Y' to conflict, we need to backtrack again. Make Y' the new Z and go back to step 2. 4b. If the incompatibilities apply cleanly, end backtracking. """ while len(self._states) >= 3: # Remove the state that triggered backtracking. del self._states[-1] # Retrieve the last candidate pin and known incompatibilities. broken_state = self._states.pop() name, candidate = broken_state.mapping.popitem() incompatibilities_from_broken = [ (k, v.incompatibilities) for k, v in broken_state.criteria.items() ] # Also mark the newly known incompatibility. incompatibilities_from_broken.append((name, [candidate])) self._r.backtracking(candidate) # Create a new state from the last known-to-work one, and apply # the previously gathered incompatibility information. def _patch_criteria(): for k, incompatibilities in incompatibilities_from_broken: if not incompatibilities: continue try: criterion = self.state.criteria[k] except KeyError: continue criterion = criterion.excluded_of(incompatibilities) if criterion is None: return False self.state.criteria[k] = criterion return True self._push_new_state() success = _patch_criteria() # It works! Let's work on this new state. if success: return True # State does not work after applying known incompatibilities. # Try the still previous state. # No way to backtrack anymore. return False
[ "def", "_backtrack", "(", "self", ")", ":", "while", "len", "(", "self", ".", "_states", ")", ">=", "3", ":", "# Remove the state that triggered backtracking.", "del", "self", ".", "_states", "[", "-", "1", "]", "# Retrieve the last candidate pin and known incompatibilities.", "broken_state", "=", "self", ".", "_states", ".", "pop", "(", ")", "name", ",", "candidate", "=", "broken_state", ".", "mapping", ".", "popitem", "(", ")", "incompatibilities_from_broken", "=", "[", "(", "k", ",", "v", ".", "incompatibilities", ")", "for", "k", ",", "v", "in", "broken_state", ".", "criteria", ".", "items", "(", ")", "]", "# Also mark the newly known incompatibility.", "incompatibilities_from_broken", ".", "append", "(", "(", "name", ",", "[", "candidate", "]", ")", ")", "self", ".", "_r", ".", "backtracking", "(", "candidate", ")", "# Create a new state from the last known-to-work one, and apply", "# the previously gathered incompatibility information.", "def", "_patch_criteria", "(", ")", ":", "for", "k", ",", "incompatibilities", "in", "incompatibilities_from_broken", ":", "if", "not", "incompatibilities", ":", "continue", "try", ":", "criterion", "=", "self", ".", "state", ".", "criteria", "[", "k", "]", "except", "KeyError", ":", "continue", "criterion", "=", "criterion", ".", "excluded_of", "(", "incompatibilities", ")", "if", "criterion", "is", "None", ":", "return", "False", "self", ".", "state", ".", "criteria", "[", "k", "]", "=", "criterion", "return", "True", "self", ".", "_push_new_state", "(", ")", "success", "=", "_patch_criteria", "(", ")", "# It works! Let's work on this new state.", "if", "success", ":", "return", "True", "# State does not work after applying known incompatibilities.", "# Try the still previous state.", "# No way to backtrack anymore.", "return", "False" ]
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/resolvelib/resolvers.py#L236-L306
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plistlib.py
python
writePlist
(rootObject, pathOrFile)
Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object.
Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object.
[ "Write", "rootObject", "to", "a", ".", "plist", "file", ".", "pathOrFile", "may", "either", "be", "a", "file", "name", "or", "a", "(", "writable", ")", "file", "object", "." ]
def writePlist(rootObject, pathOrFile): """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object. """ didOpen = 0 if isinstance(pathOrFile, (str, unicode)): pathOrFile = open(pathOrFile, "w") didOpen = 1 writer = PlistWriter(pathOrFile) writer.writeln("<plist version=\"1.0\">") writer.writeValue(rootObject) writer.writeln("</plist>") if didOpen: pathOrFile.close()
[ "def", "writePlist", "(", "rootObject", ",", "pathOrFile", ")", ":", "didOpen", "=", "0", "if", "isinstance", "(", "pathOrFile", ",", "(", "str", ",", "unicode", ")", ")", ":", "pathOrFile", "=", "open", "(", "pathOrFile", ",", "\"w\"", ")", "didOpen", "=", "1", "writer", "=", "PlistWriter", "(", "pathOrFile", ")", "writer", ".", "writeln", "(", "\"<plist version=\\\"1.0\\\">\"", ")", "writer", ".", "writeValue", "(", "rootObject", ")", "writer", ".", "writeln", "(", "\"</plist>\"", ")", "if", "didOpen", ":", "pathOrFile", ".", "close", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plistlib.py#L84-L97
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/MSVSVersion.py
python
_RegistryGetValue
(key, value)
return match.group(1)
Use _winreg or reg.exe to obtain the value of a registry key. Using _winreg is preferable because it solves an issue on some corporate environments where access to reg.exe is locked down. However, we still need to fallback to reg.exe for the case where the _winreg module is not available (for example in cygwin python). Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure.
Use _winreg or reg.exe to obtain the value of a registry key.
[ "Use", "_winreg", "or", "reg", ".", "exe", "to", "obtain", "the", "value", "of", "a", "registry", "key", "." ]
def _RegistryGetValue(key, value): """Use _winreg or reg.exe to obtain the value of a registry key. Using _winreg is preferable because it solves an issue on some corporate environments where access to reg.exe is locked down. However, we still need to fallback to reg.exe for the case where the _winreg module is not available (for example in cygwin python). Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure. """ try: return _RegistryGetValueUsingWinReg(key, value) except ImportError: pass # Fallback to reg.exe if we fail to import _winreg. text = _RegistryQuery(key, value) if not text: return None # Extract value. match = re.search(r'REG_\w+\s+([^\r]+)\r\n', text) if not match: return None return match.group(1)
[ "def", "_RegistryGetValue", "(", "key", ",", "value", ")", ":", "try", ":", "return", "_RegistryGetValueUsingWinReg", "(", "key", ",", "value", ")", "except", "ImportError", ":", "pass", "# Fallback to reg.exe if we fail to import _winreg.", "text", "=", "_RegistryQuery", "(", "key", ",", "value", ")", "if", "not", "text", ":", "return", "None", "# Extract value.", "match", "=", "re", ".", "search", "(", "r'REG_\\w+\\s+([^\\r]+)\\r\\n'", ",", "text", ")", "if", "not", "match", ":", "return", "None", "return", "match", ".", "group", "(", "1", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/MSVSVersion.py#L230-L257
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TPrGraph
(*args)
return _snap.TPrGraph(*args)
TPrGraph(PUNGraph G) -> TUNGraph Parameters: G: PUNGraph
TPrGraph(PUNGraph G) -> TUNGraph
[ "TPrGraph", "(", "PUNGraph", "G", ")", "-", ">", "TUNGraph" ]
def TPrGraph(*args): """ TPrGraph(PUNGraph G) -> TUNGraph Parameters: G: PUNGraph """ return _snap.TPrGraph(*args)
[ "def", "TPrGraph", "(", "*", "args", ")", ":", "return", "_snap", ".", "TPrGraph", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21203-L21211
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Menu.UpdateUI
(*args, **kwargs)
return _core_.Menu_UpdateUI(*args, **kwargs)
UpdateUI(self, EvtHandler source=None)
UpdateUI(self, EvtHandler source=None)
[ "UpdateUI", "(", "self", "EvtHandler", "source", "=", "None", ")" ]
def UpdateUI(*args, **kwargs): """UpdateUI(self, EvtHandler source=None)""" return _core_.Menu_UpdateUI(*args, **kwargs)
[ "def", "UpdateUI", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_UpdateUI", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12222-L12224
runtimejs/runtime
0a6e84c30823d35a4548d6634166784260ae7b74
deps/v8/gypfiles/vs_toolchain.py
python
GetVisualStudioVersion
()
return os.environ.get('GYP_MSVS_VERSION', CURRENT_DEFAULT_TOOLCHAIN_VERSION)
Return GYP_MSVS_VERSION of Visual Studio.
Return GYP_MSVS_VERSION of Visual Studio.
[ "Return", "GYP_MSVS_VERSION", "of", "Visual", "Studio", "." ]
def GetVisualStudioVersion(): """Return GYP_MSVS_VERSION of Visual Studio. """ return os.environ.get('GYP_MSVS_VERSION', CURRENT_DEFAULT_TOOLCHAIN_VERSION)
[ "def", "GetVisualStudioVersion", "(", ")", ":", "return", "os", ".", "environ", ".", "get", "(", "'GYP_MSVS_VERSION'", ",", "CURRENT_DEFAULT_TOOLCHAIN_VERSION", ")" ]
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/gypfiles/vs_toolchain.py#L110-L113
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/image/detection.py
python
DetAugmenter.__call__
(self, src, label)
Abstract implementation body
Abstract implementation body
[ "Abstract", "implementation", "body" ]
def __call__(self, src, label): """Abstract implementation body""" raise NotImplementedError("Must override implementation.")
[ "def", "__call__", "(", "self", ",", "src", ",", "label", ")", ":", "raise", "NotImplementedError", "(", "\"Must override implementation.\"", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/detection.py#L58-L60
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py2/traitlets/traitlets.py
python
HasTraits.on_trait_change
(self, handler=None, name=None, remove=False)
DEPRECATED: Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[traitname]_changed'. Thus, to create static handler for the trait 'a', create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below). If `remove` is True and `handler` is not specified, all change handlers for the specified name are uninstalled. Parameters ---------- handler : callable, None A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self). name : list, str, None If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. remove : bool If False (the default), then install the handler. If True then unintall it.
DEPRECATED: Setup a handler to be called when a trait changes.
[ "DEPRECATED", ":", "Setup", "a", "handler", "to", "be", "called", "when", "a", "trait", "changes", "." ]
def on_trait_change(self, handler=None, name=None, remove=False): """DEPRECATED: Setup a handler to be called when a trait changes. This is used to setup dynamic notifications of trait changes. Static handlers can be created by creating methods on a HasTraits subclass with the naming convention '_[traitname]_changed'. Thus, to create static handler for the trait 'a', create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below). If `remove` is True and `handler` is not specified, all change handlers for the specified name are uninstalled. Parameters ---------- handler : callable, None A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new), handler(name, old, new), or handler(name, old, new, self). name : list, str, None If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name. remove : bool If False (the default), then install the handler. If True then unintall it. """ warn("on_trait_change is deprecated in traitlets 4.1: use observe instead", DeprecationWarning, stacklevel=2) if name is None: name = All if remove: self.unobserve(_callback_wrapper(handler), names=name) else: self.observe(_callback_wrapper(handler), names=name)
[ "def", "on_trait_change", "(", "self", ",", "handler", "=", "None", ",", "name", "=", "None", ",", "remove", "=", "False", ")", ":", "warn", "(", "\"on_trait_change is deprecated in traitlets 4.1: use observe instead\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "if", "name", "is", "None", ":", "name", "=", "All", "if", "remove", ":", "self", ".", "unobserve", "(", "_callback_wrapper", "(", "handler", ")", ",", "names", "=", "name", ")", "else", ":", "self", ".", "observe", "(", "_callback_wrapper", "(", "handler", ")", ",", "names", "=", "name", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L1200-L1235
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
IKObjective.setFreePosition
(self)
return _robotsim.IKObjective_setFreePosition(self)
setFreePosition(IKObjective self) Manual: Sets a free position constraint.
setFreePosition(IKObjective self)
[ "setFreePosition", "(", "IKObjective", "self", ")" ]
def setFreePosition(self): """ setFreePosition(IKObjective self) Manual: Sets a free position constraint. """ return _robotsim.IKObjective_setFreePosition(self)
[ "def", "setFreePosition", "(", "self", ")", ":", "return", "_robotsim", ".", "IKObjective_setFreePosition", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L6317-L6326
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py
python
GradientBoostedDecisionTreeModel.make_update_ensemble_fn
(self, ensemble_stamp, training_state, dropout_seed, class_id)
return _update_ensemble
A method to create the function which updates the tree ensemble.
A method to create the function which updates the tree ensemble.
[ "A", "method", "to", "create", "the", "function", "which", "updates", "the", "tree", "ensemble", "." ]
def make_update_ensemble_fn(self, ensemble_stamp, training_state, dropout_seed, class_id): """A method to create the function which updates the tree ensemble.""" # Determine learning rate. learning_rate_tuner = self._learner_config.learning_rate_tuner.WhichOneof( "tuner") if learning_rate_tuner == "fixed" or learning_rate_tuner == "dropout": tuner = getattr(self._learner_config.learning_rate_tuner, learning_rate_tuner) learning_rate = tuner.learning_rate else: # TODO(nponomareva, soroush) do the line search. raise ValueError("Line search learning rate is not yet supported.") def _update_ensemble(): """A method to update the tree ensemble.""" # Get next stamp token. next_ensemble_stamp = ensemble_stamp + 1 # Finalize bias stats. _, _, _, bias_grads, bias_hess = ( training_state.bias_stats_accumulator.flush(ensemble_stamp, next_ensemble_stamp)) # Finalize handler splits. are_splits_ready_list = [] partition_ids_list = [] gains_list = [] split_info_list = [] for handler in training_state.handlers: (are_splits_ready, partition_ids, gains, split_info) = handler.make_splits( ensemble_stamp, next_ensemble_stamp, class_id) are_splits_ready_list.append(are_splits_ready) partition_ids_list.append(partition_ids) gains_list.append(gains) split_info_list.append(split_info) # Stack all the inputs to one tensor per type. # This is a workaround for the slowness of graph building in tf.cond. # See (b/36554864). split_sizes = array_ops.reshape( array_ops.shape_n(partition_ids_list), [len(partition_ids_list)]) partition_ids = array_ops.concat(partition_ids_list, axis=0) gains = array_ops.concat(gains_list, axis=0) split_infos = array_ops.concat(split_info_list, axis=0) # Determine if all splits are ready. are_all_splits_ready = math_ops.reduce_all( array_ops.stack( are_splits_ready_list, axis=0, name="stack_handler_readiness")) # Define bias centering update operation. def _center_bias_fn(): # Center tree ensemble bias. delta_updates = array_ops.where(bias_hess > 0, -bias_grads / bias_hess, array_ops.zeros_like(bias_grads)) center_bias = training_ops.center_tree_ensemble_bias( tree_ensemble_handle=self._ensemble_handle, stamp_token=ensemble_stamp, next_stamp_token=next_ensemble_stamp, delta_updates=delta_updates, learner_config=self._learner_config_serialized) return training_state.continue_centering.assign(center_bias) # Define ensemble growing operations. def _grow_ensemble_ready_fn(): # Grow the ensemble given the current candidates. sizes = array_ops.unstack(split_sizes) partition_ids_list = list(array_ops.split(partition_ids, sizes, axis=0)) # When using the oblivious decision tree as weak learner, it produces # one gain and one split per handler and not number of partitions. if self._learner_config.weak_learner_type == ( learner_pb2.LearnerConfig.OBLIVIOUS_DECISION_TREE): sizes = len(training_state.handlers) gains_list = list(array_ops.split(gains, sizes, axis=0)) split_info_list = list(array_ops.split(split_infos, sizes, axis=0)) return training_ops.grow_tree_ensemble( tree_ensemble_handle=self._ensemble_handle, stamp_token=ensemble_stamp, next_stamp_token=next_ensemble_stamp, learning_rate=learning_rate, partition_ids=partition_ids_list, gains=gains_list, splits=split_info_list, learner_config=self._learner_config_serialized, dropout_seed=dropout_seed, center_bias=self._center_bias, max_tree_depth=self._max_tree_depth, weak_learner_type=self._learner_config.weak_learner_type) def _grow_ensemble_not_ready_fn(): # Don't grow the ensemble, just update the stamp. return training_ops.grow_tree_ensemble( tree_ensemble_handle=self._ensemble_handle, stamp_token=ensemble_stamp, next_stamp_token=next_ensemble_stamp, learning_rate=0, partition_ids=[], gains=[], splits=[], learner_config=self._learner_config_serialized, dropout_seed=dropout_seed, center_bias=self._center_bias, max_tree_depth=self._max_tree_depth, weak_learner_type=self._learner_config.weak_learner_type) def _grow_ensemble_fn(): # Conditionally grow an ensemble depending on whether the splits # from all the handlers are ready. return control_flow_ops.cond(are_all_splits_ready, _grow_ensemble_ready_fn, _grow_ensemble_not_ready_fn) # Update ensemble. update_ops = [are_all_splits_ready] if self._center_bias: update_model = control_flow_ops.cond(training_state.continue_centering, _center_bias_fn, _grow_ensemble_fn) else: update_model = _grow_ensemble_fn() update_ops.append(update_model) # Update ensemble stats. with ops.control_dependencies([update_model]): stats = training_ops.tree_ensemble_stats( self._ensemble_handle, stamp_token=next_ensemble_stamp) update_ops.append(self._finalized_trees.assign(stats.num_trees)) update_ops.append(self._attempted_trees.assign(stats.attempted_trees)) update_ops.append(training_state.num_layers.assign(stats.num_layers)) update_ops.append(training_state.active_tree.assign(stats.active_tree)) update_ops.append( training_state.active_layer.assign(stats.active_layer)) # Flush step stats. update_ops.extend( training_state.steps_accumulator.flush(ensemble_stamp, next_ensemble_stamp)) return control_flow_ops.group(*update_ops, name="update_ensemble") return _update_ensemble
[ "def", "make_update_ensemble_fn", "(", "self", ",", "ensemble_stamp", ",", "training_state", ",", "dropout_seed", ",", "class_id", ")", ":", "# Determine learning rate.", "learning_rate_tuner", "=", "self", ".", "_learner_config", ".", "learning_rate_tuner", ".", "WhichOneof", "(", "\"tuner\"", ")", "if", "learning_rate_tuner", "==", "\"fixed\"", "or", "learning_rate_tuner", "==", "\"dropout\"", ":", "tuner", "=", "getattr", "(", "self", ".", "_learner_config", ".", "learning_rate_tuner", ",", "learning_rate_tuner", ")", "learning_rate", "=", "tuner", ".", "learning_rate", "else", ":", "# TODO(nponomareva, soroush) do the line search.", "raise", "ValueError", "(", "\"Line search learning rate is not yet supported.\"", ")", "def", "_update_ensemble", "(", ")", ":", "\"\"\"A method to update the tree ensemble.\"\"\"", "# Get next stamp token.", "next_ensemble_stamp", "=", "ensemble_stamp", "+", "1", "# Finalize bias stats.", "_", ",", "_", ",", "_", ",", "bias_grads", ",", "bias_hess", "=", "(", "training_state", ".", "bias_stats_accumulator", ".", "flush", "(", "ensemble_stamp", ",", "next_ensemble_stamp", ")", ")", "# Finalize handler splits.", "are_splits_ready_list", "=", "[", "]", "partition_ids_list", "=", "[", "]", "gains_list", "=", "[", "]", "split_info_list", "=", "[", "]", "for", "handler", "in", "training_state", ".", "handlers", ":", "(", "are_splits_ready", ",", "partition_ids", ",", "gains", ",", "split_info", ")", "=", "handler", ".", "make_splits", "(", "ensemble_stamp", ",", "next_ensemble_stamp", ",", "class_id", ")", "are_splits_ready_list", ".", "append", "(", "are_splits_ready", ")", "partition_ids_list", ".", "append", "(", "partition_ids", ")", "gains_list", ".", "append", "(", "gains", ")", "split_info_list", ".", "append", "(", "split_info", ")", "# Stack all the inputs to one tensor per type.", "# This is a workaround for the slowness of graph building in tf.cond.", "# See (b/36554864).", "split_sizes", "=", "array_ops", ".", "reshape", "(", "array_ops", ".", "shape_n", "(", "partition_ids_list", ")", ",", "[", "len", "(", "partition_ids_list", ")", "]", ")", "partition_ids", "=", "array_ops", ".", "concat", "(", "partition_ids_list", ",", "axis", "=", "0", ")", "gains", "=", "array_ops", ".", "concat", "(", "gains_list", ",", "axis", "=", "0", ")", "split_infos", "=", "array_ops", ".", "concat", "(", "split_info_list", ",", "axis", "=", "0", ")", "# Determine if all splits are ready.", "are_all_splits_ready", "=", "math_ops", ".", "reduce_all", "(", "array_ops", ".", "stack", "(", "are_splits_ready_list", ",", "axis", "=", "0", ",", "name", "=", "\"stack_handler_readiness\"", ")", ")", "# Define bias centering update operation.", "def", "_center_bias_fn", "(", ")", ":", "# Center tree ensemble bias.", "delta_updates", "=", "array_ops", ".", "where", "(", "bias_hess", ">", "0", ",", "-", "bias_grads", "/", "bias_hess", ",", "array_ops", ".", "zeros_like", "(", "bias_grads", ")", ")", "center_bias", "=", "training_ops", ".", "center_tree_ensemble_bias", "(", "tree_ensemble_handle", "=", "self", ".", "_ensemble_handle", ",", "stamp_token", "=", "ensemble_stamp", ",", "next_stamp_token", "=", "next_ensemble_stamp", ",", "delta_updates", "=", "delta_updates", ",", "learner_config", "=", "self", ".", "_learner_config_serialized", ")", "return", "training_state", ".", "continue_centering", ".", "assign", "(", "center_bias", ")", "# Define ensemble growing operations.", "def", "_grow_ensemble_ready_fn", "(", ")", ":", "# Grow the ensemble given the current candidates.", "sizes", "=", "array_ops", ".", "unstack", "(", "split_sizes", ")", "partition_ids_list", "=", "list", "(", "array_ops", ".", "split", "(", "partition_ids", ",", "sizes", ",", "axis", "=", "0", ")", ")", "# When using the oblivious decision tree as weak learner, it produces", "# one gain and one split per handler and not number of partitions.", "if", "self", ".", "_learner_config", ".", "weak_learner_type", "==", "(", "learner_pb2", ".", "LearnerConfig", ".", "OBLIVIOUS_DECISION_TREE", ")", ":", "sizes", "=", "len", "(", "training_state", ".", "handlers", ")", "gains_list", "=", "list", "(", "array_ops", ".", "split", "(", "gains", ",", "sizes", ",", "axis", "=", "0", ")", ")", "split_info_list", "=", "list", "(", "array_ops", ".", "split", "(", "split_infos", ",", "sizes", ",", "axis", "=", "0", ")", ")", "return", "training_ops", ".", "grow_tree_ensemble", "(", "tree_ensemble_handle", "=", "self", ".", "_ensemble_handle", ",", "stamp_token", "=", "ensemble_stamp", ",", "next_stamp_token", "=", "next_ensemble_stamp", ",", "learning_rate", "=", "learning_rate", ",", "partition_ids", "=", "partition_ids_list", ",", "gains", "=", "gains_list", ",", "splits", "=", "split_info_list", ",", "learner_config", "=", "self", ".", "_learner_config_serialized", ",", "dropout_seed", "=", "dropout_seed", ",", "center_bias", "=", "self", ".", "_center_bias", ",", "max_tree_depth", "=", "self", ".", "_max_tree_depth", ",", "weak_learner_type", "=", "self", ".", "_learner_config", ".", "weak_learner_type", ")", "def", "_grow_ensemble_not_ready_fn", "(", ")", ":", "# Don't grow the ensemble, just update the stamp.", "return", "training_ops", ".", "grow_tree_ensemble", "(", "tree_ensemble_handle", "=", "self", ".", "_ensemble_handle", ",", "stamp_token", "=", "ensemble_stamp", ",", "next_stamp_token", "=", "next_ensemble_stamp", ",", "learning_rate", "=", "0", ",", "partition_ids", "=", "[", "]", ",", "gains", "=", "[", "]", ",", "splits", "=", "[", "]", ",", "learner_config", "=", "self", ".", "_learner_config_serialized", ",", "dropout_seed", "=", "dropout_seed", ",", "center_bias", "=", "self", ".", "_center_bias", ",", "max_tree_depth", "=", "self", ".", "_max_tree_depth", ",", "weak_learner_type", "=", "self", ".", "_learner_config", ".", "weak_learner_type", ")", "def", "_grow_ensemble_fn", "(", ")", ":", "# Conditionally grow an ensemble depending on whether the splits", "# from all the handlers are ready.", "return", "control_flow_ops", ".", "cond", "(", "are_all_splits_ready", ",", "_grow_ensemble_ready_fn", ",", "_grow_ensemble_not_ready_fn", ")", "# Update ensemble.", "update_ops", "=", "[", "are_all_splits_ready", "]", "if", "self", ".", "_center_bias", ":", "update_model", "=", "control_flow_ops", ".", "cond", "(", "training_state", ".", "continue_centering", ",", "_center_bias_fn", ",", "_grow_ensemble_fn", ")", "else", ":", "update_model", "=", "_grow_ensemble_fn", "(", ")", "update_ops", ".", "append", "(", "update_model", ")", "# Update ensemble stats.", "with", "ops", ".", "control_dependencies", "(", "[", "update_model", "]", ")", ":", "stats", "=", "training_ops", ".", "tree_ensemble_stats", "(", "self", ".", "_ensemble_handle", ",", "stamp_token", "=", "next_ensemble_stamp", ")", "update_ops", ".", "append", "(", "self", ".", "_finalized_trees", ".", "assign", "(", "stats", ".", "num_trees", ")", ")", "update_ops", ".", "append", "(", "self", ".", "_attempted_trees", ".", "assign", "(", "stats", ".", "attempted_trees", ")", ")", "update_ops", ".", "append", "(", "training_state", ".", "num_layers", ".", "assign", "(", "stats", ".", "num_layers", ")", ")", "update_ops", ".", "append", "(", "training_state", ".", "active_tree", ".", "assign", "(", "stats", ".", "active_tree", ")", ")", "update_ops", ".", "append", "(", "training_state", ".", "active_layer", ".", "assign", "(", "stats", ".", "active_layer", ")", ")", "# Flush step stats.", "update_ops", ".", "extend", "(", "training_state", ".", "steps_accumulator", ".", "flush", "(", "ensemble_stamp", ",", "next_ensemble_stamp", ")", ")", "return", "control_flow_ops", ".", "group", "(", "*", "update_ops", ",", "name", "=", "\"update_ensemble\"", ")", "return", "_update_ensemble" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py#L1040-L1180
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/check-if-a-parentheses-string-can-be-valid.py
python
Solution.canBeValid
(self, s, locked)
return True
:type s: str :type locked: str :rtype: bool
:type s: str :type locked: str :rtype: bool
[ ":", "type", "s", ":", "str", ":", "type", "locked", ":", "str", ":", "rtype", ":", "bool" ]
def canBeValid(self, s, locked): """ :type s: str :type locked: str :rtype: bool """ if len(s)%2: return False for direction, c in ((lambda x:x, '('), (reversed, ')')): cnt = bal = 0 for i in direction(xrange(len(s))): if locked[i] == '0': cnt += 1 else: bal += 1 if s[i] == c else -1 if cnt+bal < 0: return False return True
[ "def", "canBeValid", "(", "self", ",", "s", ",", "locked", ")", ":", "if", "len", "(", "s", ")", "%", "2", ":", "return", "False", "for", "direction", ",", "c", "in", "(", "(", "lambda", "x", ":", "x", ",", "'('", ")", ",", "(", "reversed", ",", "')'", ")", ")", ":", "cnt", "=", "bal", "=", "0", "for", "i", "in", "direction", "(", "xrange", "(", "len", "(", "s", ")", ")", ")", ":", "if", "locked", "[", "i", "]", "==", "'0'", ":", "cnt", "+=", "1", "else", ":", "bal", "+=", "1", "if", "s", "[", "i", "]", "==", "c", "else", "-", "1", "if", "cnt", "+", "bal", "<", "0", ":", "return", "False", "return", "True" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/check-if-a-parentheses-string-can-be-valid.py#L5-L22
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/aliaspass.py
python
AliasPass._IsTokenInParentBlock
(token, parent_block)
return False
Determines whether the given token is contained by the given block. Args: token: A token parent_block: An EcmaContext. Returns: Whether the token is in a context that is or is a child of the given parent_block context.
Determines whether the given token is contained by the given block.
[ "Determines", "whether", "the", "given", "token", "is", "contained", "by", "the", "given", "block", "." ]
def _IsTokenInParentBlock(token, parent_block): """Determines whether the given token is contained by the given block. Args: token: A token parent_block: An EcmaContext. Returns: Whether the token is in a context that is or is a child of the given parent_block context. """ context = token.metadata.context while context: if context is parent_block: return True context = context.parent return False
[ "def", "_IsTokenInParentBlock", "(", "token", ",", "parent_block", ")", ":", "context", "=", "token", ".", "metadata", ".", "context", "while", "context", ":", "if", "context", "is", "parent_block", ":", "return", "True", "context", "=", "context", ".", "parent", "return", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/aliaspass.py#L159-L177
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pprint.py
python
_safe_tuple
(t)
return _safe_key(t[0]), _safe_key(t[1])
Helper function for comparing 2-tuples
Helper function for comparing 2-tuples
[ "Helper", "function", "for", "comparing", "2", "-", "tuples" ]
def _safe_tuple(t): "Helper function for comparing 2-tuples" return _safe_key(t[0]), _safe_key(t[1])
[ "def", "_safe_tuple", "(", "t", ")", ":", "return", "_safe_key", "(", "t", "[", "0", "]", ")", ",", "_safe_key", "(", "t", "[", "1", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pprint.py#L94-L96
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
python
AppleScript_Suite_Events._3c_
(self, _object, _attributes={}, **_arguments)
<: Less than Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything
<: Less than Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything
[ "<", ":", "Less", "than", "Required", "argument", ":", "an", "AE", "object", "reference", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "anything" ]
def _3c_(self, _object, _attributes={}, **_arguments): """<: Less than Required argument: an AE object reference Keyword argument _attributes: AppleEvent attribute dictionary Returns: anything """ _code = 'ascr' _subcode = '< ' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "_3c_", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'ascr'", "_subcode", "=", "'< '", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L99-L118