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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/dataview.py
python
DataViewItemAttr.GetItalic
(*args, **kwargs)
return _dataview.DataViewItemAttr_GetItalic(*args, **kwargs)
GetItalic(self) -> bool
GetItalic(self) -> bool
[ "GetItalic", "(", "self", ")", "-", ">", "bool" ]
def GetItalic(*args, **kwargs): """GetItalic(self) -> bool""" return _dataview.DataViewItemAttr_GetItalic(*args, **kwargs)
[ "def", "GetItalic", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewItemAttr_GetItalic", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L365-L367
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py
python
ip_network
(address, strict=True)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set.
Take an IP string/int and return an object of the correct type.
[ "Take", "an", "IP", "string", "/", "int", "and", "return", "an", "object", "of", "the", "correct", "type", "." ]
def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address)
[ "def", "ip_network", "(", "address", ",", "strict", "=", "True", ")", ":", "try", ":", "return", "IPv4Network", "(", "address", ",", "strict", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Network", "(", "address", ",", "strict", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "raise", "ValueError", "(", "'%r does not appear to be an IPv4 or IPv6 network'", "%", "address", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L121-L148
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/linalg/special_matrices.py
python
invhilbert
(n, exact=False)
return invh
Compute the inverse of the Hilbert matrix of order `n`. The entries in the inverse of a Hilbert matrix are integers. When `n` is greater than 14, some entries in the inverse exceed the upper limit of 64 bit integers. The `exact` argument provides two options for dealing with these large integers. Parameters ---------- n : int The order of the Hilbert matrix. exact : bool, optional If False, the data type of the array that is returned is np.float64, and the array is an approximation of the inverse. If True, the array is the exact integer inverse array. To represent the exact inverse when n > 14, the returned array is an object array of long integers. For n <= 14, the exact inverse is returned as an array with data type np.int64. Returns ------- invh : (n, n) ndarray The data type of the array is np.float64 if `exact` is False. If `exact` is True, the data type is either np.int64 (for n <= 14) or object (for n > 14). In the latter case, the objects in the array will be long integers. See Also -------- hilbert : Create a Hilbert matrix. Notes ----- .. versionadded:: 0.10.0 Examples -------- >>> from scipy.linalg import invhilbert >>> invhilbert(4) array([[ 16., -120., 240., -140.], [ -120., 1200., -2700., 1680.], [ 240., -2700., 6480., -4200.], [ -140., 1680., -4200., 2800.]]) >>> invhilbert(4, exact=True) array([[ 16, -120, 240, -140], [ -120, 1200, -2700, 1680], [ 240, -2700, 6480, -4200], [ -140, 1680, -4200, 2800]], dtype=int64) >>> invhilbert(16)[7,7] 4.2475099528537506e+19 >>> invhilbert(16, exact=True)[7,7] 42475099528537378560L
Compute the inverse of the Hilbert matrix of order `n`.
[ "Compute", "the", "inverse", "of", "the", "Hilbert", "matrix", "of", "order", "n", "." ]
def invhilbert(n, exact=False): """ Compute the inverse of the Hilbert matrix of order `n`. The entries in the inverse of a Hilbert matrix are integers. When `n` is greater than 14, some entries in the inverse exceed the upper limit of 64 bit integers. The `exact` argument provides two options for dealing with these large integers. Parameters ---------- n : int The order of the Hilbert matrix. exact : bool, optional If False, the data type of the array that is returned is np.float64, and the array is an approximation of the inverse. If True, the array is the exact integer inverse array. To represent the exact inverse when n > 14, the returned array is an object array of long integers. For n <= 14, the exact inverse is returned as an array with data type np.int64. Returns ------- invh : (n, n) ndarray The data type of the array is np.float64 if `exact` is False. If `exact` is True, the data type is either np.int64 (for n <= 14) or object (for n > 14). In the latter case, the objects in the array will be long integers. See Also -------- hilbert : Create a Hilbert matrix. Notes ----- .. versionadded:: 0.10.0 Examples -------- >>> from scipy.linalg import invhilbert >>> invhilbert(4) array([[ 16., -120., 240., -140.], [ -120., 1200., -2700., 1680.], [ 240., -2700., 6480., -4200.], [ -140., 1680., -4200., 2800.]]) >>> invhilbert(4, exact=True) array([[ 16, -120, 240, -140], [ -120, 1200, -2700, 1680], [ 240, -2700, 6480, -4200], [ -140, 1680, -4200, 2800]], dtype=int64) >>> invhilbert(16)[7,7] 4.2475099528537506e+19 >>> invhilbert(16, exact=True)[7,7] 42475099528537378560L """ from scipy.special import comb if exact: if n > 14: dtype = object else: dtype = np.int64 else: dtype = np.float64 invh = np.empty((n, n), dtype=dtype) for i in xrange(n): for j in xrange(0, i + 1): s = i + j invh[i, j] = ((-1) ** s * (s + 1) * comb(n + i, n - j - 1, exact) * comb(n + j, n - i - 1, exact) * comb(s, i, exact) ** 2) if i != j: invh[j, i] = invh[i, j] return invh
[ "def", "invhilbert", "(", "n", ",", "exact", "=", "False", ")", ":", "from", "scipy", ".", "special", "import", "comb", "if", "exact", ":", "if", "n", ">", "14", ":", "dtype", "=", "object", "else", ":", "dtype", "=", "np", ".", "int64", "else", ":", "dtype", "=", "np", ".", "float64", "invh", "=", "np", ".", "empty", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", "dtype", ")", "for", "i", "in", "xrange", "(", "n", ")", ":", "for", "j", "in", "xrange", "(", "0", ",", "i", "+", "1", ")", ":", "s", "=", "i", "+", "j", "invh", "[", "i", ",", "j", "]", "=", "(", "(", "-", "1", ")", "**", "s", "*", "(", "s", "+", "1", ")", "*", "comb", "(", "n", "+", "i", ",", "n", "-", "j", "-", "1", ",", "exact", ")", "*", "comb", "(", "n", "+", "j", ",", "n", "-", "i", "-", "1", ",", "exact", ")", "*", "comb", "(", "s", ",", "i", ",", "exact", ")", "**", "2", ")", "if", "i", "!=", "j", ":", "invh", "[", "j", ",", "i", "]", "=", "invh", "[", "i", ",", "j", "]", "return", "invh" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/special_matrices.py#L702-L776
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/design-hashmap.py
python
MyHashMap.put
(self, key, value)
value will always be positive. :type key: int :type value: int :rtype: void
value will always be positive. :type key: int :type value: int :rtype: void
[ "value", "will", "always", "be", "positive", ".", ":", "type", "key", ":", "int", ":", "type", "value", ":", "int", ":", "rtype", ":", "void" ]
def put(self, key, value): """ value will always be positive. :type key: int :type value: int :rtype: void """ l = self.__data[key % len(self.__data)] node = l.find(key) if node: node.val = value else: l.insert(ListNode(key, value))
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "l", "=", "self", ".", "__data", "[", "key", "%", "len", "(", "self", ".", "__data", ")", "]", "node", "=", "l", ".", "find", "(", "key", ")", "if", "node", ":", "node", ".", "val", "=", "value", "else", ":", "l", ".", "insert", "(", "ListNode", "(", "key", ",", "value", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/design-hashmap.py#L54-L66
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/filters.py
python
_split_what
(what)
return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
Returns a tuple of `frozenset`s of classes and attributes.
Returns a tuple of `frozenset`s of classes and attributes.
[ "Returns", "a", "tuple", "of", "frozenset", "s", "of", "classes", "and", "attributes", "." ]
def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
[ "def", "_split_what", "(", "what", ")", ":", "return", "(", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isclass", "(", "cls", ")", ")", ",", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isinstance", "(", "cls", ",", "Attribute", ")", ")", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/filters.py#L11-L18
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/walterMayaTraverser.py
python
WalterMayaImplementation.setOverride
(self, origin, layer, path, material, overrideType)
Save the material from the Maya nodes. It's looking for the connections of the Walter Standin object and creates/replaces the connection to the material. Args: origin: The Walter Standin object that contains the tree. layer: Render layer to save the material. path: The Alembic path to the node. material: The material object overrideType: The type of the override. Example: shader/displacement
Save the material from the Maya nodes. It's looking for the connections of the Walter Standin object and creates/replaces the connection to the material.
[ "Save", "the", "material", "from", "the", "Maya", "nodes", ".", "It", "s", "looking", "for", "the", "connections", "of", "the", "Walter", "Standin", "object", "and", "creates", "/", "replaces", "the", "connection", "to", "the", "material", "." ]
def setOverride(self, origin, layer, path, material, overrideType): """ Save the material from the Maya nodes. It's looking for the connections of the Walter Standin object and creates/replaces the connection to the material. Args: origin: The Walter Standin object that contains the tree. layer: Render layer to save the material. path: The Alembic path to the node. material: The material object overrideType: The type of the override. Example: shader/displacement """ # Material materialNode = self.getDependNode(material) if not materialNode: om.MGlobal.displayError( "%s: Material %s doesn't exist." % (self.NAME, material)) return materialMessage = materialNode.findPlug("message", False) # Get walterStandin.layersAssignation layersAssignation = self.getLayersAssignationPlug(origin) # Get walterStandin.layersAssignation[i].shaderConnections shadersPlug = self.findShadersPlug(layersAssignation, layer) # Create if not found if not shadersPlug: # Get walterStandin.layersAssignation[i] layersAssignationPlug = self.addElementToPlug(layersAssignation) # Get walterStandin.layersAssignation[i].layer layerPlug = self.getChildMPlug(layersAssignationPlug, 'layer') # Get walterStandin.layersAssignation[i].shaderConnections shadersPlug = self.getChildMPlug( layersAssignationPlug, 'shaderConnections') # Connect the layer to the layerPlug layerDepend = self.getDependNode(layer) layerMessage = layerDepend.findPlug("message", False) self.modifier.connect(layerMessage, layerPlug) self.modifier.doIt() firstAvailableCompound = None # Find if there is already an assignment with this path for j in range(shadersPlug.numElements()): # Get walterStandin.layersAssignation[i].shaderConnections[j] shadersCompound = shadersPlug.elementByPhysicalIndex(j) # Get walterStandin.layersAssignation[].shaderConnections[j].abcnode abcnodePlug = self.getChildMPlug(shadersCompound, 'abcnode') abcnode = abcnodePlug.asString() if not firstAvailableCompound and not abcnode: # Save it to reuse in future and avoid creating new elements firstAvailableCompound = shadersCompound if abcnode != path: continue # We are here because we found requested assignment. We need to # change the connection with the shader # Get walterStandin.layersAssignation[i].shaderConnections[j].shader shaderPlug = self.getChildMPlug(shadersCompound, overrideType) self.disconnectPlug(shaderPlug) self.modifier.connect(materialMessage, shaderPlug) self.modifier.doIt() return # We are here because were unable to find the path. # Add an element to walterStandin.layersAssignation[i].shaderConnections # or use available if found shadersCompound = \ firstAvailableCompound or self.addElementToPlug(shadersPlug) # Get walterStandin.layersAssignation[i].shaderConnections[j].abcnode abcnodePlug = self.getChildMPlug(shadersCompound, 'abcnode') abcnodePlug.setString(path) # Get walterStandin.layersAssignation[i].shaderConnections[j].shader shaderPlug = self.getChildMPlug(shadersCompound, overrideType) self.disconnectPlug(shaderPlug) self.modifier.connect(materialMessage, shaderPlug) self.modifier.doIt()
[ "def", "setOverride", "(", "self", ",", "origin", ",", "layer", ",", "path", ",", "material", ",", "overrideType", ")", ":", "# Material", "materialNode", "=", "self", ".", "getDependNode", "(", "material", ")", "if", "not", "materialNode", ":", "om", ".", "MGlobal", ".", "displayError", "(", "\"%s: Material %s doesn't exist.\"", "%", "(", "self", ".", "NAME", ",", "material", ")", ")", "return", "materialMessage", "=", "materialNode", ".", "findPlug", "(", "\"message\"", ",", "False", ")", "# Get walterStandin.layersAssignation", "layersAssignation", "=", "self", ".", "getLayersAssignationPlug", "(", "origin", ")", "# Get walterStandin.layersAssignation[i].shaderConnections", "shadersPlug", "=", "self", ".", "findShadersPlug", "(", "layersAssignation", ",", "layer", ")", "# Create if not found", "if", "not", "shadersPlug", ":", "# Get walterStandin.layersAssignation[i]", "layersAssignationPlug", "=", "self", ".", "addElementToPlug", "(", "layersAssignation", ")", "# Get walterStandin.layersAssignation[i].layer", "layerPlug", "=", "self", ".", "getChildMPlug", "(", "layersAssignationPlug", ",", "'layer'", ")", "# Get walterStandin.layersAssignation[i].shaderConnections", "shadersPlug", "=", "self", ".", "getChildMPlug", "(", "layersAssignationPlug", ",", "'shaderConnections'", ")", "# Connect the layer to the layerPlug", "layerDepend", "=", "self", ".", "getDependNode", "(", "layer", ")", "layerMessage", "=", "layerDepend", ".", "findPlug", "(", "\"message\"", ",", "False", ")", "self", ".", "modifier", ".", "connect", "(", "layerMessage", ",", "layerPlug", ")", "self", ".", "modifier", ".", "doIt", "(", ")", "firstAvailableCompound", "=", "None", "# Find if there is already an assignment with this path", "for", "j", "in", "range", "(", "shadersPlug", ".", "numElements", "(", ")", ")", ":", "# Get walterStandin.layersAssignation[i].shaderConnections[j]", "shadersCompound", "=", "shadersPlug", ".", "elementByPhysicalIndex", "(", "j", ")", "# Get walterStandin.layersAssignation[].shaderConnections[j].abcnode", "abcnodePlug", "=", "self", ".", "getChildMPlug", "(", "shadersCompound", ",", "'abcnode'", ")", "abcnode", "=", "abcnodePlug", ".", "asString", "(", ")", "if", "not", "firstAvailableCompound", "and", "not", "abcnode", ":", "# Save it to reuse in future and avoid creating new elements", "firstAvailableCompound", "=", "shadersCompound", "if", "abcnode", "!=", "path", ":", "continue", "# We are here because we found requested assignment. We need to", "# change the connection with the shader", "# Get walterStandin.layersAssignation[i].shaderConnections[j].shader", "shaderPlug", "=", "self", ".", "getChildMPlug", "(", "shadersCompound", ",", "overrideType", ")", "self", ".", "disconnectPlug", "(", "shaderPlug", ")", "self", ".", "modifier", ".", "connect", "(", "materialMessage", ",", "shaderPlug", ")", "self", ".", "modifier", ".", "doIt", "(", ")", "return", "# We are here because were unable to find the path.", "# Add an element to walterStandin.layersAssignation[i].shaderConnections", "# or use available if found", "shadersCompound", "=", "firstAvailableCompound", "or", "self", ".", "addElementToPlug", "(", "shadersPlug", ")", "# Get walterStandin.layersAssignation[i].shaderConnections[j].abcnode", "abcnodePlug", "=", "self", ".", "getChildMPlug", "(", "shadersCompound", ",", "'abcnode'", ")", "abcnodePlug", ".", "setString", "(", "path", ")", "# Get walterStandin.layersAssignation[i].shaderConnections[j].shader", "shaderPlug", "=", "self", ".", "getChildMPlug", "(", "shadersCompound", ",", "overrideType", ")", "self", ".", "disconnectPlug", "(", "shaderPlug", ")", "self", ".", "modifier", ".", "connect", "(", "materialMessage", ",", "shaderPlug", ")", "self", ".", "modifier", ".", "doIt", "(", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/walterMayaTraverser.py#L105-L191
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
FindPaneInDock
(dock, window)
return None
This method looks up a specified window pointer inside a dock. If found, the corresponding :class:`AuiDockInfo` pointer is returned, otherwise ``None``. :param `dock`: a :class:`AuiDockInfo` structure; :param Window `window`: the window associated to the pane we are seeking.
This method looks up a specified window pointer inside a dock. If found, the corresponding :class:`AuiDockInfo` pointer is returned, otherwise ``None``.
[ "This", "method", "looks", "up", "a", "specified", "window", "pointer", "inside", "a", "dock", ".", "If", "found", "the", "corresponding", ":", "class", ":", "AuiDockInfo", "pointer", "is", "returned", "otherwise", "None", "." ]
def FindPaneInDock(dock, window): """ This method looks up a specified window pointer inside a dock. If found, the corresponding :class:`AuiDockInfo` pointer is returned, otherwise ``None``. :param `dock`: a :class:`AuiDockInfo` structure; :param Window `window`: the window associated to the pane we are seeking. """ for p in dock.panes: if p.window == window: return p return None
[ "def", "FindPaneInDock", "(", "dock", ",", "window", ")", ":", "for", "p", "in", "dock", ".", "panes", ":", "if", "p", ".", "window", "==", "window", ":", "return", "p", "return", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L3699-L3712
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/pytables.py
python
_ensure_decoded
(s)
return s
if we have bytes, decode them to unicode
if we have bytes, decode them to unicode
[ "if", "we", "have", "bytes", "decode", "them", "to", "unicode" ]
def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
[ "def", "_ensure_decoded", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "np", ".", "bytes_", ")", ":", "s", "=", "s", ".", "decode", "(", "'UTF-8'", ")", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L58-L62
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
RobotModelDriver.getValue
(self)
return _robotsim.RobotModelDriver_getValue(self)
getValue(RobotModelDriver self) -> double Gets the current driver value from the robot's config.
getValue(RobotModelDriver self) -> double
[ "getValue", "(", "RobotModelDriver", "self", ")", "-", ">", "double" ]
def getValue(self): """ getValue(RobotModelDriver self) -> double Gets the current driver value from the robot's config. """ return _robotsim.RobotModelDriver_getValue(self)
[ "def", "getValue", "(", "self", ")", ":", "return", "_robotsim", ".", "RobotModelDriver_getValue", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L4389-L4398
sailing-pmls/bosen
06cb58902d011fbea5f9428f10ce30e621492204
style_script/cpplint.py
python
ProcessConfigOverrides
(filename)
return True
Loads the configuration files and processes the config overrides. Args: filename: The name of the file being processed by the linter. Returns: False if the current |filename| should not be processed further.
Loads the configuration files and processes the config overrides.
[ "Loads", "the", "configuration", "files", "and", "processes", "the", "config", "overrides", "." ]
def ProcessConfigOverrides(filename): """ Loads the configuration files and processes the config overrides. Args: filename: The name of the file being processed by the linter. Returns: False if the current |filename| should not be processed further. """ abs_filename = os.path.abspath(filename) cfg_filters = [] keep_looking = True while keep_looking: abs_path, base_name = os.path.split(abs_filename) if not base_name: break # Reached the root directory. cfg_file = os.path.join(abs_path, "CPPLINT.cfg") abs_filename = abs_path if not os.path.isfile(cfg_file): continue try: with open(cfg_file) as file_handle: for line in file_handle: line, _, _ = line.partition('#') # Remove comments. if not line.strip(): continue name, _, val = line.partition('=') name = name.strip() val = val.strip() if name == 'set noparent': keep_looking = False elif name == 'filter': cfg_filters.append(val) elif name == 'exclude_files': # When matching exclude_files pattern, use the base_name of # the current file name or the directory name we are processing. # For example, if we are checking for lint errors in /foo/bar/baz.cc # and we found the .cfg file at /foo/CPPLINT.cfg, then the config # file's "exclude_files" filter is meant to be checked against "bar" # and not "baz" nor "bar/baz.cc". if base_name: pattern = re.compile(val) if pattern.match(base_name): sys.stderr.write('Ignoring "%s": file excluded by "%s". ' 'File path component "%s" matches ' 'pattern "%s"\n' % (filename, cfg_file, base_name, val)) return False elif name == 'linelength': global _line_length try: _line_length = int(val) except ValueError: sys.stderr.write('Line length must be numeric.') else: sys.stderr.write( 'Invalid configuration option (%s) in file %s\n' % (name, cfg_file)) except IOError: sys.stderr.write( "Skipping config file '%s': Can't open for reading\n" % cfg_file) keep_looking = False # Apply all the accumulated filters in reverse order (top-level directory # config options having the least priority). for filter in reversed(cfg_filters): _AddFilters(filter) return True
[ "def", "ProcessConfigOverrides", "(", "filename", ")", ":", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "cfg_filters", "=", "[", "]", "keep_looking", "=", "True", "while", "keep_looking", ":", "abs_path", ",", "base_name", "=", "os", ".", "path", ".", "split", "(", "abs_filename", ")", "if", "not", "base_name", ":", "break", "# Reached the root directory.", "cfg_file", "=", "os", ".", "path", ".", "join", "(", "abs_path", ",", "\"CPPLINT.cfg\"", ")", "abs_filename", "=", "abs_path", "if", "not", "os", ".", "path", ".", "isfile", "(", "cfg_file", ")", ":", "continue", "try", ":", "with", "open", "(", "cfg_file", ")", "as", "file_handle", ":", "for", "line", "in", "file_handle", ":", "line", ",", "_", ",", "_", "=", "line", ".", "partition", "(", "'#'", ")", "# Remove comments.", "if", "not", "line", ".", "strip", "(", ")", ":", "continue", "name", ",", "_", ",", "val", "=", "line", ".", "partition", "(", "'='", ")", "name", "=", "name", ".", "strip", "(", ")", "val", "=", "val", ".", "strip", "(", ")", "if", "name", "==", "'set noparent'", ":", "keep_looking", "=", "False", "elif", "name", "==", "'filter'", ":", "cfg_filters", ".", "append", "(", "val", ")", "elif", "name", "==", "'exclude_files'", ":", "# When matching exclude_files pattern, use the base_name of", "# the current file name or the directory name we are processing.", "# For example, if we are checking for lint errors in /foo/bar/baz.cc", "# and we found the .cfg file at /foo/CPPLINT.cfg, then the config", "# file's \"exclude_files\" filter is meant to be checked against \"bar\"", "# and not \"baz\" nor \"bar/baz.cc\".", "if", "base_name", ":", "pattern", "=", "re", ".", "compile", "(", "val", ")", "if", "pattern", ".", "match", "(", "base_name", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Ignoring \"%s\": file excluded by \"%s\". '", "'File path component \"%s\" matches '", "'pattern \"%s\"\\n'", "%", "(", "filename", ",", "cfg_file", ",", "base_name", ",", "val", ")", ")", "return", "False", "elif", "name", "==", "'linelength'", ":", "global", "_line_length", "try", ":", "_line_length", "=", "int", "(", "val", ")", "except", "ValueError", ":", "sys", ".", "stderr", ".", "write", "(", "'Line length must be numeric.'", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'Invalid configuration option (%s) in file %s\\n'", "%", "(", "name", ",", "cfg_file", ")", ")", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Skipping config file '%s': Can't open for reading\\n\"", "%", "cfg_file", ")", "keep_looking", "=", "False", "# Apply all the accumulated filters in reverse order (top-level directory", "# config options having the least priority).", "for", "filter", "in", "reversed", "(", "cfg_filters", ")", ":", "_AddFilters", "(", "filter", ")", "return", "True" ]
https://github.com/sailing-pmls/bosen/blob/06cb58902d011fbea5f9428f10ce30e621492204/style_script/cpplint.py#L6048-L6121
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Text.image_create
(self, index, cnf={}, **kw)
return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw))
Create an embedded image at INDEX.
Create an embedded image at INDEX.
[ "Create", "an", "embedded", "image", "at", "INDEX", "." ]
def image_create(self, index, cnf={}, **kw): """Create an embedded image at INDEX.""" return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw))
[ "def", "image_create", "(", "self", ",", "index", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"image\"", ",", "\"create\"", ",", "index", ",", "*", "self", ".", "_options", "(", "cnf", ",", "kw", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3034-L3038
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/importlib/resources.py
python
is_resource
(package: Package, name: str)
return path.is_file()
True if 'name' is a resource inside 'package'. Directories are *not* resources.
True if 'name' is a resource inside 'package'.
[ "True", "if", "name", "is", "a", "resource", "inside", "package", "." ]
def is_resource(package: Package, name: str) -> bool: """True if 'name' is a resource inside 'package'. Directories are *not* resources. """ package = _get_package(package) _normalize_path(name) reader = _get_resource_reader(package) if reader is not None: return reader.is_resource(name) try: package_contents = set(contents(package)) except (NotADirectoryError, FileNotFoundError): return False if name not in package_contents: return False # Just because the given file_name lives as an entry in the package's # contents doesn't necessarily mean it's a resource. Directories are not # resources, so let's try to find out if it's a directory or not. path = Path(package.__spec__.origin).parent / name return path.is_file()
[ "def", "is_resource", "(", "package", ":", "Package", ",", "name", ":", "str", ")", "->", "bool", ":", "package", "=", "_get_package", "(", "package", ")", "_normalize_path", "(", "name", ")", "reader", "=", "_get_resource_reader", "(", "package", ")", "if", "reader", "is", "not", "None", ":", "return", "reader", ".", "is_resource", "(", "name", ")", "try", ":", "package_contents", "=", "set", "(", "contents", "(", "package", ")", ")", "except", "(", "NotADirectoryError", ",", "FileNotFoundError", ")", ":", "return", "False", "if", "name", "not", "in", "package_contents", ":", "return", "False", "# Just because the given file_name lives as an entry in the package's", "# contents doesn't necessarily mean it's a resource. Directories are not", "# resources, so let's try to find out if it's a directory or not.", "path", "=", "Path", "(", "package", ".", "__spec__", ".", "origin", ")", ".", "parent", "/", "name", "return", "path", ".", "is_file", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/resources.py#L218-L238
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/tabbedpages.py
python
TabbedPageSet.remove_page
(self, page_name)
Destroy the page whose name is given in page_name.
Destroy the page whose name is given in page_name.
[ "Destroy", "the", "page", "whose", "name", "is", "given", "in", "page_name", "." ]
def remove_page(self, page_name): """Destroy the page whose name is given in page_name.""" if not page_name in self.pages: raise KeyError("No such TabPage: '%s" % page_name) self._pages_order.remove(page_name) # handle removing last remaining, default, or currently shown page if len(self._pages_order) > 0: if page_name == self._default_page: # set a new default page self._default_page = self._pages_order[0] else: self._default_page = None if page_name == self._current_page: self.change_page(self._default_page) self._tab_set.remove_tab(page_name) page = self.pages.pop(page_name) page.frame.destroy()
[ "def", "remove_page", "(", "self", ",", "page_name", ")", ":", "if", "not", "page_name", "in", "self", ".", "pages", ":", "raise", "KeyError", "(", "\"No such TabPage: '%s\"", "%", "page_name", ")", "self", ".", "_pages_order", ".", "remove", "(", "page_name", ")", "# handle removing last remaining, default, or currently shown page", "if", "len", "(", "self", ".", "_pages_order", ")", ">", "0", ":", "if", "page_name", "==", "self", ".", "_default_page", ":", "# set a new default page", "self", ".", "_default_page", "=", "self", ".", "_pages_order", "[", "0", "]", "else", ":", "self", ".", "_default_page", "=", "None", "if", "page_name", "==", "self", ".", "_current_page", ":", "self", ".", "change_page", "(", "self", ".", "_default_page", ")", "self", ".", "_tab_set", ".", "remove_tab", "(", "page_name", ")", "page", "=", "self", ".", "pages", ".", "pop", "(", "page_name", ")", "page", ".", "frame", ".", "destroy", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/tabbedpages.py#L431-L451
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Image.ResampleBicubic
(*args, **kwargs)
return _core_.Image_ResampleBicubic(*args, **kwargs)
ResampleBicubic(self, int width, int height) -> Image
ResampleBicubic(self, int width, int height) -> Image
[ "ResampleBicubic", "(", "self", "int", "width", "int", "height", ")", "-", ">", "Image" ]
def ResampleBicubic(*args, **kwargs): """ResampleBicubic(self, int width, int height) -> Image""" return _core_.Image_ResampleBicubic(*args, **kwargs)
[ "def", "ResampleBicubic", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_ResampleBicubic", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2930-L2932
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/coprocessing.py
python
CoProcessor.__AppendToCinemaDTable
(self, time, producer, filename)
This is called every time catalyst writes any data file or screenshot to update the Cinema D index of outputs table. Note, we aggregate file operations later with __FinalizeCinemaDTable.
This is called every time catalyst writes any data file or screenshot to update the Cinema D index of outputs table. Note, we aggregate file operations later with __FinalizeCinemaDTable.
[ "This", "is", "called", "every", "time", "catalyst", "writes", "any", "data", "file", "or", "screenshot", "to", "update", "the", "Cinema", "D", "index", "of", "outputs", "table", ".", "Note", "we", "aggregate", "file", "operations", "later", "with", "__FinalizeCinemaDTable", "." ]
def __AppendToCinemaDTable(self, time, producer, filename): """ This is called every time catalyst writes any data file or screenshot to update the Cinema D index of outputs table. Note, we aggregate file operations later with __FinalizeCinemaDTable. """ if self.__CinemaDHelper is None: return import vtk comm = vtk.vtkMultiProcessController.GetGlobalController() if comm.GetLocalProcessId() == 0: self.__CinemaDHelper.AppendToCinemaDTable(time, producer, filename)
[ "def", "__AppendToCinemaDTable", "(", "self", ",", "time", ",", "producer", ",", "filename", ")", ":", "if", "self", ".", "__CinemaDHelper", "is", "None", ":", "return", "import", "vtk", "comm", "=", "vtk", ".", "vtkMultiProcessController", ".", "GetGlobalController", "(", ")", "if", "comm", ".", "GetLocalProcessId", "(", ")", "==", "0", ":", "self", ".", "__CinemaDHelper", ".", "AppendToCinemaDTable", "(", "time", ",", "producer", ",", "filename", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/coprocessing.py#L859-L870
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp3/ctptd.py
python
CtpTd.onFrontConnected
(self)
当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
[ "当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。" ]
def onFrontConnected(self): """当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。""" reqLoginField = td.ReqUserLoginField() reqLoginField.userID = self._userID reqLoginField.password = self._password reqLoginField.brokerID = self._brokerID self._requestId += 1 self.reqUserLogin(reqLoginField, self._requestId)
[ "def", "onFrontConnected", "(", "self", ")", ":", "reqLoginField", "=", "td", ".", "ReqUserLoginField", "(", ")", "reqLoginField", ".", "userID", "=", "self", ".", "_userID", "reqLoginField", ".", "password", "=", "self", ".", "_password", "reqLoginField", ".", "brokerID", "=", "self", ".", "_brokerID", "self", ".", "_requestId", "+=", "1", "self", ".", "reqUserLogin", "(", "reqLoginField", ",", "self", ".", "_requestId", ")" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp3/ctptd.py#L34-L41
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/utils/http_server.py
python
KVHandler.do_PUT
(self)
put method for kv handler, set value according to key.
put method for kv handler, set value according to key.
[ "put", "method", "for", "kv", "handler", "set", "value", "according", "to", "key", "." ]
def do_PUT(self): """ put method for kv handler, set value according to key. """ log_str = "PUT " + self.address_string() + self.path paths = self.path.split('/') if len(paths) < 3: print('len of request path must be 3: ' + self.path) self.send_status_code(400) return _, scope, key = paths content_length = int(self.headers['Content-Length']) try: value = self.rfile.read(content_length) except: print("receive error invalid request") self.send_status_code(404) return with self.server.kv_lock: if self.server.kv.get(scope) is None: self.server.kv[scope] = {} self.server.kv[scope][key] = value self.send_status_code(200) _http_server_logger.info(log_str)
[ "def", "do_PUT", "(", "self", ")", ":", "log_str", "=", "\"PUT \"", "+", "self", ".", "address_string", "(", ")", "+", "self", ".", "path", "paths", "=", "self", ".", "path", ".", "split", "(", "'/'", ")", "if", "len", "(", "paths", ")", "<", "3", ":", "print", "(", "'len of request path must be 3: '", "+", "self", ".", "path", ")", "self", ".", "send_status_code", "(", "400", ")", "return", "_", ",", "scope", ",", "key", "=", "paths", "content_length", "=", "int", "(", "self", ".", "headers", "[", "'Content-Length'", "]", ")", "try", ":", "value", "=", "self", ".", "rfile", ".", "read", "(", "content_length", ")", "except", ":", "print", "(", "\"receive error invalid request\"", ")", "self", ".", "send_status_code", "(", "404", ")", "return", "with", "self", ".", "server", ".", "kv_lock", ":", "if", "self", ".", "server", ".", "kv", ".", "get", "(", "scope", ")", "is", "None", ":", "self", ".", "server", ".", "kv", "[", "scope", "]", "=", "{", "}", "self", ".", "server", ".", "kv", "[", "scope", "]", "[", "key", "]", "=", "value", "self", ".", "send_status_code", "(", "200", ")", "_http_server_logger", ".", "info", "(", "log_str", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/utils/http_server.py#L75-L98
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/__init__.py
python
_TimeoutMonitor.run
(self)
Check timeout on all responses. (Internal)
Check timeout on all responses. (Internal)
[ "Check", "timeout", "on", "all", "responses", ".", "(", "Internal", ")" ]
def run(self): """Check timeout on all responses. (Internal)""" for req, resp in self.servings: resp.check_timeout()
[ "def", "run", "(", "self", ")", ":", "for", "req", ",", "resp", "in", "self", ".", "servings", ":", "resp", ".", "check_timeout", "(", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/__init__.py#L112-L115
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlDoc.searchNsByHref
(self, node, href)
return __tmp
Search a Ns aliasing a given URI. Recurse on the parents until it finds the defined namespace or return None otherwise.
Search a Ns aliasing a given URI. Recurse on the parents until it finds the defined namespace or return None otherwise.
[ "Search", "a", "Ns", "aliasing", "a", "given", "URI", ".", "Recurse", "on", "the", "parents", "until", "it", "finds", "the", "defined", "namespace", "or", "return", "None", "otherwise", "." ]
def searchNsByHref(self, node, href): """Search a Ns aliasing a given URI. Recurse on the parents until it finds the defined namespace or return None otherwise. """ if node is None: node__o = None else: node__o = node._o ret = libxml2mod.xmlSearchNsByHref(self._o, node__o, href) if ret is None:raise treeError('xmlSearchNsByHref() failed') __tmp = xmlNs(_obj=ret) return __tmp
[ "def", "searchNsByHref", "(", "self", ",", "node", ",", "href", ")", ":", "if", "node", "is", "None", ":", "node__o", "=", "None", "else", ":", "node__o", "=", "node", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlSearchNsByHref", "(", "self", ".", "_o", ",", "node__o", ",", "href", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlSearchNsByHref() failed'", ")", "__tmp", "=", "xmlNs", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L3748-L3757
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Graph.collections
(self)
return list(self._collections)
Returns the names of the collections known to this graph.
Returns the names of the collections known to this graph.
[ "Returns", "the", "names", "of", "the", "collections", "known", "to", "this", "graph", "." ]
def collections(self): """Returns the names of the collections known to this graph.""" return list(self._collections)
[ "def", "collections", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_collections", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L2929-L2931
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/decorators.py
python
jit
(func_or_sig=None, argtypes=None, device=False, inline=False, bind=True, link=[], debug=None, **kws)
JIT compile a python function conforming to the CUDA Python specification. If a signature is supplied, then a function is returned that takes a function to compile. If :param func_or_sig: A function to JIT compile, or a signature of a function to compile. If a function is supplied, then an :class:`AutoJitCUDAKernel` is returned. If a signature is supplied, then a function which takes a function to compile and returns an :class:`AutoJitCUDAKernel` is returned. .. note:: A kernel cannot have any return value. :type func_or_sig: function or numba.typing.Signature :param device: Indicates whether this is a device function. :type device: bool :param bind: Force binding to CUDA context immediately :type bind: bool :param link: A list of files containing PTX source to link with the function :type link: list :param debug: If True, check for exceptions thrown when executing the kernel. Since this degrades performance, this should only be used for debugging purposes. Defaults to False. (The default value can be overridden by setting environment variable ``NUMBA_CUDA_DEBUGINFO=1``.) :param fastmath: If true, enables flush-to-zero and fused-multiply-add, disables precise division and square root. This parameter has no effect on device function, whose fastmath setting depends on the kernel function from which they are called. :param max_registers: Limit the kernel to using at most this number of registers per thread. Useful for increasing occupancy.
JIT compile a python function conforming to the CUDA Python specification. If a signature is supplied, then a function is returned that takes a function to compile. If
[ "JIT", "compile", "a", "python", "function", "conforming", "to", "the", "CUDA", "Python", "specification", ".", "If", "a", "signature", "is", "supplied", "then", "a", "function", "is", "returned", "that", "takes", "a", "function", "to", "compile", ".", "If" ]
def jit(func_or_sig=None, argtypes=None, device=False, inline=False, bind=True, link=[], debug=None, **kws): """ JIT compile a python function conforming to the CUDA Python specification. If a signature is supplied, then a function is returned that takes a function to compile. If :param func_or_sig: A function to JIT compile, or a signature of a function to compile. If a function is supplied, then an :class:`AutoJitCUDAKernel` is returned. If a signature is supplied, then a function which takes a function to compile and returns an :class:`AutoJitCUDAKernel` is returned. .. note:: A kernel cannot have any return value. :type func_or_sig: function or numba.typing.Signature :param device: Indicates whether this is a device function. :type device: bool :param bind: Force binding to CUDA context immediately :type bind: bool :param link: A list of files containing PTX source to link with the function :type link: list :param debug: If True, check for exceptions thrown when executing the kernel. Since this degrades performance, this should only be used for debugging purposes. Defaults to False. (The default value can be overridden by setting environment variable ``NUMBA_CUDA_DEBUGINFO=1``.) :param fastmath: If true, enables flush-to-zero and fused-multiply-add, disables precise division and square root. This parameter has no effect on device function, whose fastmath setting depends on the kernel function from which they are called. :param max_registers: Limit the kernel to using at most this number of registers per thread. Useful for increasing occupancy. """ debug = config.CUDA_DEBUGINFO_DEFAULT if debug is None else debug if link and config.ENABLE_CUDASIM: raise NotImplementedError('Cannot link PTX in the simulator') if 'boundscheck' in kws: raise NotImplementedError("bounds checking is not supported for CUDA") fastmath = kws.get('fastmath', False) if argtypes is None and not sigutils.is_signature(func_or_sig): if func_or_sig is None: if config.ENABLE_CUDASIM: def autojitwrapper(func): return FakeCUDAKernel(func, device=device, fastmath=fastmath, debug=debug) else: def autojitwrapper(func): return jit(func, device=device, bind=bind, debug=debug, **kws) return autojitwrapper # func_or_sig is a function else: if config.ENABLE_CUDASIM: return FakeCUDAKernel(func_or_sig, device=device, fastmath=fastmath, debug=debug) elif device: return jitdevice(func_or_sig, debug=debug, **kws) else: targetoptions = kws.copy() targetoptions['debug'] = debug return AutoJitCUDAKernel(func_or_sig, bind=bind, targetoptions=targetoptions) else: if config.ENABLE_CUDASIM: def jitwrapper(func): return FakeCUDAKernel(func, device=device, fastmath=fastmath, debug=debug) return jitwrapper restype, argtypes = convert_types(func_or_sig, argtypes) if restype and not device and restype != types.void: raise TypeError("CUDA kernel must have void return type.") def kernel_jit(func): kernel = compile_kernel(func, argtypes, link=link, debug=debug, inline=inline, fastmath=fastmath) # Force compilation for the current context if bind: kernel.bind() return kernel def device_jit(func): return compile_device(func, restype, argtypes, inline=inline, debug=debug) if device: return device_jit else: return kernel_jit
[ "def", "jit", "(", "func_or_sig", "=", "None", ",", "argtypes", "=", "None", ",", "device", "=", "False", ",", "inline", "=", "False", ",", "bind", "=", "True", ",", "link", "=", "[", "]", ",", "debug", "=", "None", ",", "*", "*", "kws", ")", ":", "debug", "=", "config", ".", "CUDA_DEBUGINFO_DEFAULT", "if", "debug", "is", "None", "else", "debug", "if", "link", "and", "config", ".", "ENABLE_CUDASIM", ":", "raise", "NotImplementedError", "(", "'Cannot link PTX in the simulator'", ")", "if", "'boundscheck'", "in", "kws", ":", "raise", "NotImplementedError", "(", "\"bounds checking is not supported for CUDA\"", ")", "fastmath", "=", "kws", ".", "get", "(", "'fastmath'", ",", "False", ")", "if", "argtypes", "is", "None", "and", "not", "sigutils", ".", "is_signature", "(", "func_or_sig", ")", ":", "if", "func_or_sig", "is", "None", ":", "if", "config", ".", "ENABLE_CUDASIM", ":", "def", "autojitwrapper", "(", "func", ")", ":", "return", "FakeCUDAKernel", "(", "func", ",", "device", "=", "device", ",", "fastmath", "=", "fastmath", ",", "debug", "=", "debug", ")", "else", ":", "def", "autojitwrapper", "(", "func", ")", ":", "return", "jit", "(", "func", ",", "device", "=", "device", ",", "bind", "=", "bind", ",", "debug", "=", "debug", ",", "*", "*", "kws", ")", "return", "autojitwrapper", "# func_or_sig is a function", "else", ":", "if", "config", ".", "ENABLE_CUDASIM", ":", "return", "FakeCUDAKernel", "(", "func_or_sig", ",", "device", "=", "device", ",", "fastmath", "=", "fastmath", ",", "debug", "=", "debug", ")", "elif", "device", ":", "return", "jitdevice", "(", "func_or_sig", ",", "debug", "=", "debug", ",", "*", "*", "kws", ")", "else", ":", "targetoptions", "=", "kws", ".", "copy", "(", ")", "targetoptions", "[", "'debug'", "]", "=", "debug", "return", "AutoJitCUDAKernel", "(", "func_or_sig", ",", "bind", "=", "bind", ",", "targetoptions", "=", "targetoptions", ")", "else", ":", "if", "config", ".", "ENABLE_CUDASIM", ":", "def", "jitwrapper", "(", "func", ")", ":", "return", "FakeCUDAKernel", "(", "func", ",", "device", "=", "device", ",", "fastmath", "=", "fastmath", ",", "debug", "=", "debug", ")", "return", "jitwrapper", "restype", ",", "argtypes", "=", "convert_types", "(", "func_or_sig", ",", "argtypes", ")", "if", "restype", "and", "not", "device", "and", "restype", "!=", "types", ".", "void", ":", "raise", "TypeError", "(", "\"CUDA kernel must have void return type.\"", ")", "def", "kernel_jit", "(", "func", ")", ":", "kernel", "=", "compile_kernel", "(", "func", ",", "argtypes", ",", "link", "=", "link", ",", "debug", "=", "debug", ",", "inline", "=", "inline", ",", "fastmath", "=", "fastmath", ")", "# Force compilation for the current context", "if", "bind", ":", "kernel", ".", "bind", "(", ")", "return", "kernel", "def", "device_jit", "(", "func", ")", ":", "return", "compile_device", "(", "func", ",", "restype", ",", "argtypes", ",", "inline", "=", "inline", ",", "debug", "=", "debug", ")", "if", "device", ":", "return", "device_jit", "else", ":", "return", "kernel_jit" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/decorators.py#L18-L112
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
python/caffe/io.py
python
load_image
(filename, color=True)
return img
Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Returns ------- image : an image with type np.float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale.
Load an image converting from grayscale or alpha as needed.
[ "Load", "an", "image", "converting", "from", "grayscale", "or", "alpha", "as", "needed", "." ]
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Returns ------- image : an image with type np.float32 in range [0, 1] of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale. """ img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32) if img.ndim == 2: img = img[:, :, np.newaxis] if color: img = np.tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img
[ "def", "load_image", "(", "filename", ",", "color", "=", "True", ")", ":", "img", "=", "skimage", ".", "img_as_float", "(", "skimage", ".", "io", ".", "imread", "(", "filename", ",", "as_grey", "=", "not", "color", ")", ")", ".", "astype", "(", "np", ".", "float32", ")", "if", "img", ".", "ndim", "==", "2", ":", "img", "=", "img", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "if", "color", ":", "img", "=", "np", ".", "tile", "(", "img", ",", "(", "1", ",", "1", ",", "3", ")", ")", "elif", "img", ".", "shape", "[", "2", "]", "==", "4", ":", "img", "=", "img", "[", ":", ",", ":", ",", ":", "3", "]", "return", "img" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/python/caffe/io.py#L279-L303
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/moduleconfig.py
python
discover_modules
(module_root, allowed_modules)
return found_modules
Scans module_root for subdirectories that look like MongoDB modules. Returns a list of imported build.py module objects.
Scans module_root for subdirectories that look like MongoDB modules.
[ "Scans", "module_root", "for", "subdirectories", "that", "look", "like", "MongoDB", "modules", "." ]
def discover_modules(module_root, allowed_modules): """Scans module_root for subdirectories that look like MongoDB modules. Returns a list of imported build.py module objects. """ found_modules = [] if allowed_modules is not None: allowed_modules = allowed_modules.split(',') if not os.path.isdir(module_root): return found_modules for name in os.listdir(module_root): root = os.path.join(module_root, name) if name.startswith('.') or not os.path.isdir(root): continue build_py = os.path.join(root, 'build.py') module = None if allowed_modules is not None and name not in allowed_modules: print "skipping module: %s" % name continue if os.path.isfile(build_py): print "adding module: %s" % name fp = open(build_py, "r") try: module = imp.load_module("module_" + name, fp, build_py, (".py", "r", imp.PY_SOURCE)) if getattr(module, "name", None) is None: module.name = name found_modules.append(module) finally: fp.close() return found_modules
[ "def", "discover_modules", "(", "module_root", ",", "allowed_modules", ")", ":", "found_modules", "=", "[", "]", "if", "allowed_modules", "is", "not", "None", ":", "allowed_modules", "=", "allowed_modules", ".", "split", "(", "','", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "module_root", ")", ":", "return", "found_modules", "for", "name", "in", "os", ".", "listdir", "(", "module_root", ")", ":", "root", "=", "os", ".", "path", ".", "join", "(", "module_root", ",", "name", ")", "if", "name", ".", "startswith", "(", "'.'", ")", "or", "not", "os", ".", "path", ".", "isdir", "(", "root", ")", ":", "continue", "build_py", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'build.py'", ")", "module", "=", "None", "if", "allowed_modules", "is", "not", "None", "and", "name", "not", "in", "allowed_modules", ":", "print", "\"skipping module: %s\"", "%", "name", "continue", "if", "os", ".", "path", ".", "isfile", "(", "build_py", ")", ":", "print", "\"adding module: %s\"", "%", "name", "fp", "=", "open", "(", "build_py", ",", "\"r\"", ")", "try", ":", "module", "=", "imp", ".", "load_module", "(", "\"module_\"", "+", "name", ",", "fp", ",", "build_py", ",", "(", "\".py\"", ",", "\"r\"", ",", "imp", ".", "PY_SOURCE", ")", ")", "if", "getattr", "(", "module", ",", "\"name\"", ",", "None", ")", "is", "None", ":", "module", ".", "name", "=", "name", "found_modules", ".", "append", "(", "module", ")", "finally", ":", "fp", ".", "close", "(", ")", "return", "found_modules" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/moduleconfig.py#L34-L71
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/RemoteDebugger.py
python
start_debugger
(rpchandler, gui_adap_oid)
return idb_adap_oid
Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy.
Start the debugger and its RPC link in the Python subprocess
[ "Start", "the", "debugger", "and", "its", "RPC", "link", "in", "the", "Python", "subprocess" ]
def start_debugger(rpchandler, gui_adap_oid): """Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy. """ gui_proxy = GUIProxy(rpchandler, gui_adap_oid) idb = Debugger.Idb(gui_proxy) idb_adap = IdbAdapter(idb) rpchandler.register(idb_adap_oid, idb_adap) return idb_adap_oid
[ "def", "start_debugger", "(", "rpchandler", ",", "gui_adap_oid", ")", ":", "gui_proxy", "=", "GUIProxy", "(", "rpchandler", ",", "gui_adap_oid", ")", "idb", "=", "Debugger", ".", "Idb", "(", "gui_proxy", ")", "idb_adap", "=", "IdbAdapter", "(", "idb", ")", "rpchandler", ".", "register", "(", "idb_adap_oid", ",", "idb_adap", ")", "return", "idb_adap_oid" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/RemoteDebugger.py#L176-L190
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.DoDropText
(*args, **kwargs)
return _stc.StyledTextCtrl_DoDropText(*args, **kwargs)
DoDropText(self, long x, long y, String data) -> bool Allow for simulating a DnD DropText.
DoDropText(self, long x, long y, String data) -> bool
[ "DoDropText", "(", "self", "long", "x", "long", "y", "String", "data", ")", "-", ">", "bool" ]
def DoDropText(*args, **kwargs): """ DoDropText(self, long x, long y, String data) -> bool Allow for simulating a DnD DropText. """ return _stc.StyledTextCtrl_DoDropText(*args, **kwargs)
[ "def", "DoDropText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_DoDropText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6661-L6667
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
llvm/utils/lit/lit/util.py
python
to_unicode
(s)
return s
Return the parameter as type which supports unicode, possibly decoding it. In Python2, this is the unicode type. In Python3 it's the str type.
Return the parameter as type which supports unicode, possibly decoding it.
[ "Return", "the", "parameter", "as", "type", "which", "supports", "unicode", "possibly", "decoding", "it", "." ]
def to_unicode(s): """Return the parameter as type which supports unicode, possibly decoding it. In Python2, this is the unicode type. In Python3 it's the str type. """ if isinstance(s, bytes): # In Python2, this branch is taken for both 'str' and 'bytes'. # In Python3, this branch is taken only for 'bytes'. return s.decode('utf-8') return s
[ "def", "to_unicode", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "# In Python2, this branch is taken for both 'str' and 'bytes'.", "# In Python3, this branch is taken only for 'bytes'.", "return", "s", ".", "decode", "(", "'utf-8'", ")", "return", "s" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/utils/lit/lit/util.py#L98-L109
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/framework_parser.py
python
FrameworkParser.save_path
(self)
return os.path.realpath(os.path.join(self._output_path, self.output_file_format.format(rank_id=self._rank_id)))
The property of save path. Returns: str, the save path.
The property of save path.
[ "The", "property", "of", "save", "path", "." ]
def save_path(self): """ The property of save path. Returns: str, the save path. """ return os.path.realpath(os.path.join(self._output_path, self.output_file_format.format(rank_id=self._rank_id)))
[ "def", "save_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_output_path", ",", "self", ".", "output_file_format", ".", "format", "(", "rank_id", "=", "self", ".", "_rank_id", ")", ")", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/framework_parser.py#L80-L87
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py
python
asarray
(obj, itemsize=None, unicode=None, order=None)
return array(obj, itemsize, copy=False, unicode=unicode, order=order)
Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest).
Convert the input to a `chararray`, copying the data only if necessary.
[ "Convert", "the", "input", "to", "a", "chararray", "copying", "the", "data", "only", "if", "necessary", "." ]
def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order)
[ "def", "asarray", "(", "obj", ",", "itemsize", "=", "None", ",", "unicode", "=", "None", ",", "order", "=", "None", ")", ":", "return", "array", "(", "obj", ",", "itemsize", ",", "copy", "=", "False", ",", "unicode", "=", "unicode", ",", "order", "=", "order", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py#L2770-L2819
coinapi/coinapi-sdk
854f21e7f69ea8599ae35c5403565cf299d8b795
oeml-sdk/python/openapi_client/model/order_cancel_all_request.py
python
OrderCancelAllRequest.__init__
(self, exchange_id, *args, **kwargs)
OrderCancelAllRequest - a model defined in OpenAPI Args: exchange_id (str): Identifier of the exchange from which active orders should be canceled. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,)
OrderCancelAllRequest - a model defined in OpenAPI
[ "OrderCancelAllRequest", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, exchange_id, *args, **kwargs): # noqa: E501 """OrderCancelAllRequest - a model defined in OpenAPI Args: exchange_id (str): Identifier of the exchange from which active orders should be canceled. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.exchange_id = exchange_id for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
[ "def", "__init__", "(", "self", ",", "exchange_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "_check_type", "=", "kwargs", ".", "pop", "(", "'_check_type'", ",", "True", ")", "_spec_property_naming", "=", "kwargs", ".", "pop", "(", "'_spec_property_naming'", ",", "False", ")", "_path_to_item", "=", "kwargs", ".", "pop", "(", "'_path_to_item'", ",", "(", ")", ")", "_configuration", "=", "kwargs", ".", "pop", "(", "'_configuration'", ",", "None", ")", "_visited_composed_classes", "=", "kwargs", ".", "pop", "(", "'_visited_composed_classes'", ",", "(", ")", ")", "if", "args", ":", "raise", "ApiTypeError", "(", "\"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.\"", "%", "(", "args", ",", "self", ".", "__class__", ".", "__name__", ",", ")", ",", "path_to_item", "=", "_path_to_item", ",", "valid_classes", "=", "(", "self", ".", "__class__", ",", ")", ",", ")", "self", ".", "_data_store", "=", "{", "}", "self", ".", "_check_type", "=", "_check_type", "self", ".", "_spec_property_naming", "=", "_spec_property_naming", "self", ".", "_path_to_item", "=", "_path_to_item", "self", ".", "_configuration", "=", "_configuration", "self", ".", "_visited_composed_classes", "=", "_visited_composed_classes", "+", "(", "self", ".", "__class__", ",", ")", "self", ".", "exchange_id", "=", "exchange_id", "for", "var_name", ",", "var_value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "var_name", "not", "in", "self", ".", "attribute_map", "and", "self", ".", "_configuration", "is", "not", "None", "and", "self", ".", "_configuration", ".", "discard_unknown_keys", "and", "self", ".", "additional_properties_type", "is", "None", ":", "# discard variable.", "continue", "setattr", "(", "self", ",", "var_name", ",", "var_value", ")", "if", "var_name", "in", "self", ".", "read_only_vars", ":", "raise", "ApiAttributeError", "(", "f\"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate \"", "f\"class with read only attributes.\"", ")" ]
https://github.com/coinapi/coinapi-sdk/blob/854f21e7f69ea8599ae35c5403565cf299d8b795/oeml-sdk/python/openapi_client/model/order_cancel_all_request.py#L189-L262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/weakref.py
python
finalize.alive
(self)
return self in self._registry
Whether finalizer is alive
Whether finalizer is alive
[ "Whether", "finalizer", "is", "alive" ]
def alive(self): """Whether finalizer is alive""" return self in self._registry
[ "def", "alive", "(", "self", ")", ":", "return", "self", "in", "self", ".", "_registry" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/weakref.py#L591-L593
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetWrapperExtension
(self)
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.
[ "Returns", "the", "bundle", "extension", "(", ".", "app", ".", "framework", ".", "plugin", "etc", ")", ".", "Only", "valid", "for", "bundles", "." ]
def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('loadable_module', 'shared_library'): default_wrapper_extension = { 'loadable_module': 'bundle', 'shared_library': 'framework', }[self.spec['type']] wrapper_extension = self.GetPerTargetSetting( 'WRAPPER_EXTENSION', default=default_wrapper_extension) return '.' + self.spec.get('product_extension', wrapper_extension) elif self.spec['type'] == 'executable': if self._IsIosAppExtension() or self._IsIosWatchKitExtension(): return '.' + self.spec.get('product_extension', 'appex') else: return '.' + self.spec.get('product_extension', 'app') else: assert False, "Don't know extension for '%s', target '%s'" % ( self.spec['type'], self.spec['target_name'])
[ "def", "GetWrapperExtension", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'loadable_module'", ",", "'shared_library'", ")", ":", "default_wrapper_extension", "=", "{", "'loadable_module'", ":", "'bundle'", ",", "'shared_library'", ":", "'framework'", ",", "}", "[", "self", ".", "spec", "[", "'type'", "]", "]", "wrapper_extension", "=", "self", ".", "GetPerTargetSetting", "(", "'WRAPPER_EXTENSION'", ",", "default", "=", "default_wrapper_extension", ")", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "wrapper_extension", ")", "elif", "self", ".", "spec", "[", "'type'", "]", "==", "'executable'", ":", "if", "self", ".", "_IsIosAppExtension", "(", ")", "or", "self", ".", "_IsIosWatchKitExtension", "(", ")", ":", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "'appex'", ")", "else", ":", "return", "'.'", "+", "self", ".", "spec", ".", "get", "(", "'product_extension'", ",", "'app'", ")", "else", ":", "assert", "False", ",", "\"Don't know extension for '%s', target '%s'\"", "%", "(", "self", ".", "spec", "[", "'type'", "]", ",", "self", ".", "spec", "[", "'target_name'", "]", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/xcode_emulation.py#L242-L261
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py
python
NamespaceInputReader.split_input
(cls, mapper_spec)
return [NamespaceInputReader(ns_range, batch_size) for ns_range in namespace_ranges]
Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Returns: A list of InputReaders.
Returns a list of input readers for the input spec.
[ "Returns", "a", "list", "of", "input", "readers", "for", "the", "input", "spec", "." ]
def split_input(cls, mapper_spec): """Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Returns: A list of InputReaders. """ batch_size = int(_get_params(mapper_spec).get( cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE)) shard_count = mapper_spec.shard_count namespace_ranges = namespace_range.NamespaceRange.split(shard_count, contiguous=True) return [NamespaceInputReader(ns_range, batch_size) for ns_range in namespace_ranges]
[ "def", "split_input", "(", "cls", ",", "mapper_spec", ")", ":", "batch_size", "=", "int", "(", "_get_params", "(", "mapper_spec", ")", ".", "get", "(", "cls", ".", "BATCH_SIZE_PARAM", ",", "cls", ".", "_BATCH_SIZE", ")", ")", "shard_count", "=", "mapper_spec", ".", "shard_count", "namespace_ranges", "=", "namespace_range", ".", "NamespaceRange", ".", "split", "(", "shard_count", ",", "contiguous", "=", "True", ")", "return", "[", "NamespaceInputReader", "(", "ns_range", ",", "batch_size", ")", "for", "ns_range", "in", "namespace_ranges", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L1990-L2005
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
NV_ReadPublicResponse.__init__
(self, nvPublic = None, nvName = None)
This command is used to read the public area and Name of an NV Index. The public area of an Index is not privacy-sensitive and no authorization is required to read this data. Attributes: nvPublic (TPMS_NV_PUBLIC): The public area of the NV Index nvName (bytes): The Name of the nvIndex
This command is used to read the public area and Name of an NV Index. The public area of an Index is not privacy-sensitive and no authorization is required to read this data.
[ "This", "command", "is", "used", "to", "read", "the", "public", "area", "and", "Name", "of", "an", "NV", "Index", ".", "The", "public", "area", "of", "an", "Index", "is", "not", "privacy", "-", "sensitive", "and", "no", "authorization", "is", "required", "to", "read", "this", "data", "." ]
def __init__(self, nvPublic = None, nvName = None): """ This command is used to read the public area and Name of an NV Index. The public area of an Index is not privacy-sensitive and no authorization is required to read this data. Attributes: nvPublic (TPMS_NV_PUBLIC): The public area of the NV Index nvName (bytes): The Name of the nvIndex """ self.nvPublic = nvPublic self.nvName = nvName
[ "def", "__init__", "(", "self", ",", "nvPublic", "=", "None", ",", "nvName", "=", "None", ")", ":", "self", ".", "nvPublic", "=", "nvPublic", "self", ".", "nvName", "=", "nvName" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16717-L16727
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_PCR_SELECTION.initFromTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def initFromTpm(self, buf): """ TpmMarshaller method """ self.hash = buf.readShort() self.pcrSelect = buf.readSizedByteBuf(1)
[ "def", "initFromTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "hash", "=", "buf", ".", "readShort", "(", ")", "self", ".", "pcrSelect", "=", "buf", ".", "readSizedByteBuf", "(", "1", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4067-L4070
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/_filetree.py
python
FileTree.DoBeginEdit
(self, item)
return False
Overridable method that will be called when a user has started to edit an item. @param item: TreeItem return: bool (True == Allow Edit)
Overridable method that will be called when a user has started to edit an item. @param item: TreeItem return: bool (True == Allow Edit)
[ "Overridable", "method", "that", "will", "be", "called", "when", "a", "user", "has", "started", "to", "edit", "an", "item", ".", "@param", "item", ":", "TreeItem", "return", ":", "bool", "(", "True", "==", "Allow", "Edit", ")" ]
def DoBeginEdit(self, item): """Overridable method that will be called when a user has started to edit an item. @param item: TreeItem return: bool (True == Allow Edit) """ return False
[ "def", "DoBeginEdit", "(", "self", ",", "item", ")", ":", "return", "False" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/_filetree.py#L119-L126
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/dox/proc_doc.py
python
RawTextToTextNodeConverter.handleCommand
(self, token)
Handle command for the given token.
Handle command for the given token.
[ "Handle", "command", "for", "the", "given", "token", "." ]
def handleCommand(self, token): """Handle command for the given token.""" if self.current_cmd: # There is a command active if token.type == self.command_pairs[self.current_cmd]: # closing current self.handleCommandClosing() # handle closing of command else: # not closing current self.tokens_cmd.append(token) else: # no command active, open if not token.type in self.command_pairs.keys(): expected = map(dox_tokens.transToken, self.command_pairs.keys()) raise dox_parser.ParserError(token, 'Unexpected token. Must be one of %s' % expected) self.current_cmd = token.type
[ "def", "handleCommand", "(", "self", ",", "token", ")", ":", "if", "self", ".", "current_cmd", ":", "# There is a command active", "if", "token", ".", "type", "==", "self", ".", "command_pairs", "[", "self", ".", "current_cmd", "]", ":", "# closing current", "self", ".", "handleCommandClosing", "(", ")", "# handle closing of command", "else", ":", "# not closing current", "self", ".", "tokens_cmd", ".", "append", "(", "token", ")", "else", ":", "# no command active, open", "if", "not", "token", ".", "type", "in", "self", ".", "command_pairs", ".", "keys", "(", ")", ":", "expected", "=", "map", "(", "dox_tokens", ".", "transToken", ",", "self", ".", "command_pairs", ".", "keys", "(", ")", ")", "raise", "dox_parser", ".", "ParserError", "(", "token", ",", "'Unexpected token. Must be one of %s'", "%", "expected", ")", "self", ".", "current_cmd", "=", "token", ".", "type" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/proc_doc.py#L1005-L1016
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
utils/check_cfc/obj_diff.py
python
compare_exact
(objfilea, objfileb)
return filecmp.cmp(objfilea, objfileb)
Byte for byte comparison between object files. Returns True if equal, False otherwise.
Byte for byte comparison between object files. Returns True if equal, False otherwise.
[ "Byte", "for", "byte", "comparison", "between", "object", "files", ".", "Returns", "True", "if", "equal", "False", "otherwise", "." ]
def compare_exact(objfilea, objfileb): """Byte for byte comparison between object files. Returns True if equal, False otherwise. """ return filecmp.cmp(objfilea, objfileb)
[ "def", "compare_exact", "(", "objfilea", ",", "objfileb", ")", ":", "return", "filecmp", ".", "cmp", "(", "objfilea", ",", "objfileb", ")" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/utils/check_cfc/obj_diff.py#L86-L90
choasup/caffe-yolo9000
e8a476c4c23d756632f7a26c681a96e3ab672544
scripts/cpp_lint.py
python
RemoveMultiLineComments
(filename, lines, error)
Removes multiline (c-style) comments from lines.
Removes multiline (c-style) comments from lines.
[ "Removes", "multiline", "(", "c", "-", "style", ")", "comments", "from", "lines", "." ]
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", "if", "lineix_begin", ">=", "len", "(", "lines", ")", ":", "return", "lineix_end", "=", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix_begin", ")", "if", "lineix_end", ">=", "len", "(", "lines", ")", ":", "error", "(", "filename", ",", "lineix_begin", "+", "1", ",", "'readability/multiline_comment'", ",", "5", ",", "'Could not find end of multi-line comment'", ")", "return", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "lineix_begin", ",", "lineix_end", "+", "1", ")", "lineix", "=", "lineix_end", "+", "1" ]
https://github.com/choasup/caffe-yolo9000/blob/e8a476c4c23d756632f7a26c681a96e3ab672544/scripts/cpp_lint.py#L1151-L1164
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/run.py
python
MyHandler.EOFhook
(self)
Override SocketIO method - terminate wait on callback and exit thread
Override SocketIO method - terminate wait on callback and exit thread
[ "Override", "SocketIO", "method", "-", "terminate", "wait", "on", "callback", "and", "exit", "thread" ]
def EOFhook(self): "Override SocketIO method - terminate wait on callback and exit thread" global quitting quitting = True thread.interrupt_main()
[ "def", "EOFhook", "(", "self", ")", ":", "global", "quitting", "quitting", "=", "True", "thread", ".", "interrupt_main", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/run.py#L521-L525
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Tools/ccroot.py
python
add_objects_from_tgen
(self, tg)
Add the objects from the depending compiled tasks as link task inputs. Some objects are filtered: for instance, .pdb files are added to the compiled tasks but not to the link tasks (to avoid errors) PRIVATE INTERNAL USE ONLY
Add the objects from the depending compiled tasks as link task inputs.
[ "Add", "the", "objects", "from", "the", "depending", "compiled", "tasks", "as", "link", "task", "inputs", "." ]
def add_objects_from_tgen(self, tg): """ Add the objects from the depending compiled tasks as link task inputs. Some objects are filtered: for instance, .pdb files are added to the compiled tasks but not to the link tasks (to avoid errors) PRIVATE INTERNAL USE ONLY """ try: link_task = self.link_task except AttributeError: pass else: for tsk in getattr(tg, 'compiled_tasks', []): for x in tsk.outputs: if self.accept_node_to_link(x): link_task.inputs.append(x)
[ "def", "add_objects_from_tgen", "(", "self", ",", "tg", ")", ":", "try", ":", "link_task", "=", "self", ".", "link_task", "except", "AttributeError", ":", "pass", "else", ":", "for", "tsk", "in", "getattr", "(", "tg", ",", "'compiled_tasks'", ",", "[", "]", ")", ":", "for", "x", "in", "tsk", ".", "outputs", ":", "if", "self", ".", "accept_node_to_link", "(", "x", ")", ":", "link_task", ".", "inputs", ".", "append", "(", "x", ")" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/ccroot.py#L426-L442
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
utils/llvm-build/llvmbuild/main.py
python
cmake_quote_string
(value)
return value
cmake_quote_string(value) -> str Return a quoted form of the given value that is suitable for use in CMake language files.
cmake_quote_string(value) -> str
[ "cmake_quote_string", "(", "value", ")", "-", ">", "str" ]
def cmake_quote_string(value): """ cmake_quote_string(value) -> str Return a quoted form of the given value that is suitable for use in CMake language files. """ # Currently, we only handle escaping backslashes. value = value.replace("\\", "\\\\") return value
[ "def", "cmake_quote_string", "(", "value", ")", ":", "# Currently, we only handle escaping backslashes.", "value", "=", "value", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", "return", "value" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/utils/llvm-build/llvmbuild/main.py#L13-L24
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/virtualpop.py
python
IndividualMotorcycles.get_ids_veh_pop
(self)
return self.parent.ids_imoto
To be overridden by other individual vehicle types.
To be overridden by other individual vehicle types.
[ "To", "be", "overridden", "by", "other", "individual", "vehicle", "types", "." ]
def get_ids_veh_pop(self): """ To be overridden by other individual vehicle types. """ return self.parent.ids_imoto
[ "def", "get_ids_veh_pop", "(", "self", ")", ":", "return", "self", ".", "parent", ".", "ids_imoto" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/virtualpop.py#L962-L966
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/input.py
python
DependencyGraphNode.DirectAndImportedDependencies
(self, targets, dependencies=None)
return self._AddImportedDependencies(targets, dependencies)
Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for.
Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for.
[ "Returns", "a", "list", "of", "a", "target", "s", "direct", "dependencies", "and", "all", "indirect", "dependencies", "that", "a", "dependency", "has", "advertised", "settings", "should", "be", "exported", "through", "the", "dependency", "for", "." ]
def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies)
[ "def", "DirectAndImportedDependencies", "(", "self", ",", "targets", ",", "dependencies", "=", "None", ")", ":", "dependencies", "=", "self", ".", "DirectDependencies", "(", "dependencies", ")", "return", "self", ".", "_AddImportedDependencies", "(", "targets", ",", "dependencies", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/input.py#L1426-L1433
koying/SPMC
beca52667112f2661204ebb42406115825512491
tools/EventClients/lib/python/xbmcclient.py
python
XBMCClient.send_log
(self, loglevel=0, logmessage="", autoprint=True)
return packet.send(self.sock, self.addr, self.uid)
Keyword arguments: loglevel -- the loglevel, follows XBMC standard. logmessage -- the message to log autoprint -- if the logmessage should automaticly be printed to stdout
Keyword arguments: loglevel -- the loglevel, follows XBMC standard. logmessage -- the message to log autoprint -- if the logmessage should automaticly be printed to stdout
[ "Keyword", "arguments", ":", "loglevel", "--", "the", "loglevel", "follows", "XBMC", "standard", ".", "logmessage", "--", "the", "message", "to", "log", "autoprint", "--", "if", "the", "logmessage", "should", "automaticly", "be", "printed", "to", "stdout" ]
def send_log(self, loglevel=0, logmessage="", autoprint=True): """ Keyword arguments: loglevel -- the loglevel, follows XBMC standard. logmessage -- the message to log autoprint -- if the logmessage should automaticly be printed to stdout """ packet = PacketLOG(loglevel, logmessage) return packet.send(self.sock, self.addr, self.uid)
[ "def", "send_log", "(", "self", ",", "loglevel", "=", "0", ",", "logmessage", "=", "\"\"", ",", "autoprint", "=", "True", ")", ":", "packet", "=", "PacketLOG", "(", "loglevel", ",", "logmessage", ")", "return", "packet", ".", "send", "(", "self", ".", "sock", ",", "self", ".", "addr", ",", "self", ".", "uid", ")" ]
https://github.com/koying/SPMC/blob/beca52667112f2661204ebb42406115825512491/tools/EventClients/lib/python/xbmcclient.py#L611-L619
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/Maya_AnimationRiggingTools/ArtToolsOSX/MayaTools/General/Scripts/P4.py
python
Map.is_empty
(self)
return self.count() == 0
Returns True if this map has no entries yet, otherwise False
Returns True if this map has no entries yet, otherwise False
[ "Returns", "True", "if", "this", "map", "has", "no", "entries", "yet", "otherwise", "False" ]
def is_empty(self): """Returns True if this map has no entries yet, otherwise False""" return self.count() == 0
[ "def", "is_empty", "(", "self", ")", ":", "return", "self", ".", "count", "(", ")", "==", "0" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/Maya_AnimationRiggingTools/ArtToolsOSX/MayaTools/General/Scripts/P4.py#L390-L392
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py
python
Checker.build_tokens_line
(self)
return mapping
Build a logical line from tokens.
Build a logical line from tokens.
[ "Build", "a", "logical", "line", "from", "tokens", "." ]
def build_tokens_line(self): """Build a logical line from tokens.""" logical = [] comments = [] length = 0 prev_row = prev_col = mapping = None for token_type, text, start, end, line in self.tokens: if token_type in SKIP_TOKENS: continue if not mapping: mapping = [(0, start)] if token_type == tokenize.COMMENT: comments.append(text) continue if token_type == tokenize.STRING: text = mute_string(text) if prev_row: (start_row, start_col) = start if prev_row != start_row: # different row prev_text = self.lines[prev_row - 1][prev_col - 1] if prev_text == ',' or (prev_text not in '{[(' and text not in '}])'): text = ' ' + text elif prev_col != start_col: # different column text = line[prev_col:start_col] + text logical.append(text) length += len(text) mapping.append((length, end)) (prev_row, prev_col) = end self.logical_line = ''.join(logical) self.noqa = comments and noqa(''.join(comments)) return mapping
[ "def", "build_tokens_line", "(", "self", ")", ":", "logical", "=", "[", "]", "comments", "=", "[", "]", "length", "=", "0", "prev_row", "=", "prev_col", "=", "mapping", "=", "None", "for", "token_type", ",", "text", ",", "start", ",", "end", ",", "line", "in", "self", ".", "tokens", ":", "if", "token_type", "in", "SKIP_TOKENS", ":", "continue", "if", "not", "mapping", ":", "mapping", "=", "[", "(", "0", ",", "start", ")", "]", "if", "token_type", "==", "tokenize", ".", "COMMENT", ":", "comments", ".", "append", "(", "text", ")", "continue", "if", "token_type", "==", "tokenize", ".", "STRING", ":", "text", "=", "mute_string", "(", "text", ")", "if", "prev_row", ":", "(", "start_row", ",", "start_col", ")", "=", "start", "if", "prev_row", "!=", "start_row", ":", "# different row", "prev_text", "=", "self", ".", "lines", "[", "prev_row", "-", "1", "]", "[", "prev_col", "-", "1", "]", "if", "prev_text", "==", "','", "or", "(", "prev_text", "not", "in", "'{[('", "and", "text", "not", "in", "'}])'", ")", ":", "text", "=", "' '", "+", "text", "elif", "prev_col", "!=", "start_col", ":", "# different column", "text", "=", "line", "[", "prev_col", ":", "start_col", "]", "+", "text", "logical", ".", "append", "(", "text", ")", "length", "+=", "len", "(", "text", ")", "mapping", ".", "append", "(", "(", "length", ",", "end", ")", ")", "(", "prev_row", ",", "prev_col", ")", "=", "end", "self", ".", "logical_line", "=", "''", ".", "join", "(", "logical", ")", "self", ".", "noqa", "=", "comments", "and", "noqa", "(", "''", ".", "join", "(", "comments", ")", ")", "return", "mapping" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py#L1291-L1322
lynckia/licode
a892fbec56191ce21deb962fdd2a1f68c653dc23
erizo/utils/conan-include-paths/conanfile.py
python
IncludePathsGenerator.content
(self)
return " ".join(flag for flag in flags if flag)
With compiler_args you can invoke your compiler: $ gcc main.c @conanbuildinfo.args -o main $ clang main.c @conanbuildinfo.args -o main $ cl /EHsc main.c @conanbuildinfo.args
With compiler_args you can invoke your compiler: $ gcc main.c
[ "With", "compiler_args", "you", "can", "invoke", "your", "compiler", ":", "$", "gcc", "main", ".", "c" ]
def content(self): """With compiler_args you can invoke your compiler: $ gcc main.c @conanbuildinfo.args -o main $ clang main.c @conanbuildinfo.args -o main $ cl /EHsc main.c @conanbuildinfo.args """ flags = [] #flags.extend(format_defines(self._deps_build_info.defines)) flags.extend(format_include_paths(self._deps_build_info.include_paths, settings=self.conanfile.settings)) #flags.extend(self._deps_build_info.cxxflags) #flags.extend(self._deps_build_info.cflags) #arch_flag = architecture_flag(arch=self.conanfile.settings.get_safe("arch"), # compiler=self.compiler) #if arch_flag: # flags.append(arch_flag) #build_type = self.conanfile.settings.get_safe("build_type") #btfs = build_type_flags(compiler=self.compiler, build_type=build_type, # vs_toolset=self.conanfile.settings.get_safe("compiler.toolset")) #if btfs: # flags.extend(btfs) #btd = build_type_define(build_type=build_type) #if btd: # flags.extend(format_defines([btd])) #if self.compiler == "Visual Studio": # runtime = visual_runtime(self.conanfile.settings.get_safe("compiler.runtime")) # if runtime: # flags.append(runtime) # # Necessary in the "cl" invocation before specify the rest of linker flags # flags.append(visual_linker_option_separator) #the_os = (self.conanfile.settings.get_safe("os_build") or # self.conanfile.settings.get_safe("os")) #flags.extend(rpath_flags(the_os, self.compiler, self._deps_build_info.lib_paths)) #flags.extend(format_library_paths(self._deps_build_info.lib_paths, compiler=self.compiler)) #flags.extend(format_libraries(self._deps_build_info.libs, compiler=self.compiler)) #flags.extend(self._deps_build_info.sharedlinkflags) #flags.extend(self._deps_build_info.exelinkflags) #flags.extend(self._libcxx_flags()) #flags.append(cppstd_flag(self.conanfile.settings.get_safe("compiler"), # self.conanfile.settings.get_safe("compiler.version"), # self.conanfile.settings.get_safe("cppstd"))) #sysrf = sysroot_flag(self._deps_build_info.sysroot, compiler=self.compiler) #if sysrf: # flags.append(sysrf) return " ".join(flag for flag in flags if flag)
[ "def", "content", "(", "self", ")", ":", "flags", "=", "[", "]", "#flags.extend(format_defines(self._deps_build_info.defines))", "flags", ".", "extend", "(", "format_include_paths", "(", "self", ".", "_deps_build_info", ".", "include_paths", ",", "settings", "=", "self", ".", "conanfile", ".", "settings", ")", ")", "#flags.extend(self._deps_build_info.cxxflags)", "#flags.extend(self._deps_build_info.cflags)", "#arch_flag = architecture_flag(arch=self.conanfile.settings.get_safe(\"arch\"),", "# compiler=self.compiler)", "#if arch_flag:", "# flags.append(arch_flag)", "#build_type = self.conanfile.settings.get_safe(\"build_type\")", "#btfs = build_type_flags(compiler=self.compiler, build_type=build_type,", "# vs_toolset=self.conanfile.settings.get_safe(\"compiler.toolset\"))", "#if btfs:", "# flags.extend(btfs)", "#btd = build_type_define(build_type=build_type)", "#if btd:", "# flags.extend(format_defines([btd]))", "#if self.compiler == \"Visual Studio\":", "# runtime = visual_runtime(self.conanfile.settings.get_safe(\"compiler.runtime\"))", "# if runtime:", "# flags.append(runtime)", "# # Necessary in the \"cl\" invocation before specify the rest of linker flags", "# flags.append(visual_linker_option_separator)", "#the_os = (self.conanfile.settings.get_safe(\"os_build\") or", "# self.conanfile.settings.get_safe(\"os\"))", "#flags.extend(rpath_flags(the_os, self.compiler, self._deps_build_info.lib_paths))", "#flags.extend(format_library_paths(self._deps_build_info.lib_paths, compiler=self.compiler))", "#flags.extend(format_libraries(self._deps_build_info.libs, compiler=self.compiler))", "#flags.extend(self._deps_build_info.sharedlinkflags)", "#flags.extend(self._deps_build_info.exelinkflags)", "#flags.extend(self._libcxx_flags())", "#flags.append(cppstd_flag(self.conanfile.settings.get_safe(\"compiler\"),", "# self.conanfile.settings.get_safe(\"compiler.version\"),", "# self.conanfile.settings.get_safe(\"cppstd\")))", "#sysrf = sysroot_flag(self._deps_build_info.sysroot, compiler=self.compiler)", "#if sysrf:", "# flags.append(sysrf)", "return", "\" \"", ".", "join", "(", "flag", "for", "flag", "in", "flags", "if", "flag", ")" ]
https://github.com/lynckia/licode/blob/a892fbec56191ce21deb962fdd2a1f68c653dc23/erizo/utils/conan-include-paths/conanfile.py#L25-L75
sccn/lsl_archived
2ff44b7a5172b02fe845b1fc72b9ab5578a489ed
LSL/liblsl-Python/pylsl/pylsl.py
python
resolve_byprop
(prop, value, minimum=1, timeout=FOREVER)
return [StreamInfo(handle=buffer[k]) for k in range(num_found)]
Resolve all streams with a specific value for a given property. If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. Keyword arguments: prop -- The StreamInfo property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). value -- The string value that the property should have (e.g., "EEG" as the type property). minimum -- Return at least this many streams. (default 1) timeout -- Optionally a timeout of the operation, in seconds. If the timeout expires, less than the desired number of streams (possibly none) will be returned. (default FOREVER) Returns a list of matching StreamInfo objects (with empty desc field), any of which can subsequently be used to open an inlet. Example: results = resolve_Stream_byprop("type","EEG")
Resolve all streams with a specific value for a given property.
[ "Resolve", "all", "streams", "with", "a", "specific", "value", "for", "a", "given", "property", "." ]
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER): """Resolve all streams with a specific value for a given property. If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. Keyword arguments: prop -- The StreamInfo property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). value -- The string value that the property should have (e.g., "EEG" as the type property). minimum -- Return at least this many streams. (default 1) timeout -- Optionally a timeout of the operation, in seconds. If the timeout expires, less than the desired number of streams (possibly none) will be returned. (default FOREVER) Returns a list of matching StreamInfo objects (with empty desc field), any of which can subsequently be used to open an inlet. Example: results = resolve_Stream_byprop("type","EEG") """ # noinspection PyCallingNonCallable buffer = (c_void_p*1024)() num_found = lib.lsl_resolve_byprop(byref(buffer), 1024, c_char_p(str.encode(prop)), c_char_p(str.encode(value)), minimum, c_double(timeout)) return [StreamInfo(handle=buffer[k]) for k in range(num_found)]
[ "def", "resolve_byprop", "(", "prop", ",", "value", ",", "minimum", "=", "1", ",", "timeout", "=", "FOREVER", ")", ":", "# noinspection PyCallingNonCallable", "buffer", "=", "(", "c_void_p", "*", "1024", ")", "(", ")", "num_found", "=", "lib", ".", "lsl_resolve_byprop", "(", "byref", "(", "buffer", ")", ",", "1024", ",", "c_char_p", "(", "str", ".", "encode", "(", "prop", ")", ")", ",", "c_char_p", "(", "str", ".", "encode", "(", "value", ")", ")", ",", "minimum", ",", "c_double", "(", "timeout", ")", ")", "return", "[", "StreamInfo", "(", "handle", "=", "buffer", "[", "k", "]", ")", "for", "k", "in", "range", "(", "num_found", ")", "]" ]
https://github.com/sccn/lsl_archived/blob/2ff44b7a5172b02fe845b1fc72b9ab5578a489ed/LSL/liblsl-Python/pylsl/pylsl.py#L538-L567
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py
python
FindMinMaxSumCntFromData
(inputcsData, inVariableInfo, inSecondaryVariableInfo, DataMinMax, DataSumCnt, DataForIds, inPlotIdLineList)
fairly complex high level mpi-operation routine. This takes a paraview filter client side object, gets the client side data (which is presumably a multiblock dataset) and finds the min, max, sum, and count of items for a variable. It uses MPI (if the item is not global) to share values and get them across all processors. Used for plotting min/max/mean and for evaluating boolean criteria (such as whether or not to produce images) for min/max /mean/count. Data return is a bit messy and should be updated--it fills in DataMinMax, DataSumCnt, and DataForIds if it is not None
fairly complex high level mpi-operation routine. This takes a paraview filter client side object, gets the client side data (which is presumably a multiblock dataset) and finds the min, max, sum, and count of items for a variable. It uses MPI (if the item is not global) to share values and get them across all processors. Used for plotting min/max/mean and for evaluating boolean criteria (such as whether or not to produce images) for min/max /mean/count. Data return is a bit messy and should be updated--it fills in DataMinMax, DataSumCnt, and DataForIds if it is not None
[ "fairly", "complex", "high", "level", "mpi", "-", "operation", "routine", ".", "This", "takes", "a", "paraview", "filter", "client", "side", "object", "gets", "the", "client", "side", "data", "(", "which", "is", "presumably", "a", "multiblock", "dataset", ")", "and", "finds", "the", "min", "max", "sum", "and", "count", "of", "items", "for", "a", "variable", ".", "It", "uses", "MPI", "(", "if", "the", "item", "is", "not", "global", ")", "to", "share", "values", "and", "get", "them", "across", "all", "processors", ".", "Used", "for", "plotting", "min", "/", "max", "/", "mean", "and", "for", "evaluating", "boolean", "criteria", "(", "such", "as", "whether", "or", "not", "to", "produce", "images", ")", "for", "min", "/", "max", "/", "mean", "/", "count", ".", "Data", "return", "is", "a", "bit", "messy", "and", "should", "be", "updated", "--", "it", "fills", "in", "DataMinMax", "DataSumCnt", "and", "DataForIds", "if", "it", "is", "not", "None" ]
def FindMinMaxSumCntFromData(inputcsData, inVariableInfo, inSecondaryVariableInfo, DataMinMax, DataSumCnt, DataForIds, inPlotIdLineList): """fairly complex high level mpi-operation routine. This takes a paraview filter client side object, gets the client side data (which is presumably a multiblock dataset) and finds the min, max, sum, and count of items for a variable. It uses MPI (if the item is not global) to share values and get them across all processors. Used for plotting min/max/mean and for evaluating boolean criteria (such as whether or not to produce images) for min/max /mean/count. Data return is a bit messy and should be updated--it fills in DataMinMax, DataSumCnt, and DataForIds if it is not None""" if PhactoriDbg(): myDebugPrint3("FindMinMaxSumCntFromData entered\n") FindMinMaxSumCntFromDataRecurse1(inputcsData, inVariableInfo, inSecondaryVariableInfo, DataMinMax, DataSumCnt, DataForIds, inPlotIdLineList) #if variable is global, it is same on all processors so we don't need to do #any mpi communication if inVariableInfo.mVariableType != 'global': #do mpi to share values around UseReduceToSumDoubleAndIntPair(DataSumCnt) if DataSumCnt[1] == 0: #no data; we shouldn't add anything to plot lines if PhactoriDbg(100): myDebugPrint3('no data for variable; returning\n', 100) return #bad situation; if we have no data on this processor we don't want #it to mess up other processors min/max if DataMinMax[2] == False: DataMinMax[0] = sys.float_info.max DataMinMax[1] = -sys.float_info.max UseReduceToGetMinMaxPairs(DataMinMax) if DataForIds != None: UseReduceToSpreadValues(DataForIds) if PhactoriDbg(): myDebugPrint3('min/max result: ' + str(DataMinMax) + '\n') if PhactoriDbg(): myDebugPrint3(' sum result: ' + str(DataSumCnt[0]) + ' count result: ' + str(DataSumCnt[1]) + '\n') #myDebugPrint3(' average result: ' + str(DataSumCnt[0]/DataSumCnt[1]) + '\n') if PhactoriDbg(): myDebugPrint3(' average result: ' + \ str(DataSumCnt[0]/float(DataSumCnt[1])) + '\n') if PhactoriDbg(): myDebugPrint3('DataForIds result: ' + str(DataForIds) + '\n') inVariableInfo.mStats.mMin = DataMinMax[0] inVariableInfo.mStats.mMax = DataMinMax[1] inVariableInfo.mStats.mSum = DataSumCnt[0] inVariableInfo.mStats.mCount = DataSumCnt[1] inVariableInfo.mStats.mStatsTestCounter = \ gPipeAndViewsState.mFrameTagCounter if PhactoriDbg(): myDebugPrint3("FindMinMaxSumCntFromData returning\n")
[ "def", "FindMinMaxSumCntFromData", "(", "inputcsData", ",", "inVariableInfo", ",", "inSecondaryVariableInfo", ",", "DataMinMax", ",", "DataSumCnt", ",", "DataForIds", ",", "inPlotIdLineList", ")", ":", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"FindMinMaxSumCntFromData entered\\n\"", ")", "FindMinMaxSumCntFromDataRecurse1", "(", "inputcsData", ",", "inVariableInfo", ",", "inSecondaryVariableInfo", ",", "DataMinMax", ",", "DataSumCnt", ",", "DataForIds", ",", "inPlotIdLineList", ")", "#if variable is global, it is same on all processors so we don't need to do", "#any mpi communication", "if", "inVariableInfo", ".", "mVariableType", "!=", "'global'", ":", "#do mpi to share values around", "UseReduceToSumDoubleAndIntPair", "(", "DataSumCnt", ")", "if", "DataSumCnt", "[", "1", "]", "==", "0", ":", "#no data; we shouldn't add anything to plot lines", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "'no data for variable; returning\\n'", ",", "100", ")", "return", "#bad situation; if we have no data on this processor we don't want", "#it to mess up other processors min/max", "if", "DataMinMax", "[", "2", "]", "==", "False", ":", "DataMinMax", "[", "0", "]", "=", "sys", ".", "float_info", ".", "max", "DataMinMax", "[", "1", "]", "=", "-", "sys", ".", "float_info", ".", "max", "UseReduceToGetMinMaxPairs", "(", "DataMinMax", ")", "if", "DataForIds", "!=", "None", ":", "UseReduceToSpreadValues", "(", "DataForIds", ")", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "'min/max result: '", "+", "str", "(", "DataMinMax", ")", "+", "'\\n'", ")", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "' sum result: '", "+", "str", "(", "DataSumCnt", "[", "0", "]", ")", "+", "' count result: '", "+", "str", "(", "DataSumCnt", "[", "1", "]", ")", "+", "'\\n'", ")", "#myDebugPrint3(' average result: ' + str(DataSumCnt[0]/DataSumCnt[1]) + '\\n')", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "' average result: '", "+", "str", "(", "DataSumCnt", "[", "0", "]", "/", "float", "(", "DataSumCnt", "[", "1", "]", ")", ")", "+", "'\\n'", ")", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "'DataForIds result: '", "+", "str", "(", "DataForIds", ")", "+", "'\\n'", ")", "inVariableInfo", ".", "mStats", ".", "mMin", "=", "DataMinMax", "[", "0", "]", "inVariableInfo", ".", "mStats", ".", "mMax", "=", "DataMinMax", "[", "1", "]", "inVariableInfo", ".", "mStats", ".", "mSum", "=", "DataSumCnt", "[", "0", "]", "inVariableInfo", ".", "mStats", ".", "mCount", "=", "DataSumCnt", "[", "1", "]", "inVariableInfo", ".", "mStats", ".", "mStatsTestCounter", "=", "gPipeAndViewsState", ".", "mFrameTagCounter", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"FindMinMaxSumCntFromData returning\\n\"", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py#L14475-L14535
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/_bsplines.py
python
_get_dtype
(dtype)
Return np.complex128 for complex dtypes, np.float64 otherwise.
Return np.complex128 for complex dtypes, np.float64 otherwise.
[ "Return", "np", ".", "complex128", "for", "complex", "dtypes", "np", ".", "float64", "otherwise", "." ]
def _get_dtype(dtype): """Return np.complex128 for complex dtypes, np.float64 otherwise.""" if np.issubdtype(dtype, np.complexfloating): return np.complex_ else: return np.float_
[ "def", "_get_dtype", "(", "dtype", ")", ":", "if", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "complexfloating", ")", ":", "return", "np", ".", "complex_", "else", ":", "return", "np", ".", "float_" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/_bsplines.py#L25-L30
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Tensor.set_shape
(self, shape)
Updates the shape of this tensor. This method can be called multiple times, and will merge the given `shape` with the current shape of this tensor. It can be used to provide additional information about the shape of this tensor that cannot be inferred from the graph alone. For example, this can be used to provide additional information about the shapes of images: ```python _, image_data = tf.TFRecordReader(...).read(...) image = tf.image.decode_png(image_data, channels=3) # The height and width dimensions of `image` are data dependent, and # cannot be computed without executing the op. print(image.get_shape()) ==> TensorShape([Dimension(None), Dimension(None), Dimension(3)]) # We know that each image in this dataset is 28 x 28 pixels. image.set_shape([28, 28, 3]) print(image.get_shape()) ==> TensorShape([Dimension(28), Dimension(28), Dimension(3)]) ``` Args: shape: A `TensorShape` representing the shape of this tensor. Raises: ValueError: If `shape` is not compatible with the current shape of this tensor.
Updates the shape of this tensor.
[ "Updates", "the", "shape", "of", "this", "tensor", "." ]
def set_shape(self, shape): """Updates the shape of this tensor. This method can be called multiple times, and will merge the given `shape` with the current shape of this tensor. It can be used to provide additional information about the shape of this tensor that cannot be inferred from the graph alone. For example, this can be used to provide additional information about the shapes of images: ```python _, image_data = tf.TFRecordReader(...).read(...) image = tf.image.decode_png(image_data, channels=3) # The height and width dimensions of `image` are data dependent, and # cannot be computed without executing the op. print(image.get_shape()) ==> TensorShape([Dimension(None), Dimension(None), Dimension(3)]) # We know that each image in this dataset is 28 x 28 pixels. image.set_shape([28, 28, 3]) print(image.get_shape()) ==> TensorShape([Dimension(28), Dimension(28), Dimension(3)]) ``` Args: shape: A `TensorShape` representing the shape of this tensor. Raises: ValueError: If `shape` is not compatible with the current shape of this tensor. """ self._shape = self._shape.merge_with(shape)
[ "def", "set_shape", "(", "self", ",", "shape", ")", ":", "self", ".", "_shape", "=", "self", ".", "_shape", ".", "merge_with", "(", "shape", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L377-L408
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/sysconfig.py
python
_main
()
Display all information sysconfig detains.
Display all information sysconfig detains.
[ "Display", "all", "information", "sysconfig", "detains", "." ]
def _main(): """Display all information sysconfig detains.""" if '--generate-posix-vars' in sys.argv: _generate_posix_vars() return print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
[ "def", "_main", "(", ")", ":", "if", "'--generate-posix-vars'", "in", "sys", ".", "argv", ":", "_generate_posix_vars", "(", ")", "return", "print", "(", "'Platform: \"%s\"'", "%", "get_platform", "(", ")", ")", "print", "(", "'Python version: \"%s\"'", "%", "get_python_version", "(", ")", ")", "print", "(", "'Current installation scheme: \"%s\"'", "%", "_get_default_scheme", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Paths'", ",", "get_paths", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Variables'", ",", "get_config_vars", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/sysconfig.py#L692-L703
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py
python
define_unary_op
(op_name, elementwise_function)
return op
Define a unary operation for labeled tensors. Args: op_name: string name of the TensorFlow op. elementwise_function: function to call to evaluate the op on a single tf.Tensor object. This function must accept two arguments: a tf.Tensor object, and an optional `name`. Returns: Function defining the given op that acts on LabeledTensors.
Define a unary operation for labeled tensors.
[ "Define", "a", "unary", "operation", "for", "labeled", "tensors", "." ]
def define_unary_op(op_name, elementwise_function): """Define a unary operation for labeled tensors. Args: op_name: string name of the TensorFlow op. elementwise_function: function to call to evaluate the op on a single tf.Tensor object. This function must accept two arguments: a tf.Tensor object, and an optional `name`. Returns: Function defining the given op that acts on LabeledTensors. """ default_name = 'lt_%s' % op_name @tc.returns(LabeledTensor) @tc.accepts(LabeledTensorLike, tc.Optional(string_types)) def op(labeled_tensor, name=None): """LabeledTensor version of `tf.{op_name}`. See `tf.{op_name}` for full details. Args: labeled_tensor: Input tensor. name: Optional op name. Returns: A LabeledTensor with result of applying `tf.{op_name}` elementwise. """ with ops.name_scope(name, default_name, [labeled_tensor]) as scope: labeled_tensor = convert_to_labeled_tensor(labeled_tensor) result_tensor = elementwise_function(labeled_tensor.tensor, name=scope) return LabeledTensor(result_tensor, labeled_tensor.axes) op.__doc__ = op.__doc__.format(op_name=op_name) op.__name__ = op_name return op
[ "def", "define_unary_op", "(", "op_name", ",", "elementwise_function", ")", ":", "default_name", "=", "'lt_%s'", "%", "op_name", "@", "tc", ".", "returns", "(", "LabeledTensor", ")", "@", "tc", ".", "accepts", "(", "LabeledTensorLike", ",", "tc", ".", "Optional", "(", "string_types", ")", ")", "def", "op", "(", "labeled_tensor", ",", "name", "=", "None", ")", ":", "\"\"\"LabeledTensor version of `tf.{op_name}`.\n\n See `tf.{op_name}` for full details.\n\n Args:\n labeled_tensor: Input tensor.\n name: Optional op name.\n\n Returns:\n A LabeledTensor with result of applying `tf.{op_name}` elementwise.\n \"\"\"", "with", "ops", ".", "name_scope", "(", "name", ",", "default_name", ",", "[", "labeled_tensor", "]", ")", "as", "scope", ":", "labeled_tensor", "=", "convert_to_labeled_tensor", "(", "labeled_tensor", ")", "result_tensor", "=", "elementwise_function", "(", "labeled_tensor", ".", "tensor", ",", "name", "=", "scope", ")", "return", "LabeledTensor", "(", "result_tensor", ",", "labeled_tensor", ".", "axes", ")", "op", ".", "__doc__", "=", "op", ".", "__doc__", ".", "format", "(", "op_name", "=", "op_name", ")", "op", ".", "__name__", "=", "op_name", "return", "op" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py#L1060-L1097
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/coordinator.py
python
Coordinator.request_stop
(self, ex=None)
Request that the threads stop. After this is called, calls to `should_stop()` will return `True`. Note: If an exception is being passed in, in must be in the context of handling the exception (i.e. `try: ... except Exception as ex: ...`) and not a newly created one. Args: ex: Optional `Exception`, or Python `exc_info` tuple as returned by `sys.exc_info()`. If this is the first call to `request_stop()` the corresponding exception is recorded and re-raised from `join()`.
Request that the threads stop.
[ "Request", "that", "the", "threads", "stop", "." ]
def request_stop(self, ex=None): """Request that the threads stop. After this is called, calls to `should_stop()` will return `True`. Note: If an exception is being passed in, in must be in the context of handling the exception (i.e. `try: ... except Exception as ex: ...`) and not a newly created one. Args: ex: Optional `Exception`, or Python `exc_info` tuple as returned by `sys.exc_info()`. If this is the first call to `request_stop()` the corresponding exception is recorded and re-raised from `join()`. """ with self._lock: ex = self._filter_exception(ex) # If we have already joined the coordinator the exception will not have a # chance to be reported, so just raise it normally. This can happen if # you continue to use a session have having stopped and joined the # coordinator threads. if self._joined: if isinstance(ex, tuple): six.reraise(*ex) elif ex is not None: # NOTE(touts): This is bogus if request_stop() is not called # from the exception handler that raised ex. six.reraise(*sys.exc_info()) if not self._stop_event.is_set(): if ex and self._exc_info_to_raise is None: if isinstance(ex, tuple): logging.info("Error reported to Coordinator: %s, %s", type(ex[1]), compat.as_str_any(ex[1])) self._exc_info_to_raise = ex else: logging.info("Error reported to Coordinator: %s, %s", type(ex), compat.as_str_any(ex)) self._exc_info_to_raise = sys.exc_info() # self._exc_info_to_raise should contain a tuple containing exception # (type, value, traceback) if (len(self._exc_info_to_raise) != 3 or not self._exc_info_to_raise[0] or not self._exc_info_to_raise[1]): # Raise, catch and record the exception here so that error happens # where expected. try: raise ValueError( "ex must be a tuple or sys.exc_info must return the current " "exception: %s" % self._exc_info_to_raise) except ValueError: # Record this error so it kills the coordinator properly. # NOTE(touts): As above, this is bogus if request_stop() is not # called from the exception handler that raised ex. self._exc_info_to_raise = sys.exc_info() self._stop_event.set()
[ "def", "request_stop", "(", "self", ",", "ex", "=", "None", ")", ":", "with", "self", ".", "_lock", ":", "ex", "=", "self", ".", "_filter_exception", "(", "ex", ")", "# If we have already joined the coordinator the exception will not have a", "# chance to be reported, so just raise it normally. This can happen if", "# you continue to use a session have having stopped and joined the", "# coordinator threads.", "if", "self", ".", "_joined", ":", "if", "isinstance", "(", "ex", ",", "tuple", ")", ":", "six", ".", "reraise", "(", "*", "ex", ")", "elif", "ex", "is", "not", "None", ":", "# NOTE(touts): This is bogus if request_stop() is not called", "# from the exception handler that raised ex.", "six", ".", "reraise", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "if", "not", "self", ".", "_stop_event", ".", "is_set", "(", ")", ":", "if", "ex", "and", "self", ".", "_exc_info_to_raise", "is", "None", ":", "if", "isinstance", "(", "ex", ",", "tuple", ")", ":", "logging", ".", "info", "(", "\"Error reported to Coordinator: %s, %s\"", ",", "type", "(", "ex", "[", "1", "]", ")", ",", "compat", ".", "as_str_any", "(", "ex", "[", "1", "]", ")", ")", "self", ".", "_exc_info_to_raise", "=", "ex", "else", ":", "logging", ".", "info", "(", "\"Error reported to Coordinator: %s, %s\"", ",", "type", "(", "ex", ")", ",", "compat", ".", "as_str_any", "(", "ex", ")", ")", "self", ".", "_exc_info_to_raise", "=", "sys", ".", "exc_info", "(", ")", "# self._exc_info_to_raise should contain a tuple containing exception", "# (type, value, traceback)", "if", "(", "len", "(", "self", ".", "_exc_info_to_raise", ")", "!=", "3", "or", "not", "self", ".", "_exc_info_to_raise", "[", "0", "]", "or", "not", "self", ".", "_exc_info_to_raise", "[", "1", "]", ")", ":", "# Raise, catch and record the exception here so that error happens", "# where expected.", "try", ":", "raise", "ValueError", "(", "\"ex must be a tuple or sys.exc_info must return the current \"", "\"exception: %s\"", "%", "self", ".", "_exc_info_to_raise", ")", "except", "ValueError", ":", "# Record this error so it kills the coordinator properly.", "# NOTE(touts): As above, this is bogus if request_stop() is not", "# called from the exception handler that raised ex.", "self", ".", "_exc_info_to_raise", "=", "sys", ".", "exc_info", "(", ")", "self", ".", "_stop_event", ".", "set", "(", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/coordinator.py#L185-L242
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
tools/clang_format.py
python
Repo.diff
(self, command)
return self._callgito(["diff"] + command)
git diff wrapper
git diff wrapper
[ "git", "diff", "wrapper" ]
def diff(self, command): """git diff wrapper """ return self._callgito(["diff"] + command)
[ "def", "diff", "(", "self", ",", "command", ")", ":", "return", "self", ".", "_callgito", "(", "[", "\"diff\"", "]", "+", "command", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/tools/clang_format.py#L470-L473
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/plasma/Plasma.py
python
PtChangePassword
(password)
Changes the current account's password
Changes the current account's password
[ "Changes", "the", "current", "account", "s", "password" ]
def PtChangePassword(password): """Changes the current account's password""" pass
[ "def", "PtChangePassword", "(", "password", ")", ":", "pass" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L117-L119
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
libcxx/utils/gdb/libcxx/printers.py
python
AbstractRBTreePrinter._traverse
(self)
Traverses the binary search tree in order.
Traverses the binary search tree in order.
[ "Traverses", "the", "binary", "search", "tree", "in", "order", "." ]
def _traverse(self): """Traverses the binary search tree in order.""" current = self.util.root skip_left_child = False while True: if not skip_left_child and self.util.left_child(current): current = self.util.left_child(current) continue skip_left_child = False for key_value in self._get_key_value(current): yield "", key_value right_child = self.util.right_child(current) if right_child: current = right_child continue while self.util.is_right_child(current): current = self.util.parent(current) if self.util.is_left_child(current): current = self.util.parent(current) skip_left_child = True continue break
[ "def", "_traverse", "(", "self", ")", ":", "current", "=", "self", ".", "util", ".", "root", "skip_left_child", "=", "False", "while", "True", ":", "if", "not", "skip_left_child", "and", "self", ".", "util", ".", "left_child", "(", "current", ")", ":", "current", "=", "self", ".", "util", ".", "left_child", "(", "current", ")", "continue", "skip_left_child", "=", "False", "for", "key_value", "in", "self", ".", "_get_key_value", "(", "current", ")", ":", "yield", "\"\"", ",", "key_value", "right_child", "=", "self", ".", "util", ".", "right_child", "(", "current", ")", "if", "right_child", ":", "current", "=", "right_child", "continue", "while", "self", ".", "util", ".", "is_right_child", "(", "current", ")", ":", "current", "=", "self", ".", "util", ".", "parent", "(", "current", ")", "if", "self", ".", "util", ".", "is_left_child", "(", "current", ")", ":", "current", "=", "self", ".", "util", ".", "parent", "(", "current", ")", "skip_left_child", "=", "True", "continue", "break" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/libcxx/utils/gdb/libcxx/printers.py#L646-L667
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/naive_bayes.py
python
_BaseDiscreteNB.fit
(self, X, y, sample_weight=None)
return self
Fit Naive Bayes classifier according to X, y Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) Target values. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object
Fit Naive Bayes classifier according to X, y
[ "Fit", "Naive", "Bayes", "classifier", "according", "to", "X", "y" ]
def fit(self, X, y, sample_weight=None): """Fit Naive Bayes classifier according to X, y Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) Target values. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object """ X, y = self._check_X_y(X, y) _, n_features = X.shape self.n_features_ = n_features labelbin = LabelBinarizer() Y = labelbin.fit_transform(y) self.classes_ = labelbin.classes_ if Y.shape[1] == 1: Y = np.concatenate((1 - Y, Y), axis=1) # LabelBinarizer().fit_transform() returns arrays with dtype=np.int64. # We convert it to np.float64 to support sample_weight consistently; # this means we also don't have to cast X to floating point if sample_weight is not None: Y = Y.astype(np.float64, copy=False) sample_weight = np.asarray(sample_weight) sample_weight = np.atleast_2d(sample_weight) Y *= check_array(sample_weight).T class_prior = self.class_prior # Count raw events from data before updating the class log prior # and feature log probas n_effective_classes = Y.shape[1] self._init_counters(n_effective_classes, n_features) self._count(X, Y) alpha = self._check_alpha() self._update_feature_log_prob(alpha) self._update_class_log_prior(class_prior=class_prior) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ")", ":", "X", ",", "y", "=", "self", ".", "_check_X_y", "(", "X", ",", "y", ")", "_", ",", "n_features", "=", "X", ".", "shape", "self", ".", "n_features_", "=", "n_features", "labelbin", "=", "LabelBinarizer", "(", ")", "Y", "=", "labelbin", ".", "fit_transform", "(", "y", ")", "self", ".", "classes_", "=", "labelbin", ".", "classes_", "if", "Y", ".", "shape", "[", "1", "]", "==", "1", ":", "Y", "=", "np", ".", "concatenate", "(", "(", "1", "-", "Y", ",", "Y", ")", ",", "axis", "=", "1", ")", "# LabelBinarizer().fit_transform() returns arrays with dtype=np.int64.", "# We convert it to np.float64 to support sample_weight consistently;", "# this means we also don't have to cast X to floating point", "if", "sample_weight", "is", "not", "None", ":", "Y", "=", "Y", ".", "astype", "(", "np", ".", "float64", ",", "copy", "=", "False", ")", "sample_weight", "=", "np", ".", "asarray", "(", "sample_weight", ")", "sample_weight", "=", "np", ".", "atleast_2d", "(", "sample_weight", ")", "Y", "*=", "check_array", "(", "sample_weight", ")", ".", "T", "class_prior", "=", "self", ".", "class_prior", "# Count raw events from data before updating the class log prior", "# and feature log probas", "n_effective_classes", "=", "Y", ".", "shape", "[", "1", "]", "self", ".", "_init_counters", "(", "n_effective_classes", ",", "n_features", ")", "self", ".", "_count", "(", "X", ",", "Y", ")", "alpha", "=", "self", ".", "_check_alpha", "(", ")", "self", ".", "_update_feature_log_prob", "(", "alpha", ")", "self", ".", "_update_class_log_prior", "(", "class_prior", "=", "class_prior", ")", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/naive_bayes.py#L590-L639
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdAppUtils/rendererArgs.py
python
GetAllPluginArguments
()
return [ UsdImagingGL.Engine.GetRendererDisplayName(pluginId) for pluginId in UsdImagingGL.Engine.GetRendererPlugins() ]
Returns argument strings for all the renderer plugins available.
Returns argument strings for all the renderer plugins available.
[ "Returns", "argument", "strings", "for", "all", "the", "renderer", "plugins", "available", "." ]
def GetAllPluginArguments(): """ Returns argument strings for all the renderer plugins available. """ from pxr import UsdImagingGL return [ UsdImagingGL.Engine.GetRendererDisplayName(pluginId) for pluginId in UsdImagingGL.Engine.GetRendererPlugins() ]
[ "def", "GetAllPluginArguments", "(", ")", ":", "from", "pxr", "import", "UsdImagingGL", "return", "[", "UsdImagingGL", ".", "Engine", ".", "GetRendererDisplayName", "(", "pluginId", ")", "for", "pluginId", "in", "UsdImagingGL", ".", "Engine", ".", "GetRendererPlugins", "(", ")", "]" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdAppUtils/rendererArgs.py#L27-L34
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_CallbackRestOrInterface
(self, p)
CallbackRestOrInterface : CallbackRest | Interface
CallbackRestOrInterface : CallbackRest | Interface
[ "CallbackRestOrInterface", ":", "CallbackRest", "|", "Interface" ]
def p_CallbackRestOrInterface(self, p): """ CallbackRestOrInterface : CallbackRest | Interface """ assert p[1] p[0] = p[1]
[ "def", "p_CallbackRestOrInterface", "(", "self", ",", "p", ")", ":", "assert", "p", "[", "1", "]", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L4285-L4291
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
_CppLintState.BackupFilters
(self)
Saves the current filter list to backup storage.
Saves the current filter list to backup storage.
[ "Saves", "the", "current", "filter", "list", "to", "backup", "storage", "." ]
def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:]
[ "def", "BackupFilters", "(", "self", ")", ":", "self", ".", "_filters_backup", "=", "self", ".", "filters", "[", ":", "]" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L911-L913
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/chardet/chardistribution.py
python
CharDistributionAnalysis.reset
(self)
reset analyser, clear any state
reset analyser, clear any state
[ "reset", "analyser", "clear", "any", "state" ]
def reset(self): """reset analyser, clear any state""" # If this flag is set to True, detection is done and conclusion has # been made self._done = False self._total_chars = 0 # Total characters encountered # The number of characters whose frequency order is less than 512 self._freq_chars = 0
[ "def", "reset", "(", "self", ")", ":", "# If this flag is set to True, detection is done and conclusion has", "# been made", "self", ".", "_done", "=", "False", "self", ".", "_total_chars", "=", "0", "# Total characters encountered", "# The number of characters whose frequency order is less than 512", "self", ".", "_freq_chars", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/chardet/chardistribution.py#L61-L68
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.update_node_name_header_num_latest_visited
(self)
Update on the Node Name Header the Number of Latest Visited
Update on the Node Name Header the Number of Latest Visited
[ "Update", "on", "the", "Node", "Name", "Header", "the", "Number", "of", "Latest", "Visited" ]
def update_node_name_header_num_latest_visited(self): """Update on the Node Name Header the Number of Latest Visited""" for button in self.header_node_name_hbuttonbox.get_children(): self.header_node_name_hbuttonbox.remove(button) for i in range(self.nodes_on_node_name_header): button = gtk.Button() button.connect('clicked', self.on_button_node_name_header_clicked, i) label = gtk.Label() label.set_ellipsize(pango.ELLIPSIZE_END) button.add(label) self.header_node_name_hbuttonbox.add(button) self.update_node_name_header_labels_latest_visited()
[ "def", "update_node_name_header_num_latest_visited", "(", "self", ")", ":", "for", "button", "in", "self", ".", "header_node_name_hbuttonbox", ".", "get_children", "(", ")", ":", "self", ".", "header_node_name_hbuttonbox", ".", "remove", "(", "button", ")", "for", "i", "in", "range", "(", "self", ".", "nodes_on_node_name_header", ")", ":", "button", "=", "gtk", ".", "Button", "(", ")", "button", ".", "connect", "(", "'clicked'", ",", "self", ".", "on_button_node_name_header_clicked", ",", "i", ")", "label", "=", "gtk", ".", "Label", "(", ")", "label", ".", "set_ellipsize", "(", "pango", ".", "ELLIPSIZE_END", ")", "button", ".", "add", "(", "label", ")", "self", ".", "header_node_name_hbuttonbox", ".", "add", "(", "button", ")", "self", ".", "update_node_name_header_labels_latest_visited", "(", ")" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L3226-L3237
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/computation/expressions.py
python
_evaluate_standard
(op, op_str, a, b)
return op(a, b)
Standard evaluation.
Standard evaluation.
[ "Standard", "evaluation", "." ]
def _evaluate_standard(op, op_str, a, b): """ Standard evaluation. """ if _TEST_MODE: _store_test_result(False) return op(a, b)
[ "def", "_evaluate_standard", "(", "op", ",", "op_str", ",", "a", ",", "b", ")", ":", "if", "_TEST_MODE", ":", "_store_test_result", "(", "False", ")", "return", "op", "(", "a", ",", "b", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/computation/expressions.py#L63-L69
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/robotinterface.py
python
RobotInterfaceBase.clock
(self)
Returns the current time on the robot's clock, in seconds
Returns the current time on the robot's clock, in seconds
[ "Returns", "the", "current", "time", "on", "the", "robot", "s", "clock", "in", "seconds" ]
def clock(self) -> float: """Returns the current time on the robot's clock, in seconds""" raise NotImplementedError()
[ "def", "clock", "(", "self", ")", "->", "float", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L349-L351
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
SashWindow.SetExtraBorderSize
(*args, **kwargs)
return _windows_.SashWindow_SetExtraBorderSize(*args, **kwargs)
SetExtraBorderSize(self, int width)
SetExtraBorderSize(self, int width)
[ "SetExtraBorderSize", "(", "self", "int", "width", ")" ]
def SetExtraBorderSize(*args, **kwargs): """SetExtraBorderSize(self, int width)""" return _windows_.SashWindow_SetExtraBorderSize(*args, **kwargs)
[ "def", "SetExtraBorderSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SashWindow_SetExtraBorderSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1830-L1832
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/ctml_writer.py
python
validate
(species='yes', reactions='yes')
Enable or disable validation of species and reactions. :param species: Set to ``'yes'`` (default) or ``'no'``. :param reactions: Set to ``'yes'`` (default) or ``'no'``. This controls duplicate reaction checks and validation of rate expressions for some reaction types.
Enable or disable validation of species and reactions.
[ "Enable", "or", "disable", "validation", "of", "species", "and", "reactions", "." ]
def validate(species='yes', reactions='yes'): """ Enable or disable validation of species and reactions. :param species: Set to ``'yes'`` (default) or ``'no'``. :param reactions: Set to ``'yes'`` (default) or ``'no'``. This controls duplicate reaction checks and validation of rate expressions for some reaction types. """ global _valsp global _valrxn _valsp = species _valrxn = reactions
[ "def", "validate", "(", "species", "=", "'yes'", ",", "reactions", "=", "'yes'", ")", ":", "global", "_valsp", "global", "_valrxn", "_valsp", "=", "species", "_valrxn", "=", "reactions" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml_writer.py#L284-L298
svn2github/webrtc
0e4615a75ed555ec866cd5543bfea586f3385ceb
webrtc/tools/barcode_tools/barcode_encoder.py
python
combine_yuv_frames_into_one_file
(output_file_name, input_directory='.')
return success
Combines several YUV frames into one YUV video file. The function combines the YUV frames from input_directory into one YUV video file. The frames should be named in the format frame_xxxx.yuv where xxxx stands for the frame number. The numbers have to be consecutive and start from 0000. The YUV frames are removed after they have been added to the video. Args: output_file_name(string): The name of the file to produce. input_directory(string): The directory from which the YUV frames are read. Return: (bool): True if the frame stitching went OK.
Combines several YUV frames into one YUV video file.
[ "Combines", "several", "YUV", "frames", "into", "one", "YUV", "video", "file", "." ]
def combine_yuv_frames_into_one_file(output_file_name, input_directory='.'): """Combines several YUV frames into one YUV video file. The function combines the YUV frames from input_directory into one YUV video file. The frames should be named in the format frame_xxxx.yuv where xxxx stands for the frame number. The numbers have to be consecutive and start from 0000. The YUV frames are removed after they have been added to the video. Args: output_file_name(string): The name of the file to produce. input_directory(string): The directory from which the YUV frames are read. Return: (bool): True if the frame stitching went OK. """ output_file = open(output_file_name, "wb") success = helper_functions.perform_action_on_all_files( input_directory, 'barcode_', 'yuv', 0, _add_to_file_and_delete, output_file=output_file) output_file.close() return success
[ "def", "combine_yuv_frames_into_one_file", "(", "output_file_name", ",", "input_directory", "=", "'.'", ")", ":", "output_file", "=", "open", "(", "output_file_name", ",", "\"wb\"", ")", "success", "=", "helper_functions", ".", "perform_action_on_all_files", "(", "input_directory", ",", "'barcode_'", ",", "'yuv'", ",", "0", ",", "_add_to_file_and_delete", ",", "output_file", "=", "output_file", ")", "output_file", ".", "close", "(", ")", "return", "success" ]
https://github.com/svn2github/webrtc/blob/0e4615a75ed555ec866cd5543bfea586f3385ceb/webrtc/tools/barcode_tools/barcode_encoder.py#L119-L138
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py
python
PlottingCanvasPresenter.set_axis_limits
(self, ax_num, xlims, ylims)
Sets the x and y limits for a specified axis in the figure
Sets the x and y limits for a specified axis in the figure
[ "Sets", "the", "x", "and", "y", "limits", "for", "a", "specified", "axis", "in", "the", "figure" ]
def set_axis_limits(self, ax_num, xlims, ylims): """Sets the x and y limits for a specified axis in the figure""" self._view.set_axis_xlimits(ax_num, xlims) self._view.set_axis_ylimits(ax_num, ylims)
[ "def", "set_axis_limits", "(", "self", ",", "ax_num", ",", "xlims", ",", "ylims", ")", ":", "self", ".", "_view", ".", "set_axis_xlimits", "(", "ax_num", ",", "xlims", ")", "self", ".", "_view", ".", "set_axis_ylimits", "(", "ax_num", ",", "ylims", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py#L106-L109
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py
python
Session.head
(self, url, **kwargs)
return self.request('HEAD', url, **kwargs)
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a HEAD request. Returns :class:`Response` object.
[ "r", "Sends", "a", "HEAD", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
[ "def", "head", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py#L556-L565
microsoft/DirectXShaderCompiler
8348ff8d9e0287610ba05d3a828e10af981a1c05
tools/clang/bindings/python/clang/cindex.py
python
CursorKind.is_attribute
(self)
return conf.lib.clang_isAttribute(self)
Test if this is an attribute kind.
Test if this is an attribute kind.
[ "Test", "if", "this", "is", "an", "attribute", "kind", "." ]
def is_attribute(self): """Test if this is an attribute kind.""" return conf.lib.clang_isAttribute(self)
[ "def", "is_attribute", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isAttribute", "(", "self", ")" ]
https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/bindings/python/clang/cindex.py#L575-L577
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNEANetNodeI.IsInNId
(self, *args)
return _snap.TNEANetNodeI_IsInNId(self, *args)
IsInNId(TNEANetNodeI self, int const & NId) -> bool Parameters: NId: int const &
IsInNId(TNEANetNodeI self, int const & NId) -> bool
[ "IsInNId", "(", "TNEANetNodeI", "self", "int", "const", "&", "NId", ")", "-", ">", "bool" ]
def IsInNId(self, *args): """ IsInNId(TNEANetNodeI self, int const & NId) -> bool Parameters: NId: int const & """ return _snap.TNEANetNodeI_IsInNId(self, *args)
[ "def", "IsInNId", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNEANetNodeI_IsInNId", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L20828-L20836
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/function.py
python
_DefinedFunction.__init__
(self, func, argnames, input_types, func_name=None, grad_func=None, python_grad_func=None, **kwargs)
Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. input_types: The function's argument types. Can be a tuple, list of tf data types. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid.
Creates _DefinedFunction.
[ "Creates", "_DefinedFunction", "." ]
def __init__(self, func, argnames, input_types, func_name=None, grad_func=None, python_grad_func=None, **kwargs): """Creates _DefinedFunction. Args: func: A python callable which constructs a tf function body. argnames: A list of strings for function argument names. input_types: The function's argument types. Can be a tuple, list of tf data types. func_name: The function name. Defaults to None, in which derives from 'func'. grad_func: This function's gradient function, if not None. Defaults to None. python_grad_func: A python callable implementing the gradient of the function python-side. **kwargs: The keyword arguments. **kwargs is passed to every call site of this function. Raises: ValueError: The function definition is invalid. """ self._func = func self._input_types = input_types self._func_name = func_name self._grad_func = grad_func self._python_grad_func = python_grad_func self._extra_kwargs = kwargs self._definition = None # Constructed lazily. self._args = [] assert isinstance(input_types, (list, tuple)) for i in range(len(input_types)): argname = argnames[i] if i < len(argnames) else ("arg%d" % i) argtype = input_types[i] self._args.append((argname, argtype))
[ "def", "__init__", "(", "self", ",", "func", ",", "argnames", ",", "input_types", ",", "func_name", "=", "None", ",", "grad_func", "=", "None", ",", "python_grad_func", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_func", "=", "func", "self", ".", "_input_types", "=", "input_types", "self", ".", "_func_name", "=", "func_name", "self", ".", "_grad_func", "=", "grad_func", "self", ".", "_python_grad_func", "=", "python_grad_func", "self", ".", "_extra_kwargs", "=", "kwargs", "self", ".", "_definition", "=", "None", "# Constructed lazily.", "self", ".", "_args", "=", "[", "]", "assert", "isinstance", "(", "input_types", ",", "(", "list", ",", "tuple", ")", ")", "for", "i", "in", "range", "(", "len", "(", "input_types", ")", ")", ":", "argname", "=", "argnames", "[", "i", "]", "if", "i", "<", "len", "(", "argnames", ")", "else", "(", "\"arg%d\"", "%", "i", ")", "argtype", "=", "input_types", "[", "i", "]", "self", ".", "_args", ".", "append", "(", "(", "argname", ",", "argtype", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/function.py#L411-L452
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
EventFilter/L1TXRawToDigi/python/util/rrapi.py
python
RRApiError.__str__
(self)
return self.message
Get message
Get message
[ "Get", "message" ]
def __str__(self): """ Get message """ return self.message
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "message" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/EventFilter/L1TXRawToDigi/python/util/rrapi.py#L43-L45
jeog/TDAmeritradeAPI
91c738afd7d57b54f6231170bd64c2550fafd34d
python/tdma_api/get.py
python
OrdersGetter.set_to_entered_time
(self, to_entered_time)
Sets/Changes date/time after which no orders will be returned. iso8601 date/time ("yyyy-MM-dd" or "yyyy-MM-dd'T'HH::mm::ssz") <= 60 days ago
Sets/Changes date/time after which no orders will be returned.
[ "Sets", "/", "Changes", "date", "/", "time", "after", "which", "no", "orders", "will", "be", "returned", "." ]
def set_to_entered_time(self, to_entered_time): """Sets/Changes date/time after which no orders will be returned. iso8601 date/time ("yyyy-MM-dd" or "yyyy-MM-dd'T'HH::mm::ssz") <= 60 days ago """ clib.set_str(self._abi('SetToEnteredTime'), to_entered_time, self._obj)
[ "def", "set_to_entered_time", "(", "self", ",", "to_entered_time", ")", ":", "clib", ".", "set_str", "(", "self", ".", "_abi", "(", "'SetToEnteredTime'", ")", ",", "to_entered_time", ",", "self", ".", "_obj", ")" ]
https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L1409-L1416
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/rpc/backend_registry.py
python
register_backend
( backend_name, construct_rpc_backend_options_handler, init_backend_handler )
return BackendType[backend_name]
Registers a new RPC backend. Args: backend_name (str): backend string to identify the handler. construct_rpc_backend_options_handler (function): Handler that is invoked when rpc_backend.construct_rpc_backend_options(**dict) is called. init_backend_handler (function): Handler that is invoked when the `_init_rpc_backend()` function is called with a backend. This returns the agent.
Registers a new RPC backend.
[ "Registers", "a", "new", "RPC", "backend", "." ]
def register_backend( backend_name, construct_rpc_backend_options_handler, init_backend_handler ): """Registers a new RPC backend. Args: backend_name (str): backend string to identify the handler. construct_rpc_backend_options_handler (function): Handler that is invoked when rpc_backend.construct_rpc_backend_options(**dict) is called. init_backend_handler (function): Handler that is invoked when the `_init_rpc_backend()` function is called with a backend. This returns the agent. """ global BackendType if backend_registered(backend_name): raise RuntimeError("RPC backend {}: already registered".format(backend_name)) # Create a new enum type, `BackendType`, with extended members. existing_enum_dict = {member.name: member.value for member in BackendType} extended_enum_dict = dict( { backend_name: BackendValue( construct_rpc_backend_options_handler=construct_rpc_backend_options_handler, init_backend_handler=init_backend_handler, ) }, **existing_enum_dict ) # Can't handle Function Enum API (mypy bug #9079) BackendType = enum.Enum(value="BackendType", names=extended_enum_dict) # type: ignore[misc] # Unable to assign a function a method (mypy bug #2427) BackendType.__repr__ = _backend_type_repr # type: ignore[assignment] BackendType.__doc__ = _backend_type_doc return BackendType[backend_name]
[ "def", "register_backend", "(", "backend_name", ",", "construct_rpc_backend_options_handler", ",", "init_backend_handler", ")", ":", "global", "BackendType", "if", "backend_registered", "(", "backend_name", ")", ":", "raise", "RuntimeError", "(", "\"RPC backend {}: already registered\"", ".", "format", "(", "backend_name", ")", ")", "# Create a new enum type, `BackendType`, with extended members.", "existing_enum_dict", "=", "{", "member", ".", "name", ":", "member", ".", "value", "for", "member", "in", "BackendType", "}", "extended_enum_dict", "=", "dict", "(", "{", "backend_name", ":", "BackendValue", "(", "construct_rpc_backend_options_handler", "=", "construct_rpc_backend_options_handler", ",", "init_backend_handler", "=", "init_backend_handler", ",", ")", "}", ",", "*", "*", "existing_enum_dict", ")", "# Can't handle Function Enum API (mypy bug #9079)", "BackendType", "=", "enum", ".", "Enum", "(", "value", "=", "\"BackendType\"", ",", "names", "=", "extended_enum_dict", ")", "# type: ignore[misc]", "# Unable to assign a function a method (mypy bug #2427)", "BackendType", ".", "__repr__", "=", "_backend_type_repr", "# type: ignore[assignment]", "BackendType", ".", "__doc__", "=", "_backend_type_doc", "return", "BackendType", "[", "backend_name", "]" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/rpc/backend_registry.py#L50-L83
diwu/Tiny-Wings-Remake-on-Android
a9fd714432a350b69615bf8dbb40448231a54524
twxes10/libs/cocos2dx/platform/third_party/marmalade/freetype/src/tools/docmaker/tohtml.py
python
HtmlFormatter.make_html_words
( self, words )
return line
convert a series of simple words into some HTML text
convert a series of simple words into some HTML text
[ "convert", "a", "series", "of", "simple", "words", "into", "some", "HTML", "text" ]
def make_html_words( self, words ): """ convert a series of simple words into some HTML text """ line = "" if words: line = html_quote( words[0] ) for w in words[1:]: line = line + " " + html_quote( w ) return line
[ "def", "make_html_words", "(", "self", ",", "words", ")", ":", "line", "=", "\"\"", "if", "words", ":", "line", "=", "html_quote", "(", "words", "[", "0", "]", ")", "for", "w", "in", "words", "[", "1", ":", "]", ":", "line", "=", "line", "+", "\" \"", "+", "html_quote", "(", "w", ")", "return", "line" ]
https://github.com/diwu/Tiny-Wings-Remake-on-Android/blob/a9fd714432a350b69615bf8dbb40448231a54524/twxes10/libs/cocos2dx/platform/third_party/marmalade/freetype/src/tools/docmaker/tohtml.py#L245-L253
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/smtplib.py
python
SMTP.rcpt
(self, recip, options=[])
return self.getreply()
SMTP 'rcpt' command -- indicates 1 recipient for this mail.
SMTP 'rcpt' command -- indicates 1 recipient for this mail.
[ "SMTP", "rcpt", "command", "--", "indicates", "1", "recipient", "for", "this", "mail", "." ]
def rcpt(self, recip, options=[]): """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = ' ' + ' '.join(options) self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist)) return self.getreply()
[ "def", "rcpt", "(", "self", ",", "recip", ",", "options", "=", "[", "]", ")", ":", "optionlist", "=", "''", "if", "options", "and", "self", ".", "does_esmtp", ":", "optionlist", "=", "' '", "+", "' '", ".", "join", "(", "options", ")", "self", ".", "putcmd", "(", "\"rcpt\"", ",", "\"TO:%s%s\"", "%", "(", "quoteaddr", "(", "recip", ")", ",", "optionlist", ")", ")", "return", "self", ".", "getreply", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/smtplib.py#L475-L481
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py
python
TurtleScreen.window_height
(self)
return self._window_size()[1]
Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480
Return the height of the turtle window.
[ "Return", "the", "height", "of", "the", "turtle", "window", "." ]
def window_height(self): """ Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480 """ return self._window_size()[1]
[ "def", "window_height", "(", "self", ")", ":", "return", "self", ".", "_window_size", "(", ")", "[", "1", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L1317-L1324
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/parallel_for/gradients.py
python
batch_jacobian
(output, inp, use_pfor=True, parallel_iterations=None)
return array_ops.reshape(output, new_shape)
Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`. e.g. x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) y = x * x jacobian = batch_jacobian(y, x) # => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] Args: output: A tensor with shape [b, y1, ..., y_n]. `output[i,...]` should only depend on `inp[i,...]`. inp: A tensor with shape [b, x1, ..., x_m] use_pfor: If true, uses pfor for computing the Jacobian. Else uses a tf.while_loop. parallel_iterations: A knob to control how many iterations are vectorized and dispatched in parallel. The default value of None, when use_pfor is true, corresponds to vectorizing all the iterations. When use_pfor is false, the default value of None corresponds to parallel_iterations=10. This knob can be used to control the total memory usage. Returns: A tensor `t` with shape [b, y_1, ..., y_n, x1, ..., x_m] where `t[i, ...]` is the jacobian of `output[i, ...]` w.r.t. `inp[i, ...]`, i.e. stacked per-example jacobians. Raises: ValueError: if first dimension of `output` and `inp` do not match.
Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`.
[ "Computes", "and", "stacks", "jacobians", "of", "output", "[", "i", "...", "]", "w", ".", "r", ".", "t", ".", "input", "[", "i", "...", "]", "." ]
def batch_jacobian(output, inp, use_pfor=True, parallel_iterations=None): """Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`. e.g. x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) y = x * x jacobian = batch_jacobian(y, x) # => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] Args: output: A tensor with shape [b, y1, ..., y_n]. `output[i,...]` should only depend on `inp[i,...]`. inp: A tensor with shape [b, x1, ..., x_m] use_pfor: If true, uses pfor for computing the Jacobian. Else uses a tf.while_loop. parallel_iterations: A knob to control how many iterations are vectorized and dispatched in parallel. The default value of None, when use_pfor is true, corresponds to vectorizing all the iterations. When use_pfor is false, the default value of None corresponds to parallel_iterations=10. This knob can be used to control the total memory usage. Returns: A tensor `t` with shape [b, y_1, ..., y_n, x1, ..., x_m] where `t[i, ...]` is the jacobian of `output[i, ...]` w.r.t. `inp[i, ...]`, i.e. stacked per-example jacobians. Raises: ValueError: if first dimension of `output` and `inp` do not match. """ output_shape = output.shape if not output_shape[0].is_compatible_with(inp.shape[0]): raise ValueError(f"Need first dimension of `output` shape ({output.shape}) " f"and `inp` shape ({inp.shape}) to match.") if output_shape.is_fully_defined(): batch_size = int(output_shape[0]) output_row_size = output_shape.num_elements() // batch_size else: output_shape = array_ops.shape(output) batch_size = output_shape[0] output_row_size = array_ops.size(output) // batch_size inp_shape = array_ops.shape(inp) # Flatten output to 2-D. with ops.control_dependencies( [check_ops.assert_equal(batch_size, inp_shape[0])]): output = array_ops.reshape(output, [batch_size, output_row_size]) def loop_fn(i): y = array_ops.gather(output, i, axis=1) return gradient_ops.gradients(y, inp)[0] if use_pfor: pfor_output = control_flow_ops.pfor(loop_fn, output_row_size, parallel_iterations=parallel_iterations) else: pfor_output = control_flow_ops.for_loop( loop_fn, output.dtype, output_row_size, parallel_iterations=parallel_iterations) if pfor_output is None: return None pfor_output = array_ops.reshape(pfor_output, [output_row_size, batch_size, -1]) output = array_ops.transpose(pfor_output, [1, 0, 2]) new_shape = array_ops.concat([output_shape, inp_shape[1:]], axis=0) return array_ops.reshape(output, new_shape)
[ "def", "batch_jacobian", "(", "output", ",", "inp", ",", "use_pfor", "=", "True", ",", "parallel_iterations", "=", "None", ")", ":", "output_shape", "=", "output", ".", "shape", "if", "not", "output_shape", "[", "0", "]", ".", "is_compatible_with", "(", "inp", ".", "shape", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "f\"Need first dimension of `output` shape ({output.shape}) \"", "f\"and `inp` shape ({inp.shape}) to match.\"", ")", "if", "output_shape", ".", "is_fully_defined", "(", ")", ":", "batch_size", "=", "int", "(", "output_shape", "[", "0", "]", ")", "output_row_size", "=", "output_shape", ".", "num_elements", "(", ")", "//", "batch_size", "else", ":", "output_shape", "=", "array_ops", ".", "shape", "(", "output", ")", "batch_size", "=", "output_shape", "[", "0", "]", "output_row_size", "=", "array_ops", ".", "size", "(", "output", ")", "//", "batch_size", "inp_shape", "=", "array_ops", ".", "shape", "(", "inp", ")", "# Flatten output to 2-D.", "with", "ops", ".", "control_dependencies", "(", "[", "check_ops", ".", "assert_equal", "(", "batch_size", ",", "inp_shape", "[", "0", "]", ")", "]", ")", ":", "output", "=", "array_ops", ".", "reshape", "(", "output", ",", "[", "batch_size", ",", "output_row_size", "]", ")", "def", "loop_fn", "(", "i", ")", ":", "y", "=", "array_ops", ".", "gather", "(", "output", ",", "i", ",", "axis", "=", "1", ")", "return", "gradient_ops", ".", "gradients", "(", "y", ",", "inp", ")", "[", "0", "]", "if", "use_pfor", ":", "pfor_output", "=", "control_flow_ops", ".", "pfor", "(", "loop_fn", ",", "output_row_size", ",", "parallel_iterations", "=", "parallel_iterations", ")", "else", ":", "pfor_output", "=", "control_flow_ops", ".", "for_loop", "(", "loop_fn", ",", "output", ".", "dtype", ",", "output_row_size", ",", "parallel_iterations", "=", "parallel_iterations", ")", "if", "pfor_output", "is", "None", ":", "return", "None", "pfor_output", "=", "array_ops", ".", "reshape", "(", "pfor_output", ",", "[", "output_row_size", ",", "batch_size", ",", "-", "1", "]", ")", "output", "=", "array_ops", ".", "transpose", "(", "pfor_output", ",", "[", "1", ",", "0", ",", "2", "]", ")", "new_shape", "=", "array_ops", ".", "concat", "(", "[", "output_shape", ",", "inp_shape", "[", "1", ":", "]", "]", ",", "axis", "=", "0", ")", "return", "array_ops", ".", "reshape", "(", "output", ",", "new_shape", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/parallel_for/gradients.py#L79-L143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PreMDIParentFrame
(*args, **kwargs)
return val
PreMDIParentFrame() -> MDIParentFrame
PreMDIParentFrame() -> MDIParentFrame
[ "PreMDIParentFrame", "()", "-", ">", "MDIParentFrame" ]
def PreMDIParentFrame(*args, **kwargs): """PreMDIParentFrame() -> MDIParentFrame""" val = _windows_.new_PreMDIParentFrame(*args, **kwargs) return val
[ "def", "PreMDIParentFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_windows_", ".", "new_PreMDIParentFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4066-L4069
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/fifelog.py
python
LogManager.__init__
(self, engine, promptlog=True, filelog=False)
Constructs new log manager @param engine: Engine to hook into @param promptlog: If true, logs to prompt @param filelog: If true, logs to file (fife.log)
Constructs new log manager
[ "Constructs", "new", "log", "manager" ]
def __init__(self, engine, promptlog=True, filelog=False): """ Constructs new log manager @param engine: Engine to hook into @param promptlog: If true, logs to prompt @param filelog: If true, logs to file (fife.log) """ self.engine = engine self.lm = engine.getLogManager() self.lm.setLogToPrompt(promptlog) self.lm.setLogToFile(filelog) self.mod2name = {} for k, v in list(fife.__dict__.items()): if k.startswith('LM_') and k not in ('LM_CORE', 'LM_MODULE_MAX'): self.mod2name[v] = self.lm.getModuleName(v) self.name2mod = dict([(v.lower(), k) for k, v in list(self.mod2name.items())])
[ "def", "__init__", "(", "self", ",", "engine", ",", "promptlog", "=", "True", ",", "filelog", "=", "False", ")", ":", "self", ".", "engine", "=", "engine", "self", ".", "lm", "=", "engine", ".", "getLogManager", "(", ")", "self", ".", "lm", ".", "setLogToPrompt", "(", "promptlog", ")", "self", ".", "lm", ".", "setLogToFile", "(", "filelog", ")", "self", ".", "mod2name", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "fife", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if", "k", ".", "startswith", "(", "'LM_'", ")", "and", "k", "not", "in", "(", "'LM_CORE'", ",", "'LM_MODULE_MAX'", ")", ":", "self", ".", "mod2name", "[", "v", "]", "=", "self", ".", "lm", ".", "getModuleName", "(", "v", ")", "self", ".", "name2mod", "=", "dict", "(", "[", "(", "v", ".", "lower", "(", ")", ",", "k", ")", "for", "k", ",", "v", "in", "list", "(", "self", ".", "mod2name", ".", "items", "(", ")", ")", "]", ")" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/fifelog.py#L35-L50
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/control-examples/OperationalSpaceController.py
python
Task.drawGL
(self,q)
Optionally can be overridden to visualize the task in OpenGL.
Optionally can be overridden to visualize the task in OpenGL.
[ "Optionally", "can", "be", "overridden", "to", "visualize", "the", "task", "in", "OpenGL", "." ]
def drawGL(self,q): """Optionally can be overridden to visualize the task in OpenGL.""" pass
[ "def", "drawGL", "(", "self", ",", "q", ")", ":", "pass" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/control-examples/OperationalSpaceController.py#L629-L631
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showbase/Audio3DManager.py
python
Audio3DManager.getSoundMinDistance
(self, sound)
return sound.get3dMinDistance()
Controls the distance (in units) that this sound begins to fall off. Also affects the rate it falls off. Default is 3.28 (in feet, this is 1 meter)
Controls the distance (in units) that this sound begins to fall off. Also affects the rate it falls off. Default is 3.28 (in feet, this is 1 meter)
[ "Controls", "the", "distance", "(", "in", "units", ")", "that", "this", "sound", "begins", "to", "fall", "off", ".", "Also", "affects", "the", "rate", "it", "falls", "off", ".", "Default", "is", "3", ".", "28", "(", "in", "feet", "this", "is", "1", "meter", ")" ]
def getSoundMinDistance(self, sound): """ Controls the distance (in units) that this sound begins to fall off. Also affects the rate it falls off. Default is 3.28 (in feet, this is 1 meter) """ return sound.get3dMinDistance()
[ "def", "getSoundMinDistance", "(", "self", ",", "sound", ")", ":", "return", "sound", ".", "get3dMinDistance", "(", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Audio3DManager.py#L94-L100
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/profile_analyzer_cli.py
python
ProfileDataTableView.__init__
(self, profile_datum_list, time_unit=cli_shared.TIME_UNIT_US)
Constructor. Args: profile_datum_list: List of `ProfileDatum` objects. time_unit: must be in cli_shared.TIME_UNITS.
Constructor.
[ "Constructor", "." ]
def __init__(self, profile_datum_list, time_unit=cli_shared.TIME_UNIT_US): """Constructor. Args: profile_datum_list: List of `ProfileDatum` objects. time_unit: must be in cli_shared.TIME_UNITS. """ self._profile_datum_list = profile_datum_list self.formatted_start_time = [ datum.start_time for datum in profile_datum_list] self.formatted_op_time = [ cli_shared.time_to_readable_str(datum.op_time, force_time_unit=time_unit) for datum in profile_datum_list] self.formatted_exec_time = [ cli_shared.time_to_readable_str( datum.node_exec_stats.all_end_rel_micros, force_time_unit=time_unit) for datum in profile_datum_list] self._column_names = ["Node", "Op Type", "Start Time (us)", "Op Time (%s)" % time_unit, "Exec Time (%s)" % time_unit, "Filename:Lineno(function)"] self._column_sort_ids = [SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, SORT_OPS_BY_START_TIME, SORT_OPS_BY_OP_TIME, SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_LINE]
[ "def", "__init__", "(", "self", ",", "profile_datum_list", ",", "time_unit", "=", "cli_shared", ".", "TIME_UNIT_US", ")", ":", "self", ".", "_profile_datum_list", "=", "profile_datum_list", "self", ".", "formatted_start_time", "=", "[", "datum", ".", "start_time", "for", "datum", "in", "profile_datum_list", "]", "self", ".", "formatted_op_time", "=", "[", "cli_shared", ".", "time_to_readable_str", "(", "datum", ".", "op_time", ",", "force_time_unit", "=", "time_unit", ")", "for", "datum", "in", "profile_datum_list", "]", "self", ".", "formatted_exec_time", "=", "[", "cli_shared", ".", "time_to_readable_str", "(", "datum", ".", "node_exec_stats", ".", "all_end_rel_micros", ",", "force_time_unit", "=", "time_unit", ")", "for", "datum", "in", "profile_datum_list", "]", "self", ".", "_column_names", "=", "[", "\"Node\"", ",", "\"Op Type\"", ",", "\"Start Time (us)\"", ",", "\"Op Time (%s)\"", "%", "time_unit", ",", "\"Exec Time (%s)\"", "%", "time_unit", ",", "\"Filename:Lineno(function)\"", "]", "self", ".", "_column_sort_ids", "=", "[", "SORT_OPS_BY_OP_NAME", ",", "SORT_OPS_BY_OP_TYPE", ",", "SORT_OPS_BY_START_TIME", ",", "SORT_OPS_BY_OP_TIME", ",", "SORT_OPS_BY_EXEC_TIME", ",", "SORT_OPS_BY_LINE", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/profile_analyzer_cli.py#L51-L79
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py
python
RegistryInfo.vc_for_python
(self)
return r'DevDiv\VCForPython'
Microsoft Visual C++ for Python registry key. Return ------ str Registry key
Microsoft Visual C++ for Python registry key.
[ "Microsoft", "Visual", "C", "++", "for", "Python", "registry", "key", "." ]
def vc_for_python(self): """ Microsoft Visual C++ for Python registry key. Return ------ str Registry key """ return r'DevDiv\VCForPython'
[ "def", "vc_for_python", "(", "self", ")", ":", "return", "r'DevDiv\\VCForPython'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py#L550-L559
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/ISISCommandInterface.py
python
get_q_resolution_w2
()
return val
Get the second width for rectangular apertures @returns the second width in mm
Get the second width for rectangular apertures
[ "Get", "the", "second", "width", "for", "rectangular", "apertures" ]
def get_q_resolution_w2(): ''' Get the second width for rectangular apertures @returns the second width in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_w2, "W2") print(str(val)) return val
[ "def", "get_q_resolution_w2", "(", ")", ":", "val", "=", "get_q_resolution_float", "(", "ReductionSingleton", "(", ")", ".", "to_Q", ".", "get_q_resolution_w2", ",", "\"W2\"", ")", "print", "(", "str", "(", "val", ")", ")", "return", "val" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/ISISCommandInterface.py#L1701-L1708
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py
python
GmmAlgorithm._define_partial_maximization_operation
(self, shard_id, shard)
Computes the partial statistics of the means and covariances. Args: shard_id: current shard id. shard: current data shard, 1 X num_examples X dimensions.
Computes the partial statistics of the means and covariances.
[ "Computes", "the", "partial", "statistics", "of", "the", "means", "and", "covariances", "." ]
def _define_partial_maximization_operation(self, shard_id, shard): """Computes the partial statistics of the means and covariances. Args: shard_id: current shard id. shard: current data shard, 1 X num_examples X dimensions. """ # Soft assignment of each data point to each of the two clusters. self._points_in_k[shard_id] = tf.reduce_sum(self._w[shard_id], 0, keep_dims=True) # Partial means. w_mul_x = tf.expand_dims( tf.matmul(self._w[shard_id], tf.squeeze(shard, [0]), transpose_a=True), 1) self._w_mul_x.append(w_mul_x) # Partial covariances. x = tf.concat(0, [shard for _ in range(self._num_classes)]) x_trans = tf.transpose(x, perm=[0, 2, 1]) x_mul_w = tf.concat(0, [ tf.expand_dims(x_trans[k, :, :] * self._w[shard_id][:, k], 0) for k in range(self._num_classes)]) self._w_mul_x2.append(tf.batch_matmul(x_mul_w, x))
[ "def", "_define_partial_maximization_operation", "(", "self", ",", "shard_id", ",", "shard", ")", ":", "# Soft assignment of each data point to each of the two clusters.", "self", ".", "_points_in_k", "[", "shard_id", "]", "=", "tf", ".", "reduce_sum", "(", "self", ".", "_w", "[", "shard_id", "]", ",", "0", ",", "keep_dims", "=", "True", ")", "# Partial means.", "w_mul_x", "=", "tf", ".", "expand_dims", "(", "tf", ".", "matmul", "(", "self", ".", "_w", "[", "shard_id", "]", ",", "tf", ".", "squeeze", "(", "shard", ",", "[", "0", "]", ")", ",", "transpose_a", "=", "True", ")", ",", "1", ")", "self", ".", "_w_mul_x", ".", "append", "(", "w_mul_x", ")", "# Partial covariances.", "x", "=", "tf", ".", "concat", "(", "0", ",", "[", "shard", "for", "_", "in", "range", "(", "self", ".", "_num_classes", ")", "]", ")", "x_trans", "=", "tf", ".", "transpose", "(", "x", ",", "perm", "=", "[", "0", ",", "2", ",", "1", "]", ")", "x_mul_w", "=", "tf", ".", "concat", "(", "0", ",", "[", "tf", ".", "expand_dims", "(", "x_trans", "[", "k", ",", ":", ",", ":", "]", "*", "self", ".", "_w", "[", "shard_id", "]", "[", ":", ",", "k", "]", ",", "0", ")", "for", "k", "in", "range", "(", "self", ".", "_num_classes", ")", "]", ")", "self", ".", "_w_mul_x2", ".", "append", "(", "tf", ".", "batch_matmul", "(", "x_mul_w", ",", "x", ")", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L307-L328
mapsme/omim
1892903b63f2c85b16ed4966d21fe76aba06b9ba
tools/python/maps_generator/generator/env.py
python
find_last_build_dir
(hint: Optional[AnyStr] = None)
return None if not pairs or pairs[0][1] == 0 else pairs[0][0].split(os.sep)[-1]
It tries to find a last generation directory. If it's found function returns path of last generation directory. Otherwise returns None.
It tries to find a last generation directory. If it's found function returns path of last generation directory. Otherwise returns None.
[ "It", "tries", "to", "find", "a", "last", "generation", "directory", ".", "If", "it", "s", "found", "function", "returns", "path", "of", "last", "generation", "directory", ".", "Otherwise", "returns", "None", "." ]
def find_last_build_dir(hint: Optional[AnyStr] = None) -> Optional[AnyStr]: """ It tries to find a last generation directory. If it's found function returns path of last generation directory. Otherwise returns None. """ if hint is not None: p = os.path.join(settings.MAIN_OUT_PATH, hint) return hint if os.path.exists(p) else None try: paths = [ os.path.join(settings.MAIN_OUT_PATH, f) for f in os.listdir(settings.MAIN_OUT_PATH) ] except FileNotFoundError: logger.exception(f"{settings.MAIN_OUT_PATH} not found.") return None versions = [] for path in paths: version_path = os.path.join(path, settings.VERSION_FILE_NAME) if not os.path.isfile(version_path): versions.append(0) else: versions.append(Version.read(version_path)) pairs = sorted(zip(paths, versions), key=lambda p: p[1], reverse=True) return None if not pairs or pairs[0][1] == 0 else pairs[0][0].split(os.sep)[-1]
[ "def", "find_last_build_dir", "(", "hint", ":", "Optional", "[", "AnyStr", "]", "=", "None", ")", "->", "Optional", "[", "AnyStr", "]", ":", "if", "hint", "is", "not", "None", ":", "p", "=", "os", ".", "path", ".", "join", "(", "settings", ".", "MAIN_OUT_PATH", ",", "hint", ")", "return", "hint", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "else", "None", "try", ":", "paths", "=", "[", "os", ".", "path", ".", "join", "(", "settings", ".", "MAIN_OUT_PATH", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "settings", ".", "MAIN_OUT_PATH", ")", "]", "except", "FileNotFoundError", ":", "logger", ".", "exception", "(", "f\"{settings.MAIN_OUT_PATH} not found.\"", ")", "return", "None", "versions", "=", "[", "]", "for", "path", "in", "paths", ":", "version_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "settings", ".", "VERSION_FILE_NAME", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "version_path", ")", ":", "versions", ".", "append", "(", "0", ")", "else", ":", "versions", ".", "append", "(", "Version", ".", "read", "(", "version_path", ")", ")", "pairs", "=", "sorted", "(", "zip", "(", "paths", ",", "versions", ")", ",", "key", "=", "lambda", "p", ":", "p", "[", "1", "]", ",", "reverse", "=", "True", ")", "return", "None", "if", "not", "pairs", "or", "pairs", "[", "0", "]", "[", "1", "]", "==", "0", "else", "pairs", "[", "0", "]", "[", "0", "]", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "1", "]" ]
https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/maps_generator/generator/env.py#L88-L112
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/parser.py
python
_parse_initializer
(ctxt, node)
return init
Parse a global initializer.
Parse a global initializer.
[ "Parse", "a", "global", "initializer", "." ]
def _parse_initializer(ctxt, node): # type: (errors.ParserContext, Union[yaml.nodes.ScalarNode, yaml.nodes.MappingNode]) -> syntax.GlobalInitializer """Parse a global initializer.""" init = syntax.GlobalInitializer(ctxt.file_name, node.start_mark.line, node.start_mark.column) if node.id == 'scalar': init.name = node.value return init _generic_parser(ctxt, node, "initializer", init, { "register": _RuleDesc('scalar', _RuleDesc.REQUIRED), "store": _RuleDesc('scalar'), }) return init
[ "def", "_parse_initializer", "(", "ctxt", ",", "node", ")", ":", "# type: (errors.ParserContext, Union[yaml.nodes.ScalarNode, yaml.nodes.MappingNode]) -> syntax.GlobalInitializer", "init", "=", "syntax", ".", "GlobalInitializer", "(", "ctxt", ".", "file_name", ",", "node", ".", "start_mark", ".", "line", ",", "node", ".", "start_mark", ".", "column", ")", "if", "node", ".", "id", "==", "'scalar'", ":", "init", ".", "name", "=", "node", ".", "value", "return", "init", "_generic_parser", "(", "ctxt", ",", "node", ",", "\"initializer\"", ",", "init", ",", "{", "\"register\"", ":", "_RuleDesc", "(", "'scalar'", ",", "_RuleDesc", ".", "REQUIRED", ")", ",", "\"store\"", ":", "_RuleDesc", "(", "'scalar'", ")", ",", "}", ")", "return", "init" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/parser.py#L179-L193
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ShallowWaterApplication/python_scripts/postprocess/line_graph_output_process.py
python
LineGraphOutputProcess.Check
(self)
Check the file settings.
Check the file settings.
[ "Check", "the", "file", "settings", "." ]
def Check(self): """Check the file settings.""" # Generate a dummy file to validate the parameters file = TimeBasedAsciiFileWriterUtility(self.model_part, self.file_settings, "").file file.close() DeleteFileIfExisting(file.name)
[ "def", "Check", "(", "self", ")", ":", "# Generate a dummy file to validate the parameters", "file", "=", "TimeBasedAsciiFileWriterUtility", "(", "self", ".", "model_part", ",", "self", ".", "file_settings", ",", "\"\"", ")", ".", "file", "file", ".", "close", "(", ")", "DeleteFileIfExisting", "(", "file", ".", "name", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShallowWaterApplication/python_scripts/postprocess/line_graph_output_process.py#L98-L104
microsoft/DirectXShaderCompiler
8348ff8d9e0287610ba05d3a828e10af981a1c05
utils/hct/CodeTags.py
python
StripIndent
(lines, indent)
return map(strip_indent, lines)
Remove indent from lines of text
Remove indent from lines of text
[ "Remove", "indent", "from", "lines", "of", "text" ]
def StripIndent(lines, indent): "Remove indent from lines of text" def strip_indent(line): if line.startswith(indent): return line[len(indent):] return line if isinstance(lines, basestring): lines = lines.splitlines() return map(strip_indent, lines)
[ "def", "StripIndent", "(", "lines", ",", "indent", ")", ":", "def", "strip_indent", "(", "line", ")", ":", "if", "line", ".", "startswith", "(", "indent", ")", ":", "return", "line", "[", "len", "(", "indent", ")", ":", "]", "return", "line", "if", "isinstance", "(", "lines", ",", "basestring", ")", ":", "lines", "=", "lines", ".", "splitlines", "(", ")", "return", "map", "(", "strip_indent", ",", "lines", ")" ]
https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/utils/hct/CodeTags.py#L87-L95
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBFrame.GetCFA
(self)
return _lldb.SBFrame_GetCFA(self)
GetCFA(self) -> addr_t Get the Canonical Frame Address for this stack frame. This is the DWARF standard's definition of a CFA, a stack address that remains constant throughout the lifetime of the function. Returns an lldb::addr_t stack address, or LLDB_INVALID_ADDRESS if the CFA cannot be determined.
GetCFA(self) -> addr_t
[ "GetCFA", "(", "self", ")", "-", ">", "addr_t" ]
def GetCFA(self): """ GetCFA(self) -> addr_t Get the Canonical Frame Address for this stack frame. This is the DWARF standard's definition of a CFA, a stack address that remains constant throughout the lifetime of the function. Returns an lldb::addr_t stack address, or LLDB_INVALID_ADDRESS if the CFA cannot be determined. """ return _lldb.SBFrame_GetCFA(self)
[ "def", "GetCFA", "(", "self", ")", ":", "return", "_lldb", ".", "SBFrame_GetCFA", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4513-L4523
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.BeginLineSpacing
(*args, **kwargs)
return _richtext.RichTextCtrl_BeginLineSpacing(*args, **kwargs)
BeginLineSpacing(self, int lineSpacing) -> bool Begin line spacing
BeginLineSpacing(self, int lineSpacing) -> bool
[ "BeginLineSpacing", "(", "self", "int", "lineSpacing", ")", "-", ">", "bool" ]
def BeginLineSpacing(*args, **kwargs): """ BeginLineSpacing(self, int lineSpacing) -> bool Begin line spacing """ return _richtext.RichTextCtrl_BeginLineSpacing(*args, **kwargs)
[ "def", "BeginLineSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_BeginLineSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3495-L3501
manticoresoftware/manticoresearch
f675d16267543d934ce84074f087d13496ec462c
api/sphinxapi.py
python
SphinxClient.SetFilterStringList
( self, attribute, value, exclude=0 )
Set string list filter.
Set string list filter.
[ "Set", "string", "list", "filter", "." ]
def SetFilterStringList ( self, attribute, value, exclude=0 ): """ Set string list filter. """ assert(isinstance(attribute, str)) assert(iter(value)) for v in value: assert(isinstance(v, str)) self._filters.append ( { 'type':SPH_FILTER_STRING_LIST, 'attr':attribute, 'exclude':exclude, 'values':value } )
[ "def", "SetFilterStringList", "(", "self", ",", "attribute", ",", "value", ",", "exclude", "=", "0", ")", ":", "assert", "(", "isinstance", "(", "attribute", ",", "str", ")", ")", "assert", "(", "iter", "(", "value", ")", ")", "for", "v", "in", "value", ":", "assert", "(", "isinstance", "(", "v", ",", "str", ")", ")", "self", ".", "_filters", ".", "append", "(", "{", "'type'", ":", "SPH_FILTER_STRING_LIST", ",", "'attr'", ":", "attribute", ",", "'exclude'", ":", "exclude", ",", "'values'", ":", "value", "}", ")" ]
https://github.com/manticoresoftware/manticoresearch/blob/f675d16267543d934ce84074f087d13496ec462c/api/sphinxapi.py#L454-L464
ElunaLuaEngine/Eluna
4d862f0bf6b08de451fe215ee0645fbdf7a23a9b
docs/ElunaDoc/parser.py
python
ClassParser.to_class_doc
(self)
return MangosClassDoc(self.class_name, self.class_description, self.methods)
Create an instance of `MangosClassDoc` from the parser's data. Is called by `parse_file` once parsing is finished.
Create an instance of `MangosClassDoc` from the parser's data.
[ "Create", "an", "instance", "of", "MangosClassDoc", "from", "the", "parser", "s", "data", "." ]
def to_class_doc(self): """Create an instance of `MangosClassDoc` from the parser's data. Is called by `parse_file` once parsing is finished. """ return MangosClassDoc(self.class_name, self.class_description, self.methods)
[ "def", "to_class_doc", "(", "self", ")", ":", "return", "MangosClassDoc", "(", "self", ".", "class_name", ",", "self", ".", "class_description", ",", "self", ".", "methods", ")" ]
https://github.com/ElunaLuaEngine/Eluna/blob/4d862f0bf6b08de451fe215ee0645fbdf7a23a9b/docs/ElunaDoc/parser.py#L311-L316
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
doc/pattern_tools/svgfig.py
python
Ticks.compute_logminiticks
(self, base)
Return optimal logarithmic miniticks, given a set of ticks. Normally only used internally.
Return optimal logarithmic miniticks, given a set of ticks.
[ "Return", "optimal", "logarithmic", "miniticks", "given", "a", "set", "of", "ticks", "." ]
def compute_logminiticks(self, base): """Return optimal logarithmic miniticks, given a set of ticks. Normally only used internally. """ if self.low >= self.high: raise ValueError("low must be less than high") lowN = math.floor(math.log(self.low, base)) highN = math.ceil(math.log(self.high, base)) output = [] num_ticks = 0 for n in range(int(lowN), int(highN)+1): x = base**n if self.low <= x <= self.high: num_ticks += 1 for m in range(2, int(math.ceil(base))): minix = m * x if self.low <= minix <= self.high: output.append(minix) if num_ticks <= 2: return [] else: return output
[ "def", "compute_logminiticks", "(", "self", ",", "base", ")", ":", "if", "self", ".", "low", ">=", "self", ".", "high", ":", "raise", "ValueError", "(", "\"low must be less than high\"", ")", "lowN", "=", "math", ".", "floor", "(", "math", ".", "log", "(", "self", ".", "low", ",", "base", ")", ")", "highN", "=", "math", ".", "ceil", "(", "math", ".", "log", "(", "self", ".", "high", ",", "base", ")", ")", "output", "=", "[", "]", "num_ticks", "=", "0", "for", "n", "in", "range", "(", "int", "(", "lowN", ")", ",", "int", "(", "highN", ")", "+", "1", ")", ":", "x", "=", "base", "**", "n", "if", "self", ".", "low", "<=", "x", "<=", "self", ".", "high", ":", "num_ticks", "+=", "1", "for", "m", "in", "range", "(", "2", ",", "int", "(", "math", ".", "ceil", "(", "base", ")", ")", ")", ":", "minix", "=", "m", "*", "x", "if", "self", ".", "low", "<=", "minix", "<=", "self", ".", "high", ":", "output", ".", "append", "(", "minix", ")", "if", "num_ticks", "<=", "2", ":", "return", "[", "]", "else", ":", "return", "output" ]
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/doc/pattern_tools/svgfig.py#L3043-L3067
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/array_manager.py
python
ArrayManager.fast_xs
(self, loc: int)
return result
Return the array corresponding to `frame.iloc[loc]`. Parameters ---------- loc : int Returns ------- np.ndarray or ExtensionArray
Return the array corresponding to `frame.iloc[loc]`.
[ "Return", "the", "array", "corresponding", "to", "frame", ".", "iloc", "[", "loc", "]", "." ]
def fast_xs(self, loc: int) -> ArrayLike: """ Return the array corresponding to `frame.iloc[loc]`. Parameters ---------- loc : int Returns ------- np.ndarray or ExtensionArray """ dtype = interleaved_dtype([arr.dtype for arr in self.arrays]) values = [arr[loc] for arr in self.arrays] if isinstance(dtype, ExtensionDtype): result = dtype.construct_array_type()._from_sequence(values, dtype=dtype) # for datetime64/timedelta64, the np.ndarray constructor cannot handle pd.NaT elif is_datetime64_ns_dtype(dtype): result = DatetimeArray._from_sequence(values, dtype=dtype)._data elif is_timedelta64_ns_dtype(dtype): result = TimedeltaArray._from_sequence(values, dtype=dtype)._data else: result = np.array(values, dtype=dtype) return result
[ "def", "fast_xs", "(", "self", ",", "loc", ":", "int", ")", "->", "ArrayLike", ":", "dtype", "=", "interleaved_dtype", "(", "[", "arr", ".", "dtype", "for", "arr", "in", "self", ".", "arrays", "]", ")", "values", "=", "[", "arr", "[", "loc", "]", "for", "arr", "in", "self", ".", "arrays", "]", "if", "isinstance", "(", "dtype", ",", "ExtensionDtype", ")", ":", "result", "=", "dtype", ".", "construct_array_type", "(", ")", ".", "_from_sequence", "(", "values", ",", "dtype", "=", "dtype", ")", "# for datetime64/timedelta64, the np.ndarray constructor cannot handle pd.NaT", "elif", "is_datetime64_ns_dtype", "(", "dtype", ")", ":", "result", "=", "DatetimeArray", ".", "_from_sequence", "(", "values", ",", "dtype", "=", "dtype", ")", ".", "_data", "elif", "is_timedelta64_ns_dtype", "(", "dtype", ")", ":", "result", "=", "TimedeltaArray", ".", "_from_sequence", "(", "values", ",", "dtype", "=", "dtype", ")", ".", "_data", "else", ":", "result", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "dtype", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/array_manager.py#L735-L759
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/ltisys.py
python
StateSpace.__new__
(cls, *system, **kwargs)
return super(StateSpace, cls).__new__(cls)
Create new StateSpace object and settle inheritance.
Create new StateSpace object and settle inheritance.
[ "Create", "new", "StateSpace", "object", "and", "settle", "inheritance", "." ]
def __new__(cls, *system, **kwargs): """Create new StateSpace object and settle inheritance.""" # Handle object conversion if input is an instance of `lti` if len(system) == 1 and isinstance(system[0], LinearTimeInvariant): return system[0].to_ss() # Choose whether to inherit from `lti` or from `dlti` if cls is StateSpace: if kwargs.get('dt') is None: return StateSpaceContinuous.__new__(StateSpaceContinuous, *system, **kwargs) else: return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system, **kwargs) # No special conversion needed return super(StateSpace, cls).__new__(cls)
[ "def", "__new__", "(", "cls", ",", "*", "system", ",", "*", "*", "kwargs", ")", ":", "# Handle object conversion if input is an instance of `lti`", "if", "len", "(", "system", ")", "==", "1", "and", "isinstance", "(", "system", "[", "0", "]", ",", "LinearTimeInvariant", ")", ":", "return", "system", "[", "0", "]", ".", "to_ss", "(", ")", "# Choose whether to inherit from `lti` or from `dlti`", "if", "cls", "is", "StateSpace", ":", "if", "kwargs", ".", "get", "(", "'dt'", ")", "is", "None", ":", "return", "StateSpaceContinuous", ".", "__new__", "(", "StateSpaceContinuous", ",", "*", "system", ",", "*", "*", "kwargs", ")", "else", ":", "return", "StateSpaceDiscrete", ".", "__new__", "(", "StateSpaceDiscrete", ",", "*", "system", ",", "*", "*", "kwargs", ")", "# No special conversion needed", "return", "super", "(", "StateSpace", ",", "cls", ")", ".", "__new__", "(", "cls", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L1301-L1317
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/session_ops.py
python
TensorHandle.__init__
(self, handle, dtype, session)
Constructs a new tensor handle. A tensor handle for a persistent tensor is a python string that has the form of "tensor_name;unique_id;device_name". Args: handle: A tensor handle. dtype: The data type of the tensor represented by `handle`. session: The session in which the tensor is produced.
Constructs a new tensor handle.
[ "Constructs", "a", "new", "tensor", "handle", "." ]
def __init__(self, handle, dtype, session): """Constructs a new tensor handle. A tensor handle for a persistent tensor is a python string that has the form of "tensor_name;unique_id;device_name". Args: handle: A tensor handle. dtype: The data type of the tensor represented by `handle`. session: The session in which the tensor is produced. """ self._handle = compat.as_str_any(handle) self._dtype = dtype self._session = session self._auto_gc_enabled = True
[ "def", "__init__", "(", "self", ",", "handle", ",", "dtype", ",", "session", ")", ":", "self", ".", "_handle", "=", "compat", ".", "as_str_any", "(", "handle", ")", "self", ".", "_dtype", "=", "dtype", "self", ".", "_session", "=", "session", "self", ".", "_auto_gc_enabled", "=", "True" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/session_ops.py#L41-L55