repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.lastChild
def lastChild(self): ''' lastChild - property, Get the last child block, text or tag @return <str/AdvancedTag/None> - The last child block, or None if no child blocks ''' blocks = object.__getattribute__(self, 'blocks') # First block is empty string for indent, but don't hardcode incase that changes if blocks[0] == '': firstIdx = 1 else: firstIdx = 0 if len(blocks) <= firstIdx: return None return blocks[-1]
python
def lastChild(self): ''' lastChild - property, Get the last child block, text or tag @return <str/AdvancedTag/None> - The last child block, or None if no child blocks ''' blocks = object.__getattribute__(self, 'blocks') # First block is empty string for indent, but don't hardcode incase that changes if blocks[0] == '': firstIdx = 1 else: firstIdx = 0 if len(blocks) <= firstIdx: return None return blocks[-1]
[ "def", "lastChild", "(", "self", ")", ":", "blocks", "=", "object", ".", "__getattribute__", "(", "self", ",", "'blocks'", ")", "# First block is empty string for indent, but don't hardcode incase that changes", "if", "blocks", "[", "0", "]", "==", "''", ":", "firstIdx", "=", "1", "else", ":", "firstIdx", "=", "0", "if", "len", "(", "blocks", ")", "<=", "firstIdx", ":", "return", "None", "return", "blocks", "[", "-", "1", "]" ]
lastChild - property, Get the last child block, text or tag @return <str/AdvancedTag/None> - The last child block, or None if no child blocks
[ "lastChild", "-", "property", "Get", "the", "last", "child", "block", "text", "or", "tag" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L895-L911
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.nextSibling
def nextSibling(self): ''' nextSibling - Returns the next sibling. This is the child following this node in the parent's list of children. This could be text or an element. use nextSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent after this node, Otherwise the following node (text or tag) ''' parentNode = self.parentNode # If no parent, no siblings. if not parentNode: return None # Determine index in blocks myBlockIdx = parentNode.blocks.index(self) # If we are the last, no next sibling if myBlockIdx == len(parentNode.blocks) - 1: return None # Else, return the next block in parent return parentNode.blocks[ myBlockIdx + 1 ]
python
def nextSibling(self): ''' nextSibling - Returns the next sibling. This is the child following this node in the parent's list of children. This could be text or an element. use nextSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent after this node, Otherwise the following node (text or tag) ''' parentNode = self.parentNode # If no parent, no siblings. if not parentNode: return None # Determine index in blocks myBlockIdx = parentNode.blocks.index(self) # If we are the last, no next sibling if myBlockIdx == len(parentNode.blocks) - 1: return None # Else, return the next block in parent return parentNode.blocks[ myBlockIdx + 1 ]
[ "def", "nextSibling", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no siblings.", "if", "not", "parentNode", ":", "return", "None", "# Determine index in blocks", "myBlockIdx", "=", "parentNode", ".", "blocks", ".", "index", "(", "self", ")", "# If we are the last, no next sibling", "if", "myBlockIdx", "==", "len", "(", "parentNode", ".", "blocks", ")", "-", "1", ":", "return", "None", "# Else, return the next block in parent", "return", "parentNode", ".", "blocks", "[", "myBlockIdx", "+", "1", "]" ]
nextSibling - Returns the next sibling. This is the child following this node in the parent's list of children. This could be text or an element. use nextSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent after this node, Otherwise the following node (text or tag)
[ "nextSibling", "-", "Returns", "the", "next", "sibling", ".", "This", "is", "the", "child", "following", "this", "node", "in", "the", "parent", "s", "list", "of", "children", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L929-L952
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.nextElementSibling
def nextElementSibling(self): ''' nextElementSibling - Returns the next sibling that is an element. This is the tag node following this node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent after this node, Otherwise the following element (tag) ''' parentNode = self.parentNode # If no parent, no siblings if not parentNode: return None # Determine the index in children myElementIdx = parentNode.children.index(self) # If we are last child, no next sibling if myElementIdx == len(parentNode.children) - 1: return None # Else, return the next child in parent return parentNode.children[myElementIdx+1]
python
def nextElementSibling(self): ''' nextElementSibling - Returns the next sibling that is an element. This is the tag node following this node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent after this node, Otherwise the following element (tag) ''' parentNode = self.parentNode # If no parent, no siblings if not parentNode: return None # Determine the index in children myElementIdx = parentNode.children.index(self) # If we are last child, no next sibling if myElementIdx == len(parentNode.children) - 1: return None # Else, return the next child in parent return parentNode.children[myElementIdx+1]
[ "def", "nextElementSibling", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no siblings", "if", "not", "parentNode", ":", "return", "None", "# Determine the index in children", "myElementIdx", "=", "parentNode", ".", "children", ".", "index", "(", "self", ")", "# If we are last child, no next sibling", "if", "myElementIdx", "==", "len", "(", "parentNode", ".", "children", ")", "-", "1", ":", "return", "None", "# Else, return the next child in parent", "return", "parentNode", ".", "children", "[", "myElementIdx", "+", "1", "]" ]
nextElementSibling - Returns the next sibling that is an element. This is the tag node following this node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent after this node, Otherwise the following element (tag)
[ "nextElementSibling", "-", "Returns", "the", "next", "sibling", "that", "is", "an", "element", ".", "This", "is", "the", "tag", "node", "following", "this", "node", "in", "the", "parent", "s", "list", "of", "children" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L955-L977
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.previousSibling
def previousSibling(self): ''' previousSibling - Returns the previous sibling. This would be the previous node (text or tag) in the parent's list This could be text or an element. use previousSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent before this node, Otherwise the previous node (text or tag) ''' parentNode = self.parentNode # If no parent, no previous sibling if not parentNode: return None # Determine block index on parent of this node myBlockIdx = parentNode.blocks.index(self) # If we are the first, no previous sibling if myBlockIdx == 0: return None # Else, return the previous block in parent return parentNode.blocks[myBlockIdx-1]
python
def previousSibling(self): ''' previousSibling - Returns the previous sibling. This would be the previous node (text or tag) in the parent's list This could be text or an element. use previousSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent before this node, Otherwise the previous node (text or tag) ''' parentNode = self.parentNode # If no parent, no previous sibling if not parentNode: return None # Determine block index on parent of this node myBlockIdx = parentNode.blocks.index(self) # If we are the first, no previous sibling if myBlockIdx == 0: return None # Else, return the previous block in parent return parentNode.blocks[myBlockIdx-1]
[ "def", "previousSibling", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no previous sibling", "if", "not", "parentNode", ":", "return", "None", "# Determine block index on parent of this node", "myBlockIdx", "=", "parentNode", ".", "blocks", ".", "index", "(", "self", ")", "# If we are the first, no previous sibling", "if", "myBlockIdx", "==", "0", ":", "return", "None", "# Else, return the previous block in parent", "return", "parentNode", ".", "blocks", "[", "myBlockIdx", "-", "1", "]" ]
previousSibling - Returns the previous sibling. This would be the previous node (text or tag) in the parent's list This could be text or an element. use previousSiblingElement to ensure element @return <None/str/AdvancedTag> - None if there are no nodes (text or tag) in the parent before this node, Otherwise the previous node (text or tag)
[ "previousSibling", "-", "Returns", "the", "previous", "sibling", ".", "This", "would", "be", "the", "previous", "node", "(", "text", "or", "tag", ")", "in", "the", "parent", "s", "list", "This", "could", "be", "text", "or", "an", "element", ".", "use", "previousSiblingElement", "to", "ensure", "element" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L982-L1006
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.previousElementSibling
def previousElementSibling(self): ''' previousElementSibling - Returns the previous sibling that is an element. This is the previous tag node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent before this node, Otherwise the previous element (tag) ''' parentNode = self.parentNode # If no parent, no siblings if not parentNode: return None # Determine this node's index in the children of parent myElementIdx = parentNode.children.index(self) # If we are the first child, no previous element if myElementIdx == 0: return None # Else, return previous element tag return parentNode.children[myElementIdx-1]
python
def previousElementSibling(self): ''' previousElementSibling - Returns the previous sibling that is an element. This is the previous tag node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent before this node, Otherwise the previous element (tag) ''' parentNode = self.parentNode # If no parent, no siblings if not parentNode: return None # Determine this node's index in the children of parent myElementIdx = parentNode.children.index(self) # If we are the first child, no previous element if myElementIdx == 0: return None # Else, return previous element tag return parentNode.children[myElementIdx-1]
[ "def", "previousElementSibling", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no siblings", "if", "not", "parentNode", ":", "return", "None", "# Determine this node's index in the children of parent", "myElementIdx", "=", "parentNode", ".", "children", ".", "index", "(", "self", ")", "# If we are the first child, no previous element", "if", "myElementIdx", "==", "0", ":", "return", "None", "# Else, return previous element tag", "return", "parentNode", ".", "children", "[", "myElementIdx", "-", "1", "]" ]
previousElementSibling - Returns the previous sibling that is an element. This is the previous tag node in the parent's list of children @return <None/AdvancedTag> - None if there are no children (tag) in the parent before this node, Otherwise the previous element (tag)
[ "previousElementSibling", "-", "Returns", "the", "previous", "sibling", "that", "is", "an", "element", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1009-L1034
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.tagBlocks
def tagBlocks(self): ''' tagBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a tag (not text) NOTE: This is similar to .children , and you should probably use .children instead except within this class itself @return list<AdvancedTag> - A list of direct children which are tags. ''' myBlocks = self.blocks return [block for block in myBlocks if issubclass(block.__class__, AdvancedTag)]
python
def tagBlocks(self): ''' tagBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a tag (not text) NOTE: This is similar to .children , and you should probably use .children instead except within this class itself @return list<AdvancedTag> - A list of direct children which are tags. ''' myBlocks = self.blocks return [block for block in myBlocks if issubclass(block.__class__, AdvancedTag)]
[ "def", "tagBlocks", "(", "self", ")", ":", "myBlocks", "=", "self", ".", "blocks", "return", "[", "block", "for", "block", "in", "myBlocks", "if", "issubclass", "(", "block", ".", "__class__", ",", "AdvancedTag", ")", "]" ]
tagBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a tag (not text) NOTE: This is similar to .children , and you should probably use .children instead except within this class itself @return list<AdvancedTag> - A list of direct children which are tags.
[ "tagBlocks", "-", "Property", ".", "Returns", "all", "the", "blocks", "which", "are", "direct", "children", "of", "this", "node", "where", "that", "block", "is", "a", "tag", "(", "not", "text", ")" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1040-L1051
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getBlocksTags
def getBlocksTags(self): ''' getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag. The tuples are ( block, blockIdx ) where "blockIdx" is the index of self.blocks wherein the tag resides. @return list< tuple(block, blockIdx) > - A list of tuples of child blocks which are tags and their index in the self.blocks list ''' myBlocks = self.blocks return [ (myBlocks[i], i) for i in range( len(myBlocks) ) if issubclass(myBlocks[i].__class__, AdvancedTag) ]
python
def getBlocksTags(self): ''' getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag. The tuples are ( block, blockIdx ) where "blockIdx" is the index of self.blocks wherein the tag resides. @return list< tuple(block, blockIdx) > - A list of tuples of child blocks which are tags and their index in the self.blocks list ''' myBlocks = self.blocks return [ (myBlocks[i], i) for i in range( len(myBlocks) ) if issubclass(myBlocks[i].__class__, AdvancedTag) ]
[ "def", "getBlocksTags", "(", "self", ")", ":", "myBlocks", "=", "self", ".", "blocks", "return", "[", "(", "myBlocks", "[", "i", "]", ",", "i", ")", "for", "i", "in", "range", "(", "len", "(", "myBlocks", ")", ")", "if", "issubclass", "(", "myBlocks", "[", "i", "]", ".", "__class__", ",", "AdvancedTag", ")", "]" ]
getBlocksTags - Returns a list of tuples referencing the blocks which are direct children of this node, and the block is an AdvancedTag. The tuples are ( block, blockIdx ) where "blockIdx" is the index of self.blocks wherein the tag resides. @return list< tuple(block, blockIdx) > - A list of tuples of child blocks which are tags and their index in the self.blocks list
[ "getBlocksTags", "-", "Returns", "a", "list", "of", "tuples", "referencing", "the", "blocks", "which", "are", "direct", "children", "of", "this", "node", "and", "the", "block", "is", "an", "AdvancedTag", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1054-L1064
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.textBlocks
def textBlocks(self): ''' textBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a text (not a tag) @return list<AdvancedTag> - A list of direct children which are text. ''' myBlocks = self.blocks return [block for block in myBlocks if not issubclass(block.__class__, AdvancedTag)]
python
def textBlocks(self): ''' textBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a text (not a tag) @return list<AdvancedTag> - A list of direct children which are text. ''' myBlocks = self.blocks return [block for block in myBlocks if not issubclass(block.__class__, AdvancedTag)]
[ "def", "textBlocks", "(", "self", ")", ":", "myBlocks", "=", "self", ".", "blocks", "return", "[", "block", "for", "block", "in", "myBlocks", "if", "not", "issubclass", "(", "block", ".", "__class__", ",", "AdvancedTag", ")", "]" ]
textBlocks - Property. Returns all the blocks which are direct children of this node, where that block is a text (not a tag) @return list<AdvancedTag> - A list of direct children which are text.
[ "textBlocks", "-", "Property", ".", "Returns", "all", "the", "blocks", "which", "are", "direct", "children", "of", "this", "node", "where", "that", "block", "is", "a", "text", "(", "not", "a", "tag", ")" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1068-L1077
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.textContent
def textContent(self): ''' textContent - property, gets the text of this node and all inner nodes. Use .innerText for just this node's text @return <str> - The text of all nodes at this level or lower ''' def _collateText(curNode): ''' _collateText - Recursive function to gather the "text" of all blocks in the order that they appear @param curNode <AdvancedTag> - The current AdvancedTag to process @return list<str> - A list of strings in order. Join using '' to obtain text as it would appear ''' curStrLst = [] blocks = object.__getattribute__(curNode, 'blocks') for block in blocks: if isTagNode(block): curStrLst += _collateText(block) else: curStrLst.append(block) return curStrLst return ''.join(_collateText(self))
python
def textContent(self): ''' textContent - property, gets the text of this node and all inner nodes. Use .innerText for just this node's text @return <str> - The text of all nodes at this level or lower ''' def _collateText(curNode): ''' _collateText - Recursive function to gather the "text" of all blocks in the order that they appear @param curNode <AdvancedTag> - The current AdvancedTag to process @return list<str> - A list of strings in order. Join using '' to obtain text as it would appear ''' curStrLst = [] blocks = object.__getattribute__(curNode, 'blocks') for block in blocks: if isTagNode(block): curStrLst += _collateText(block) else: curStrLst.append(block) return curStrLst return ''.join(_collateText(self))
[ "def", "textContent", "(", "self", ")", ":", "def", "_collateText", "(", "curNode", ")", ":", "'''\n _collateText - Recursive function to gather the \"text\" of all blocks\n\n in the order that they appear\n\n @param curNode <AdvancedTag> - The current AdvancedTag to process\n\n @return list<str> - A list of strings in order. Join using '' to obtain text\n as it would appear\n '''", "curStrLst", "=", "[", "]", "blocks", "=", "object", ".", "__getattribute__", "(", "curNode", ",", "'blocks'", ")", "for", "block", "in", "blocks", ":", "if", "isTagNode", "(", "block", ")", ":", "curStrLst", "+=", "_collateText", "(", "block", ")", "else", ":", "curStrLst", ".", "append", "(", "block", ")", "return", "curStrLst", "return", "''", ".", "join", "(", "_collateText", "(", "self", ")", ")" ]
textContent - property, gets the text of this node and all inner nodes. Use .innerText for just this node's text @return <str> - The text of all nodes at this level or lower
[ "textContent", "-", "property", "gets", "the", "text", "of", "this", "node", "and", "all", "inner", "nodes", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1092-L1124
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.containsUid
def containsUid(self, uid): ''' containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself. @param uid <uuid.UUID> - uuid to check @return <bool> - True if #uid is this node's uid, or is the uid of any children at any level down ''' # Check if this node is the match if self.uid == uid: return True # Scan all children for child in self.children: if child.containsUid(uid): return True return False
python
def containsUid(self, uid): ''' containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself. @param uid <uuid.UUID> - uuid to check @return <bool> - True if #uid is this node's uid, or is the uid of any children at any level down ''' # Check if this node is the match if self.uid == uid: return True # Scan all children for child in self.children: if child.containsUid(uid): return True return False
[ "def", "containsUid", "(", "self", ",", "uid", ")", ":", "# Check if this node is the match", "if", "self", ".", "uid", "==", "uid", ":", "return", "True", "# Scan all children", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "containsUid", "(", "uid", ")", ":", "return", "True", "return", "False" ]
containsUid - Check if the uid (unique internal ID) appears anywhere as a direct child to this node, or the node itself. @param uid <uuid.UUID> - uuid to check @return <bool> - True if #uid is this node's uid, or is the uid of any children at any level down
[ "containsUid", "-", "Check", "if", "the", "uid", "(", "unique", "internal", "ID", ")", "appears", "anywhere", "as", "a", "direct", "child", "to", "this", "node", "or", "the", "node", "itself", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1181-L1198
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAllChildNodes
def getAllChildNodes(self): ''' getAllChildNodes - Gets all the children, and their children, and their children, and so on, all the way to the end as a TagCollection. Use .childNodes for a regular list @return TagCollection<AdvancedTag> - A TagCollection of all children (and their children recursive) ''' ret = TagCollection() # Scan all the children of this node for child in self.children: # Append each child ret.append(child) # Append children's children recursive ret += child.getAllChildNodes() return ret
python
def getAllChildNodes(self): ''' getAllChildNodes - Gets all the children, and their children, and their children, and so on, all the way to the end as a TagCollection. Use .childNodes for a regular list @return TagCollection<AdvancedTag> - A TagCollection of all children (and their children recursive) ''' ret = TagCollection() # Scan all the children of this node for child in self.children: # Append each child ret.append(child) # Append children's children recursive ret += child.getAllChildNodes() return ret
[ "def", "getAllChildNodes", "(", "self", ")", ":", "ret", "=", "TagCollection", "(", ")", "# Scan all the children of this node", "for", "child", "in", "self", ".", "children", ":", "# Append each child", "ret", ".", "append", "(", "child", ")", "# Append children's children recursive", "ret", "+=", "child", ".", "getAllChildNodes", "(", ")", "return", "ret" ]
getAllChildNodes - Gets all the children, and their children, and their children, and so on, all the way to the end as a TagCollection. Use .childNodes for a regular list @return TagCollection<AdvancedTag> - A TagCollection of all children (and their children recursive)
[ "getAllChildNodes", "-", "Gets", "all", "the", "children", "and", "their", "children", "and", "their", "children", "and", "so", "on", "all", "the", "way", "to", "the", "end", "as", "a", "TagCollection", ".", "Use", ".", "childNodes", "for", "a", "regular", "list" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1200-L1220
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAllChildNodeUids
def getAllChildNodeUids(self): ''' getAllChildNodeUids - Returns all the unique internal IDs for all children, and there children, so on and so forth until the end. For performing "contains node" kind of logic, this is more efficent than copying the entire nodeset @return set<uuid.UUID> A set of uuid objects ''' ret = set() # Iterate through all children for child in self.children: # Add child's uid ret.add(child.uid) # Add child's children's uid and their children, recursive ret.update(child.getAllChildNodeUids()) return ret
python
def getAllChildNodeUids(self): ''' getAllChildNodeUids - Returns all the unique internal IDs for all children, and there children, so on and so forth until the end. For performing "contains node" kind of logic, this is more efficent than copying the entire nodeset @return set<uuid.UUID> A set of uuid objects ''' ret = set() # Iterate through all children for child in self.children: # Add child's uid ret.add(child.uid) # Add child's children's uid and their children, recursive ret.update(child.getAllChildNodeUids()) return ret
[ "def", "getAllChildNodeUids", "(", "self", ")", ":", "ret", "=", "set", "(", ")", "# Iterate through all children", "for", "child", "in", "self", ".", "children", ":", "# Add child's uid", "ret", ".", "add", "(", "child", ".", "uid", ")", "# Add child's children's uid and their children, recursive", "ret", ".", "update", "(", "child", ".", "getAllChildNodeUids", "(", ")", ")", "return", "ret" ]
getAllChildNodeUids - Returns all the unique internal IDs for all children, and there children, so on and so forth until the end. For performing "contains node" kind of logic, this is more efficent than copying the entire nodeset @return set<uuid.UUID> A set of uuid objects
[ "getAllChildNodeUids", "-", "Returns", "all", "the", "unique", "internal", "IDs", "for", "all", "children", "and", "there", "children", "so", "on", "and", "so", "forth", "until", "the", "end", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1238-L1256
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAllNodeUids
def getAllNodeUids(self): ''' getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid @return set<uuid.UUID> A set of uuid objects ''' # Start with a set including this tag's uuid ret = { self.uid } ret.update(self.getAllChildNodeUids()) return ret
python
def getAllNodeUids(self): ''' getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid @return set<uuid.UUID> A set of uuid objects ''' # Start with a set including this tag's uuid ret = { self.uid } ret.update(self.getAllChildNodeUids()) return ret
[ "def", "getAllNodeUids", "(", "self", ")", ":", "# Start with a set including this tag's uuid", "ret", "=", "{", "self", ".", "uid", "}", "ret", ".", "update", "(", "self", ".", "getAllChildNodeUids", "(", ")", ")", "return", "ret" ]
getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid @return set<uuid.UUID> A set of uuid objects
[ "getAllNodeUids", "-", "Returns", "all", "the", "unique", "internal", "IDs", "from", "getAllChildNodeUids", "but", "also", "includes", "this", "tag", "s", "uid" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1258-L1269
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeers
def getPeers(self): ''' getPeers - Get elements who share a parent with this element @return - TagCollection of elements ''' parentNode = self.parentNode # If no parent, no peers if not parentNode: return None peers = parentNode.children # Otherwise, get all children of parent excluding this node return TagCollection([peer for peer in peers if peer is not self])
python
def getPeers(self): ''' getPeers - Get elements who share a parent with this element @return - TagCollection of elements ''' parentNode = self.parentNode # If no parent, no peers if not parentNode: return None peers = parentNode.children # Otherwise, get all children of parent excluding this node return TagCollection([peer for peer in peers if peer is not self])
[ "def", "getPeers", "(", "self", ")", ":", "parentNode", "=", "self", ".", "parentNode", "# If no parent, no peers", "if", "not", "parentNode", ":", "return", "None", "peers", "=", "parentNode", ".", "children", "# Otherwise, get all children of parent excluding this node", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "peer", "is", "not", "self", "]", ")" ]
getPeers - Get elements who share a parent with this element @return - TagCollection of elements
[ "getPeers", "-", "Get", "elements", "who", "share", "a", "parent", "with", "this", "element" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1272-L1286
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getStartTag
def getStartTag(self): ''' getStartTag - Returns the start tag represented as HTML @return - String of start tag with attributes ''' attributeStrings = [] # Get all attributes as a tuple (name<str>, value<str>) for name, val in self._attributes.items(): # Get all attributes if val: val = tostr(val) # Only binary attributes have a "present/not present" if val or name not in TAG_ITEM_BINARY_ATTRIBUTES: # Escape any quotes found in the value val = escapeQuotes(val) # Add a name="value" to the resulting string attributeStrings.append('%s="%s"' %(name, val) ) else: # This is a binary attribute, and thus only includes the name ( e.x. checked ) attributeStrings.append(name) # Join together all the attributes in @attributeStrings list into a string if attributeStrings: attributeString = ' ' + ' '.join(attributeStrings) else: attributeString = '' # If this is a self-closing tag, generate like <tag attr1="val" attr2="val2" /> with the close "/>" # Include the indent prior to tag opening if self.isSelfClosing is False: return "%s<%s%s >" %(self._indent, self.tagName, attributeString) else: return "%s<%s%s />" %(self._indent, self.tagName, attributeString)
python
def getStartTag(self): ''' getStartTag - Returns the start tag represented as HTML @return - String of start tag with attributes ''' attributeStrings = [] # Get all attributes as a tuple (name<str>, value<str>) for name, val in self._attributes.items(): # Get all attributes if val: val = tostr(val) # Only binary attributes have a "present/not present" if val or name not in TAG_ITEM_BINARY_ATTRIBUTES: # Escape any quotes found in the value val = escapeQuotes(val) # Add a name="value" to the resulting string attributeStrings.append('%s="%s"' %(name, val) ) else: # This is a binary attribute, and thus only includes the name ( e.x. checked ) attributeStrings.append(name) # Join together all the attributes in @attributeStrings list into a string if attributeStrings: attributeString = ' ' + ' '.join(attributeStrings) else: attributeString = '' # If this is a self-closing tag, generate like <tag attr1="val" attr2="val2" /> with the close "/>" # Include the indent prior to tag opening if self.isSelfClosing is False: return "%s<%s%s >" %(self._indent, self.tagName, attributeString) else: return "%s<%s%s />" %(self._indent, self.tagName, attributeString)
[ "def", "getStartTag", "(", "self", ")", ":", "attributeStrings", "=", "[", "]", "# Get all attributes as a tuple (name<str>, value<str>)", "for", "name", ",", "val", "in", "self", ".", "_attributes", ".", "items", "(", ")", ":", "# Get all attributes", "if", "val", ":", "val", "=", "tostr", "(", "val", ")", "# Only binary attributes have a \"present/not present\"", "if", "val", "or", "name", "not", "in", "TAG_ITEM_BINARY_ATTRIBUTES", ":", "# Escape any quotes found in the value", "val", "=", "escapeQuotes", "(", "val", ")", "# Add a name=\"value\" to the resulting string", "attributeStrings", ".", "append", "(", "'%s=\"%s\"'", "%", "(", "name", ",", "val", ")", ")", "else", ":", "# This is a binary attribute, and thus only includes the name ( e.x. checked )", "attributeStrings", ".", "append", "(", "name", ")", "# Join together all the attributes in @attributeStrings list into a string", "if", "attributeStrings", ":", "attributeString", "=", "' '", "+", "' '", ".", "join", "(", "attributeStrings", ")", "else", ":", "attributeString", "=", "''", "# If this is a self-closing tag, generate like <tag attr1=\"val\" attr2=\"val2\" /> with the close \"/>\"", "# Include the indent prior to tag opening", "if", "self", ".", "isSelfClosing", "is", "False", ":", "return", "\"%s<%s%s >\"", "%", "(", "self", ".", "_indent", ",", "self", ".", "tagName", ",", "attributeString", ")", "else", ":", "return", "\"%s<%s%s />\"", "%", "(", "self", ".", "_indent", ",", "self", ".", "tagName", ",", "attributeString", ")" ]
getStartTag - Returns the start tag represented as HTML @return - String of start tag with attributes
[ "getStartTag", "-", "Returns", "the", "start", "tag", "represented", "as", "HTML" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1395-L1430
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getEndTag
def getEndTag(self): ''' getEndTag - returns the end tag representation as HTML string @return - String of end tag ''' # If this is a self-closing tag, we have no end tag (opens and closes in the start) if self.isSelfClosing is True: return '' tagName = self.tagName # Do not add any indentation to the end of preformatted tags. if self._indent and tagName in PREFORMATTED_TAGS: return "</%s>" %(tagName, ) # Otherwise, indent the end of this tag return "%s</%s>" %(self._indent, tagName)
python
def getEndTag(self): ''' getEndTag - returns the end tag representation as HTML string @return - String of end tag ''' # If this is a self-closing tag, we have no end tag (opens and closes in the start) if self.isSelfClosing is True: return '' tagName = self.tagName # Do not add any indentation to the end of preformatted tags. if self._indent and tagName in PREFORMATTED_TAGS: return "</%s>" %(tagName, ) # Otherwise, indent the end of this tag return "%s</%s>" %(self._indent, tagName)
[ "def", "getEndTag", "(", "self", ")", ":", "# If this is a self-closing tag, we have no end tag (opens and closes in the start)", "if", "self", ".", "isSelfClosing", "is", "True", ":", "return", "''", "tagName", "=", "self", ".", "tagName", "# Do not add any indentation to the end of preformatted tags.", "if", "self", ".", "_indent", "and", "tagName", "in", "PREFORMATTED_TAGS", ":", "return", "\"</%s>\"", "%", "(", "tagName", ",", ")", "# Otherwise, indent the end of this tag", "return", "\"%s</%s>\"", "%", "(", "self", ".", "_indent", ",", "tagName", ")" ]
getEndTag - returns the end tag representation as HTML string @return - String of end tag
[ "getEndTag", "-", "returns", "the", "end", "tag", "representation", "as", "HTML", "string" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1432-L1449
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.innerHTML
def innerHTML(self): ''' innerHTML - Returns an HTML string of the inner contents of this tag, including children. @return - String of inner contents HTML ''' # If a self-closing tag, there are no contents if self.isSelfClosing is True: return '' # Assemble all the blocks. ret = [] # Iterate through blocks for block in self.blocks: # For each block: # If a tag, append the outer html (start tag, contents, and end tag) # Else, append the text node directly if isinstance(block, AdvancedTag): ret.append(block.outerHTML) else: ret.append(block) return ''.join(ret)
python
def innerHTML(self): ''' innerHTML - Returns an HTML string of the inner contents of this tag, including children. @return - String of inner contents HTML ''' # If a self-closing tag, there are no contents if self.isSelfClosing is True: return '' # Assemble all the blocks. ret = [] # Iterate through blocks for block in self.blocks: # For each block: # If a tag, append the outer html (start tag, contents, and end tag) # Else, append the text node directly if isinstance(block, AdvancedTag): ret.append(block.outerHTML) else: ret.append(block) return ''.join(ret)
[ "def", "innerHTML", "(", "self", ")", ":", "# If a self-closing tag, there are no contents", "if", "self", ".", "isSelfClosing", "is", "True", ":", "return", "''", "# Assemble all the blocks.", "ret", "=", "[", "]", "# Iterate through blocks", "for", "block", "in", "self", ".", "blocks", ":", "# For each block:", "# If a tag, append the outer html (start tag, contents, and end tag)", "# Else, append the text node directly", "if", "isinstance", "(", "block", ",", "AdvancedTag", ")", ":", "ret", ".", "append", "(", "block", ".", "outerHTML", ")", "else", ":", "ret", ".", "append", "(", "block", ")", "return", "''", ".", "join", "(", "ret", ")" ]
innerHTML - Returns an HTML string of the inner contents of this tag, including children. @return - String of inner contents HTML
[ "innerHTML", "-", "Returns", "an", "HTML", "string", "of", "the", "inner", "contents", "of", "this", "tag", "including", "children", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1452-L1477
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAttribute
def getAttribute(self, attrName, defaultValue=None): ''' getAttribute - Gets an attribute on this tag. Be wary using this for classname, maybe use addClass/removeClass. Attribute names are all lowercase. @return - The attribute value, or None if none exists. ''' if attrName in TAG_ITEM_BINARY_ATTRIBUTES: if attrName in self._attributes: attrVal = self._attributes[attrName] if not attrVal: return True # Empty valued binary attribute return attrVal # optionally-valued binary attribute else: return False else: return self._attributes.get(attrName, defaultValue)
python
def getAttribute(self, attrName, defaultValue=None): ''' getAttribute - Gets an attribute on this tag. Be wary using this for classname, maybe use addClass/removeClass. Attribute names are all lowercase. @return - The attribute value, or None if none exists. ''' if attrName in TAG_ITEM_BINARY_ATTRIBUTES: if attrName in self._attributes: attrVal = self._attributes[attrName] if not attrVal: return True # Empty valued binary attribute return attrVal # optionally-valued binary attribute else: return False else: return self._attributes.get(attrName, defaultValue)
[ "def", "getAttribute", "(", "self", ",", "attrName", ",", "defaultValue", "=", "None", ")", ":", "if", "attrName", "in", "TAG_ITEM_BINARY_ATTRIBUTES", ":", "if", "attrName", "in", "self", ".", "_attributes", ":", "attrVal", "=", "self", ".", "_attributes", "[", "attrName", "]", "if", "not", "attrVal", ":", "return", "True", "# Empty valued binary attribute", "return", "attrVal", "# optionally-valued binary attribute", "else", ":", "return", "False", "else", ":", "return", "self", ".", "_attributes", ".", "get", "(", "attrName", ",", "defaultValue", ")" ]
getAttribute - Gets an attribute on this tag. Be wary using this for classname, maybe use addClass/removeClass. Attribute names are all lowercase. @return - The attribute value, or None if none exists.
[ "getAttribute", "-", "Gets", "an", "attribute", "on", "this", "tag", ".", "Be", "wary", "using", "this", "for", "classname", "maybe", "use", "addClass", "/", "removeClass", ".", "Attribute", "names", "are", "all", "lowercase", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1489-L1505
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAttributesList
def getAttributesList(self): ''' getAttributesList - Get a copy of all attributes as a list of tuples (name, value) ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return list< tuple< str(name), str(value) > > - A list of tuples of attrName, attrValue pairs, all converted to strings. This is suitable for passing back into AdvancedTag when creating a new tag. ''' return [ (tostr(name)[:], tostr(value)[:]) for name, value in self._attributes.items() ]
python
def getAttributesList(self): ''' getAttributesList - Get a copy of all attributes as a list of tuples (name, value) ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return list< tuple< str(name), str(value) > > - A list of tuples of attrName, attrValue pairs, all converted to strings. This is suitable for passing back into AdvancedTag when creating a new tag. ''' return [ (tostr(name)[:], tostr(value)[:]) for name, value in self._attributes.items() ]
[ "def", "getAttributesList", "(", "self", ")", ":", "return", "[", "(", "tostr", "(", "name", ")", "[", ":", "]", ",", "tostr", "(", "value", ")", "[", ":", "]", ")", "for", "name", ",", "value", "in", "self", ".", "_attributes", ".", "items", "(", ")", "]" ]
getAttributesList - Get a copy of all attributes as a list of tuples (name, value) ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return list< tuple< str(name), str(value) > > - A list of tuples of attrName, attrValue pairs, all converted to strings. This is suitable for passing back into AdvancedTag when creating a new tag.
[ "getAttributesList", "-", "Get", "a", "copy", "of", "all", "attributes", "as", "a", "list", "of", "tuples", "(", "name", "value", ")" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1508-L1519
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getAttributesDict
def getAttributesDict(self): ''' getAttributesDict - Get a copy of all attributes as a dict map of name -> value ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return <dict ( str(name), str(value) )> - A dict of attrName to attrValue , all as strings and copies. ''' return { tostr(name)[:] : tostr(value)[:] for name, value in self._attributes.items() }
python
def getAttributesDict(self): ''' getAttributesDict - Get a copy of all attributes as a dict map of name -> value ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return <dict ( str(name), str(value) )> - A dict of attrName to attrValue , all as strings and copies. ''' return { tostr(name)[:] : tostr(value)[:] for name, value in self._attributes.items() }
[ "def", "getAttributesDict", "(", "self", ")", ":", "return", "{", "tostr", "(", "name", ")", "[", ":", "]", ":", "tostr", "(", "value", ")", "[", ":", "]", "for", "name", ",", "value", "in", "self", ".", "_attributes", ".", "items", "(", ")", "}" ]
getAttributesDict - Get a copy of all attributes as a dict map of name -> value ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return <dict ( str(name), str(value) )> - A dict of attrName to attrValue , all as strings and copies.
[ "getAttributesDict", "-", "Get", "a", "copy", "of", "all", "attributes", "as", "a", "dict", "map", "of", "name", "-", ">", "value" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1522-L1532
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.hasAttribute
def hasAttribute(self, attrName): ''' hasAttribute - Checks for the existance of an attribute. Attribute names are all lowercase. @param attrName <str> - The attribute name @return <bool> - True or False if attribute exists by that name ''' attrName = attrName.lower() # Check if requested attribute is present on this node return bool(attrName in self._attributes)
python
def hasAttribute(self, attrName): ''' hasAttribute - Checks for the existance of an attribute. Attribute names are all lowercase. @param attrName <str> - The attribute name @return <bool> - True or False if attribute exists by that name ''' attrName = attrName.lower() # Check if requested attribute is present on this node return bool(attrName in self._attributes)
[ "def", "hasAttribute", "(", "self", ",", "attrName", ")", ":", "attrName", "=", "attrName", ".", "lower", "(", ")", "# Check if requested attribute is present on this node", "return", "bool", "(", "attrName", "in", "self", ".", "_attributes", ")" ]
hasAttribute - Checks for the existance of an attribute. Attribute names are all lowercase. @param attrName <str> - The attribute name @return <bool> - True or False if attribute exists by that name
[ "hasAttribute", "-", "Checks", "for", "the", "existance", "of", "an", "attribute", ".", "Attribute", "names", "are", "all", "lowercase", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1554-L1565
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.removeAttribute
def removeAttribute(self, attrName): ''' removeAttribute - Removes an attribute, by name. @param attrName <str> - The attribute name ''' attrName = attrName.lower() # Delete provided attribute name ( #attrName ) from attributes map try: del self._attributes[attrName] except KeyError: pass
python
def removeAttribute(self, attrName): ''' removeAttribute - Removes an attribute, by name. @param attrName <str> - The attribute name ''' attrName = attrName.lower() # Delete provided attribute name ( #attrName ) from attributes map try: del self._attributes[attrName] except KeyError: pass
[ "def", "removeAttribute", "(", "self", ",", "attrName", ")", ":", "attrName", "=", "attrName", ".", "lower", "(", ")", "# Delete provided attribute name ( #attrName ) from attributes map", "try", ":", "del", "self", ".", "_attributes", "[", "attrName", "]", "except", "KeyError", ":", "pass" ]
removeAttribute - Removes an attribute, by name. @param attrName <str> - The attribute name
[ "removeAttribute", "-", "Removes", "an", "attribute", "by", "name", ".", "@param", "attrName", "<str", ">", "-", "The", "attribute", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1567-L1580
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.addClass
def addClass(self, className): ''' addClass - append a class name to the end of the "class" attribute, if not present @param className <str> - The name of the class to add ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.addClass(oneClassName) return myClassNames = self._classNames # Do not allow duplicates if className in myClassNames: return # Regenerate "classNames" and "class" attr. # TODO: Maybe those should be properties? myClassNames.append(className) return None
python
def addClass(self, className): ''' addClass - append a class name to the end of the "class" attribute, if not present @param className <str> - The name of the class to add ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.addClass(oneClassName) return myClassNames = self._classNames # Do not allow duplicates if className in myClassNames: return # Regenerate "classNames" and "class" attr. # TODO: Maybe those should be properties? myClassNames.append(className) return None
[ "def", "addClass", "(", "self", ",", "className", ")", ":", "className", "=", "stripWordsOnly", "(", "className", ")", "if", "not", "className", ":", "return", "None", "if", "' '", "in", "className", ":", "# Multiple class names passed, do one at a time", "for", "oneClassName", "in", "className", ".", "split", "(", "' '", ")", ":", "self", ".", "addClass", "(", "oneClassName", ")", "return", "myClassNames", "=", "self", ".", "_classNames", "# Do not allow duplicates", "if", "className", "in", "myClassNames", ":", "return", "# Regenerate \"classNames\" and \"class\" attr.", "# TODO: Maybe those should be properties?", "myClassNames", ".", "append", "(", "className", ")", "return", "None" ]
addClass - append a class name to the end of the "class" attribute, if not present @param className <str> - The name of the class to add
[ "addClass", "-", "append", "a", "class", "name", "to", "the", "end", "of", "the", "class", "attribute", "if", "not", "present" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1593-L1620
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.removeClass
def removeClass(self, className): ''' removeClass - remove a class name if present. Returns the class name if removed, otherwise None. @param className <str> - The name of the class to remove @return <str> - The class name removed if one was removed, otherwise None if #className wasn't present ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.removeClass(oneClassName) return myClassNames = self._classNames # If not present, this is a no-op if className not in myClassNames: return None myClassNames.remove(className) return className
python
def removeClass(self, className): ''' removeClass - remove a class name if present. Returns the class name if removed, otherwise None. @param className <str> - The name of the class to remove @return <str> - The class name removed if one was removed, otherwise None if #className wasn't present ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.removeClass(oneClassName) return myClassNames = self._classNames # If not present, this is a no-op if className not in myClassNames: return None myClassNames.remove(className) return className
[ "def", "removeClass", "(", "self", ",", "className", ")", ":", "className", "=", "stripWordsOnly", "(", "className", ")", "if", "not", "className", ":", "return", "None", "if", "' '", "in", "className", ":", "# Multiple class names passed, do one at a time", "for", "oneClassName", "in", "className", ".", "split", "(", "' '", ")", ":", "self", ".", "removeClass", "(", "oneClassName", ")", "return", "myClassNames", "=", "self", ".", "_classNames", "# If not present, this is a no-op", "if", "className", "not", "in", "myClassNames", ":", "return", "None", "myClassNames", ".", "remove", "(", "className", ")", "return", "className" ]
removeClass - remove a class name if present. Returns the class name if removed, otherwise None. @param className <str> - The name of the class to remove @return <str> - The class name removed if one was removed, otherwise None if #className wasn't present
[ "removeClass", "-", "remove", "a", "class", "name", "if", "present", ".", "Returns", "the", "class", "name", "if", "removed", "otherwise", "None", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1623-L1651
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getStyleDict
def getStyleDict(self): ''' getStyleDict - Gets a dictionary of style attribute/value pairs. @return - OrderedDict of "style" attribute. ''' # TODO: This method is not used and does not appear in any tests. styleStr = (self.getAttribute('style') or '').strip() styles = styleStr.split(';') # Won't work for strings containing semicolon.. styleDict = OrderedDict() for item in styles: try: splitIdx = item.index(':') name = item[:splitIdx].strip().lower() value = item[splitIdx+1:].strip() styleDict[name] = value except: continue return styleDict
python
def getStyleDict(self): ''' getStyleDict - Gets a dictionary of style attribute/value pairs. @return - OrderedDict of "style" attribute. ''' # TODO: This method is not used and does not appear in any tests. styleStr = (self.getAttribute('style') or '').strip() styles = styleStr.split(';') # Won't work for strings containing semicolon.. styleDict = OrderedDict() for item in styles: try: splitIdx = item.index(':') name = item[:splitIdx].strip().lower() value = item[splitIdx+1:].strip() styleDict[name] = value except: continue return styleDict
[ "def", "getStyleDict", "(", "self", ")", ":", "# TODO: This method is not used and does not appear in any tests.", "styleStr", "=", "(", "self", ".", "getAttribute", "(", "'style'", ")", "or", "''", ")", ".", "strip", "(", ")", "styles", "=", "styleStr", ".", "split", "(", "';'", ")", "# Won't work for strings containing semicolon..", "styleDict", "=", "OrderedDict", "(", ")", "for", "item", "in", "styles", ":", "try", ":", "splitIdx", "=", "item", ".", "index", "(", "':'", ")", "name", "=", "item", "[", ":", "splitIdx", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "value", "=", "item", "[", "splitIdx", "+", "1", ":", "]", ".", "strip", "(", ")", "styleDict", "[", "name", "]", "=", "value", "except", ":", "continue", "return", "styleDict" ]
getStyleDict - Gets a dictionary of style attribute/value pairs. @return - OrderedDict of "style" attribute.
[ "getStyleDict", "-", "Gets", "a", "dictionary", "of", "style", "attribute", "/", "value", "pairs", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1654-L1675
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.setStyle
def setStyle(self, styleName, styleValue): ''' setStyle - Sets a style param. Example: "display", "block" If you need to set many styles on an element, use setStyles instead. It takes a dictionary of attribute, value pairs and applies it all in one go (faster) To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleName - The name of the style element @param styleValue - The value of which to assign the style element @return - String of current value of "style" after change is made. ''' myAttributes = self._attributes if 'style' not in myAttributes: myAttributes['style'] = "%s: %s" %(styleName, styleValue) else: setattr(myAttributes['style'], styleName, styleValue)
python
def setStyle(self, styleName, styleValue): ''' setStyle - Sets a style param. Example: "display", "block" If you need to set many styles on an element, use setStyles instead. It takes a dictionary of attribute, value pairs and applies it all in one go (faster) To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleName - The name of the style element @param styleValue - The value of which to assign the style element @return - String of current value of "style" after change is made. ''' myAttributes = self._attributes if 'style' not in myAttributes: myAttributes['style'] = "%s: %s" %(styleName, styleValue) else: setattr(myAttributes['style'], styleName, styleValue)
[ "def", "setStyle", "(", "self", ",", "styleName", ",", "styleValue", ")", ":", "myAttributes", "=", "self", ".", "_attributes", "if", "'style'", "not", "in", "myAttributes", ":", "myAttributes", "[", "'style'", "]", "=", "\"%s: %s\"", "%", "(", "styleName", ",", "styleValue", ")", "else", ":", "setattr", "(", "myAttributes", "[", "'style'", "]", ",", "styleName", ",", "styleValue", ")" ]
setStyle - Sets a style param. Example: "display", "block" If you need to set many styles on an element, use setStyles instead. It takes a dictionary of attribute, value pairs and applies it all in one go (faster) To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleName - The name of the style element @param styleValue - The value of which to assign the style element @return - String of current value of "style" after change is made.
[ "setStyle", "-", "Sets", "a", "style", "param", ".", "Example", ":", "display", "block" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1689-L1709
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.setStyles
def setStyles(self, styleUpdatesDict): ''' setStyles - Sets one or more style params. This all happens in one shot, so it is much much faster than calling setStyle for every value. To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleUpdatesDict - Dictionary of attribute : value styles. @return - String of current value of "style" after change is made. ''' setStyleMethod = self.setStyle for newName, newValue in styleUpdatesDict.items(): setStyleMethod(newName, newValue) return self.style
python
def setStyles(self, styleUpdatesDict): ''' setStyles - Sets one or more style params. This all happens in one shot, so it is much much faster than calling setStyle for every value. To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleUpdatesDict - Dictionary of attribute : value styles. @return - String of current value of "style" after change is made. ''' setStyleMethod = self.setStyle for newName, newValue in styleUpdatesDict.items(): setStyleMethod(newName, newValue) return self.style
[ "def", "setStyles", "(", "self", ",", "styleUpdatesDict", ")", ":", "setStyleMethod", "=", "self", ".", "setStyle", "for", "newName", ",", "newValue", "in", "styleUpdatesDict", ".", "items", "(", ")", ":", "setStyleMethod", "(", "newName", ",", "newValue", ")", "return", "self", ".", "style" ]
setStyles - Sets one or more style params. This all happens in one shot, so it is much much faster than calling setStyle for every value. To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleUpdatesDict - Dictionary of attribute : value styles. @return - String of current value of "style" after change is made.
[ "setStyles", "-", "Sets", "one", "or", "more", "style", "params", ".", "This", "all", "happens", "in", "one", "shot", "so", "it", "is", "much", "much", "faster", "than", "calling", "setStyle", "for", "every", "value", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1712-L1728
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getElementById
def getElementById(self, _id): ''' getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None ''' for child in self.children: if child.getAttribute('id') == _id: return child found = child.getElementById(_id) if found is not None: return found return None
python
def getElementById(self, _id): ''' getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None ''' for child in self.children: if child.getAttribute('id') == _id: return child found = child.getElementById(_id) if found is not None: return found return None
[ "def", "getElementById", "(", "self", ",", "_id", ")", ":", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "getAttribute", "(", "'id'", ")", "==", "_id", ":", "return", "child", "found", "=", "child", ".", "getElementById", "(", "_id", ")", "if", "found", "is", "not", "None", ":", "return", "found", "return", "None" ]
getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None
[ "getElementById", "-", "Search", "children", "of", "this", "tag", "for", "a", "tag", "containing", "an", "id" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1781-L1795
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getElementsByAttr
def getElementsByAttr(self, attrName, attrValue): ''' getElementsByAttr - Search children of this tag for tags with an attribute name/value pair @param attrName - Attribute name (lowercase) @param attrValue - Attribute value @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.getAttribute(attrName) == attrValue: elements.append(child) elements += child.getElementsByAttr(attrName, attrValue) return TagCollection(elements)
python
def getElementsByAttr(self, attrName, attrValue): ''' getElementsByAttr - Search children of this tag for tags with an attribute name/value pair @param attrName - Attribute name (lowercase) @param attrValue - Attribute value @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.getAttribute(attrName) == attrValue: elements.append(child) elements += child.getElementsByAttr(attrName, attrValue) return TagCollection(elements)
[ "def", "getElementsByAttr", "(", "self", ",", "attrName", ",", "attrValue", ")", ":", "elements", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "getAttribute", "(", "attrName", ")", "==", "attrValue", ":", "elements", ".", "append", "(", "child", ")", "elements", "+=", "child", ".", "getElementsByAttr", "(", "attrName", ",", "attrValue", ")", "return", "TagCollection", "(", "elements", ")" ]
getElementsByAttr - Search children of this tag for tags with an attribute name/value pair @param attrName - Attribute name (lowercase) @param attrValue - Attribute value @return - TagCollection of matching elements
[ "getElementsByAttr", "-", "Search", "children", "of", "this", "tag", "for", "tags", "with", "an", "attribute", "name", "/", "value", "pair" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1797-L1811
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getElementsByClassName
def getElementsByClassName(self, className): ''' getElementsByClassName - Search children of this tag for tags containing a given class name @param className - Class name @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.hasClass(className) is True: elements.append(child) elements += child.getElementsByClassName(className) return TagCollection(elements)
python
def getElementsByClassName(self, className): ''' getElementsByClassName - Search children of this tag for tags containing a given class name @param className - Class name @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.hasClass(className) is True: elements.append(child) elements += child.getElementsByClassName(className) return TagCollection(elements)
[ "def", "getElementsByClassName", "(", "self", ",", "className", ")", ":", "elements", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "hasClass", "(", "className", ")", "is", "True", ":", "elements", ".", "append", "(", "child", ")", "elements", "+=", "child", ".", "getElementsByClassName", "(", "className", ")", "return", "TagCollection", "(", "elements", ")" ]
getElementsByClassName - Search children of this tag for tags containing a given class name @param className - Class name @return - TagCollection of matching elements
[ "getElementsByClassName", "-", "Search", "children", "of", "this", "tag", "for", "tags", "containing", "a", "given", "class", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1823-L1836
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getElementsWithAttrValues
def getElementsWithAttrValues(self, attrName, attrValues): ''' getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of acceptable attribute values @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.getAttribute(attrName) in attrValues: elements.append(child) elements += child.getElementsWithAttrValues(attrName, attrValues) return TagCollection(elements)
python
def getElementsWithAttrValues(self, attrName, attrValues): ''' getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of acceptable attribute values @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.getAttribute(attrName) in attrValues: elements.append(child) elements += child.getElementsWithAttrValues(attrName, attrValues) return TagCollection(elements)
[ "def", "getElementsWithAttrValues", "(", "self", ",", "attrName", ",", "attrValues", ")", ":", "elements", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "getAttribute", "(", "attrName", ")", "in", "attrValues", ":", "elements", ".", "append", "(", "child", ")", "elements", "+=", "child", ".", "getElementsWithAttrValues", "(", "attrName", ",", "attrValues", ")", "return", "TagCollection", "(", "elements", ")" ]
getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of acceptable attribute values @return - TagCollection of matching elements
[ "getElementsWithAttrValues", "-", "Search", "children", "of", "this", "tag", "for", "tags", "with", "an", "attribute", "name", "and", "one", "of", "several", "values" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1838-L1853
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getElementsCustomFilter
def getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Searches children of this tag for those matching a provided user function @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return - TagCollection of matching results @see getFirstElementCustomFilter ''' elements = [] for child in self.children: if filterFunc(child) is True: elements.append(child) elements += child.getElementsCustomFilter(filterFunc) return TagCollection(elements)
python
def getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Searches children of this tag for those matching a provided user function @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return - TagCollection of matching results @see getFirstElementCustomFilter ''' elements = [] for child in self.children: if filterFunc(child) is True: elements.append(child) elements += child.getElementsCustomFilter(filterFunc) return TagCollection(elements)
[ "def", "getElementsCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "elements", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "filterFunc", "(", "child", ")", "is", "True", ":", "elements", ".", "append", "(", "child", ")", "elements", "+=", "child", ".", "getElementsCustomFilter", "(", "filterFunc", ")", "return", "TagCollection", "(", "elements", ")" ]
getElementsCustomFilter - Searches children of this tag for those matching a provided user function @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return - TagCollection of matching results @see getFirstElementCustomFilter
[ "getElementsCustomFilter", "-", "Searches", "children", "of", "this", "tag", "for", "those", "matching", "a", "provided", "user", "function" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1856-L1873
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getFirstElementCustomFilter
def getFirstElementCustomFilter(self, filterFunc): ''' getFirstElementCustomFilter - Gets the first element which matches a given filter func. Scans first child, to the bottom, then next child to the bottom, etc. Does not include "self" node. @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getElementsCustomFilter ''' for child in self.children: if filterFunc(child) is True: return child childSearchResult = child.getFirstElementCustomFilter(filterFunc) if childSearchResult is not None: return childSearchResult return None
python
def getFirstElementCustomFilter(self, filterFunc): ''' getFirstElementCustomFilter - Gets the first element which matches a given filter func. Scans first child, to the bottom, then next child to the bottom, etc. Does not include "self" node. @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getElementsCustomFilter ''' for child in self.children: if filterFunc(child) is True: return child childSearchResult = child.getFirstElementCustomFilter(filterFunc) if childSearchResult is not None: return childSearchResult return None
[ "def", "getFirstElementCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "for", "child", "in", "self", ".", "children", ":", "if", "filterFunc", "(", "child", ")", "is", "True", ":", "return", "child", "childSearchResult", "=", "child", ".", "getFirstElementCustomFilter", "(", "filterFunc", ")", "if", "childSearchResult", "is", "not", "None", ":", "return", "childSearchResult", "return", "None" ]
getFirstElementCustomFilter - Gets the first element which matches a given filter func. Scans first child, to the bottom, then next child to the bottom, etc. Does not include "self" node. @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getElementsCustomFilter
[ "getFirstElementCustomFilter", "-", "Gets", "the", "first", "element", "which", "matches", "a", "given", "filter", "func", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1875-L1896
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getParentElementCustomFilter
def getParentElementCustomFilter(self, filterFunc): ''' getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getFirstElementCustomFilter for matches against children ''' parentNode = self.parentNode while parentNode: if filterFunc(parentNode) is True: return parentNode parentNode = parentNode.parentNode return None
python
def getParentElementCustomFilter(self, filterFunc): ''' getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getFirstElementCustomFilter for matches against children ''' parentNode = self.parentNode while parentNode: if filterFunc(parentNode) is True: return parentNode parentNode = parentNode.parentNode return None
[ "def", "getParentElementCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "parentNode", "=", "self", ".", "parentNode", "while", "parentNode", ":", "if", "filterFunc", "(", "parentNode", ")", "is", "True", ":", "return", "parentNode", "parentNode", "=", "parentNode", ".", "parentNode", "return", "None" ]
getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getFirstElementCustomFilter for matches against children
[ "getParentElementCustomFilter", "-", "Runs", "through", "parent", "on", "up", "to", "document", "root", "returning", "the" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1898-L1919
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeersCustomFilter
def getPeersCustomFilter(self, filterFunc): ''' getPeersCustomFilter - Get elements who share a parent with this element and also pass a custom filter check @param filterFunc <lambda/function> - Passed in an element, and returns True if it should be treated as a match, otherwise False. @return <TagCollection> - Resulting peers, or None if no parent node. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if filterFunc(peer) is True])
python
def getPeersCustomFilter(self, filterFunc): ''' getPeersCustomFilter - Get elements who share a parent with this element and also pass a custom filter check @param filterFunc <lambda/function> - Passed in an element, and returns True if it should be treated as a match, otherwise False. @return <TagCollection> - Resulting peers, or None if no parent node. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if filterFunc(peer) is True])
[ "def", "getPeersCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "peers", "=", "self", ".", "peers", "if", "peers", "is", "None", ":", "return", "None", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "filterFunc", "(", "peer", ")", "is", "True", "]", ")" ]
getPeersCustomFilter - Get elements who share a parent with this element and also pass a custom filter check @param filterFunc <lambda/function> - Passed in an element, and returns True if it should be treated as a match, otherwise False. @return <TagCollection> - Resulting peers, or None if no parent node.
[ "getPeersCustomFilter", "-", "Get", "elements", "who", "share", "a", "parent", "with", "this", "element", "and", "also", "pass", "a", "custom", "filter", "check" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1922-L1934
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeersByAttr
def getPeersByAttr(self, attrName, attrValue): ''' getPeersByAttr - Gets peers (elements on same level) which match an attribute/value combination. @param attrName - Name of attribute @param attrValue - Value that must match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.getAttribute(attrName) == attrValue])
python
def getPeersByAttr(self, attrName, attrValue): ''' getPeersByAttr - Gets peers (elements on same level) which match an attribute/value combination. @param attrName - Name of attribute @param attrValue - Value that must match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.getAttribute(attrName) == attrValue])
[ "def", "getPeersByAttr", "(", "self", ",", "attrName", ",", "attrValue", ")", ":", "peers", "=", "self", ".", "peers", "if", "peers", "is", "None", ":", "return", "None", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "peer", ".", "getAttribute", "(", "attrName", ")", "==", "attrValue", "]", ")" ]
getPeersByAttr - Gets peers (elements on same level) which match an attribute/value combination. @param attrName - Name of attribute @param attrValue - Value that must match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched.
[ "getPeersByAttr", "-", "Gets", "peers", "(", "elements", "on", "same", "level", ")", "which", "match", "an", "attribute", "/", "value", "combination", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1937-L1949
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeersWithAttrValues
def getPeersWithAttrValues(self, attrName, attrValues): ''' getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName are in the list of possible vaues #attrValues @param attrName - Name of attribute @param attrValues - List of possible values which will match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.getAttribute(attrName) in attrValues])
python
def getPeersWithAttrValues(self, attrName, attrValues): ''' getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName are in the list of possible vaues #attrValues @param attrName - Name of attribute @param attrValues - List of possible values which will match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.getAttribute(attrName) in attrValues])
[ "def", "getPeersWithAttrValues", "(", "self", ",", "attrName", ",", "attrValues", ")", ":", "peers", "=", "self", ".", "peers", "if", "peers", "is", "None", ":", "return", "None", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "peer", ".", "getAttribute", "(", "attrName", ")", "in", "attrValues", "]", ")" ]
getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName are in the list of possible vaues #attrValues @param attrName - Name of attribute @param attrValues - List of possible values which will match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched.
[ "getPeersWithAttrValues", "-", "Gets", "peers", "(", "elements", "on", "same", "level", ")", "whose", "attribute", "given", "by", "#attrName", "are", "in", "the", "list", "of", "possible", "vaues", "#attrValues" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1951-L1964
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeersByName
def getPeersByName(self, name): ''' getPeersByName - Gets peers (elements on same level) with a given name @param name - Name to match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.name == name])
python
def getPeersByName(self, name): ''' getPeersByName - Gets peers (elements on same level) with a given name @param name - Name to match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.name == name])
[ "def", "getPeersByName", "(", "self", ",", "name", ")", ":", "peers", "=", "self", ".", "peers", "if", "peers", "is", "None", ":", "return", "None", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "peer", ".", "name", "==", "name", "]", ")" ]
getPeersByName - Gets peers (elements on same level) with a given name @param name - Name to match @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched.
[ "getPeersByName", "-", "Gets", "peers", "(", "elements", "on", "same", "level", ")", "with", "a", "given", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1966-L1977
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.getPeersByClassName
def getPeersByClassName(self, className): ''' getPeersByClassName - Gets peers (elements on same level) with a given class name @param className - classname must contain this name @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.hasClass(className)])
python
def getPeersByClassName(self, className): ''' getPeersByClassName - Gets peers (elements on same level) with a given class name @param className - classname must contain this name @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if peer.hasClass(className)])
[ "def", "getPeersByClassName", "(", "self", ",", "className", ")", ":", "peers", "=", "self", ".", "peers", "if", "peers", "is", "None", ":", "return", "None", "return", "TagCollection", "(", "[", "peer", "for", "peer", "in", "peers", "if", "peer", ".", "hasClass", "(", "className", ")", "]", ")" ]
getPeersByClassName - Gets peers (elements on same level) with a given class name @param className - classname must contain this name @return - None if no parent element (error condition), otherwise a TagCollection of peers that matched.
[ "getPeersByClassName", "-", "Gets", "peers", "(", "elements", "on", "same", "level", ")", "with", "a", "given", "class", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L1979-L1990
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
AdvancedTag.isTagEqual
def isTagEqual(self, other): ''' isTagEqual - Compare if a tag contains the same tag name and attributes as another tag, i.e. if everything between < and > parts of this tag are the same. Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that) So for example: tag1 = document.getElementById('something') tag2 = copy.copy(tag1) tag1 == tag2 # This is False tag1.isTagEqual(tag2) # This is True @return bool - True if tags have the same name and attributes, otherwise False ''' # if type(other) != type(self): # return False # NOTE: Instead of type check, # just see if we can get the needed attributes in case subclassing try: if self.tagName != other.tagName: return False myAttributes = self._attributes otherAttributes = other._attributes attributeKeysSelf = list(myAttributes.keys()) attributeKeysOther = list(otherAttributes.keys()) except: return False # Check that we have all the same attribute names if set(attributeKeysSelf) != set(attributeKeysOther): return False for key in attributeKeysSelf: if myAttributes.get(key) != otherAttributes.get(key): return False return True
python
def isTagEqual(self, other): ''' isTagEqual - Compare if a tag contains the same tag name and attributes as another tag, i.e. if everything between < and > parts of this tag are the same. Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that) So for example: tag1 = document.getElementById('something') tag2 = copy.copy(tag1) tag1 == tag2 # This is False tag1.isTagEqual(tag2) # This is True @return bool - True if tags have the same name and attributes, otherwise False ''' # if type(other) != type(self): # return False # NOTE: Instead of type check, # just see if we can get the needed attributes in case subclassing try: if self.tagName != other.tagName: return False myAttributes = self._attributes otherAttributes = other._attributes attributeKeysSelf = list(myAttributes.keys()) attributeKeysOther = list(otherAttributes.keys()) except: return False # Check that we have all the same attribute names if set(attributeKeysSelf) != set(attributeKeysOther): return False for key in attributeKeysSelf: if myAttributes.get(key) != otherAttributes.get(key): return False return True
[ "def", "isTagEqual", "(", "self", ",", "other", ")", ":", "# if type(other) != type(self):", "# return False", "# NOTE: Instead of type check,", "# just see if we can get the needed attributes in case subclassing", "try", ":", "if", "self", ".", "tagName", "!=", "other", ".", "tagName", ":", "return", "False", "myAttributes", "=", "self", ".", "_attributes", "otherAttributes", "=", "other", ".", "_attributes", "attributeKeysSelf", "=", "list", "(", "myAttributes", ".", "keys", "(", ")", ")", "attributeKeysOther", "=", "list", "(", "otherAttributes", ".", "keys", "(", ")", ")", "except", ":", "return", "False", "# Check that we have all the same attribute names", "if", "set", "(", "attributeKeysSelf", ")", "!=", "set", "(", "attributeKeysOther", ")", ":", "return", "False", "for", "key", "in", "attributeKeysSelf", ":", "if", "myAttributes", ".", "get", "(", "key", ")", "!=", "otherAttributes", ".", "get", "(", "key", ")", ":", "return", "False", "return", "True" ]
isTagEqual - Compare if a tag contains the same tag name and attributes as another tag, i.e. if everything between < and > parts of this tag are the same. Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that) So for example: tag1 = document.getElementById('something') tag2 = copy.copy(tag1) tag1 == tag2 # This is False tag1.isTagEqual(tag2) # This is True @return bool - True if tags have the same name and attributes, otherwise False
[ "isTagEqual", "-", "Compare", "if", "a", "tag", "contains", "the", "same", "tag", "name", "and", "attributes", "as", "another", "tag" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2002-L2046
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.append
def append(self, tag): ''' append - Append an item to this tag collection @param tag - an AdvancedTag ''' list.append(self, tag) self.uids.add(tag.uid)
python
def append(self, tag): ''' append - Append an item to this tag collection @param tag - an AdvancedTag ''' list.append(self, tag) self.uids.add(tag.uid)
[ "def", "append", "(", "self", ",", "tag", ")", ":", "list", ".", "append", "(", "self", ",", "tag", ")", "self", ".", "uids", ".", "add", "(", "tag", ".", "uid", ")" ]
append - Append an item to this tag collection @param tag - an AdvancedTag
[ "append", "-", "Append", "an", "item", "to", "this", "tag", "collection" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2241-L2248
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.remove
def remove(self, toRemove): ''' remove - Remove an item from this tag collection @param toRemove - an AdvancedTag ''' list.remove(self, toRemove) self.uids.remove(toRemove.uid)
python
def remove(self, toRemove): ''' remove - Remove an item from this tag collection @param toRemove - an AdvancedTag ''' list.remove(self, toRemove) self.uids.remove(toRemove.uid)
[ "def", "remove", "(", "self", ",", "toRemove", ")", ":", "list", ".", "remove", "(", "self", ",", "toRemove", ")", "self", ".", "uids", ".", "remove", "(", "toRemove", ".", "uid", ")" ]
remove - Remove an item from this tag collection @param toRemove - an AdvancedTag
[ "remove", "-", "Remove", "an", "item", "from", "this", "tag", "collection" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2250-L2257
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.filterCollection
def filterCollection(self, filterFunc): ''' filterCollection - Filters only the immediate objects contained within this Collection against a function, not including any children @param filterFunc <function> - A function or lambda expression that returns True to have that element match @return TagCollection<AdvancedTag> ''' ret = TagCollection() if len(self) == 0: return ret for tag in self: if filterFunc(tag) is True: ret.append(tag) return ret
python
def filterCollection(self, filterFunc): ''' filterCollection - Filters only the immediate objects contained within this Collection against a function, not including any children @param filterFunc <function> - A function or lambda expression that returns True to have that element match @return TagCollection<AdvancedTag> ''' ret = TagCollection() if len(self) == 0: return ret for tag in self: if filterFunc(tag) is True: ret.append(tag) return ret
[ "def", "filterCollection", "(", "self", ",", "filterFunc", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "for", "tag", "in", "self", ":", "if", "filterFunc", "(", "tag", ")", "is", "True", ":", "ret", ".", "append", "(", "tag", ")", "return", "ret" ]
filterCollection - Filters only the immediate objects contained within this Collection against a function, not including any children @param filterFunc <function> - A function or lambda expression that returns True to have that element match @return TagCollection<AdvancedTag>
[ "filterCollection", "-", "Filters", "only", "the", "immediate", "objects", "contained", "within", "this", "Collection", "against", "a", "function", "not", "including", "any", "children" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2267-L2283
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsByTagName
def getElementsByTagName(self, tagName): ''' getElementsByTagName - Gets elements within this collection having a specific tag name @param tagName - String of tag name @return - TagCollection of unique elements within this collection with given tag name ''' ret = TagCollection() if len(self) == 0: return ret tagName = tagName.lower() _cmpFunc = lambda tag : bool(tag.tagName == tagName) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsByTagName(self, tagName): ''' getElementsByTagName - Gets elements within this collection having a specific tag name @param tagName - String of tag name @return - TagCollection of unique elements within this collection with given tag name ''' ret = TagCollection() if len(self) == 0: return ret tagName = tagName.lower() _cmpFunc = lambda tag : bool(tag.tagName == tagName) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsByTagName", "(", "self", ",", "tagName", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "tagName", "=", "tagName", ".", "lower", "(", ")", "_cmpFunc", "=", "lambda", "tag", ":", "bool", "(", "tag", ".", "tagName", "==", "tagName", ")", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsByTagName - Gets elements within this collection having a specific tag name @param tagName - String of tag name @return - TagCollection of unique elements within this collection with given tag name
[ "getElementsByTagName", "-", "Gets", "elements", "within", "this", "collection", "having", "a", "specific", "tag", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2285-L2303
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsByName
def getElementsByName(self, name): ''' getElementsByName - Get elements within this collection having a specific name @param name - String of "name" attribute @return - TagCollection of unique elements within this collection with given "name" ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : bool(tag.name == name) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsByName(self, name): ''' getElementsByName - Get elements within this collection having a specific name @param name - String of "name" attribute @return - TagCollection of unique elements within this collection with given "name" ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : bool(tag.name == name) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsByName", "(", "self", ",", "name", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "_cmpFunc", "=", "lambda", "tag", ":", "bool", "(", "tag", ".", "name", "==", "name", ")", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsByName - Get elements within this collection having a specific name @param name - String of "name" attribute @return - TagCollection of unique elements within this collection with given "name"
[ "getElementsByName", "-", "Get", "elements", "within", "this", "collection", "having", "a", "specific", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2306-L2321
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsByClassName
def getElementsByClassName(self, className): ''' getElementsByClassName - Get elements within this collection containing a specific class name @param className - A single class name @return - TagCollection of unique elements within this collection tagged with a specific class name ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : tag.hasClass(className) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsByClassName(self, className): ''' getElementsByClassName - Get elements within this collection containing a specific class name @param className - A single class name @return - TagCollection of unique elements within this collection tagged with a specific class name ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : tag.hasClass(className) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsByClassName", "(", "self", ",", "className", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "_cmpFunc", "=", "lambda", "tag", ":", "tag", ".", "hasClass", "(", "className", ")", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsByClassName - Get elements within this collection containing a specific class name @param className - A single class name @return - TagCollection of unique elements within this collection tagged with a specific class name
[ "getElementsByClassName", "-", "Get", "elements", "within", "this", "collection", "containing", "a", "specific", "class", "name" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2323-L2338
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementById
def getElementById(self, _id): ''' getElementById - Gets an element within this collection by id @param _id - string of "id" attribute @return - a single tag matching the id, or None if none found ''' for tag in self: if tag.id == _id: return tag for subtag in tag.children: tmp = subtag.getElementById(_id) if tmp is not None: return tmp return None
python
def getElementById(self, _id): ''' getElementById - Gets an element within this collection by id @param _id - string of "id" attribute @return - a single tag matching the id, or None if none found ''' for tag in self: if tag.id == _id: return tag for subtag in tag.children: tmp = subtag.getElementById(_id) if tmp is not None: return tmp return None
[ "def", "getElementById", "(", "self", ",", "_id", ")", ":", "for", "tag", "in", "self", ":", "if", "tag", ".", "id", "==", "_id", ":", "return", "tag", "for", "subtag", "in", "tag", ".", "children", ":", "tmp", "=", "subtag", ".", "getElementById", "(", "_id", ")", "if", "tmp", "is", "not", "None", ":", "return", "tmp", "return", "None" ]
getElementById - Gets an element within this collection by id @param _id - string of "id" attribute @return - a single tag matching the id, or None if none found
[ "getElementById", "-", "Gets", "an", "element", "within", "this", "collection", "by", "id" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2340-L2355
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsByAttr
def getElementsByAttr(self, attr, value): ''' getElementsByAttr - Get elements within this collection posessing a given attribute/value pair @param attr - Attribute name (lowercase) @param value - Matching value @return - TagCollection of all elements matching name/value ''' ret = TagCollection() if len(self) == 0: return ret attr = attr.lower() _cmpFunc = lambda tag : tag.getAttribute(attr) == value for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsByAttr(self, attr, value): ''' getElementsByAttr - Get elements within this collection posessing a given attribute/value pair @param attr - Attribute name (lowercase) @param value - Matching value @return - TagCollection of all elements matching name/value ''' ret = TagCollection() if len(self) == 0: return ret attr = attr.lower() _cmpFunc = lambda tag : tag.getAttribute(attr) == value for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsByAttr", "(", "self", ",", "attr", ",", "value", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "attr", "=", "attr", ".", "lower", "(", ")", "_cmpFunc", "=", "lambda", "tag", ":", "tag", ".", "getAttribute", "(", "attr", ")", "==", "value", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsByAttr - Get elements within this collection posessing a given attribute/value pair @param attr - Attribute name (lowercase) @param value - Matching value @return - TagCollection of all elements matching name/value
[ "getElementsByAttr", "-", "Get", "elements", "within", "this", "collection", "posessing", "a", "given", "attribute", "/", "value", "pair" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2357-L2375
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsWithAttrValues
def getElementsWithAttrValues(self, attr, values): ''' getElementsWithAttrValues - Get elements within this collection possessing an attribute name matching one of several values @param attr <lowercase str> - Attribute name (lowerase) @param values set<str> - Set of possible matching values @return - TagCollection of all elements matching criteria ''' ret = TagCollection() if len(self) == 0: return ret if type(values) != set: values = set(values) attr = attr.lower() _cmpFunc = lambda tag : tag.getAttribute(attr) in values for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsWithAttrValues(self, attr, values): ''' getElementsWithAttrValues - Get elements within this collection possessing an attribute name matching one of several values @param attr <lowercase str> - Attribute name (lowerase) @param values set<str> - Set of possible matching values @return - TagCollection of all elements matching criteria ''' ret = TagCollection() if len(self) == 0: return ret if type(values) != set: values = set(values) attr = attr.lower() _cmpFunc = lambda tag : tag.getAttribute(attr) in values for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsWithAttrValues", "(", "self", ",", "attr", ",", "values", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "if", "type", "(", "values", ")", "!=", "set", ":", "values", "=", "set", "(", "values", ")", "attr", "=", "attr", ".", "lower", "(", ")", "_cmpFunc", "=", "lambda", "tag", ":", "tag", ".", "getAttribute", "(", "attr", ")", "in", "values", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsWithAttrValues - Get elements within this collection possessing an attribute name matching one of several values @param attr <lowercase str> - Attribute name (lowerase) @param values set<str> - Set of possible matching values @return - TagCollection of all elements matching criteria
[ "getElementsWithAttrValues", "-", "Get", "elements", "within", "this", "collection", "possessing", "an", "attribute", "name", "matching", "one", "of", "several", "values" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2377-L2398
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getElementsCustomFilter
def getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Get elements within this collection that match a user-provided function. @param filterFunc <function> - A function that returns True if the element matches criteria @return - TagCollection of all elements that matched criteria ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : filterFunc(tag) is True for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
python
def getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Get elements within this collection that match a user-provided function. @param filterFunc <function> - A function that returns True if the element matches criteria @return - TagCollection of all elements that matched criteria ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : filterFunc(tag) is True for tag in self: TagCollection._subset(ret, _cmpFunc, tag) return ret
[ "def", "getElementsCustomFilter", "(", "self", ",", "filterFunc", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "_cmpFunc", "=", "lambda", "tag", ":", "filterFunc", "(", "tag", ")", "is", "True", "for", "tag", "in", "self", ":", "TagCollection", ".", "_subset", "(", "ret", ",", "_cmpFunc", ",", "tag", ")", "return", "ret" ]
getElementsCustomFilter - Get elements within this collection that match a user-provided function. @param filterFunc <function> - A function that returns True if the element matches criteria @return - TagCollection of all elements that matched criteria
[ "getElementsCustomFilter", "-", "Get", "elements", "within", "this", "collection", "that", "match", "a", "user", "-", "provided", "function", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2400-L2416
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getAllNodes
def getAllNodes(self): ''' getAllNodes - Gets all the nodes, and all their children for every node within this collection ''' ret = TagCollection() for tag in self: ret.append(tag) ret += tag.getAllChildNodes() return ret
python
def getAllNodes(self): ''' getAllNodes - Gets all the nodes, and all their children for every node within this collection ''' ret = TagCollection() for tag in self: ret.append(tag) ret += tag.getAllChildNodes() return ret
[ "def", "getAllNodes", "(", "self", ")", ":", "ret", "=", "TagCollection", "(", ")", "for", "tag", "in", "self", ":", "ret", ".", "append", "(", "tag", ")", "ret", "+=", "tag", ".", "getAllChildNodes", "(", ")", "return", "ret" ]
getAllNodes - Gets all the nodes, and all their children for every node within this collection
[ "getAllNodes", "-", "Gets", "all", "the", "nodes", "and", "all", "their", "children", "for", "every", "node", "within", "this", "collection" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2418-L2428
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.getAllNodeUids
def getAllNodeUids(self): ''' getAllNodeUids - Gets all the internal uids of all nodes, their children, and all their children so on.. @return set<uuid.UUID> ''' ret = set() for child in self: ret.update(child.getAllNodeUids()) return ret
python
def getAllNodeUids(self): ''' getAllNodeUids - Gets all the internal uids of all nodes, their children, and all their children so on.. @return set<uuid.UUID> ''' ret = set() for child in self: ret.update(child.getAllNodeUids()) return ret
[ "def", "getAllNodeUids", "(", "self", ")", ":", "ret", "=", "set", "(", ")", "for", "child", "in", "self", ":", "ret", ".", "update", "(", "child", ".", "getAllNodeUids", "(", ")", ")", "return", "ret" ]
getAllNodeUids - Gets all the internal uids of all nodes, their children, and all their children so on.. @return set<uuid.UUID>
[ "getAllNodeUids", "-", "Gets", "all", "the", "internal", "uids", "of", "all", "nodes", "their", "children", "and", "all", "their", "children", "so", "on", ".." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2430-L2441
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.contains
def contains(self, em): ''' contains - Check if #em occurs within any of the elements within this list, as themselves or as a child, any number of levels down. To check if JUST an element is contained within this list directly, use the "in" operator. @param em <AdvancedTag> - Element of interest @return <bool> - True if contained, otherwise False ''' for node in self: if node.contains(em): return True return False
python
def contains(self, em): ''' contains - Check if #em occurs within any of the elements within this list, as themselves or as a child, any number of levels down. To check if JUST an element is contained within this list directly, use the "in" operator. @param em <AdvancedTag> - Element of interest @return <bool> - True if contained, otherwise False ''' for node in self: if node.contains(em): return True return False
[ "def", "contains", "(", "self", ",", "em", ")", ":", "for", "node", "in", "self", ":", "if", "node", ".", "contains", "(", "em", ")", ":", "return", "True", "return", "False" ]
contains - Check if #em occurs within any of the elements within this list, as themselves or as a child, any number of levels down. To check if JUST an element is contained within this list directly, use the "in" operator. @param em <AdvancedTag> - Element of interest @return <bool> - True if contained, otherwise False
[ "contains", "-", "Check", "if", "#em", "occurs", "within", "any", "of", "the", "elements", "within", "this", "list", "as", "themselves", "or", "as", "a", "child", "any", "number", "of", "levels", "down", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2443-L2459
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.containsUid
def containsUid(self, uid): ''' containsUid - Check if #uid is the uid (unique internal identifier) of any of the elements within this list, as themselves or as a child, any number of levels down. @param uid <uuid.UUID> - uuid of interest @return <bool> - True if contained, otherwise False ''' for node in self: if node.containsUid(uid): return True return False
python
def containsUid(self, uid): ''' containsUid - Check if #uid is the uid (unique internal identifier) of any of the elements within this list, as themselves or as a child, any number of levels down. @param uid <uuid.UUID> - uuid of interest @return <bool> - True if contained, otherwise False ''' for node in self: if node.containsUid(uid): return True return False
[ "def", "containsUid", "(", "self", ",", "uid", ")", ":", "for", "node", "in", "self", ":", "if", "node", ".", "containsUid", "(", "uid", ")", ":", "return", "True", "return", "False" ]
containsUid - Check if #uid is the uid (unique internal identifier) of any of the elements within this list, as themselves or as a child, any number of levels down. @param uid <uuid.UUID> - uuid of interest @return <bool> - True if contained, otherwise False
[ "containsUid", "-", "Check", "if", "#uid", "is", "the", "uid", "(", "unique", "internal", "identifier", ")", "of", "any", "of", "the", "elements", "within", "this", "list", "as", "themselves", "or", "as", "a", "child", "any", "number", "of", "levels", "down", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2461-L2475
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.filterAll
def filterAll(self, **kwargs): ''' filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterAnd(**kwargs)
python
def filterAll(self, **kwargs): ''' filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterAnd(**kwargs)
[ "def", "filterAll", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "canFilterTags", "is", "False", ":", "raise", "NotImplementedError", "(", "'filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust \"find\" method, or the getElement* methods.'", ")", "allNodes", "=", "self", ".", "getAllNodes", "(", ")", "filterableNodes", "=", "FilterableTagCollection", "(", "allNodes", ")", "return", "filterableNodes", ".", "filterAnd", "(", "*", "*", "kwargs", ")" ]
filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag>
[ "filterAll", "aka", "filterAllAnd", "-", "Perform", "a", "filter", "operation", "on", "ALL", "nodes", "in", "this", "collection", "and", "all", "their", "children", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2478-L2503
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Tags.py
TagCollection.filterAllOr
def filterAllOr(self, **kwargs): ''' filterAllOr - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ANY the filter criteria. for ALL, use the *And methods For just the nodes in this collection, use "filterOr" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterOr(**kwargs)
python
def filterAllOr(self, **kwargs): ''' filterAllOr - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ANY the filter criteria. for ALL, use the *And methods For just the nodes in this collection, use "filterOr" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterOr(**kwargs)
[ "def", "filterAllOr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "canFilterTags", "is", "False", ":", "raise", "NotImplementedError", "(", "'filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust \"find\" method, or the getElement* methods.'", ")", "allNodes", "=", "self", ".", "getAllNodes", "(", ")", "filterableNodes", "=", "FilterableTagCollection", "(", "allNodes", ")", "return", "filterableNodes", ".", "filterOr", "(", "*", "*", "kwargs", ")" ]
filterAllOr - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ANY the filter criteria. for ALL, use the *And methods For just the nodes in this collection, use "filterOr" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag>
[ "filterAllOr", "-", "Perform", "a", "filter", "operation", "on", "ALL", "nodes", "in", "this", "collection", "and", "all", "their", "children", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Tags.py#L2507-L2533
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Formatter.py
AdvancedHTMLFormatter.handle_starttag
def handle_starttag(self, tagName, attributeList, isSelfClosing=False): ''' handle_starttag - Internal for parsing ''' tagName = tagName.lower() inTag = self._inTag if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS: isSelfClosing = True newTag = AdvancedTag(tagName, attributeList, isSelfClosing) if self.root is None: self.root = newTag elif len(inTag) > 0: inTag[-1].appendChild(newTag) else: raise MultipleRootNodeException() if self.inPreformatted is 0: newTag._indent = self._getIndent() if tagName in PREFORMATTED_TAGS: self.inPreformatted += 1 if isSelfClosing is False: inTag.append(newTag) if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel += 1
python
def handle_starttag(self, tagName, attributeList, isSelfClosing=False): ''' handle_starttag - Internal for parsing ''' tagName = tagName.lower() inTag = self._inTag if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS: isSelfClosing = True newTag = AdvancedTag(tagName, attributeList, isSelfClosing) if self.root is None: self.root = newTag elif len(inTag) > 0: inTag[-1].appendChild(newTag) else: raise MultipleRootNodeException() if self.inPreformatted is 0: newTag._indent = self._getIndent() if tagName in PREFORMATTED_TAGS: self.inPreformatted += 1 if isSelfClosing is False: inTag.append(newTag) if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel += 1
[ "def", "handle_starttag", "(", "self", ",", "tagName", ",", "attributeList", ",", "isSelfClosing", "=", "False", ")", ":", "tagName", "=", "tagName", ".", "lower", "(", ")", "inTag", "=", "self", ".", "_inTag", "if", "isSelfClosing", "is", "False", "and", "tagName", "in", "IMPLICIT_SELF_CLOSING_TAGS", ":", "isSelfClosing", "=", "True", "newTag", "=", "AdvancedTag", "(", "tagName", ",", "attributeList", ",", "isSelfClosing", ")", "if", "self", ".", "root", "is", "None", ":", "self", ".", "root", "=", "newTag", "elif", "len", "(", "inTag", ")", ">", "0", ":", "inTag", "[", "-", "1", "]", ".", "appendChild", "(", "newTag", ")", "else", ":", "raise", "MultipleRootNodeException", "(", ")", "if", "self", ".", "inPreformatted", "is", "0", ":", "newTag", ".", "_indent", "=", "self", ".", "_getIndent", "(", ")", "if", "tagName", "in", "PREFORMATTED_TAGS", ":", "self", ".", "inPreformatted", "+=", "1", "if", "isSelfClosing", "is", "False", ":", "inTag", ".", "append", "(", "newTag", ")", "if", "tagName", "!=", "INVISIBLE_ROOT_TAG", ":", "self", ".", "currentIndentLevel", "+=", "1" ]
handle_starttag - Internal for parsing
[ "handle_starttag", "-", "Internal", "for", "parsing" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Formatter.py#L155-L182
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Formatter.py
AdvancedHTMLFormatter.handle_endtag
def handle_endtag(self, tagName): ''' handle_endtag - Internal for parsing ''' inTag = self._inTag try: # Handle closing tags which should have been closed but weren't foundIt = False for i in range(len(inTag)): if inTag[i].tagName == tagName: foundIt = True break if not foundIt: sys.stderr.write('WARNING: found close tag with no matching start.\n') return while inTag[-1].tagName != tagName: oldTag = inTag.pop() if oldTag.tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 self.currentIndentLevel -= 1 inTag.pop() if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel -= 1 if tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 except: pass
python
def handle_endtag(self, tagName): ''' handle_endtag - Internal for parsing ''' inTag = self._inTag try: # Handle closing tags which should have been closed but weren't foundIt = False for i in range(len(inTag)): if inTag[i].tagName == tagName: foundIt = True break if not foundIt: sys.stderr.write('WARNING: found close tag with no matching start.\n') return while inTag[-1].tagName != tagName: oldTag = inTag.pop() if oldTag.tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 self.currentIndentLevel -= 1 inTag.pop() if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel -= 1 if tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 except: pass
[ "def", "handle_endtag", "(", "self", ",", "tagName", ")", ":", "inTag", "=", "self", ".", "_inTag", "try", ":", "# Handle closing tags which should have been closed but weren't", "foundIt", "=", "False", "for", "i", "in", "range", "(", "len", "(", "inTag", ")", ")", ":", "if", "inTag", "[", "i", "]", ".", "tagName", "==", "tagName", ":", "foundIt", "=", "True", "break", "if", "not", "foundIt", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING: found close tag with no matching start.\\n'", ")", "return", "while", "inTag", "[", "-", "1", "]", ".", "tagName", "!=", "tagName", ":", "oldTag", "=", "inTag", ".", "pop", "(", ")", "if", "oldTag", ".", "tagName", "in", "PREFORMATTED_TAGS", ":", "self", ".", "inPreformatted", "-=", "1", "self", ".", "currentIndentLevel", "-=", "1", "inTag", ".", "pop", "(", ")", "if", "tagName", "!=", "INVISIBLE_ROOT_TAG", ":", "self", ".", "currentIndentLevel", "-=", "1", "if", "tagName", "in", "PREFORMATTED_TAGS", ":", "self", ".", "inPreformatted", "-=", "1", "except", ":", "pass" ]
handle_endtag - Internal for parsing
[ "handle_endtag", "-", "Internal", "for", "parsing" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Formatter.py#L191-L221
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Formatter.py
AdvancedHTMLFormatter.handle_data
def handle_data(self, data): ''' handle_data - Internal for parsing ''' if data: inTag = self._inTag if len(inTag) > 0: if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS: data = data.replace('\t', ' ').strip('\r\n') if data.startswith(' '): data = ' ' + data.lstrip() if data.endswith(' '): data = data.rstrip() + ' ' inTag[-1].appendText(data) elif data.strip(): # Must be text prior to or after root node raise MultipleRootNodeException()
python
def handle_data(self, data): ''' handle_data - Internal for parsing ''' if data: inTag = self._inTag if len(inTag) > 0: if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS: data = data.replace('\t', ' ').strip('\r\n') if data.startswith(' '): data = ' ' + data.lstrip() if data.endswith(' '): data = data.rstrip() + ' ' inTag[-1].appendText(data) elif data.strip(): # Must be text prior to or after root node raise MultipleRootNodeException()
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "data", ":", "inTag", "=", "self", ".", "_inTag", "if", "len", "(", "inTag", ")", ">", "0", ":", "if", "inTag", "[", "-", "1", "]", ".", "tagName", "not", "in", "PRESERVE_CONTENTS_TAGS", ":", "data", "=", "data", ".", "replace", "(", "'\\t'", ",", "' '", ")", ".", "strip", "(", "'\\r\\n'", ")", "if", "data", ".", "startswith", "(", "' '", ")", ":", "data", "=", "' '", "+", "data", ".", "lstrip", "(", ")", "if", "data", ".", "endswith", "(", "' '", ")", ":", "data", "=", "data", ".", "rstrip", "(", ")", "+", "' '", "inTag", "[", "-", "1", "]", ".", "appendText", "(", "data", ")", "elif", "data", ".", "strip", "(", ")", ":", "# Must be text prior to or after root node", "raise", "MultipleRootNodeException", "(", ")" ]
handle_data - Internal for parsing
[ "handle_data", "-", "Internal", "for", "parsing" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Formatter.py#L223-L239
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Formatter.py
AdvancedTagSlim.getStartTag
def getStartTag(self, *args, **kwargs): ''' getStartTag - Override the end-spacing rules @see AdvancedTag.getStartTag ''' ret = AdvancedTag.getStartTag(self, *args, **kwargs) if ret.endswith(' >'): ret = ret[:-2] + '>' elif object.__getattribute__(self, 'slimSelfClosing') and ret.endswith(' />'): ret = ret[:-3] + '/>' return ret
python
def getStartTag(self, *args, **kwargs): ''' getStartTag - Override the end-spacing rules @see AdvancedTag.getStartTag ''' ret = AdvancedTag.getStartTag(self, *args, **kwargs) if ret.endswith(' >'): ret = ret[:-2] + '>' elif object.__getattribute__(self, 'slimSelfClosing') and ret.endswith(' />'): ret = ret[:-3] + '/>' return ret
[ "def", "getStartTag", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "AdvancedTag", ".", "getStartTag", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "ret", ".", "endswith", "(", "' >'", ")", ":", "ret", "=", "ret", "[", ":", "-", "2", "]", "+", "'>'", "elif", "object", ".", "__getattribute__", "(", "self", ",", "'slimSelfClosing'", ")", "and", "ret", ".", "endswith", "(", "' />'", ")", ":", "ret", "=", "ret", "[", ":", "-", "3", "]", "+", "'/>'", "return", "ret" ]
getStartTag - Override the end-spacing rules @see AdvancedTag.getStartTag
[ "getStartTag", "-", "Override", "the", "end", "-", "spacing", "rules" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Formatter.py#L368-L382
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/utils.py
stripIEConditionals
def stripIEConditionals(contents, addHtmlIfMissing=True): ''' stripIEConditionals - Strips Internet Explorer conditional statements. @param contents <str> - Contents String @param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing. ''' allMatches = IE_CONDITIONAL_PATTERN.findall(contents) if not allMatches: return contents for match in allMatches: contents = contents.replace(match, '') if END_HTML.match(contents) and not START_HTML.match(contents): contents = addStartTag(contents, '<html>') return contents
python
def stripIEConditionals(contents, addHtmlIfMissing=True): ''' stripIEConditionals - Strips Internet Explorer conditional statements. @param contents <str> - Contents String @param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing. ''' allMatches = IE_CONDITIONAL_PATTERN.findall(contents) if not allMatches: return contents for match in allMatches: contents = contents.replace(match, '') if END_HTML.match(contents) and not START_HTML.match(contents): contents = addStartTag(contents, '<html>') return contents
[ "def", "stripIEConditionals", "(", "contents", ",", "addHtmlIfMissing", "=", "True", ")", ":", "allMatches", "=", "IE_CONDITIONAL_PATTERN", ".", "findall", "(", "contents", ")", "if", "not", "allMatches", ":", "return", "contents", "for", "match", "in", "allMatches", ":", "contents", "=", "contents", ".", "replace", "(", "match", ",", "''", ")", "if", "END_HTML", ".", "match", "(", "contents", ")", "and", "not", "START_HTML", ".", "match", "(", "contents", ")", ":", "contents", "=", "addStartTag", "(", "contents", ",", "'<html>'", ")", "return", "contents" ]
stripIEConditionals - Strips Internet Explorer conditional statements. @param contents <str> - Contents String @param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing.
[ "stripIEConditionals", "-", "Strips", "Internet", "Explorer", "conditional", "statements", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/utils.py#L24-L41
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/utils.py
addStartTag
def addStartTag(contents, startTag): ''' addStartTag - Safetly add a start tag to the document, taking into account the DOCTYPE @param contents <str> - Contents @param startTag <str> - Fully formed tag, i.e. <html> ''' matchObj = DOCTYPE_MATCH.match(contents) if matchObj: idx = matchObj.end() else: idx = 0 return "%s\n%s\n%s" %(contents[:idx], startTag, contents[idx:])
python
def addStartTag(contents, startTag): ''' addStartTag - Safetly add a start tag to the document, taking into account the DOCTYPE @param contents <str> - Contents @param startTag <str> - Fully formed tag, i.e. <html> ''' matchObj = DOCTYPE_MATCH.match(contents) if matchObj: idx = matchObj.end() else: idx = 0 return "%s\n%s\n%s" %(contents[:idx], startTag, contents[idx:])
[ "def", "addStartTag", "(", "contents", ",", "startTag", ")", ":", "matchObj", "=", "DOCTYPE_MATCH", ".", "match", "(", "contents", ")", "if", "matchObj", ":", "idx", "=", "matchObj", ".", "end", "(", ")", "else", ":", "idx", "=", "0", "return", "\"%s\\n%s\\n%s\"", "%", "(", "contents", "[", ":", "idx", "]", ",", "startTag", ",", "contents", "[", "idx", ":", "]", ")" ]
addStartTag - Safetly add a start tag to the document, taking into account the DOCTYPE @param contents <str> - Contents @param startTag <str> - Fully formed tag, i.e. <html>
[ "addStartTag", "-", "Safetly", "add", "a", "start", "tag", "to", "the", "document", "taking", "into", "account", "the", "DOCTYPE" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/utils.py#L44-L57
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Validator.py
ValidatingAdvancedHTMLParser.handle_endtag
def handle_endtag(self, tagName): ''' Internal for parsing ''' inTag = self._inTag if len(inTag) == 0: # Attempted to close, but no open tags raise InvalidCloseException(tagName, []) foundIt = False i = len(inTag) - 1 while i >= 0: if inTag[i].tagName == tagName: foundIt = True break i -= 1 if not foundIt: # Attempted to close, but did not match anything raise InvalidCloseException(tagName, inTag) if inTag[-1].tagName != tagName: raise MissedCloseException(tagName, [x for x in inTag[-1 * (i+1): ] ] ) inTag.pop()
python
def handle_endtag(self, tagName): ''' Internal for parsing ''' inTag = self._inTag if len(inTag) == 0: # Attempted to close, but no open tags raise InvalidCloseException(tagName, []) foundIt = False i = len(inTag) - 1 while i >= 0: if inTag[i].tagName == tagName: foundIt = True break i -= 1 if not foundIt: # Attempted to close, but did not match anything raise InvalidCloseException(tagName, inTag) if inTag[-1].tagName != tagName: raise MissedCloseException(tagName, [x for x in inTag[-1 * (i+1): ] ] ) inTag.pop()
[ "def", "handle_endtag", "(", "self", ",", "tagName", ")", ":", "inTag", "=", "self", ".", "_inTag", "if", "len", "(", "inTag", ")", "==", "0", ":", "# Attempted to close, but no open tags", "raise", "InvalidCloseException", "(", "tagName", ",", "[", "]", ")", "foundIt", "=", "False", "i", "=", "len", "(", "inTag", ")", "-", "1", "while", "i", ">=", "0", ":", "if", "inTag", "[", "i", "]", ".", "tagName", "==", "tagName", ":", "foundIt", "=", "True", "break", "i", "-=", "1", "if", "not", "foundIt", ":", "# Attempted to close, but did not match anything", "raise", "InvalidCloseException", "(", "tagName", ",", "inTag", ")", "if", "inTag", "[", "-", "1", "]", ".", "tagName", "!=", "tagName", ":", "raise", "MissedCloseException", "(", "tagName", ",", "[", "x", "for", "x", "in", "inTag", "[", "-", "1", "*", "(", "i", "+", "1", ")", ":", "]", "]", ")", "inTag", ".", "pop", "(", ")" ]
Internal for parsing
[ "Internal", "for", "parsing" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Validator.py#L20-L44
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
convertToBooleanString
def convertToBooleanString(val=None): ''' convertToBooleanString - Converts a value to either a string of "true" or "false" @param val <int/str/bool> - Value ''' if hasattr(val, 'lower'): val = val.lower() # Technically, if you set one of these attributes (like "spellcheck") to a string of 'false', # it gets set to true. But we will retain "false" here. if val in ('false', '0'): return 'false' else: return 'true' try: if bool(val): return "true" except: pass return "false"
python
def convertToBooleanString(val=None): ''' convertToBooleanString - Converts a value to either a string of "true" or "false" @param val <int/str/bool> - Value ''' if hasattr(val, 'lower'): val = val.lower() # Technically, if you set one of these attributes (like "spellcheck") to a string of 'false', # it gets set to true. But we will retain "false" here. if val in ('false', '0'): return 'false' else: return 'true' try: if bool(val): return "true" except: pass return "false"
[ "def", "convertToBooleanString", "(", "val", "=", "None", ")", ":", "if", "hasattr", "(", "val", ",", "'lower'", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "# Technically, if you set one of these attributes (like \"spellcheck\") to a string of 'false',", "# it gets set to true. But we will retain \"false\" here.", "if", "val", "in", "(", "'false'", ",", "'0'", ")", ":", "return", "'false'", "else", ":", "return", "'true'", "try", ":", "if", "bool", "(", "val", ")", ":", "return", "\"true\"", "except", ":", "pass", "return", "\"false\"" ]
convertToBooleanString - Converts a value to either a string of "true" or "false" @param val <int/str/bool> - Value
[ "convertToBooleanString", "-", "Converts", "a", "value", "to", "either", "a", "string", "of", "true", "or", "false" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L38-L60
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
convertBooleanStringToBoolean
def convertBooleanStringToBoolean(val=None): ''' convertBooleanStringToBoolean - Convert from a boolean attribute (string "true" / "false" ) into a booelan ''' if not val: return False if hasattr(val, 'lower'): val = val.lower() if val == "false": return False return True
python
def convertBooleanStringToBoolean(val=None): ''' convertBooleanStringToBoolean - Convert from a boolean attribute (string "true" / "false" ) into a booelan ''' if not val: return False if hasattr(val, 'lower'): val = val.lower() if val == "false": return False return True
[ "def", "convertBooleanStringToBoolean", "(", "val", "=", "None", ")", ":", "if", "not", "val", ":", "return", "False", "if", "hasattr", "(", "val", ",", "'lower'", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "==", "\"false\"", ":", "return", "False", "return", "True" ]
convertBooleanStringToBoolean - Convert from a boolean attribute (string "true" / "false" ) into a booelan
[ "convertBooleanStringToBoolean", "-", "Convert", "from", "a", "boolean", "attribute", "(", "string", "true", "/", "false", ")", "into", "a", "booelan" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L62-L74
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
convertToPositiveInt
def convertToPositiveInt(val=None, invalidDefault=0): ''' convertToPositiveInt - Convert to a positive integer, and if invalid use a given value ''' if val is None: return invalidDefault try: val = int(val) except: return invalidDefault if val < 0: return invalidDefault return val
python
def convertToPositiveInt(val=None, invalidDefault=0): ''' convertToPositiveInt - Convert to a positive integer, and if invalid use a given value ''' if val is None: return invalidDefault try: val = int(val) except: return invalidDefault if val < 0: return invalidDefault return val
[ "def", "convertToPositiveInt", "(", "val", "=", "None", ",", "invalidDefault", "=", "0", ")", ":", "if", "val", "is", "None", ":", "return", "invalidDefault", "try", ":", "val", "=", "int", "(", "val", ")", "except", ":", "return", "invalidDefault", "if", "val", "<", "0", ":", "return", "invalidDefault", "return", "val" ]
convertToPositiveInt - Convert to a positive integer, and if invalid use a given value
[ "convertToPositiveInt", "-", "Convert", "to", "a", "positive", "integer", "and", "if", "invalid", "use", "a", "given", "value" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L77-L92
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
_handleInvalid
def _handleInvalid(invalidDefault): ''' _handleInvalid - Common code for raising / returning an invalid value @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value ''' # If not # If an instantiated Exception, raise that exception try: isInstantiatedException = bool( issubclass(invalidDefault.__class__, Exception) ) except: isInstantiatedException = False if isInstantiatedException: raise invalidDefault else: try: isExceptionType = bool( issubclass( invalidDefault, Exception) ) except TypeError: isExceptionType = False # If an Exception type, instantiate and raise if isExceptionType: raise invalidDefault() else: # Otherwise, just return invalidDefault itself return invalidDefault
python
def _handleInvalid(invalidDefault): ''' _handleInvalid - Common code for raising / returning an invalid value @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value ''' # If not # If an instantiated Exception, raise that exception try: isInstantiatedException = bool( issubclass(invalidDefault.__class__, Exception) ) except: isInstantiatedException = False if isInstantiatedException: raise invalidDefault else: try: isExceptionType = bool( issubclass( invalidDefault, Exception) ) except TypeError: isExceptionType = False # If an Exception type, instantiate and raise if isExceptionType: raise invalidDefault() else: # Otherwise, just return invalidDefault itself return invalidDefault
[ "def", "_handleInvalid", "(", "invalidDefault", ")", ":", "# If not", "# If an instantiated Exception, raise that exception", "try", ":", "isInstantiatedException", "=", "bool", "(", "issubclass", "(", "invalidDefault", ".", "__class__", ",", "Exception", ")", ")", "except", ":", "isInstantiatedException", "=", "False", "if", "isInstantiatedException", ":", "raise", "invalidDefault", "else", ":", "try", ":", "isExceptionType", "=", "bool", "(", "issubclass", "(", "invalidDefault", ",", "Exception", ")", ")", "except", "TypeError", ":", "isExceptionType", "=", "False", "# If an Exception type, instantiate and raise", "if", "isExceptionType", ":", "raise", "invalidDefault", "(", ")", "else", ":", "# Otherwise, just return invalidDefault itself", "return", "invalidDefault" ]
_handleInvalid - Common code for raising / returning an invalid value @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value
[ "_handleInvalid", "-", "Common", "code", "for", "raising", "/", "returning", "an", "invalid", "value" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L94-L127
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
convertPossibleValues
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''): ''' convertPossibleValues - Convert input value to one of several possible values, with a default for invalid entries @param val <None/str> - The input value @param possibleValues list<str> - A list of possible values @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None) ''' from .utils import tostr # If null, retain null if val is None: if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Convert to a string val = tostr(val).lower() # If empty string, same as null if val == '': if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Check if this is a valid value if val not in possibleValues: return _handleInvalid(invalidDefault) return val
python
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''): ''' convertPossibleValues - Convert input value to one of several possible values, with a default for invalid entries @param val <None/str> - The input value @param possibleValues list<str> - A list of possible values @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None) ''' from .utils import tostr # If null, retain null if val is None: if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Convert to a string val = tostr(val).lower() # If empty string, same as null if val == '': if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Check if this is a valid value if val not in possibleValues: return _handleInvalid(invalidDefault) return val
[ "def", "convertPossibleValues", "(", "val", ",", "possibleValues", ",", "invalidDefault", ",", "emptyValue", "=", "''", ")", ":", "from", ".", "utils", "import", "tostr", "# If null, retain null", "if", "val", "is", "None", ":", "if", "emptyValue", "is", "EMPTY_IS_INVALID", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "return", "emptyValue", "# Convert to a string", "val", "=", "tostr", "(", "val", ")", ".", "lower", "(", ")", "# If empty string, same as null", "if", "val", "==", "''", ":", "if", "emptyValue", "is", "EMPTY_IS_INVALID", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "return", "emptyValue", "# Check if this is a valid value", "if", "val", "not", "in", "possibleValues", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "return", "val" ]
convertPossibleValues - Convert input value to one of several possible values, with a default for invalid entries @param val <None/str> - The input value @param possibleValues list<str> - A list of possible values @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None)
[ "convertPossibleValues", "-", "Convert", "input", "value", "to", "one", "of", "several", "possible", "values", "with", "a", "default", "for", "invalid", "entries" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L130-L174
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/conversions.py
convertToIntRange
def convertToIntRange(val, minValue, maxValue, invalidDefault, emptyValue=''): ''' converToIntRange - Convert input value to an integer within a certain range @param val <None/str/int/float> - The input value @param minValue <None/int> - The minimum value (inclusive), or None if no minimum @param maxValue <None/int> - The maximum value (inclusive), or None if no maximum @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None) ''' from .utils import tostr # If null, retain null if val is None or val == '': if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue try: val = int(val) except ValueError: return _handleInvalid(invalidDefault) if minValue is not None and val < minValue: return _handleInvalid(invalidDefault) if maxValue is not None and val > maxValue: return _handleInvalid(invalidDefault) return val
python
def convertToIntRange(val, minValue, maxValue, invalidDefault, emptyValue=''): ''' converToIntRange - Convert input value to an integer within a certain range @param val <None/str/int/float> - The input value @param minValue <None/int> - The minimum value (inclusive), or None if no minimum @param maxValue <None/int> - The maximum value (inclusive), or None if no maximum @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None) ''' from .utils import tostr # If null, retain null if val is None or val == '': if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue try: val = int(val) except ValueError: return _handleInvalid(invalidDefault) if minValue is not None and val < minValue: return _handleInvalid(invalidDefault) if maxValue is not None and val > maxValue: return _handleInvalid(invalidDefault) return val
[ "def", "convertToIntRange", "(", "val", ",", "minValue", ",", "maxValue", ",", "invalidDefault", ",", "emptyValue", "=", "''", ")", ":", "from", ".", "utils", "import", "tostr", "# If null, retain null", "if", "val", "is", "None", "or", "val", "==", "''", ":", "if", "emptyValue", "is", "EMPTY_IS_INVALID", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "return", "emptyValue", "try", ":", "val", "=", "int", "(", "val", ")", "except", "ValueError", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "if", "minValue", "is", "not", "None", "and", "val", "<", "minValue", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "if", "maxValue", "is", "not", "None", "and", "val", ">", "maxValue", ":", "return", "_handleInvalid", "(", "invalidDefault", ")", "return", "val" ]
converToIntRange - Convert input value to an integer within a certain range @param val <None/str/int/float> - The input value @param minValue <None/int> - The minimum value (inclusive), or None if no minimum @param maxValue <None/int> - The maximum value (inclusive), or None if no maximum @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None)
[ "converToIntRange", "-", "Convert", "input", "value", "to", "an", "integer", "within", "a", "certain", "range", "@param", "val", "<None", "/", "str", "/", "int", "/", "float", ">", "-", "The", "input", "value" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/conversions.py#L177-L218
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
SpecialAttributesDict._setTag
def _setTag(self, tag): ''' _setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict. If bool(#tag) is True, will set the weakref to that tag. Otherwise, will clear the reference @param tag <AdvancedTag/None> - Either the AdvancedTag to associate, or None to clear current association ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = None
python
def _setTag(self, tag): ''' _setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict. If bool(#tag) is True, will set the weakref to that tag. Otherwise, will clear the reference @param tag <AdvancedTag/None> - Either the AdvancedTag to associate, or None to clear current association ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = None
[ "def", "_setTag", "(", "self", ",", "tag", ")", ":", "if", "tag", ":", "self", ".", "_tagRef", "=", "weakref", ".", "ref", "(", "tag", ")", "else", ":", "self", ".", "_tagRef", "=", "None" ]
_setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict. If bool(#tag) is True, will set the weakref to that tag. Otherwise, will clear the reference @param tag <AdvancedTag/None> - Either the AdvancedTag to associate, or None to clear current association
[ "_setTag", "-", "INTERNAL", "METHOD", ".", "Associated", "a", "given", "AdvancedTag", "to", "this", "attributes", "dict", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L46-L59
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
SpecialAttributesDict._handleClassAttr
def _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames) > 0: dict.__setitem__(self, "class", self.tag.className) else: try: dict.__delitem__(self, "class") except: pass styleAttr = self.tag.style if styleAttr.isEmpty() is False: dict.__setitem__(self, "style", styleAttr) else: try: dict.__delitem__(self, "style") except: pass
python
def _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames) > 0: dict.__setitem__(self, "class", self.tag.className) else: try: dict.__delitem__(self, "class") except: pass styleAttr = self.tag.style if styleAttr.isEmpty() is False: dict.__setitem__(self, "style", styleAttr) else: try: dict.__delitem__(self, "style") except: pass
[ "def", "_handleClassAttr", "(", "self", ")", ":", "if", "len", "(", "self", ".", "tag", ".", "_classNames", ")", ">", "0", ":", "dict", ".", "__setitem__", "(", "self", ",", "\"class\"", ",", "self", ".", "tag", ".", "className", ")", "else", ":", "try", ":", "dict", ".", "__delitem__", "(", "self", ",", "\"class\"", ")", "except", ":", "pass", "styleAttr", "=", "self", ".", "tag", ".", "style", "if", "styleAttr", ".", "isEmpty", "(", ")", "is", "False", ":", "dict", ".", "__setitem__", "(", "self", ",", "\"style\"", ",", "styleAttr", ")", "else", ":", "try", ":", "dict", ".", "__delitem__", "(", "self", ",", "\"style\"", ")", "except", ":", "pass" ]
_handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack.
[ "_handleClassAttr", "-", "Hack", "to", "ensure", "class", "and", "style", "show", "up", "in", "attributes", "when", "classes", "are", "set", "and", "doesn", "t", "when", "no", "classes", "are", "present", "on", "associated", "tag", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L151-L173
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
SpecialAttributesDict.get
def get(self, key, default=None): ''' get - Gets an attribute by key with the chance to provide a default value @param key <str> - The key to query @param default <Anything> Default None - The value to return if key is not found @return - The value of attribute at #key, or #default if not present. ''' key = key.lower() if key == 'class': return self.tag.className if key in ('style', 'class') or key in self.keys(): return self[key] return default
python
def get(self, key, default=None): ''' get - Gets an attribute by key with the chance to provide a default value @param key <str> - The key to query @param default <Anything> Default None - The value to return if key is not found @return - The value of attribute at #key, or #default if not present. ''' key = key.lower() if key == 'class': return self.tag.className if key in ('style', 'class') or key in self.keys(): return self[key] return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "==", "'class'", ":", "return", "self", ".", "tag", ".", "className", "if", "key", "in", "(", "'style'", ",", "'class'", ")", "or", "key", "in", "self", ".", "keys", "(", ")", ":", "return", "self", "[", "key", "]", "return", "default" ]
get - Gets an attribute by key with the chance to provide a default value @param key <str> - The key to query @param default <Anything> Default None - The value to return if key is not found @return - The value of attribute at #key, or #default if not present.
[ "get", "-", "Gets", "an", "attribute", "by", "key", "with", "the", "chance", "to", "provide", "a", "default", "value" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L187-L205
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
SpecialAttributesDict._direct_set
def _direct_set(self, key, value): ''' _direct_set - INTERNAL USE ONLY!!!! Directly sets a value on the underlying dict, without running through the setitem logic ''' dict.__setitem__(self, key, value) return value
python
def _direct_set(self, key, value): ''' _direct_set - INTERNAL USE ONLY!!!! Directly sets a value on the underlying dict, without running through the setitem logic ''' dict.__setitem__(self, key, value) return value
[ "def", "_direct_set", "(", "self", ",", "key", ",", "value", ")", ":", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "value", ")", "return", "value" ]
_direct_set - INTERNAL USE ONLY!!!! Directly sets a value on the underlying dict, without running through the setitem logic
[ "_direct_set", "-", "INTERNAL", "USE", "ONLY!!!!" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L207-L215
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute.setTag
def setTag(self, tag): ''' setTag - Set the tag association for this style. This will handle the underlying weakref to the tag. Call setTag(None) to clear the association, otherwise setTag(tag) to associate this style to that tag. @param tag <AdvancedTag/None> - The new association. If None, the association is cleared, otherwise the passed tag becomes associated with this style. ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = None
python
def setTag(self, tag): ''' setTag - Set the tag association for this style. This will handle the underlying weakref to the tag. Call setTag(None) to clear the association, otherwise setTag(tag) to associate this style to that tag. @param tag <AdvancedTag/None> - The new association. If None, the association is cleared, otherwise the passed tag becomes associated with this style. ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = None
[ "def", "setTag", "(", "self", ",", "tag", ")", ":", "if", "tag", ":", "self", ".", "_tagRef", "=", "weakref", ".", "ref", "(", "tag", ")", "else", ":", "self", ".", "_tagRef", "=", "None" ]
setTag - Set the tag association for this style. This will handle the underlying weakref to the tag. Call setTag(None) to clear the association, otherwise setTag(tag) to associate this style to that tag. @param tag <AdvancedTag/None> - The new association. If None, the association is cleared, otherwise the passed tag becomes associated with this style.
[ "setTag", "-", "Set", "the", "tag", "association", "for", "this", "style", ".", "This", "will", "handle", "the", "underlying", "weakref", "to", "the", "tag", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L445-L462
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute._ensureHtmlAttribute
def _ensureHtmlAttribute(self): ''' _ensureHtmlAttribute - INTERNAL METHOD. Ensure the "style" attribute is present in the html attributes when is has a value, and absent when it does not. This requires special linkage. ''' tag = self.tag if tag: styleDict = self._styleDict tagAttributes = tag._attributes # If this is called before we have _attributes setup if not issubclass(tagAttributes.__class__, SpecialAttributesDict): return # If we have any styles set, ensure we have the style="whatever" in the HTML representation, # otherwise ensure we don't have style="" if not styleDict: tagAttributes._direct_del('style') else: #if 'style' not in tagAttributes.keys(): tagAttributes._direct_set('style', self)
python
def _ensureHtmlAttribute(self): ''' _ensureHtmlAttribute - INTERNAL METHOD. Ensure the "style" attribute is present in the html attributes when is has a value, and absent when it does not. This requires special linkage. ''' tag = self.tag if tag: styleDict = self._styleDict tagAttributes = tag._attributes # If this is called before we have _attributes setup if not issubclass(tagAttributes.__class__, SpecialAttributesDict): return # If we have any styles set, ensure we have the style="whatever" in the HTML representation, # otherwise ensure we don't have style="" if not styleDict: tagAttributes._direct_del('style') else: #if 'style' not in tagAttributes.keys(): tagAttributes._direct_set('style', self)
[ "def", "_ensureHtmlAttribute", "(", "self", ")", ":", "tag", "=", "self", ".", "tag", "if", "tag", ":", "styleDict", "=", "self", ".", "_styleDict", "tagAttributes", "=", "tag", ".", "_attributes", "# If this is called before we have _attributes setup", "if", "not", "issubclass", "(", "tagAttributes", ".", "__class__", ",", "SpecialAttributesDict", ")", ":", "return", "# If we have any styles set, ensure we have the style=\"whatever\" in the HTML representation,", "# otherwise ensure we don't have style=\"\" ", "if", "not", "styleDict", ":", "tagAttributes", ".", "_direct_del", "(", "'style'", ")", "else", ":", "#if 'style' not in tagAttributes.keys():", "tagAttributes", ".", "_direct_set", "(", "'style'", ",", "self", ")" ]
_ensureHtmlAttribute - INTERNAL METHOD. Ensure the "style" attribute is present in the html attributes when is has a value, and absent when it does not. This requires special linkage.
[ "_ensureHtmlAttribute", "-", "INTERNAL", "METHOD", ".", "Ensure", "the", "style", "attribute", "is", "present", "in", "the", "html", "attributes", "when", "is", "has", "a", "value", "and", "absent", "when", "it", "does", "not", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L519-L542
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute.setProperty
def setProperty(self, name, value): ''' setProperty - Set a style property to a value. NOTE: To remove a style, use a value of empty string, or None @param name <str> - The style name. NOTE: The dash names are expected here, whereas dot-access expects the camel case names. Example: name="font-weight" versus the dot-access style.fontWeight @param value <str> - The style value, or empty string to remove property ''' styleDict = self._styleDict if value in ('', None): try: del styleDict[name] except KeyError: pass else: styleDict[name] = str(value)
python
def setProperty(self, name, value): ''' setProperty - Set a style property to a value. NOTE: To remove a style, use a value of empty string, or None @param name <str> - The style name. NOTE: The dash names are expected here, whereas dot-access expects the camel case names. Example: name="font-weight" versus the dot-access style.fontWeight @param value <str> - The style value, or empty string to remove property ''' styleDict = self._styleDict if value in ('', None): try: del styleDict[name] except KeyError: pass else: styleDict[name] = str(value)
[ "def", "setProperty", "(", "self", ",", "name", ",", "value", ")", ":", "styleDict", "=", "self", ".", "_styleDict", "if", "value", "in", "(", "''", ",", "None", ")", ":", "try", ":", "del", "styleDict", "[", "name", "]", "except", "KeyError", ":", "pass", "else", ":", "styleDict", "[", "name", "]", "=", "str", "(", "value", ")" ]
setProperty - Set a style property to a value. NOTE: To remove a style, use a value of empty string, or None @param name <str> - The style name. NOTE: The dash names are expected here, whereas dot-access expects the camel case names. Example: name="font-weight" versus the dot-access style.fontWeight @param value <str> - The style value, or empty string to remove property
[ "setProperty", "-", "Set", "a", "style", "property", "to", "a", "value", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L555-L577
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute.dashNameToCamelCase
def dashNameToCamelCase(dashName): ''' dashNameToCamelCase - Converts a "dash name" (like padding-top) to its camel-case name ( like "paddingTop" ) @param dashName <str> - A name containing dashes NOTE: This method is currently unused, but may be used in the future. kept for completeness. @return <str> - The camel-case form ''' nameParts = dashName.split('-') for i in range(1, len(nameParts), 1): nameParts[i][0] = nameParts[i][0].upper() return ''.join(nameParts)
python
def dashNameToCamelCase(dashName): ''' dashNameToCamelCase - Converts a "dash name" (like padding-top) to its camel-case name ( like "paddingTop" ) @param dashName <str> - A name containing dashes NOTE: This method is currently unused, but may be used in the future. kept for completeness. @return <str> - The camel-case form ''' nameParts = dashName.split('-') for i in range(1, len(nameParts), 1): nameParts[i][0] = nameParts[i][0].upper() return ''.join(nameParts)
[ "def", "dashNameToCamelCase", "(", "dashName", ")", ":", "nameParts", "=", "dashName", ".", "split", "(", "'-'", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "nameParts", ")", ",", "1", ")", ":", "nameParts", "[", "i", "]", "[", "0", "]", "=", "nameParts", "[", "i", "]", "[", "0", "]", ".", "upper", "(", ")", "return", "''", ".", "join", "(", "nameParts", ")" ]
dashNameToCamelCase - Converts a "dash name" (like padding-top) to its camel-case name ( like "paddingTop" ) @param dashName <str> - A name containing dashes NOTE: This method is currently unused, but may be used in the future. kept for completeness. @return <str> - The camel-case form
[ "dashNameToCamelCase", "-", "Converts", "a", "dash", "name", "(", "like", "padding", "-", "top", ")", "to", "its", "camel", "-", "case", "name", "(", "like", "paddingTop", ")" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L598-L612
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute.camelCaseToDashName
def camelCaseToDashName(camelCase): ''' camelCaseToDashName - Convert a camel case name to a dash-name (like paddingTop to padding-top) @param camelCase <str> - A camel-case string @return <str> - A dash-name ''' camelCaseList = list(camelCase) ret = [] for ch in camelCaseList: if ch.isupper(): ret.append('-') ret.append(ch.lower()) else: ret.append(ch) return ''.join(ret)
python
def camelCaseToDashName(camelCase): ''' camelCaseToDashName - Convert a camel case name to a dash-name (like paddingTop to padding-top) @param camelCase <str> - A camel-case string @return <str> - A dash-name ''' camelCaseList = list(camelCase) ret = [] for ch in camelCaseList: if ch.isupper(): ret.append('-') ret.append(ch.lower()) else: ret.append(ch) return ''.join(ret)
[ "def", "camelCaseToDashName", "(", "camelCase", ")", ":", "camelCaseList", "=", "list", "(", "camelCase", ")", "ret", "=", "[", "]", "for", "ch", "in", "camelCaseList", ":", "if", "ch", ".", "isupper", "(", ")", ":", "ret", ".", "append", "(", "'-'", ")", "ret", ".", "append", "(", "ch", ".", "lower", "(", ")", ")", "else", ":", "ret", ".", "append", "(", "ch", ")", "return", "''", ".", "join", "(", "ret", ")" ]
camelCaseToDashName - Convert a camel case name to a dash-name (like paddingTop to padding-top) @param camelCase <str> - A camel-case string @return <str> - A dash-name
[ "camelCaseToDashName", "-", "Convert", "a", "camel", "case", "name", "to", "a", "dash", "-", "name", "(", "like", "paddingTop", "to", "padding", "-", "top", ")" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L615-L635
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute.styleToDict
def styleToDict(styleStr): ''' getStyleDict - Gets a dictionary of style attribute/value pairs. NOTE: dash-names (like padding-top) are used here @return - OrderedDict of "style" attribute. ''' styleStr = styleStr.strip() styles = styleStr.split(';') # Won't work for strings containing semicolon.. styleDict = OrderedDict() for item in styles: try: splitIdx = item.index(':') name = item[:splitIdx].strip().lower() value = item[splitIdx+1:].strip() styleDict[name] = value except: continue return styleDict
python
def styleToDict(styleStr): ''' getStyleDict - Gets a dictionary of style attribute/value pairs. NOTE: dash-names (like padding-top) are used here @return - OrderedDict of "style" attribute. ''' styleStr = styleStr.strip() styles = styleStr.split(';') # Won't work for strings containing semicolon.. styleDict = OrderedDict() for item in styles: try: splitIdx = item.index(':') name = item[:splitIdx].strip().lower() value = item[splitIdx+1:].strip() styleDict[name] = value except: continue return styleDict
[ "def", "styleToDict", "(", "styleStr", ")", ":", "styleStr", "=", "styleStr", ".", "strip", "(", ")", "styles", "=", "styleStr", ".", "split", "(", "';'", ")", "# Won't work for strings containing semicolon..", "styleDict", "=", "OrderedDict", "(", ")", "for", "item", "in", "styles", ":", "try", ":", "splitIdx", "=", "item", ".", "index", "(", "':'", ")", "name", "=", "item", "[", ":", "splitIdx", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "value", "=", "item", "[", "splitIdx", "+", "1", ":", "]", ".", "strip", "(", ")", "styleDict", "[", "name", "]", "=", "value", "except", ":", "continue", "return", "styleDict" ]
getStyleDict - Gets a dictionary of style attribute/value pairs. NOTE: dash-names (like padding-top) are used here @return - OrderedDict of "style" attribute.
[ "getStyleDict", "-", "Gets", "a", "dictionary", "of", "style", "attribute", "/", "value", "pairs", "." ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L638-L659
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/SpecialAttributes.py
StyleAttribute._asStr
def _asStr(self): ''' _asStr - Get the string representation of this style @return <str> - A string representation of this style (semicolon separated, key: value format) ''' styleDict = self._styleDict if styleDict: return '; '.join([name + ': ' + value for name, value in styleDict.items()]) return ''
python
def _asStr(self): ''' _asStr - Get the string representation of this style @return <str> - A string representation of this style (semicolon separated, key: value format) ''' styleDict = self._styleDict if styleDict: return '; '.join([name + ': ' + value for name, value in styleDict.items()]) return ''
[ "def", "_asStr", "(", "self", ")", ":", "styleDict", "=", "self", ".", "_styleDict", "if", "styleDict", ":", "return", "'; '", ".", "join", "(", "[", "name", "+", "': '", "+", "value", "for", "name", ",", "value", "in", "styleDict", ".", "items", "(", ")", "]", ")", "return", "''" ]
_asStr - Get the string representation of this style @return <str> - A string representation of this style (semicolon separated, key: value format)
[ "_asStr", "-", "Get", "the", "string", "representation", "of", "this", "style" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/SpecialAttributes.py#L738-L748
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/constants.py
_special_value_rows
def _special_value_rows(em): ''' _special_value_rows - Handle "rows" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('rows', 2), minValue=1, maxValue=None, invalidDefault=2) else: # frameset return em.getAttribute('rows', '')
python
def _special_value_rows(em): ''' _special_value_rows - Handle "rows" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('rows', 2), minValue=1, maxValue=None, invalidDefault=2) else: # frameset return em.getAttribute('rows', '')
[ "def", "_special_value_rows", "(", "em", ")", ":", "if", "em", ".", "tagName", "==", "'textarea'", ":", "return", "convertToIntRange", "(", "em", ".", "getAttribute", "(", "'rows'", ",", "2", ")", ",", "minValue", "=", "1", ",", "maxValue", "=", "None", ",", "invalidDefault", "=", "2", ")", "else", ":", "# frameset", "return", "em", ".", "getAttribute", "(", "'rows'", ",", "''", ")" ]
_special_value_rows - Handle "rows" special attribute, which differs if tagName is a textarea or frameset
[ "_special_value_rows", "-", "Handle", "rows", "special", "attribute", "which", "differs", "if", "tagName", "is", "a", "textarea", "or", "frameset" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/constants.py#L248-L256
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/constants.py
_special_value_cols
def _special_value_cols(em): ''' _special_value_cols - Handle "cols" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('cols', 20), minValue=1, maxValue=None, invalidDefault=20) else: # frameset return em.getAttribute('cols', '')
python
def _special_value_cols(em): ''' _special_value_cols - Handle "cols" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('cols', 20), minValue=1, maxValue=None, invalidDefault=20) else: # frameset return em.getAttribute('cols', '')
[ "def", "_special_value_cols", "(", "em", ")", ":", "if", "em", ".", "tagName", "==", "'textarea'", ":", "return", "convertToIntRange", "(", "em", ".", "getAttribute", "(", "'cols'", ",", "20", ")", ",", "minValue", "=", "1", ",", "maxValue", "=", "None", ",", "invalidDefault", "=", "20", ")", "else", ":", "# frameset", "return", "em", ".", "getAttribute", "(", "'cols'", ",", "''", ")" ]
_special_value_cols - Handle "cols" special attribute, which differs if tagName is a textarea or frameset
[ "_special_value_cols", "-", "Handle", "cols", "special", "attribute", "which", "differs", "if", "tagName", "is", "a", "textarea", "or", "frameset" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/constants.py#L258-L266
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/constants.py
_special_value_autocomplete
def _special_value_autocomplete(em): ''' handle "autocomplete" property, which has different behaviour for form vs input" ''' if em.tagName == 'form': return convertPossibleValues(em.getAttribute('autocomplete', 'on'), POSSIBLE_VALUES_ON_OFF, invalidDefault='on', emptyValue=EMPTY_IS_INVALID) # else: input return convertPossibleValues(em.getAttribute('autocomplete', ''), POSSIBLE_VALUES_ON_OFF, invalidDefault="", emptyValue='')
python
def _special_value_autocomplete(em): ''' handle "autocomplete" property, which has different behaviour for form vs input" ''' if em.tagName == 'form': return convertPossibleValues(em.getAttribute('autocomplete', 'on'), POSSIBLE_VALUES_ON_OFF, invalidDefault='on', emptyValue=EMPTY_IS_INVALID) # else: input return convertPossibleValues(em.getAttribute('autocomplete', ''), POSSIBLE_VALUES_ON_OFF, invalidDefault="", emptyValue='')
[ "def", "_special_value_autocomplete", "(", "em", ")", ":", "if", "em", ".", "tagName", "==", "'form'", ":", "return", "convertPossibleValues", "(", "em", ".", "getAttribute", "(", "'autocomplete'", ",", "'on'", ")", ",", "POSSIBLE_VALUES_ON_OFF", ",", "invalidDefault", "=", "'on'", ",", "emptyValue", "=", "EMPTY_IS_INVALID", ")", "# else: input", "return", "convertPossibleValues", "(", "em", ".", "getAttribute", "(", "'autocomplete'", ",", "''", ")", ",", "POSSIBLE_VALUES_ON_OFF", ",", "invalidDefault", "=", "\"\"", ",", "emptyValue", "=", "''", ")" ]
handle "autocomplete" property, which has different behaviour for form vs input"
[ "handle", "autocomplete", "property", "which", "has", "different", "behaviour", "for", "form", "vs", "input" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/constants.py#L268-L275
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/constants.py
_special_value_size
def _special_value_size(em): ''' handle "size" property, which has different behaviour for input vs everything else ''' if em.tagName == 'input': # TODO: "size" on an input is implemented very weirdly. Negative values are treated as invalid, # A value of "0" raises an exception (and does not set HTML attribute) # No upper limit. return convertToPositiveInt(em.getAttribute('size', 20), invalidDefault=20) return em.getAttribute('size', '')
python
def _special_value_size(em): ''' handle "size" property, which has different behaviour for input vs everything else ''' if em.tagName == 'input': # TODO: "size" on an input is implemented very weirdly. Negative values are treated as invalid, # A value of "0" raises an exception (and does not set HTML attribute) # No upper limit. return convertToPositiveInt(em.getAttribute('size', 20), invalidDefault=20) return em.getAttribute('size', '')
[ "def", "_special_value_size", "(", "em", ")", ":", "if", "em", ".", "tagName", "==", "'input'", ":", "# TODO: \"size\" on an input is implemented very weirdly. Negative values are treated as invalid,", "# A value of \"0\" raises an exception (and does not set HTML attribute)", "# No upper limit.", "return", "convertToPositiveInt", "(", "em", ".", "getAttribute", "(", "'size'", ",", "20", ")", ",", "invalidDefault", "=", "20", ")", "return", "em", ".", "getAttribute", "(", "'size'", ",", "''", ")" ]
handle "size" property, which has different behaviour for input vs everything else
[ "handle", "size", "property", "which", "has", "different", "behaviour", "for", "input", "vs", "everything", "else" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/constants.py#L277-L286
train
kata198/AdvancedHTMLParser
AdvancedHTMLParser/constants.py
_special_value_maxLength
def _special_value_maxLength(em, newValue=NOT_PROVIDED): ''' _special_value_maxLength - Handle the special "maxLength" property @param em <AdvancedTag> - The tag element @param newValue - Default NOT_PROVIDED, if provided will use that value instead of the current .getAttribute value on the tag. This is because this method can be used for both validation and getting/setting ''' if newValue is NOT_PROVIDED: if not em.hasAttribute('maxlength'): return -1 curValue = em.getAttribute('maxlength', '-1') # If we are accessing, the invalid default should be negative invalidDefault = -1 else: curValue = newValue # If we are setting, we should raise an exception upon invalid value invalidDefault = IndexSizeErrorException return convertToIntRange(curValue, minValue=0, maxValue=None, emptyValue='0', invalidDefault=invalidDefault)
python
def _special_value_maxLength(em, newValue=NOT_PROVIDED): ''' _special_value_maxLength - Handle the special "maxLength" property @param em <AdvancedTag> - The tag element @param newValue - Default NOT_PROVIDED, if provided will use that value instead of the current .getAttribute value on the tag. This is because this method can be used for both validation and getting/setting ''' if newValue is NOT_PROVIDED: if not em.hasAttribute('maxlength'): return -1 curValue = em.getAttribute('maxlength', '-1') # If we are accessing, the invalid default should be negative invalidDefault = -1 else: curValue = newValue # If we are setting, we should raise an exception upon invalid value invalidDefault = IndexSizeErrorException return convertToIntRange(curValue, minValue=0, maxValue=None, emptyValue='0', invalidDefault=invalidDefault)
[ "def", "_special_value_maxLength", "(", "em", ",", "newValue", "=", "NOT_PROVIDED", ")", ":", "if", "newValue", "is", "NOT_PROVIDED", ":", "if", "not", "em", ".", "hasAttribute", "(", "'maxlength'", ")", ":", "return", "-", "1", "curValue", "=", "em", ".", "getAttribute", "(", "'maxlength'", ",", "'-1'", ")", "# If we are accessing, the invalid default should be negative", "invalidDefault", "=", "-", "1", "else", ":", "curValue", "=", "newValue", "# If we are setting, we should raise an exception upon invalid value", "invalidDefault", "=", "IndexSizeErrorException", "return", "convertToIntRange", "(", "curValue", ",", "minValue", "=", "0", ",", "maxValue", "=", "None", ",", "emptyValue", "=", "'0'", ",", "invalidDefault", "=", "invalidDefault", ")" ]
_special_value_maxLength - Handle the special "maxLength" property @param em <AdvancedTag> - The tag element @param newValue - Default NOT_PROVIDED, if provided will use that value instead of the current .getAttribute value on the tag. This is because this method can be used for both validation and getting/setting
[ "_special_value_maxLength", "-", "Handle", "the", "special", "maxLength", "property" ]
06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/constants.py#L300-L327
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/data_objects.py
DataObject.get_by_value
def get_by_value(cls, value, type): """ Converts a value into a corresponding data object. For files, this looks up a file DataObject by name, uuid, and/or md5. For other types, it creates a new DataObject. """ if type == 'file': return cls._get_file_by_value(value) else: data_object = DataObject(data={ 'value': cls._type_cast(value, type)}, type=type) data_object.full_clean() data_object.save() return data_object
python
def get_by_value(cls, value, type): """ Converts a value into a corresponding data object. For files, this looks up a file DataObject by name, uuid, and/or md5. For other types, it creates a new DataObject. """ if type == 'file': return cls._get_file_by_value(value) else: data_object = DataObject(data={ 'value': cls._type_cast(value, type)}, type=type) data_object.full_clean() data_object.save() return data_object
[ "def", "get_by_value", "(", "cls", ",", "value", ",", "type", ")", ":", "if", "type", "==", "'file'", ":", "return", "cls", ".", "_get_file_by_value", "(", "value", ")", "else", ":", "data_object", "=", "DataObject", "(", "data", "=", "{", "'value'", ":", "cls", ".", "_type_cast", "(", "value", ",", "type", ")", "}", ",", "type", "=", "type", ")", "data_object", ".", "full_clean", "(", ")", "data_object", ".", "save", "(", ")", "return", "data_object" ]
Converts a value into a corresponding data object. For files, this looks up a file DataObject by name, uuid, and/or md5. For other types, it creates a new DataObject.
[ "Converts", "a", "value", "into", "a", "corresponding", "data", "object", ".", "For", "files", "this", "looks", "up", "a", "file", "DataObject", "by", "name", "uuid", "and", "/", "or", "md5", ".", "For", "other", "types", "it", "creates", "a", "new", "DataObject", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/data_objects.py#L55-L67
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/data_objects.py
DataObject._get_file_by_value
def _get_file_by_value(cls, value): """Look up a file DataObject by name, uuid, and/or md5. """ # Ignore any FileResource with no DataObject. This is a typical state # for a deleted file that has not yet been cleaned up. queryset = FileResource.objects.exclude(data_object__isnull=True) matches = FileResource.filter_by_name_or_id_or_tag_or_hash( value, queryset=queryset) if matches.count() == 0: raise ValidationError( 'No file found that matches value "%s"' % value) elif matches.count() > 1: match_id_list = ['%s@%s' % (match.filename, match.get_uuid()) for match in matches] match_id_string = ('", "'.join(match_id_list)) raise ValidationError( 'Multiple files were found matching value "%s": "%s". '\ 'Use a more precise identifier to select just one file.' % ( value, match_id_string)) return matches.first().data_object
python
def _get_file_by_value(cls, value): """Look up a file DataObject by name, uuid, and/or md5. """ # Ignore any FileResource with no DataObject. This is a typical state # for a deleted file that has not yet been cleaned up. queryset = FileResource.objects.exclude(data_object__isnull=True) matches = FileResource.filter_by_name_or_id_or_tag_or_hash( value, queryset=queryset) if matches.count() == 0: raise ValidationError( 'No file found that matches value "%s"' % value) elif matches.count() > 1: match_id_list = ['%s@%s' % (match.filename, match.get_uuid()) for match in matches] match_id_string = ('", "'.join(match_id_list)) raise ValidationError( 'Multiple files were found matching value "%s": "%s". '\ 'Use a more precise identifier to select just one file.' % ( value, match_id_string)) return matches.first().data_object
[ "def", "_get_file_by_value", "(", "cls", ",", "value", ")", ":", "# Ignore any FileResource with no DataObject. This is a typical state", "# for a deleted file that has not yet been cleaned up.", "queryset", "=", "FileResource", ".", "objects", ".", "exclude", "(", "data_object__isnull", "=", "True", ")", "matches", "=", "FileResource", ".", "filter_by_name_or_id_or_tag_or_hash", "(", "value", ",", "queryset", "=", "queryset", ")", "if", "matches", ".", "count", "(", ")", "==", "0", ":", "raise", "ValidationError", "(", "'No file found that matches value \"%s\"'", "%", "value", ")", "elif", "matches", ".", "count", "(", ")", ">", "1", ":", "match_id_list", "=", "[", "'%s@%s'", "%", "(", "match", ".", "filename", ",", "match", ".", "get_uuid", "(", ")", ")", "for", "match", "in", "matches", "]", "match_id_string", "=", "(", "'\", \"'", ".", "join", "(", "match_id_list", ")", ")", "raise", "ValidationError", "(", "'Multiple files were found matching value \"%s\": \"%s\". '", "'Use a more precise identifier to select just one file.'", "%", "(", "value", ",", "match_id_string", ")", ")", "return", "matches", ".", "first", "(", ")", ".", "data_object" ]
Look up a file DataObject by name, uuid, and/or md5.
[ "Look", "up", "a", "file", "DataObject", "by", "name", "uuid", "and", "/", "or", "md5", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/data_objects.py#L87-L106
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/data_objects.py
FileResource._get_run_breadcrumbs
def _get_run_breadcrumbs(cls, source_type, data_object, task_attempt): """Create a path for a given file, in such a way that files end up being organized and browsable by run """ # We cannot generate the path unless connect to a TaskAttempt # and a run if not task_attempt: return [] # If multiple tasks exist, use the original. task = task_attempt.tasks.earliest('datetime_created') if task is None: return [] run = task.run if run is None: return [] breadcrumbs = [ run.name, "task-%s" % str(task.uuid)[0:8], "attempt-%s" % str(task_attempt.uuid)[0:8], ] # Include any ancestors if run is nested while run.parent is not None: run = run.parent breadcrumbs = [run.name] + breadcrumbs # Prepend first breadcrumb with datetime and id breadcrumbs[0] = "%s-%s-%s" % ( run.datetime_created.strftime('%Y-%m-%dT%H.%M.%SZ'), str(run.uuid)[0:8], breadcrumbs[0]) breadcrumbs = ['runs'] + breadcrumbs return breadcrumbs
python
def _get_run_breadcrumbs(cls, source_type, data_object, task_attempt): """Create a path for a given file, in such a way that files end up being organized and browsable by run """ # We cannot generate the path unless connect to a TaskAttempt # and a run if not task_attempt: return [] # If multiple tasks exist, use the original. task = task_attempt.tasks.earliest('datetime_created') if task is None: return [] run = task.run if run is None: return [] breadcrumbs = [ run.name, "task-%s" % str(task.uuid)[0:8], "attempt-%s" % str(task_attempt.uuid)[0:8], ] # Include any ancestors if run is nested while run.parent is not None: run = run.parent breadcrumbs = [run.name] + breadcrumbs # Prepend first breadcrumb with datetime and id breadcrumbs[0] = "%s-%s-%s" % ( run.datetime_created.strftime('%Y-%m-%dT%H.%M.%SZ'), str(run.uuid)[0:8], breadcrumbs[0]) breadcrumbs = ['runs'] + breadcrumbs return breadcrumbs
[ "def", "_get_run_breadcrumbs", "(", "cls", ",", "source_type", ",", "data_object", ",", "task_attempt", ")", ":", "# We cannot generate the path unless connect to a TaskAttempt", "# and a run", "if", "not", "task_attempt", ":", "return", "[", "]", "# If multiple tasks exist, use the original.", "task", "=", "task_attempt", ".", "tasks", ".", "earliest", "(", "'datetime_created'", ")", "if", "task", "is", "None", ":", "return", "[", "]", "run", "=", "task", ".", "run", "if", "run", "is", "None", ":", "return", "[", "]", "breadcrumbs", "=", "[", "run", ".", "name", ",", "\"task-%s\"", "%", "str", "(", "task", ".", "uuid", ")", "[", "0", ":", "8", "]", ",", "\"attempt-%s\"", "%", "str", "(", "task_attempt", ".", "uuid", ")", "[", "0", ":", "8", "]", ",", "]", "# Include any ancestors if run is nested", "while", "run", ".", "parent", "is", "not", "None", ":", "run", "=", "run", ".", "parent", "breadcrumbs", "=", "[", "run", ".", "name", "]", "+", "breadcrumbs", "# Prepend first breadcrumb with datetime and id", "breadcrumbs", "[", "0", "]", "=", "\"%s-%s-%s\"", "%", "(", "run", ".", "datetime_created", ".", "strftime", "(", "'%Y-%m-%dT%H.%M.%SZ'", ")", ",", "str", "(", "run", ".", "uuid", ")", "[", "0", ":", "8", "]", ",", "breadcrumbs", "[", "0", "]", ")", "breadcrumbs", "=", "[", "'runs'", "]", "+", "breadcrumbs", "return", "breadcrumbs" ]
Create a path for a given file, in such a way that files end up being organized and browsable by run
[ "Create", "a", "path", "for", "a", "given", "file", "in", "such", "a", "way", "that", "files", "end", "up", "being", "organized", "and", "browsable", "by", "run" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/data_objects.py#L384-L418
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/base.py
FilterHelper.filter_by_name_or_id_or_tag
def filter_by_name_or_id_or_tag(self, query_string, queryset = None): """Find objects that match the identifier of form {name}@{ID}, {name}, or @{ID}, where ID may be truncated """ assert self.Model.NAME_FIELD, \ 'NAME_FIELD is missing on model %s' % self.Model.__name__ assert self.Model.ID_FIELD, \ 'ID_FIELD is missing on model %s' % self.Model.__name__ assert self.Model.TAG_FIELD, \ 'TAG_FIELD is missing on model %s' % self.Model.__name__ filter_args = {} name, uuid, tag = self._parse_as_name_or_id_or_tag(query_string) if name is not None: filter_args[self.Model.NAME_FIELD] = name if uuid is not None: filter_args[self.Model.ID_FIELD+'__startswith'] = uuid if tag is not None: filter_args[self.Model.TAG_FIELD] = tag if queryset is None: queryset = self.Model.objects.all() return queryset.filter(**filter_args)
python
def filter_by_name_or_id_or_tag(self, query_string, queryset = None): """Find objects that match the identifier of form {name}@{ID}, {name}, or @{ID}, where ID may be truncated """ assert self.Model.NAME_FIELD, \ 'NAME_FIELD is missing on model %s' % self.Model.__name__ assert self.Model.ID_FIELD, \ 'ID_FIELD is missing on model %s' % self.Model.__name__ assert self.Model.TAG_FIELD, \ 'TAG_FIELD is missing on model %s' % self.Model.__name__ filter_args = {} name, uuid, tag = self._parse_as_name_or_id_or_tag(query_string) if name is not None: filter_args[self.Model.NAME_FIELD] = name if uuid is not None: filter_args[self.Model.ID_FIELD+'__startswith'] = uuid if tag is not None: filter_args[self.Model.TAG_FIELD] = tag if queryset is None: queryset = self.Model.objects.all() return queryset.filter(**filter_args)
[ "def", "filter_by_name_or_id_or_tag", "(", "self", ",", "query_string", ",", "queryset", "=", "None", ")", ":", "assert", "self", ".", "Model", ".", "NAME_FIELD", ",", "'NAME_FIELD is missing on model %s'", "%", "self", ".", "Model", ".", "__name__", "assert", "self", ".", "Model", ".", "ID_FIELD", ",", "'ID_FIELD is missing on model %s'", "%", "self", ".", "Model", ".", "__name__", "assert", "self", ".", "Model", ".", "TAG_FIELD", ",", "'TAG_FIELD is missing on model %s'", "%", "self", ".", "Model", ".", "__name__", "filter_args", "=", "{", "}", "name", ",", "uuid", ",", "tag", "=", "self", ".", "_parse_as_name_or_id_or_tag", "(", "query_string", ")", "if", "name", "is", "not", "None", ":", "filter_args", "[", "self", ".", "Model", ".", "NAME_FIELD", "]", "=", "name", "if", "uuid", "is", "not", "None", ":", "filter_args", "[", "self", ".", "Model", ".", "ID_FIELD", "+", "'__startswith'", "]", "=", "uuid", "if", "tag", "is", "not", "None", ":", "filter_args", "[", "self", ".", "Model", ".", "TAG_FIELD", "]", "=", "tag", "if", "queryset", "is", "None", ":", "queryset", "=", "self", ".", "Model", ".", "objects", ".", "all", "(", ")", "return", "queryset", ".", "filter", "(", "*", "*", "filter_args", ")" ]
Find objects that match the identifier of form {name}@{ID}, {name}, or @{ID}, where ID may be truncated
[ "Find", "objects", "that", "match", "the", "identifier", "of", "form", "{", "name", "}" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/base.py#L126-L147
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/base.py
BaseModel.save
def save(self, *args, **kwargs): """ This save method protects against two processesses concurrently modifying the same object. Normally the second save would silently overwrite the changes from the first. Instead we raise a ConcurrentModificationError. """ cls = self.__class__ if self.pk: rows = cls.objects.filter( pk=self.pk, _change=self._change).update( _change=self._change + 1) if not rows: raise ConcurrentModificationError(cls.__name__, self.pk) self._change += 1 count = 0 max_retries=3 while True: try: return super(BaseModel, self).save(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 1
python
def save(self, *args, **kwargs): """ This save method protects against two processesses concurrently modifying the same object. Normally the second save would silently overwrite the changes from the first. Instead we raise a ConcurrentModificationError. """ cls = self.__class__ if self.pk: rows = cls.objects.filter( pk=self.pk, _change=self._change).update( _change=self._change + 1) if not rows: raise ConcurrentModificationError(cls.__name__, self.pk) self._change += 1 count = 0 max_retries=3 while True: try: return super(BaseModel, self).save(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 1
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cls", "=", "self", ".", "__class__", "if", "self", ".", "pk", ":", "rows", "=", "cls", ".", "objects", ".", "filter", "(", "pk", "=", "self", ".", "pk", ",", "_change", "=", "self", ".", "_change", ")", ".", "update", "(", "_change", "=", "self", ".", "_change", "+", "1", ")", "if", "not", "rows", ":", "raise", "ConcurrentModificationError", "(", "cls", ".", "__name__", ",", "self", ".", "pk", ")", "self", ".", "_change", "+=", "1", "count", "=", "0", "max_retries", "=", "3", "while", "True", ":", "try", ":", "return", "super", "(", "BaseModel", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "django", ".", "db", ".", "utils", ".", "OperationalError", ":", "if", "count", ">=", "max_retries", ":", "raise", "count", "+=", "1" ]
This save method protects against two processesses concurrently modifying the same object. Normally the second save would silently overwrite the changes from the first. Instead we raise a ConcurrentModificationError.
[ "This", "save", "method", "protects", "against", "two", "processesses", "concurrently", "modifying", "the", "same", "object", ".", "Normally", "the", "second", "save", "would", "silently", "overwrite", "the", "changes", "from", "the", "first", ".", "Instead", "we", "raise", "a", "ConcurrentModificationError", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/base.py#L225-L248
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/base.py
BaseModel.setattrs_and_save_with_retries
def setattrs_and_save_with_retries(self, assignments, max_retries=5): """ If the object is being edited by other processes, save may fail due to concurrent modification. This method recovers and retries the edit. assignments is a dict of {attribute: value} """ count = 0 obj=self while True: for attribute, value in assignments.iteritems(): setattr(obj, attribute, value) try: obj.full_clean() obj.save() except ConcurrentModificationError: if count >= max_retries: raise SaveRetriesExceededError( 'Exceeded retries when saving "%s" of id "%s" '\ 'with assigned values "%s"' % (self.__class__, self.id, assignments)) count += 1 obj = self.__class__.objects.get(id=self.id) continue return obj
python
def setattrs_and_save_with_retries(self, assignments, max_retries=5): """ If the object is being edited by other processes, save may fail due to concurrent modification. This method recovers and retries the edit. assignments is a dict of {attribute: value} """ count = 0 obj=self while True: for attribute, value in assignments.iteritems(): setattr(obj, attribute, value) try: obj.full_clean() obj.save() except ConcurrentModificationError: if count >= max_retries: raise SaveRetriesExceededError( 'Exceeded retries when saving "%s" of id "%s" '\ 'with assigned values "%s"' % (self.__class__, self.id, assignments)) count += 1 obj = self.__class__.objects.get(id=self.id) continue return obj
[ "def", "setattrs_and_save_with_retries", "(", "self", ",", "assignments", ",", "max_retries", "=", "5", ")", ":", "count", "=", "0", "obj", "=", "self", "while", "True", ":", "for", "attribute", ",", "value", "in", "assignments", ".", "iteritems", "(", ")", ":", "setattr", "(", "obj", ",", "attribute", ",", "value", ")", "try", ":", "obj", ".", "full_clean", "(", ")", "obj", ".", "save", "(", ")", "except", "ConcurrentModificationError", ":", "if", "count", ">=", "max_retries", ":", "raise", "SaveRetriesExceededError", "(", "'Exceeded retries when saving \"%s\" of id \"%s\" '", "'with assigned values \"%s\"'", "%", "(", "self", ".", "__class__", ",", "self", ".", "id", ",", "assignments", ")", ")", "count", "+=", "1", "obj", "=", "self", ".", "__class__", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "id", ")", "continue", "return", "obj" ]
If the object is being edited by other processes, save may fail due to concurrent modification. This method recovers and retries the edit. assignments is a dict of {attribute: value}
[ "If", "the", "object", "is", "being", "edited", "by", "other", "processes", "save", "may", "fail", "due", "to", "concurrent", "modification", ".", "This", "method", "recovers", "and", "retries", "the", "edit", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/base.py#L250-L275
train
StanfordBioinformatics/loom
server/loomengine_server/api/models/base.py
BaseModel.delete
def delete(self, *args, **kwargs): """ This method implements retries for object deletion. """ count = 0 max_retries=3 while True: try: return super(BaseModel, self).delete(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 1
python
def delete(self, *args, **kwargs): """ This method implements retries for object deletion. """ count = 0 max_retries=3 while True: try: return super(BaseModel, self).delete(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 1
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "count", "=", "0", "max_retries", "=", "3", "while", "True", ":", "try", ":", "return", "super", "(", "BaseModel", ",", "self", ")", ".", "delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "django", ".", "db", ".", "utils", ".", "OperationalError", ":", "if", "count", ">=", "max_retries", ":", "raise", "count", "+=", "1" ]
This method implements retries for object deletion.
[ "This", "method", "implements", "retries", "for", "object", "deletion", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/models/base.py#L277-L289
train
StanfordBioinformatics/loom
client/loomengine/common.py
get_server_type
def get_server_type(): """Checks server.ini for server type.""" server_location_file = os.path.expanduser(SERVER_LOCATION_FILE) if not os.path.exists(server_location_file): raise Exception( "%s not found. Please run 'loom server set " "<servertype>' first." % server_location_file) config = ConfigParser.SafeConfigParser() config.read(server_location_file) server_type = config.get('server', 'type') return server_type
python
def get_server_type(): """Checks server.ini for server type.""" server_location_file = os.path.expanduser(SERVER_LOCATION_FILE) if not os.path.exists(server_location_file): raise Exception( "%s not found. Please run 'loom server set " "<servertype>' first." % server_location_file) config = ConfigParser.SafeConfigParser() config.read(server_location_file) server_type = config.get('server', 'type') return server_type
[ "def", "get_server_type", "(", ")", ":", "server_location_file", "=", "os", ".", "path", ".", "expanduser", "(", "SERVER_LOCATION_FILE", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "server_location_file", ")", ":", "raise", "Exception", "(", "\"%s not found. Please run 'loom server set \"", "\"<servertype>' first.\"", "%", "server_location_file", ")", "config", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "config", ".", "read", "(", "server_location_file", ")", "server_type", "=", "config", ".", "get", "(", "'server'", ",", "'type'", ")", "return", "server_type" ]
Checks server.ini for server type.
[ "Checks", "server", ".", "ini", "for", "server", "type", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/common.py#L110-L120
train
StanfordBioinformatics/loom
utils/loomengine_utils/import_manager.py
ImportManager._set_upload_status
def _set_upload_status(self, file_data_object, upload_status): """ Set file_data_object.file_resource.upload_status """ uuid = file_data_object['uuid'] return self.connection.update_data_object( uuid, {'uuid': uuid, 'value': { 'upload_status': upload_status}} )
python
def _set_upload_status(self, file_data_object, upload_status): """ Set file_data_object.file_resource.upload_status """ uuid = file_data_object['uuid'] return self.connection.update_data_object( uuid, {'uuid': uuid, 'value': { 'upload_status': upload_status}} )
[ "def", "_set_upload_status", "(", "self", ",", "file_data_object", ",", "upload_status", ")", ":", "uuid", "=", "file_data_object", "[", "'uuid'", "]", "return", "self", ".", "connection", ".", "update_data_object", "(", "uuid", ",", "{", "'uuid'", ":", "uuid", ",", "'value'", ":", "{", "'upload_status'", ":", "upload_status", "}", "}", ")" ]
Set file_data_object.file_resource.upload_status
[ "Set", "file_data_object", ".", "file_resource", ".", "upload_status" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/utils/loomengine_utils/import_manager.py#L406-L413
train
StanfordBioinformatics/loom
utils/loomengine_utils/import_manager.py
ImportManager._substitute_file_uuids_throughout_template
def _substitute_file_uuids_throughout_template(self, template, file_dependencies): """Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That way templates have a preference to connect to files nested under their ".dependencies" over files that were previously imported to the server. """ if not isinstance(template, dict): # Nothing to do if this is a reference to a previously imported template. return for input in template.get('inputs', []): self._substitute_file_uuids_in_input(input, file_dependencies) for step in template.get('steps', []): self._substitute_file_uuids_throughout_template(step, file_dependencies)
python
def _substitute_file_uuids_throughout_template(self, template, file_dependencies): """Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That way templates have a preference to connect to files nested under their ".dependencies" over files that were previously imported to the server. """ if not isinstance(template, dict): # Nothing to do if this is a reference to a previously imported template. return for input in template.get('inputs', []): self._substitute_file_uuids_in_input(input, file_dependencies) for step in template.get('steps', []): self._substitute_file_uuids_throughout_template(step, file_dependencies)
[ "def", "_substitute_file_uuids_throughout_template", "(", "self", ",", "template", ",", "file_dependencies", ")", ":", "if", "not", "isinstance", "(", "template", ",", "dict", ")", ":", "# Nothing to do if this is a reference to a previously imported template.", "return", "for", "input", "in", "template", ".", "get", "(", "'inputs'", ",", "[", "]", ")", ":", "self", ".", "_substitute_file_uuids_in_input", "(", "input", ",", "file_dependencies", ")", "for", "step", "in", "template", ".", "get", "(", "'steps'", ",", "[", "]", ")", ":", "self", ".", "_substitute_file_uuids_throughout_template", "(", "step", ",", "file_dependencies", ")" ]
Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That way templates have a preference to connect to files nested under their ".dependencies" over files that were previously imported to the server.
[ "Anywhere", "in", "template", "that", "refers", "to", "a", "data", "object", "but", "does", "not", "give", "a", "specific", "UUID", "if", "a", "matching", "file", "can", "be", "found", "in", "file_dependencies", "we", "will", "change", "the", "data", "object", "reference", "to", "use", "that", "UUID", ".", "That", "way", "templates", "have", "a", "preference", "to", "connect", "to", "files", "nested", "under", "their", ".", "dependencies", "over", "files", "that", "were", "previously", "imported", "to", "the", "server", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/utils/loomengine_utils/import_manager.py#L614-L627
train
StanfordBioinformatics/loom
client/loomengine/run.py
RunStart._get_inputs
def _get_inputs(self): """Converts command line args into a list of template inputs """ # Convert file inputs to a dict, to make it easier to override # them with commandline inputs file_inputs = self._get_file_inputs() try: jsonschema.validate(file_inputs, file_input_schema) except jsonschema.ValidationError: raise SystemExit("ERROR! Input file was invalid") input_dict = {} for (channel, input_id) in file_inputs.iteritems(): input_dict[channel] = input_id if self.args.inputs: for kv_pair in self.args.inputs: (channel, input_id) = kv_pair.split('=') input_dict[channel] = self._parse_string_to_nested_lists( input_id) inputs = [] for (channel, contents) in input_dict.iteritems(): inputs.append({ 'channel': channel, 'data': { 'contents': contents } }) return inputs
python
def _get_inputs(self): """Converts command line args into a list of template inputs """ # Convert file inputs to a dict, to make it easier to override # them with commandline inputs file_inputs = self._get_file_inputs() try: jsonschema.validate(file_inputs, file_input_schema) except jsonschema.ValidationError: raise SystemExit("ERROR! Input file was invalid") input_dict = {} for (channel, input_id) in file_inputs.iteritems(): input_dict[channel] = input_id if self.args.inputs: for kv_pair in self.args.inputs: (channel, input_id) = kv_pair.split('=') input_dict[channel] = self._parse_string_to_nested_lists( input_id) inputs = [] for (channel, contents) in input_dict.iteritems(): inputs.append({ 'channel': channel, 'data': { 'contents': contents } }) return inputs
[ "def", "_get_inputs", "(", "self", ")", ":", "# Convert file inputs to a dict, to make it easier to override", "# them with commandline inputs", "file_inputs", "=", "self", ".", "_get_file_inputs", "(", ")", "try", ":", "jsonschema", ".", "validate", "(", "file_inputs", ",", "file_input_schema", ")", "except", "jsonschema", ".", "ValidationError", ":", "raise", "SystemExit", "(", "\"ERROR! Input file was invalid\"", ")", "input_dict", "=", "{", "}", "for", "(", "channel", ",", "input_id", ")", "in", "file_inputs", ".", "iteritems", "(", ")", ":", "input_dict", "[", "channel", "]", "=", "input_id", "if", "self", ".", "args", ".", "inputs", ":", "for", "kv_pair", "in", "self", ".", "args", ".", "inputs", ":", "(", "channel", ",", "input_id", ")", "=", "kv_pair", ".", "split", "(", "'='", ")", "input_dict", "[", "channel", "]", "=", "self", ".", "_parse_string_to_nested_lists", "(", "input_id", ")", "inputs", "=", "[", "]", "for", "(", "channel", ",", "contents", ")", "in", "input_dict", ".", "iteritems", "(", ")", ":", "inputs", ".", "append", "(", "{", "'channel'", ":", "channel", ",", "'data'", ":", "{", "'contents'", ":", "contents", "}", "}", ")", "return", "inputs" ]
Converts command line args into a list of template inputs
[ "Converts", "command", "line", "args", "into", "a", "list", "of", "template", "inputs" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/run.py#L113-L141
train
StanfordBioinformatics/loom
client/loomengine/run.py
RunStart._parse_string_to_nested_lists
def _parse_string_to_nested_lists(self, value): """e.g., convert "[[a,b,c],[d,e],[f,g]]" into [["a","b","c"],["d","e"],["f","g"]] """ if not re.match(r'\[.*\]', value.strip()): if '[' in value or ']' in value or ',' in value: raise Exception('Missing outer brace') elif len(value.strip()) == 0: raise Exception('Missing value') else: terms = value.split(',') terms = [term.strip() for term in terms] if len(terms) == 1: return terms[0] else: return terms # remove outer braces value = value[1:-1] terms = [] depth = 0 leftmost = 0 first_open_brace = None break_on_commas = False for i in range(len(value)): if value[i] == ',' and depth == 0: terms.append( self._parse_string_to_nested_lists(value[leftmost:i])) leftmost = i+1 if value[i] == '[': if first_open_brace is None: first_open_brace = i depth += 1 if value[i] == ']': depth -= 1 if depth < 0: raise Exception('Unbalanced close brace') i += i if depth > 0: raise Exception('Expected "]"') terms.append( self._parse_string_to_nested_lists(value[leftmost:len(value)])) return terms
python
def _parse_string_to_nested_lists(self, value): """e.g., convert "[[a,b,c],[d,e],[f,g]]" into [["a","b","c"],["d","e"],["f","g"]] """ if not re.match(r'\[.*\]', value.strip()): if '[' in value or ']' in value or ',' in value: raise Exception('Missing outer brace') elif len(value.strip()) == 0: raise Exception('Missing value') else: terms = value.split(',') terms = [term.strip() for term in terms] if len(terms) == 1: return terms[0] else: return terms # remove outer braces value = value[1:-1] terms = [] depth = 0 leftmost = 0 first_open_brace = None break_on_commas = False for i in range(len(value)): if value[i] == ',' and depth == 0: terms.append( self._parse_string_to_nested_lists(value[leftmost:i])) leftmost = i+1 if value[i] == '[': if first_open_brace is None: first_open_brace = i depth += 1 if value[i] == ']': depth -= 1 if depth < 0: raise Exception('Unbalanced close brace') i += i if depth > 0: raise Exception('Expected "]"') terms.append( self._parse_string_to_nested_lists(value[leftmost:len(value)])) return terms
[ "def", "_parse_string_to_nested_lists", "(", "self", ",", "value", ")", ":", "if", "not", "re", ".", "match", "(", "r'\\[.*\\]'", ",", "value", ".", "strip", "(", ")", ")", ":", "if", "'['", "in", "value", "or", "']'", "in", "value", "or", "','", "in", "value", ":", "raise", "Exception", "(", "'Missing outer brace'", ")", "elif", "len", "(", "value", ".", "strip", "(", ")", ")", "==", "0", ":", "raise", "Exception", "(", "'Missing value'", ")", "else", ":", "terms", "=", "value", ".", "split", "(", "','", ")", "terms", "=", "[", "term", ".", "strip", "(", ")", "for", "term", "in", "terms", "]", "if", "len", "(", "terms", ")", "==", "1", ":", "return", "terms", "[", "0", "]", "else", ":", "return", "terms", "# remove outer braces", "value", "=", "value", "[", "1", ":", "-", "1", "]", "terms", "=", "[", "]", "depth", "=", "0", "leftmost", "=", "0", "first_open_brace", "=", "None", "break_on_commas", "=", "False", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "if", "value", "[", "i", "]", "==", "','", "and", "depth", "==", "0", ":", "terms", ".", "append", "(", "self", ".", "_parse_string_to_nested_lists", "(", "value", "[", "leftmost", ":", "i", "]", ")", ")", "leftmost", "=", "i", "+", "1", "if", "value", "[", "i", "]", "==", "'['", ":", "if", "first_open_brace", "is", "None", ":", "first_open_brace", "=", "i", "depth", "+=", "1", "if", "value", "[", "i", "]", "==", "']'", ":", "depth", "-=", "1", "if", "depth", "<", "0", ":", "raise", "Exception", "(", "'Unbalanced close brace'", ")", "i", "+=", "i", "if", "depth", ">", "0", ":", "raise", "Exception", "(", "'Expected \"]\"'", ")", "terms", ".", "append", "(", "self", ".", "_parse_string_to_nested_lists", "(", "value", "[", "leftmost", ":", "len", "(", "value", ")", "]", ")", ")", "return", "terms" ]
e.g., convert "[[a,b,c],[d,e],[f,g]]" into [["a","b","c"],["d","e"],["f","g"]]
[ "e", ".", "g", ".", "convert", "[[", "a", "b", "c", "]", "[", "d", "e", "]", "[", "f", "g", "]]", "into", "[[", "a", "b", "c", "]", "[", "d", "e", "]", "[", "f", "g", "]]" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/run.py#L179-L221
train
StanfordBioinformatics/loom
client/loomengine/run.py
RunRestart._get_inputs
def _get_inputs(self, old_inputs): """Converts command line args into a list of template inputs """ # Convert inputs to dict to facilitate overriding by channel name # Also, drop DataNode ID and keep only contents. input_dict = {} for input in old_inputs: # Strip out DataNode UUID and URL input['data'] = {'contents': input['data']['contents']} input_dict[input['channel']] = input file_inputs = self._get_file_inputs() try: jsonschema.validate(file_inputs, file_input_schema) except jsonschema.ValidationError: raise SystemExit("ERROR! User inputs file is not valid") for (channel, input_id) in file_inputs.iteritems(): input_dict[channel] = { 'channel': channel, 'data': {'contents': input_id} } # Override with cli user inputs if specified if self.args.inputs: for kv_pair in self.args.inputs: (channel, input_id) = kv_pair.split('=') input_dict[channel] = { 'channel': channel, 'data': { 'contents': self._parse_string_to_nested_lists(input_id)} } return input_dict.values()
python
def _get_inputs(self, old_inputs): """Converts command line args into a list of template inputs """ # Convert inputs to dict to facilitate overriding by channel name # Also, drop DataNode ID and keep only contents. input_dict = {} for input in old_inputs: # Strip out DataNode UUID and URL input['data'] = {'contents': input['data']['contents']} input_dict[input['channel']] = input file_inputs = self._get_file_inputs() try: jsonschema.validate(file_inputs, file_input_schema) except jsonschema.ValidationError: raise SystemExit("ERROR! User inputs file is not valid") for (channel, input_id) in file_inputs.iteritems(): input_dict[channel] = { 'channel': channel, 'data': {'contents': input_id} } # Override with cli user inputs if specified if self.args.inputs: for kv_pair in self.args.inputs: (channel, input_id) = kv_pair.split('=') input_dict[channel] = { 'channel': channel, 'data': { 'contents': self._parse_string_to_nested_lists(input_id)} } return input_dict.values()
[ "def", "_get_inputs", "(", "self", ",", "old_inputs", ")", ":", "# Convert inputs to dict to facilitate overriding by channel name", "# Also, drop DataNode ID and keep only contents.", "input_dict", "=", "{", "}", "for", "input", "in", "old_inputs", ":", "# Strip out DataNode UUID and URL", "input", "[", "'data'", "]", "=", "{", "'contents'", ":", "input", "[", "'data'", "]", "[", "'contents'", "]", "}", "input_dict", "[", "input", "[", "'channel'", "]", "]", "=", "input", "file_inputs", "=", "self", ".", "_get_file_inputs", "(", ")", "try", ":", "jsonschema", ".", "validate", "(", "file_inputs", ",", "file_input_schema", ")", "except", "jsonschema", ".", "ValidationError", ":", "raise", "SystemExit", "(", "\"ERROR! User inputs file is not valid\"", ")", "for", "(", "channel", ",", "input_id", ")", "in", "file_inputs", ".", "iteritems", "(", ")", ":", "input_dict", "[", "channel", "]", "=", "{", "'channel'", ":", "channel", ",", "'data'", ":", "{", "'contents'", ":", "input_id", "}", "}", "# Override with cli user inputs if specified", "if", "self", ".", "args", ".", "inputs", ":", "for", "kv_pair", "in", "self", ".", "args", ".", "inputs", ":", "(", "channel", ",", "input_id", ")", "=", "kv_pair", ".", "split", "(", "'='", ")", "input_dict", "[", "channel", "]", "=", "{", "'channel'", ":", "channel", ",", "'data'", ":", "{", "'contents'", ":", "self", ".", "_parse_string_to_nested_lists", "(", "input_id", ")", "}", "}", "return", "input_dict", ".", "values", "(", ")" ]
Converts command line args into a list of template inputs
[ "Converts", "command", "line", "args", "into", "a", "list", "of", "template", "inputs" ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/run.py#L285-L316
train
StanfordBioinformatics/loom
server/loomengine_server/api/serializers/__init__.py
CreateWithParentModelSerializer.create
def create(self, validated_data): """ This is a standard method called indirectly by calling 'save' on the serializer. This method expects the 'parent_field' and 'parent_instance' to be included in the Serializer context. """ if self.context.get('parent_field') \ and self.context.get('parent_instance'): validated_data.update({ self.context.get('parent_field'): self.context.get('parent_instance')}) instance = self.Meta.model(**validated_data) instance.full_clean() instance.save() return instance
python
def create(self, validated_data): """ This is a standard method called indirectly by calling 'save' on the serializer. This method expects the 'parent_field' and 'parent_instance' to be included in the Serializer context. """ if self.context.get('parent_field') \ and self.context.get('parent_instance'): validated_data.update({ self.context.get('parent_field'): self.context.get('parent_instance')}) instance = self.Meta.model(**validated_data) instance.full_clean() instance.save() return instance
[ "def", "create", "(", "self", ",", "validated_data", ")", ":", "if", "self", ".", "context", ".", "get", "(", "'parent_field'", ")", "and", "self", ".", "context", ".", "get", "(", "'parent_instance'", ")", ":", "validated_data", ".", "update", "(", "{", "self", ".", "context", ".", "get", "(", "'parent_field'", ")", ":", "self", ".", "context", ".", "get", "(", "'parent_instance'", ")", "}", ")", "instance", "=", "self", ".", "Meta", ".", "model", "(", "*", "*", "validated_data", ")", "instance", ".", "full_clean", "(", ")", "instance", ".", "save", "(", ")", "return", "instance" ]
This is a standard method called indirectly by calling 'save' on the serializer. This method expects the 'parent_field' and 'parent_instance' to be included in the Serializer context.
[ "This", "is", "a", "standard", "method", "called", "indirectly", "by", "calling", "save", "on", "the", "serializer", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/server/loomengine_server/api/serializers/__init__.py#L42-L57
train
StanfordBioinformatics/loom
utils/loomengine_utils/connection.py
disable_insecure_request_warning
def disable_insecure_request_warning(): """Suppress warning about untrusted SSL certificate.""" import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
python
def disable_insecure_request_warning(): """Suppress warning about untrusted SSL certificate.""" import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
[ "def", "disable_insecure_request_warning", "(", ")", ":", "import", "requests", "from", "requests", ".", "packages", ".", "urllib3", ".", "exceptions", "import", "InsecureRequestWarning", "requests", ".", "packages", ".", "urllib3", ".", "disable_warnings", "(", "InsecureRequestWarning", ")" ]
Suppress warning about untrusted SSL certificate.
[ "Suppress", "warning", "about", "untrusted", "SSL", "certificate", "." ]
db2031a1a87124fee1aeb7414a668c03d774a698
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/utils/loomengine_utils/connection.py#L14-L18
train