repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_release_kids | def avl_release_kids(node):
"""
splits a node from its kids maintaining parent pointers
"""
left, right = node.left, node.right
if left is not None:
# assert left.parent is node
left.parent = None
if right is not None:
# assert right.parent is node
right.parent = None
node.balance = 0
node.left = None
node.right = None
return node, left, right | python | def avl_release_kids(node):
"""
splits a node from its kids maintaining parent pointers
"""
left, right = node.left, node.right
if left is not None:
# assert left.parent is node
left.parent = None
if right is not None:
# assert right.parent is node
right.parent = None
node.balance = 0
node.left = None
node.right = None
return node, left, right | [
"def",
"avl_release_kids",
"(",
"node",
")",
":",
"left",
",",
"right",
"=",
"node",
".",
"left",
",",
"node",
".",
"right",
"if",
"left",
"is",
"not",
"None",
":",
"# assert left.parent is node",
"left",
".",
"parent",
"=",
"None",
"if",
"right",
"is",
"not",
"None",
":",
"# assert right.parent is node",
"right",
".",
"parent",
"=",
"None",
"node",
".",
"balance",
"=",
"0",
"node",
".",
"left",
"=",
"None",
"node",
".",
"right",
"=",
"None",
"return",
"node",
",",
"left",
",",
"right"
] | splits a node from its kids maintaining parent pointers | [
"splits",
"a",
"node",
"from",
"its",
"kids",
"maintaining",
"parent",
"pointers"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L500-L514 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_release_parent | def avl_release_parent(node):
"""
removes the parent of a child
"""
parent = node.parent
if parent is not None:
if parent.right is node:
parent.right = None
elif parent.left is node:
parent.left = None
else:
raise AssertionError('impossible state')
node.parent = None
parent.balance = max(height(parent.right), height(parent.left)) + 1
return node, parent | python | def avl_release_parent(node):
"""
removes the parent of a child
"""
parent = node.parent
if parent is not None:
if parent.right is node:
parent.right = None
elif parent.left is node:
parent.left = None
else:
raise AssertionError('impossible state')
node.parent = None
parent.balance = max(height(parent.right), height(parent.left)) + 1
return node, parent | [
"def",
"avl_release_parent",
"(",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"parent",
"is",
"not",
"None",
":",
"if",
"parent",
".",
"right",
"is",
"node",
":",
"parent",
".",
"right",
"=",
"None",
"elif",
"parent",
".",
"left",
"is",
"node",
":",
"parent",
".",
"left",
"=",
"None",
"else",
":",
"raise",
"AssertionError",
"(",
"'impossible state'",
")",
"node",
".",
"parent",
"=",
"None",
"parent",
".",
"balance",
"=",
"max",
"(",
"height",
"(",
"parent",
".",
"right",
")",
",",
"height",
"(",
"parent",
".",
"left",
")",
")",
"+",
"1",
"return",
"node",
",",
"parent"
] | removes the parent of a child | [
"removes",
"the",
"parent",
"of",
"a",
"child"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L517-L531 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_join | def avl_join(t1, t2, node):
"""
Joins two trees `t1` and `t1` with an intermediate key-value pair
CommandLine:
python -m utool.experimental.euler_tour_tree_avl avl_join
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['a', 'b', 'c', 'b', 'd', 'b', 'a'])
>>> other = EulerTourTree(['E', 'F', 'G', 'F', 'E'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> self.print_tree()
>>> other.print_tree()
>>> new.print_tree()
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'])
>>> other = EulerTourTree(['X'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> ut.qtensure()
>>> #self.show_nx(fnum=1)
>>> #other.show_nx(fnum=2)
>>> new.show_nx()
Running Time:
O(abs(r(t1) - r(t2)))
O(abs(height(t1) - height(t2)))
"""
if DEBUG_JOIN:
print('-- JOIN node=%r' % (node,))
if t1 is None and t2 is None:
if DEBUG_JOIN:
print('Join Case 1')
top = node
elif t1 is None:
# FIXME keep track of count if possible
if DEBUG_JOIN:
print('Join Case 2')
top = avl_insert_dir(t2, node, 0)
elif t2 is None:
if DEBUG_JOIN:
print('Join Case 3')
top = avl_insert_dir(t1, node, 1)
else:
h1 = height(t1)
h2 = height(t2)
if h1 > h2 + 1:
if DEBUG_JOIN:
print('Join Case 4')
top = avl_join_dir_recursive(t1, t2, node, 1)
if DEBUG_JOIN:
ascii_tree(t1, 'top')
elif h2 > h1 + 1:
if DEBUG_JOIN:
print('Join Case 5')
ascii_tree(t1)
ascii_tree(t2)
top = avl_join_dir_recursive(t1, t2, node, 0)
if DEBUG_JOIN:
ascii_tree(top)
else:
if DEBUG_JOIN:
print('Join Case 6')
# Insert at the top of the tree
top = avl_new_top(t1, t2, node, 0)
return top | python | def avl_join(t1, t2, node):
"""
Joins two trees `t1` and `t1` with an intermediate key-value pair
CommandLine:
python -m utool.experimental.euler_tour_tree_avl avl_join
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['a', 'b', 'c', 'b', 'd', 'b', 'a'])
>>> other = EulerTourTree(['E', 'F', 'G', 'F', 'E'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> self.print_tree()
>>> other.print_tree()
>>> new.print_tree()
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'])
>>> other = EulerTourTree(['X'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> ut.qtensure()
>>> #self.show_nx(fnum=1)
>>> #other.show_nx(fnum=2)
>>> new.show_nx()
Running Time:
O(abs(r(t1) - r(t2)))
O(abs(height(t1) - height(t2)))
"""
if DEBUG_JOIN:
print('-- JOIN node=%r' % (node,))
if t1 is None and t2 is None:
if DEBUG_JOIN:
print('Join Case 1')
top = node
elif t1 is None:
# FIXME keep track of count if possible
if DEBUG_JOIN:
print('Join Case 2')
top = avl_insert_dir(t2, node, 0)
elif t2 is None:
if DEBUG_JOIN:
print('Join Case 3')
top = avl_insert_dir(t1, node, 1)
else:
h1 = height(t1)
h2 = height(t2)
if h1 > h2 + 1:
if DEBUG_JOIN:
print('Join Case 4')
top = avl_join_dir_recursive(t1, t2, node, 1)
if DEBUG_JOIN:
ascii_tree(t1, 'top')
elif h2 > h1 + 1:
if DEBUG_JOIN:
print('Join Case 5')
ascii_tree(t1)
ascii_tree(t2)
top = avl_join_dir_recursive(t1, t2, node, 0)
if DEBUG_JOIN:
ascii_tree(top)
else:
if DEBUG_JOIN:
print('Join Case 6')
# Insert at the top of the tree
top = avl_new_top(t1, t2, node, 0)
return top | [
"def",
"avl_join",
"(",
"t1",
",",
"t2",
",",
"node",
")",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'-- JOIN node=%r'",
"%",
"(",
"node",
",",
")",
")",
"if",
"t1",
"is",
"None",
"and",
"t2",
"is",
"None",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 1'",
")",
"top",
"=",
"node",
"elif",
"t1",
"is",
"None",
":",
"# FIXME keep track of count if possible",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 2'",
")",
"top",
"=",
"avl_insert_dir",
"(",
"t2",
",",
"node",
",",
"0",
")",
"elif",
"t2",
"is",
"None",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 3'",
")",
"top",
"=",
"avl_insert_dir",
"(",
"t1",
",",
"node",
",",
"1",
")",
"else",
":",
"h1",
"=",
"height",
"(",
"t1",
")",
"h2",
"=",
"height",
"(",
"t2",
")",
"if",
"h1",
">",
"h2",
"+",
"1",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 4'",
")",
"top",
"=",
"avl_join_dir_recursive",
"(",
"t1",
",",
"t2",
",",
"node",
",",
"1",
")",
"if",
"DEBUG_JOIN",
":",
"ascii_tree",
"(",
"t1",
",",
"'top'",
")",
"elif",
"h2",
">",
"h1",
"+",
"1",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 5'",
")",
"ascii_tree",
"(",
"t1",
")",
"ascii_tree",
"(",
"t2",
")",
"top",
"=",
"avl_join_dir_recursive",
"(",
"t1",
",",
"t2",
",",
"node",
",",
"0",
")",
"if",
"DEBUG_JOIN",
":",
"ascii_tree",
"(",
"top",
")",
"else",
":",
"if",
"DEBUG_JOIN",
":",
"print",
"(",
"'Join Case 6'",
")",
"# Insert at the top of the tree",
"top",
"=",
"avl_new_top",
"(",
"t1",
",",
"t2",
",",
"node",
",",
"0",
")",
"return",
"top"
] | Joins two trees `t1` and `t1` with an intermediate key-value pair
CommandLine:
python -m utool.experimental.euler_tour_tree_avl avl_join
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['a', 'b', 'c', 'b', 'd', 'b', 'a'])
>>> other = EulerTourTree(['E', 'F', 'G', 'F', 'E'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> self.print_tree()
>>> other.print_tree()
>>> new.print_tree()
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> self = EulerTourTree(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'])
>>> other = EulerTourTree(['X'])
>>> node = Node(value='Q')
>>> root = avl_join(self.root, other.root, node)
>>> new = EulerTourTree(root=root)
>>> print('new = %r' % (new,))
>>> ut.quit_if_noshow()
>>> ut.qtensure()
>>> #self.show_nx(fnum=1)
>>> #other.show_nx(fnum=2)
>>> new.show_nx()
Running Time:
O(abs(r(t1) - r(t2)))
O(abs(height(t1) - height(t2))) | [
"Joins",
"two",
"trees",
"t1",
"and",
"t1",
"with",
"an",
"intermediate",
"key",
"-",
"value",
"pair"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L667-L746 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_split_last | def avl_split_last(root):
"""
Removes the maximum element from the tree
Returns:
tuple: new_root, last_node
O(log(n)) = O(height(root))
"""
if root is None:
raise IndexError('Empty tree has no maximum element')
root, left, right = avl_release_kids(root)
if right is None:
new_root, last_node = left, root
else:
new_right, last_node = avl_split_last(right)
new_root = avl_join(left, new_right, root)
return (new_root, last_node) | python | def avl_split_last(root):
"""
Removes the maximum element from the tree
Returns:
tuple: new_root, last_node
O(log(n)) = O(height(root))
"""
if root is None:
raise IndexError('Empty tree has no maximum element')
root, left, right = avl_release_kids(root)
if right is None:
new_root, last_node = left, root
else:
new_right, last_node = avl_split_last(right)
new_root = avl_join(left, new_right, root)
return (new_root, last_node) | [
"def",
"avl_split_last",
"(",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'Empty tree has no maximum element'",
")",
"root",
",",
"left",
",",
"right",
"=",
"avl_release_kids",
"(",
"root",
")",
"if",
"right",
"is",
"None",
":",
"new_root",
",",
"last_node",
"=",
"left",
",",
"root",
"else",
":",
"new_right",
",",
"last_node",
"=",
"avl_split_last",
"(",
"right",
")",
"new_root",
"=",
"avl_join",
"(",
"left",
",",
"new_right",
",",
"root",
")",
"return",
"(",
"new_root",
",",
"last_node",
")"
] | Removes the maximum element from the tree
Returns:
tuple: new_root, last_node
O(log(n)) = O(height(root)) | [
"Removes",
"the",
"maximum",
"element",
"from",
"the",
"tree"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L749-L766 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_split_first | def avl_split_first(root):
"""
Removes the minimum element from the tree
Returns:
tuple: new_root, first_node
O(log(n)) = O(height(root))
"""
if root is None:
raise IndexError('Empty tree has no maximum element')
root, left, right = avl_release_kids(root)
if left is None:
new_root, first_node = right, root
else:
new_left, first_node = avl_split_first(left)
new_root = avl_join(new_left, right, root)
return (new_root, first_node) | python | def avl_split_first(root):
"""
Removes the minimum element from the tree
Returns:
tuple: new_root, first_node
O(log(n)) = O(height(root))
"""
if root is None:
raise IndexError('Empty tree has no maximum element')
root, left, right = avl_release_kids(root)
if left is None:
new_root, first_node = right, root
else:
new_left, first_node = avl_split_first(left)
new_root = avl_join(new_left, right, root)
return (new_root, first_node) | [
"def",
"avl_split_first",
"(",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'Empty tree has no maximum element'",
")",
"root",
",",
"left",
",",
"right",
"=",
"avl_release_kids",
"(",
"root",
")",
"if",
"left",
"is",
"None",
":",
"new_root",
",",
"first_node",
"=",
"right",
",",
"root",
"else",
":",
"new_left",
",",
"first_node",
"=",
"avl_split_first",
"(",
"left",
")",
"new_root",
"=",
"avl_join",
"(",
"new_left",
",",
"right",
",",
"root",
")",
"return",
"(",
"new_root",
",",
"first_node",
")"
] | Removes the minimum element from the tree
Returns:
tuple: new_root, first_node
O(log(n)) = O(height(root)) | [
"Removes",
"the",
"minimum",
"element",
"from",
"the",
"tree"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L769-L786 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | avl_join2 | def avl_join2(t1, t2):
"""
join two trees without any intermediate key
Returns:
Node: new_root
O(log(n) + log(m)) = O(r(t1) + r(t2))
For AVL-Trees the rank r(t1) = height(t1) - 1
"""
if t1 is None and t2 is None:
new_root = None
elif t2 is None:
new_root = t1
elif t1 is None:
new_root = t2
else:
new_left, last_node = avl_split_last(t1)
debug = 0
if debug:
EulerTourTree(root=new_left)._assert_nodes('new_left')
EulerTourTree(root=last_node)._assert_nodes('last_node')
EulerTourTree(root=t2)._assert_nodes('t2')
print('new_left')
EulerTourTree(root=new_left).print_tree()
print('last_node')
EulerTourTree(root=last_node).print_tree()
print('t2')
EulerTourTree(root=t2).print_tree()
new_root = avl_join(new_left, t2, last_node)
if debug:
print('new_root')
EulerTourTree(root=new_root).print_tree()
EulerTourTree(root=last_node)._assert_nodes('new_root')
return new_root | python | def avl_join2(t1, t2):
"""
join two trees without any intermediate key
Returns:
Node: new_root
O(log(n) + log(m)) = O(r(t1) + r(t2))
For AVL-Trees the rank r(t1) = height(t1) - 1
"""
if t1 is None and t2 is None:
new_root = None
elif t2 is None:
new_root = t1
elif t1 is None:
new_root = t2
else:
new_left, last_node = avl_split_last(t1)
debug = 0
if debug:
EulerTourTree(root=new_left)._assert_nodes('new_left')
EulerTourTree(root=last_node)._assert_nodes('last_node')
EulerTourTree(root=t2)._assert_nodes('t2')
print('new_left')
EulerTourTree(root=new_left).print_tree()
print('last_node')
EulerTourTree(root=last_node).print_tree()
print('t2')
EulerTourTree(root=t2).print_tree()
new_root = avl_join(new_left, t2, last_node)
if debug:
print('new_root')
EulerTourTree(root=new_root).print_tree()
EulerTourTree(root=last_node)._assert_nodes('new_root')
return new_root | [
"def",
"avl_join2",
"(",
"t1",
",",
"t2",
")",
":",
"if",
"t1",
"is",
"None",
"and",
"t2",
"is",
"None",
":",
"new_root",
"=",
"None",
"elif",
"t2",
"is",
"None",
":",
"new_root",
"=",
"t1",
"elif",
"t1",
"is",
"None",
":",
"new_root",
"=",
"t2",
"else",
":",
"new_left",
",",
"last_node",
"=",
"avl_split_last",
"(",
"t1",
")",
"debug",
"=",
"0",
"if",
"debug",
":",
"EulerTourTree",
"(",
"root",
"=",
"new_left",
")",
".",
"_assert_nodes",
"(",
"'new_left'",
")",
"EulerTourTree",
"(",
"root",
"=",
"last_node",
")",
".",
"_assert_nodes",
"(",
"'last_node'",
")",
"EulerTourTree",
"(",
"root",
"=",
"t2",
")",
".",
"_assert_nodes",
"(",
"'t2'",
")",
"print",
"(",
"'new_left'",
")",
"EulerTourTree",
"(",
"root",
"=",
"new_left",
")",
".",
"print_tree",
"(",
")",
"print",
"(",
"'last_node'",
")",
"EulerTourTree",
"(",
"root",
"=",
"last_node",
")",
".",
"print_tree",
"(",
")",
"print",
"(",
"'t2'",
")",
"EulerTourTree",
"(",
"root",
"=",
"t2",
")",
".",
"print_tree",
"(",
")",
"new_root",
"=",
"avl_join",
"(",
"new_left",
",",
"t2",
",",
"last_node",
")",
"if",
"debug",
":",
"print",
"(",
"'new_root'",
")",
"EulerTourTree",
"(",
"root",
"=",
"new_root",
")",
".",
"print_tree",
"(",
")",
"EulerTourTree",
"(",
"root",
"=",
"last_node",
")",
".",
"_assert_nodes",
"(",
"'new_root'",
")",
"return",
"new_root"
] | join two trees without any intermediate key
Returns:
Node: new_root
O(log(n) + log(m)) = O(r(t1) + r(t2))
For AVL-Trees the rank r(t1) = height(t1) - 1 | [
"join",
"two",
"trees",
"without",
"any",
"intermediate",
"key"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L789-L831 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | EulerTourTree.to_networkx | def to_networkx(self, labels=None, edge_labels=False):
""" Get a networkx representation of the binary search tree. """
import networkx as nx
graph = nx.DiGraph()
for node in self._traverse_nodes():
u = node.key
graph.add_node(u) # Minor redundancy
# Set node properties
graph.nodes[u]['value'] = node.value
if labels is not None:
label = ','.join([str(getattr(node, k)) for k in labels])
graph.nodes[u]['label'] = label
if node.left is not None:
v = node.left.key
graph.add_node(v)
graph.add_edge(u, v)
if edge_labels:
graph.edge[u][v]['label'] = 'L'
if node.right is not None:
v = node.right.key
graph.add_node(v)
graph.add_edge(u, v)
if edge_labels:
graph.edge[u][v]['label'] = 'R'
return graph | python | def to_networkx(self, labels=None, edge_labels=False):
""" Get a networkx representation of the binary search tree. """
import networkx as nx
graph = nx.DiGraph()
for node in self._traverse_nodes():
u = node.key
graph.add_node(u) # Minor redundancy
# Set node properties
graph.nodes[u]['value'] = node.value
if labels is not None:
label = ','.join([str(getattr(node, k)) for k in labels])
graph.nodes[u]['label'] = label
if node.left is not None:
v = node.left.key
graph.add_node(v)
graph.add_edge(u, v)
if edge_labels:
graph.edge[u][v]['label'] = 'L'
if node.right is not None:
v = node.right.key
graph.add_node(v)
graph.add_edge(u, v)
if edge_labels:
graph.edge[u][v]['label'] = 'R'
return graph | [
"def",
"to_networkx",
"(",
"self",
",",
"labels",
"=",
"None",
",",
"edge_labels",
"=",
"False",
")",
":",
"import",
"networkx",
"as",
"nx",
"graph",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"for",
"node",
"in",
"self",
".",
"_traverse_nodes",
"(",
")",
":",
"u",
"=",
"node",
".",
"key",
"graph",
".",
"add_node",
"(",
"u",
")",
"# Minor redundancy",
"# Set node properties",
"graph",
".",
"nodes",
"[",
"u",
"]",
"[",
"'value'",
"]",
"=",
"node",
".",
"value",
"if",
"labels",
"is",
"not",
"None",
":",
"label",
"=",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"getattr",
"(",
"node",
",",
"k",
")",
")",
"for",
"k",
"in",
"labels",
"]",
")",
"graph",
".",
"nodes",
"[",
"u",
"]",
"[",
"'label'",
"]",
"=",
"label",
"if",
"node",
".",
"left",
"is",
"not",
"None",
":",
"v",
"=",
"node",
".",
"left",
".",
"key",
"graph",
".",
"add_node",
"(",
"v",
")",
"graph",
".",
"add_edge",
"(",
"u",
",",
"v",
")",
"if",
"edge_labels",
":",
"graph",
".",
"edge",
"[",
"u",
"]",
"[",
"v",
"]",
"[",
"'label'",
"]",
"=",
"'L'",
"if",
"node",
".",
"right",
"is",
"not",
"None",
":",
"v",
"=",
"node",
".",
"right",
".",
"key",
"graph",
".",
"add_node",
"(",
"v",
")",
"graph",
".",
"add_edge",
"(",
"u",
",",
"v",
")",
"if",
"edge_labels",
":",
"graph",
".",
"edge",
"[",
"u",
"]",
"[",
"v",
"]",
"[",
"'label'",
"]",
"=",
"'R'",
"return",
"graph"
] | Get a networkx representation of the binary search tree. | [
"Get",
"a",
"networkx",
"representation",
"of",
"the",
"binary",
"search",
"tree",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L395-L419 | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | EulerTourTree.repr_tree | def repr_tree(self):
"""
reconstruct represented tree as a DiGraph to
preserve the current rootedness
"""
import utool as ut
import networkx as nx
repr_tree = nx.DiGraph()
for u, v in ut.itertwo(self.values()):
if not repr_tree.has_edge(v, u):
repr_tree.add_edge(u, v)
return repr_tree | python | def repr_tree(self):
"""
reconstruct represented tree as a DiGraph to
preserve the current rootedness
"""
import utool as ut
import networkx as nx
repr_tree = nx.DiGraph()
for u, v in ut.itertwo(self.values()):
if not repr_tree.has_edge(v, u):
repr_tree.add_edge(u, v)
return repr_tree | [
"def",
"repr_tree",
"(",
"self",
")",
":",
"import",
"utool",
"as",
"ut",
"import",
"networkx",
"as",
"nx",
"repr_tree",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"for",
"u",
",",
"v",
"in",
"ut",
".",
"itertwo",
"(",
"self",
".",
"values",
"(",
")",
")",
":",
"if",
"not",
"repr_tree",
".",
"has_edge",
"(",
"v",
",",
"u",
")",
":",
"repr_tree",
".",
"add_edge",
"(",
"u",
",",
"v",
")",
"return",
"repr_tree"
] | reconstruct represented tree as a DiGraph to
preserve the current rootedness | [
"reconstruct",
"represented",
"tree",
"as",
"a",
"DiGraph",
"to",
"preserve",
"the",
"current",
"rootedness"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L422-L433 | train |
Erotemic/utool | utool/_internal/meta_util_path.py | unixjoin | def unixjoin(*args):
"""
Like os.path.join, but uses forward slashes on win32
"""
isabs_list = list(map(isabs, args))
if any(isabs_list):
poslist = [count for count, flag in enumerate(isabs_list) if flag]
pos = poslist[-1]
return '/'.join(args[pos:])
else:
return '/'.join(args) | python | def unixjoin(*args):
"""
Like os.path.join, but uses forward slashes on win32
"""
isabs_list = list(map(isabs, args))
if any(isabs_list):
poslist = [count for count, flag in enumerate(isabs_list) if flag]
pos = poslist[-1]
return '/'.join(args[pos:])
else:
return '/'.join(args) | [
"def",
"unixjoin",
"(",
"*",
"args",
")",
":",
"isabs_list",
"=",
"list",
"(",
"map",
"(",
"isabs",
",",
"args",
")",
")",
"if",
"any",
"(",
"isabs_list",
")",
":",
"poslist",
"=",
"[",
"count",
"for",
"count",
",",
"flag",
"in",
"enumerate",
"(",
"isabs_list",
")",
"if",
"flag",
"]",
"pos",
"=",
"poslist",
"[",
"-",
"1",
"]",
"return",
"'/'",
".",
"join",
"(",
"args",
"[",
"pos",
":",
"]",
")",
"else",
":",
"return",
"'/'",
".",
"join",
"(",
"args",
")"
] | Like os.path.join, but uses forward slashes on win32 | [
"Like",
"os",
".",
"path",
".",
"join",
"but",
"uses",
"forward",
"slashes",
"on",
"win32"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/meta_util_path.py#L25-L35 | train |
glormph/msstitch | src/app/actions/pycolator/splitmerge.py | create_merge_psm_map | def create_merge_psm_map(peptides, ns):
"""Loops through peptides, stores sequences mapped to PSM ids."""
psmmap = {}
for peptide in peptides:
seq = reader.get_peptide_seq(peptide, ns)
psm_ids = reader.get_psm_ids_from_peptide(peptide, ns)
for psm_id in psm_ids:
try:
psmmap[seq][psm_id.text] = 1
except KeyError:
psmmap[seq] = {psm_id.text: 2}
for seq, psm_id_dict in psmmap.items():
psmmap[seq] = [x for x in psm_id_dict]
return psmmap | python | def create_merge_psm_map(peptides, ns):
"""Loops through peptides, stores sequences mapped to PSM ids."""
psmmap = {}
for peptide in peptides:
seq = reader.get_peptide_seq(peptide, ns)
psm_ids = reader.get_psm_ids_from_peptide(peptide, ns)
for psm_id in psm_ids:
try:
psmmap[seq][psm_id.text] = 1
except KeyError:
psmmap[seq] = {psm_id.text: 2}
for seq, psm_id_dict in psmmap.items():
psmmap[seq] = [x for x in psm_id_dict]
return psmmap | [
"def",
"create_merge_psm_map",
"(",
"peptides",
",",
"ns",
")",
":",
"psmmap",
"=",
"{",
"}",
"for",
"peptide",
"in",
"peptides",
":",
"seq",
"=",
"reader",
".",
"get_peptide_seq",
"(",
"peptide",
",",
"ns",
")",
"psm_ids",
"=",
"reader",
".",
"get_psm_ids_from_peptide",
"(",
"peptide",
",",
"ns",
")",
"for",
"psm_id",
"in",
"psm_ids",
":",
"try",
":",
"psmmap",
"[",
"seq",
"]",
"[",
"psm_id",
".",
"text",
"]",
"=",
"1",
"except",
"KeyError",
":",
"psmmap",
"[",
"seq",
"]",
"=",
"{",
"psm_id",
".",
"text",
":",
"2",
"}",
"for",
"seq",
",",
"psm_id_dict",
"in",
"psmmap",
".",
"items",
"(",
")",
":",
"psmmap",
"[",
"seq",
"]",
"=",
"[",
"x",
"for",
"x",
"in",
"psm_id_dict",
"]",
"return",
"psmmap"
] | Loops through peptides, stores sequences mapped to PSM ids. | [
"Loops",
"through",
"peptides",
"stores",
"sequences",
"mapped",
"to",
"PSM",
"ids",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/pycolator/splitmerge.py#L8-L21 | train |
samuelcolvin/buildpg | buildpg/asyncpg.py | create_pool_b | def create_pool_b(
dsn=None,
*,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
connection_class=BuildPgConnection,
**connect_kwargs,
):
"""
Create a connection pool.
Can be used either with an ``async with`` block:
Identical to ``asyncpg.create_pool`` except that both the pool and connection have the *_b varients of
``execute``, ``fetch``, ``fetchval``, ``fetchrow`` etc
Arguments are exactly the same as ``asyncpg.create_pool``.
"""
return BuildPgPool(
dsn,
connection_class=connection_class,
min_size=min_size,
max_size=max_size,
max_queries=max_queries,
loop=loop,
setup=setup,
init=init,
max_inactive_connection_lifetime=max_inactive_connection_lifetime,
**connect_kwargs,
) | python | def create_pool_b(
dsn=None,
*,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
connection_class=BuildPgConnection,
**connect_kwargs,
):
"""
Create a connection pool.
Can be used either with an ``async with`` block:
Identical to ``asyncpg.create_pool`` except that both the pool and connection have the *_b varients of
``execute``, ``fetch``, ``fetchval``, ``fetchrow`` etc
Arguments are exactly the same as ``asyncpg.create_pool``.
"""
return BuildPgPool(
dsn,
connection_class=connection_class,
min_size=min_size,
max_size=max_size,
max_queries=max_queries,
loop=loop,
setup=setup,
init=init,
max_inactive_connection_lifetime=max_inactive_connection_lifetime,
**connect_kwargs,
) | [
"def",
"create_pool_b",
"(",
"dsn",
"=",
"None",
",",
"*",
",",
"min_size",
"=",
"10",
",",
"max_size",
"=",
"10",
",",
"max_queries",
"=",
"50000",
",",
"max_inactive_connection_lifetime",
"=",
"300.0",
",",
"setup",
"=",
"None",
",",
"init",
"=",
"None",
",",
"loop",
"=",
"None",
",",
"connection_class",
"=",
"BuildPgConnection",
",",
"*",
"*",
"connect_kwargs",
",",
")",
":",
"return",
"BuildPgPool",
"(",
"dsn",
",",
"connection_class",
"=",
"connection_class",
",",
"min_size",
"=",
"min_size",
",",
"max_size",
"=",
"max_size",
",",
"max_queries",
"=",
"max_queries",
",",
"loop",
"=",
"loop",
",",
"setup",
"=",
"setup",
",",
"init",
"=",
"init",
",",
"max_inactive_connection_lifetime",
"=",
"max_inactive_connection_lifetime",
",",
"*",
"*",
"connect_kwargs",
",",
")"
] | Create a connection pool.
Can be used either with an ``async with`` block:
Identical to ``asyncpg.create_pool`` except that both the pool and connection have the *_b varients of
``execute``, ``fetch``, ``fetchval``, ``fetchrow`` etc
Arguments are exactly the same as ``asyncpg.create_pool``. | [
"Create",
"a",
"connection",
"pool",
"."
] | 33cccff45279834d02ec7e97d8417da8fd2a875d | https://github.com/samuelcolvin/buildpg/blob/33cccff45279834d02ec7e97d8417da8fd2a875d/buildpg/asyncpg.py#L85-L119 | train |
LEMS/pylems | lems/sim/sim.py | Simulation.add_runnable | def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimError('Duplicate runnable component {0}'.format(runnable.id))
self.runnables[runnable.id] = runnable | python | def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimError('Duplicate runnable component {0}'.format(runnable.id))
self.runnables[runnable.id] = runnable | [
"def",
"add_runnable",
"(",
"self",
",",
"runnable",
")",
":",
"if",
"runnable",
".",
"id",
"in",
"self",
".",
"runnables",
":",
"raise",
"SimError",
"(",
"'Duplicate runnable component {0}'",
".",
"format",
"(",
"runnable",
".",
"id",
")",
")",
"self",
".",
"runnables",
"[",
"runnable",
".",
"id",
"]",
"=",
"runnable"
] | Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable | [
"Adds",
"a",
"runnable",
"component",
"to",
"the",
"list",
"of",
"runnable",
"components",
"in",
"this",
"simulation",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/sim.py#L37-L49 | train |
LEMS/pylems | lems/sim/sim.py | Simulation.run | def run(self):
"""
Runs the simulation.
"""
self.init_run()
if self.debug: self.dump("AfterInit: ")
#print("++++++++++++++++ Time: %f"%self.current_time)
while self.step():
#self.dump("Time: %f"%self.current_time)
#print("++++++++++++++++ Time: %f"%self.current_time)
pass | python | def run(self):
"""
Runs the simulation.
"""
self.init_run()
if self.debug: self.dump("AfterInit: ")
#print("++++++++++++++++ Time: %f"%self.current_time)
while self.step():
#self.dump("Time: %f"%self.current_time)
#print("++++++++++++++++ Time: %f"%self.current_time)
pass | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"init_run",
"(",
")",
"if",
"self",
".",
"debug",
":",
"self",
".",
"dump",
"(",
"\"AfterInit: \"",
")",
"#print(\"++++++++++++++++ Time: %f\"%self.current_time)",
"while",
"self",
".",
"step",
"(",
")",
":",
"#self.dump(\"Time: %f\"%self.current_time)",
"#print(\"++++++++++++++++ Time: %f\"%self.current_time)",
"pass"
] | Runs the simulation. | [
"Runs",
"the",
"simulation",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/sim.py#L86-L97 | train |
moluwole/Bast | bast/cli.py | controller_creatr | def controller_creatr(filename):
"""Name of the controller file to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:controller command')
return
path = os.path.abspath('.') + '/controller'
if not os.path.exists(path):
os.makedirs(path)
# if os.path.isfile(path + )
file_name = str(filename + '.py')
if os.path.isfile(path+"/" + file_name):
click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
return
controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n pass"
controller_file.write(compose)
controller_file.close()
click.echo(Fore.GREEN + "Controller " + filename + " created successfully") | python | def controller_creatr(filename):
"""Name of the controller file to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:controller command')
return
path = os.path.abspath('.') + '/controller'
if not os.path.exists(path):
os.makedirs(path)
# if os.path.isfile(path + )
file_name = str(filename + '.py')
if os.path.isfile(path+"/" + file_name):
click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
return
controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n pass"
controller_file.write(compose)
controller_file.close()
click.echo(Fore.GREEN + "Controller " + filename + " created successfully") | [
"def",
"controller_creatr",
"(",
"filename",
")",
":",
"if",
"not",
"check",
"(",
")",
":",
"click",
".",
"echo",
"(",
"Fore",
".",
"RED",
"+",
"'ERROR: Ensure you are in a bast app to run the create:controller command'",
")",
"return",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"+",
"'/controller'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"# if os.path.isfile(path + )",
"file_name",
"=",
"str",
"(",
"filename",
"+",
"'.py'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
"+",
"\"/\"",
"+",
"file_name",
")",
":",
"click",
".",
"echo",
"(",
"Fore",
".",
"WHITE",
"+",
"Back",
".",
"RED",
"+",
"\"ERROR: Controller file exists\"",
")",
"return",
"controller_file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"+",
"'/controller/'",
"+",
"file_name",
",",
"'w+'",
")",
"compose",
"=",
"\"from bast import Controller\\n\\nclass \"",
"+",
"filename",
"+",
"\"(Controller):\\n pass\"",
"controller_file",
".",
"write",
"(",
"compose",
")",
"controller_file",
".",
"close",
"(",
")",
"click",
".",
"echo",
"(",
"Fore",
".",
"GREEN",
"+",
"\"Controller \"",
"+",
"filename",
"+",
"\" created successfully\"",
")"
] | Name of the controller file to be created | [
"Name",
"of",
"the",
"controller",
"file",
"to",
"be",
"created"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/cli.py#L41-L61 | train |
moluwole/Bast | bast/cli.py | view_creatr | def view_creatr(filename):
"""Name of the View File to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command')
return
path = os.path.abspath('.') + '/public/templates'
if not os.path.exists(path):
os.makedirs(path)
filename_ = str(filename + ".html").lower()
view_file = open(path + "/" + filename_, 'w+')
view_file.write("")
view_file.close()
click.echo(Fore.GREEN + "View file " + filename_ + "created in public/template folder") | python | def view_creatr(filename):
"""Name of the View File to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command')
return
path = os.path.abspath('.') + '/public/templates'
if not os.path.exists(path):
os.makedirs(path)
filename_ = str(filename + ".html").lower()
view_file = open(path + "/" + filename_, 'w+')
view_file.write("")
view_file.close()
click.echo(Fore.GREEN + "View file " + filename_ + "created in public/template folder") | [
"def",
"view_creatr",
"(",
"filename",
")",
":",
"if",
"not",
"check",
"(",
")",
":",
"click",
".",
"echo",
"(",
"Fore",
".",
"RED",
"+",
"'ERROR: Ensure you are in a bast app to run the create:view command'",
")",
"return",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"+",
"'/public/templates'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"filename_",
"=",
"str",
"(",
"filename",
"+",
"\".html\"",
")",
".",
"lower",
"(",
")",
"view_file",
"=",
"open",
"(",
"path",
"+",
"\"/\"",
"+",
"filename_",
",",
"'w+'",
")",
"view_file",
".",
"write",
"(",
"\"\"",
")",
"view_file",
".",
"close",
"(",
")",
"click",
".",
"echo",
"(",
"Fore",
".",
"GREEN",
"+",
"\"View file \"",
"+",
"filename_",
"+",
"\"created in public/template folder\"",
")"
] | Name of the View File to be created | [
"Name",
"of",
"the",
"View",
"File",
"to",
"be",
"created"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/cli.py#L85-L99 | train |
moluwole/Bast | bast/cli.py | migration_creatr | def migration_creatr(migration_file, create, table):
"""Name of the migration file"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:migration command')
return
migration = CreateMigration()
if table is None:
table = snake_case(migration_file)
file = migration.create_file(snake_case(migration_file), table=table, create=create)
click.echo(Fore.GREEN + 'Migration file created at %s' % file) | python | def migration_creatr(migration_file, create, table):
"""Name of the migration file"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:migration command')
return
migration = CreateMigration()
if table is None:
table = snake_case(migration_file)
file = migration.create_file(snake_case(migration_file), table=table, create=create)
click.echo(Fore.GREEN + 'Migration file created at %s' % file) | [
"def",
"migration_creatr",
"(",
"migration_file",
",",
"create",
",",
"table",
")",
":",
"if",
"not",
"check",
"(",
")",
":",
"click",
".",
"echo",
"(",
"Fore",
".",
"RED",
"+",
"'ERROR: Ensure you are in a bast app to run the create:migration command'",
")",
"return",
"migration",
"=",
"CreateMigration",
"(",
")",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"snake_case",
"(",
"migration_file",
")",
"file",
"=",
"migration",
".",
"create_file",
"(",
"snake_case",
"(",
"migration_file",
")",
",",
"table",
"=",
"table",
",",
"create",
"=",
"create",
")",
"click",
".",
"echo",
"(",
"Fore",
".",
"GREEN",
"+",
"'Migration file created at %s'",
"%",
"file",
")"
] | Name of the migration file | [
"Name",
"of",
"the",
"migration",
"file"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/cli.py#L175-L185 | train |
mbunse/socket_client_server | socket_client_server/socket_client_server.py | Sock_Server.quit | def quit(self):
"""
Quit socket server
"""
logging.info("quiting sock server")
if self.__quit is not None:
self.__quit.set()
self.join()
return | python | def quit(self):
"""
Quit socket server
"""
logging.info("quiting sock server")
if self.__quit is not None:
self.__quit.set()
self.join()
return | [
"def",
"quit",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"quiting sock server\"",
")",
"if",
"self",
".",
"__quit",
"is",
"not",
"None",
":",
"self",
".",
"__quit",
".",
"set",
"(",
")",
"self",
".",
"join",
"(",
")",
"return"
] | Quit socket server | [
"Quit",
"socket",
"server"
] | 8e884925cf887d386554c1859f626d8f01bd0036 | https://github.com/mbunse/socket_client_server/blob/8e884925cf887d386554c1859f626d8f01bd0036/socket_client_server/socket_client_server.py#L146-L154 | train |
glormph/msstitch | src/app/actions/peptable/psmtopeptable.py | get_quantcols | def get_quantcols(pattern, oldheader, coltype):
"""Searches for quantification columns using pattern and header list.
Calls reader function to do regexp. Returns a single column for
precursor quant."""
if pattern is None:
return False
if coltype == 'precur':
return reader.get_cols_in_file(pattern, oldheader, single_col=True) | python | def get_quantcols(pattern, oldheader, coltype):
"""Searches for quantification columns using pattern and header list.
Calls reader function to do regexp. Returns a single column for
precursor quant."""
if pattern is None:
return False
if coltype == 'precur':
return reader.get_cols_in_file(pattern, oldheader, single_col=True) | [
"def",
"get_quantcols",
"(",
"pattern",
",",
"oldheader",
",",
"coltype",
")",
":",
"if",
"pattern",
"is",
"None",
":",
"return",
"False",
"if",
"coltype",
"==",
"'precur'",
":",
"return",
"reader",
".",
"get_cols_in_file",
"(",
"pattern",
",",
"oldheader",
",",
"single_col",
"=",
"True",
")"
] | Searches for quantification columns using pattern and header list.
Calls reader function to do regexp. Returns a single column for
precursor quant. | [
"Searches",
"for",
"quantification",
"columns",
"using",
"pattern",
"and",
"header",
"list",
".",
"Calls",
"reader",
"function",
"to",
"do",
"regexp",
".",
"Returns",
"a",
"single",
"column",
"for",
"precursor",
"quant",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/peptable/psmtopeptable.py#L10-L17 | train |
glormph/msstitch | src/app/actions/peptable/psmtopeptable.py | get_peptide_quant | def get_peptide_quant(quantdata, quanttype):
"""Parses lists of quantdata and returns maxvalue from them. Strips NA"""
parsefnx = {'precur': max}
quantfloats = []
for q in quantdata:
try:
quantfloats.append(float(q))
except(TypeError, ValueError):
pass
if not quantfloats:
return 'NA'
return str(parsefnx[quanttype](quantfloats)) | python | def get_peptide_quant(quantdata, quanttype):
"""Parses lists of quantdata and returns maxvalue from them. Strips NA"""
parsefnx = {'precur': max}
quantfloats = []
for q in quantdata:
try:
quantfloats.append(float(q))
except(TypeError, ValueError):
pass
if not quantfloats:
return 'NA'
return str(parsefnx[quanttype](quantfloats)) | [
"def",
"get_peptide_quant",
"(",
"quantdata",
",",
"quanttype",
")",
":",
"parsefnx",
"=",
"{",
"'precur'",
":",
"max",
"}",
"quantfloats",
"=",
"[",
"]",
"for",
"q",
"in",
"quantdata",
":",
"try",
":",
"quantfloats",
".",
"append",
"(",
"float",
"(",
"q",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"if",
"not",
"quantfloats",
":",
"return",
"'NA'",
"return",
"str",
"(",
"parsefnx",
"[",
"quanttype",
"]",
"(",
"quantfloats",
")",
")"
] | Parses lists of quantdata and returns maxvalue from them. Strips NA | [
"Parses",
"lists",
"of",
"quantdata",
"and",
"returns",
"maxvalue",
"from",
"them",
".",
"Strips",
"NA"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/peptable/psmtopeptable.py#L50-L61 | train |
Erotemic/utool | utool/util_csv.py | read_csv | def read_csv(fpath):
""" reads csv in unicode """
import csv
import utool as ut
#csvfile = open(fpath, 'rb')
with open(fpath, 'rb') as csvfile:
row_iter = csv.reader(csvfile, delimiter=str(','), quotechar=str('|'))
row_list = [ut.lmap(ut.ensure_unicode, row) for row in row_iter]
return row_list | python | def read_csv(fpath):
""" reads csv in unicode """
import csv
import utool as ut
#csvfile = open(fpath, 'rb')
with open(fpath, 'rb') as csvfile:
row_iter = csv.reader(csvfile, delimiter=str(','), quotechar=str('|'))
row_list = [ut.lmap(ut.ensure_unicode, row) for row in row_iter]
return row_list | [
"def",
"read_csv",
"(",
"fpath",
")",
":",
"import",
"csv",
"import",
"utool",
"as",
"ut",
"#csvfile = open(fpath, 'rb')",
"with",
"open",
"(",
"fpath",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"row_iter",
"=",
"csv",
".",
"reader",
"(",
"csvfile",
",",
"delimiter",
"=",
"str",
"(",
"','",
")",
",",
"quotechar",
"=",
"str",
"(",
"'|'",
")",
")",
"row_list",
"=",
"[",
"ut",
".",
"lmap",
"(",
"ut",
".",
"ensure_unicode",
",",
"row",
")",
"for",
"row",
"in",
"row_iter",
"]",
"return",
"row_list"
] | reads csv in unicode | [
"reads",
"csv",
"in",
"unicode"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_csv.py#L151-L159 | train |
Erotemic/utool | utool/_internal/meta_util_dbg.py | get_caller_name | def get_caller_name(N=0, strict=True):
""" Standalone version of get_caller_name """
if isinstance(N, (list, tuple)):
name_list = []
for N_ in N:
try:
name_list.append(get_caller_name(N_))
except AssertionError:
name_list.append('X')
return '[' + ']['.join(name_list) + ']'
# <get_parent_frame>
parent_frame = get_stack_frame(N=N + 2, strict=strict)
# </get_parent_frame>
caller_name = parent_frame.f_code.co_name
if caller_name == '<module>':
co_filename = parent_frame.f_code.co_filename
caller_name = splitext(split(co_filename)[1])[0]
if caller_name == '__init__':
co_filename = parent_frame.f_code.co_filename
caller_name = basename(dirname(co_filename)) + '.' + caller_name
return caller_name | python | def get_caller_name(N=0, strict=True):
""" Standalone version of get_caller_name """
if isinstance(N, (list, tuple)):
name_list = []
for N_ in N:
try:
name_list.append(get_caller_name(N_))
except AssertionError:
name_list.append('X')
return '[' + ']['.join(name_list) + ']'
# <get_parent_frame>
parent_frame = get_stack_frame(N=N + 2, strict=strict)
# </get_parent_frame>
caller_name = parent_frame.f_code.co_name
if caller_name == '<module>':
co_filename = parent_frame.f_code.co_filename
caller_name = splitext(split(co_filename)[1])[0]
if caller_name == '__init__':
co_filename = parent_frame.f_code.co_filename
caller_name = basename(dirname(co_filename)) + '.' + caller_name
return caller_name | [
"def",
"get_caller_name",
"(",
"N",
"=",
"0",
",",
"strict",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"N",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"name_list",
"=",
"[",
"]",
"for",
"N_",
"in",
"N",
":",
"try",
":",
"name_list",
".",
"append",
"(",
"get_caller_name",
"(",
"N_",
")",
")",
"except",
"AssertionError",
":",
"name_list",
".",
"append",
"(",
"'X'",
")",
"return",
"'['",
"+",
"']['",
".",
"join",
"(",
"name_list",
")",
"+",
"']'",
"# <get_parent_frame>",
"parent_frame",
"=",
"get_stack_frame",
"(",
"N",
"=",
"N",
"+",
"2",
",",
"strict",
"=",
"strict",
")",
"# </get_parent_frame>",
"caller_name",
"=",
"parent_frame",
".",
"f_code",
".",
"co_name",
"if",
"caller_name",
"==",
"'<module>'",
":",
"co_filename",
"=",
"parent_frame",
".",
"f_code",
".",
"co_filename",
"caller_name",
"=",
"splitext",
"(",
"split",
"(",
"co_filename",
")",
"[",
"1",
"]",
")",
"[",
"0",
"]",
"if",
"caller_name",
"==",
"'__init__'",
":",
"co_filename",
"=",
"parent_frame",
".",
"f_code",
".",
"co_filename",
"caller_name",
"=",
"basename",
"(",
"dirname",
"(",
"co_filename",
")",
")",
"+",
"'.'",
"+",
"caller_name",
"return",
"caller_name"
] | Standalone version of get_caller_name | [
"Standalone",
"version",
"of",
"get_caller_name"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/meta_util_dbg.py#L27-L47 | train |
quikmile/trellio | trellio/registry.py | Registry._handle_ping | def _handle_ping(self, packet, protocol):
""" Responds to pings from registry_client only if the node_ids present in the ping payload are registered
:param packet: The 'ping' packet received
:param protocol: The protocol on which the pong should be sent
"""
if 'payload' in packet:
is_valid_node = True
node_ids = list(packet['payload'].values())
for node_id in node_ids:
if self._repository.get_node(node_id) is None:
is_valid_node = False
break
if is_valid_node:
self._pong(packet, protocol)
else:
self._pong(packet, protocol) | python | def _handle_ping(self, packet, protocol):
""" Responds to pings from registry_client only if the node_ids present in the ping payload are registered
:param packet: The 'ping' packet received
:param protocol: The protocol on which the pong should be sent
"""
if 'payload' in packet:
is_valid_node = True
node_ids = list(packet['payload'].values())
for node_id in node_ids:
if self._repository.get_node(node_id) is None:
is_valid_node = False
break
if is_valid_node:
self._pong(packet, protocol)
else:
self._pong(packet, protocol) | [
"def",
"_handle_ping",
"(",
"self",
",",
"packet",
",",
"protocol",
")",
":",
"if",
"'payload'",
"in",
"packet",
":",
"is_valid_node",
"=",
"True",
"node_ids",
"=",
"list",
"(",
"packet",
"[",
"'payload'",
"]",
".",
"values",
"(",
")",
")",
"for",
"node_id",
"in",
"node_ids",
":",
"if",
"self",
".",
"_repository",
".",
"get_node",
"(",
"node_id",
")",
"is",
"None",
":",
"is_valid_node",
"=",
"False",
"break",
"if",
"is_valid_node",
":",
"self",
".",
"_pong",
"(",
"packet",
",",
"protocol",
")",
"else",
":",
"self",
".",
"_pong",
"(",
"packet",
",",
"protocol",
")"
] | Responds to pings from registry_client only if the node_ids present in the ping payload are registered
:param packet: The 'ping' packet received
:param protocol: The protocol on which the pong should be sent | [
"Responds",
"to",
"pings",
"from",
"registry_client",
"only",
"if",
"the",
"node_ids",
"present",
"in",
"the",
"ping",
"payload",
"are",
"registered"
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/registry.py#L379-L395 | train |
glormph/msstitch | src/app/drivers/pycolator/splitmerge.py | MergeDriver.set_features | def set_features(self):
""""Merge all psms and peptides"""
allpsms_str = readers.generate_psms_multiple_fractions_strings(
self.mergefiles, self.ns)
allpeps = preparation.merge_peptides(self.mergefiles, self.ns)
self.features = {'psm': allpsms_str, 'peptide': allpeps} | python | def set_features(self):
""""Merge all psms and peptides"""
allpsms_str = readers.generate_psms_multiple_fractions_strings(
self.mergefiles, self.ns)
allpeps = preparation.merge_peptides(self.mergefiles, self.ns)
self.features = {'psm': allpsms_str, 'peptide': allpeps} | [
"def",
"set_features",
"(",
"self",
")",
":",
"allpsms_str",
"=",
"readers",
".",
"generate_psms_multiple_fractions_strings",
"(",
"self",
".",
"mergefiles",
",",
"self",
".",
"ns",
")",
"allpeps",
"=",
"preparation",
".",
"merge_peptides",
"(",
"self",
".",
"mergefiles",
",",
"self",
".",
"ns",
")",
"self",
".",
"features",
"=",
"{",
"'psm'",
":",
"allpsms_str",
",",
"'peptide'",
":",
"allpeps",
"}"
] | Merge all psms and peptides | [
"Merge",
"all",
"psms",
"and",
"peptides"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/pycolator/splitmerge.py#L94-L99 | train |
Erotemic/utool | utool/util_git.py | git_sequence_editor_squash | def git_sequence_editor_squash(fpath):
r"""
squashes wip messages
CommandLine:
python -m utool.util_git --exec-git_sequence_editor_squash
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> import utool as ut
>>> from utool.util_git import * # NOQA
>>> fpath = ut.get_argval('--fpath', str, default=None)
>>> git_sequence_editor_squash(fpath)
Ignore:
text = ut.codeblock(
'''
pick 852aa05 better doctest for tips
pick 3c779b8 wip
pick 02bc21d wip
pick 1853828 Fixed root tablename
pick 9d50233 doctest updates
pick 66230a5 wip
pick c612e98 wip
pick b298598 Fixed tablename error
pick 1120a87 wip
pick f6c4838 wip
pick 7f92575 wip
''')
Ignore:
def squash_consecutive_commits_with_same_message():
# http://stackoverflow.com/questions/8226278/git-alias-to-squash-all-commits-with-a-particular-commit-message
# Can do interactively with this. Can it be done automatically and pay attention to
# Timestamps etc?
git rebase --interactive HEAD~40 --autosquash
git rebase --interactive $(git merge-base HEAD master) --autosquash
# Lookbehind correct version
%s/\([a-z]* [a-z0-9]* wip\n\)\@<=pick \([a-z0-9]*\) wip/squash \2 wip/gc
# THE FULL NON-INTERACTIVE AUTOSQUASH SCRIPT
# TODO: Dont squash if there is a one hour timedelta between commits
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git rev-list HEAD | tail -n 1) --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~10 --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git merge-base HEAD master) --autosquash --no-verify
# 14d778fa30a93f85c61f34d09eddb6d2cafd11e2
# c509a95d4468ebb61097bd9f4d302367424772a3
# b0ffc26011e33378ee30730c5e0ef1994bfe1a90
# GIT_SEQUENCE_EDITOR=<script> git rebase -i <params>
# GIT_SEQUENCE_EDITOR="echo 'FOOBAR $1' " git rebase -i HEAD~40 --autosquash
# git checkout master
# git branch -D tmp
# git checkout -b tmp
# option to get the tail commit
$(git rev-list HEAD | tail -n 1)
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash --no-verify
<params>
"""
# print(sys.argv)
import utool as ut
text = ut.read_from(fpath)
# print('fpath = %r' % (fpath,))
print(text)
# Doesnt work because of fixed witdth requirement
# search = (ut.util_regex.positive_lookbehind('[a-z]* [a-z0-9]* wip\n') + 'pick ' +
# ut.reponamed_field('hash', '[a-z0-9]*') + ' wip')
# repl = ('squash ' + ut.bref_field('hash') + ' wip')
# import re
# new_text = re.sub(search, repl, text, flags=re.MULTILINE)
# print(new_text)
prev_msg = None
prev_dt = None
new_lines = []
def get_commit_date(hashid):
out, err, ret = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False, quiet=True, pad_stdout=False)
# from datetime import datetime
from dateutil import parser
# print('out = %r' % (out,))
stamp = out.strip('\n')
# print('stamp = %r' % (stamp,))
dt = parser.parse(stamp)
# dt = datetime.strptime(stamp, '%Y-%m-%d %H:%M:%S %Z')
# print('dt = %r' % (dt,))
return dt
for line in text.split('\n'):
commit_line = line.split(' ')
if len(commit_line) < 3:
prev_msg = None
prev_dt = None
new_lines += [line]
continue
action = commit_line[0]
hashid = commit_line[1]
msg = ' ' .join(commit_line[2:])
try:
dt = get_commit_date(hashid)
except ValueError:
prev_msg = None
prev_dt = None
new_lines += [line]
continue
orig_msg = msg
can_squash = action == 'pick' and msg == 'wip' and prev_msg == 'wip'
if prev_dt is not None and prev_msg == 'wip':
tdelta = dt - prev_dt
# Only squash closely consecutive commits
threshold_minutes = 45
td_min = (tdelta.total_seconds() / 60.)
# print(tdelta)
can_squash &= td_min < threshold_minutes
msg = msg + ' -- tdelta=%r' % (ut.get_timedelta_str(tdelta),)
if can_squash:
new_line = ' ' .join(['squash', hashid, msg])
new_lines += [new_line]
else:
new_lines += [line]
prev_msg = orig_msg
prev_dt = dt
new_text = '\n'.join(new_lines)
def get_commit_date(hashid):
out = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False)
print('out = %r' % (out,))
# print('Dry run')
# ut.dump_autogen_code(fpath, new_text)
print(new_text)
ut.write_to(fpath, new_text, n=None) | python | def git_sequence_editor_squash(fpath):
r"""
squashes wip messages
CommandLine:
python -m utool.util_git --exec-git_sequence_editor_squash
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> import utool as ut
>>> from utool.util_git import * # NOQA
>>> fpath = ut.get_argval('--fpath', str, default=None)
>>> git_sequence_editor_squash(fpath)
Ignore:
text = ut.codeblock(
'''
pick 852aa05 better doctest for tips
pick 3c779b8 wip
pick 02bc21d wip
pick 1853828 Fixed root tablename
pick 9d50233 doctest updates
pick 66230a5 wip
pick c612e98 wip
pick b298598 Fixed tablename error
pick 1120a87 wip
pick f6c4838 wip
pick 7f92575 wip
''')
Ignore:
def squash_consecutive_commits_with_same_message():
# http://stackoverflow.com/questions/8226278/git-alias-to-squash-all-commits-with-a-particular-commit-message
# Can do interactively with this. Can it be done automatically and pay attention to
# Timestamps etc?
git rebase --interactive HEAD~40 --autosquash
git rebase --interactive $(git merge-base HEAD master) --autosquash
# Lookbehind correct version
%s/\([a-z]* [a-z0-9]* wip\n\)\@<=pick \([a-z0-9]*\) wip/squash \2 wip/gc
# THE FULL NON-INTERACTIVE AUTOSQUASH SCRIPT
# TODO: Dont squash if there is a one hour timedelta between commits
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git rev-list HEAD | tail -n 1) --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~10 --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git merge-base HEAD master) --autosquash --no-verify
# 14d778fa30a93f85c61f34d09eddb6d2cafd11e2
# c509a95d4468ebb61097bd9f4d302367424772a3
# b0ffc26011e33378ee30730c5e0ef1994bfe1a90
# GIT_SEQUENCE_EDITOR=<script> git rebase -i <params>
# GIT_SEQUENCE_EDITOR="echo 'FOOBAR $1' " git rebase -i HEAD~40 --autosquash
# git checkout master
# git branch -D tmp
# git checkout -b tmp
# option to get the tail commit
$(git rev-list HEAD | tail -n 1)
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash --no-verify
<params>
"""
# print(sys.argv)
import utool as ut
text = ut.read_from(fpath)
# print('fpath = %r' % (fpath,))
print(text)
# Doesnt work because of fixed witdth requirement
# search = (ut.util_regex.positive_lookbehind('[a-z]* [a-z0-9]* wip\n') + 'pick ' +
# ut.reponamed_field('hash', '[a-z0-9]*') + ' wip')
# repl = ('squash ' + ut.bref_field('hash') + ' wip')
# import re
# new_text = re.sub(search, repl, text, flags=re.MULTILINE)
# print(new_text)
prev_msg = None
prev_dt = None
new_lines = []
def get_commit_date(hashid):
out, err, ret = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False, quiet=True, pad_stdout=False)
# from datetime import datetime
from dateutil import parser
# print('out = %r' % (out,))
stamp = out.strip('\n')
# print('stamp = %r' % (stamp,))
dt = parser.parse(stamp)
# dt = datetime.strptime(stamp, '%Y-%m-%d %H:%M:%S %Z')
# print('dt = %r' % (dt,))
return dt
for line in text.split('\n'):
commit_line = line.split(' ')
if len(commit_line) < 3:
prev_msg = None
prev_dt = None
new_lines += [line]
continue
action = commit_line[0]
hashid = commit_line[1]
msg = ' ' .join(commit_line[2:])
try:
dt = get_commit_date(hashid)
except ValueError:
prev_msg = None
prev_dt = None
new_lines += [line]
continue
orig_msg = msg
can_squash = action == 'pick' and msg == 'wip' and prev_msg == 'wip'
if prev_dt is not None and prev_msg == 'wip':
tdelta = dt - prev_dt
# Only squash closely consecutive commits
threshold_minutes = 45
td_min = (tdelta.total_seconds() / 60.)
# print(tdelta)
can_squash &= td_min < threshold_minutes
msg = msg + ' -- tdelta=%r' % (ut.get_timedelta_str(tdelta),)
if can_squash:
new_line = ' ' .join(['squash', hashid, msg])
new_lines += [new_line]
else:
new_lines += [line]
prev_msg = orig_msg
prev_dt = dt
new_text = '\n'.join(new_lines)
def get_commit_date(hashid):
out = ut.cmd('git show -s --format=%ci ' + hashid, verbose=False)
print('out = %r' % (out,))
# print('Dry run')
# ut.dump_autogen_code(fpath, new_text)
print(new_text)
ut.write_to(fpath, new_text, n=None) | [
"def",
"git_sequence_editor_squash",
"(",
"fpath",
")",
":",
"# print(sys.argv)",
"import",
"utool",
"as",
"ut",
"text",
"=",
"ut",
".",
"read_from",
"(",
"fpath",
")",
"# print('fpath = %r' % (fpath,))",
"print",
"(",
"text",
")",
"# Doesnt work because of fixed witdth requirement",
"# search = (ut.util_regex.positive_lookbehind('[a-z]* [a-z0-9]* wip\\n') + 'pick ' +",
"# ut.reponamed_field('hash', '[a-z0-9]*') + ' wip')",
"# repl = ('squash ' + ut.bref_field('hash') + ' wip')",
"# import re",
"# new_text = re.sub(search, repl, text, flags=re.MULTILINE)",
"# print(new_text)",
"prev_msg",
"=",
"None",
"prev_dt",
"=",
"None",
"new_lines",
"=",
"[",
"]",
"def",
"get_commit_date",
"(",
"hashid",
")",
":",
"out",
",",
"err",
",",
"ret",
"=",
"ut",
".",
"cmd",
"(",
"'git show -s --format=%ci '",
"+",
"hashid",
",",
"verbose",
"=",
"False",
",",
"quiet",
"=",
"True",
",",
"pad_stdout",
"=",
"False",
")",
"# from datetime import datetime",
"from",
"dateutil",
"import",
"parser",
"# print('out = %r' % (out,))",
"stamp",
"=",
"out",
".",
"strip",
"(",
"'\\n'",
")",
"# print('stamp = %r' % (stamp,))",
"dt",
"=",
"parser",
".",
"parse",
"(",
"stamp",
")",
"# dt = datetime.strptime(stamp, '%Y-%m-%d %H:%M:%S %Z')",
"# print('dt = %r' % (dt,))",
"return",
"dt",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"commit_line",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"commit_line",
")",
"<",
"3",
":",
"prev_msg",
"=",
"None",
"prev_dt",
"=",
"None",
"new_lines",
"+=",
"[",
"line",
"]",
"continue",
"action",
"=",
"commit_line",
"[",
"0",
"]",
"hashid",
"=",
"commit_line",
"[",
"1",
"]",
"msg",
"=",
"' '",
".",
"join",
"(",
"commit_line",
"[",
"2",
":",
"]",
")",
"try",
":",
"dt",
"=",
"get_commit_date",
"(",
"hashid",
")",
"except",
"ValueError",
":",
"prev_msg",
"=",
"None",
"prev_dt",
"=",
"None",
"new_lines",
"+=",
"[",
"line",
"]",
"continue",
"orig_msg",
"=",
"msg",
"can_squash",
"=",
"action",
"==",
"'pick'",
"and",
"msg",
"==",
"'wip'",
"and",
"prev_msg",
"==",
"'wip'",
"if",
"prev_dt",
"is",
"not",
"None",
"and",
"prev_msg",
"==",
"'wip'",
":",
"tdelta",
"=",
"dt",
"-",
"prev_dt",
"# Only squash closely consecutive commits",
"threshold_minutes",
"=",
"45",
"td_min",
"=",
"(",
"tdelta",
".",
"total_seconds",
"(",
")",
"/",
"60.",
")",
"# print(tdelta)",
"can_squash",
"&=",
"td_min",
"<",
"threshold_minutes",
"msg",
"=",
"msg",
"+",
"' -- tdelta=%r'",
"%",
"(",
"ut",
".",
"get_timedelta_str",
"(",
"tdelta",
")",
",",
")",
"if",
"can_squash",
":",
"new_line",
"=",
"' '",
".",
"join",
"(",
"[",
"'squash'",
",",
"hashid",
",",
"msg",
"]",
")",
"new_lines",
"+=",
"[",
"new_line",
"]",
"else",
":",
"new_lines",
"+=",
"[",
"line",
"]",
"prev_msg",
"=",
"orig_msg",
"prev_dt",
"=",
"dt",
"new_text",
"=",
"'\\n'",
".",
"join",
"(",
"new_lines",
")",
"def",
"get_commit_date",
"(",
"hashid",
")",
":",
"out",
"=",
"ut",
".",
"cmd",
"(",
"'git show -s --format=%ci '",
"+",
"hashid",
",",
"verbose",
"=",
"False",
")",
"print",
"(",
"'out = %r'",
"%",
"(",
"out",
",",
")",
")",
"# print('Dry run')",
"# ut.dump_autogen_code(fpath, new_text)",
"print",
"(",
"new_text",
")",
"ut",
".",
"write_to",
"(",
"fpath",
",",
"new_text",
",",
"n",
"=",
"None",
")"
] | r"""
squashes wip messages
CommandLine:
python -m utool.util_git --exec-git_sequence_editor_squash
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> import utool as ut
>>> from utool.util_git import * # NOQA
>>> fpath = ut.get_argval('--fpath', str, default=None)
>>> git_sequence_editor_squash(fpath)
Ignore:
text = ut.codeblock(
'''
pick 852aa05 better doctest for tips
pick 3c779b8 wip
pick 02bc21d wip
pick 1853828 Fixed root tablename
pick 9d50233 doctest updates
pick 66230a5 wip
pick c612e98 wip
pick b298598 Fixed tablename error
pick 1120a87 wip
pick f6c4838 wip
pick 7f92575 wip
''')
Ignore:
def squash_consecutive_commits_with_same_message():
# http://stackoverflow.com/questions/8226278/git-alias-to-squash-all-commits-with-a-particular-commit-message
# Can do interactively with this. Can it be done automatically and pay attention to
# Timestamps etc?
git rebase --interactive HEAD~40 --autosquash
git rebase --interactive $(git merge-base HEAD master) --autosquash
# Lookbehind correct version
%s/\([a-z]* [a-z0-9]* wip\n\)\@<=pick \([a-z0-9]*\) wip/squash \2 wip/gc
# THE FULL NON-INTERACTIVE AUTOSQUASH SCRIPT
# TODO: Dont squash if there is a one hour timedelta between commits
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git rev-list HEAD | tail -n 1) --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~10 --autosquash --no-verify
GIT_EDITOR="cat $1" GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i $(git merge-base HEAD master) --autosquash --no-verify
# 14d778fa30a93f85c61f34d09eddb6d2cafd11e2
# c509a95d4468ebb61097bd9f4d302367424772a3
# b0ffc26011e33378ee30730c5e0ef1994bfe1a90
# GIT_SEQUENCE_EDITOR=<script> git rebase -i <params>
# GIT_SEQUENCE_EDITOR="echo 'FOOBAR $1' " git rebase -i HEAD~40 --autosquash
# git checkout master
# git branch -D tmp
# git checkout -b tmp
# option to get the tail commit
$(git rev-list HEAD | tail -n 1)
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash
# GIT_SEQUENCE_EDITOR="python -m utool.util_git --exec-git_sequence_editor_squash \
--fpath $1" git rebase -i HEAD~40 --autosquash --no-verify
<params> | [
"r",
"squashes",
"wip",
"messages"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_git.py#L876-L1016 | train |
Erotemic/utool | utool/util_git.py | std_build_command | def std_build_command(repo='.'):
"""
DEPRICATE
My standard build script names.
Calls mingw_build.bat on windows and unix_build.sh on unix
"""
import utool as ut
print('+**** stdbuild *******')
print('repo = %r' % (repo,))
if sys.platform.startswith('win32'):
# vtool --rebuild-sver didnt work with this line
#scriptname = './mingw_build.bat'
scriptname = 'mingw_build.bat'
else:
scriptname = './unix_build.sh'
if repo == '':
# default to cwd
repo = '.'
else:
os.chdir(repo)
ut.assert_exists(scriptname)
normbuild_flag = '--no-rmbuild'
if ut.get_argflag(normbuild_flag):
scriptname += ' ' + normbuild_flag
# Execute build
ut.cmd(scriptname)
#os.system(scriptname)
print('L**** stdbuild *******') | python | def std_build_command(repo='.'):
"""
DEPRICATE
My standard build script names.
Calls mingw_build.bat on windows and unix_build.sh on unix
"""
import utool as ut
print('+**** stdbuild *******')
print('repo = %r' % (repo,))
if sys.platform.startswith('win32'):
# vtool --rebuild-sver didnt work with this line
#scriptname = './mingw_build.bat'
scriptname = 'mingw_build.bat'
else:
scriptname = './unix_build.sh'
if repo == '':
# default to cwd
repo = '.'
else:
os.chdir(repo)
ut.assert_exists(scriptname)
normbuild_flag = '--no-rmbuild'
if ut.get_argflag(normbuild_flag):
scriptname += ' ' + normbuild_flag
# Execute build
ut.cmd(scriptname)
#os.system(scriptname)
print('L**** stdbuild *******') | [
"def",
"std_build_command",
"(",
"repo",
"=",
"'.'",
")",
":",
"import",
"utool",
"as",
"ut",
"print",
"(",
"'+**** stdbuild *******'",
")",
"print",
"(",
"'repo = %r'",
"%",
"(",
"repo",
",",
")",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win32'",
")",
":",
"# vtool --rebuild-sver didnt work with this line",
"#scriptname = './mingw_build.bat'",
"scriptname",
"=",
"'mingw_build.bat'",
"else",
":",
"scriptname",
"=",
"'./unix_build.sh'",
"if",
"repo",
"==",
"''",
":",
"# default to cwd",
"repo",
"=",
"'.'",
"else",
":",
"os",
".",
"chdir",
"(",
"repo",
")",
"ut",
".",
"assert_exists",
"(",
"scriptname",
")",
"normbuild_flag",
"=",
"'--no-rmbuild'",
"if",
"ut",
".",
"get_argflag",
"(",
"normbuild_flag",
")",
":",
"scriptname",
"+=",
"' '",
"+",
"normbuild_flag",
"# Execute build",
"ut",
".",
"cmd",
"(",
"scriptname",
")",
"#os.system(scriptname)",
"print",
"(",
"'L**** stdbuild *******'",
")"
] | DEPRICATE
My standard build script names.
Calls mingw_build.bat on windows and unix_build.sh on unix | [
"DEPRICATE",
"My",
"standard",
"build",
"script",
"names",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_git.py#L1019-L1047 | train |
Thermondo/django-heroku-connect | heroku_connect/management/commands/import_mappings.py | Command.wait_for_import | def wait_for_import(self, connection_id, wait_interval):
"""
Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seconds.
Raises:
CommandError: If fetch connection information fails.
"""
self.stdout.write(self.style.NOTICE('Waiting for import'), ending='')
state = utils.ConnectionStates.IMPORT_CONFIGURATION
while state == utils.ConnectionStates.IMPORT_CONFIGURATION:
# before you get the first state, the API can be a bit behind
self.stdout.write(self.style.NOTICE('.'), ending='')
time.sleep(wait_interval) # take a breath
try:
connection = utils.get_connection(connection_id)
except requests.HTTPError as e:
raise CommandError("Failed to fetch connection information.") from e
else:
state = connection['state']
self.stdout.write(self.style.NOTICE(' Done!')) | python | def wait_for_import(self, connection_id, wait_interval):
"""
Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seconds.
Raises:
CommandError: If fetch connection information fails.
"""
self.stdout.write(self.style.NOTICE('Waiting for import'), ending='')
state = utils.ConnectionStates.IMPORT_CONFIGURATION
while state == utils.ConnectionStates.IMPORT_CONFIGURATION:
# before you get the first state, the API can be a bit behind
self.stdout.write(self.style.NOTICE('.'), ending='')
time.sleep(wait_interval) # take a breath
try:
connection = utils.get_connection(connection_id)
except requests.HTTPError as e:
raise CommandError("Failed to fetch connection information.") from e
else:
state = connection['state']
self.stdout.write(self.style.NOTICE(' Done!')) | [
"def",
"wait_for_import",
"(",
"self",
",",
"connection_id",
",",
"wait_interval",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"NOTICE",
"(",
"'Waiting for import'",
")",
",",
"ending",
"=",
"''",
")",
"state",
"=",
"utils",
".",
"ConnectionStates",
".",
"IMPORT_CONFIGURATION",
"while",
"state",
"==",
"utils",
".",
"ConnectionStates",
".",
"IMPORT_CONFIGURATION",
":",
"# before you get the first state, the API can be a bit behind",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"NOTICE",
"(",
"'.'",
")",
",",
"ending",
"=",
"''",
")",
"time",
".",
"sleep",
"(",
"wait_interval",
")",
"# take a breath",
"try",
":",
"connection",
"=",
"utils",
".",
"get_connection",
"(",
"connection_id",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"raise",
"CommandError",
"(",
"\"Failed to fetch connection information.\"",
")",
"from",
"e",
"else",
":",
"state",
"=",
"connection",
"[",
"'state'",
"]",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"NOTICE",
"(",
"' Done!'",
")",
")"
] | Wait until connection state is no longer ``IMPORT_CONFIGURATION``.
Args:
connection_id (str): Heroku Connect connection to monitor.
wait_interval (int): How frequently to poll in seconds.
Raises:
CommandError: If fetch connection information fails. | [
"Wait",
"until",
"connection",
"state",
"is",
"no",
"longer",
"IMPORT_CONFIGURATION",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/management/commands/import_mappings.py#L76-L100 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/disableaccess_key.py | Plugin.setup | def setup(self):
"""Method runs the plugin"""
if self.dry_run is not True:
self.client = self._get_client()
self._disable_access_key() | python | def setup(self):
"""Method runs the plugin"""
if self.dry_run is not True:
self.client = self._get_client()
self._disable_access_key() | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"self",
".",
"dry_run",
"is",
"not",
"True",
":",
"self",
".",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"self",
".",
"_disable_access_key",
"(",
")"
] | Method runs the plugin | [
"Method",
"runs",
"the",
"plugin"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/disableaccess_key.py#L29-L33 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/disableaccess_key.py | Plugin.validate | def validate(self):
"""Returns whether this plugin does what it claims to have done"""
try:
response = self.client.get_access_key_last_used(
AccessKeyId=self.access_key_id
)
username = response['UserName']
access_keys = self.client.list_access_keys(
UserName=username
)
for key in access_keys['AccessKeyMetadata']:
if \
(key['AccessKeyId'] == self.access_key_id)\
and (key['Status'] == 'Inactive'):
return True
return False
except Exception as e:
logger.info(
"Failed to validate key disable for "
"key {id} due to: {e}.".format(
e=e, id=self.access_key_id
)
)
return False | python | def validate(self):
"""Returns whether this plugin does what it claims to have done"""
try:
response = self.client.get_access_key_last_used(
AccessKeyId=self.access_key_id
)
username = response['UserName']
access_keys = self.client.list_access_keys(
UserName=username
)
for key in access_keys['AccessKeyMetadata']:
if \
(key['AccessKeyId'] == self.access_key_id)\
and (key['Status'] == 'Inactive'):
return True
return False
except Exception as e:
logger.info(
"Failed to validate key disable for "
"key {id} due to: {e}.".format(
e=e, id=self.access_key_id
)
)
return False | [
"def",
"validate",
"(",
"self",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"client",
".",
"get_access_key_last_used",
"(",
"AccessKeyId",
"=",
"self",
".",
"access_key_id",
")",
"username",
"=",
"response",
"[",
"'UserName'",
"]",
"access_keys",
"=",
"self",
".",
"client",
".",
"list_access_keys",
"(",
"UserName",
"=",
"username",
")",
"for",
"key",
"in",
"access_keys",
"[",
"'AccessKeyMetadata'",
"]",
":",
"if",
"(",
"key",
"[",
"'AccessKeyId'",
"]",
"==",
"self",
".",
"access_key_id",
")",
"and",
"(",
"key",
"[",
"'Status'",
"]",
"==",
"'Inactive'",
")",
":",
"return",
"True",
"return",
"False",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"info",
"(",
"\"Failed to validate key disable for \"",
"\"key {id} due to: {e}.\"",
".",
"format",
"(",
"e",
"=",
"e",
",",
"id",
"=",
"self",
".",
"access_key_id",
")",
")",
"return",
"False"
] | Returns whether this plugin does what it claims to have done | [
"Returns",
"whether",
"this",
"plugin",
"does",
"what",
"it",
"claims",
"to",
"have",
"done"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/disableaccess_key.py#L35-L61 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/disableaccess_key.py | Plugin._disable_access_key | def _disable_access_key(self, force_disable_self=False):
"""This function first checks to see if the key is already disabled\
if not then it goes to disabling
"""
client = self.client
if self.validate is True:
return
else:
try:
client.update_access_key(
UserName=self._search_user_for_key(),
AccessKeyId=self.access_key_id,
Status='Inactive'
)
logger.info(
"Access key {id} has "
"been disabled.".format(id=self.access_key_id)
)
except Exception as e:
logger.info(
"Access key {id} could not "
"be disabled due to: {e}.".format(
e=e, id=self.access_key_id
)
) | python | def _disable_access_key(self, force_disable_self=False):
"""This function first checks to see if the key is already disabled\
if not then it goes to disabling
"""
client = self.client
if self.validate is True:
return
else:
try:
client.update_access_key(
UserName=self._search_user_for_key(),
AccessKeyId=self.access_key_id,
Status='Inactive'
)
logger.info(
"Access key {id} has "
"been disabled.".format(id=self.access_key_id)
)
except Exception as e:
logger.info(
"Access key {id} could not "
"be disabled due to: {e}.".format(
e=e, id=self.access_key_id
)
) | [
"def",
"_disable_access_key",
"(",
"self",
",",
"force_disable_self",
"=",
"False",
")",
":",
"client",
"=",
"self",
".",
"client",
"if",
"self",
".",
"validate",
"is",
"True",
":",
"return",
"else",
":",
"try",
":",
"client",
".",
"update_access_key",
"(",
"UserName",
"=",
"self",
".",
"_search_user_for_key",
"(",
")",
",",
"AccessKeyId",
"=",
"self",
".",
"access_key_id",
",",
"Status",
"=",
"'Inactive'",
")",
"logger",
".",
"info",
"(",
"\"Access key {id} has \"",
"\"been disabled.\"",
".",
"format",
"(",
"id",
"=",
"self",
".",
"access_key_id",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"info",
"(",
"\"Access key {id} could not \"",
"\"be disabled due to: {e}.\"",
".",
"format",
"(",
"e",
"=",
"e",
",",
"id",
"=",
"self",
".",
"access_key_id",
")",
")"
] | This function first checks to see if the key is already disabled\
if not then it goes to disabling | [
"This",
"function",
"first",
"checks",
"to",
"see",
"if",
"the",
"key",
"is",
"already",
"disabled",
"\\"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/disableaccess_key.py#L90-L115 | train |
glormph/msstitch | src/app/actions/prottable/create_empty.py | generate_master_proteins | def generate_master_proteins(psms, protcol):
"""Fed with a psms generator, this returns the master proteins present
in the PSM table. PSMs with multiple master proteins are excluded."""
master_proteins = {}
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
for psm in psms:
protacc = psm[protcol]
if ';' in protacc:
continue
master_proteins[protacc] = 1
if 'NA' in master_proteins:
master_proteins.pop('NA')
if '' in master_proteins:
master_proteins.pop('')
for protacc in master_proteins:
yield {prottabledata.HEADER_PROTEIN: protacc} | python | def generate_master_proteins(psms, protcol):
"""Fed with a psms generator, this returns the master proteins present
in the PSM table. PSMs with multiple master proteins are excluded."""
master_proteins = {}
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
for psm in psms:
protacc = psm[protcol]
if ';' in protacc:
continue
master_proteins[protacc] = 1
if 'NA' in master_proteins:
master_proteins.pop('NA')
if '' in master_proteins:
master_proteins.pop('')
for protacc in master_proteins:
yield {prottabledata.HEADER_PROTEIN: protacc} | [
"def",
"generate_master_proteins",
"(",
"psms",
",",
"protcol",
")",
":",
"master_proteins",
"=",
"{",
"}",
"if",
"not",
"protcol",
":",
"protcol",
"=",
"mzidtsvdata",
".",
"HEADER_MASTER_PROT",
"for",
"psm",
"in",
"psms",
":",
"protacc",
"=",
"psm",
"[",
"protcol",
"]",
"if",
"';'",
"in",
"protacc",
":",
"continue",
"master_proteins",
"[",
"protacc",
"]",
"=",
"1",
"if",
"'NA'",
"in",
"master_proteins",
":",
"master_proteins",
".",
"pop",
"(",
"'NA'",
")",
"if",
"''",
"in",
"master_proteins",
":",
"master_proteins",
".",
"pop",
"(",
"''",
")",
"for",
"protacc",
"in",
"master_proteins",
":",
"yield",
"{",
"prottabledata",
".",
"HEADER_PROTEIN",
":",
"protacc",
"}"
] | Fed with a psms generator, this returns the master proteins present
in the PSM table. PSMs with multiple master proteins are excluded. | [
"Fed",
"with",
"a",
"psms",
"generator",
"this",
"returns",
"the",
"master",
"proteins",
"present",
"in",
"the",
"PSM",
"table",
".",
"PSMs",
"with",
"multiple",
"master",
"proteins",
"are",
"excluded",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/create_empty.py#L5-L21 | train |
glormph/msstitch | src/app/drivers/pycolator/base.py | PycolatorDriver.prepare_percolator_output | def prepare_percolator_output(self, fn):
"""Returns namespace and static xml from percolator output file"""
ns = xml.get_namespace(fn)
static = readers.get_percolator_static_xml(fn, ns)
return ns, static | python | def prepare_percolator_output(self, fn):
"""Returns namespace and static xml from percolator output file"""
ns = xml.get_namespace(fn)
static = readers.get_percolator_static_xml(fn, ns)
return ns, static | [
"def",
"prepare_percolator_output",
"(",
"self",
",",
"fn",
")",
":",
"ns",
"=",
"xml",
".",
"get_namespace",
"(",
"fn",
")",
"static",
"=",
"readers",
".",
"get_percolator_static_xml",
"(",
"fn",
",",
"ns",
")",
"return",
"ns",
",",
"static"
] | Returns namespace and static xml from percolator output file | [
"Returns",
"namespace",
"and",
"static",
"xml",
"from",
"percolator",
"output",
"file"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/pycolator/base.py#L13-L17 | train |
rhazdon/django-sonic-screwdriver | django_sonic_screwdriver/git/decorators.py | git_available | def git_available(func):
"""
Check, if a git repository exists in the given folder.
"""
def inner(*args):
os.chdir(APISettings.GIT_DIR)
if call(['git', 'rev-parse']) == 0:
return func(*args)
Shell.fail('There is no git repository!')
return exit(1)
return inner | python | def git_available(func):
"""
Check, if a git repository exists in the given folder.
"""
def inner(*args):
os.chdir(APISettings.GIT_DIR)
if call(['git', 'rev-parse']) == 0:
return func(*args)
Shell.fail('There is no git repository!')
return exit(1)
return inner | [
"def",
"git_available",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
")",
":",
"os",
".",
"chdir",
"(",
"APISettings",
".",
"GIT_DIR",
")",
"if",
"call",
"(",
"[",
"'git'",
",",
"'rev-parse'",
"]",
")",
"==",
"0",
":",
"return",
"func",
"(",
"*",
"args",
")",
"Shell",
".",
"fail",
"(",
"'There is no git repository!'",
")",
"return",
"exit",
"(",
"1",
")",
"return",
"inner"
] | Check, if a git repository exists in the given folder. | [
"Check",
"if",
"a",
"git",
"repository",
"exists",
"in",
"the",
"given",
"folder",
"."
] | 89e885e8c1322fc5c3e0f79b03a55acdc6e63972 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/decorators.py#L8-L21 | train |
YuriyGuts/pygoose | pygoose/kg/gpu.py | _cuda_get_gpu_spec_string | def _cuda_get_gpu_spec_string(gpu_ids=None):
"""
Build a GPU id string to be used for CUDA_VISIBLE_DEVICES.
"""
if gpu_ids is None:
return ''
if isinstance(gpu_ids, list):
return ','.join(str(gpu_id) for gpu_id in gpu_ids)
if isinstance(gpu_ids, int):
return str(gpu_ids)
return gpu_ids | python | def _cuda_get_gpu_spec_string(gpu_ids=None):
"""
Build a GPU id string to be used for CUDA_VISIBLE_DEVICES.
"""
if gpu_ids is None:
return ''
if isinstance(gpu_ids, list):
return ','.join(str(gpu_id) for gpu_id in gpu_ids)
if isinstance(gpu_ids, int):
return str(gpu_ids)
return gpu_ids | [
"def",
"_cuda_get_gpu_spec_string",
"(",
"gpu_ids",
"=",
"None",
")",
":",
"if",
"gpu_ids",
"is",
"None",
":",
"return",
"''",
"if",
"isinstance",
"(",
"gpu_ids",
",",
"list",
")",
":",
"return",
"','",
".",
"join",
"(",
"str",
"(",
"gpu_id",
")",
"for",
"gpu_id",
"in",
"gpu_ids",
")",
"if",
"isinstance",
"(",
"gpu_ids",
",",
"int",
")",
":",
"return",
"str",
"(",
"gpu_ids",
")",
"return",
"gpu_ids"
] | Build a GPU id string to be used for CUDA_VISIBLE_DEVICES. | [
"Build",
"a",
"GPU",
"id",
"string",
"to",
"be",
"used",
"for",
"CUDA_VISIBLE_DEVICES",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/gpu.py#L4-L18 | train |
moluwole/Bast | bast/controller.py | Controller.write_error | def write_error(self, status_code, **kwargs):
"""
Handle Exceptions from the server. Formats the HTML into readable form
"""
reason = self._reason
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
error = []
for line in traceback.format_exception(*kwargs["exc_info"]):
error.append(line)
else:
error = None
data = {'_traceback': error, 'message': reason, 'code': status_code}
content = self.render_exception(**data)
self.write(content) | python | def write_error(self, status_code, **kwargs):
"""
Handle Exceptions from the server. Formats the HTML into readable form
"""
reason = self._reason
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
error = []
for line in traceback.format_exception(*kwargs["exc_info"]):
error.append(line)
else:
error = None
data = {'_traceback': error, 'message': reason, 'code': status_code}
content = self.render_exception(**data)
self.write(content) | [
"def",
"write_error",
"(",
"self",
",",
"status_code",
",",
"*",
"*",
"kwargs",
")",
":",
"reason",
"=",
"self",
".",
"_reason",
"if",
"self",
".",
"settings",
".",
"get",
"(",
"\"serve_traceback\"",
")",
"and",
"\"exc_info\"",
"in",
"kwargs",
":",
"error",
"=",
"[",
"]",
"for",
"line",
"in",
"traceback",
".",
"format_exception",
"(",
"*",
"kwargs",
"[",
"\"exc_info\"",
"]",
")",
":",
"error",
".",
"append",
"(",
"line",
")",
"else",
":",
"error",
"=",
"None",
"data",
"=",
"{",
"'_traceback'",
":",
"error",
",",
"'message'",
":",
"reason",
",",
"'code'",
":",
"status_code",
"}",
"content",
"=",
"self",
".",
"render_exception",
"(",
"*",
"*",
"data",
")",
"self",
".",
"write",
"(",
"content",
")"
] | Handle Exceptions from the server. Formats the HTML into readable form | [
"Handle",
"Exceptions",
"from",
"the",
"server",
".",
"Formats",
"the",
"HTML",
"into",
"readable",
"form"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L37-L51 | train |
moluwole/Bast | bast/controller.py | Controller.view | def view(self, template_name, kwargs=None):
"""
Used to render template to view
Sample usage
+++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
self.view('index.html')
"""
if kwargs is None:
kwargs = dict()
self.add_('session', self.session)
content = self.render_template(template_name, **kwargs)
self.write(content) | python | def view(self, template_name, kwargs=None):
"""
Used to render template to view
Sample usage
+++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
self.view('index.html')
"""
if kwargs is None:
kwargs = dict()
self.add_('session', self.session)
content = self.render_template(template_name, **kwargs)
self.write(content) | [
"def",
"view",
"(",
"self",
",",
"template_name",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"dict",
"(",
")",
"self",
".",
"add_",
"(",
"'session'",
",",
"self",
".",
"session",
")",
"content",
"=",
"self",
".",
"render_template",
"(",
"template_name",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"write",
"(",
"content",
")"
] | Used to render template to view
Sample usage
+++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
self.view('index.html') | [
"Used",
"to",
"render",
"template",
"to",
"view"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L53-L73 | train |
moluwole/Bast | bast/controller.py | Controller.initialize | def initialize(self, method, middleware, request_type):
"""
Overridden initialize method from Tornado. Assigns the controller method and middleware attached to the route being executed
to global variables to be used
"""
self.method = method
self.middleware = middleware
self.request_type = request_type | python | def initialize(self, method, middleware, request_type):
"""
Overridden initialize method from Tornado. Assigns the controller method and middleware attached to the route being executed
to global variables to be used
"""
self.method = method
self.middleware = middleware
self.request_type = request_type | [
"def",
"initialize",
"(",
"self",
",",
"method",
",",
"middleware",
",",
"request_type",
")",
":",
"self",
".",
"method",
"=",
"method",
"self",
".",
"middleware",
"=",
"middleware",
"self",
".",
"request_type",
"=",
"request_type"
] | Overridden initialize method from Tornado. Assigns the controller method and middleware attached to the route being executed
to global variables to be used | [
"Overridden",
"initialize",
"method",
"from",
"Tornado",
".",
"Assigns",
"the",
"controller",
"method",
"and",
"middleware",
"attached",
"to",
"the",
"route",
"being",
"executed",
"to",
"global",
"variables",
"to",
"be",
"used"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L98-L105 | train |
moluwole/Bast | bast/controller.py | Controller.only | def only(self, arguments):
"""
returns the key, value pair of the arguments passed as a dict object
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.only(['username'])
Returns only the argument username and assigns it to the data variable.
"""
data = {}
if not isinstance(arguments, list):
arguments = list(arguments)
for i in arguments:
data[i] = self.get_argument(i)
return data | python | def only(self, arguments):
"""
returns the key, value pair of the arguments passed as a dict object
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.only(['username'])
Returns only the argument username and assigns it to the data variable.
"""
data = {}
if not isinstance(arguments, list):
arguments = list(arguments)
for i in arguments:
data[i] = self.get_argument(i)
return data | [
"def",
"only",
"(",
"self",
",",
"arguments",
")",
":",
"data",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"arguments",
"=",
"list",
"(",
"arguments",
")",
"for",
"i",
"in",
"arguments",
":",
"data",
"[",
"i",
"]",
"=",
"self",
".",
"get_argument",
"(",
"i",
")",
"return",
"data"
] | returns the key, value pair of the arguments passed as a dict object
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.only(['username'])
Returns only the argument username and assigns it to the data variable. | [
"returns",
"the",
"key",
"value",
"pair",
"of",
"the",
"arguments",
"passed",
"as",
"a",
"dict",
"object"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L107-L129 | train |
moluwole/Bast | bast/controller.py | Controller.all | def all(self):
"""
Returns all the arguments passed with the request
Sample Usage
++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.all()
Returns a dictionary of all the request arguments
"""
data = {}
args = self.request.arguments
for key, value in args.items():
data[key] = self.get_argument(key)
return data | python | def all(self):
"""
Returns all the arguments passed with the request
Sample Usage
++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.all()
Returns a dictionary of all the request arguments
"""
data = {}
args = self.request.arguments
for key, value in args.items():
data[key] = self.get_argument(key)
return data | [
"def",
"all",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"args",
"=",
"self",
".",
"request",
".",
"arguments",
"for",
"key",
",",
"value",
"in",
"args",
".",
"items",
"(",
")",
":",
"data",
"[",
"key",
"]",
"=",
"self",
".",
"get_argument",
"(",
"key",
")",
"return",
"data"
] | Returns all the arguments passed with the request
Sample Usage
++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.all()
Returns a dictionary of all the request arguments | [
"Returns",
"all",
"the",
"arguments",
"passed",
"with",
"the",
"request"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L131-L153 | train |
moluwole/Bast | bast/controller.py | Controller.except_ | def except_(self, arguments):
"""
returns the arguments passed to the route except that set by user
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.except_(['arg_name'])
Returns a dictionary of all arguments except for that provided by as ``arg_name``
"""
if not isinstance(arguments, list):
arguments = list(arguments)
args = self.request.arguments
data = {}
for key, value in args.items():
if key not in arguments:
data[key] = self.get_argument(key)
return data | python | def except_(self, arguments):
"""
returns the arguments passed to the route except that set by user
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.except_(['arg_name'])
Returns a dictionary of all arguments except for that provided by as ``arg_name``
"""
if not isinstance(arguments, list):
arguments = list(arguments)
args = self.request.arguments
data = {}
for key, value in args.items():
if key not in arguments:
data[key] = self.get_argument(key)
return data | [
"def",
"except_",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"arguments",
"=",
"list",
"(",
"arguments",
")",
"args",
"=",
"self",
".",
"request",
".",
"arguments",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"arguments",
":",
"data",
"[",
"key",
"]",
"=",
"self",
".",
"get_argument",
"(",
"key",
")",
"return",
"data"
] | returns the arguments passed to the route except that set by user
Sample Usage
++++++++++++++
.. code:: python
from bast import Controller
class MyController(Controller):
def index(self):
data = self.except_(['arg_name'])
Returns a dictionary of all arguments except for that provided by as ``arg_name`` | [
"returns",
"the",
"arguments",
"passed",
"to",
"the",
"route",
"except",
"that",
"set",
"by",
"user"
] | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L155-L180 | train |
neithere/monk | monk/mongo.py | MongoBoundDictMixin.get_one | def get_one(cls, db, *args, **kwargs):
"""
Returns an object that corresponds to given query or ``None``.
Example::
item = Item.get_one(db, {'title': u'Hello'})
"""
data = db[cls.collection].find_one(*args, **kwargs)
if data:
return cls.wrap_incoming(data, db)
else:
return None | python | def get_one(cls, db, *args, **kwargs):
"""
Returns an object that corresponds to given query or ``None``.
Example::
item = Item.get_one(db, {'title': u'Hello'})
"""
data = db[cls.collection].find_one(*args, **kwargs)
if data:
return cls.wrap_incoming(data, db)
else:
return None | [
"def",
"get_one",
"(",
"cls",
",",
"db",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"db",
"[",
"cls",
".",
"collection",
"]",
".",
"find_one",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"cls",
".",
"wrap_incoming",
"(",
"data",
",",
"db",
")",
"else",
":",
"return",
"None"
] | Returns an object that corresponds to given query or ``None``.
Example::
item = Item.get_one(db, {'title': u'Hello'}) | [
"Returns",
"an",
"object",
"that",
"corresponds",
"to",
"given",
"query",
"or",
"None",
"."
] | 4b2ee5152b081ac288ce8568422a027b5e7d2b1c | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L186-L199 | train |
neithere/monk | monk/mongo.py | MongoBoundDictMixin.get_id | def get_id(self):
""" Returns object id or ``None``.
"""
import warnings
warnings.warn('{0}.get_id() is deprecated, '
'use {0}.id instead'.format(type(self).__name__),
DeprecationWarning)
return self.get('_id') | python | def get_id(self):
""" Returns object id or ``None``.
"""
import warnings
warnings.warn('{0}.get_id() is deprecated, '
'use {0}.id instead'.format(type(self).__name__),
DeprecationWarning)
return self.get('_id') | [
"def",
"get_id",
"(",
"self",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'{0}.get_id() is deprecated, '",
"'use {0}.id instead'",
".",
"format",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
")",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"get",
"(",
"'_id'",
")"
] | Returns object id or ``None``. | [
"Returns",
"object",
"id",
"or",
"None",
"."
] | 4b2ee5152b081ac288ce8568422a027b5e7d2b1c | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L232-L239 | train |
neithere/monk | monk/mongo.py | MongoBoundDictMixin.get_ref | def get_ref(self):
""" Returns a `DBRef` for this object or ``None``.
"""
_id = self.id
if _id is None:
return None
else:
return DBRef(self.collection, _id) | python | def get_ref(self):
""" Returns a `DBRef` for this object or ``None``.
"""
_id = self.id
if _id is None:
return None
else:
return DBRef(self.collection, _id) | [
"def",
"get_ref",
"(",
"self",
")",
":",
"_id",
"=",
"self",
".",
"id",
"if",
"_id",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"DBRef",
"(",
"self",
".",
"collection",
",",
"_id",
")"
] | Returns a `DBRef` for this object or ``None``. | [
"Returns",
"a",
"DBRef",
"for",
"this",
"object",
"or",
"None",
"."
] | 4b2ee5152b081ac288ce8568422a027b5e7d2b1c | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/mongo.py#L241-L248 | train |
quikmile/trellio | trellio/utils/log.py | CustomTimeLoggingFormatter.formatTime | def formatTime(self, record, datefmt=None): # noqa
"""
Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds.
"""
if datefmt:
s = datetime.datetime.now().strftime(datefmt)
else:
t = datetime.datetime.now().strftime(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s | python | def formatTime(self, record, datefmt=None): # noqa
"""
Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds.
"""
if datefmt:
s = datetime.datetime.now().strftime(datefmt)
else:
t = datetime.datetime.now().strftime(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"# noqa",
"if",
"datefmt",
":",
"s",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"datefmt",
")",
"else",
":",
"t",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"self",
".",
"default_time_format",
")",
"s",
"=",
"self",
".",
"default_msec_format",
"%",
"(",
"t",
",",
"record",
".",
"msecs",
")",
"return",
"s"
] | Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds. | [
"Overrides",
"formatTime",
"method",
"to",
"use",
"datetime",
"module",
"instead",
"of",
"time",
"module",
"to",
"display",
"time",
"in",
"microseconds",
".",
"Time",
"module",
"by",
"default",
"does",
"not",
"resolve",
"time",
"to",
"microseconds",
"."
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/utils/log.py#L21-L32 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogQuerySet.related_to | def related_to(self, instance):
"""Filter for all log objects of the same connected model as the given instance."""
return self.filter(table_name=instance.table_name, record_id=instance.record_id) | python | def related_to(self, instance):
"""Filter for all log objects of the same connected model as the given instance."""
return self.filter(table_name=instance.table_name, record_id=instance.record_id) | [
"def",
"related_to",
"(",
"self",
",",
"instance",
")",
":",
"return",
"self",
".",
"filter",
"(",
"table_name",
"=",
"instance",
".",
"table_name",
",",
"record_id",
"=",
"instance",
".",
"record_id",
")"
] | Filter for all log objects of the same connected model as the given instance. | [
"Filter",
"for",
"all",
"log",
"objects",
"of",
"the",
"same",
"connected",
"model",
"as",
"the",
"given",
"instance",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L18-L20 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogAbstract.capture_insert_from_model | def capture_insert_from_model(cls, table_name, record_id, *, exclude_fields=()):
"""
Create a fresh insert record from the current model state in the database.
For read-write connected models, this will lead to the attempted creation of a
corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
exclude_fields (Iterable[str]): The names of fields that will not be included in the
write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model
"""
exclude_cols = ()
if exclude_fields:
model_cls = get_connected_model_for_table_name(table_name)
exclude_cols = cls._fieldnames_to_colnames(model_cls, exclude_fields)
raw_query = sql.SQL("""
SELECT {schema}.hc_capture_insert_from_row(
hstore({schema}.{table_name}.*),
%(table_name)s,
ARRAY[{exclude_cols}]::text[] -- cast to type expected by stored procedure
) AS id
FROM {schema}.{table_name}
WHERE id = %(record_id)s
""").format(
schema=sql.Identifier(settings.HEROKU_CONNECT_SCHEMA),
table_name=sql.Identifier(table_name),
exclude_cols=sql.SQL(', ').join(sql.Identifier(col) for col in exclude_cols),
)
params = {'record_id': record_id, 'table_name': table_name}
result_qs = TriggerLog.objects.raw(raw_query, params)
return list(result_qs) | python | def capture_insert_from_model(cls, table_name, record_id, *, exclude_fields=()):
"""
Create a fresh insert record from the current model state in the database.
For read-write connected models, this will lead to the attempted creation of a
corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
exclude_fields (Iterable[str]): The names of fields that will not be included in the
write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model
"""
exclude_cols = ()
if exclude_fields:
model_cls = get_connected_model_for_table_name(table_name)
exclude_cols = cls._fieldnames_to_colnames(model_cls, exclude_fields)
raw_query = sql.SQL("""
SELECT {schema}.hc_capture_insert_from_row(
hstore({schema}.{table_name}.*),
%(table_name)s,
ARRAY[{exclude_cols}]::text[] -- cast to type expected by stored procedure
) AS id
FROM {schema}.{table_name}
WHERE id = %(record_id)s
""").format(
schema=sql.Identifier(settings.HEROKU_CONNECT_SCHEMA),
table_name=sql.Identifier(table_name),
exclude_cols=sql.SQL(', ').join(sql.Identifier(col) for col in exclude_cols),
)
params = {'record_id': record_id, 'table_name': table_name}
result_qs = TriggerLog.objects.raw(raw_query, params)
return list(result_qs) | [
"def",
"capture_insert_from_model",
"(",
"cls",
",",
"table_name",
",",
"record_id",
",",
"*",
",",
"exclude_fields",
"=",
"(",
")",
")",
":",
"exclude_cols",
"=",
"(",
")",
"if",
"exclude_fields",
":",
"model_cls",
"=",
"get_connected_model_for_table_name",
"(",
"table_name",
")",
"exclude_cols",
"=",
"cls",
".",
"_fieldnames_to_colnames",
"(",
"model_cls",
",",
"exclude_fields",
")",
"raw_query",
"=",
"sql",
".",
"SQL",
"(",
"\"\"\"\n SELECT {schema}.hc_capture_insert_from_row(\n hstore({schema}.{table_name}.*),\n %(table_name)s,\n ARRAY[{exclude_cols}]::text[] -- cast to type expected by stored procedure\n ) AS id\n FROM {schema}.{table_name}\n WHERE id = %(record_id)s\n \"\"\"",
")",
".",
"format",
"(",
"schema",
"=",
"sql",
".",
"Identifier",
"(",
"settings",
".",
"HEROKU_CONNECT_SCHEMA",
")",
",",
"table_name",
"=",
"sql",
".",
"Identifier",
"(",
"table_name",
")",
",",
"exclude_cols",
"=",
"sql",
".",
"SQL",
"(",
"', '",
")",
".",
"join",
"(",
"sql",
".",
"Identifier",
"(",
"col",
")",
"for",
"col",
"in",
"exclude_cols",
")",
",",
")",
"params",
"=",
"{",
"'record_id'",
":",
"record_id",
",",
"'table_name'",
":",
"table_name",
"}",
"result_qs",
"=",
"TriggerLog",
".",
"objects",
".",
"raw",
"(",
"raw_query",
",",
"params",
")",
"return",
"list",
"(",
"result_qs",
")"
] | Create a fresh insert record from the current model state in the database.
For read-write connected models, this will lead to the attempted creation of a
corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
exclude_fields (Iterable[str]): The names of fields that will not be included in the
write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model | [
"Create",
"a",
"fresh",
"insert",
"record",
"from",
"the",
"current",
"model",
"state",
"in",
"the",
"database",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L130-L170 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogAbstract.capture_update_from_model | def capture_update_from_model(cls, table_name, record_id, *, update_fields=()):
"""
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
update_fields (Iterable[str]): If given, the names of fields that will be included in
the write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model
"""
include_cols = ()
if update_fields:
model_cls = get_connected_model_for_table_name(table_name)
include_cols = cls._fieldnames_to_colnames(model_cls, update_fields)
raw_query = sql.SQL("""
SELECT {schema}.hc_capture_update_from_row(
hstore({schema}.{table_name}.*),
%(table_name)s,
ARRAY[{include_cols}]::text[] -- cast to type expected by stored procedure
) AS id
FROM {schema}.{table_name}
WHERE id = %(record_id)s
""").format(
schema=sql.Identifier(settings.HEROKU_CONNECT_SCHEMA),
table_name=sql.Identifier(table_name),
include_cols=sql.SQL(', ').join(sql.Identifier(col) for col in include_cols),
)
params = {'record_id': record_id, 'table_name': table_name}
result_qs = TriggerLog.objects.raw(raw_query, params)
return list(result_qs) | python | def capture_update_from_model(cls, table_name, record_id, *, update_fields=()):
"""
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
update_fields (Iterable[str]): If given, the names of fields that will be included in
the write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model
"""
include_cols = ()
if update_fields:
model_cls = get_connected_model_for_table_name(table_name)
include_cols = cls._fieldnames_to_colnames(model_cls, update_fields)
raw_query = sql.SQL("""
SELECT {schema}.hc_capture_update_from_row(
hstore({schema}.{table_name}.*),
%(table_name)s,
ARRAY[{include_cols}]::text[] -- cast to type expected by stored procedure
) AS id
FROM {schema}.{table_name}
WHERE id = %(record_id)s
""").format(
schema=sql.Identifier(settings.HEROKU_CONNECT_SCHEMA),
table_name=sql.Identifier(table_name),
include_cols=sql.SQL(', ').join(sql.Identifier(col) for col in include_cols),
)
params = {'record_id': record_id, 'table_name': table_name}
result_qs = TriggerLog.objects.raw(raw_query, params)
return list(result_qs) | [
"def",
"capture_update_from_model",
"(",
"cls",
",",
"table_name",
",",
"record_id",
",",
"*",
",",
"update_fields",
"=",
"(",
")",
")",
":",
"include_cols",
"=",
"(",
")",
"if",
"update_fields",
":",
"model_cls",
"=",
"get_connected_model_for_table_name",
"(",
"table_name",
")",
"include_cols",
"=",
"cls",
".",
"_fieldnames_to_colnames",
"(",
"model_cls",
",",
"update_fields",
")",
"raw_query",
"=",
"sql",
".",
"SQL",
"(",
"\"\"\"\n SELECT {schema}.hc_capture_update_from_row(\n hstore({schema}.{table_name}.*),\n %(table_name)s,\n ARRAY[{include_cols}]::text[] -- cast to type expected by stored procedure\n ) AS id\n FROM {schema}.{table_name}\n WHERE id = %(record_id)s\n \"\"\"",
")",
".",
"format",
"(",
"schema",
"=",
"sql",
".",
"Identifier",
"(",
"settings",
".",
"HEROKU_CONNECT_SCHEMA",
")",
",",
"table_name",
"=",
"sql",
".",
"Identifier",
"(",
"table_name",
")",
",",
"include_cols",
"=",
"sql",
".",
"SQL",
"(",
"', '",
")",
".",
"join",
"(",
"sql",
".",
"Identifier",
"(",
"col",
")",
"for",
"col",
"in",
"include_cols",
")",
",",
")",
"params",
"=",
"{",
"'record_id'",
":",
"record_id",
",",
"'table_name'",
":",
"table_name",
"}",
"result_qs",
"=",
"TriggerLog",
".",
"objects",
".",
"raw",
"(",
"raw_query",
",",
"params",
")",
"return",
"list",
"(",
"result_qs",
")"
] | Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (without schema)
record_id (int): The primary id of the connected model
update_fields (Iterable[str]): If given, the names of fields that will be included in
the write record
Returns:
A list of the created TriggerLog entries (usually one).
Raises:
LookupError: if ``table_name`` does not belong to a connected model | [
"Create",
"a",
"fresh",
"update",
"record",
"from",
"the",
"current",
"model",
"state",
"in",
"the",
"database",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L173-L212 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogAbstract.get_model | def get_model(self):
"""
Fetch the instance of the connected model referenced by this log record.
Returns:
The connected instance, or ``None`` if it does not exists.
"""
model_cls = get_connected_model_for_table_name(self.table_name)
return model_cls._default_manager.filter(id=self.record_id).first() | python | def get_model(self):
"""
Fetch the instance of the connected model referenced by this log record.
Returns:
The connected instance, or ``None`` if it does not exists.
"""
model_cls = get_connected_model_for_table_name(self.table_name)
return model_cls._default_manager.filter(id=self.record_id).first() | [
"def",
"get_model",
"(",
"self",
")",
":",
"model_cls",
"=",
"get_connected_model_for_table_name",
"(",
"self",
".",
"table_name",
")",
"return",
"model_cls",
".",
"_default_manager",
".",
"filter",
"(",
"id",
"=",
"self",
".",
"record_id",
")",
".",
"first",
"(",
")"
] | Fetch the instance of the connected model referenced by this log record.
Returns:
The connected instance, or ``None`` if it does not exists. | [
"Fetch",
"the",
"instance",
"of",
"the",
"connected",
"model",
"referenced",
"by",
"this",
"log",
"record",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L223-L232 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogAbstract.related | def related(self, *, exclude_self=False):
"""
Get a QuerySet for all trigger log objects for the same connected model.
Args:
exclude_self (bool): Whether to exclude this log object from the result list
"""
manager = type(self)._default_manager
queryset = manager.related_to(self)
if exclude_self:
queryset = queryset.exclude(id=self.id)
return queryset | python | def related(self, *, exclude_self=False):
"""
Get a QuerySet for all trigger log objects for the same connected model.
Args:
exclude_self (bool): Whether to exclude this log object from the result list
"""
manager = type(self)._default_manager
queryset = manager.related_to(self)
if exclude_self:
queryset = queryset.exclude(id=self.id)
return queryset | [
"def",
"related",
"(",
"self",
",",
"*",
",",
"exclude_self",
"=",
"False",
")",
":",
"manager",
"=",
"type",
"(",
"self",
")",
".",
"_default_manager",
"queryset",
"=",
"manager",
".",
"related_to",
"(",
"self",
")",
"if",
"exclude_self",
":",
"queryset",
"=",
"queryset",
".",
"exclude",
"(",
"id",
"=",
"self",
".",
"id",
")",
"return",
"queryset"
] | Get a QuerySet for all trigger log objects for the same connected model.
Args:
exclude_self (bool): Whether to exclude this log object from the result list | [
"Get",
"a",
"QuerySet",
"for",
"all",
"trigger",
"log",
"objects",
"for",
"the",
"same",
"connected",
"model",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L234-L245 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogAbstract._fieldnames_to_colnames | def _fieldnames_to_colnames(model_cls, fieldnames):
"""Get the names of columns referenced by the given model fields."""
get_field = model_cls._meta.get_field
fields = map(get_field, fieldnames)
return {f.column for f in fields} | python | def _fieldnames_to_colnames(model_cls, fieldnames):
"""Get the names of columns referenced by the given model fields."""
get_field = model_cls._meta.get_field
fields = map(get_field, fieldnames)
return {f.column for f in fields} | [
"def",
"_fieldnames_to_colnames",
"(",
"model_cls",
",",
"fieldnames",
")",
":",
"get_field",
"=",
"model_cls",
".",
"_meta",
".",
"get_field",
"fields",
"=",
"map",
"(",
"get_field",
",",
"fieldnames",
")",
"return",
"{",
"f",
".",
"column",
"for",
"f",
"in",
"fields",
"}"
] | Get the names of columns referenced by the given model fields. | [
"Get",
"the",
"names",
"of",
"columns",
"referenced",
"by",
"the",
"given",
"model",
"fields",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L258-L262 | train |
Thermondo/django-heroku-connect | heroku_connect/models.py | TriggerLogArchive.redo | def redo(self):
"""
Re-sync the change recorded in this trigger log.
Creates a ``NEW`` live trigger log from the data in this archived trigger log and sets
the state of this archived instance to ``REQUEUED``.
.. seealso:: :meth:`.TriggerLog.redo`
Returns:
The :class:`.TriggerLog` instance that was created from the data of this archived log.
"""
trigger_log = self._to_live_trigger_log(state=TRIGGER_LOG_STATE['NEW'])
trigger_log.save(force_insert=True) # make sure we get a fresh row
self.state = TRIGGER_LOG_STATE['REQUEUED']
self.save(update_fields=['state'])
return trigger_log | python | def redo(self):
"""
Re-sync the change recorded in this trigger log.
Creates a ``NEW`` live trigger log from the data in this archived trigger log and sets
the state of this archived instance to ``REQUEUED``.
.. seealso:: :meth:`.TriggerLog.redo`
Returns:
The :class:`.TriggerLog` instance that was created from the data of this archived log.
"""
trigger_log = self._to_live_trigger_log(state=TRIGGER_LOG_STATE['NEW'])
trigger_log.save(force_insert=True) # make sure we get a fresh row
self.state = TRIGGER_LOG_STATE['REQUEUED']
self.save(update_fields=['state'])
return trigger_log | [
"def",
"redo",
"(",
"self",
")",
":",
"trigger_log",
"=",
"self",
".",
"_to_live_trigger_log",
"(",
"state",
"=",
"TRIGGER_LOG_STATE",
"[",
"'NEW'",
"]",
")",
"trigger_log",
".",
"save",
"(",
"force_insert",
"=",
"True",
")",
"# make sure we get a fresh row",
"self",
".",
"state",
"=",
"TRIGGER_LOG_STATE",
"[",
"'REQUEUED'",
"]",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'state'",
"]",
")",
"return",
"trigger_log"
] | Re-sync the change recorded in this trigger log.
Creates a ``NEW`` live trigger log from the data in this archived trigger log and sets
the state of this archived instance to ``REQUEUED``.
.. seealso:: :meth:`.TriggerLog.redo`
Returns:
The :class:`.TriggerLog` instance that was created from the data of this archived log. | [
"Re",
"-",
"sync",
"the",
"change",
"recorded",
"in",
"this",
"trigger",
"log",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L308-L325 | train |
glormph/msstitch | src/app/actions/prottable/isoquant.py | add_isoquant_data | def add_isoquant_data(proteins, quantproteins, quantacc, quantfields):
"""Runs through a protein table and adds quant data from ANOTHER protein
table that contains that data."""
for protein in base_add_isoquant_data(proteins, quantproteins,
prottabledata.HEADER_PROTEIN,
quantacc, quantfields):
yield protein | python | def add_isoquant_data(proteins, quantproteins, quantacc, quantfields):
"""Runs through a protein table and adds quant data from ANOTHER protein
table that contains that data."""
for protein in base_add_isoquant_data(proteins, quantproteins,
prottabledata.HEADER_PROTEIN,
quantacc, quantfields):
yield protein | [
"def",
"add_isoquant_data",
"(",
"proteins",
",",
"quantproteins",
",",
"quantacc",
",",
"quantfields",
")",
":",
"for",
"protein",
"in",
"base_add_isoquant_data",
"(",
"proteins",
",",
"quantproteins",
",",
"prottabledata",
".",
"HEADER_PROTEIN",
",",
"quantacc",
",",
"quantfields",
")",
":",
"yield",
"protein"
] | Runs through a protein table and adds quant data from ANOTHER protein
table that contains that data. | [
"Runs",
"through",
"a",
"protein",
"table",
"and",
"adds",
"quant",
"data",
"from",
"ANOTHER",
"protein",
"table",
"that",
"contains",
"that",
"data",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/isoquant.py#L15-L21 | train |
glormph/msstitch | src/app/actions/peptable/isoquant.py | add_isoquant_data | def add_isoquant_data(peptides, quantpeptides, quantacc, quantfields):
"""Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data."""
for peptide in base_add_isoquant_data(peptides, quantpeptides,
peptabledata.HEADER_PEPTIDE,
quantacc, quantfields):
yield peptide | python | def add_isoquant_data(peptides, quantpeptides, quantacc, quantfields):
"""Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data."""
for peptide in base_add_isoquant_data(peptides, quantpeptides,
peptabledata.HEADER_PEPTIDE,
quantacc, quantfields):
yield peptide | [
"def",
"add_isoquant_data",
"(",
"peptides",
",",
"quantpeptides",
",",
"quantacc",
",",
"quantfields",
")",
":",
"for",
"peptide",
"in",
"base_add_isoquant_data",
"(",
"peptides",
",",
"quantpeptides",
",",
"peptabledata",
".",
"HEADER_PEPTIDE",
",",
"quantacc",
",",
"quantfields",
")",
":",
"yield",
"peptide"
] | Runs through a peptide table and adds quant data from ANOTHER peptide
table that contains that data. | [
"Runs",
"through",
"a",
"peptide",
"table",
"and",
"adds",
"quant",
"data",
"from",
"ANOTHER",
"peptide",
"table",
"that",
"contains",
"that",
"data",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/peptable/isoquant.py#L5-L11 | train |
chriso/gauged | gauged/results/time_series.py | TimeSeries.map | def map(self, fn):
"""Run a map function across all y points in the series"""
return TimeSeries([(x, fn(y)) for x, y in self.points]) | python | def map(self, fn):
"""Run a map function across all y points in the series"""
return TimeSeries([(x, fn(y)) for x, y in self.points]) | [
"def",
"map",
"(",
"self",
",",
"fn",
")",
":",
"return",
"TimeSeries",
"(",
"[",
"(",
"x",
",",
"fn",
"(",
"y",
")",
")",
"for",
"x",
",",
"y",
"in",
"self",
".",
"points",
"]",
")"
] | Run a map function across all y points in the series | [
"Run",
"a",
"map",
"function",
"across",
"all",
"y",
"points",
"in",
"the",
"series"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/results/time_series.py#L43-L45 | train |
glormph/msstitch | src/app/actions/prottable/merge.py | build_proteintable | def build_proteintable(pqdb, headerfields, mergecutoff, isobaric=False,
precursor=False, probability=False, fdr=False,
pep=False, genecentric=False):
"""Fetches proteins and quants from joined lookup table, loops through
them and when all of a protein's quants have been collected, yields the
protein quant information."""
pdmap = create_featuredata_map(pqdb, genecentric=genecentric,
psm_fill_fun=pinfo.add_psms_to_proteindata,
pgene_fill_fun=pinfo.add_protgene_to_protdata,
count_fun=pinfo.count_peps_psms,
get_uniques=True)
empty_return = lambda x, y, z: {}
iso_fun = {True: get_isobaric_quant, False: empty_return}[isobaric]
ms1_fun = {True: get_precursor_quant, False: empty_return}[precursor]
prob_fun = {True: get_prot_probability,
False: empty_return}[probability]
fdr_fun = {True: get_prot_fdr,
False: empty_return}[fdr]
pep_fun = {True: get_prot_pep,
False: empty_return}[pep]
pdata_fun = {True: get_protein_data_genecentric,
False: get_protein_data}[genecentric is not False]
protein_sql, sqlfieldmap = pqdb.prepare_mergetable_sql(precursor, isobaric,
probability, fdr,
pep)
accession_field = prottabledata.ACCESSIONS[genecentric]
proteins = pqdb.get_merged_features(protein_sql)
protein = next(proteins)
outprotein = {accession_field: protein[sqlfieldmap['p_acc']]}
check_prot = {k: v for k, v in outprotein.items()}
if not mergecutoff or protein_pool_fdr_cutoff(protein, sqlfieldmap,
mergecutoff):
fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun,
pep_fun, pdata_fun, protein, sqlfieldmap,
headerfields, pdmap, accession_field)
for protein in proteins:
if mergecutoff and not protein_pool_fdr_cutoff(protein, sqlfieldmap,
mergecutoff):
continue
p_acc = protein[sqlfieldmap['p_acc']]
if p_acc != outprotein[accession_field]:
# check if protein has been filled, otherwise do not output
# sometimes proteins have NA in all fields
if outprotein != check_prot:
yield outprotein
outprotein = {accession_field: p_acc}
check_prot = {k: v for k, v in outprotein.items()}
fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun,
pep_fun, pdata_fun, protein, sqlfieldmap,
headerfields, pdmap, accession_field)
if outprotein != check_prot:
yield outprotein | python | def build_proteintable(pqdb, headerfields, mergecutoff, isobaric=False,
precursor=False, probability=False, fdr=False,
pep=False, genecentric=False):
"""Fetches proteins and quants from joined lookup table, loops through
them and when all of a protein's quants have been collected, yields the
protein quant information."""
pdmap = create_featuredata_map(pqdb, genecentric=genecentric,
psm_fill_fun=pinfo.add_psms_to_proteindata,
pgene_fill_fun=pinfo.add_protgene_to_protdata,
count_fun=pinfo.count_peps_psms,
get_uniques=True)
empty_return = lambda x, y, z: {}
iso_fun = {True: get_isobaric_quant, False: empty_return}[isobaric]
ms1_fun = {True: get_precursor_quant, False: empty_return}[precursor]
prob_fun = {True: get_prot_probability,
False: empty_return}[probability]
fdr_fun = {True: get_prot_fdr,
False: empty_return}[fdr]
pep_fun = {True: get_prot_pep,
False: empty_return}[pep]
pdata_fun = {True: get_protein_data_genecentric,
False: get_protein_data}[genecentric is not False]
protein_sql, sqlfieldmap = pqdb.prepare_mergetable_sql(precursor, isobaric,
probability, fdr,
pep)
accession_field = prottabledata.ACCESSIONS[genecentric]
proteins = pqdb.get_merged_features(protein_sql)
protein = next(proteins)
outprotein = {accession_field: protein[sqlfieldmap['p_acc']]}
check_prot = {k: v for k, v in outprotein.items()}
if not mergecutoff or protein_pool_fdr_cutoff(protein, sqlfieldmap,
mergecutoff):
fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun,
pep_fun, pdata_fun, protein, sqlfieldmap,
headerfields, pdmap, accession_field)
for protein in proteins:
if mergecutoff and not protein_pool_fdr_cutoff(protein, sqlfieldmap,
mergecutoff):
continue
p_acc = protein[sqlfieldmap['p_acc']]
if p_acc != outprotein[accession_field]:
# check if protein has been filled, otherwise do not output
# sometimes proteins have NA in all fields
if outprotein != check_prot:
yield outprotein
outprotein = {accession_field: p_acc}
check_prot = {k: v for k, v in outprotein.items()}
fill_mergefeature(outprotein, iso_fun, ms1_fun, prob_fun, fdr_fun,
pep_fun, pdata_fun, protein, sqlfieldmap,
headerfields, pdmap, accession_field)
if outprotein != check_prot:
yield outprotein | [
"def",
"build_proteintable",
"(",
"pqdb",
",",
"headerfields",
",",
"mergecutoff",
",",
"isobaric",
"=",
"False",
",",
"precursor",
"=",
"False",
",",
"probability",
"=",
"False",
",",
"fdr",
"=",
"False",
",",
"pep",
"=",
"False",
",",
"genecentric",
"=",
"False",
")",
":",
"pdmap",
"=",
"create_featuredata_map",
"(",
"pqdb",
",",
"genecentric",
"=",
"genecentric",
",",
"psm_fill_fun",
"=",
"pinfo",
".",
"add_psms_to_proteindata",
",",
"pgene_fill_fun",
"=",
"pinfo",
".",
"add_protgene_to_protdata",
",",
"count_fun",
"=",
"pinfo",
".",
"count_peps_psms",
",",
"get_uniques",
"=",
"True",
")",
"empty_return",
"=",
"lambda",
"x",
",",
"y",
",",
"z",
":",
"{",
"}",
"iso_fun",
"=",
"{",
"True",
":",
"get_isobaric_quant",
",",
"False",
":",
"empty_return",
"}",
"[",
"isobaric",
"]",
"ms1_fun",
"=",
"{",
"True",
":",
"get_precursor_quant",
",",
"False",
":",
"empty_return",
"}",
"[",
"precursor",
"]",
"prob_fun",
"=",
"{",
"True",
":",
"get_prot_probability",
",",
"False",
":",
"empty_return",
"}",
"[",
"probability",
"]",
"fdr_fun",
"=",
"{",
"True",
":",
"get_prot_fdr",
",",
"False",
":",
"empty_return",
"}",
"[",
"fdr",
"]",
"pep_fun",
"=",
"{",
"True",
":",
"get_prot_pep",
",",
"False",
":",
"empty_return",
"}",
"[",
"pep",
"]",
"pdata_fun",
"=",
"{",
"True",
":",
"get_protein_data_genecentric",
",",
"False",
":",
"get_protein_data",
"}",
"[",
"genecentric",
"is",
"not",
"False",
"]",
"protein_sql",
",",
"sqlfieldmap",
"=",
"pqdb",
".",
"prepare_mergetable_sql",
"(",
"precursor",
",",
"isobaric",
",",
"probability",
",",
"fdr",
",",
"pep",
")",
"accession_field",
"=",
"prottabledata",
".",
"ACCESSIONS",
"[",
"genecentric",
"]",
"proteins",
"=",
"pqdb",
".",
"get_merged_features",
"(",
"protein_sql",
")",
"protein",
"=",
"next",
"(",
"proteins",
")",
"outprotein",
"=",
"{",
"accession_field",
":",
"protein",
"[",
"sqlfieldmap",
"[",
"'p_acc'",
"]",
"]",
"}",
"check_prot",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"outprotein",
".",
"items",
"(",
")",
"}",
"if",
"not",
"mergecutoff",
"or",
"protein_pool_fdr_cutoff",
"(",
"protein",
",",
"sqlfieldmap",
",",
"mergecutoff",
")",
":",
"fill_mergefeature",
"(",
"outprotein",
",",
"iso_fun",
",",
"ms1_fun",
",",
"prob_fun",
",",
"fdr_fun",
",",
"pep_fun",
",",
"pdata_fun",
",",
"protein",
",",
"sqlfieldmap",
",",
"headerfields",
",",
"pdmap",
",",
"accession_field",
")",
"for",
"protein",
"in",
"proteins",
":",
"if",
"mergecutoff",
"and",
"not",
"protein_pool_fdr_cutoff",
"(",
"protein",
",",
"sqlfieldmap",
",",
"mergecutoff",
")",
":",
"continue",
"p_acc",
"=",
"protein",
"[",
"sqlfieldmap",
"[",
"'p_acc'",
"]",
"]",
"if",
"p_acc",
"!=",
"outprotein",
"[",
"accession_field",
"]",
":",
"# check if protein has been filled, otherwise do not output",
"# sometimes proteins have NA in all fields",
"if",
"outprotein",
"!=",
"check_prot",
":",
"yield",
"outprotein",
"outprotein",
"=",
"{",
"accession_field",
":",
"p_acc",
"}",
"check_prot",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"outprotein",
".",
"items",
"(",
")",
"}",
"fill_mergefeature",
"(",
"outprotein",
",",
"iso_fun",
",",
"ms1_fun",
",",
"prob_fun",
",",
"fdr_fun",
",",
"pep_fun",
",",
"pdata_fun",
",",
"protein",
",",
"sqlfieldmap",
",",
"headerfields",
",",
"pdmap",
",",
"accession_field",
")",
"if",
"outprotein",
"!=",
"check_prot",
":",
"yield",
"outprotein"
] | Fetches proteins and quants from joined lookup table, loops through
them and when all of a protein's quants have been collected, yields the
protein quant information. | [
"Fetches",
"proteins",
"and",
"quants",
"from",
"joined",
"lookup",
"table",
"loops",
"through",
"them",
"and",
"when",
"all",
"of",
"a",
"protein",
"s",
"quants",
"have",
"been",
"collected",
"yields",
"the",
"protein",
"quant",
"information",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/merge.py#L9-L60 | train |
glormph/msstitch | src/app/actions/mzidtsv/proteingrouping.py | count_protein_group_hits | def count_protein_group_hits(lineproteins, groups):
"""Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts.
"""
hits = []
for group in groups:
hits.append(0)
for protein in lineproteins:
if protein in group:
hits[-1] += 1
return [str(x) for x in hits] | python | def count_protein_group_hits(lineproteins, groups):
"""Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts.
"""
hits = []
for group in groups:
hits.append(0)
for protein in lineproteins:
if protein in group:
hits[-1] += 1
return [str(x) for x in hits] | [
"def",
"count_protein_group_hits",
"(",
"lineproteins",
",",
"groups",
")",
":",
"hits",
"=",
"[",
"]",
"for",
"group",
"in",
"groups",
":",
"hits",
".",
"append",
"(",
"0",
")",
"for",
"protein",
"in",
"lineproteins",
":",
"if",
"protein",
"in",
"group",
":",
"hits",
"[",
"-",
"1",
"]",
"+=",
"1",
"return",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"hits",
"]"
] | Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts. | [
"Takes",
"a",
"list",
"of",
"protein",
"accessions",
"and",
"a",
"list",
"of",
"protein",
"groups",
"content",
"from",
"DB",
".",
"Counts",
"for",
"each",
"group",
"in",
"list",
"how",
"many",
"proteins",
"are",
"found",
"in",
"lineproteins",
".",
"Returns",
"list",
"of",
"str",
"amounts",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/proteingrouping.py#L57-L68 | train |
Erotemic/utool | utool/util_logging.py | get_logging_dir | def get_logging_dir(appname='default'):
"""
The default log dir is in the system resource directory
But the utool global cache allows for the user to override
where the logs for a specific app should be stored.
Returns:
log_dir_realpath (str): real path to logging directory
"""
from utool._internal import meta_util_cache
from utool._internal import meta_util_cplat
from utool import util_cache
if appname is None or appname == 'default':
appname = util_cache.get_default_appname()
resource_dpath = meta_util_cplat.get_resource_dir()
default = join(resource_dpath, appname, 'logs')
# Check global cache for a custom logging dir otherwise
# use the default.
log_dir = meta_util_cache.global_cache_read(logdir_cacheid,
appname=appname,
default=default)
log_dir_realpath = realpath(log_dir)
return log_dir_realpath | python | def get_logging_dir(appname='default'):
"""
The default log dir is in the system resource directory
But the utool global cache allows for the user to override
where the logs for a specific app should be stored.
Returns:
log_dir_realpath (str): real path to logging directory
"""
from utool._internal import meta_util_cache
from utool._internal import meta_util_cplat
from utool import util_cache
if appname is None or appname == 'default':
appname = util_cache.get_default_appname()
resource_dpath = meta_util_cplat.get_resource_dir()
default = join(resource_dpath, appname, 'logs')
# Check global cache for a custom logging dir otherwise
# use the default.
log_dir = meta_util_cache.global_cache_read(logdir_cacheid,
appname=appname,
default=default)
log_dir_realpath = realpath(log_dir)
return log_dir_realpath | [
"def",
"get_logging_dir",
"(",
"appname",
"=",
"'default'",
")",
":",
"from",
"utool",
".",
"_internal",
"import",
"meta_util_cache",
"from",
"utool",
".",
"_internal",
"import",
"meta_util_cplat",
"from",
"utool",
"import",
"util_cache",
"if",
"appname",
"is",
"None",
"or",
"appname",
"==",
"'default'",
":",
"appname",
"=",
"util_cache",
".",
"get_default_appname",
"(",
")",
"resource_dpath",
"=",
"meta_util_cplat",
".",
"get_resource_dir",
"(",
")",
"default",
"=",
"join",
"(",
"resource_dpath",
",",
"appname",
",",
"'logs'",
")",
"# Check global cache for a custom logging dir otherwise",
"# use the default.",
"log_dir",
"=",
"meta_util_cache",
".",
"global_cache_read",
"(",
"logdir_cacheid",
",",
"appname",
"=",
"appname",
",",
"default",
"=",
"default",
")",
"log_dir_realpath",
"=",
"realpath",
"(",
"log_dir",
")",
"return",
"log_dir_realpath"
] | The default log dir is in the system resource directory
But the utool global cache allows for the user to override
where the logs for a specific app should be stored.
Returns:
log_dir_realpath (str): real path to logging directory | [
"The",
"default",
"log",
"dir",
"is",
"in",
"the",
"system",
"resource",
"directory",
"But",
"the",
"utool",
"global",
"cache",
"allows",
"for",
"the",
"user",
"to",
"override",
"where",
"the",
"logs",
"for",
"a",
"specific",
"app",
"should",
"be",
"stored",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_logging.py#L186-L208 | train |
Erotemic/utool | utool/util_logging.py | add_logging_handler | def add_logging_handler(handler, format_='file'):
"""
mostly for util_logging internals
"""
global __UTOOL_ROOT_LOGGER__
if __UTOOL_ROOT_LOGGER__ is None:
builtins.print('[WARNING] logger not started, cannot add handler')
return
# create formatter and add it to the handlers
#logformat = '%Y-%m-%d %H:%M:%S'
#logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
timeformat = '%H:%M:%S'
if format_ == 'file':
logformat = '[%(asctime)s]%(message)s'
elif format_ == 'stdout':
logformat = '%(message)s'
else:
raise AssertionError('unknown logging format_: %r' % format_)
# Create formatter for handlers
formatter = logging.Formatter(logformat, timeformat)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
__UTOOL_ROOT_LOGGER__.addHandler(handler) | python | def add_logging_handler(handler, format_='file'):
"""
mostly for util_logging internals
"""
global __UTOOL_ROOT_LOGGER__
if __UTOOL_ROOT_LOGGER__ is None:
builtins.print('[WARNING] logger not started, cannot add handler')
return
# create formatter and add it to the handlers
#logformat = '%Y-%m-%d %H:%M:%S'
#logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
timeformat = '%H:%M:%S'
if format_ == 'file':
logformat = '[%(asctime)s]%(message)s'
elif format_ == 'stdout':
logformat = '%(message)s'
else:
raise AssertionError('unknown logging format_: %r' % format_)
# Create formatter for handlers
formatter = logging.Formatter(logformat, timeformat)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
__UTOOL_ROOT_LOGGER__.addHandler(handler) | [
"def",
"add_logging_handler",
"(",
"handler",
",",
"format_",
"=",
"'file'",
")",
":",
"global",
"__UTOOL_ROOT_LOGGER__",
"if",
"__UTOOL_ROOT_LOGGER__",
"is",
"None",
":",
"builtins",
".",
"print",
"(",
"'[WARNING] logger not started, cannot add handler'",
")",
"return",
"# create formatter and add it to the handlers",
"#logformat = '%Y-%m-%d %H:%M:%S'",
"#logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'",
"timeformat",
"=",
"'%H:%M:%S'",
"if",
"format_",
"==",
"'file'",
":",
"logformat",
"=",
"'[%(asctime)s]%(message)s'",
"elif",
"format_",
"==",
"'stdout'",
":",
"logformat",
"=",
"'%(message)s'",
"else",
":",
"raise",
"AssertionError",
"(",
"'unknown logging format_: %r'",
"%",
"format_",
")",
"# Create formatter for handlers",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"logformat",
",",
"timeformat",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"__UTOOL_ROOT_LOGGER__",
".",
"addHandler",
"(",
"handler",
")"
] | mostly for util_logging internals | [
"mostly",
"for",
"util_logging",
"internals"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_logging.py#L280-L302 | train |
Erotemic/utool | utool/util_logging.py | start_logging | def start_logging(log_fpath=None, mode='a', appname='default', log_dir=None):
r"""
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE_DOCTEST
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> ut.util_logging._utool_print()('hello world')
>>> ut.util_logging._utool_write()('writing1')
>>> ut.util_logging._utool_write()('writing2\n')
>>> ut.util_logging._utool_write()('writing3')
>>> ut.util_logging._utool_flush()()
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> print('current_log_text =\n%s' % (current_log_text,))
>>> assert current_log_text.find('hello world') > 0, 'cant hello world'
>>> assert current_log_text.find('writing1writing2') > 0, 'cant find writing1writing2'
>>> assert current_log_text.find('writing3') > 0, 'cant find writing3'
Example1:
>>> # DISABLE_DOCTEST
>>> # Ensure that progress is logged
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> [x for x in ut.ProgressIter(range(0, 1000), freq=4)]
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> assert current_log_text.find('rate') > 0, 'progress was not logged'
>>> print(current_log_text)
"""
global __UTOOL_ROOT_LOGGER__
global __UTOOL_PRINT__
global __UTOOL_WRITE__
global __UTOOL_FLUSH__
global __CURRENT_LOG_FPATH__
if LOGGING_VERBOSE:
print('[utool] start_logging()')
# FIXME: The test for doctest may not work
if __UTOOL_ROOT_LOGGER__ is None and __IN_MAIN_PROCESS__ and not __inside_doctest():
if LOGGING_VERBOSE:
print('[utool] start_logging()... rootcheck OK')
#logging.config.dictConfig(LOGGING)
if log_fpath is None:
log_fpath = get_log_fpath(num='next', appname=appname, log_dir=log_dir)
__CURRENT_LOG_FPATH__ = log_fpath
# Print what is about to happen
if VERBOSE or LOGGING_VERBOSE:
startmsg = ('logging to log_fpath=%r' % log_fpath)
_utool_print()(startmsg)
# Create root logger
__UTOOL_ROOT_LOGGER__ = logging.getLogger('root')
__UTOOL_ROOT_LOGGER__.setLevel('DEBUG')
# create file handler which logs even debug messages
#fh = logging.handlers.WatchedFileHandler(log_fpath)
logfile_handler = logging.FileHandler(log_fpath, mode=mode)
#stdout_handler = logging.StreamHandler(__UTOOL_STDOUT__)
stdout_handler = CustomStreamHandler(__UTOOL_STDOUT__)
stdout_handler.terminator = ''
# http://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module
#stdout_handler.terminator = ''
add_logging_handler(logfile_handler, format_='file')
add_logging_handler(stdout_handler, format_='stdout')
__UTOOL_ROOT_LOGGER__.propagate = False
__UTOOL_ROOT_LOGGER__.setLevel(logging.DEBUG)
# Overwrite utool functions with the logging functions
def utool_flush(*args):
""" flushes whatever is in the current utool write buffer """
# Flushes only the stdout handler
stdout_handler.flush()
#__UTOOL_ROOT_LOGGER__.flush()
#global __UTOOL_WRITE_BUFFER__
#if len(__UTOOL_WRITE_BUFFER__) > 0:
# msg = ''.join(__UTOOL_WRITE_BUFFER__)
# #sys.stdout.write('FLUSHING %r\n' % (len(__UTOOL_WRITE_BUFFER__)))
# __UTOOL_WRITE_BUFFER__ = []
# return __UTOOL_ROOT_LOGGER__.info(msg)
#__PYTHON_FLUSH__()
def utool_write(*args):
""" writes to current utool logs and to sys.stdout.write """
#global __UTOOL_WRITE_BUFFER__
#sys.stdout.write('WRITEING\n')
msg = ', '.join(map(six.text_type, args))
#__UTOOL_WRITE_BUFFER__.append(msg)
__UTOOL_ROOT_LOGGER__.info(msg)
#if msg.endswith('\n'):
# # Flush on newline, and remove newline
# __UTOOL_WRITE_BUFFER__[-1] = __UTOOL_WRITE_BUFFER__[-1][:-1]
# utool_flush()
#elif len(__UTOOL_WRITE_BUFFER__) > 32:
# # Flush if buffer is too large
# utool_flush()
if not PRINT_ALL_CALLERS:
def utool_print(*args):
""" standard utool print function """
#sys.stdout.write('PRINT\n')
endline = '\n'
try:
msg = ', '.join(map(six.text_type, args))
return __UTOOL_ROOT_LOGGER__.info(msg + endline)
except UnicodeDecodeError:
new_msg = ', '.join(map(meta_util_six.ensure_unicode, args))
#print(new_msg)
return __UTOOL_ROOT_LOGGER__.info(new_msg + endline)
else:
def utool_print(*args):
""" debugging utool print function """
import utool as ut
utool_flush()
endline = '\n'
__UTOOL_ROOT_LOGGER__.info('\n\n----------')
__UTOOL_ROOT_LOGGER__.info(ut.get_caller_name(range(0, 20)))
return __UTOOL_ROOT_LOGGER__.info(', '.join(map(six.text_type, args)) + endline)
def utool_printdbg(*args):
""" DRPRICATE standard utool print debug function """
return __UTOOL_ROOT_LOGGER__.debug(', '.join(map(six.text_type, args)))
# overwrite the utool printers
__UTOOL_WRITE__ = utool_write
__UTOOL_FLUSH__ = utool_flush
__UTOOL_PRINT__ = utool_print
# Test out our shiney new logger
if VERBOSE or LOGGING_VERBOSE:
__UTOOL_PRINT__('<__LOG_START__>')
__UTOOL_PRINT__(startmsg)
else:
if LOGGING_VERBOSE:
print('[utool] start_logging()... FAILED TO START')
print('DEBUG INFO')
print('__inside_doctest() = %r' % (__inside_doctest(),))
print('__IN_MAIN_PROCESS__ = %r' % (__IN_MAIN_PROCESS__,))
print('__UTOOL_ROOT_LOGGER__ = %r' % (__UTOOL_ROOT_LOGGER__,)) | python | def start_logging(log_fpath=None, mode='a', appname='default', log_dir=None):
r"""
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE_DOCTEST
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> ut.util_logging._utool_print()('hello world')
>>> ut.util_logging._utool_write()('writing1')
>>> ut.util_logging._utool_write()('writing2\n')
>>> ut.util_logging._utool_write()('writing3')
>>> ut.util_logging._utool_flush()()
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> print('current_log_text =\n%s' % (current_log_text,))
>>> assert current_log_text.find('hello world') > 0, 'cant hello world'
>>> assert current_log_text.find('writing1writing2') > 0, 'cant find writing1writing2'
>>> assert current_log_text.find('writing3') > 0, 'cant find writing3'
Example1:
>>> # DISABLE_DOCTEST
>>> # Ensure that progress is logged
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> [x for x in ut.ProgressIter(range(0, 1000), freq=4)]
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> assert current_log_text.find('rate') > 0, 'progress was not logged'
>>> print(current_log_text)
"""
global __UTOOL_ROOT_LOGGER__
global __UTOOL_PRINT__
global __UTOOL_WRITE__
global __UTOOL_FLUSH__
global __CURRENT_LOG_FPATH__
if LOGGING_VERBOSE:
print('[utool] start_logging()')
# FIXME: The test for doctest may not work
if __UTOOL_ROOT_LOGGER__ is None and __IN_MAIN_PROCESS__ and not __inside_doctest():
if LOGGING_VERBOSE:
print('[utool] start_logging()... rootcheck OK')
#logging.config.dictConfig(LOGGING)
if log_fpath is None:
log_fpath = get_log_fpath(num='next', appname=appname, log_dir=log_dir)
__CURRENT_LOG_FPATH__ = log_fpath
# Print what is about to happen
if VERBOSE or LOGGING_VERBOSE:
startmsg = ('logging to log_fpath=%r' % log_fpath)
_utool_print()(startmsg)
# Create root logger
__UTOOL_ROOT_LOGGER__ = logging.getLogger('root')
__UTOOL_ROOT_LOGGER__.setLevel('DEBUG')
# create file handler which logs even debug messages
#fh = logging.handlers.WatchedFileHandler(log_fpath)
logfile_handler = logging.FileHandler(log_fpath, mode=mode)
#stdout_handler = logging.StreamHandler(__UTOOL_STDOUT__)
stdout_handler = CustomStreamHandler(__UTOOL_STDOUT__)
stdout_handler.terminator = ''
# http://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module
#stdout_handler.terminator = ''
add_logging_handler(logfile_handler, format_='file')
add_logging_handler(stdout_handler, format_='stdout')
__UTOOL_ROOT_LOGGER__.propagate = False
__UTOOL_ROOT_LOGGER__.setLevel(logging.DEBUG)
# Overwrite utool functions with the logging functions
def utool_flush(*args):
""" flushes whatever is in the current utool write buffer """
# Flushes only the stdout handler
stdout_handler.flush()
#__UTOOL_ROOT_LOGGER__.flush()
#global __UTOOL_WRITE_BUFFER__
#if len(__UTOOL_WRITE_BUFFER__) > 0:
# msg = ''.join(__UTOOL_WRITE_BUFFER__)
# #sys.stdout.write('FLUSHING %r\n' % (len(__UTOOL_WRITE_BUFFER__)))
# __UTOOL_WRITE_BUFFER__ = []
# return __UTOOL_ROOT_LOGGER__.info(msg)
#__PYTHON_FLUSH__()
def utool_write(*args):
""" writes to current utool logs and to sys.stdout.write """
#global __UTOOL_WRITE_BUFFER__
#sys.stdout.write('WRITEING\n')
msg = ', '.join(map(six.text_type, args))
#__UTOOL_WRITE_BUFFER__.append(msg)
__UTOOL_ROOT_LOGGER__.info(msg)
#if msg.endswith('\n'):
# # Flush on newline, and remove newline
# __UTOOL_WRITE_BUFFER__[-1] = __UTOOL_WRITE_BUFFER__[-1][:-1]
# utool_flush()
#elif len(__UTOOL_WRITE_BUFFER__) > 32:
# # Flush if buffer is too large
# utool_flush()
if not PRINT_ALL_CALLERS:
def utool_print(*args):
""" standard utool print function """
#sys.stdout.write('PRINT\n')
endline = '\n'
try:
msg = ', '.join(map(six.text_type, args))
return __UTOOL_ROOT_LOGGER__.info(msg + endline)
except UnicodeDecodeError:
new_msg = ', '.join(map(meta_util_six.ensure_unicode, args))
#print(new_msg)
return __UTOOL_ROOT_LOGGER__.info(new_msg + endline)
else:
def utool_print(*args):
""" debugging utool print function """
import utool as ut
utool_flush()
endline = '\n'
__UTOOL_ROOT_LOGGER__.info('\n\n----------')
__UTOOL_ROOT_LOGGER__.info(ut.get_caller_name(range(0, 20)))
return __UTOOL_ROOT_LOGGER__.info(', '.join(map(six.text_type, args)) + endline)
def utool_printdbg(*args):
""" DRPRICATE standard utool print debug function """
return __UTOOL_ROOT_LOGGER__.debug(', '.join(map(six.text_type, args)))
# overwrite the utool printers
__UTOOL_WRITE__ = utool_write
__UTOOL_FLUSH__ = utool_flush
__UTOOL_PRINT__ = utool_print
# Test out our shiney new logger
if VERBOSE or LOGGING_VERBOSE:
__UTOOL_PRINT__('<__LOG_START__>')
__UTOOL_PRINT__(startmsg)
else:
if LOGGING_VERBOSE:
print('[utool] start_logging()... FAILED TO START')
print('DEBUG INFO')
print('__inside_doctest() = %r' % (__inside_doctest(),))
print('__IN_MAIN_PROCESS__ = %r' % (__IN_MAIN_PROCESS__,))
print('__UTOOL_ROOT_LOGGER__ = %r' % (__UTOOL_ROOT_LOGGER__,)) | [
"def",
"start_logging",
"(",
"log_fpath",
"=",
"None",
",",
"mode",
"=",
"'a'",
",",
"appname",
"=",
"'default'",
",",
"log_dir",
"=",
"None",
")",
":",
"global",
"__UTOOL_ROOT_LOGGER__",
"global",
"__UTOOL_PRINT__",
"global",
"__UTOOL_WRITE__",
"global",
"__UTOOL_FLUSH__",
"global",
"__CURRENT_LOG_FPATH__",
"if",
"LOGGING_VERBOSE",
":",
"print",
"(",
"'[utool] start_logging()'",
")",
"# FIXME: The test for doctest may not work",
"if",
"__UTOOL_ROOT_LOGGER__",
"is",
"None",
"and",
"__IN_MAIN_PROCESS__",
"and",
"not",
"__inside_doctest",
"(",
")",
":",
"if",
"LOGGING_VERBOSE",
":",
"print",
"(",
"'[utool] start_logging()... rootcheck OK'",
")",
"#logging.config.dictConfig(LOGGING)",
"if",
"log_fpath",
"is",
"None",
":",
"log_fpath",
"=",
"get_log_fpath",
"(",
"num",
"=",
"'next'",
",",
"appname",
"=",
"appname",
",",
"log_dir",
"=",
"log_dir",
")",
"__CURRENT_LOG_FPATH__",
"=",
"log_fpath",
"# Print what is about to happen",
"if",
"VERBOSE",
"or",
"LOGGING_VERBOSE",
":",
"startmsg",
"=",
"(",
"'logging to log_fpath=%r'",
"%",
"log_fpath",
")",
"_utool_print",
"(",
")",
"(",
"startmsg",
")",
"# Create root logger",
"__UTOOL_ROOT_LOGGER__",
"=",
"logging",
".",
"getLogger",
"(",
"'root'",
")",
"__UTOOL_ROOT_LOGGER__",
".",
"setLevel",
"(",
"'DEBUG'",
")",
"# create file handler which logs even debug messages",
"#fh = logging.handlers.WatchedFileHandler(log_fpath)",
"logfile_handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_fpath",
",",
"mode",
"=",
"mode",
")",
"#stdout_handler = logging.StreamHandler(__UTOOL_STDOUT__)",
"stdout_handler",
"=",
"CustomStreamHandler",
"(",
"__UTOOL_STDOUT__",
")",
"stdout_handler",
".",
"terminator",
"=",
"''",
"# http://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module",
"#stdout_handler.terminator = ''",
"add_logging_handler",
"(",
"logfile_handler",
",",
"format_",
"=",
"'file'",
")",
"add_logging_handler",
"(",
"stdout_handler",
",",
"format_",
"=",
"'stdout'",
")",
"__UTOOL_ROOT_LOGGER__",
".",
"propagate",
"=",
"False",
"__UTOOL_ROOT_LOGGER__",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Overwrite utool functions with the logging functions",
"def",
"utool_flush",
"(",
"*",
"args",
")",
":",
"\"\"\" flushes whatever is in the current utool write buffer \"\"\"",
"# Flushes only the stdout handler",
"stdout_handler",
".",
"flush",
"(",
")",
"#__UTOOL_ROOT_LOGGER__.flush()",
"#global __UTOOL_WRITE_BUFFER__",
"#if len(__UTOOL_WRITE_BUFFER__) > 0:",
"# msg = ''.join(__UTOOL_WRITE_BUFFER__)",
"# #sys.stdout.write('FLUSHING %r\\n' % (len(__UTOOL_WRITE_BUFFER__)))",
"# __UTOOL_WRITE_BUFFER__ = []",
"# return __UTOOL_ROOT_LOGGER__.info(msg)",
"#__PYTHON_FLUSH__()",
"def",
"utool_write",
"(",
"*",
"args",
")",
":",
"\"\"\" writes to current utool logs and to sys.stdout.write \"\"\"",
"#global __UTOOL_WRITE_BUFFER__",
"#sys.stdout.write('WRITEING\\n')",
"msg",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"six",
".",
"text_type",
",",
"args",
")",
")",
"#__UTOOL_WRITE_BUFFER__.append(msg)",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"msg",
")",
"#if msg.endswith('\\n'):",
"# # Flush on newline, and remove newline",
"# __UTOOL_WRITE_BUFFER__[-1] = __UTOOL_WRITE_BUFFER__[-1][:-1]",
"# utool_flush()",
"#elif len(__UTOOL_WRITE_BUFFER__) > 32:",
"# # Flush if buffer is too large",
"# utool_flush()",
"if",
"not",
"PRINT_ALL_CALLERS",
":",
"def",
"utool_print",
"(",
"*",
"args",
")",
":",
"\"\"\" standard utool print function \"\"\"",
"#sys.stdout.write('PRINT\\n')",
"endline",
"=",
"'\\n'",
"try",
":",
"msg",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"six",
".",
"text_type",
",",
"args",
")",
")",
"return",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"msg",
"+",
"endline",
")",
"except",
"UnicodeDecodeError",
":",
"new_msg",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"meta_util_six",
".",
"ensure_unicode",
",",
"args",
")",
")",
"#print(new_msg)",
"return",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"new_msg",
"+",
"endline",
")",
"else",
":",
"def",
"utool_print",
"(",
"*",
"args",
")",
":",
"\"\"\" debugging utool print function \"\"\"",
"import",
"utool",
"as",
"ut",
"utool_flush",
"(",
")",
"endline",
"=",
"'\\n'",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"'\\n\\n----------'",
")",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"ut",
".",
"get_caller_name",
"(",
"range",
"(",
"0",
",",
"20",
")",
")",
")",
"return",
"__UTOOL_ROOT_LOGGER__",
".",
"info",
"(",
"', '",
".",
"join",
"(",
"map",
"(",
"six",
".",
"text_type",
",",
"args",
")",
")",
"+",
"endline",
")",
"def",
"utool_printdbg",
"(",
"*",
"args",
")",
":",
"\"\"\" DRPRICATE standard utool print debug function \"\"\"",
"return",
"__UTOOL_ROOT_LOGGER__",
".",
"debug",
"(",
"', '",
".",
"join",
"(",
"map",
"(",
"six",
".",
"text_type",
",",
"args",
")",
")",
")",
"# overwrite the utool printers",
"__UTOOL_WRITE__",
"=",
"utool_write",
"__UTOOL_FLUSH__",
"=",
"utool_flush",
"__UTOOL_PRINT__",
"=",
"utool_print",
"# Test out our shiney new logger",
"if",
"VERBOSE",
"or",
"LOGGING_VERBOSE",
":",
"__UTOOL_PRINT__",
"(",
"'<__LOG_START__>'",
")",
"__UTOOL_PRINT__",
"(",
"startmsg",
")",
"else",
":",
"if",
"LOGGING_VERBOSE",
":",
"print",
"(",
"'[utool] start_logging()... FAILED TO START'",
")",
"print",
"(",
"'DEBUG INFO'",
")",
"print",
"(",
"'__inside_doctest() = %r'",
"%",
"(",
"__inside_doctest",
"(",
")",
",",
")",
")",
"print",
"(",
"'__IN_MAIN_PROCESS__ = %r'",
"%",
"(",
"__IN_MAIN_PROCESS__",
",",
")",
")",
"print",
"(",
"'__UTOOL_ROOT_LOGGER__ = %r'",
"%",
"(",
"__UTOOL_ROOT_LOGGER__",
",",
")",
")"
] | r"""
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE_DOCTEST
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> ut.util_logging._utool_print()('hello world')
>>> ut.util_logging._utool_write()('writing1')
>>> ut.util_logging._utool_write()('writing2\n')
>>> ut.util_logging._utool_write()('writing3')
>>> ut.util_logging._utool_flush()()
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> print('current_log_text =\n%s' % (current_log_text,))
>>> assert current_log_text.find('hello world') > 0, 'cant hello world'
>>> assert current_log_text.find('writing1writing2') > 0, 'cant find writing1writing2'
>>> assert current_log_text.find('writing3') > 0, 'cant find writing3'
Example1:
>>> # DISABLE_DOCTEST
>>> # Ensure that progress is logged
>>> import sys
>>> sys.argv.append('--verb-logging')
>>> import utool as ut
>>> ut.start_logging()
>>> [x for x in ut.ProgressIter(range(0, 1000), freq=4)]
>>> handler = ut.util_logging.__UTOOL_ROOT_LOGGER__.handlers[0]
>>> current_log_fpath = handler.stream.name
>>> current_log_text = ut.read_from(current_log_fpath)
>>> assert current_log_text.find('rate') > 0, 'progress was not logged'
>>> print(current_log_text) | [
"r",
"Overwrites",
"utool",
"print",
"functions",
"to",
"use",
"a",
"logger"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_logging.py#L375-L520 | train |
Erotemic/utool | utool/util_logging.py | stop_logging | def stop_logging():
"""
Restores utool print functions to python defaults
"""
global __UTOOL_ROOT_LOGGER__
global __UTOOL_PRINT__
global __UTOOL_WRITE__
global __UTOOL_FLUSH__
if __UTOOL_ROOT_LOGGER__ is not None:
# Flush remaining buffer
if VERBOSE or LOGGING_VERBOSE:
_utool_print()()('<__LOG_STOP__>')
_utool_flush()()
# Remove handlers
for h in __UTOOL_ROOT_LOGGER__.handlers[:]:
__UTOOL_ROOT_LOGGER__.removeHandler(h)
# Reset objects
__UTOOL_ROOT_LOGGER__ = None
__UTOOL_PRINT__ = None
__UTOOL_WRITE__ = None
__UTOOL_FLUSH__ = None | python | def stop_logging():
"""
Restores utool print functions to python defaults
"""
global __UTOOL_ROOT_LOGGER__
global __UTOOL_PRINT__
global __UTOOL_WRITE__
global __UTOOL_FLUSH__
if __UTOOL_ROOT_LOGGER__ is not None:
# Flush remaining buffer
if VERBOSE or LOGGING_VERBOSE:
_utool_print()()('<__LOG_STOP__>')
_utool_flush()()
# Remove handlers
for h in __UTOOL_ROOT_LOGGER__.handlers[:]:
__UTOOL_ROOT_LOGGER__.removeHandler(h)
# Reset objects
__UTOOL_ROOT_LOGGER__ = None
__UTOOL_PRINT__ = None
__UTOOL_WRITE__ = None
__UTOOL_FLUSH__ = None | [
"def",
"stop_logging",
"(",
")",
":",
"global",
"__UTOOL_ROOT_LOGGER__",
"global",
"__UTOOL_PRINT__",
"global",
"__UTOOL_WRITE__",
"global",
"__UTOOL_FLUSH__",
"if",
"__UTOOL_ROOT_LOGGER__",
"is",
"not",
"None",
":",
"# Flush remaining buffer",
"if",
"VERBOSE",
"or",
"LOGGING_VERBOSE",
":",
"_utool_print",
"(",
")",
"(",
")",
"(",
"'<__LOG_STOP__>'",
")",
"_utool_flush",
"(",
")",
"(",
")",
"# Remove handlers",
"for",
"h",
"in",
"__UTOOL_ROOT_LOGGER__",
".",
"handlers",
"[",
":",
"]",
":",
"__UTOOL_ROOT_LOGGER__",
".",
"removeHandler",
"(",
"h",
")",
"# Reset objects",
"__UTOOL_ROOT_LOGGER__",
"=",
"None",
"__UTOOL_PRINT__",
"=",
"None",
"__UTOOL_WRITE__",
"=",
"None",
"__UTOOL_FLUSH__",
"=",
"None"
] | Restores utool print functions to python defaults | [
"Restores",
"utool",
"print",
"functions",
"to",
"python",
"defaults"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_logging.py#L523-L543 | train |
Erotemic/utool | utool/util_list.py | replace_nones | def replace_nones(list_, repl=-1):
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list_ = [None, 0, 1, 2]
>>> repl = -1
>>> # execute function
>>> repl_list = replace_nones(list_, repl)
>>> # verify results
>>> result = str(repl_list)
>>> print(result)
[-1, 0, 1, 2]
"""
repl_list = [
repl if item is None else (
replace_nones(item, repl) if isinstance(item, list) else item
)
for item in list_
]
return repl_list | python | def replace_nones(list_, repl=-1):
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list_ = [None, 0, 1, 2]
>>> repl = -1
>>> # execute function
>>> repl_list = replace_nones(list_, repl)
>>> # verify results
>>> result = str(repl_list)
>>> print(result)
[-1, 0, 1, 2]
"""
repl_list = [
repl if item is None else (
replace_nones(item, repl) if isinstance(item, list) else item
)
for item in list_
]
return repl_list | [
"def",
"replace_nones",
"(",
"list_",
",",
"repl",
"=",
"-",
"1",
")",
":",
"repl_list",
"=",
"[",
"repl",
"if",
"item",
"is",
"None",
"else",
"(",
"replace_nones",
"(",
"item",
",",
"repl",
")",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
"else",
"item",
")",
"for",
"item",
"in",
"list_",
"]",
"return",
"repl_list"
] | r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list_ = [None, 0, 1, 2]
>>> repl = -1
>>> # execute function
>>> repl_list = replace_nones(list_, repl)
>>> # verify results
>>> result = str(repl_list)
>>> print(result)
[-1, 0, 1, 2] | [
"r",
"Recursively",
"removes",
"Nones",
"in",
"all",
"lists",
"and",
"sublists",
"and",
"replaces",
"them",
"with",
"the",
"repl",
"variable"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L78-L113 | train |
Erotemic/utool | utool/util_list.py | recursive_replace | def recursive_replace(list_, target, repl=-1):
r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
"""
repl_list = [
recursive_replace(item, target, repl) if isinstance(item, (list, np.ndarray)) else
(repl if item == target else item)
for item in list_
]
return repl_list | python | def recursive_replace(list_, target, repl=-1):
r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable
"""
repl_list = [
recursive_replace(item, target, repl) if isinstance(item, (list, np.ndarray)) else
(repl if item == target else item)
for item in list_
]
return repl_list | [
"def",
"recursive_replace",
"(",
"list_",
",",
"target",
",",
"repl",
"=",
"-",
"1",
")",
":",
"repl_list",
"=",
"[",
"recursive_replace",
"(",
"item",
",",
"target",
",",
"repl",
")",
"if",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
"else",
"(",
"repl",
"if",
"item",
"==",
"target",
"else",
"item",
")",
"for",
"item",
"in",
"list_",
"]",
"return",
"repl_list"
] | r"""
Recursively removes target in all lists and sublists and replaces them with
the repl variable | [
"r",
"Recursively",
"removes",
"target",
"in",
"all",
"lists",
"and",
"sublists",
"and",
"replaces",
"them",
"with",
"the",
"repl",
"variable"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L116-L126 | train |
Erotemic/utool | utool/util_list.py | ensure_list_size | def ensure_list_size(list_, size_):
""" Allocates more space if needbe.
Ensures len(``list_``) == ``size_``.
Args:
list_ (list): ``list`` to extend
size_ (int): amount to exent by
"""
lendiff = (size_) - len(list_)
if lendiff > 0:
extension = [None for _ in range(lendiff)]
list_.extend(extension) | python | def ensure_list_size(list_, size_):
""" Allocates more space if needbe.
Ensures len(``list_``) == ``size_``.
Args:
list_ (list): ``list`` to extend
size_ (int): amount to exent by
"""
lendiff = (size_) - len(list_)
if lendiff > 0:
extension = [None for _ in range(lendiff)]
list_.extend(extension) | [
"def",
"ensure_list_size",
"(",
"list_",
",",
"size_",
")",
":",
"lendiff",
"=",
"(",
"size_",
")",
"-",
"len",
"(",
"list_",
")",
"if",
"lendiff",
">",
"0",
":",
"extension",
"=",
"[",
"None",
"for",
"_",
"in",
"range",
"(",
"lendiff",
")",
"]",
"list_",
".",
"extend",
"(",
"extension",
")"
] | Allocates more space if needbe.
Ensures len(``list_``) == ``size_``.
Args:
list_ (list): ``list`` to extend
size_ (int): amount to exent by | [
"Allocates",
"more",
"space",
"if",
"needbe",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L150-L162 | train |
Erotemic/utool | utool/util_list.py | multi_replace | def multi_replace(instr, search_list=[], repl_list=None):
"""
Does a string replace with a list of search and replacements
TODO: rename
"""
repl_list = [''] * len(search_list) if repl_list is None else repl_list
for ser, repl in zip(search_list, repl_list):
instr = instr.replace(ser, repl)
return instr | python | def multi_replace(instr, search_list=[], repl_list=None):
"""
Does a string replace with a list of search and replacements
TODO: rename
"""
repl_list = [''] * len(search_list) if repl_list is None else repl_list
for ser, repl in zip(search_list, repl_list):
instr = instr.replace(ser, repl)
return instr | [
"def",
"multi_replace",
"(",
"instr",
",",
"search_list",
"=",
"[",
"]",
",",
"repl_list",
"=",
"None",
")",
":",
"repl_list",
"=",
"[",
"''",
"]",
"*",
"len",
"(",
"search_list",
")",
"if",
"repl_list",
"is",
"None",
"else",
"repl_list",
"for",
"ser",
",",
"repl",
"in",
"zip",
"(",
"search_list",
",",
"repl_list",
")",
":",
"instr",
"=",
"instr",
".",
"replace",
"(",
"ser",
",",
"repl",
")",
"return",
"instr"
] | Does a string replace with a list of search and replacements
TODO: rename | [
"Does",
"a",
"string",
"replace",
"with",
"a",
"list",
"of",
"search",
"and",
"replacements"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L387-L396 | train |
Erotemic/utool | utool/util_list.py | invertible_flatten1 | def invertible_flatten1(unflat_list):
r"""
Flattens `unflat_list` but remember how to reconstruct the `unflat_list`
Returns `flat_list` and the `reverse_list` with indexes into the
`flat_list`
Args:
unflat_list (list): list of nested lists that we will flatten.
Returns:
tuple : (flat_list, reverse_list)
CommandLine:
python -m utool.util_list --exec-invertible_flatten1 --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> unflat_list = [[1, 2, 3], [4, 5], [6, 6]]
>>> flat_list, reverse_list = invertible_flatten1(unflat_list)
>>> result = ('flat_list = %s\n' % (ut.repr2(flat_list),))
>>> result += ('reverse_list = %s' % (ut.repr2(reverse_list),))
>>> print(result)
flat_list = [1, 2, 3, 4, 5, 6, 6]
reverse_list = [[0, 1, 2], [3, 4], [5, 6]]
"""
nextnum = functools.partial(six.next, itertools.count(0))
# Build an unflat list of flat indexes
reverse_list = [[nextnum() for _ in tup] for tup in unflat_list]
flat_list = flatten(unflat_list)
return flat_list, reverse_list | python | def invertible_flatten1(unflat_list):
r"""
Flattens `unflat_list` but remember how to reconstruct the `unflat_list`
Returns `flat_list` and the `reverse_list` with indexes into the
`flat_list`
Args:
unflat_list (list): list of nested lists that we will flatten.
Returns:
tuple : (flat_list, reverse_list)
CommandLine:
python -m utool.util_list --exec-invertible_flatten1 --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> unflat_list = [[1, 2, 3], [4, 5], [6, 6]]
>>> flat_list, reverse_list = invertible_flatten1(unflat_list)
>>> result = ('flat_list = %s\n' % (ut.repr2(flat_list),))
>>> result += ('reverse_list = %s' % (ut.repr2(reverse_list),))
>>> print(result)
flat_list = [1, 2, 3, 4, 5, 6, 6]
reverse_list = [[0, 1, 2], [3, 4], [5, 6]]
"""
nextnum = functools.partial(six.next, itertools.count(0))
# Build an unflat list of flat indexes
reverse_list = [[nextnum() for _ in tup] for tup in unflat_list]
flat_list = flatten(unflat_list)
return flat_list, reverse_list | [
"def",
"invertible_flatten1",
"(",
"unflat_list",
")",
":",
"nextnum",
"=",
"functools",
".",
"partial",
"(",
"six",
".",
"next",
",",
"itertools",
".",
"count",
"(",
"0",
")",
")",
"# Build an unflat list of flat indexes",
"reverse_list",
"=",
"[",
"[",
"nextnum",
"(",
")",
"for",
"_",
"in",
"tup",
"]",
"for",
"tup",
"in",
"unflat_list",
"]",
"flat_list",
"=",
"flatten",
"(",
"unflat_list",
")",
"return",
"flat_list",
",",
"reverse_list"
] | r"""
Flattens `unflat_list` but remember how to reconstruct the `unflat_list`
Returns `flat_list` and the `reverse_list` with indexes into the
`flat_list`
Args:
unflat_list (list): list of nested lists that we will flatten.
Returns:
tuple : (flat_list, reverse_list)
CommandLine:
python -m utool.util_list --exec-invertible_flatten1 --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> unflat_list = [[1, 2, 3], [4, 5], [6, 6]]
>>> flat_list, reverse_list = invertible_flatten1(unflat_list)
>>> result = ('flat_list = %s\n' % (ut.repr2(flat_list),))
>>> result += ('reverse_list = %s' % (ut.repr2(reverse_list),))
>>> print(result)
flat_list = [1, 2, 3, 4, 5, 6, 6]
reverse_list = [[0, 1, 2], [3, 4], [5, 6]] | [
"r",
"Flattens",
"unflat_list",
"but",
"remember",
"how",
"to",
"reconstruct",
"the",
"unflat_list",
"Returns",
"flat_list",
"and",
"the",
"reverse_list",
"with",
"indexes",
"into",
"the",
"flat_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L423-L454 | train |
Erotemic/utool | utool/util_list.py | invertible_flatten2 | def invertible_flatten2(unflat_list):
"""
An alternative to invertible_flatten1 which uses cumsum
Flattens ``list`` but remember how to reconstruct the unflat ``list``
Returns flat ``list`` and the unflat ``list`` with indexes into the flat
``list``
Args:
unflat_list (list):
Returns:
tuple: flat_list, cumlen_list
SeeAlso:
invertible_flatten1
unflatten1
unflatten2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool
>>> utool.util_list
>>> unflat_list = [[5], [2, 3, 12, 3, 3], [9], [13, 3], [5]]
>>> flat_list, cumlen_list = invertible_flatten2(unflat_list)
>>> unflat_list2 = unflatten2(flat_list, cumlen_list)
>>> assert unflat_list2 == unflat_list
>>> result = ((flat_list, cumlen_list))
>>> print(result)
([5, 2, 3, 12, 3, 3, 9, 13, 3, 5], [1, 6, 7, 9, 10])
TODO: This flatten is faster fix it to be used everywhere
Timeit:
unflat_list = [[random.random() for _ in range(int(random.random() * 1000))] for __ in range(200)]
unflat_arrs = list(map(np.array, unflat_list))
%timeit invertible_flatten2(unflat_list)
%timeit invertible_flatten2_numpy(unflat_list)
%timeit invertible_flatten2_numpy(unflat_arrs)
Timeits:
import utool
unflat_list = aids_list1
flat_aids1, reverse_list = utool.invertible_flatten1(unflat_list)
flat_aids2, cumlen_list = utool.invertible_flatten2(unflat_list)
unflat_list1 = utool.unflatten1(flat_aids1, reverse_list)
unflat_list2 = utool.unflatten2(flat_aids2, cumlen_list)
assert list(map(list, unflat_list1)) == unflat_list2
print(utool.get_object_size_str(unflat_list, 'unflat_list '))
print(utool.get_object_size_str(flat_aids1, 'flat_aids1 '))
print(utool.get_object_size_str(flat_aids2, 'flat_aids2 '))
print(utool.get_object_size_str(reverse_list, 'reverse_list '))
print(utool.get_object_size_str(cumlen_list, 'cumlen_list '))
print(utool.get_object_size_str(unflat_list1, 'unflat_list1 '))
print(utool.get_object_size_str(unflat_list2, 'unflat_list2 '))
print('Timings 1:)
%timeit utool.invertible_flatten1(unflat_list)
%timeit utool.unflatten1(flat_aids1, reverse_list)
print('Timings 2:)
%timeit utool.invertible_flatten2(unflat_list)
%timeit utool.unflatten2(flat_aids2, cumlen_list)
"""
sublen_list = list(map(len, unflat_list))
if not util_type.HAVE_NUMPY:
cumlen_list = np.cumsum(sublen_list)
# Build an unflat list of flat indexes
else:
cumlen_list = list(accumulate(sublen_list))
flat_list = flatten(unflat_list)
return flat_list, cumlen_list | python | def invertible_flatten2(unflat_list):
"""
An alternative to invertible_flatten1 which uses cumsum
Flattens ``list`` but remember how to reconstruct the unflat ``list``
Returns flat ``list`` and the unflat ``list`` with indexes into the flat
``list``
Args:
unflat_list (list):
Returns:
tuple: flat_list, cumlen_list
SeeAlso:
invertible_flatten1
unflatten1
unflatten2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool
>>> utool.util_list
>>> unflat_list = [[5], [2, 3, 12, 3, 3], [9], [13, 3], [5]]
>>> flat_list, cumlen_list = invertible_flatten2(unflat_list)
>>> unflat_list2 = unflatten2(flat_list, cumlen_list)
>>> assert unflat_list2 == unflat_list
>>> result = ((flat_list, cumlen_list))
>>> print(result)
([5, 2, 3, 12, 3, 3, 9, 13, 3, 5], [1, 6, 7, 9, 10])
TODO: This flatten is faster fix it to be used everywhere
Timeit:
unflat_list = [[random.random() for _ in range(int(random.random() * 1000))] for __ in range(200)]
unflat_arrs = list(map(np.array, unflat_list))
%timeit invertible_flatten2(unflat_list)
%timeit invertible_flatten2_numpy(unflat_list)
%timeit invertible_flatten2_numpy(unflat_arrs)
Timeits:
import utool
unflat_list = aids_list1
flat_aids1, reverse_list = utool.invertible_flatten1(unflat_list)
flat_aids2, cumlen_list = utool.invertible_flatten2(unflat_list)
unflat_list1 = utool.unflatten1(flat_aids1, reverse_list)
unflat_list2 = utool.unflatten2(flat_aids2, cumlen_list)
assert list(map(list, unflat_list1)) == unflat_list2
print(utool.get_object_size_str(unflat_list, 'unflat_list '))
print(utool.get_object_size_str(flat_aids1, 'flat_aids1 '))
print(utool.get_object_size_str(flat_aids2, 'flat_aids2 '))
print(utool.get_object_size_str(reverse_list, 'reverse_list '))
print(utool.get_object_size_str(cumlen_list, 'cumlen_list '))
print(utool.get_object_size_str(unflat_list1, 'unflat_list1 '))
print(utool.get_object_size_str(unflat_list2, 'unflat_list2 '))
print('Timings 1:)
%timeit utool.invertible_flatten1(unflat_list)
%timeit utool.unflatten1(flat_aids1, reverse_list)
print('Timings 2:)
%timeit utool.invertible_flatten2(unflat_list)
%timeit utool.unflatten2(flat_aids2, cumlen_list)
"""
sublen_list = list(map(len, unflat_list))
if not util_type.HAVE_NUMPY:
cumlen_list = np.cumsum(sublen_list)
# Build an unflat list of flat indexes
else:
cumlen_list = list(accumulate(sublen_list))
flat_list = flatten(unflat_list)
return flat_list, cumlen_list | [
"def",
"invertible_flatten2",
"(",
"unflat_list",
")",
":",
"sublen_list",
"=",
"list",
"(",
"map",
"(",
"len",
",",
"unflat_list",
")",
")",
"if",
"not",
"util_type",
".",
"HAVE_NUMPY",
":",
"cumlen_list",
"=",
"np",
".",
"cumsum",
"(",
"sublen_list",
")",
"# Build an unflat list of flat indexes",
"else",
":",
"cumlen_list",
"=",
"list",
"(",
"accumulate",
"(",
"sublen_list",
")",
")",
"flat_list",
"=",
"flatten",
"(",
"unflat_list",
")",
"return",
"flat_list",
",",
"cumlen_list"
] | An alternative to invertible_flatten1 which uses cumsum
Flattens ``list`` but remember how to reconstruct the unflat ``list``
Returns flat ``list`` and the unflat ``list`` with indexes into the flat
``list``
Args:
unflat_list (list):
Returns:
tuple: flat_list, cumlen_list
SeeAlso:
invertible_flatten1
unflatten1
unflatten2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool
>>> utool.util_list
>>> unflat_list = [[5], [2, 3, 12, 3, 3], [9], [13, 3], [5]]
>>> flat_list, cumlen_list = invertible_flatten2(unflat_list)
>>> unflat_list2 = unflatten2(flat_list, cumlen_list)
>>> assert unflat_list2 == unflat_list
>>> result = ((flat_list, cumlen_list))
>>> print(result)
([5, 2, 3, 12, 3, 3, 9, 13, 3, 5], [1, 6, 7, 9, 10])
TODO: This flatten is faster fix it to be used everywhere
Timeit:
unflat_list = [[random.random() for _ in range(int(random.random() * 1000))] for __ in range(200)]
unflat_arrs = list(map(np.array, unflat_list))
%timeit invertible_flatten2(unflat_list)
%timeit invertible_flatten2_numpy(unflat_list)
%timeit invertible_flatten2_numpy(unflat_arrs)
Timeits:
import utool
unflat_list = aids_list1
flat_aids1, reverse_list = utool.invertible_flatten1(unflat_list)
flat_aids2, cumlen_list = utool.invertible_flatten2(unflat_list)
unflat_list1 = utool.unflatten1(flat_aids1, reverse_list)
unflat_list2 = utool.unflatten2(flat_aids2, cumlen_list)
assert list(map(list, unflat_list1)) == unflat_list2
print(utool.get_object_size_str(unflat_list, 'unflat_list '))
print(utool.get_object_size_str(flat_aids1, 'flat_aids1 '))
print(utool.get_object_size_str(flat_aids2, 'flat_aids2 '))
print(utool.get_object_size_str(reverse_list, 'reverse_list '))
print(utool.get_object_size_str(cumlen_list, 'cumlen_list '))
print(utool.get_object_size_str(unflat_list1, 'unflat_list1 '))
print(utool.get_object_size_str(unflat_list2, 'unflat_list2 '))
print('Timings 1:)
%timeit utool.invertible_flatten1(unflat_list)
%timeit utool.unflatten1(flat_aids1, reverse_list)
print('Timings 2:)
%timeit utool.invertible_flatten2(unflat_list)
%timeit utool.unflatten2(flat_aids2, cumlen_list) | [
"An",
"alternative",
"to",
"invertible_flatten1",
"which",
"uses",
"cumsum"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L594-L665 | train |
Erotemic/utool | utool/util_list.py | invertible_flatten2_numpy | def invertible_flatten2_numpy(unflat_arrs, axis=0):
""" more numpy version
TODO: move to vtool
Args:
unflat_arrs (list): list of ndarrays
Returns:
tuple: (flat_list, cumlen_list)
CommandLine:
python -m utool.util_list --test-invertible_flatten2_numpy
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_list import * # NOQA
>>> unflat_arrs = [np.array([1, 2, 1]), np.array([5, 9]), np.array([4])]
>>> (flat_list, cumlen_list) = invertible_flatten2_numpy(unflat_arrs)
>>> result = str((flat_list, cumlen_list))
>>> print(result)
(array([1, 2, 1, 5, 9, 4]), array([3, 5, 6]))
"""
cumlen_list = np.cumsum([arr.shape[axis] for arr in unflat_arrs])
flat_list = np.concatenate(unflat_arrs, axis=axis)
return flat_list, cumlen_list | python | def invertible_flatten2_numpy(unflat_arrs, axis=0):
""" more numpy version
TODO: move to vtool
Args:
unflat_arrs (list): list of ndarrays
Returns:
tuple: (flat_list, cumlen_list)
CommandLine:
python -m utool.util_list --test-invertible_flatten2_numpy
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_list import * # NOQA
>>> unflat_arrs = [np.array([1, 2, 1]), np.array([5, 9]), np.array([4])]
>>> (flat_list, cumlen_list) = invertible_flatten2_numpy(unflat_arrs)
>>> result = str((flat_list, cumlen_list))
>>> print(result)
(array([1, 2, 1, 5, 9, 4]), array([3, 5, 6]))
"""
cumlen_list = np.cumsum([arr.shape[axis] for arr in unflat_arrs])
flat_list = np.concatenate(unflat_arrs, axis=axis)
return flat_list, cumlen_list | [
"def",
"invertible_flatten2_numpy",
"(",
"unflat_arrs",
",",
"axis",
"=",
"0",
")",
":",
"cumlen_list",
"=",
"np",
".",
"cumsum",
"(",
"[",
"arr",
".",
"shape",
"[",
"axis",
"]",
"for",
"arr",
"in",
"unflat_arrs",
"]",
")",
"flat_list",
"=",
"np",
".",
"concatenate",
"(",
"unflat_arrs",
",",
"axis",
"=",
"axis",
")",
"return",
"flat_list",
",",
"cumlen_list"
] | more numpy version
TODO: move to vtool
Args:
unflat_arrs (list): list of ndarrays
Returns:
tuple: (flat_list, cumlen_list)
CommandLine:
python -m utool.util_list --test-invertible_flatten2_numpy
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_list import * # NOQA
>>> unflat_arrs = [np.array([1, 2, 1]), np.array([5, 9]), np.array([4])]
>>> (flat_list, cumlen_list) = invertible_flatten2_numpy(unflat_arrs)
>>> result = str((flat_list, cumlen_list))
>>> print(result)
(array([1, 2, 1, 5, 9, 4]), array([3, 5, 6])) | [
"more",
"numpy",
"version"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L668-L693 | train |
Erotemic/utool | utool/util_list.py | unflat_unique_rowid_map | def unflat_unique_rowid_map(func, unflat_rowids, **kwargs):
"""
performs only one call to the underlying func with unique rowids the func
must be some lookup function
TODO: move this to a better place.
CommandLine:
python -m utool.util_list --test-unflat_unique_rowid_map:0
python -m utool.util_list --test-unflat_unique_rowid_map:1
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls0 = [0]
>>> num_input0 = [0]
>>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0):
... num_calls0[0] += 1
... num_input0[0] += len(rowids)
... return [rowid + 10 for rowid in rowids]
>>> func = func0
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls0[0], 1)
>>> ut.assert_eq(num_input0[0], 4)
[[11, 12, 13], [12, 15], [11], []]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls1 = [0]
>>> num_input1 = [0]
>>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np):
... num_calls1[0] += 1
... num_input1[0] += len(rowids)
... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids]
>>> func = func1
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls1[0], 1)
>>> ut.assert_eq(num_input1[0], 4)
[[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []]
"""
import utool as ut
# First flatten the list, and remember the original dimensions
flat_rowids, reverse_list = ut.invertible_flatten2(unflat_rowids)
# Then make the input unique
flat_rowids_arr = np.array(flat_rowids)
unique_flat_rowids, inverse_unique = np.unique(flat_rowids_arr, return_inverse=True)
# Then preform the lookup / implicit mapping
unique_flat_vals = func(unique_flat_rowids, **kwargs)
# Then broadcast unique values back to original flat positions
flat_vals_ = np.array(unique_flat_vals)[inverse_unique]
#flat_vals_ = np.array(unique_flat_vals).take(inverse_unique, axis=0)
output_shape = tuple(list(flat_rowids_arr.shape) + list(flat_vals_.shape[1:]))
flat_vals = np.array(flat_vals_).reshape(output_shape)
# Then _unflatten the results to the original input dimensions
unflat_vals = ut.unflatten2(flat_vals, reverse_list)
return unflat_vals | python | def unflat_unique_rowid_map(func, unflat_rowids, **kwargs):
"""
performs only one call to the underlying func with unique rowids the func
must be some lookup function
TODO: move this to a better place.
CommandLine:
python -m utool.util_list --test-unflat_unique_rowid_map:0
python -m utool.util_list --test-unflat_unique_rowid_map:1
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls0 = [0]
>>> num_input0 = [0]
>>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0):
... num_calls0[0] += 1
... num_input0[0] += len(rowids)
... return [rowid + 10 for rowid in rowids]
>>> func = func0
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls0[0], 1)
>>> ut.assert_eq(num_input0[0], 4)
[[11, 12, 13], [12, 15], [11], []]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls1 = [0]
>>> num_input1 = [0]
>>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np):
... num_calls1[0] += 1
... num_input1[0] += len(rowids)
... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids]
>>> func = func1
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls1[0], 1)
>>> ut.assert_eq(num_input1[0], 4)
[[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []]
"""
import utool as ut
# First flatten the list, and remember the original dimensions
flat_rowids, reverse_list = ut.invertible_flatten2(unflat_rowids)
# Then make the input unique
flat_rowids_arr = np.array(flat_rowids)
unique_flat_rowids, inverse_unique = np.unique(flat_rowids_arr, return_inverse=True)
# Then preform the lookup / implicit mapping
unique_flat_vals = func(unique_flat_rowids, **kwargs)
# Then broadcast unique values back to original flat positions
flat_vals_ = np.array(unique_flat_vals)[inverse_unique]
#flat_vals_ = np.array(unique_flat_vals).take(inverse_unique, axis=0)
output_shape = tuple(list(flat_rowids_arr.shape) + list(flat_vals_.shape[1:]))
flat_vals = np.array(flat_vals_).reshape(output_shape)
# Then _unflatten the results to the original input dimensions
unflat_vals = ut.unflatten2(flat_vals, reverse_list)
return unflat_vals | [
"def",
"unflat_unique_rowid_map",
"(",
"func",
",",
"unflat_rowids",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"utool",
"as",
"ut",
"# First flatten the list, and remember the original dimensions",
"flat_rowids",
",",
"reverse_list",
"=",
"ut",
".",
"invertible_flatten2",
"(",
"unflat_rowids",
")",
"# Then make the input unique",
"flat_rowids_arr",
"=",
"np",
".",
"array",
"(",
"flat_rowids",
")",
"unique_flat_rowids",
",",
"inverse_unique",
"=",
"np",
".",
"unique",
"(",
"flat_rowids_arr",
",",
"return_inverse",
"=",
"True",
")",
"# Then preform the lookup / implicit mapping",
"unique_flat_vals",
"=",
"func",
"(",
"unique_flat_rowids",
",",
"*",
"*",
"kwargs",
")",
"# Then broadcast unique values back to original flat positions",
"flat_vals_",
"=",
"np",
".",
"array",
"(",
"unique_flat_vals",
")",
"[",
"inverse_unique",
"]",
"#flat_vals_ = np.array(unique_flat_vals).take(inverse_unique, axis=0)",
"output_shape",
"=",
"tuple",
"(",
"list",
"(",
"flat_rowids_arr",
".",
"shape",
")",
"+",
"list",
"(",
"flat_vals_",
".",
"shape",
"[",
"1",
":",
"]",
")",
")",
"flat_vals",
"=",
"np",
".",
"array",
"(",
"flat_vals_",
")",
".",
"reshape",
"(",
"output_shape",
")",
"# Then _unflatten the results to the original input dimensions",
"unflat_vals",
"=",
"ut",
".",
"unflatten2",
"(",
"flat_vals",
",",
"reverse_list",
")",
"return",
"unflat_vals"
] | performs only one call to the underlying func with unique rowids the func
must be some lookup function
TODO: move this to a better place.
CommandLine:
python -m utool.util_list --test-unflat_unique_rowid_map:0
python -m utool.util_list --test-unflat_unique_rowid_map:1
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls0 = [0]
>>> num_input0 = [0]
>>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0):
... num_calls0[0] += 1
... num_input0[0] += len(rowids)
... return [rowid + 10 for rowid in rowids]
>>> func = func0
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls0[0], 1)
>>> ut.assert_eq(num_input0[0], 4)
[[11, 12, 13], [12, 15], [11], []]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> kwargs = {}
>>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []]
>>> num_calls1 = [0]
>>> num_input1 = [0]
>>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np):
... num_calls1[0] += 1
... num_input1[0] += len(rowids)
... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids]
>>> func = func1
>>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs)
>>> result = [arr.tolist() for arr in unflat_vals]
>>> print(result)
>>> ut.assert_eq(num_calls1[0], 1)
>>> ut.assert_eq(num_input1[0], 4)
[[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []] | [
"performs",
"only",
"one",
"call",
"to",
"the",
"underlying",
"func",
"with",
"unique",
"rowids",
"the",
"func",
"must",
"be",
"some",
"lookup",
"function"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L728-L796 | train |
Erotemic/utool | utool/util_list.py | allsame | def allsame(list_, strict=True):
"""
checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal
"""
if len(list_) == 0:
return True
first_item = list_[0]
return list_all_eq_to(list_, first_item, strict) | python | def allsame(list_, strict=True):
"""
checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal
"""
if len(list_) == 0:
return True
first_item = list_[0]
return list_all_eq_to(list_, first_item, strict) | [
"def",
"allsame",
"(",
"list_",
",",
"strict",
"=",
"True",
")",
":",
"if",
"len",
"(",
"list_",
")",
"==",
"0",
":",
"return",
"True",
"first_item",
"=",
"list_",
"[",
"0",
"]",
"return",
"list_all_eq_to",
"(",
"list_",
",",
"first_item",
",",
"strict",
")"
] | checks to see if list is equal everywhere
Args:
list_ (list):
Returns:
True if all items in the list are equal | [
"checks",
"to",
"see",
"if",
"list",
"is",
"equal",
"everywhere"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L832-L845 | train |
Erotemic/utool | utool/util_list.py | list_all_eq_to | def list_all_eq_to(list_, val, strict=True):
"""
checks to see if list is equal everywhere to a value
Args:
list_ (list):
val : value to check against
Returns:
True if all items in the list are equal to val
"""
if util_type.HAVE_NUMPY and isinstance(val, np.ndarray):
return all([np.all(item == val) for item in list_])
try:
# FUTURE WARNING
# FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=FutureWarning)
flags = [item == val for item in list_]
return all([np.all(flag) if hasattr(flag, '__array__') else flag
for flag in flags])
#return all([item == val for item in list_])
except ValueError:
if not strict:
return all([repr(item) == repr(val) for item in list_])
else:
raise | python | def list_all_eq_to(list_, val, strict=True):
"""
checks to see if list is equal everywhere to a value
Args:
list_ (list):
val : value to check against
Returns:
True if all items in the list are equal to val
"""
if util_type.HAVE_NUMPY and isinstance(val, np.ndarray):
return all([np.all(item == val) for item in list_])
try:
# FUTURE WARNING
# FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=FutureWarning)
flags = [item == val for item in list_]
return all([np.all(flag) if hasattr(flag, '__array__') else flag
for flag in flags])
#return all([item == val for item in list_])
except ValueError:
if not strict:
return all([repr(item) == repr(val) for item in list_])
else:
raise | [
"def",
"list_all_eq_to",
"(",
"list_",
",",
"val",
",",
"strict",
"=",
"True",
")",
":",
"if",
"util_type",
".",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"all",
"(",
"[",
"np",
".",
"all",
"(",
"item",
"==",
"val",
")",
"for",
"item",
"in",
"list_",
"]",
")",
"try",
":",
"# FUTURE WARNING",
"# FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"category",
"=",
"FutureWarning",
")",
"flags",
"=",
"[",
"item",
"==",
"val",
"for",
"item",
"in",
"list_",
"]",
"return",
"all",
"(",
"[",
"np",
".",
"all",
"(",
"flag",
")",
"if",
"hasattr",
"(",
"flag",
",",
"'__array__'",
")",
"else",
"flag",
"for",
"flag",
"in",
"flags",
"]",
")",
"#return all([item == val for item in list_])",
"except",
"ValueError",
":",
"if",
"not",
"strict",
":",
"return",
"all",
"(",
"[",
"repr",
"(",
"item",
")",
"==",
"repr",
"(",
"val",
")",
"for",
"item",
"in",
"list_",
"]",
")",
"else",
":",
"raise"
] | checks to see if list is equal everywhere to a value
Args:
list_ (list):
val : value to check against
Returns:
True if all items in the list are equal to val | [
"checks",
"to",
"see",
"if",
"list",
"is",
"equal",
"everywhere",
"to",
"a",
"value"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L848-L874 | train |
Erotemic/utool | utool/util_list.py | get_dirty_items | def get_dirty_items(item_list, flag_list):
"""
Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items
"""
assert len(item_list) == len(flag_list)
dirty_items = [item for (item, flag) in
zip(item_list, flag_list)
if not flag]
#print('num_dirty_items = %r' % len(dirty_items))
#print('item_list = %r' % (item_list,))
#print('flag_list = %r' % (flag_list,))
return dirty_items | python | def get_dirty_items(item_list, flag_list):
"""
Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items
"""
assert len(item_list) == len(flag_list)
dirty_items = [item for (item, flag) in
zip(item_list, flag_list)
if not flag]
#print('num_dirty_items = %r' % len(dirty_items))
#print('item_list = %r' % (item_list,))
#print('flag_list = %r' % (flag_list,))
return dirty_items | [
"def",
"get_dirty_items",
"(",
"item_list",
",",
"flag_list",
")",
":",
"assert",
"len",
"(",
"item_list",
")",
"==",
"len",
"(",
"flag_list",
")",
"dirty_items",
"=",
"[",
"item",
"for",
"(",
"item",
",",
"flag",
")",
"in",
"zip",
"(",
"item_list",
",",
"flag_list",
")",
"if",
"not",
"flag",
"]",
"#print('num_dirty_items = %r' % len(dirty_items))",
"#print('item_list = %r' % (item_list,))",
"#print('flag_list = %r' % (flag_list,))",
"return",
"dirty_items"
] | Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items | [
"Returns",
"each",
"item",
"in",
"item_list",
"where",
"not",
"flag",
"in",
"flag_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L877-L895 | train |
Erotemic/utool | utool/util_list.py | filterfalse_items | def filterfalse_items(item_list, flag_list):
"""
Returns items in item list where the corresponding item in flag list is true
Args:
item_list (list): list of items
flag_list (list): list of truthy values
Returns:
filtered_items : items where the corresponding flag was truthy
SeeAlso:
util_iter.ifilterfalse_items
"""
assert len(item_list) == len(flag_list)
filtered_items = list(util_iter.ifilterfalse_items(item_list, flag_list))
return filtered_items | python | def filterfalse_items(item_list, flag_list):
"""
Returns items in item list where the corresponding item in flag list is true
Args:
item_list (list): list of items
flag_list (list): list of truthy values
Returns:
filtered_items : items where the corresponding flag was truthy
SeeAlso:
util_iter.ifilterfalse_items
"""
assert len(item_list) == len(flag_list)
filtered_items = list(util_iter.ifilterfalse_items(item_list, flag_list))
return filtered_items | [
"def",
"filterfalse_items",
"(",
"item_list",
",",
"flag_list",
")",
":",
"assert",
"len",
"(",
"item_list",
")",
"==",
"len",
"(",
"flag_list",
")",
"filtered_items",
"=",
"list",
"(",
"util_iter",
".",
"ifilterfalse_items",
"(",
"item_list",
",",
"flag_list",
")",
")",
"return",
"filtered_items"
] | Returns items in item list where the corresponding item in flag list is true
Args:
item_list (list): list of items
flag_list (list): list of truthy values
Returns:
filtered_items : items where the corresponding flag was truthy
SeeAlso:
util_iter.ifilterfalse_items | [
"Returns",
"items",
"in",
"item",
"list",
"where",
"the",
"corresponding",
"item",
"in",
"flag",
"list",
"is",
"true"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L966-L982 | train |
Erotemic/utool | utool/util_list.py | isect | def isect(list1, list2):
r"""
returns list1 elements that are also in list2. preserves order of list1
intersect_ordered
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> result = intersect_ordered(list1, list2)
>>> print(result)
['featweight_rowid']
Timeit:
def timeit_func(func, *args):
niter = 10
times = []
for count in range(niter):
with ut.Timer(verbose=False) as t:
_ = func(*args)
times.append(t.ellapsed)
return sum(times) / niter
grid = {
'size1': [1000, 5000, 10000, 50000],
'size2': [1000, 5000, 10000, 50000],
#'overlap': [0, 1],
}
data = []
for kw in ut.all_dict_combinations(grid):
pool = np.arange(kw['size1'] * 2)
size2 = size1 = kw['size1']
size2 = kw['size2']
list1 = (np.random.rand(size1) * size1).astype(np.int32).tolist()
list1 = ut.random_sample(pool, size1).tolist()
list2 = ut.random_sample(pool, size2).tolist()
list1 = set(list1)
list2 = set(list2)
kw['ut'] = timeit_func(ut.isect, list1, list2)
#kw['np1'] = timeit_func(np.intersect1d, list1, list2)
#kw['py1'] = timeit_func(lambda a, b: set.intersection(set(a), set(b)), list1, list2)
kw['py2'] = timeit_func(lambda a, b: sorted(set.intersection(set(a), set(b))), list1, list2)
data.append(kw)
import pandas as pd
pd.options.display.max_rows = 1000
pd.options.display.width = 1000
df = pd.DataFrame.from_dict(data)
data_keys = list(grid.keys())
other_keys = ut.setdiff(df.columns, data_keys)
df = df.reindex_axis(data_keys + other_keys, axis=1)
df['abs_change'] = df['ut'] - df['py2']
df['pct_change'] = df['abs_change'] / df['ut'] * 100
#print(df.sort('abs_change', ascending=False))
print(str(df).split('\n')[0])
for row in df.values:
argmin = row[len(data_keys):len(data_keys) + len(other_keys)].argmin() + len(data_keys)
print(' ' + ', '.join([
'%6d' % (r) if x < len(data_keys) else (
ut.color_text('%8.6f' % (r,), 'blue')
if x == argmin else '%8.6f' % (r,))
for x, r in enumerate(row)
]))
%timeit ut.isect(list1, list2)
%timeit np.intersect1d(list1, list2, assume_unique=True)
%timeit set.intersection(set(list1), set(list2))
#def highlight_max(s):
# '''
# highlight the maximum in a Series yellow.
# '''
# is_max = s == s.max()
# return ['background-color: yellow' if v else '' for v in is_max]
#df.style.apply(highlight_max)
"""
set2 = set(list2)
return [item for item in list1 if item in set2] | python | def isect(list1, list2):
r"""
returns list1 elements that are also in list2. preserves order of list1
intersect_ordered
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> result = intersect_ordered(list1, list2)
>>> print(result)
['featweight_rowid']
Timeit:
def timeit_func(func, *args):
niter = 10
times = []
for count in range(niter):
with ut.Timer(verbose=False) as t:
_ = func(*args)
times.append(t.ellapsed)
return sum(times) / niter
grid = {
'size1': [1000, 5000, 10000, 50000],
'size2': [1000, 5000, 10000, 50000],
#'overlap': [0, 1],
}
data = []
for kw in ut.all_dict_combinations(grid):
pool = np.arange(kw['size1'] * 2)
size2 = size1 = kw['size1']
size2 = kw['size2']
list1 = (np.random.rand(size1) * size1).astype(np.int32).tolist()
list1 = ut.random_sample(pool, size1).tolist()
list2 = ut.random_sample(pool, size2).tolist()
list1 = set(list1)
list2 = set(list2)
kw['ut'] = timeit_func(ut.isect, list1, list2)
#kw['np1'] = timeit_func(np.intersect1d, list1, list2)
#kw['py1'] = timeit_func(lambda a, b: set.intersection(set(a), set(b)), list1, list2)
kw['py2'] = timeit_func(lambda a, b: sorted(set.intersection(set(a), set(b))), list1, list2)
data.append(kw)
import pandas as pd
pd.options.display.max_rows = 1000
pd.options.display.width = 1000
df = pd.DataFrame.from_dict(data)
data_keys = list(grid.keys())
other_keys = ut.setdiff(df.columns, data_keys)
df = df.reindex_axis(data_keys + other_keys, axis=1)
df['abs_change'] = df['ut'] - df['py2']
df['pct_change'] = df['abs_change'] / df['ut'] * 100
#print(df.sort('abs_change', ascending=False))
print(str(df).split('\n')[0])
for row in df.values:
argmin = row[len(data_keys):len(data_keys) + len(other_keys)].argmin() + len(data_keys)
print(' ' + ', '.join([
'%6d' % (r) if x < len(data_keys) else (
ut.color_text('%8.6f' % (r,), 'blue')
if x == argmin else '%8.6f' % (r,))
for x, r in enumerate(row)
]))
%timeit ut.isect(list1, list2)
%timeit np.intersect1d(list1, list2, assume_unique=True)
%timeit set.intersection(set(list1), set(list2))
#def highlight_max(s):
# '''
# highlight the maximum in a Series yellow.
# '''
# is_max = s == s.max()
# return ['background-color: yellow' if v else '' for v in is_max]
#df.style.apply(highlight_max)
"""
set2 = set(list2)
return [item for item in list1 if item in set2] | [
"def",
"isect",
"(",
"list1",
",",
"list2",
")",
":",
"set2",
"=",
"set",
"(",
"list2",
")",
"return",
"[",
"item",
"for",
"item",
"in",
"list1",
"if",
"item",
"in",
"set2",
"]"
] | r"""
returns list1 elements that are also in list2. preserves order of list1
intersect_ordered
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> result = intersect_ordered(list1, list2)
>>> print(result)
['featweight_rowid']
Timeit:
def timeit_func(func, *args):
niter = 10
times = []
for count in range(niter):
with ut.Timer(verbose=False) as t:
_ = func(*args)
times.append(t.ellapsed)
return sum(times) / niter
grid = {
'size1': [1000, 5000, 10000, 50000],
'size2': [1000, 5000, 10000, 50000],
#'overlap': [0, 1],
}
data = []
for kw in ut.all_dict_combinations(grid):
pool = np.arange(kw['size1'] * 2)
size2 = size1 = kw['size1']
size2 = kw['size2']
list1 = (np.random.rand(size1) * size1).astype(np.int32).tolist()
list1 = ut.random_sample(pool, size1).tolist()
list2 = ut.random_sample(pool, size2).tolist()
list1 = set(list1)
list2 = set(list2)
kw['ut'] = timeit_func(ut.isect, list1, list2)
#kw['np1'] = timeit_func(np.intersect1d, list1, list2)
#kw['py1'] = timeit_func(lambda a, b: set.intersection(set(a), set(b)), list1, list2)
kw['py2'] = timeit_func(lambda a, b: sorted(set.intersection(set(a), set(b))), list1, list2)
data.append(kw)
import pandas as pd
pd.options.display.max_rows = 1000
pd.options.display.width = 1000
df = pd.DataFrame.from_dict(data)
data_keys = list(grid.keys())
other_keys = ut.setdiff(df.columns, data_keys)
df = df.reindex_axis(data_keys + other_keys, axis=1)
df['abs_change'] = df['ut'] - df['py2']
df['pct_change'] = df['abs_change'] / df['ut'] * 100
#print(df.sort('abs_change', ascending=False))
print(str(df).split('\n')[0])
for row in df.values:
argmin = row[len(data_keys):len(data_keys) + len(other_keys)].argmin() + len(data_keys)
print(' ' + ', '.join([
'%6d' % (r) if x < len(data_keys) else (
ut.color_text('%8.6f' % (r,), 'blue')
if x == argmin else '%8.6f' % (r,))
for x, r in enumerate(row)
]))
%timeit ut.isect(list1, list2)
%timeit np.intersect1d(list1, list2, assume_unique=True)
%timeit set.intersection(set(list1), set(list2))
#def highlight_max(s):
# '''
# highlight the maximum in a Series yellow.
# '''
# is_max = s == s.max()
# return ['background-color: yellow' if v else '' for v in is_max]
#df.style.apply(highlight_max) | [
"r",
"returns",
"list1",
"elements",
"that",
"are",
"also",
"in",
"list2",
".",
"preserves",
"order",
"of",
"list1"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1001-L1088 | train |
Erotemic/utool | utool/util_list.py | is_subset_of_any | def is_subset_of_any(set_, other_sets):
"""
returns True if set_ is a subset of any set in other_sets
Args:
set_ (set):
other_sets (list of sets):
Returns:
bool: flag
CommandLine:
python -m utool.util_list --test-is_subset_of_any
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2, 1}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
False
"""
set_ = set(set_)
other_sets = map(set, other_sets)
return any([set_.issubset(other_set) for other_set in other_sets]) | python | def is_subset_of_any(set_, other_sets):
"""
returns True if set_ is a subset of any set in other_sets
Args:
set_ (set):
other_sets (list of sets):
Returns:
bool: flag
CommandLine:
python -m utool.util_list --test-is_subset_of_any
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2, 1}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
False
"""
set_ = set(set_)
other_sets = map(set, other_sets)
return any([set_.issubset(other_set) for other_set in other_sets]) | [
"def",
"is_subset_of_any",
"(",
"set_",
",",
"other_sets",
")",
":",
"set_",
"=",
"set",
"(",
"set_",
")",
"other_sets",
"=",
"map",
"(",
"set",
",",
"other_sets",
")",
"return",
"any",
"(",
"[",
"set_",
".",
"issubset",
"(",
"other_set",
")",
"for",
"other_set",
"in",
"other_sets",
"]",
")"
] | returns True if set_ is a subset of any set in other_sets
Args:
set_ (set):
other_sets (list of sets):
Returns:
bool: flag
CommandLine:
python -m utool.util_list --test-is_subset_of_any
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2, 1}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> set_ = {1, 2}
>>> other_sets = [{1, 4}, {3, 2}]
>>> # execute function
>>> result = is_subset_of_any(set_, other_sets)
>>> # verify results
>>> print(result)
False | [
"returns",
"True",
"if",
"set_",
"is",
"a",
"subset",
"of",
"any",
"set",
"in",
"other_sets"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1157-L1197 | train |
Erotemic/utool | utool/util_list.py | unique_ordered | def unique_ordered(list_):
"""
Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]
>>> unique_list = unique_ordered(list_)
>>> result = ('unique_list = %s' % (str(unique_list),))
>>> print(result)
unique_list = [4, 6, 0, 1, 2]
"""
list_ = list(list_)
flag_list = flag_unique_items(list_)
unique_list = compress(list_, flag_list)
return unique_list | python | def unique_ordered(list_):
"""
Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]
>>> unique_list = unique_ordered(list_)
>>> result = ('unique_list = %s' % (str(unique_list),))
>>> print(result)
unique_list = [4, 6, 0, 1, 2]
"""
list_ = list(list_)
flag_list = flag_unique_items(list_)
unique_list = compress(list_, flag_list)
return unique_list | [
"def",
"unique_ordered",
"(",
"list_",
")",
":",
"list_",
"=",
"list",
"(",
"list_",
")",
"flag_list",
"=",
"flag_unique_items",
"(",
"list_",
")",
"unique_list",
"=",
"compress",
"(",
"list_",
",",
"flag_list",
")",
"return",
"unique_list"
] | Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [4, 6, 6, 0, 6, 1, 0, 2, 2, 1]
>>> unique_list = unique_ordered(list_)
>>> result = ('unique_list = %s' % (str(unique_list),))
>>> print(result)
unique_list = [4, 6, 0, 1, 2] | [
"Returns",
"unique",
"items",
"in",
"list_",
"in",
"the",
"order",
"they",
"were",
"seen",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1352-L1377 | train |
Erotemic/utool | utool/util_list.py | setdiff | def setdiff(list1, list2):
"""
returns list1 elements that are not in list2. preserves order of list1
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> new_list = setdiff_ordered(list1, list2)
>>> result = ut.repr4(new_list, nl=False)
>>> print(result)
['feature_rowid', 'config_rowid', 'featweight_forground_weight']
"""
set2 = set(list2)
return [item for item in list1 if item not in set2] | python | def setdiff(list1, list2):
"""
returns list1 elements that are not in list2. preserves order of list1
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> new_list = setdiff_ordered(list1, list2)
>>> result = ut.repr4(new_list, nl=False)
>>> print(result)
['feature_rowid', 'config_rowid', 'featweight_forground_weight']
"""
set2 = set(list2)
return [item for item in list1 if item not in set2] | [
"def",
"setdiff",
"(",
"list1",
",",
"list2",
")",
":",
"set2",
"=",
"set",
"(",
"list2",
")",
"return",
"[",
"item",
"for",
"item",
"in",
"list1",
"if",
"item",
"not",
"in",
"set2",
"]"
] | returns list1 elements that are not in list2. preserves order of list1
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']
>>> list2 = [u'featweight_rowid']
>>> new_list = setdiff_ordered(list1, list2)
>>> result = ut.repr4(new_list, nl=False)
>>> print(result)
['feature_rowid', 'config_rowid', 'featweight_forground_weight'] | [
"returns",
"list1",
"elements",
"that",
"are",
"not",
"in",
"list2",
".",
"preserves",
"order",
"of",
"list1"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1407-L1430 | train |
Erotemic/utool | utool/util_list.py | isetdiff_flags | def isetdiff_flags(list1, list2):
"""
move to util_iter
"""
set2 = set(list2)
return (item not in set2 for item in list1) | python | def isetdiff_flags(list1, list2):
"""
move to util_iter
"""
set2 = set(list2)
return (item not in set2 for item in list1) | [
"def",
"isetdiff_flags",
"(",
"list1",
",",
"list2",
")",
":",
"set2",
"=",
"set",
"(",
"list2",
")",
"return",
"(",
"item",
"not",
"in",
"set2",
"for",
"item",
"in",
"list1",
")"
] | move to util_iter | [
"move",
"to",
"util_iter"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1437-L1442 | train |
Erotemic/utool | utool/util_list.py | unflat_take | def unflat_take(items_list, unflat_index_list):
r"""
Returns nested subset of items_list
Args:
items_list (list):
unflat_index_list (list): nested list of indices
CommandLine:
python -m utool.util_list --exec-unflat_take
SeeAlso:
ut.take
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> items_list = [1, 2, 3, 4, 5]
>>> unflat_index_list = [[0, 1], [2, 3], [0, 4]]
>>> result = unflat_take(items_list, unflat_index_list)
>>> print(result)
[[1, 2], [3, 4], [1, 5]]
"""
return [unflat_take(items_list, xs)
if isinstance(xs, list) else
take(items_list, xs)
for xs in unflat_index_list] | python | def unflat_take(items_list, unflat_index_list):
r"""
Returns nested subset of items_list
Args:
items_list (list):
unflat_index_list (list): nested list of indices
CommandLine:
python -m utool.util_list --exec-unflat_take
SeeAlso:
ut.take
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> items_list = [1, 2, 3, 4, 5]
>>> unflat_index_list = [[0, 1], [2, 3], [0, 4]]
>>> result = unflat_take(items_list, unflat_index_list)
>>> print(result)
[[1, 2], [3, 4], [1, 5]]
"""
return [unflat_take(items_list, xs)
if isinstance(xs, list) else
take(items_list, xs)
for xs in unflat_index_list] | [
"def",
"unflat_take",
"(",
"items_list",
",",
"unflat_index_list",
")",
":",
"return",
"[",
"unflat_take",
"(",
"items_list",
",",
"xs",
")",
"if",
"isinstance",
"(",
"xs",
",",
"list",
")",
"else",
"take",
"(",
"items_list",
",",
"xs",
")",
"for",
"xs",
"in",
"unflat_index_list",
"]"
] | r"""
Returns nested subset of items_list
Args:
items_list (list):
unflat_index_list (list): nested list of indices
CommandLine:
python -m utool.util_list --exec-unflat_take
SeeAlso:
ut.take
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> items_list = [1, 2, 3, 4, 5]
>>> unflat_index_list = [[0, 1], [2, 3], [0, 4]]
>>> result = unflat_take(items_list, unflat_index_list)
>>> print(result)
[[1, 2], [3, 4], [1, 5]] | [
"r",
"Returns",
"nested",
"subset",
"of",
"items_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1568-L1594 | train |
Erotemic/utool | utool/util_list.py | argsort | def argsort(*args, **kwargs):
"""
like np.argsort but for lists
Args:
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
CommandLine:
python -m utool.util_list argsort
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100})
>>> print(result)
"""
if len(args) == 1 and isinstance(args[0], dict):
dict_ = args[0]
index_list = list(dict_.keys())
value_list = list(dict_.values())
return sortedby2(index_list, value_list)
else:
index_list = list(range(len(args[0])))
return sortedby2(index_list, *args, **kwargs) | python | def argsort(*args, **kwargs):
"""
like np.argsort but for lists
Args:
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
CommandLine:
python -m utool.util_list argsort
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100})
>>> print(result)
"""
if len(args) == 1 and isinstance(args[0], dict):
dict_ = args[0]
index_list = list(dict_.keys())
value_list = list(dict_.values())
return sortedby2(index_list, value_list)
else:
index_list = list(range(len(args[0])))
return sortedby2(index_list, *args, **kwargs) | [
"def",
"argsort",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"dict",
")",
":",
"dict_",
"=",
"args",
"[",
"0",
"]",
"index_list",
"=",
"list",
"(",
"dict_",
".",
"keys",
"(",
")",
")",
"value_list",
"=",
"list",
"(",
"dict_",
".",
"values",
"(",
")",
")",
"return",
"sortedby2",
"(",
"index_list",
",",
"value_list",
")",
"else",
":",
"index_list",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"args",
"[",
"0",
"]",
")",
")",
")",
"return",
"sortedby2",
"(",
"index_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | like np.argsort but for lists
Args:
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
CommandLine:
python -m utool.util_list argsort
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100})
>>> print(result) | [
"like",
"np",
".",
"argsort",
"but",
"for",
"lists"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1597-L1622 | train |
Erotemic/utool | utool/util_list.py | argsort2 | def argsort2(indexable, key=None, reverse=False):
"""
Returns the indices that would sort a indexable object.
This is similar to np.argsort, but it is written in pure python and works
on both lists and dictionaries.
Args:
indexable (list or dict): indexable to sort by
Returns:
list: indices: list of indices such that sorts the indexable
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> # argsort works on dicts
>>> dict_ = indexable = {'a': 3, 'b': 2, 'c': 100}
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(dict_, indices)) == sorted(dict_.values())
>>> # argsort works on lists
>>> indexable = [100, 2, 432, 10]
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(indexable, indices)) == sorted(indexable)
>>> # argsort works on iterators
>>> indexable = reversed(range(100))
>>> indices = ut.argsort2(indexable)
>>> assert indices[0] == 99
"""
# Create an iterator of value/key pairs
if isinstance(indexable, dict):
vk_iter = ((v, k) for k, v in indexable.items())
else:
vk_iter = ((v, k) for k, v in enumerate(indexable))
# Sort by values and extract the keys
if key is None:
indices = [k for v, k in sorted(vk_iter, reverse=reverse)]
else:
indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]),
reverse=reverse)]
return indices | python | def argsort2(indexable, key=None, reverse=False):
"""
Returns the indices that would sort a indexable object.
This is similar to np.argsort, but it is written in pure python and works
on both lists and dictionaries.
Args:
indexable (list or dict): indexable to sort by
Returns:
list: indices: list of indices such that sorts the indexable
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> # argsort works on dicts
>>> dict_ = indexable = {'a': 3, 'b': 2, 'c': 100}
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(dict_, indices)) == sorted(dict_.values())
>>> # argsort works on lists
>>> indexable = [100, 2, 432, 10]
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(indexable, indices)) == sorted(indexable)
>>> # argsort works on iterators
>>> indexable = reversed(range(100))
>>> indices = ut.argsort2(indexable)
>>> assert indices[0] == 99
"""
# Create an iterator of value/key pairs
if isinstance(indexable, dict):
vk_iter = ((v, k) for k, v in indexable.items())
else:
vk_iter = ((v, k) for k, v in enumerate(indexable))
# Sort by values and extract the keys
if key is None:
indices = [k for v, k in sorted(vk_iter, reverse=reverse)]
else:
indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]),
reverse=reverse)]
return indices | [
"def",
"argsort2",
"(",
"indexable",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"# Create an iterator of value/key pairs",
"if",
"isinstance",
"(",
"indexable",
",",
"dict",
")",
":",
"vk_iter",
"=",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"indexable",
".",
"items",
"(",
")",
")",
"else",
":",
"vk_iter",
"=",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"enumerate",
"(",
"indexable",
")",
")",
"# Sort by values and extract the keys",
"if",
"key",
"is",
"None",
":",
"indices",
"=",
"[",
"k",
"for",
"v",
",",
"k",
"in",
"sorted",
"(",
"vk_iter",
",",
"reverse",
"=",
"reverse",
")",
"]",
"else",
":",
"indices",
"=",
"[",
"k",
"for",
"v",
",",
"k",
"in",
"sorted",
"(",
"vk_iter",
",",
"key",
"=",
"lambda",
"vk",
":",
"key",
"(",
"vk",
"[",
"0",
"]",
")",
",",
"reverse",
"=",
"reverse",
")",
"]",
"return",
"indices"
] | Returns the indices that would sort a indexable object.
This is similar to np.argsort, but it is written in pure python and works
on both lists and dictionaries.
Args:
indexable (list or dict): indexable to sort by
Returns:
list: indices: list of indices such that sorts the indexable
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> # argsort works on dicts
>>> dict_ = indexable = {'a': 3, 'b': 2, 'c': 100}
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(dict_, indices)) == sorted(dict_.values())
>>> # argsort works on lists
>>> indexable = [100, 2, 432, 10]
>>> indices = ut.argsort2(indexable)
>>> assert list(ut.take(indexable, indices)) == sorted(indexable)
>>> # argsort works on iterators
>>> indexable = reversed(range(100))
>>> indices = ut.argsort2(indexable)
>>> assert indices[0] == 99 | [
"Returns",
"the",
"indices",
"that",
"would",
"sort",
"a",
"indexable",
"object",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1625-L1665 | train |
Erotemic/utool | utool/util_list.py | index_complement | def index_complement(index_list, len_=None):
"""
Returns the other indicies in a list of length ``len_``
"""
mask1 = index_to_boolmask(index_list, len_)
mask2 = not_list(mask1)
index_list_bar = list_where(mask2)
return index_list_bar | python | def index_complement(index_list, len_=None):
"""
Returns the other indicies in a list of length ``len_``
"""
mask1 = index_to_boolmask(index_list, len_)
mask2 = not_list(mask1)
index_list_bar = list_where(mask2)
return index_list_bar | [
"def",
"index_complement",
"(",
"index_list",
",",
"len_",
"=",
"None",
")",
":",
"mask1",
"=",
"index_to_boolmask",
"(",
"index_list",
",",
"len_",
")",
"mask2",
"=",
"not_list",
"(",
"mask1",
")",
"index_list_bar",
"=",
"list_where",
"(",
"mask2",
")",
"return",
"index_list_bar"
] | Returns the other indicies in a list of length ``len_`` | [
"Returns",
"the",
"other",
"indicies",
"in",
"a",
"list",
"of",
"length",
"len_"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1746-L1753 | train |
Erotemic/utool | utool/util_list.py | take_complement | def take_complement(list_, index_list):
""" Returns items in ``list_`` not indexed by index_list """
mask = not_list(index_to_boolmask(index_list, len(list_)))
return compress(list_, mask) | python | def take_complement(list_, index_list):
""" Returns items in ``list_`` not indexed by index_list """
mask = not_list(index_to_boolmask(index_list, len(list_)))
return compress(list_, mask) | [
"def",
"take_complement",
"(",
"list_",
",",
"index_list",
")",
":",
"mask",
"=",
"not_list",
"(",
"index_to_boolmask",
"(",
"index_list",
",",
"len",
"(",
"list_",
")",
")",
")",
"return",
"compress",
"(",
"list_",
",",
"mask",
")"
] | Returns items in ``list_`` not indexed by index_list | [
"Returns",
"items",
"in",
"list_",
"not",
"indexed",
"by",
"index_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1756-L1759 | train |
Erotemic/utool | utool/util_list.py | take | def take(list_, index_list):
"""
Selects a subset of a list based on a list of indices.
This is similar to np.take, but pure python.
Args:
list_ (list): some indexable object
index_list (list, slice, int): some indexing object
Returns:
list or scalar: subset of the list
CommandLine:
python -m utool.util_list --test-take
SeeAlso:
ut.dict_take
ut.dict_subset
ut.none_take
ut.compress
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index_list = [2, 0]
>>> result = take(list_, index_list)
>>> print(result)
[2, 0]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = 2
>>> result = take(list_, index)
>>> print(result)
2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = slice(1, None, 2)
>>> result = take(list_, index)
>>> print(result)
[1, 3]
"""
try:
return [list_[index] for index in index_list]
except TypeError:
return list_[index_list] | python | def take(list_, index_list):
"""
Selects a subset of a list based on a list of indices.
This is similar to np.take, but pure python.
Args:
list_ (list): some indexable object
index_list (list, slice, int): some indexing object
Returns:
list or scalar: subset of the list
CommandLine:
python -m utool.util_list --test-take
SeeAlso:
ut.dict_take
ut.dict_subset
ut.none_take
ut.compress
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index_list = [2, 0]
>>> result = take(list_, index_list)
>>> print(result)
[2, 0]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = 2
>>> result = take(list_, index)
>>> print(result)
2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = slice(1, None, 2)
>>> result = take(list_, index)
>>> print(result)
[1, 3]
"""
try:
return [list_[index] for index in index_list]
except TypeError:
return list_[index_list] | [
"def",
"take",
"(",
"list_",
",",
"index_list",
")",
":",
"try",
":",
"return",
"[",
"list_",
"[",
"index",
"]",
"for",
"index",
"in",
"index_list",
"]",
"except",
"TypeError",
":",
"return",
"list_",
"[",
"index_list",
"]"
] | Selects a subset of a list based on a list of indices.
This is similar to np.take, but pure python.
Args:
list_ (list): some indexable object
index_list (list, slice, int): some indexing object
Returns:
list or scalar: subset of the list
CommandLine:
python -m utool.util_list --test-take
SeeAlso:
ut.dict_take
ut.dict_subset
ut.none_take
ut.compress
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index_list = [2, 0]
>>> result = take(list_, index_list)
>>> print(result)
[2, 0]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = 2
>>> result = take(list_, index)
>>> print(result)
2
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [0, 1, 2, 3]
>>> index = slice(1, None, 2)
>>> result = take(list_, index)
>>> print(result)
[1, 3] | [
"Selects",
"a",
"subset",
"of",
"a",
"list",
"based",
"on",
"a",
"list",
"of",
"indices",
".",
"This",
"is",
"similar",
"to",
"np",
".",
"take",
"but",
"pure",
"python",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1772-L1823 | train |
Erotemic/utool | utool/util_list.py | take_percentile | def take_percentile(arr, percent):
""" take the top `percent` items in a list rounding up """
size = len(arr)
stop = min(int(size * percent), len(arr))
return arr[0:stop] | python | def take_percentile(arr, percent):
""" take the top `percent` items in a list rounding up """
size = len(arr)
stop = min(int(size * percent), len(arr))
return arr[0:stop] | [
"def",
"take_percentile",
"(",
"arr",
",",
"percent",
")",
":",
"size",
"=",
"len",
"(",
"arr",
")",
"stop",
"=",
"min",
"(",
"int",
"(",
"size",
"*",
"percent",
")",
",",
"len",
"(",
"arr",
")",
")",
"return",
"arr",
"[",
"0",
":",
"stop",
"]"
] | take the top `percent` items in a list rounding up | [
"take",
"the",
"top",
"percent",
"items",
"in",
"a",
"list",
"rounding",
"up"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1834-L1838 | train |
Erotemic/utool | utool/util_list.py | snapped_slice | def snapped_slice(size, frac, n):
r"""
Creates a slice spanning `n` items in a list of length `size` at position
`frac`.
Args:
size (int): length of the list
frac (float): position in the range [0, 1]
n (int): number of items in the slice
Returns:
slice: slice object that best fits the criteria
SeeAlso:
take_percentile_parts
Example:
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> print(snapped_slice(0, 0, 10))
>>> print(snapped_slice(1, 0, 10))
>>> print(snapped_slice(100, 0, 10))
>>> print(snapped_slice(9, 0, 10))
>>> print(snapped_slice(100, 1, 10))
pass
"""
if size < n:
n = size
start = int(size * frac - ceil(n / 2)) + 1
stop = int(size * frac + floor(n / 2)) + 1
# slide to the front or the back
buf = 0
if stop >= size:
buf = (size - stop)
elif start < 0:
buf = 0 - start
stop += buf
start += buf
assert stop <= size, 'out of bounds [%r, %r]' % (stop, start)
sl = slice(start, stop)
return sl | python | def snapped_slice(size, frac, n):
r"""
Creates a slice spanning `n` items in a list of length `size` at position
`frac`.
Args:
size (int): length of the list
frac (float): position in the range [0, 1]
n (int): number of items in the slice
Returns:
slice: slice object that best fits the criteria
SeeAlso:
take_percentile_parts
Example:
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> print(snapped_slice(0, 0, 10))
>>> print(snapped_slice(1, 0, 10))
>>> print(snapped_slice(100, 0, 10))
>>> print(snapped_slice(9, 0, 10))
>>> print(snapped_slice(100, 1, 10))
pass
"""
if size < n:
n = size
start = int(size * frac - ceil(n / 2)) + 1
stop = int(size * frac + floor(n / 2)) + 1
# slide to the front or the back
buf = 0
if stop >= size:
buf = (size - stop)
elif start < 0:
buf = 0 - start
stop += buf
start += buf
assert stop <= size, 'out of bounds [%r, %r]' % (stop, start)
sl = slice(start, stop)
return sl | [
"def",
"snapped_slice",
"(",
"size",
",",
"frac",
",",
"n",
")",
":",
"if",
"size",
"<",
"n",
":",
"n",
"=",
"size",
"start",
"=",
"int",
"(",
"size",
"*",
"frac",
"-",
"ceil",
"(",
"n",
"/",
"2",
")",
")",
"+",
"1",
"stop",
"=",
"int",
"(",
"size",
"*",
"frac",
"+",
"floor",
"(",
"n",
"/",
"2",
")",
")",
"+",
"1",
"# slide to the front or the back",
"buf",
"=",
"0",
"if",
"stop",
">=",
"size",
":",
"buf",
"=",
"(",
"size",
"-",
"stop",
")",
"elif",
"start",
"<",
"0",
":",
"buf",
"=",
"0",
"-",
"start",
"stop",
"+=",
"buf",
"start",
"+=",
"buf",
"assert",
"stop",
"<=",
"size",
",",
"'out of bounds [%r, %r]'",
"%",
"(",
"stop",
",",
"start",
")",
"sl",
"=",
"slice",
"(",
"start",
",",
"stop",
")",
"return",
"sl"
] | r"""
Creates a slice spanning `n` items in a list of length `size` at position
`frac`.
Args:
size (int): length of the list
frac (float): position in the range [0, 1]
n (int): number of items in the slice
Returns:
slice: slice object that best fits the criteria
SeeAlso:
take_percentile_parts
Example:
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> print(snapped_slice(0, 0, 10))
>>> print(snapped_slice(1, 0, 10))
>>> print(snapped_slice(100, 0, 10))
>>> print(snapped_slice(9, 0, 10))
>>> print(snapped_slice(100, 1, 10))
pass | [
"r",
"Creates",
"a",
"slice",
"spanning",
"n",
"items",
"in",
"a",
"list",
"of",
"length",
"size",
"at",
"position",
"frac",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1841-L1884 | train |
Erotemic/utool | utool/util_list.py | take_percentile_parts | def take_percentile_parts(arr, front=None, mid=None, back=None):
r"""
Take parts from front, back, or middle of a list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> arr = list(range(20))
>>> front = 3
>>> mid = 3
>>> back = 3
>>> result = take_percentile_parts(arr, front, mid, back)
>>> print(result)
[0, 1, 2, 9, 10, 11, 17, 18, 19]
"""
slices = []
if front:
slices += [snapped_slice(len(arr), 0.0, front)]
if mid:
slices += [snapped_slice(len(arr), 0.5, mid)]
if back:
slices += [snapped_slice(len(arr), 1.0, back)]
parts = flatten([arr[sl] for sl in slices])
return parts | python | def take_percentile_parts(arr, front=None, mid=None, back=None):
r"""
Take parts from front, back, or middle of a list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> arr = list(range(20))
>>> front = 3
>>> mid = 3
>>> back = 3
>>> result = take_percentile_parts(arr, front, mid, back)
>>> print(result)
[0, 1, 2, 9, 10, 11, 17, 18, 19]
"""
slices = []
if front:
slices += [snapped_slice(len(arr), 0.0, front)]
if mid:
slices += [snapped_slice(len(arr), 0.5, mid)]
if back:
slices += [snapped_slice(len(arr), 1.0, back)]
parts = flatten([arr[sl] for sl in slices])
return parts | [
"def",
"take_percentile_parts",
"(",
"arr",
",",
"front",
"=",
"None",
",",
"mid",
"=",
"None",
",",
"back",
"=",
"None",
")",
":",
"slices",
"=",
"[",
"]",
"if",
"front",
":",
"slices",
"+=",
"[",
"snapped_slice",
"(",
"len",
"(",
"arr",
")",
",",
"0.0",
",",
"front",
")",
"]",
"if",
"mid",
":",
"slices",
"+=",
"[",
"snapped_slice",
"(",
"len",
"(",
"arr",
")",
",",
"0.5",
",",
"mid",
")",
"]",
"if",
"back",
":",
"slices",
"+=",
"[",
"snapped_slice",
"(",
"len",
"(",
"arr",
")",
",",
"1.0",
",",
"back",
")",
"]",
"parts",
"=",
"flatten",
"(",
"[",
"arr",
"[",
"sl",
"]",
"for",
"sl",
"in",
"slices",
"]",
")",
"return",
"parts"
] | r"""
Take parts from front, back, or middle of a list
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> arr = list(range(20))
>>> front = 3
>>> mid = 3
>>> back = 3
>>> result = take_percentile_parts(arr, front, mid, back)
>>> print(result)
[0, 1, 2, 9, 10, 11, 17, 18, 19] | [
"r",
"Take",
"parts",
"from",
"front",
"back",
"or",
"middle",
"of",
"a",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1907-L1931 | train |
Erotemic/utool | utool/util_list.py | broadcast_zip | def broadcast_zip(list1, list2):
r"""
Zips elementwise pairs between list1 and list2. Broadcasts
the first dimension if a single list is of length 1.
Aliased as bzip
Args:
list1 (list):
list2 (list):
Returns:
list: list of pairs
SeeAlso:
util_dict.dzip
Raises:
ValueError: if the list dimensions are not broadcastable
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> assert list(bzip([1, 2, 3], [4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1, 2, 3], [4, 4, 4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1], [4, 4, 4])) == [(1, 4), (1, 4), (1, 4)]
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [])
>>> ut.assert_raises(ValueError, bzip, [], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [], [4])
>>> ut.assert_raises(ValueError, bzip, [1, 2], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [4, 5])
"""
try:
len(list1)
except TypeError:
list1 = list(list1)
try:
len(list2)
except TypeError:
list2 = list(list2)
# if len(list1) == 0 or len(list2) == 0:
# # Corner case where either list is empty
# return []
if len(list1) == 1 and len(list2) > 1:
list1 = list1 * len(list2)
elif len(list1) > 1 and len(list2) == 1:
list2 = list2 * len(list1)
elif len(list1) != len(list2):
raise ValueError('out of alignment len(list1)=%r, len(list2)=%r' % (
len(list1), len(list2)))
# return list(zip(list1, list2))
return zip(list1, list2) | python | def broadcast_zip(list1, list2):
r"""
Zips elementwise pairs between list1 and list2. Broadcasts
the first dimension if a single list is of length 1.
Aliased as bzip
Args:
list1 (list):
list2 (list):
Returns:
list: list of pairs
SeeAlso:
util_dict.dzip
Raises:
ValueError: if the list dimensions are not broadcastable
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> assert list(bzip([1, 2, 3], [4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1, 2, 3], [4, 4, 4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1], [4, 4, 4])) == [(1, 4), (1, 4), (1, 4)]
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [])
>>> ut.assert_raises(ValueError, bzip, [], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [], [4])
>>> ut.assert_raises(ValueError, bzip, [1, 2], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [4, 5])
"""
try:
len(list1)
except TypeError:
list1 = list(list1)
try:
len(list2)
except TypeError:
list2 = list(list2)
# if len(list1) == 0 or len(list2) == 0:
# # Corner case where either list is empty
# return []
if len(list1) == 1 and len(list2) > 1:
list1 = list1 * len(list2)
elif len(list1) > 1 and len(list2) == 1:
list2 = list2 * len(list1)
elif len(list1) != len(list2):
raise ValueError('out of alignment len(list1)=%r, len(list2)=%r' % (
len(list1), len(list2)))
# return list(zip(list1, list2))
return zip(list1, list2) | [
"def",
"broadcast_zip",
"(",
"list1",
",",
"list2",
")",
":",
"try",
":",
"len",
"(",
"list1",
")",
"except",
"TypeError",
":",
"list1",
"=",
"list",
"(",
"list1",
")",
"try",
":",
"len",
"(",
"list2",
")",
"except",
"TypeError",
":",
"list2",
"=",
"list",
"(",
"list2",
")",
"# if len(list1) == 0 or len(list2) == 0:",
"# # Corner case where either list is empty",
"# return []",
"if",
"len",
"(",
"list1",
")",
"==",
"1",
"and",
"len",
"(",
"list2",
")",
">",
"1",
":",
"list1",
"=",
"list1",
"*",
"len",
"(",
"list2",
")",
"elif",
"len",
"(",
"list1",
")",
">",
"1",
"and",
"len",
"(",
"list2",
")",
"==",
"1",
":",
"list2",
"=",
"list2",
"*",
"len",
"(",
"list1",
")",
"elif",
"len",
"(",
"list1",
")",
"!=",
"len",
"(",
"list2",
")",
":",
"raise",
"ValueError",
"(",
"'out of alignment len(list1)=%r, len(list2)=%r'",
"%",
"(",
"len",
"(",
"list1",
")",
",",
"len",
"(",
"list2",
")",
")",
")",
"# return list(zip(list1, list2))",
"return",
"zip",
"(",
"list1",
",",
"list2",
")"
] | r"""
Zips elementwise pairs between list1 and list2. Broadcasts
the first dimension if a single list is of length 1.
Aliased as bzip
Args:
list1 (list):
list2 (list):
Returns:
list: list of pairs
SeeAlso:
util_dict.dzip
Raises:
ValueError: if the list dimensions are not broadcastable
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> assert list(bzip([1, 2, 3], [4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1, 2, 3], [4, 4, 4])) == [(1, 4), (2, 4), (3, 4)]
>>> assert list(bzip([1], [4, 4, 4])) == [(1, 4), (1, 4), (1, 4)]
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [])
>>> ut.assert_raises(ValueError, bzip, [], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [], [4])
>>> ut.assert_raises(ValueError, bzip, [1, 2], [4, 5, 6])
>>> ut.assert_raises(ValueError, bzip, [1, 2, 3], [4, 5]) | [
"r",
"Zips",
"elementwise",
"pairs",
"between",
"list1",
"and",
"list2",
".",
"Broadcasts",
"the",
"first",
"dimension",
"if",
"a",
"single",
"list",
"is",
"of",
"length",
"1",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1979-L2031 | train |
Erotemic/utool | utool/util_list.py | equal | def equal(list1, list2):
""" takes flags returns indexes of True values """
return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)] | python | def equal(list1, list2):
""" takes flags returns indexes of True values """
return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)] | [
"def",
"equal",
"(",
"list1",
",",
"list2",
")",
":",
"return",
"[",
"item1",
"==",
"item2",
"for",
"item1",
",",
"item2",
"in",
"broadcast_zip",
"(",
"list1",
",",
"list2",
")",
"]"
] | takes flags returns indexes of True values | [
"takes",
"flags",
"returns",
"indexes",
"of",
"True",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2039-L2041 | train |
Erotemic/utool | utool/util_list.py | scalar_input_map | def scalar_input_map(func, input_):
"""
Map like function
Args:
func: function to apply
input_ : either an iterable or scalar value
Returns:
If ``input_`` is iterable this function behaves like map
otherwise applies func to ``input_``
"""
if util_iter.isiterable(input_):
return list(map(func, input_))
else:
return func(input_) | python | def scalar_input_map(func, input_):
"""
Map like function
Args:
func: function to apply
input_ : either an iterable or scalar value
Returns:
If ``input_`` is iterable this function behaves like map
otherwise applies func to ``input_``
"""
if util_iter.isiterable(input_):
return list(map(func, input_))
else:
return func(input_) | [
"def",
"scalar_input_map",
"(",
"func",
",",
"input_",
")",
":",
"if",
"util_iter",
".",
"isiterable",
"(",
"input_",
")",
":",
"return",
"list",
"(",
"map",
"(",
"func",
",",
"input_",
")",
")",
"else",
":",
"return",
"func",
"(",
"input_",
")"
] | Map like function
Args:
func: function to apply
input_ : either an iterable or scalar value
Returns:
If ``input_`` is iterable this function behaves like map
otherwise applies func to ``input_`` | [
"Map",
"like",
"function"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2061-L2076 | train |
Erotemic/utool | utool/util_list.py | partial_imap_1to1 | def partial_imap_1to1(func, si_func):
""" a bit messy
DEPRICATE
"""
@functools.wraps(si_func)
def wrapper(input_):
if not util_iter.isiterable(input_):
return func(si_func(input_))
else:
return list(map(func, si_func(input_)))
set_funcname(wrapper, util_str.get_callable_name(func) + '_mapper_' + get_funcname(si_func))
return wrapper | python | def partial_imap_1to1(func, si_func):
""" a bit messy
DEPRICATE
"""
@functools.wraps(si_func)
def wrapper(input_):
if not util_iter.isiterable(input_):
return func(si_func(input_))
else:
return list(map(func, si_func(input_)))
set_funcname(wrapper, util_str.get_callable_name(func) + '_mapper_' + get_funcname(si_func))
return wrapper | [
"def",
"partial_imap_1to1",
"(",
"func",
",",
"si_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"si_func",
")",
"def",
"wrapper",
"(",
"input_",
")",
":",
"if",
"not",
"util_iter",
".",
"isiterable",
"(",
"input_",
")",
":",
"return",
"func",
"(",
"si_func",
"(",
"input_",
")",
")",
"else",
":",
"return",
"list",
"(",
"map",
"(",
"func",
",",
"si_func",
"(",
"input_",
")",
")",
")",
"set_funcname",
"(",
"wrapper",
",",
"util_str",
".",
"get_callable_name",
"(",
"func",
")",
"+",
"'_mapper_'",
"+",
"get_funcname",
"(",
"si_func",
")",
")",
"return",
"wrapper"
] | a bit messy
DEPRICATE | [
"a",
"bit",
"messy"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2079-L2091 | train |
Erotemic/utool | utool/util_list.py | sample_zip | def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1):
""" Helper for sampling
Given a list of lists, samples one item for each list and bins them into
num_samples bins. If all sublists are of equal size this is equivilent to a
zip, but otherewise consecutive bins will have monotonically less
elemements
# Doctest doesn't work with assertionerror
#util_list.sample_zip(items_list, 2)
#...
#AssertionError: Overflow occured
Args:
items_list (list):
num_samples (?):
allow_overflow (bool):
per_bin (int):
Returns:
tuple : (samples_list, overflow_samples)
Examples:
>>> # DISABLE_DOCTEST
>>> from utool import util_list
>>> items_list = [[1, 2, 3, 4, 0], [5, 6, 7], [], [8, 9], [10]]
>>> util_list.sample_zip(items_list, 5)
...
[[1, 5, 8, 10], [2, 6, 9], [3, 7], [4], [0]]
>>> util_list.sample_zip(items_list, 2, allow_overflow=True)
...
([[1, 5, 8, 10], [2, 6, 9]], [3, 7, 4])
>>> util_list.sample_zip(items_list, 4, allow_overflow=True, per_bin=2)
...
([[1, 5, 8, 10, 2, 6, 9], [3, 7, 4], [], []], [0])
"""
# Prealloc a list of lists
samples_list = [[] for _ in range(num_samples)]
# Sample the ix-th value from every list
samples_iter = zip_longest(*items_list)
sx = 0
for ix, samples_ in zip(range(num_samples), samples_iter):
samples = filter_Nones(samples_)
samples_list[sx].extend(samples)
# Put per_bin from each sublist into a sample
if (ix + 1) % per_bin == 0:
sx += 1
# Check for overflow
if allow_overflow:
overflow_samples = flatten([filter_Nones(samples_) for samples_ in samples_iter])
return samples_list, overflow_samples
else:
try:
samples_iter.next()
except StopIteration:
pass
else:
raise AssertionError('Overflow occured')
return samples_list | python | def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1):
""" Helper for sampling
Given a list of lists, samples one item for each list and bins them into
num_samples bins. If all sublists are of equal size this is equivilent to a
zip, but otherewise consecutive bins will have monotonically less
elemements
# Doctest doesn't work with assertionerror
#util_list.sample_zip(items_list, 2)
#...
#AssertionError: Overflow occured
Args:
items_list (list):
num_samples (?):
allow_overflow (bool):
per_bin (int):
Returns:
tuple : (samples_list, overflow_samples)
Examples:
>>> # DISABLE_DOCTEST
>>> from utool import util_list
>>> items_list = [[1, 2, 3, 4, 0], [5, 6, 7], [], [8, 9], [10]]
>>> util_list.sample_zip(items_list, 5)
...
[[1, 5, 8, 10], [2, 6, 9], [3, 7], [4], [0]]
>>> util_list.sample_zip(items_list, 2, allow_overflow=True)
...
([[1, 5, 8, 10], [2, 6, 9]], [3, 7, 4])
>>> util_list.sample_zip(items_list, 4, allow_overflow=True, per_bin=2)
...
([[1, 5, 8, 10, 2, 6, 9], [3, 7, 4], [], []], [0])
"""
# Prealloc a list of lists
samples_list = [[] for _ in range(num_samples)]
# Sample the ix-th value from every list
samples_iter = zip_longest(*items_list)
sx = 0
for ix, samples_ in zip(range(num_samples), samples_iter):
samples = filter_Nones(samples_)
samples_list[sx].extend(samples)
# Put per_bin from each sublist into a sample
if (ix + 1) % per_bin == 0:
sx += 1
# Check for overflow
if allow_overflow:
overflow_samples = flatten([filter_Nones(samples_) for samples_ in samples_iter])
return samples_list, overflow_samples
else:
try:
samples_iter.next()
except StopIteration:
pass
else:
raise AssertionError('Overflow occured')
return samples_list | [
"def",
"sample_zip",
"(",
"items_list",
",",
"num_samples",
",",
"allow_overflow",
"=",
"False",
",",
"per_bin",
"=",
"1",
")",
":",
"# Prealloc a list of lists",
"samples_list",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"num_samples",
")",
"]",
"# Sample the ix-th value from every list",
"samples_iter",
"=",
"zip_longest",
"(",
"*",
"items_list",
")",
"sx",
"=",
"0",
"for",
"ix",
",",
"samples_",
"in",
"zip",
"(",
"range",
"(",
"num_samples",
")",
",",
"samples_iter",
")",
":",
"samples",
"=",
"filter_Nones",
"(",
"samples_",
")",
"samples_list",
"[",
"sx",
"]",
".",
"extend",
"(",
"samples",
")",
"# Put per_bin from each sublist into a sample",
"if",
"(",
"ix",
"+",
"1",
")",
"%",
"per_bin",
"==",
"0",
":",
"sx",
"+=",
"1",
"# Check for overflow",
"if",
"allow_overflow",
":",
"overflow_samples",
"=",
"flatten",
"(",
"[",
"filter_Nones",
"(",
"samples_",
")",
"for",
"samples_",
"in",
"samples_iter",
"]",
")",
"return",
"samples_list",
",",
"overflow_samples",
"else",
":",
"try",
":",
"samples_iter",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"raise",
"AssertionError",
"(",
"'Overflow occured'",
")",
"return",
"samples_list"
] | Helper for sampling
Given a list of lists, samples one item for each list and bins them into
num_samples bins. If all sublists are of equal size this is equivilent to a
zip, but otherewise consecutive bins will have monotonically less
elemements
# Doctest doesn't work with assertionerror
#util_list.sample_zip(items_list, 2)
#...
#AssertionError: Overflow occured
Args:
items_list (list):
num_samples (?):
allow_overflow (bool):
per_bin (int):
Returns:
tuple : (samples_list, overflow_samples)
Examples:
>>> # DISABLE_DOCTEST
>>> from utool import util_list
>>> items_list = [[1, 2, 3, 4, 0], [5, 6, 7], [], [8, 9], [10]]
>>> util_list.sample_zip(items_list, 5)
...
[[1, 5, 8, 10], [2, 6, 9], [3, 7], [4], [0]]
>>> util_list.sample_zip(items_list, 2, allow_overflow=True)
...
([[1, 5, 8, 10], [2, 6, 9]], [3, 7, 4])
>>> util_list.sample_zip(items_list, 4, allow_overflow=True, per_bin=2)
...
([[1, 5, 8, 10, 2, 6, 9], [3, 7, 4], [], []], [0]) | [
"Helper",
"for",
"sampling"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2094-L2152 | train |
Erotemic/utool | utool/util_list.py | issorted | def issorted(list_, op=operator.le):
"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""
return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1)) | python | def issorted(list_, op=operator.le):
"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""
return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1)) | [
"def",
"issorted",
"(",
"list_",
",",
"op",
"=",
"operator",
".",
"le",
")",
":",
"return",
"all",
"(",
"op",
"(",
"list_",
"[",
"ix",
"]",
",",
"list_",
"[",
"ix",
"+",
"1",
"]",
")",
"for",
"ix",
"in",
"range",
"(",
"len",
"(",
"list_",
")",
"-",
"1",
")",
")"
] | Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted | [
"Determines",
"if",
"a",
"list",
"is",
"sorted"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2213-L2224 | train |
Erotemic/utool | utool/util_list.py | list_depth | def list_depth(list_, func=max, _depth=0):
"""
Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]
>>> result = (list_depth(list_, _depth=0))
>>> print(result)
"""
depth_list = [list_depth(item, func=func, _depth=_depth + 1)
for item in list_ if util_type.is_listlike(item)]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | python | def list_depth(list_, func=max, _depth=0):
"""
Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]
>>> result = (list_depth(list_, _depth=0))
>>> print(result)
"""
depth_list = [list_depth(item, func=func, _depth=_depth + 1)
for item in list_ if util_type.is_listlike(item)]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | [
"def",
"list_depth",
"(",
"list_",
",",
"func",
"=",
"max",
",",
"_depth",
"=",
"0",
")",
":",
"depth_list",
"=",
"[",
"list_depth",
"(",
"item",
",",
"func",
"=",
"func",
",",
"_depth",
"=",
"_depth",
"+",
"1",
")",
"for",
"item",
"in",
"list_",
"if",
"util_type",
".",
"is_listlike",
"(",
"item",
")",
"]",
"if",
"len",
"(",
"depth_list",
")",
">",
"0",
":",
"return",
"func",
"(",
"depth_list",
")",
"else",
":",
"return",
"_depth"
] | Returns the deepest level of nesting within a list of lists
Args:
list_ : a nested listlike object
func : depth aggregation strategy (defaults to max)
_depth : internal var
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]]
>>> result = (list_depth(list_, _depth=0))
>>> print(result) | [
"Returns",
"the",
"deepest",
"level",
"of",
"nesting",
"within",
"a",
"list",
"of",
"lists"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2434-L2456 | train |
Erotemic/utool | utool/util_list.py | depth | def depth(sequence, func=max, _depth=0):
"""
Find the nesting depth of a nested sequence
"""
if isinstance(sequence, dict):
sequence = list(sequence.values())
depth_list = [depth(item, func=func, _depth=_depth + 1)
for item in sequence if (isinstance(item, dict) or util_type.is_listlike(item))]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | python | def depth(sequence, func=max, _depth=0):
"""
Find the nesting depth of a nested sequence
"""
if isinstance(sequence, dict):
sequence = list(sequence.values())
depth_list = [depth(item, func=func, _depth=_depth + 1)
for item in sequence if (isinstance(item, dict) or util_type.is_listlike(item))]
if len(depth_list) > 0:
return func(depth_list)
else:
return _depth | [
"def",
"depth",
"(",
"sequence",
",",
"func",
"=",
"max",
",",
"_depth",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"sequence",
",",
"dict",
")",
":",
"sequence",
"=",
"list",
"(",
"sequence",
".",
"values",
"(",
")",
")",
"depth_list",
"=",
"[",
"depth",
"(",
"item",
",",
"func",
"=",
"func",
",",
"_depth",
"=",
"_depth",
"+",
"1",
")",
"for",
"item",
"in",
"sequence",
"if",
"(",
"isinstance",
"(",
"item",
",",
"dict",
")",
"or",
"util_type",
".",
"is_listlike",
"(",
"item",
")",
")",
"]",
"if",
"len",
"(",
"depth_list",
")",
">",
"0",
":",
"return",
"func",
"(",
"depth_list",
")",
"else",
":",
"return",
"_depth"
] | Find the nesting depth of a nested sequence | [
"Find",
"the",
"nesting",
"depth",
"of",
"a",
"nested",
"sequence"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2459-L2470 | train |
Erotemic/utool | utool/util_list.py | list_deep_types | def list_deep_types(list_):
"""
Returns all types in a deep list
"""
type_list = []
for item in list_:
if util_type.is_listlike(item):
type_list.extend(list_deep_types(item))
else:
type_list.append(type(item))
return type_list | python | def list_deep_types(list_):
"""
Returns all types in a deep list
"""
type_list = []
for item in list_:
if util_type.is_listlike(item):
type_list.extend(list_deep_types(item))
else:
type_list.append(type(item))
return type_list | [
"def",
"list_deep_types",
"(",
"list_",
")",
":",
"type_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list_",
":",
"if",
"util_type",
".",
"is_listlike",
"(",
"item",
")",
":",
"type_list",
".",
"extend",
"(",
"list_deep_types",
"(",
"item",
")",
")",
"else",
":",
"type_list",
".",
"append",
"(",
"type",
"(",
"item",
")",
")",
"return",
"type_list"
] | Returns all types in a deep list | [
"Returns",
"all",
"types",
"in",
"a",
"deep",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2473-L2483 | train |
Erotemic/utool | utool/util_list.py | depth_profile | def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False):
r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
list_ (list):
max_depth (None):
compress_homogenous (bool):
compress_consecutive (bool): experimental
CommandLine:
python -m utool.util_list --test-depth_profile
Setup:
>>> from utool.util_list import * # NOQA
Example0:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
>>> result = depth_profile(list_)
>>> print(result)
(2, 3, 4)
Example1:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_)
>>> print(result)
[[(1, 1, 1), 3], [1, 2, [1, 2]], 2]
Example2:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_, max_depth=1)
>>> print(result)
[[(1, '1'), 3], [1, 2, [1, '2']], 2]
Example3:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 2], [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
[[2, 3], 1]
Example4:
>>> # ENABLE_DOCTEST
>>> list_ = [[3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [9, 5, 3], [2, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
[2] * 6 + [3, 2]
Example5:
>>> # ENABLE_DOCTEST
>>> list_ = [[[3, 9], 2], [[3, 9], 2], [[3, 9], 2], [[3, 9], 2]] #, [3, 2], [3, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
(4, [2, 1])
Example6:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[1, 2]], [1, 2]], [[[1, 2]], [1, 2]], [[[0, 2]], [1]]]
>>> result1 = depth_profile(list_, compress_homogenous=True, compress_consecutive=False)
>>> result2 = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> result = str(result1) + '\n' + str(result2)
>>> print(result)
[[(1, 2), 2], [(1, 2), 2], [(1, 2), 1]]
[[(1, 2), 2]] * 2 + [[(1, 2), 1]]
Example7:
>>> # ENABLE_DOCTEST
>>> list_ = [[{'a': [1, 2], 'b': [3, 4, 5]}, [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example8:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1]], [[[1, 1], [1, 1]]], [[[[1, 3], 1], [[1, 3, 3], 1, 1]]]]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example9:
>>> # ENABLE_DOCTEST
>>> list_ = []
>>> result = depth_profile(list_)
>>> print(result)
# THIS IS AN ERROR???
SHOULD BE
#[1, 1], [1, 2, 2], (1, ([1, 2]), (
Example10:
>>> # ENABLE_DOCTEST
>>> fm1 = [[0, 0], [0, 0]]
>>> fm2 = [[0, 0], [0, 0], [0, 0]]
>>> fm3 = [[0, 0], [0, 0], [0, 0], [0, 0]]
>>> list_ = [0, 0, 0]
>>> list_ = [fm1, fm2, fm3]
>>> max_depth = 0
>>> new_depth = True
>>> result = depth_profile(list_, max_depth=max_depth, new_depth=new_depth)
>>> print(result)
"""
if isinstance(list_, dict):
list_ = list(list_.values()) # handle dict
level_shape_list = []
# For a pure bottom level list return the length
if not any(map(util_type.is_listlike, list_)):
return len(list_)
if False and new_depth:
pass
# max_depth_ = None if max_depth is None else max_depth - 1
# if max_depth_ is None or max_depth_ > 0:
# pass
# else:
# for item in list_:
# if isinstance(item, dict):
# item = list(item.values()) # handle dict
# if util_type.is_listlike(item):
# if max_depth is None:
# level_shape_list.append(depth_profile(item, None))
# else:
# if max_depth >= 0:
# level_shape_list.append(depth_profile(item, max_depth - 1))
# else:
# level_shape_list.append(str(len(item)))
# else:
# level_shape_list.append(1)
else:
for item in list_:
if isinstance(item, dict):
item = list(item.values()) # handle dict
if util_type.is_listlike(item):
if max_depth is None:
level_shape_list.append(depth_profile(item, None))
else:
if max_depth >= 0:
level_shape_list.append(depth_profile(item, max_depth - 1))
else:
level_shape_list.append(str(len(item)))
else:
level_shape_list.append(1)
if compress_homogenous:
# removes redudant information by returning a shape duple
if allsame(level_shape_list):
dim_ = level_shape_list[0]
len_ = len(level_shape_list)
if isinstance(dim_, tuple):
level_shape_list = tuple([len_] + list(dim_))
else:
level_shape_list = tuple([len_, dim_])
if compress_consecutive:
hash_list = list(map(hash, map(str, level_shape_list)))
consec_list = group_consecutives(hash_list, 0)
if len(consec_list) != len(level_shape_list):
len_list = list(map(len, consec_list))
cumsum_list = np.cumsum(len_list)
consec_str = '['
thresh = 1
for len_, cumsum in zip(len_list, cumsum_list):
value = level_shape_list[cumsum - 1]
if len_ > thresh:
consec_str += str(value) + '] * ' + str(len_)
consec_str += ' + ['
else:
consec_str += str(value) + ', '
if consec_str.endswith(', '):
consec_str = consec_str[:-2]
#consec_str += ']'
#consec_str = consec_str.rstrip(', ').rstrip(']')
#consec_str = consec_str.rstrip(', ')
#if consec_str.endswith(']'):
# consec_str = consec_str[:-1]
consec_str += ']'
level_shape_list = consec_str
return level_shape_list | python | def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False):
r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
list_ (list):
max_depth (None):
compress_homogenous (bool):
compress_consecutive (bool): experimental
CommandLine:
python -m utool.util_list --test-depth_profile
Setup:
>>> from utool.util_list import * # NOQA
Example0:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
>>> result = depth_profile(list_)
>>> print(result)
(2, 3, 4)
Example1:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_)
>>> print(result)
[[(1, 1, 1), 3], [1, 2, [1, 2]], 2]
Example2:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_, max_depth=1)
>>> print(result)
[[(1, '1'), 3], [1, 2, [1, '2']], 2]
Example3:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 2], [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
[[2, 3], 1]
Example4:
>>> # ENABLE_DOCTEST
>>> list_ = [[3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [9, 5, 3], [2, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
[2] * 6 + [3, 2]
Example5:
>>> # ENABLE_DOCTEST
>>> list_ = [[[3, 9], 2], [[3, 9], 2], [[3, 9], 2], [[3, 9], 2]] #, [3, 2], [3, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
(4, [2, 1])
Example6:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[1, 2]], [1, 2]], [[[1, 2]], [1, 2]], [[[0, 2]], [1]]]
>>> result1 = depth_profile(list_, compress_homogenous=True, compress_consecutive=False)
>>> result2 = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> result = str(result1) + '\n' + str(result2)
>>> print(result)
[[(1, 2), 2], [(1, 2), 2], [(1, 2), 1]]
[[(1, 2), 2]] * 2 + [[(1, 2), 1]]
Example7:
>>> # ENABLE_DOCTEST
>>> list_ = [[{'a': [1, 2], 'b': [3, 4, 5]}, [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example8:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1]], [[[1, 1], [1, 1]]], [[[[1, 3], 1], [[1, 3, 3], 1, 1]]]]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example9:
>>> # ENABLE_DOCTEST
>>> list_ = []
>>> result = depth_profile(list_)
>>> print(result)
# THIS IS AN ERROR???
SHOULD BE
#[1, 1], [1, 2, 2], (1, ([1, 2]), (
Example10:
>>> # ENABLE_DOCTEST
>>> fm1 = [[0, 0], [0, 0]]
>>> fm2 = [[0, 0], [0, 0], [0, 0]]
>>> fm3 = [[0, 0], [0, 0], [0, 0], [0, 0]]
>>> list_ = [0, 0, 0]
>>> list_ = [fm1, fm2, fm3]
>>> max_depth = 0
>>> new_depth = True
>>> result = depth_profile(list_, max_depth=max_depth, new_depth=new_depth)
>>> print(result)
"""
if isinstance(list_, dict):
list_ = list(list_.values()) # handle dict
level_shape_list = []
# For a pure bottom level list return the length
if not any(map(util_type.is_listlike, list_)):
return len(list_)
if False and new_depth:
pass
# max_depth_ = None if max_depth is None else max_depth - 1
# if max_depth_ is None or max_depth_ > 0:
# pass
# else:
# for item in list_:
# if isinstance(item, dict):
# item = list(item.values()) # handle dict
# if util_type.is_listlike(item):
# if max_depth is None:
# level_shape_list.append(depth_profile(item, None))
# else:
# if max_depth >= 0:
# level_shape_list.append(depth_profile(item, max_depth - 1))
# else:
# level_shape_list.append(str(len(item)))
# else:
# level_shape_list.append(1)
else:
for item in list_:
if isinstance(item, dict):
item = list(item.values()) # handle dict
if util_type.is_listlike(item):
if max_depth is None:
level_shape_list.append(depth_profile(item, None))
else:
if max_depth >= 0:
level_shape_list.append(depth_profile(item, max_depth - 1))
else:
level_shape_list.append(str(len(item)))
else:
level_shape_list.append(1)
if compress_homogenous:
# removes redudant information by returning a shape duple
if allsame(level_shape_list):
dim_ = level_shape_list[0]
len_ = len(level_shape_list)
if isinstance(dim_, tuple):
level_shape_list = tuple([len_] + list(dim_))
else:
level_shape_list = tuple([len_, dim_])
if compress_consecutive:
hash_list = list(map(hash, map(str, level_shape_list)))
consec_list = group_consecutives(hash_list, 0)
if len(consec_list) != len(level_shape_list):
len_list = list(map(len, consec_list))
cumsum_list = np.cumsum(len_list)
consec_str = '['
thresh = 1
for len_, cumsum in zip(len_list, cumsum_list):
value = level_shape_list[cumsum - 1]
if len_ > thresh:
consec_str += str(value) + '] * ' + str(len_)
consec_str += ' + ['
else:
consec_str += str(value) + ', '
if consec_str.endswith(', '):
consec_str = consec_str[:-2]
#consec_str += ']'
#consec_str = consec_str.rstrip(', ').rstrip(']')
#consec_str = consec_str.rstrip(', ')
#if consec_str.endswith(']'):
# consec_str = consec_str[:-1]
consec_str += ']'
level_shape_list = consec_str
return level_shape_list | [
"def",
"depth_profile",
"(",
"list_",
",",
"max_depth",
"=",
"None",
",",
"compress_homogenous",
"=",
"True",
",",
"compress_consecutive",
"=",
"False",
",",
"new_depth",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"list_",
",",
"dict",
")",
":",
"list_",
"=",
"list",
"(",
"list_",
".",
"values",
"(",
")",
")",
"# handle dict",
"level_shape_list",
"=",
"[",
"]",
"# For a pure bottom level list return the length",
"if",
"not",
"any",
"(",
"map",
"(",
"util_type",
".",
"is_listlike",
",",
"list_",
")",
")",
":",
"return",
"len",
"(",
"list_",
")",
"if",
"False",
"and",
"new_depth",
":",
"pass",
"# max_depth_ = None if max_depth is None else max_depth - 1",
"# if max_depth_ is None or max_depth_ > 0:",
"# pass",
"# else:",
"# for item in list_:",
"# if isinstance(item, dict):",
"# item = list(item.values()) # handle dict",
"# if util_type.is_listlike(item):",
"# if max_depth is None:",
"# level_shape_list.append(depth_profile(item, None))",
"# else:",
"# if max_depth >= 0:",
"# level_shape_list.append(depth_profile(item, max_depth - 1))",
"# else:",
"# level_shape_list.append(str(len(item)))",
"# else:",
"# level_shape_list.append(1)",
"else",
":",
"for",
"item",
"in",
"list_",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"item",
"=",
"list",
"(",
"item",
".",
"values",
"(",
")",
")",
"# handle dict",
"if",
"util_type",
".",
"is_listlike",
"(",
"item",
")",
":",
"if",
"max_depth",
"is",
"None",
":",
"level_shape_list",
".",
"append",
"(",
"depth_profile",
"(",
"item",
",",
"None",
")",
")",
"else",
":",
"if",
"max_depth",
">=",
"0",
":",
"level_shape_list",
".",
"append",
"(",
"depth_profile",
"(",
"item",
",",
"max_depth",
"-",
"1",
")",
")",
"else",
":",
"level_shape_list",
".",
"append",
"(",
"str",
"(",
"len",
"(",
"item",
")",
")",
")",
"else",
":",
"level_shape_list",
".",
"append",
"(",
"1",
")",
"if",
"compress_homogenous",
":",
"# removes redudant information by returning a shape duple",
"if",
"allsame",
"(",
"level_shape_list",
")",
":",
"dim_",
"=",
"level_shape_list",
"[",
"0",
"]",
"len_",
"=",
"len",
"(",
"level_shape_list",
")",
"if",
"isinstance",
"(",
"dim_",
",",
"tuple",
")",
":",
"level_shape_list",
"=",
"tuple",
"(",
"[",
"len_",
"]",
"+",
"list",
"(",
"dim_",
")",
")",
"else",
":",
"level_shape_list",
"=",
"tuple",
"(",
"[",
"len_",
",",
"dim_",
"]",
")",
"if",
"compress_consecutive",
":",
"hash_list",
"=",
"list",
"(",
"map",
"(",
"hash",
",",
"map",
"(",
"str",
",",
"level_shape_list",
")",
")",
")",
"consec_list",
"=",
"group_consecutives",
"(",
"hash_list",
",",
"0",
")",
"if",
"len",
"(",
"consec_list",
")",
"!=",
"len",
"(",
"level_shape_list",
")",
":",
"len_list",
"=",
"list",
"(",
"map",
"(",
"len",
",",
"consec_list",
")",
")",
"cumsum_list",
"=",
"np",
".",
"cumsum",
"(",
"len_list",
")",
"consec_str",
"=",
"'['",
"thresh",
"=",
"1",
"for",
"len_",
",",
"cumsum",
"in",
"zip",
"(",
"len_list",
",",
"cumsum_list",
")",
":",
"value",
"=",
"level_shape_list",
"[",
"cumsum",
"-",
"1",
"]",
"if",
"len_",
">",
"thresh",
":",
"consec_str",
"+=",
"str",
"(",
"value",
")",
"+",
"'] * '",
"+",
"str",
"(",
"len_",
")",
"consec_str",
"+=",
"' + ['",
"else",
":",
"consec_str",
"+=",
"str",
"(",
"value",
")",
"+",
"', '",
"if",
"consec_str",
".",
"endswith",
"(",
"', '",
")",
":",
"consec_str",
"=",
"consec_str",
"[",
":",
"-",
"2",
"]",
"#consec_str += ']'",
"#consec_str = consec_str.rstrip(', ').rstrip(']')",
"#consec_str = consec_str.rstrip(', ')",
"#if consec_str.endswith(']'):",
"# consec_str = consec_str[:-1]",
"consec_str",
"+=",
"']'",
"level_shape_list",
"=",
"consec_str",
"return",
"level_shape_list"
] | r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
list_ (list):
max_depth (None):
compress_homogenous (bool):
compress_consecutive (bool): experimental
CommandLine:
python -m utool.util_list --test-depth_profile
Setup:
>>> from utool.util_list import * # NOQA
Example0:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
>>> result = depth_profile(list_)
>>> print(result)
(2, 3, 4)
Example1:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_)
>>> print(result)
[[(1, 1, 1), 3], [1, 2, [1, 2]], 2]
Example2:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[[1]]], [3, 4, 33]], [[1], [2, 3], [4, [5, 5]]], [1, 3]]
>>> result = depth_profile(list_, max_depth=1)
>>> print(result)
[[(1, '1'), 3], [1, 2, [1, '2']], 2]
Example3:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1, 2], [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
[[2, 3], 1]
Example4:
>>> # ENABLE_DOCTEST
>>> list_ = [[3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [9, 5, 3], [2, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
[2] * 6 + [3, 2]
Example5:
>>> # ENABLE_DOCTEST
>>> list_ = [[[3, 9], 2], [[3, 9], 2], [[3, 9], 2], [[3, 9], 2]] #, [3, 2], [3, 2]]
>>> result = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> print(result)
(4, [2, 1])
Example6:
>>> # ENABLE_DOCTEST
>>> list_ = [[[[1, 2]], [1, 2]], [[[1, 2]], [1, 2]], [[[0, 2]], [1]]]
>>> result1 = depth_profile(list_, compress_homogenous=True, compress_consecutive=False)
>>> result2 = depth_profile(list_, compress_homogenous=True, compress_consecutive=True)
>>> result = str(result1) + '\n' + str(result2)
>>> print(result)
[[(1, 2), 2], [(1, 2), 2], [(1, 2), 1]]
[[(1, 2), 2]] * 2 + [[(1, 2), 1]]
Example7:
>>> # ENABLE_DOCTEST
>>> list_ = [[{'a': [1, 2], 'b': [3, 4, 5]}, [1, 2, 3]], None]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example8:
>>> # ENABLE_DOCTEST
>>> list_ = [[[1]], [[[1, 1], [1, 1]]], [[[[1, 3], 1], [[1, 3, 3], 1, 1]]]]
>>> result = depth_profile(list_, compress_homogenous=True)
>>> print(result)
Example9:
>>> # ENABLE_DOCTEST
>>> list_ = []
>>> result = depth_profile(list_)
>>> print(result)
# THIS IS AN ERROR???
SHOULD BE
#[1, 1], [1, 2, 2], (1, ([1, 2]), (
Example10:
>>> # ENABLE_DOCTEST
>>> fm1 = [[0, 0], [0, 0]]
>>> fm2 = [[0, 0], [0, 0], [0, 0]]
>>> fm3 = [[0, 0], [0, 0], [0, 0], [0, 0]]
>>> list_ = [0, 0, 0]
>>> list_ = [fm1, fm2, fm3]
>>> max_depth = 0
>>> new_depth = True
>>> result = depth_profile(list_, max_depth=max_depth, new_depth=new_depth)
>>> print(result) | [
"r",
"Returns",
"a",
"nested",
"list",
"corresponding",
"the",
"shape",
"of",
"the",
"nested",
"structures",
"lists",
"represent",
"depth",
"tuples",
"represent",
"shape",
".",
"The",
"values",
"of",
"the",
"items",
"do",
"not",
"matter",
".",
"only",
"the",
"lengths",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2486-L2665 | train |
Erotemic/utool | utool/util_list.py | list_cover | def list_cover(list1, list2):
r"""
returns boolean for each position in list1 if it is in list2
Args:
list1 (list):
list2 (list):
Returns:
list: incover_list - true where list1 intersects list2
CommandLine:
python -m utool.util_list --test-list_cover
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list1 = [1, 2, 3, 4, 5, 6]
>>> list2 = [2, 3, 6]
>>> # execute function
>>> incover_list = list_cover(list1, list2)
>>> # verify results
>>> result = str(incover_list)
>>> print(result)
[False, True, True, False, False, True]
"""
set2 = set(list2)
incover_list = [item1 in set2 for item1 in list1]
return incover_list | python | def list_cover(list1, list2):
r"""
returns boolean for each position in list1 if it is in list2
Args:
list1 (list):
list2 (list):
Returns:
list: incover_list - true where list1 intersects list2
CommandLine:
python -m utool.util_list --test-list_cover
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list1 = [1, 2, 3, 4, 5, 6]
>>> list2 = [2, 3, 6]
>>> # execute function
>>> incover_list = list_cover(list1, list2)
>>> # verify results
>>> result = str(incover_list)
>>> print(result)
[False, True, True, False, False, True]
"""
set2 = set(list2)
incover_list = [item1 in set2 for item1 in list1]
return incover_list | [
"def",
"list_cover",
"(",
"list1",
",",
"list2",
")",
":",
"set2",
"=",
"set",
"(",
"list2",
")",
"incover_list",
"=",
"[",
"item1",
"in",
"set2",
"for",
"item1",
"in",
"list1",
"]",
"return",
"incover_list"
] | r"""
returns boolean for each position in list1 if it is in list2
Args:
list1 (list):
list2 (list):
Returns:
list: incover_list - true where list1 intersects list2
CommandLine:
python -m utool.util_list --test-list_cover
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> # build test data
>>> list1 = [1, 2, 3, 4, 5, 6]
>>> list2 = [2, 3, 6]
>>> # execute function
>>> incover_list = list_cover(list1, list2)
>>> # verify results
>>> result = str(incover_list)
>>> print(result)
[False, True, True, False, False, True] | [
"r",
"returns",
"boolean",
"for",
"each",
"position",
"in",
"list1",
"if",
"it",
"is",
"in",
"list2"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L2846-L2875 | train |
Erotemic/utool | utool/util_list.py | list_alignment | def list_alignment(list1, list2, missing=False):
"""
Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
list: sorting that will map list1 onto list2
CommandLine:
python -m utool.util_list list_alignment
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'b', 'c']
>>> sortx = list_alignment(list1, list2)
>>> list1_aligned = take(list1, sortx)
>>> assert list1_aligned == list2
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'a2', 'b', 'c', 'd']
>>> sortx = ut.list_alignment(list1, list2, missing=True)
>>> print('sortx = %r' % (sortx,))
>>> list1_aligned = ut.none_take(list1, sortx)
>>> result = ('list1_aligned = %s' % (ut.repr2(list1_aligned),))
>>> print(result)
list1_aligned = ['a', None, 'b', 'c', None]
"""
import utool as ut
item1_to_idx = make_index_lookup(list1)
if missing:
sortx = ut.dict_take(item1_to_idx, list2, None)
else:
sortx = ut.take(item1_to_idx, list2)
return sortx | python | def list_alignment(list1, list2, missing=False):
"""
Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
list: sorting that will map list1 onto list2
CommandLine:
python -m utool.util_list list_alignment
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'b', 'c']
>>> sortx = list_alignment(list1, list2)
>>> list1_aligned = take(list1, sortx)
>>> assert list1_aligned == list2
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'a2', 'b', 'c', 'd']
>>> sortx = ut.list_alignment(list1, list2, missing=True)
>>> print('sortx = %r' % (sortx,))
>>> list1_aligned = ut.none_take(list1, sortx)
>>> result = ('list1_aligned = %s' % (ut.repr2(list1_aligned),))
>>> print(result)
list1_aligned = ['a', None, 'b', 'c', None]
"""
import utool as ut
item1_to_idx = make_index_lookup(list1)
if missing:
sortx = ut.dict_take(item1_to_idx, list2, None)
else:
sortx = ut.take(item1_to_idx, list2)
return sortx | [
"def",
"list_alignment",
"(",
"list1",
",",
"list2",
",",
"missing",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"item1_to_idx",
"=",
"make_index_lookup",
"(",
"list1",
")",
"if",
"missing",
":",
"sortx",
"=",
"ut",
".",
"dict_take",
"(",
"item1_to_idx",
",",
"list2",
",",
"None",
")",
"else",
":",
"sortx",
"=",
"ut",
".",
"take",
"(",
"item1_to_idx",
",",
"list2",
")",
"return",
"sortx"
] | Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
list: sorting that will map list1 onto list2
CommandLine:
python -m utool.util_list list_alignment
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'b', 'c']
>>> sortx = list_alignment(list1, list2)
>>> list1_aligned = take(list1, sortx)
>>> assert list1_aligned == list2
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list1 = ['b', 'c', 'a']
>>> list2 = ['a', 'a2', 'b', 'c', 'd']
>>> sortx = ut.list_alignment(list1, list2, missing=True)
>>> print('sortx = %r' % (sortx,))
>>> list1_aligned = ut.none_take(list1, sortx)
>>> result = ('list1_aligned = %s' % (ut.repr2(list1_aligned),))
>>> print(result)
list1_aligned = ['a', None, 'b', 'c', None] | [
"Assumes",
"list",
"items",
"are",
"unique"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L3008-L3052 | train |
Erotemic/utool | utool/util_list.py | list_transpose | def list_transpose(list_, shape=None):
r"""
Swaps rows and columns.
nCols should be specified if the initial list is empty.
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_list --test-list_transpose
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[1, 2], [3, 4]]
>>> result = list_transpose(list_)
>>> print(result)
[(1, 3), (2, 4)]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = []
>>> result = list_transpose(list_, shape=(0, 5))
>>> print(result)
[[], [], [], [], []]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[], [], [], [], []]
>>> result = list_transpose(list_)
>>> print(result)
[]
Example3:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list_ = [[1, 2, 3], [3, 4]]
>>> ut.assert_raises(ValueError, list_transpose, list_)
"""
num_cols_set = unique([len(x) for x in list_])
if shape is None:
if len(num_cols_set) == 0:
raise ValueError('listT does not support empty transpose without shapes')
else:
assert len(shape) == 2, 'shape must be a 2-tuple'
if len(num_cols_set) == 0:
return [[] for _ in range(shape[1])]
elif num_cols_set[0] == 0:
return []
if len(num_cols_set) != 1:
raise ValueError('inconsistent column lengths=%r' % (num_cols_set,))
return list(zip(*list_)) | python | def list_transpose(list_, shape=None):
r"""
Swaps rows and columns.
nCols should be specified if the initial list is empty.
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_list --test-list_transpose
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[1, 2], [3, 4]]
>>> result = list_transpose(list_)
>>> print(result)
[(1, 3), (2, 4)]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = []
>>> result = list_transpose(list_, shape=(0, 5))
>>> print(result)
[[], [], [], [], []]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[], [], [], [], []]
>>> result = list_transpose(list_)
>>> print(result)
[]
Example3:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list_ = [[1, 2, 3], [3, 4]]
>>> ut.assert_raises(ValueError, list_transpose, list_)
"""
num_cols_set = unique([len(x) for x in list_])
if shape is None:
if len(num_cols_set) == 0:
raise ValueError('listT does not support empty transpose without shapes')
else:
assert len(shape) == 2, 'shape must be a 2-tuple'
if len(num_cols_set) == 0:
return [[] for _ in range(shape[1])]
elif num_cols_set[0] == 0:
return []
if len(num_cols_set) != 1:
raise ValueError('inconsistent column lengths=%r' % (num_cols_set,))
return list(zip(*list_)) | [
"def",
"list_transpose",
"(",
"list_",
",",
"shape",
"=",
"None",
")",
":",
"num_cols_set",
"=",
"unique",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"list_",
"]",
")",
"if",
"shape",
"is",
"None",
":",
"if",
"len",
"(",
"num_cols_set",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'listT does not support empty transpose without shapes'",
")",
"else",
":",
"assert",
"len",
"(",
"shape",
")",
"==",
"2",
",",
"'shape must be a 2-tuple'",
"if",
"len",
"(",
"num_cols_set",
")",
"==",
"0",
":",
"return",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"shape",
"[",
"1",
"]",
")",
"]",
"elif",
"num_cols_set",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"num_cols_set",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'inconsistent column lengths=%r'",
"%",
"(",
"num_cols_set",
",",
")",
")",
"return",
"list",
"(",
"zip",
"(",
"*",
"list_",
")",
")"
] | r"""
Swaps rows and columns.
nCols should be specified if the initial list is empty.
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_list --test-list_transpose
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[1, 2], [3, 4]]
>>> result = list_transpose(list_)
>>> print(result)
[(1, 3), (2, 4)]
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = []
>>> result = list_transpose(list_, shape=(0, 5))
>>> print(result)
[[], [], [], [], []]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [[], [], [], [], []]
>>> result = list_transpose(list_)
>>> print(result)
[]
Example3:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> list_ = [[1, 2, 3], [3, 4]]
>>> ut.assert_raises(ValueError, list_transpose, list_) | [
"r",
"Swaps",
"rows",
"and",
"columns",
".",
"nCols",
"should",
"be",
"specified",
"if",
"the",
"initial",
"list",
"is",
"empty",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L3065-L3122 | train |
Erotemic/utool | utool/util_list.py | delete_items_by_index | def delete_items_by_index(list_, index_list, copy=False):
"""
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [8, 1, 8, 1, 6, 6, 3, 4, 4, 5, 6]
>>> index_list = [2, -1]
>>> result = delete_items_by_index(list_, index_list)
>>> print(result)
[8, 1, 1, 6, 6, 3, 4, 4, 5]
"""
if copy:
list_ = list_[:]
# Rectify negative indicies
index_list_ = [(len(list_) + x if x < 0 else x) for x in index_list]
# Remove largest indicies first
index_list_ = sorted(index_list_, reverse=True)
for index in index_list_:
del list_[index]
return list_ | python | def delete_items_by_index(list_, index_list, copy=False):
"""
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [8, 1, 8, 1, 6, 6, 3, 4, 4, 5, 6]
>>> index_list = [2, -1]
>>> result = delete_items_by_index(list_, index_list)
>>> print(result)
[8, 1, 1, 6, 6, 3, 4, 4, 5]
"""
if copy:
list_ = list_[:]
# Rectify negative indicies
index_list_ = [(len(list_) + x if x < 0 else x) for x in index_list]
# Remove largest indicies first
index_list_ = sorted(index_list_, reverse=True)
for index in index_list_:
del list_[index]
return list_ | [
"def",
"delete_items_by_index",
"(",
"list_",
",",
"index_list",
",",
"copy",
"=",
"False",
")",
":",
"if",
"copy",
":",
"list_",
"=",
"list_",
"[",
":",
"]",
"# Rectify negative indicies",
"index_list_",
"=",
"[",
"(",
"len",
"(",
"list_",
")",
"+",
"x",
"if",
"x",
"<",
"0",
"else",
"x",
")",
"for",
"x",
"in",
"index_list",
"]",
"# Remove largest indicies first",
"index_list_",
"=",
"sorted",
"(",
"index_list_",
",",
"reverse",
"=",
"True",
")",
"for",
"index",
"in",
"index_list_",
":",
"del",
"list_",
"[",
"index",
"]",
"return",
"list_"
] | Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> list_ = [8, 1, 8, 1, 6, 6, 3, 4, 4, 5, 6]
>>> index_list = [2, -1]
>>> result = delete_items_by_index(list_, index_list)
>>> print(result)
[8, 1, 1, 6, 6, 3, 4, 4, 5] | [
"Remove",
"items",
"from",
"list_",
"at",
"positions",
"specified",
"in",
"index_list",
"The",
"original",
"list_",
"is",
"preserved",
"if",
"copy",
"is",
"True"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L3128-L3155 | train |
Erotemic/utool | utool/util_list.py | delete_list_items | def delete_list_items(list_, item_list, copy=False):
r"""
Remove items in ``item_list`` from ``list_``.
The original ``list_`` is preserved if ``copy`` is True
"""
if copy:
list_ = list_[:]
for item in item_list:
list_.remove(item)
return list_ | python | def delete_list_items(list_, item_list, copy=False):
r"""
Remove items in ``item_list`` from ``list_``.
The original ``list_`` is preserved if ``copy`` is True
"""
if copy:
list_ = list_[:]
for item in item_list:
list_.remove(item)
return list_ | [
"def",
"delete_list_items",
"(",
"list_",
",",
"item_list",
",",
"copy",
"=",
"False",
")",
":",
"if",
"copy",
":",
"list_",
"=",
"list_",
"[",
":",
"]",
"for",
"item",
"in",
"item_list",
":",
"list_",
".",
"remove",
"(",
"item",
")",
"return",
"list_"
] | r"""
Remove items in ``item_list`` from ``list_``.
The original ``list_`` is preserved if ``copy`` is True | [
"r",
"Remove",
"items",
"in",
"item_list",
"from",
"list_",
".",
"The",
"original",
"list_",
"is",
"preserved",
"if",
"copy",
"is",
"True"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L3158-L3167 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.