nodes
stringlengths 501
22.4k
| edges
stringlengths 138
5.07k
| code
stringlengths 108
19.3k
|
---|---|---|
0, module; 1, function_definition; 2, function_name:find_nearest; 3, parameters; 4, block; 5, identifier:sorted_list; 6, identifier:x; 7, expression_statement; 8, if_statement; 9, comment:"""
Find the nearest item of x from sorted array.
:type array: list
:param array: an iterable object that support inex
:param x: a comparable value
note: for finding the nearest item from a descending array, I recommend
find_nearest(sorted_list[::-1], x). Because the built-in list[::-1] method
is super fast.
Usage::
>>> find_nearest([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5.1)
5
**中文文档**
在正序数组中, 返回最接近x的数。
"""; 10, comparison_operator:x <= sorted_list[0]; 11, block; 12, elif_clause; 13, else_clause; 14, identifier:x; 15, subscript; 16, return_statement; 17, comparison_operator:x >= sorted_list[-1]; 18, block; 19, block; 20, identifier:sorted_list; 21, integer:0; 22, subscript; 23, identifier:x; 24, subscript; 25, return_statement; 26, expression_statement; 27, expression_statement; 28, if_statement; 29, identifier:sorted_list; 30, integer:0; 31, identifier:sorted_list; 32, unary_operator; 33, subscript; 34, assignment; 35, assignment; 36, comparison_operator:(x - lower) > (upper - x); 37, block; 38, else_clause; 39, integer:1; 40, identifier:sorted_list; 41, unary_operator; 42, identifier:lower; 43, call; 44, identifier:upper; 45, call; 46, parenthesized_expression; 47, parenthesized_expression; 48, return_statement; 49, block; 50, integer:1; 51, identifier:find_le; 52, argument_list; 53, identifier:find_ge; 54, argument_list; 55, binary_operator:x - lower; 56, binary_operator:upper - x; 57, identifier:upper; 58, return_statement; 59, identifier:sorted_list; 60, identifier:x; 61, identifier:sorted_list; 62, identifier:x; 63, identifier:x; 64, identifier:lower; 65, identifier:upper; 66, identifier:x; 67, identifier:lower | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 8, 11; 8, 12; 8, 13; 10, 14; 10, 15; 11, 16; 12, 17; 12, 18; 13, 19; 15, 20; 15, 21; 16, 22; 17, 23; 17, 24; 18, 25; 19, 26; 19, 27; 19, 28; 22, 29; 22, 30; 24, 31; 24, 32; 25, 33; 26, 34; 27, 35; 28, 36; 28, 37; 28, 38; 32, 39; 33, 40; 33, 41; 34, 42; 34, 43; 35, 44; 35, 45; 36, 46; 36, 47; 37, 48; 38, 49; 41, 50; 43, 51; 43, 52; 45, 53; 45, 54; 46, 55; 47, 56; 48, 57; 49, 58; 52, 59; 52, 60; 54, 61; 54, 62; 55, 63; 55, 64; 56, 65; 56, 66; 58, 67 | def find_nearest(sorted_list, x):
"""
Find the nearest item of x from sorted array.
:type array: list
:param array: an iterable object that support inex
:param x: a comparable value
note: for finding the nearest item from a descending array, I recommend
find_nearest(sorted_list[::-1], x). Because the built-in list[::-1] method
is super fast.
Usage::
>>> find_nearest([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5.1)
5
**中文文档**
在正序数组中, 返回最接近x的数。
"""
if x <= sorted_list[0]:
return sorted_list[0]
elif x >= sorted_list[-1]:
return sorted_list[-1]
else:
lower = find_le(sorted_list, x)
upper = find_ge(sorted_list, x)
if (x - lower) > (upper - x):
return upper
else:
return lower |
0, module; 1, function_definition; 2, function_name:_parse_dependencies; 3, parameters; 4, block; 5, identifier:string; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, for_statement; 13, expression_statement; 14, return_statement; 15, comment:"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""; 16, assignment; 17, assignment; 18, call; 19, assignment; 20, assignment; 21, identifier:dependency; 22, identifier:unsorted_dependencies; 23, block; 24, assignment; 25, expression_list; 26, identifier:contents; 27, call; 28, identifier:unsorted_dependencies; 29, call; 30, identifier:_check_parameters; 31, argument_list; 32, identifier:buildable_dependencies; 33, list; 34, identifier:given_dependencies; 35, list; 36, if_statement; 37, identifier:string; 38, subscript; 39, identifier:buildable_dependencies; 40, identifier:given_dependencies; 41, identifier:string; 42, identifier:_get_contents_between; 43, argument_list; 44, attribute; 45, argument_list; 46, identifier:unsorted_dependencies; 47, tuple; 48, comparison_operator:dependency[0] == '?'; 49, block; 50, else_clause; 51, identifier:string; 52, slice; 53, identifier:string; 54, string; 55, string; 56, identifier:contents; 57, identifier:split; 58, string; 59, string; 60, subscript; 61, string; 62, expression_statement; 63, block; 64, binary_operator:string.index(')') + 1; 65, string_content:(; 66, string_content:); 67, string_content:,; 68, string_content:?; 69, identifier:dependency; 70, integer:0; 71, string_content:?; 72, call; 73, expression_statement; 74, call; 75, integer:1; 76, attribute; 77, argument_list; 78, call; 79, attribute; 80, argument_list; 81, identifier:given_dependencies; 82, identifier:append; 83, subscript; 84, attribute; 85, argument_list; 86, identifier:string; 87, identifier:index; 88, string; 89, identifier:dependency; 90, slice; 91, identifier:buildable_dependencies; 92, identifier:append; 93, identifier:dependency; 94, string_content:); 95, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 7, 16; 8, 17; 9, 18; 10, 19; 11, 20; 12, 21; 12, 22; 12, 23; 13, 24; 14, 25; 16, 26; 16, 27; 17, 28; 17, 29; 18, 30; 18, 31; 19, 32; 19, 33; 20, 34; 20, 35; 23, 36; 24, 37; 24, 38; 25, 39; 25, 40; 25, 41; 27, 42; 27, 43; 29, 44; 29, 45; 31, 46; 31, 47; 36, 48; 36, 49; 36, 50; 38, 51; 38, 52; 43, 53; 43, 54; 43, 55; 44, 56; 44, 57; 45, 58; 47, 59; 48, 60; 48, 61; 49, 62; 50, 63; 52, 64; 54, 65; 55, 66; 58, 67; 59, 68; 60, 69; 60, 70; 61, 71; 62, 72; 63, 73; 64, 74; 64, 75; 72, 76; 72, 77; 73, 78; 74, 79; 74, 80; 76, 81; 76, 82; 77, 83; 78, 84; 78, 85; 79, 86; 79, 87; 80, 88; 83, 89; 83, 90; 84, 91; 84, 92; 85, 93; 88, 94; 90, 95 | def _parse_dependencies(string):
"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""
contents = _get_contents_between(string, '(', ')')
unsorted_dependencies = contents.split(',')
_check_parameters(unsorted_dependencies, ('?',))
buildable_dependencies = []
given_dependencies = []
for dependency in unsorted_dependencies:
if dependency[0] == '?':
given_dependencies.append(dependency[1:])
else:
buildable_dependencies.append(dependency)
string = string[string.index(')') + 1:]
return buildable_dependencies, given_dependencies, string |
0, module; 1, function_definition; 2, function_name:assert_output; 3, parameters; 4, block; 5, identifier:output; 6, identifier:assert_equal; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, comment:"""
Check that two outputs have the same contents as one another, even if they
aren't sorted yet
"""; 12, assignment; 13, assignment; 14, comparison_operator:sorted_output != sorted_assert; 15, block; 16, identifier:sorted_output; 17, call; 18, identifier:sorted_assert; 19, call; 20, identifier:sorted_output; 21, identifier:sorted_assert; 22, raise_statement; 23, identifier:sorted; 24, argument_list; 25, identifier:sorted; 26, argument_list; 27, call; 28, identifier:output; 29, identifier:assert_equal; 30, identifier:ValueError; 31, argument_list; 32, call; 33, attribute; 34, argument_list; 35, identifier:ASSERT_ERROR; 36, identifier:format; 37, identifier:sorted_output; 38, identifier:sorted_assert | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 10, 14; 10, 15; 12, 16; 12, 17; 13, 18; 13, 19; 14, 20; 14, 21; 15, 22; 17, 23; 17, 24; 19, 25; 19, 26; 22, 27; 24, 28; 26, 29; 27, 30; 27, 31; 31, 32; 32, 33; 32, 34; 33, 35; 33, 36; 34, 37; 34, 38 | def assert_output(output, assert_equal):
"""
Check that two outputs have the same contents as one another, even if they
aren't sorted yet
"""
sorted_output = sorted(output)
sorted_assert = sorted(assert_equal)
if sorted_output != sorted_assert:
raise ValueError(ASSERT_ERROR.format(sorted_output, sorted_assert)) |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:self; 6, identifier:request; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, if_statement; 12, return_statement; 13, identifier:reverse; 14, False; 15, comment:"""Sort current collection."""; 16, assignment; 17, not_operator; 18, block; 19, identifier:reverse; 20, block; 21, call; 22, identifier:field; 23, call; 24, identifier:field; 25, return_statement; 26, expression_statement; 27, attribute; 28, argument_list; 29, attribute; 30, argument_list; 31, attribute; 32, assignment; 33, attribute; 34, identifier:order_by; 35, identifier:field; 36, attribute; 37, identifier:get; 38, attribute; 39, identifier:self; 40, identifier:collection; 41, identifier:field; 42, call; 43, identifier:self; 44, identifier:collection; 45, attribute; 46, identifier:fields; 47, identifier:self; 48, identifier:columns_sort; 49, attribute; 50, argument_list; 51, attribute; 52, identifier:_meta; 53, identifier:field; 54, identifier:desc; 55, identifier:self; 56, identifier:model | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 9, 16; 10, 17; 10, 18; 11, 19; 11, 20; 12, 21; 16, 22; 16, 23; 17, 24; 18, 25; 20, 26; 21, 27; 21, 28; 23, 29; 23, 30; 25, 31; 26, 32; 27, 33; 27, 34; 28, 35; 29, 36; 29, 37; 30, 38; 31, 39; 31, 40; 32, 41; 32, 42; 33, 43; 33, 44; 36, 45; 36, 46; 38, 47; 38, 48; 42, 49; 42, 50; 45, 51; 45, 52; 49, 53; 49, 54; 51, 55; 51, 56 | def sort(self, request, reverse=False):
"""Sort current collection."""
field = self.model._meta.fields.get(self.columns_sort)
if not field:
return self.collection
if reverse:
field = field.desc()
return self.collection.order_by(field) |
0, module; 1, function_definition; 2, function_name:find_files; 3, parameters; 4, block; 5, default_parameter; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, identifier:path; 16, string; 17, identifier:ext; 18, string; 19, identifier:level; 20, None; 21, identifier:typ; 22, identifier:list; 23, identifier:dirs; 24, False; 25, identifier:files; 26, True; 27, identifier:verbosity; 28, integer:0; 29, comment:""" Recursively find all files in the indicated directory
Filter by the indicated file name extension (ext)
Args:
path (str): Root/base path to search.
ext (str): File name extension. Only file paths that ".endswith()" this string will be returned
level (int, optional): Depth of file tree to halt recursion at.
None = full recursion to as deep as it goes
0 = nonrecursive, just provide a list of files at the root level of the tree
1 = one level of depth deeper in the tree
typ (type): output type (default: list). if a mapping type is provided the keys will be the full paths (unique)
dirs (bool): Whether to yield dir paths along with file paths (default: False)
files (bool): Whether to yield file paths (default: True)
`dirs=True`, `files=False` is equivalent to `ls -d`
Returns:
list of dicts: dict keys are { 'path', 'name', 'bytes', 'created', 'modified', 'accessed', 'permissions' }
path (str): Full, absolute paths to file beneath the indicated directory and ending with `ext`
name (str): File name only (everythin after the last slash in the path)
size (int): File size in bytes
created (datetime): File creation timestamp from file system
modified (datetime): File modification timestamp from file system
accessed (datetime): File access timestamp from file system
permissions (int): File permissions bytes as a chown-style integer with a maximum of 4 digits
type (str): One of 'file', 'dir', 'symlink->file', 'symlink->dir', 'symlink->broken'
e.g.: 777 or 1755
Examples:
>>> 'util.py' in [d['name'] for d in find_files(os.path.dirname(__file__), ext='.py', level=0)]
True
>>> (d for d in find_files(os.path.dirname(__file__), ext='.py') if d['name'] == 'util.py').next()['size'] > 1000
True
There should be an __init__ file in the same directory as this script.
And it should be at the top of the list.
>>> sorted(d['name'] for d in find_files(os.path.dirname(__file__), ext='.py', level=0))[0]
'__init__.py'
>>> all(d['type'] in ('file','dir','symlink->file','symlink->dir','mount-point->file','mount-point->dir','block-device',
'symlink->broken','pipe','special','socket','unknown') for d in find_files(level=1, files=True, dirs=True))
True
>>> os.path.join(os.path.dirname(__file__), '__init__.py') in find_files(
... os.path.dirname(__file__), ext='.py', level=0, typ=dict)
True
"""; 30, assignment; 31, call; 32, block; 33, elif_clause; 34, else_clause; 35, identifier:gen; 36, call; 37, identifier:isinstance; 38, argument_list; 39, return_statement; 40, comparison_operator:typ is not None; 41, block; 42, block; 43, identifier:generate_files; 44, argument_list; 45, call; 46, attribute; 47, call; 48, identifier:typ; 49, None; 50, return_statement; 51, return_statement; 52, identifier:path; 53, keyword_argument; 54, keyword_argument; 55, keyword_argument; 56, keyword_argument; 57, keyword_argument; 58, identifier:typ; 59, argument_list; 60, identifier:collections; 61, identifier:Mapping; 62, identifier:typ; 63, generator_expression; 64, call; 65, identifier:gen; 66, identifier:ext; 67, identifier:ext; 68, identifier:level; 69, identifier:level; 70, identifier:dirs; 71, identifier:dirs; 72, identifier:files; 73, identifier:files; 74, identifier:verbosity; 75, identifier:verbosity; 76, tuple; 77, for_in_clause; 78, identifier:typ; 79, argument_list; 80, subscript; 81, identifier:ff; 82, identifier:ff; 83, identifier:gen; 84, identifier:gen; 85, identifier:ff; 86, string; 87, string_content:path | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 5, 15; 5, 16; 6, 17; 6, 18; 7, 19; 7, 20; 8, 21; 8, 22; 9, 23; 9, 24; 10, 25; 10, 26; 11, 27; 11, 28; 12, 29; 13, 30; 14, 31; 14, 32; 14, 33; 14, 34; 30, 35; 30, 36; 31, 37; 31, 38; 32, 39; 33, 40; 33, 41; 34, 42; 36, 43; 36, 44; 38, 45; 38, 46; 39, 47; 40, 48; 40, 49; 41, 50; 42, 51; 44, 52; 44, 53; 44, 54; 44, 55; 44, 56; 44, 57; 45, 58; 45, 59; 46, 60; 46, 61; 47, 62; 47, 63; 50, 64; 51, 65; 53, 66; 53, 67; 54, 68; 54, 69; 55, 70; 55, 71; 56, 72; 56, 73; 57, 74; 57, 75; 63, 76; 63, 77; 64, 78; 64, 79; 76, 80; 76, 81; 77, 82; 77, 83; 79, 84; 80, 85; 80, 86; 86, 87 | def find_files(path='', ext='', level=None, typ=list, dirs=False, files=True, verbosity=0):
""" Recursively find all files in the indicated directory
Filter by the indicated file name extension (ext)
Args:
path (str): Root/base path to search.
ext (str): File name extension. Only file paths that ".endswith()" this string will be returned
level (int, optional): Depth of file tree to halt recursion at.
None = full recursion to as deep as it goes
0 = nonrecursive, just provide a list of files at the root level of the tree
1 = one level of depth deeper in the tree
typ (type): output type (default: list). if a mapping type is provided the keys will be the full paths (unique)
dirs (bool): Whether to yield dir paths along with file paths (default: False)
files (bool): Whether to yield file paths (default: True)
`dirs=True`, `files=False` is equivalent to `ls -d`
Returns:
list of dicts: dict keys are { 'path', 'name', 'bytes', 'created', 'modified', 'accessed', 'permissions' }
path (str): Full, absolute paths to file beneath the indicated directory and ending with `ext`
name (str): File name only (everythin after the last slash in the path)
size (int): File size in bytes
created (datetime): File creation timestamp from file system
modified (datetime): File modification timestamp from file system
accessed (datetime): File access timestamp from file system
permissions (int): File permissions bytes as a chown-style integer with a maximum of 4 digits
type (str): One of 'file', 'dir', 'symlink->file', 'symlink->dir', 'symlink->broken'
e.g.: 777 or 1755
Examples:
>>> 'util.py' in [d['name'] for d in find_files(os.path.dirname(__file__), ext='.py', level=0)]
True
>>> (d for d in find_files(os.path.dirname(__file__), ext='.py') if d['name'] == 'util.py').next()['size'] > 1000
True
There should be an __init__ file in the same directory as this script.
And it should be at the top of the list.
>>> sorted(d['name'] for d in find_files(os.path.dirname(__file__), ext='.py', level=0))[0]
'__init__.py'
>>> all(d['type'] in ('file','dir','symlink->file','symlink->dir','mount-point->file','mount-point->dir','block-device',
'symlink->broken','pipe','special','socket','unknown') for d in find_files(level=1, files=True, dirs=True))
True
>>> os.path.join(os.path.dirname(__file__), '__init__.py') in find_files(
... os.path.dirname(__file__), ext='.py', level=0, typ=dict)
True
"""
gen = generate_files(path, ext=ext, level=level, dirs=dirs, files=files, verbosity=verbosity)
if isinstance(typ(), collections.Mapping):
return typ((ff['path'], ff) for ff in gen)
elif typ is not None:
return typ(gen)
else:
return gen |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:self; 6, identifier:request; 7, default_parameter; 8, expression_statement; 9, return_statement; 10, identifier:reverse; 11, False; 12, comment:"""Sort collection."""; 13, call; 14, identifier:sorted; 15, argument_list; 16, attribute; 17, keyword_argument; 18, keyword_argument; 19, identifier:self; 20, identifier:collection; 21, identifier:key; 22, lambda; 23, identifier:reverse; 24, identifier:reverse; 25, lambda_parameters; 26, call; 27, identifier:o; 28, identifier:getattr; 29, argument_list; 30, identifier:o; 31, attribute; 32, integer:0; 33, identifier:self; 34, identifier:columns_sort | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 7, 10; 7, 11; 8, 12; 9, 13; 13, 14; 13, 15; 15, 16; 15, 17; 15, 18; 16, 19; 16, 20; 17, 21; 17, 22; 18, 23; 18, 24; 22, 25; 22, 26; 25, 27; 26, 28; 26, 29; 29, 30; 29, 31; 29, 32; 31, 33; 31, 34 | async def sort(self, request, reverse=False):
"""Sort collection."""
return sorted(
self.collection, key=lambda o: getattr(o, self.columns_sort, 0), reverse=reverse) |
0, module; 1, function_definition; 2, function_name:map_aliases_to_device_objects; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""
A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias.
"""; 11, assignment; 12, identifier:dev_o; 13, identifier:all_devices; 14, block; 15, identifier:all_devices; 16, identifier:all_devices; 17, call; 18, expression_statement; 19, attribute; 20, argument_list; 21, assignment; 22, identifier:self; 23, identifier:get_all_devices_in_portal; 24, subscript; 25, subscript; 26, identifier:dev_o; 27, string; 28, subscript; 29, subscript; 30, string_content:portals_aliases; 31, subscript; 32, string; 33, identifier:dev_o; 34, string; 35, subscript; 36, string; 37, string_content:aliases; 38, string_content:rid; 39, subscript; 40, integer:1; 41, string_content:info; 42, call; 43, integer:2; 44, attribute; 45, argument_list; 46, identifier:self; 47, identifier:get_portal_by_name; 48, call; 49, attribute; 50, argument_list; 51, identifier:self; 52, identifier:portal_name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 14, 18; 17, 19; 17, 20; 18, 21; 19, 22; 19, 23; 21, 24; 21, 25; 24, 26; 24, 27; 25, 28; 25, 29; 27, 30; 28, 31; 28, 32; 29, 33; 29, 34; 31, 35; 31, 36; 32, 37; 34, 38; 35, 39; 35, 40; 36, 41; 39, 42; 39, 43; 42, 44; 42, 45; 44, 46; 44, 47; 45, 48; 48, 49; 48, 50; 49, 51; 49, 52 | def map_aliases_to_device_objects(self):
"""
A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias.
"""
all_devices = self.get_all_devices_in_portal()
for dev_o in all_devices:
dev_o['portals_aliases'] = self.get_portal_by_name(
self.portal_name()
)[2][1]['info']['aliases'][ dev_o['rid'] ]
return all_devices |
0, module; 1, function_definition; 2, function_name:print_sorted_device_list; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, expression_statement; 13, identifier:device_list; 14, None; 15, identifier:sort_key; 16, string; 17, comment:"""
Takes in a sort key and prints the device list according to that sort.
Default sorts on serial number.
Current supported sort options are:
- name
- sn
- portals_aliases
Can take optional device object list.
"""; 18, assignment; 19, assignment; 20, comparison_operator:sort_key == 'sn'; 21, block; 22, elif_clause; 23, elif_clause; 24, else_clause; 25, call; 26, string_content:sn; 27, identifier:dev_list; 28, conditional_expression:device_list if device_list is not None else self.get_all_devices_in_portal(); 29, identifier:sorted_dev_list; 30, list; 31, identifier:sort_key; 32, string; 33, expression_statement; 34, expression_statement; 35, for_statement; 36, comparison_operator:sort_key == 'name'; 37, block; 38, comparison_operator:sort_key == 'portals_aliases'; 39, block; 40, block; 41, attribute; 42, argument_list; 43, identifier:device_list; 44, comparison_operator:device_list is not None; 45, call; 46, string_content:sn; 47, assignment; 48, assignment; 49, identifier:key; 50, identifier:sort_keys; 51, block; 52, identifier:sort_key; 53, string; 54, expression_statement; 55, expression_statement; 56, for_statement; 57, identifier:sort_key; 58, string; 59, expression_statement; 60, expression_statement; 61, for_statement; 62, expression_statement; 63, expression_statement; 64, identifier:self; 65, identifier:print_device_list; 66, keyword_argument; 67, identifier:device_list; 68, None; 69, attribute; 70, argument_list; 71, identifier:sort_keys; 72, list_comprehension; 73, identifier:sort_keys; 74, call; 75, expression_statement; 76, string_content:name; 77, assignment; 78, assignment; 79, identifier:key; 80, identifier:sort_keys; 81, block; 82, string_content:portals_aliases; 83, assignment; 84, assignment; 85, identifier:key; 86, identifier:sort_keys; 87, block; 88, call; 89, assignment; 90, identifier:device_list; 91, identifier:sorted_dev_list; 92, identifier:self; 93, identifier:get_all_devices_in_portal; 94, subscript; 95, for_in_clause; 96, if_clause; 97, identifier:sorted; 98, argument_list; 99, call; 100, identifier:sort_keys; 101, list_comprehension; 102, identifier:sort_keys; 103, call; 104, expression_statement; 105, identifier:sort_keys; 106, list_comprehension; 107, identifier:sort_keys; 108, call; 109, expression_statement; 110, identifier:print; 111, argument_list; 112, identifier:sort_keys; 113, None; 114, identifier:k; 115, identifier:sort_key; 116, identifier:k; 117, identifier:dev_list; 118, comparison_operator:k[sort_key] is not None; 119, identifier:sort_keys; 120, attribute; 121, argument_list; 122, subscript; 123, line_continuation:\; 124, for_in_clause; 125, if_clause; 126, identifier:sorted; 127, argument_list; 128, call; 129, subscript; 130, for_in_clause; 131, if_clause; 132, identifier:sorted; 133, argument_list; 134, call; 135, call; 136, subscript; 137, None; 138, identifier:sorted_dev_list; 139, identifier:extend; 140, list_comprehension; 141, subscript; 142, identifier:sort_key; 143, identifier:k; 144, identifier:dev_list; 145, comparison_operator:k['info']['description'][sort_key] is not None; 146, identifier:sort_keys; 147, attribute; 148, argument_list; 149, identifier:k; 150, identifier:sort_key; 151, identifier:k; 152, identifier:dev_list; 153, comparison_operator:k[sort_key] is not None; 154, identifier:sort_keys; 155, attribute; 156, argument_list; 157, attribute; 158, argument_list; 159, identifier:k; 160, identifier:sort_key; 161, identifier:d; 162, for_in_clause; 163, if_clause; 164, subscript; 165, string; 166, subscript; 167, None; 168, identifier:sorted_dev_list; 169, identifier:extend; 170, list_comprehension; 171, subscript; 172, None; 173, identifier:sorted_dev_list; 174, identifier:extend; 175, list_comprehension; 176, string:"Sort key {!r} not recognized."; 177, identifier:format; 178, identifier:sort_key; 179, identifier:d; 180, identifier:dev_list; 181, comparison_operator:d['sn'] == key; 182, identifier:k; 183, string; 184, string_content:description; 185, subscript; 186, identifier:sort_key; 187, identifier:d; 188, for_in_clause; 189, line_continuation:\; 190, if_clause; 191, identifier:k; 192, identifier:sort_key; 193, identifier:d; 194, for_in_clause; 195, if_clause; 196, subscript; 197, identifier:key; 198, string_content:info; 199, subscript; 200, string; 201, identifier:d; 202, identifier:dev_list; 203, comparison_operator:d['info']['description'][sort_key] == key; 204, identifier:d; 205, identifier:dev_list; 206, comparison_operator:d[sort_key] == key; 207, identifier:d; 208, string; 209, identifier:k; 210, string; 211, string_content:description; 212, subscript; 213, identifier:key; 214, subscript; 215, identifier:key; 216, string_content:sn; 217, string_content:info; 218, subscript; 219, identifier:sort_key; 220, identifier:d; 221, identifier:sort_key; 222, subscript; 223, string; 224, identifier:d; 225, string; 226, string_content:description; 227, string_content:info | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 6, 14; 7, 15; 7, 16; 8, 17; 9, 18; 10, 19; 11, 20; 11, 21; 11, 22; 11, 23; 11, 24; 12, 25; 16, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 20, 32; 21, 33; 21, 34; 21, 35; 22, 36; 22, 37; 23, 38; 23, 39; 24, 40; 25, 41; 25, 42; 28, 43; 28, 44; 28, 45; 32, 46; 33, 47; 34, 48; 35, 49; 35, 50; 35, 51; 36, 52; 36, 53; 37, 54; 37, 55; 37, 56; 38, 57; 38, 58; 39, 59; 39, 60; 39, 61; 40, 62; 40, 63; 41, 64; 41, 65; 42, 66; 44, 67; 44, 68; 45, 69; 45, 70; 47, 71; 47, 72; 48, 73; 48, 74; 51, 75; 53, 76; 54, 77; 55, 78; 56, 79; 56, 80; 56, 81; 58, 82; 59, 83; 60, 84; 61, 85; 61, 86; 61, 87; 62, 88; 63, 89; 66, 90; 66, 91; 69, 92; 69, 93; 72, 94; 72, 95; 72, 96; 74, 97; 74, 98; 75, 99; 77, 100; 77, 101; 78, 102; 78, 103; 81, 104; 83, 105; 83, 106; 84, 107; 84, 108; 87, 109; 88, 110; 88, 111; 89, 112; 89, 113; 94, 114; 94, 115; 95, 116; 95, 117; 96, 118; 98, 119; 99, 120; 99, 121; 101, 122; 101, 123; 101, 124; 101, 125; 103, 126; 103, 127; 104, 128; 106, 129; 106, 130; 106, 131; 108, 132; 108, 133; 109, 134; 111, 135; 118, 136; 118, 137; 120, 138; 120, 139; 121, 140; 122, 141; 122, 142; 124, 143; 124, 144; 125, 145; 127, 146; 128, 147; 128, 148; 129, 149; 129, 150; 130, 151; 130, 152; 131, 153; 133, 154; 134, 155; 134, 156; 135, 157; 135, 158; 136, 159; 136, 160; 140, 161; 140, 162; 140, 163; 141, 164; 141, 165; 145, 166; 145, 167; 147, 168; 147, 169; 148, 170; 153, 171; 153, 172; 155, 173; 155, 174; 156, 175; 157, 176; 157, 177; 158, 178; 162, 179; 162, 180; 163, 181; 164, 182; 164, 183; 165, 184; 166, 185; 166, 186; 170, 187; 170, 188; 170, 189; 170, 190; 171, 191; 171, 192; 175, 193; 175, 194; 175, 195; 181, 196; 181, 197; 183, 198; 185, 199; 185, 200; 188, 201; 188, 202; 190, 203; 194, 204; 194, 205; 195, 206; 196, 207; 196, 208; 199, 209; 199, 210; 200, 211; 203, 212; 203, 213; 206, 214; 206, 215; 208, 216; 210, 217; 212, 218; 212, 219; 214, 220; 214, 221; 218, 222; 218, 223; 222, 224; 222, 225; 223, 226; 225, 227 | def print_sorted_device_list(self, device_list=None, sort_key='sn'):
"""
Takes in a sort key and prints the device list according to that sort.
Default sorts on serial number.
Current supported sort options are:
- name
- sn
- portals_aliases
Can take optional device object list.
"""
dev_list = device_list if device_list is not None else self.get_all_devices_in_portal()
sorted_dev_list = []
if sort_key == 'sn':
sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ]
sort_keys = sorted(sort_keys)
for key in sort_keys:
sorted_dev_list.extend([ d for d in dev_list if d['sn'] == key ])
elif sort_key == 'name':
sort_keys = [ k['info']['description'][sort_key]\
for k in dev_list if k['info']['description'][sort_key] is not None ]
sort_keys = sorted(sort_keys)
for key in sort_keys:
sorted_dev_list.extend( [ d for d in dev_list\
if d['info']['description'][sort_key] == key
]
)
elif sort_key == 'portals_aliases':
sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ]
sort_keys = sorted(sort_keys)
for key in sort_keys:
sorted_dev_list.extend([ d for d in dev_list if d[sort_key] == key ])
else:
print("Sort key {!r} not recognized.".format(sort_key))
sort_keys = None
self.print_device_list(device_list=sorted_dev_list) |
0, module; 1, function_definition; 2, function_name:compile_vocab; 3, parameters; 4, block; 5, identifier:docs; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, try_statement; 13, for_statement; 14, return_statement; 15, identifier:limit; 16, float:1e6; 17, identifier:verbose; 18, integer:0; 19, identifier:tokenizer; 20, call; 21, comment:"""Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
<gensim.corpora.dictionary.Dictionary ...>
>>> print(d)
Dictionary(4 unique tokens: [u'AAA', u'BBB', u'CCC', u'label'])
>>> sorted(d.token2id.values())
[0, 1, 2, 3]
>>> sorted(d.token2id.keys())
[u'AAA', u'BBB', u'CCC', u'label']
"""; 22, assignment; 23, assignment; 24, block; 25, except_clause; 26, pattern_list; 27, call; 28, comment:# if isinstance(doc, (tuple, list)) and len(doc) == 2 and isinstance(doc[1], int):; 29, comment:# doc, score = docs; 30, block; 31, identifier:d; 32, identifier:Tokenizer; 33, argument_list; 34, identifier:tokenizer; 35, call; 36, identifier:d; 37, call; 38, expression_statement; 39, expression_statement; 40, tuple; 41, block; 42, identifier:i; 43, identifier:doc; 44, identifier:enumerate; 45, argument_list; 46, try_statement; 47, if_statement; 48, expression_statement; 49, if_statement; 50, keyword_argument; 51, keyword_argument; 52, keyword_argument; 53, identifier:make_tokenizer; 54, argument_list; 55, identifier:Dictionary; 56, argument_list; 57, assignment; 58, assignment; 59, identifier:AttributeError; 60, identifier:TypeError; 61, pass_statement; 62, identifier:docs; 63, comment:# in case docs is a values() queryset (dicts of records in a DB table); 64, block; 65, except_clause; 66, comparison_operator:i >= limit; 67, block; 68, call; 69, boolean_operator; 70, block; 71, identifier:stem; 72, None; 73, identifier:lower; 74, None; 75, identifier:strip; 76, None; 77, identifier:tokenizer; 78, identifier:limit; 79, call; 80, identifier:docs; 81, call; 82, expression_statement; 83, identifier:AttributeError; 84, comment:# doc already is a values_list; 85, block; 86, identifier:i; 87, identifier:limit; 88, break_statement; 89, attribute; 90, argument_list; 91, identifier:verbose; 92, not_operator; 93, expression_statement; 94, identifier:min; 95, argument_list; 96, attribute; 97, argument_list; 98, assignment; 99, if_statement; 100, identifier:d; 101, identifier:add_documents; 102, list; 103, binary_operator:i % 100; 104, call; 105, identifier:limit; 106, call; 107, identifier:docs; 108, identifier:iterator; 109, identifier:doc; 110, call; 111, not_operator; 112, block; 113, else_clause; 114, call; 115, identifier:i; 116, integer:100; 117, attribute; 118, argument_list; 119, attribute; 120, argument_list; 121, attribute; 122, argument_list; 123, call; 124, expression_statement; 125, block; 126, identifier:list; 127, argument_list; 128, identifier:log; 129, identifier:info; 130, call; 131, identifier:docs; 132, identifier:count; 133, identifier:doc; 134, identifier:values; 135, identifier:isinstance; 136, argument_list; 137, assignment; 138, expression_statement; 139, call; 140, attribute; 141, argument_list; 142, identifier:doc; 143, identifier:str; 144, identifier:doc; 145, call; 146, assignment; 147, identifier:tokenizer; 148, argument_list; 149, string; 150, identifier:format; 151, identifier:i; 152, subscript; 153, attribute; 154, argument_list; 155, identifier:doc; 156, call; 157, identifier:doc; 158, string_content:{}: {}; 159, call; 160, slice; 161, string; 162, identifier:join; 163, list_comprehension; 164, identifier:str; 165, argument_list; 166, identifier:repr; 167, argument_list; 168, integer:120; 169, string_content:; 170, call; 171, for_in_clause; 172, identifier:doc; 173, identifier:d; 174, identifier:str; 175, argument_list; 176, identifier:v; 177, identifier:doc; 178, identifier:v | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 11, 23; 12, 24; 12, 25; 13, 26; 13, 27; 13, 28; 13, 29; 13, 30; 14, 31; 20, 32; 20, 33; 22, 34; 22, 35; 23, 36; 23, 37; 24, 38; 24, 39; 25, 40; 25, 41; 26, 42; 26, 43; 27, 44; 27, 45; 30, 46; 30, 47; 30, 48; 30, 49; 33, 50; 33, 51; 33, 52; 35, 53; 35, 54; 37, 55; 37, 56; 38, 57; 39, 58; 40, 59; 40, 60; 41, 61; 45, 62; 46, 63; 46, 64; 46, 65; 47, 66; 47, 67; 48, 68; 49, 69; 49, 70; 50, 71; 50, 72; 51, 73; 51, 74; 52, 75; 52, 76; 54, 77; 57, 78; 57, 79; 58, 80; 58, 81; 64, 82; 65, 83; 65, 84; 65, 85; 66, 86; 66, 87; 67, 88; 68, 89; 68, 90; 69, 91; 69, 92; 70, 93; 79, 94; 79, 95; 81, 96; 81, 97; 82, 98; 85, 99; 89, 100; 89, 101; 90, 102; 92, 103; 93, 104; 95, 105; 95, 106; 96, 107; 96, 108; 98, 109; 98, 110; 99, 111; 99, 112; 99, 113; 102, 114; 103, 115; 103, 116; 104, 117; 104, 118; 106, 119; 106, 120; 110, 121; 110, 122; 111, 123; 112, 124; 113, 125; 114, 126; 114, 127; 117, 128; 117, 129; 118, 130; 119, 131; 119, 132; 121, 133; 121, 134; 123, 135; 123, 136; 124, 137; 125, 138; 127, 139; 130, 140; 130, 141; 136, 142; 136, 143; 137, 144; 137, 145; 138, 146; 139, 147; 139, 148; 140, 149; 140, 150; 141, 151; 141, 152; 145, 153; 145, 154; 146, 155; 146, 156; 148, 157; 149, 158; 152, 159; 152, 160; 153, 161; 153, 162; 154, 163; 156, 164; 156, 165; 159, 166; 159, 167; 160, 168; 161, 169; 163, 170; 163, 171; 165, 172; 167, 173; 170, 174; 170, 175; 171, 176; 171, 177; 175, 178 | def compile_vocab(docs, limit=1e6, verbose=0, tokenizer=Tokenizer(stem=None, lower=None, strip=None)):
"""Get the set of words used anywhere in a sequence of documents and assign an integer id
This vectorizer is much faster than the scikit-learn version (and only requires low/constant RAM ?).
>>> gen = ('label: ' + chr(ord('A') + i % 3)*3 for i in range(11))
>>> d = compile_vocab(gen, verbose=0)
>>> d
<gensim.corpora.dictionary.Dictionary ...>
>>> print(d)
Dictionary(4 unique tokens: [u'AAA', u'BBB', u'CCC', u'label'])
>>> sorted(d.token2id.values())
[0, 1, 2, 3]
>>> sorted(d.token2id.keys())
[u'AAA', u'BBB', u'CCC', u'label']
"""
tokenizer = make_tokenizer(tokenizer)
d = Dictionary()
try:
limit = min(limit, docs.count())
docs = docs.iterator()
except (AttributeError, TypeError):
pass
for i, doc in enumerate(docs):
# if isinstance(doc, (tuple, list)) and len(doc) == 2 and isinstance(doc[1], int):
# doc, score = docs
try:
# in case docs is a values() queryset (dicts of records in a DB table)
doc = doc.values()
except AttributeError: # doc already is a values_list
if not isinstance(doc, str):
doc = ' '.join([str(v) for v in doc])
else:
doc = str(doc)
if i >= limit:
break
d.add_documents([list(tokenizer(doc))])
if verbose and not i % 100:
log.info('{}: {}'.format(i, repr(d)[:120]))
return d |
0, module; 1, function_definition; 2, function_name:find_point_in_section_list; 3, parameters; 4, block; 5, identifier:point; 6, identifier:section_list; 7, expression_statement; 8, if_statement; 9, if_statement; 10, try_statement; 11, comment:"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5,
32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for
them the function returns 5, and 30, 30.7 and 31 all match [30-31].
Parameters
---------
point : float
The point for which to match a section.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
float
The start of the section the given point belongs to. None if no match
was found.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_point_in_section_list(4, seclist)
>>> find_point_in_section_list(5, seclist)
5
>>> find_point_in_section_list(27, seclist)
8
>>> find_point_in_section_list(31, seclist)
30
"""; 12, boolean_operator; 13, block; 14, comparison_operator:point in section_list; 15, block; 16, block; 17, except_clause; 18, comparison_operator:point < section_list[0]; 19, comparison_operator:point > section_list[-1]; 20, return_statement; 21, identifier:point; 22, identifier:section_list; 23, if_statement; 24, expression_statement; 25, if_statement; 26, return_statement; 27, expression_statement; 28, return_statement; 29, identifier:IndexError; 30, block; 31, identifier:point; 32, subscript; 33, identifier:point; 34, subscript; 35, None; 36, comparison_operator:point == section_list[-1]; 37, block; 38, assignment; 39, comparison_operator:ind == 0; 40, block; 41, subscript; 42, assignment; 43, subscript; 44, return_statement; 45, identifier:section_list; 46, integer:0; 47, identifier:section_list; 48, unary_operator; 49, identifier:point; 50, subscript; 51, return_statement; 52, identifier:ind; 53, binary_operator:section_list.bisect(point)-1; 54, identifier:ind; 55, integer:0; 56, return_statement; 57, identifier:section_list; 58, identifier:ind; 59, identifier:ind; 60, call; 61, identifier:section_list; 62, binary_operator:ind-1; 63, None; 64, integer:1; 65, identifier:section_list; 66, unary_operator; 67, subscript; 68, call; 69, integer:1; 70, subscript; 71, attribute; 72, argument_list; 73, identifier:ind; 74, integer:1; 75, integer:1; 76, identifier:section_list; 77, unary_operator; 78, attribute; 79, argument_list; 80, identifier:section_list; 81, integer:0; 82, identifier:section_list; 83, identifier:bisect; 84, identifier:point; 85, integer:2; 86, identifier:section_list; 87, identifier:bisect; 88, identifier:point | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 8, 13; 9, 14; 9, 15; 10, 16; 10, 17; 12, 18; 12, 19; 13, 20; 14, 21; 14, 22; 15, 23; 15, 24; 15, 25; 15, 26; 16, 27; 16, 28; 17, 29; 17, 30; 18, 31; 18, 32; 19, 33; 19, 34; 20, 35; 23, 36; 23, 37; 24, 38; 25, 39; 25, 40; 26, 41; 27, 42; 28, 43; 30, 44; 32, 45; 32, 46; 34, 47; 34, 48; 36, 49; 36, 50; 37, 51; 38, 52; 38, 53; 39, 54; 39, 55; 40, 56; 41, 57; 41, 58; 42, 59; 42, 60; 43, 61; 43, 62; 44, 63; 48, 64; 50, 65; 50, 66; 51, 67; 53, 68; 53, 69; 56, 70; 60, 71; 60, 72; 62, 73; 62, 74; 66, 75; 67, 76; 67, 77; 68, 78; 68, 79; 70, 80; 70, 81; 71, 82; 71, 83; 72, 84; 77, 85; 78, 86; 78, 87; 79, 88 | def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5,
32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for
them the function returns 5, and 30, 30.7 and 31 all match [30-31].
Parameters
---------
point : float
The point for which to match a section.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
float
The start of the section the given point belongs to. None if no match
was found.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_point_in_section_list(4, seclist)
>>> find_point_in_section_list(5, seclist)
5
>>> find_point_in_section_list(27, seclist)
8
>>> find_point_in_section_list(31, seclist)
30
"""
if point < section_list[0] or point > section_list[-1]:
return None
if point in section_list:
if point == section_list[-1]:
return section_list[-2]
ind = section_list.bisect(point)-1
if ind == 0:
return section_list[0]
return section_list[ind]
try:
ind = section_list.bisect(point)
return section_list[ind-1]
except IndexError:
return None |
0, module; 1, function_definition; 2, function_name:find_range_ix_in_section_list; 3, parameters; 4, block; 5, identifier:start; 6, identifier:end; 7, identifier:section_list; 8, expression_statement; 9, if_statement; 10, if_statement; 11, if_statement; 12, return_statement; 13, comment:"""Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The index range of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_ix_in_section_list(3, 4, seclist)
[0, 0]
>>> find_range_ix_in_section_list(6, 7, seclist)
[0, 1]
>>> find_range_ix_in_section_list(7, 9, seclist)
[0, 2]
>>> find_range_ix_in_section_list(7, 30, seclist)
[0, 3]
>>> find_range_ix_in_section_list(7, 321, seclist)
[0, 3]
>>> find_range_ix_in_section_list(4, 321, seclist)
[0, 3]
"""; 14, boolean_operator; 15, block; 16, comparison_operator:start < section_list[0]; 17, block; 18, else_clause; 19, comparison_operator:end > section_list[-1]; 20, block; 21, else_clause; 22, list; 23, comparison_operator:start > section_list[-1]; 24, comparison_operator:end < section_list[0]; 25, return_statement; 26, identifier:start; 27, subscript; 28, expression_statement; 29, block; 30, identifier:end; 31, subscript; 32, expression_statement; 33, block; 34, call; 35, binary_operator:section_list.index(end_section)+1; 36, identifier:start; 37, subscript; 38, identifier:end; 39, subscript; 40, list; 41, identifier:section_list; 42, integer:0; 43, assignment; 44, expression_statement; 45, identifier:section_list; 46, unary_operator; 47, assignment; 48, expression_statement; 49, attribute; 50, argument_list; 51, call; 52, integer:1; 53, identifier:section_list; 54, unary_operator; 55, identifier:section_list; 56, integer:0; 57, integer:0; 58, integer:0; 59, identifier:start_section; 60, subscript; 61, assignment; 62, integer:1; 63, identifier:end_section; 64, subscript; 65, assignment; 66, identifier:section_list; 67, identifier:index; 68, identifier:start_section; 69, attribute; 70, argument_list; 71, integer:1; 72, identifier:section_list; 73, integer:0; 74, identifier:start_section; 75, call; 76, identifier:section_list; 77, unary_operator; 78, identifier:end_section; 79, call; 80, identifier:section_list; 81, identifier:index; 82, identifier:end_section; 83, identifier:find_point_in_section_list; 84, argument_list; 85, integer:2; 86, identifier:find_point_in_section_list; 87, argument_list; 88, identifier:start; 89, identifier:section_list; 90, identifier:end; 91, identifier:section_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 8, 13; 9, 14; 9, 15; 10, 16; 10, 17; 10, 18; 11, 19; 11, 20; 11, 21; 12, 22; 14, 23; 14, 24; 15, 25; 16, 26; 16, 27; 17, 28; 18, 29; 19, 30; 19, 31; 20, 32; 21, 33; 22, 34; 22, 35; 23, 36; 23, 37; 24, 38; 24, 39; 25, 40; 27, 41; 27, 42; 28, 43; 29, 44; 31, 45; 31, 46; 32, 47; 33, 48; 34, 49; 34, 50; 35, 51; 35, 52; 37, 53; 37, 54; 39, 55; 39, 56; 40, 57; 40, 58; 43, 59; 43, 60; 44, 61; 46, 62; 47, 63; 47, 64; 48, 65; 49, 66; 49, 67; 50, 68; 51, 69; 51, 70; 54, 71; 60, 72; 60, 73; 61, 74; 61, 75; 64, 76; 64, 77; 65, 78; 65, 79; 69, 80; 69, 81; 70, 82; 75, 83; 75, 84; 77, 85; 79, 86; 79, 87; 84, 88; 84, 89; 87, 90; 87, 91 | def find_range_ix_in_section_list(start, end, section_list):
"""Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The index range of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_ix_in_section_list(3, 4, seclist)
[0, 0]
>>> find_range_ix_in_section_list(6, 7, seclist)
[0, 1]
>>> find_range_ix_in_section_list(7, 9, seclist)
[0, 2]
>>> find_range_ix_in_section_list(7, 30, seclist)
[0, 3]
>>> find_range_ix_in_section_list(7, 321, seclist)
[0, 3]
>>> find_range_ix_in_section_list(4, 321, seclist)
[0, 3]
"""
if start > section_list[-1] or end < section_list[0]:
return [0, 0]
if start < section_list[0]:
start_section = section_list[0]
else:
start_section = find_point_in_section_list(start, section_list)
if end > section_list[-1]:
end_section = section_list[-2]
else:
end_section = find_point_in_section_list(end, section_list)
return [
section_list.index(start_section), section_list.index(end_section)+1] |
0, module; 1, function_definition; 2, function_name:find_range_in_section_list; 3, parameters; 4, block; 5, identifier:start; 6, identifier:end; 7, identifier:section_list; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, comment:"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The starting points of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_in_section_list(3, 4, seclist)
[]
>>> find_range_in_section_list(6, 7, seclist)
[5]
>>> find_range_in_section_list(7, 9, seclist)
[5, 8]
>>> find_range_in_section_list(7, 30, seclist)
[5, 8, 30]
>>> find_range_in_section_list(7, 321, seclist)
[5, 8, 30]
>>> find_range_in_section_list(4, 321, seclist)
[5, 8, 30]
"""; 12, assignment; 13, subscript; 14, identifier:ind; 15, call; 16, identifier:section_list; 17, slice; 18, identifier:find_range_ix_in_section_list; 19, argument_list; 20, subscript; 21, subscript; 22, identifier:start; 23, identifier:end; 24, identifier:section_list; 25, identifier:ind; 26, integer:0; 27, identifier:ind; 28, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 8, 11; 9, 12; 10, 13; 12, 14; 12, 15; 13, 16; 13, 17; 15, 18; 15, 19; 17, 20; 17, 21; 19, 22; 19, 23; 19, 24; 20, 25; 20, 26; 21, 27; 21, 28 | def find_range_in_section_list(start, end, section_list):
"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The starting points of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_in_section_list(3, 4, seclist)
[]
>>> find_range_in_section_list(6, 7, seclist)
[5]
>>> find_range_in_section_list(7, 9, seclist)
[5, 8]
>>> find_range_in_section_list(7, 30, seclist)
[5, 8, 30]
>>> find_range_in_section_list(7, 321, seclist)
[5, 8, 30]
>>> find_range_in_section_list(4, 321, seclist)
[5, 8, 30]
"""
ind = find_range_ix_in_section_list(start, end, section_list)
return section_list[ind[0]: ind[1]] |
0, module; 1, function_definition; 2, function_name:find_range_ix_in_point_list; 3, parameters; 4, block; 5, identifier:start; 6, identifier:end; 7, identifier:point_list; 8, expression_statement; 9, return_statement; 10, comment:"""Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A list of points.
Returns
-------
iterable
The index range of all points inside the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> point_list = SortedList([5, 8, 15])
>>> find_range_ix_in_point_list(3, 4, point_list)
[0, 0]
>>> find_range_ix_in_point_list(3, 7, point_list)
[0, 1]
>>> find_range_ix_in_point_list(3, 8, point_list)
[0, 2]
>>> find_range_ix_in_point_list(4, 15, point_list)
[0, 3]
>>> find_range_ix_in_point_list(4, 321, point_list)
[0, 3]
>>> find_range_ix_in_point_list(6, 321, point_list)
[1, 3]
"""; 11, list; 12, call; 13, call; 14, attribute; 15, argument_list; 16, attribute; 17, argument_list; 18, identifier:point_list; 19, identifier:bisect_left; 20, identifier:start; 21, identifier:point_list; 22, identifier:bisect_right; 23, identifier:end | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 8, 10; 9, 11; 11, 12; 11, 13; 12, 14; 12, 15; 13, 16; 13, 17; 14, 18; 14, 19; 15, 20; 16, 21; 16, 22; 17, 23 | def find_range_ix_in_point_list(start, end, point_list):
"""Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A list of points.
Returns
-------
iterable
The index range of all points inside the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> point_list = SortedList([5, 8, 15])
>>> find_range_ix_in_point_list(3, 4, point_list)
[0, 0]
>>> find_range_ix_in_point_list(3, 7, point_list)
[0, 1]
>>> find_range_ix_in_point_list(3, 8, point_list)
[0, 2]
>>> find_range_ix_in_point_list(4, 15, point_list)
[0, 3]
>>> find_range_ix_in_point_list(4, 321, point_list)
[0, 3]
>>> find_range_ix_in_point_list(6, 321, point_list)
[1, 3]
"""
return [point_list.bisect_left(start), point_list.bisect_right(end)] |
0, module; 1, function_definition; 2, function_name:parse_int_string; 3, parameters; 4, type; 5, block; 6, typed_parameter; 7, generic_type; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, for_statement; 15, return_statement; 16, identifier:int_string; 17, type; 18, identifier:List; 19, type_parameter; 20, comment:"""
Given a string like "1 23 4-8 32 1", return a unique list of those integers in the string and
the integers in the ranges in the string.
Non-numbers ignored. Not necessarily sorted
"""; 21, assignment; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, identifier:token; 27, identifier:tokens; 28, block; 29, call; 30, identifier:str; 31, type; 32, identifier:cleaned; 33, call; 34, identifier:cleaned; 35, call; 36, identifier:cleaned; 37, call; 38, identifier:tokens; 39, call; 40, identifier:indices; 41, type; 42, call; 43, if_statement; 44, identifier:list; 45, argument_list; 46, identifier:int; 47, attribute; 48, argument_list; 49, attribute; 50, argument_list; 51, attribute; 52, argument_list; 53, attribute; 54, argument_list; 55, generic_type; 56, identifier:set; 57, argument_list; 58, comparison_operator:"-" in token; 59, block; 60, else_clause; 61, identifier:indices; 62, string:" "; 63, identifier:join; 64, call; 65, identifier:cleaned; 66, identifier:replace; 67, string:" - "; 68, string:"-"; 69, identifier:cleaned; 70, identifier:replace; 71, string:","; 72, string:" "; 73, identifier:cleaned; 74, identifier:split; 75, string:" "; 76, identifier:Set; 77, type_parameter; 78, string:"-"; 79, identifier:token; 80, expression_statement; 81, if_statement; 82, expression_statement; 83, expression_statement; 84, expression_statement; 85, block; 86, attribute; 87, argument_list; 88, type; 89, assignment; 90, comparison_operator:len(endpoints) != 2; 91, block; 92, assignment; 93, assignment; 94, assignment; 95, try_statement; 96, call; 97, identifier:split; 98, identifier:int; 99, identifier:endpoints; 100, call; 101, call; 102, integer:2; 103, expression_statement; 104, continue_statement; 105, identifier:start; 106, call; 107, identifier:end; 108, binary_operator:int(endpoints[1]) + 1; 109, identifier:indices; 110, call; 111, block; 112, except_clause; 113, attribute; 114, argument_list; 115, attribute; 116, argument_list; 117, identifier:len; 118, argument_list; 119, call; 120, identifier:int; 121, argument_list; 122, call; 123, integer:1; 124, attribute; 125, argument_list; 126, expression_statement; 127, identifier:ValueError; 128, block; 129, identifier:int_string; 130, identifier:strip; 131, identifier:token; 132, identifier:split; 133, string:"-"; 134, identifier:endpoints; 135, attribute; 136, argument_list; 137, subscript; 138, identifier:int; 139, argument_list; 140, identifier:indices; 141, identifier:union; 142, identifier:indices; 143, call; 144, call; 145, expression_statement; 146, identifier:LOG; 147, identifier:info; 148, string:f"Dropping '{token}' as invalid - weird range."; 149, identifier:endpoints; 150, integer:0; 151, subscript; 152, identifier:set; 153, argument_list; 154, attribute; 155, argument_list; 156, call; 157, identifier:endpoints; 158, integer:1; 159, call; 160, identifier:indices; 161, identifier:add; 162, call; 163, attribute; 164, argument_list; 165, identifier:range; 166, argument_list; 167, identifier:int; 168, argument_list; 169, identifier:LOG; 170, identifier:info; 171, string:f"Dropping '{token}' as invalid - not an int."; 172, identifier:start; 173, identifier:end; 174, identifier:token | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 4, 7; 5, 8; 5, 9; 5, 10; 5, 11; 5, 12; 5, 13; 5, 14; 5, 15; 6, 16; 6, 17; 7, 18; 7, 19; 8, 20; 9, 21; 10, 22; 11, 23; 12, 24; 13, 25; 14, 26; 14, 27; 14, 28; 15, 29; 17, 30; 19, 31; 21, 32; 21, 33; 22, 34; 22, 35; 23, 36; 23, 37; 24, 38; 24, 39; 25, 40; 25, 41; 25, 42; 28, 43; 29, 44; 29, 45; 31, 46; 33, 47; 33, 48; 35, 49; 35, 50; 37, 51; 37, 52; 39, 53; 39, 54; 41, 55; 42, 56; 42, 57; 43, 58; 43, 59; 43, 60; 45, 61; 47, 62; 47, 63; 48, 64; 49, 65; 49, 66; 50, 67; 50, 68; 51, 69; 51, 70; 52, 71; 52, 72; 53, 73; 53, 74; 54, 75; 55, 76; 55, 77; 58, 78; 58, 79; 59, 80; 59, 81; 59, 82; 59, 83; 59, 84; 60, 85; 64, 86; 64, 87; 77, 88; 80, 89; 81, 90; 81, 91; 82, 92; 83, 93; 84, 94; 85, 95; 86, 96; 86, 97; 88, 98; 89, 99; 89, 100; 90, 101; 90, 102; 91, 103; 91, 104; 92, 105; 92, 106; 93, 107; 93, 108; 94, 109; 94, 110; 95, 111; 95, 112; 96, 113; 96, 114; 100, 115; 100, 116; 101, 117; 101, 118; 103, 119; 106, 120; 106, 121; 108, 122; 108, 123; 110, 124; 110, 125; 111, 126; 112, 127; 112, 128; 113, 129; 113, 130; 115, 131; 115, 132; 116, 133; 118, 134; 119, 135; 119, 136; 121, 137; 122, 138; 122, 139; 124, 140; 124, 141; 125, 142; 125, 143; 126, 144; 128, 145; 135, 146; 135, 147; 136, 148; 137, 149; 137, 150; 139, 151; 143, 152; 143, 153; 144, 154; 144, 155; 145, 156; 151, 157; 151, 158; 153, 159; 154, 160; 154, 161; 155, 162; 156, 163; 156, 164; 159, 165; 159, 166; 162, 167; 162, 168; 163, 169; 163, 170; 164, 171; 166, 172; 166, 173; 168, 174 | def parse_int_string(int_string: str) -> List[int]:
"""
Given a string like "1 23 4-8 32 1", return a unique list of those integers in the string and
the integers in the ranges in the string.
Non-numbers ignored. Not necessarily sorted
"""
cleaned = " ".join(int_string.strip().split())
cleaned = cleaned.replace(" - ", "-")
cleaned = cleaned.replace(",", " ")
tokens = cleaned.split(" ")
indices: Set[int] = set()
for token in tokens:
if "-" in token:
endpoints = token.split("-")
if len(endpoints) != 2:
LOG.info(f"Dropping '{token}' as invalid - weird range.")
continue
start = int(endpoints[0])
end = int(endpoints[1]) + 1
indices = indices.union(indices, set(range(start, end)))
else:
try:
indices.add(int(token))
except ValueError:
LOG.info(f"Dropping '{token}' as invalid - not an int.")
return list(indices) |
0, module; 1, function_definition; 2, function_name:persistence2stats; 3, parameters; 4, block; 5, identifier:rev_docs; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, for_statement; 18, identifier:min_persisted; 19, integer:5; 20, identifier:min_visible; 21, integer:1209600; 22, identifier:include; 23, None; 24, identifier:exclude; 25, None; 26, identifier:verbose; 27, False; 28, comment:"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
min_persisted : `int`
The minimum future revisions that a token must persist in order
to be considered "persistent".
min_visible : `int`
The minimum number of seconds that a token must be visible in order
to be considered "persistent".
include : `func`
A function that returns `True` when a token should be included in
statistical processing
exclude : `str` | `re.SRE_Pattern`
A function that returns `True` when a token should *not* be
included in statistical processing (Takes precedence over
'include')
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""; 29, assignment; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, identifier:rev_doc; 35, identifier:rev_docs; 36, block; 37, identifier:rev_docs; 38, call; 39, identifier:min_persisted; 40, call; 41, identifier:min_visible; 42, call; 43, identifier:include; 44, conditional_expression:include if include is not None else lambda t: True; 45, identifier:exclude; 46, conditional_expression:exclude if exclude is not None else lambda t: False; 47, expression_statement; 48, expression_statement; 49, expression_statement; 50, for_statement; 51, if_statement; 52, expression_statement; 53, expression_statement; 54, attribute; 55, argument_list; 56, identifier:int; 57, argument_list; 58, identifier:int; 59, argument_list; 60, identifier:include; 61, comparison_operator:include is not None; 62, lambda; 63, identifier:exclude; 64, comparison_operator:exclude is not None; 65, lambda; 66, assignment; 67, assignment; 68, assignment; 69, identifier:token_doc; 70, identifier:filtered_docs; 71, block; 72, identifier:verbose; 73, block; 74, call; 75, yield; 76, attribute; 77, identifier:normalize; 78, identifier:rev_docs; 79, identifier:min_persisted; 80, identifier:min_visible; 81, identifier:include; 82, None; 83, lambda_parameters; 84, True; 85, identifier:exclude; 86, None; 87, lambda_parameters; 88, False; 89, identifier:persistence_doc; 90, subscript; 91, identifier:stats_doc; 92, dictionary; 93, identifier:filtered_docs; 94, generator_expression; 95, if_statement; 96, expression_statement; 97, expression_statement; 98, expression_statement; 99, expression_statement; 100, comment:# Look for time threshold; 101, if_statement; 102, expression_statement; 103, expression_statement; 104, attribute; 105, argument_list; 106, identifier:rev_doc; 107, identifier:mwxml; 108, identifier:utilities; 109, identifier:t; 110, identifier:t; 111, identifier:rev_doc; 112, string; 113, pair; 114, pair; 115, pair; 116, pair; 117, pair; 118, pair; 119, pair; 120, pair; 121, identifier:t; 122, for_in_clause; 123, if_clause; 124, identifier:verbose; 125, block; 126, augmented_assignment; 127, augmented_assignment; 128, augmented_assignment; 129, augmented_assignment; 130, comparison_operator:token_doc['seconds_visible'] >= min_visible; 131, block; 132, else_clause; 133, call; 134, call; 135, subscript; 136, identifier:update; 137, identifier:stats_doc; 138, string_content:persistence; 139, string; 140, integer:0; 141, string; 142, integer:0; 143, string; 144, integer:0; 145, string; 146, integer:0; 147, string; 148, integer:0; 149, string; 150, integer:0; 151, string; 152, False; 153, string; 154, False; 155, identifier:t; 156, subscript; 157, boolean_operator; 158, expression_statement; 159, expression_statement; 160, subscript; 161, integer:1; 162, subscript; 163, call; 164, subscript; 165, line_continuation:\; 166, call; 167, subscript; 168, line_continuation:\; 169, call; 170, subscript; 171, identifier:min_visible; 172, expression_statement; 173, expression_statement; 174, comment:# Look for review threshold; 175, block; 176, attribute; 177, argument_list; 178, attribute; 179, argument_list; 180, identifier:rev_doc; 181, string; 182, string_content:tokens_added; 183, string_content:persistent_tokens; 184, string_content:non_self_persistent_tokens; 185, string_content:sum_log_persisted; 186, string_content:sum_log_non_self_persisted; 187, string_content:sum_log_seconds_visible; 188, string_content:censored; 189, string_content:non_self_censored; 190, identifier:persistence_doc; 191, string; 192, call; 193, not_operator; 194, call; 195, call; 196, identifier:stats_doc; 197, string; 198, identifier:stats_doc; 199, string; 200, identifier:log; 201, argument_list; 202, identifier:stats_doc; 203, string; 204, identifier:log; 205, argument_list; 206, identifier:stats_doc; 207, string; 208, identifier:log; 209, argument_list; 210, identifier:token_doc; 211, string; 212, augmented_assignment; 213, augmented_assignment; 214, expression_statement; 215, expression_statement; 216, comment:# Check for censoring; 217, if_statement; 218, attribute; 219, identifier:write; 220, string:"\n"; 221, attribute; 222, identifier:flush; 223, string_content:persistence; 224, string_content:tokens; 225, identifier:include; 226, argument_list; 227, call; 228, attribute; 229, argument_list; 230, attribute; 231, argument_list; 232, string_content:tokens_added; 233, string_content:sum_log_persisted; 234, binary_operator:token_doc['persisted'] + 1; 235, string_content:sum_log_non_self_persisted; 236, binary_operator:token_doc['non_self_persisted'] + 1; 237, string_content:sum_log_seconds_visible; 238, binary_operator:token_doc['seconds_visible'] + 1; 239, string_content:seconds_visible; 240, subscript; 241, integer:1; 242, subscript; 243, integer:1; 244, augmented_assignment; 245, augmented_assignment; 246, comparison_operator:persistence_doc['seconds_possible'] < min_visible; 247, block; 248, else_clause; 249, identifier:sys; 250, identifier:stderr; 251, identifier:sys; 252, identifier:stderr; 253, subscript; 254, identifier:exclude; 255, argument_list; 256, attribute; 257, identifier:write; 258, string:"."; 259, attribute; 260, identifier:flush; 261, subscript; 262, integer:1; 263, subscript; 264, integer:1; 265, subscript; 266, integer:1; 267, identifier:stats_doc; 268, string; 269, identifier:stats_doc; 270, string; 271, subscript; 272, line_continuation:\; 273, comparison_operator:token_doc['persisted'] >= min_persisted; 274, subscript; 275, line_continuation:\; 276, comparison_operator:token_doc['non_self_persisted'] >= min_persisted; 277, subscript; 278, identifier:min_visible; 279, expression_statement; 280, expression_statement; 281, block; 282, identifier:t; 283, string; 284, subscript; 285, identifier:sys; 286, identifier:stderr; 287, identifier:sys; 288, identifier:stderr; 289, identifier:token_doc; 290, string; 291, identifier:token_doc; 292, string; 293, identifier:token_doc; 294, string; 295, string_content:persistent_tokens; 296, string_content:non_self_persistent_tokens; 297, identifier:stats_doc; 298, string; 299, subscript; 300, identifier:min_persisted; 301, identifier:stats_doc; 302, string; 303, subscript; 304, identifier:min_persisted; 305, identifier:persistence_doc; 306, string; 307, assignment; 308, assignment; 309, if_statement; 310, if_statement; 311, string_content:text; 312, identifier:t; 313, string; 314, string_content:persisted; 315, string_content:non_self_persisted; 316, string_content:seconds_visible; 317, string_content:persistent_tokens; 318, identifier:token_doc; 319, string; 320, string_content:non_self_persistent_tokens; 321, identifier:token_doc; 322, string; 323, string_content:seconds_possible; 324, subscript; 325, True; 326, subscript; 327, True; 328, comparison_operator:persistence_doc['revisions_processed'] < min_persisted; 329, block; 330, comparison_operator:persistence_doc['non_self_processed'] < min_persisted; 331, block; 332, string_content:text; 333, string_content:persisted; 334, string_content:non_self_persisted; 335, identifier:stats_doc; 336, string; 337, identifier:stats_doc; 338, string; 339, subscript; 340, identifier:min_persisted; 341, expression_statement; 342, subscript; 343, identifier:min_persisted; 344, expression_statement; 345, string_content:censored; 346, string_content:non_self_censored; 347, identifier:persistence_doc; 348, string; 349, assignment; 350, identifier:persistence_doc; 351, string; 352, assignment; 353, string_content:revisions_processed; 354, subscript; 355, True; 356, string_content:non_self_processed; 357, subscript; 358, True; 359, identifier:stats_doc; 360, string; 361, identifier:stats_doc; 362, string; 363, string_content:censored; 364, string_content:non_self_censored | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 6, 18; 6, 19; 7, 20; 7, 21; 8, 22; 8, 23; 9, 24; 9, 25; 10, 26; 10, 27; 11, 28; 12, 29; 13, 30; 14, 31; 15, 32; 16, 33; 17, 34; 17, 35; 17, 36; 29, 37; 29, 38; 30, 39; 30, 40; 31, 41; 31, 42; 32, 43; 32, 44; 33, 45; 33, 46; 36, 47; 36, 48; 36, 49; 36, 50; 36, 51; 36, 52; 36, 53; 38, 54; 38, 55; 40, 56; 40, 57; 42, 58; 42, 59; 44, 60; 44, 61; 44, 62; 46, 63; 46, 64; 46, 65; 47, 66; 48, 67; 49, 68; 50, 69; 50, 70; 50, 71; 51, 72; 51, 73; 52, 74; 53, 75; 54, 76; 54, 77; 55, 78; 57, 79; 59, 80; 61, 81; 61, 82; 62, 83; 62, 84; 64, 85; 64, 86; 65, 87; 65, 88; 66, 89; 66, 90; 67, 91; 67, 92; 68, 93; 68, 94; 71, 95; 71, 96; 71, 97; 71, 98; 71, 99; 71, 100; 71, 101; 73, 102; 73, 103; 74, 104; 74, 105; 75, 106; 76, 107; 76, 108; 83, 109; 87, 110; 90, 111; 90, 112; 92, 113; 92, 114; 92, 115; 92, 116; 92, 117; 92, 118; 92, 119; 92, 120; 94, 121; 94, 122; 94, 123; 95, 124; 95, 125; 96, 126; 97, 127; 98, 128; 99, 129; 101, 130; 101, 131; 101, 132; 102, 133; 103, 134; 104, 135; 104, 136; 105, 137; 112, 138; 113, 139; 113, 140; 114, 141; 114, 142; 115, 143; 115, 144; 116, 145; 116, 146; 117, 147; 117, 148; 118, 149; 118, 150; 119, 151; 119, 152; 120, 153; 120, 154; 122, 155; 122, 156; 123, 157; 125, 158; 125, 159; 126, 160; 126, 161; 127, 162; 127, 163; 128, 164; 128, 165; 128, 166; 129, 167; 129, 168; 129, 169; 130, 170; 130, 171; 131, 172; 131, 173; 132, 174; 132, 175; 133, 176; 133, 177; 134, 178; 134, 179; 135, 180; 135, 181; 139, 182; 141, 183; 143, 184; 145, 185; 147, 186; 149, 187; 151, 188; 153, 189; 156, 190; 156, 191; 157, 192; 157, 193; 158, 194; 159, 195; 160, 196; 160, 197; 162, 198; 162, 199; 163, 200; 163, 201; 164, 202; 164, 203; 166, 204; 166, 205; 167, 206; 167, 207; 169, 208; 169, 209; 170, 210; 170, 211; 172, 212; 173, 213; 175, 214; 175, 215; 175, 216; 175, 217; 176, 218; 176, 219; 177, 220; 178, 221; 178, 222; 181, 223; 191, 224; 192, 225; 192, 226; 193, 227; 194, 228; 194, 229; 195, 230; 195, 231; 197, 232; 199, 233; 201, 234; 203, 235; 205, 236; 207, 237; 209, 238; 211, 239; 212, 240; 212, 241; 213, 242; 213, 243; 214, 244; 215, 245; 217, 246; 217, 247; 217, 248; 218, 249; 218, 250; 221, 251; 221, 252; 226, 253; 227, 254; 227, 255; 228, 256; 228, 257; 229, 258; 230, 259; 230, 260; 234, 261; 234, 262; 236, 263; 236, 264; 238, 265; 238, 266; 240, 267; 240, 268; 242, 269; 242, 270; 244, 271; 244, 272; 244, 273; 245, 274; 245, 275; 245, 276; 246, 277; 246, 278; 247, 279; 247, 280; 248, 281; 253, 282; 253, 283; 255, 284; 256, 285; 256, 286; 259, 287; 259, 288; 261, 289; 261, 290; 263, 291; 263, 292; 265, 293; 265, 294; 268, 295; 270, 296; 271, 297; 271, 298; 273, 299; 273, 300; 274, 301; 274, 302; 276, 303; 276, 304; 277, 305; 277, 306; 279, 307; 280, 308; 281, 309; 281, 310; 283, 311; 284, 312; 284, 313; 290, 314; 292, 315; 294, 316; 298, 317; 299, 318; 299, 319; 302, 320; 303, 321; 303, 322; 306, 323; 307, 324; 307, 325; 308, 326; 308, 327; 309, 328; 309, 329; 310, 330; 310, 331; 313, 332; 319, 333; 322, 334; 324, 335; 324, 336; 326, 337; 326, 338; 328, 339; 328, 340; 329, 341; 330, 342; 330, 343; 331, 344; 336, 345; 338, 346; 339, 347; 339, 348; 341, 349; 342, 350; 342, 351; 344, 352; 348, 353; 349, 354; 349, 355; 351, 356; 352, 357; 352, 358; 354, 359; 354, 360; 357, 361; 357, 362; 360, 363; 362, 364 | def persistence2stats(rev_docs, min_persisted=5, min_visible=1209600,
include=None, exclude=None, verbose=False):
"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
min_persisted : `int`
The minimum future revisions that a token must persist in order
to be considered "persistent".
min_visible : `int`
The minimum number of seconds that a token must be visible in order
to be considered "persistent".
include : `func`
A function that returns `True` when a token should be included in
statistical processing
exclude : `str` | `re.SRE_Pattern`
A function that returns `True` when a token should *not* be
included in statistical processing (Takes precedence over
'include')
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""
rev_docs = mwxml.utilities.normalize(rev_docs)
min_persisted = int(min_persisted)
min_visible = int(min_visible)
include = include if include is not None else lambda t: True
exclude = exclude if exclude is not None else lambda t: False
for rev_doc in rev_docs:
persistence_doc = rev_doc['persistence']
stats_doc = {
'tokens_added': 0,
'persistent_tokens': 0,
'non_self_persistent_tokens': 0,
'sum_log_persisted': 0,
'sum_log_non_self_persisted': 0,
'sum_log_seconds_visible': 0,
'censored': False,
'non_self_censored': False
}
filtered_docs = (t for t in persistence_doc['tokens']
if include(t['text']) and not exclude(t['text']))
for token_doc in filtered_docs:
if verbose:
sys.stderr.write(".")
sys.stderr.flush()
stats_doc['tokens_added'] += 1
stats_doc['sum_log_persisted'] += log(token_doc['persisted'] + 1)
stats_doc['sum_log_non_self_persisted'] += \
log(token_doc['non_self_persisted'] + 1)
stats_doc['sum_log_seconds_visible'] += \
log(token_doc['seconds_visible'] + 1)
# Look for time threshold
if token_doc['seconds_visible'] >= min_visible:
stats_doc['persistent_tokens'] += 1
stats_doc['non_self_persistent_tokens'] += 1
else:
# Look for review threshold
stats_doc['persistent_tokens'] += \
token_doc['persisted'] >= min_persisted
stats_doc['non_self_persistent_tokens'] += \
token_doc['non_self_persisted'] >= min_persisted
# Check for censoring
if persistence_doc['seconds_possible'] < min_visible:
stats_doc['censored'] = True
stats_doc['non_self_censored'] = True
else:
if persistence_doc['revisions_processed'] < min_persisted:
stats_doc['censored'] = True
if persistence_doc['non_self_processed'] < min_persisted:
stats_doc['non_self_censored'] = True
if verbose:
sys.stderr.write("\n")
sys.stderr.flush()
rev_doc['persistence'].update(stats_doc)
yield rev_doc |
0, module; 1, function_definition; 2, function_name:diffs2persistence; 3, parameters; 4, block; 5, identifier:rev_docs; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, comment:# Group the docs by page; 16, expression_statement; 17, for_statement; 18, identifier:window_size; 19, integer:50; 20, identifier:revert_radius; 21, integer:15; 22, identifier:sunset; 23, None; 24, identifier:verbose; 25, False; 26, comment:"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds a 'persistence' field to them containing statistics about how each
token "added" in the revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
revert_radius : `int`
The number of revisions back that a revert can reference.
sunset : :class:`mwtypes.Timestamp`
The date of the database dump we are generating from. This is
used to apply a 'time visible' statistic. If not set, now() will
be assumed.
keep_diff : `bool`
Do not drop the `diff` field from the revision document after
processing is complete.
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""; 27, assignment; 28, assignment; 29, assignment; 30, assignment; 31, assignment; 32, pattern_list; 33, identifier:page_docs; 34, block; 35, identifier:rev_docs; 36, call; 37, identifier:window_size; 38, call; 39, identifier:revert_radius; 40, call; 41, identifier:sunset; 42, conditional_expression:Timestamp(sunset) if sunset is not None \
else Timestamp(time.time()); 43, identifier:page_docs; 44, call; 45, identifier:page_title; 46, identifier:rev_docs; 47, if_statement; 48, comment:# We need a look-ahead to know how long this revision was visible; 49, expression_statement; 50, comment:# The window allows us to manage memory; 51, expression_statement; 52, comment:# The state does the actual processing work; 53, expression_statement; 54, while_statement; 55, while_statement; 56, if_statement; 57, attribute; 58, argument_list; 59, identifier:int; 60, argument_list; 61, identifier:int; 62, argument_list; 63, call; 64, comparison_operator:sunset is not None; 65, line_continuation:\; 66, call; 67, identifier:groupby; 68, argument_list; 69, identifier:verbose; 70, block; 71, assignment; 72, assignment; 73, assignment; 74, identifier:rev_docs; 75, block; 76, comparison_operator:len(window) > 0; 77, block; 78, identifier:verbose; 79, block; 80, attribute; 81, identifier:normalize; 82, identifier:rev_docs; 83, identifier:window_size; 84, identifier:revert_radius; 85, identifier:Timestamp; 86, argument_list; 87, identifier:sunset; 88, None; 89, identifier:Timestamp; 90, argument_list; 91, identifier:rev_docs; 92, keyword_argument; 93, expression_statement; 94, identifier:rev_docs; 95, call; 96, identifier:window; 97, call; 98, identifier:state; 99, call; 100, expression_statement; 101, expression_statement; 102, if_statement; 103, if_statement; 104, expression_statement; 105, if_statement; 106, call; 107, integer:0; 108, expression_statement; 109, expression_statement; 110, expression_statement; 111, expression_statement; 112, if_statement; 113, expression_statement; 114, identifier:mwxml; 115, identifier:utilities; 116, identifier:sunset; 117, call; 118, identifier:key; 119, lambda; 120, call; 121, identifier:peekable; 122, argument_list; 123, identifier:deque; 124, argument_list; 125, identifier:DiffState; 126, argument_list; 127, assignment; 128, assignment; 129, comparison_operator:next_doc is not None; 130, block; 131, else_clause; 132, comparison_operator:seconds_visible < 0; 133, block; 134, assignment; 135, comparison_operator:len(window) == window_size; 136, comment:# Time to start writing some stats; 137, block; 138, else_clause; 139, identifier:len; 140, argument_list; 141, assignment; 142, assignment; 143, assignment; 144, yield; 145, identifier:verbose; 146, block; 147, call; 148, attribute; 149, argument_list; 150, lambda_parameters; 151, subscript; 152, attribute; 153, argument_list; 154, identifier:rev_docs; 155, keyword_argument; 156, keyword_argument; 157, identifier:rev_doc; 158, call; 159, identifier:next_doc; 160, call; 161, identifier:next_doc; 162, None; 163, expression_statement; 164, block; 165, identifier:seconds_visible; 166, integer:0; 167, expression_statement; 168, expression_statement; 169, pattern_list; 170, line_continuation:\; 171, call; 172, call; 173, identifier:window_size; 174, expression_statement; 175, expression_statement; 176, expression_statement; 177, expression_statement; 178, expression_statement; 179, if_statement; 180, block; 181, identifier:window; 182, pattern_list; 183, call; 184, identifier:persistence; 185, call; 186, subscript; 187, identifier:persistence; 188, identifier:old_doc; 189, expression_statement; 190, expression_statement; 191, attribute; 192, argument_list; 193, identifier:time; 194, identifier:time; 195, identifier:d; 196, subscript; 197, string; 198, attribute; 199, identifier:write; 200, binary_operator:page_title + ": "; 201, identifier:maxlen; 202, identifier:window_size; 203, identifier:revert_radius; 204, identifier:revert_radius; 205, identifier:next; 206, argument_list; 207, attribute; 208, argument_list; 209, assignment; 210, expression_statement; 211, call; 212, assignment; 213, identifier:_; 214, identifier:tokens_added; 215, identifier:_; 216, attribute; 217, argument_list; 218, identifier:len; 219, argument_list; 220, assignment; 221, call; 222, assignment; 223, assignment; 224, yield; 225, identifier:verbose; 226, block; 227, expression_statement; 228, identifier:old_doc; 229, identifier:old_added; 230, attribute; 231, argument_list; 232, identifier:token_persistence; 233, argument_list; 234, identifier:old_doc; 235, string; 236, call; 237, call; 238, attribute; 239, identifier:write; 240, string:"\n"; 241, identifier:d; 242, string; 243, string_content:title; 244, identifier:sys; 245, identifier:stderr; 246, identifier:page_title; 247, string:": "; 248, identifier:rev_docs; 249, identifier:rev_docs; 250, identifier:peek; 251, None; 252, identifier:seconds_visible; 253, binary_operator:Timestamp(next_doc['timestamp']) - \
Timestamp(rev_doc['timestamp']); 254, assignment; 255, attribute; 256, argument_list; 257, identifier:seconds_visible; 258, integer:0; 259, identifier:state; 260, identifier:update_opdocs; 261, subscript; 262, subscript; 263, tuple; 264, identifier:window; 265, pattern_list; 266, subscript; 267, attribute; 268, argument_list; 269, identifier:persistence; 270, call; 271, subscript; 272, identifier:persistence; 273, identifier:old_doc; 274, expression_statement; 275, expression_statement; 276, call; 277, identifier:window; 278, identifier:popleft; 279, identifier:old_doc; 280, identifier:old_added; 281, identifier:window; 282, identifier:sunset; 283, string_content:persistence; 284, attribute; 285, argument_list; 286, attribute; 287, argument_list; 288, identifier:sys; 289, identifier:stderr; 290, string_content:page; 291, call; 292, line_continuation:\; 293, call; 294, identifier:seconds_visible; 295, binary_operator:sunset - Timestamp(rev_doc['timestamp']); 296, identifier:logger; 297, identifier:warn; 298, call; 299, identifier:rev_doc; 300, string; 301, subscript; 302, string; 303, subscript; 304, identifier:seconds_visible; 305, identifier:old_doc; 306, identifier:old_added; 307, identifier:window; 308, integer:0; 309, identifier:window; 310, identifier:append; 311, tuple; 312, identifier:token_persistence; 313, argument_list; 314, identifier:old_doc; 315, string; 316, call; 317, call; 318, attribute; 319, argument_list; 320, attribute; 321, identifier:write; 322, string:"_"; 323, attribute; 324, identifier:flush; 325, identifier:Timestamp; 326, argument_list; 327, identifier:Timestamp; 328, argument_list; 329, identifier:sunset; 330, call; 331, attribute; 332, argument_list; 333, string_content:sha1; 334, identifier:rev_doc; 335, string; 336, string_content:ops; 337, identifier:rev_doc; 338, string; 339, identifier:rev_doc; 340, identifier:tokens_added; 341, identifier:old_doc; 342, identifier:old_added; 343, identifier:window; 344, None; 345, string_content:persistence; 346, attribute; 347, argument_list; 348, attribute; 349, argument_list; 350, identifier:window; 351, identifier:append; 352, tuple; 353, identifier:sys; 354, identifier:stderr; 355, identifier:sys; 356, identifier:stderr; 357, subscript; 358, subscript; 359, identifier:Timestamp; 360, argument_list; 361, string:"Seconds visible {0} is less than zero."; 362, identifier:format; 363, identifier:seconds_visible; 364, string_content:diff; 365, string_content:user; 366, attribute; 367, identifier:write; 368, string:"."; 369, attribute; 370, identifier:flush; 371, identifier:rev_doc; 372, identifier:tokens_added; 373, identifier:next_doc; 374, string; 375, identifier:rev_doc; 376, string; 377, subscript; 378, identifier:sys; 379, identifier:stderr; 380, identifier:sys; 381, identifier:stderr; 382, string_content:timestamp; 383, string_content:timestamp; 384, identifier:rev_doc; 385, string; 386, string_content:timestamp | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 6, 18; 6, 19; 7, 20; 7, 21; 8, 22; 8, 23; 9, 24; 9, 25; 10, 26; 11, 27; 12, 28; 13, 29; 14, 30; 16, 31; 17, 32; 17, 33; 17, 34; 27, 35; 27, 36; 28, 37; 28, 38; 29, 39; 29, 40; 30, 41; 30, 42; 31, 43; 31, 44; 32, 45; 32, 46; 34, 47; 34, 48; 34, 49; 34, 50; 34, 51; 34, 52; 34, 53; 34, 54; 34, 55; 34, 56; 36, 57; 36, 58; 38, 59; 38, 60; 40, 61; 40, 62; 42, 63; 42, 64; 42, 65; 42, 66; 44, 67; 44, 68; 47, 69; 47, 70; 49, 71; 51, 72; 53, 73; 54, 74; 54, 75; 55, 76; 55, 77; 56, 78; 56, 79; 57, 80; 57, 81; 58, 82; 60, 83; 62, 84; 63, 85; 63, 86; 64, 87; 64, 88; 66, 89; 66, 90; 68, 91; 68, 92; 70, 93; 71, 94; 71, 95; 72, 96; 72, 97; 73, 98; 73, 99; 75, 100; 75, 101; 75, 102; 75, 103; 75, 104; 75, 105; 76, 106; 76, 107; 77, 108; 77, 109; 77, 110; 77, 111; 77, 112; 79, 113; 80, 114; 80, 115; 86, 116; 90, 117; 92, 118; 92, 119; 93, 120; 95, 121; 95, 122; 97, 123; 97, 124; 99, 125; 99, 126; 100, 127; 101, 128; 102, 129; 102, 130; 102, 131; 103, 132; 103, 133; 104, 134; 105, 135; 105, 136; 105, 137; 105, 138; 106, 139; 106, 140; 108, 141; 109, 142; 110, 143; 111, 144; 112, 145; 112, 146; 113, 147; 117, 148; 117, 149; 119, 150; 119, 151; 120, 152; 120, 153; 122, 154; 124, 155; 126, 156; 127, 157; 127, 158; 128, 159; 128, 160; 129, 161; 129, 162; 130, 163; 131, 164; 132, 165; 132, 166; 133, 167; 133, 168; 134, 169; 134, 170; 134, 171; 135, 172; 135, 173; 137, 174; 137, 175; 137, 176; 137, 177; 137, 178; 137, 179; 138, 180; 140, 181; 141, 182; 141, 183; 142, 184; 142, 185; 143, 186; 143, 187; 144, 188; 146, 189; 146, 190; 147, 191; 147, 192; 148, 193; 148, 194; 150, 195; 151, 196; 151, 197; 152, 198; 152, 199; 153, 200; 155, 201; 155, 202; 156, 203; 156, 204; 158, 205; 158, 206; 160, 207; 160, 208; 163, 209; 164, 210; 167, 211; 168, 212; 169, 213; 169, 214; 169, 215; 171, 216; 171, 217; 172, 218; 172, 219; 174, 220; 175, 221; 176, 222; 177, 223; 178, 224; 179, 225; 179, 226; 180, 227; 182, 228; 182, 229; 183, 230; 183, 231; 185, 232; 185, 233; 186, 234; 186, 235; 189, 236; 190, 237; 191, 238; 191, 239; 192, 240; 196, 241; 196, 242; 197, 243; 198, 244; 198, 245; 200, 246; 200, 247; 206, 248; 207, 249; 207, 250; 208, 251; 209, 252; 209, 253; 210, 254; 211, 255; 211, 256; 212, 257; 212, 258; 216, 259; 216, 260; 217, 261; 217, 262; 217, 263; 219, 264; 220, 265; 220, 266; 221, 267; 221, 268; 222, 269; 222, 270; 223, 271; 223, 272; 224, 273; 226, 274; 226, 275; 227, 276; 230, 277; 230, 278; 233, 279; 233, 280; 233, 281; 233, 282; 235, 283; 236, 284; 236, 285; 237, 286; 237, 287; 238, 288; 238, 289; 242, 290; 253, 291; 253, 292; 253, 293; 254, 294; 254, 295; 255, 296; 255, 297; 256, 298; 261, 299; 261, 300; 262, 301; 262, 302; 263, 303; 263, 304; 265, 305; 265, 306; 266, 307; 266, 308; 267, 309; 267, 310; 268, 311; 270, 312; 270, 313; 271, 314; 271, 315; 274, 316; 275, 317; 276, 318; 276, 319; 284, 320; 284, 321; 285, 322; 286, 323; 286, 324; 291, 325; 291, 326; 293, 327; 293, 328; 295, 329; 295, 330; 298, 331; 298, 332; 300, 333; 301, 334; 301, 335; 302, 336; 303, 337; 303, 338; 311, 339; 311, 340; 313, 341; 313, 342; 313, 343; 313, 344; 315, 345; 316, 346; 316, 347; 317, 348; 317, 349; 318, 350; 318, 351; 319, 352; 320, 353; 320, 354; 323, 355; 323, 356; 326, 357; 328, 358; 330, 359; 330, 360; 331, 361; 331, 362; 332, 363; 335, 364; 338, 365; 346, 366; 346, 367; 347, 368; 348, 369; 348, 370; 352, 371; 352, 372; 357, 373; 357, 374; 358, 375; 358, 376; 360, 377; 366, 378; 366, 379; 369, 380; 369, 381; 374, 382; 376, 383; 377, 384; 377, 385; 385, 386 | def diffs2persistence(rev_docs, window_size=50, revert_radius=15, sunset=None,
verbose=False):
"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds a 'persistence' field to them containing statistics about how each
token "added" in the revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
revert_radius : `int`
The number of revisions back that a revert can reference.
sunset : :class:`mwtypes.Timestamp`
The date of the database dump we are generating from. This is
used to apply a 'time visible' statistic. If not set, now() will
be assumed.
keep_diff : `bool`
Do not drop the `diff` field from the revision document after
processing is complete.
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""
rev_docs = mwxml.utilities.normalize(rev_docs)
window_size = int(window_size)
revert_radius = int(revert_radius)
sunset = Timestamp(sunset) if sunset is not None \
else Timestamp(time.time())
# Group the docs by page
page_docs = groupby(rev_docs, key=lambda d: d['page']['title'])
for page_title, rev_docs in page_docs:
if verbose:
sys.stderr.write(page_title + ": ")
# We need a look-ahead to know how long this revision was visible
rev_docs = peekable(rev_docs)
# The window allows us to manage memory
window = deque(maxlen=window_size)
# The state does the actual processing work
state = DiffState(revert_radius=revert_radius)
while rev_docs:
rev_doc = next(rev_docs)
next_doc = rev_docs.peek(None)
if next_doc is not None:
seconds_visible = Timestamp(next_doc['timestamp']) - \
Timestamp(rev_doc['timestamp'])
else:
seconds_visible = sunset - Timestamp(rev_doc['timestamp'])
if seconds_visible < 0:
logger.warn("Seconds visible {0} is less than zero."
.format(seconds_visible))
seconds_visible = 0
_, tokens_added, _ = \
state.update_opdocs(rev_doc['sha1'], rev_doc['diff']['ops'],
(rev_doc['user'], seconds_visible))
if len(window) == window_size:
# Time to start writing some stats
old_doc, old_added = window[0]
window.append((rev_doc, tokens_added))
persistence = token_persistence(old_doc, old_added, window,
None)
old_doc['persistence'] = persistence
yield old_doc
if verbose:
sys.stderr.write(".")
sys.stderr.flush()
else:
window.append((rev_doc, tokens_added))
while len(window) > 0:
old_doc, old_added = window.popleft()
persistence = token_persistence(old_doc, old_added, window, sunset)
old_doc['persistence'] = persistence
yield old_doc
if verbose:
sys.stderr.write("_")
sys.stderr.flush()
if verbose:
sys.stderr.write("\n") |
0, module; 1, function_definition; 2, function_name:_build_module_db; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, for_statement; 10, comment:"""
Build database of module callables sorted by line number.
The database is a dictionary whose keys are module file names and
whose values are lists of dictionaries containing name and line
number of callables in that module
"""; 11, assignment; 12, pattern_list; 13, call; 14, block; 15, identifier:fname; 16, call; 17, block; 18, identifier:tdict; 19, call; 20, identifier:callable_name; 21, identifier:callable_dict; 22, attribute; 23, argument_list; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, attribute; 28, argument_list; 29, expression_statement; 30, attribute; 31, argument_list; 32, attribute; 33, identifier:items; 34, assignment; 35, assignment; 36, call; 37, identifier:tdict; 38, identifier:keys; 39, assignment; 40, identifier:collections; 41, identifier:defaultdict; 42, lambda; 43, attribute; 44, identifier:callables_db; 45, pattern_list; 46, subscript; 47, identifier:cname; 48, parenthesized_expression; 49, attribute; 50, argument_list; 51, subscript; 52, call; 53, list; 54, identifier:self; 55, identifier:_exh_obj; 56, identifier:fname; 57, identifier:line_no; 58, identifier:callable_dict; 59, string:"code_id"; 60, conditional_expression:"{cls_name}.__init__".format(cls_name=callable_name)
if callable_dict["type"] == "class"
else callable_name; 61, subscript; 62, identifier:append; 63, dictionary; 64, attribute; 65, identifier:fname; 66, identifier:sorted; 67, argument_list; 68, call; 69, comparison_operator:callable_dict["type"] == "class"; 70, identifier:callable_name; 71, identifier:tdict; 72, identifier:fname; 73, pair; 74, pair; 75, identifier:self; 76, identifier:_module_obj_db; 77, subscript; 78, keyword_argument; 79, attribute; 80, argument_list; 81, subscript; 82, string:"class"; 83, string:"name"; 84, identifier:cname; 85, string:"line"; 86, identifier:line_no; 87, identifier:tdict; 88, identifier:fname; 89, identifier:key; 90, lambda; 91, string:"{cls_name}.__init__"; 92, identifier:format; 93, keyword_argument; 94, identifier:callable_dict; 95, string:"type"; 96, lambda_parameters; 97, subscript; 98, identifier:cls_name; 99, identifier:callable_name; 100, identifier:idict; 101, identifier:idict; 102, string:"line" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 9, 16; 9, 17; 11, 18; 11, 19; 12, 20; 12, 21; 13, 22; 13, 23; 14, 24; 14, 25; 14, 26; 16, 27; 16, 28; 17, 29; 19, 30; 19, 31; 22, 32; 22, 33; 24, 34; 25, 35; 26, 36; 27, 37; 27, 38; 29, 39; 30, 40; 30, 41; 31, 42; 32, 43; 32, 44; 34, 45; 34, 46; 35, 47; 35, 48; 36, 49; 36, 50; 39, 51; 39, 52; 42, 53; 43, 54; 43, 55; 45, 56; 45, 57; 46, 58; 46, 59; 48, 60; 49, 61; 49, 62; 50, 63; 51, 64; 51, 65; 52, 66; 52, 67; 60, 68; 60, 69; 60, 70; 61, 71; 61, 72; 63, 73; 63, 74; 64, 75; 64, 76; 67, 77; 67, 78; 68, 79; 68, 80; 69, 81; 69, 82; 73, 83; 73, 84; 74, 85; 74, 86; 77, 87; 77, 88; 78, 89; 78, 90; 79, 91; 79, 92; 80, 93; 81, 94; 81, 95; 90, 96; 90, 97; 93, 98; 93, 99; 96, 100; 97, 101; 97, 102 | def _build_module_db(self):
"""
Build database of module callables sorted by line number.
The database is a dictionary whose keys are module file names and
whose values are lists of dictionaries containing name and line
number of callables in that module
"""
tdict = collections.defaultdict(lambda: [])
for callable_name, callable_dict in self._exh_obj.callables_db.items():
fname, line_no = callable_dict["code_id"]
cname = (
"{cls_name}.__init__".format(cls_name=callable_name)
if callable_dict["type"] == "class"
else callable_name
)
tdict[fname].append({"name": cname, "line": line_no})
for fname in tdict.keys():
self._module_obj_db[fname] = sorted(
tdict[fname], key=lambda idict: idict["line"]
) |
0, module; 1, function_definition; 2, function_name:_sorted_keys_items; 3, parameters; 4, block; 5, identifier:dobj; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, comment:"""Return dictionary items sorted by key."""; 10, assignment; 11, identifier:key; 12, identifier:keys; 13, block; 14, identifier:keys; 15, call; 16, expression_statement; 17, identifier:sorted; 18, argument_list; 19, yield; 20, call; 21, expression_list; 22, attribute; 23, argument_list; 24, identifier:key; 25, subscript; 26, identifier:dobj; 27, identifier:keys; 28, identifier:dobj; 29, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 8, 12; 8, 13; 10, 14; 10, 15; 13, 16; 15, 17; 15, 18; 16, 19; 18, 20; 19, 21; 20, 22; 20, 23; 21, 24; 21, 25; 22, 26; 22, 27; 25, 28; 25, 29 | def _sorted_keys_items(dobj):
"""Return dictionary items sorted by key."""
keys = sorted(dobj.keys())
for key in keys:
yield key, dobj[key] |
0, module; 1, function_definition; 2, function_name:subdict_by_keys; 3, parameters; 4, block; 5, identifier:dict_obj; 6, identifier:keys; 7, expression_statement; 8, return_statement; 9, comment:"""Returns a sub-dict composed solely of the given keys.
Parameters
----------
dict_obj : dict
The dict to create a sub-dict from.
keys : list of str
The keys to keep in the sub-dict. Keys not present in the given dict
will be ignored.
Returns
-------
dict
A sub-dict of the given dict composed solely of the given keys.
Example:
--------
>>> dict_obj = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> subdict = subdict_by_keys(dict_obj, ['b', 'd', 'e'])
>>> print(sorted(subdict.items()))
[('b', 2), ('d', 4)]
"""; 10, dictionary_comprehension; 11, pair; 12, for_in_clause; 13, identifier:k; 14, subscript; 15, identifier:k; 16, call; 17, identifier:dict_obj; 18, identifier:k; 19, attribute; 20, argument_list; 21, call; 22, identifier:intersection; 23, call; 24, identifier:set; 25, argument_list; 26, attribute; 27, argument_list; 28, identifier:keys; 29, identifier:dict_obj; 30, identifier:keys | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 10, 11; 10, 12; 11, 13; 11, 14; 12, 15; 12, 16; 14, 17; 14, 18; 16, 19; 16, 20; 19, 21; 19, 22; 20, 23; 21, 24; 21, 25; 23, 26; 23, 27; 25, 28; 26, 29; 26, 30 | def subdict_by_keys(dict_obj, keys):
"""Returns a sub-dict composed solely of the given keys.
Parameters
----------
dict_obj : dict
The dict to create a sub-dict from.
keys : list of str
The keys to keep in the sub-dict. Keys not present in the given dict
will be ignored.
Returns
-------
dict
A sub-dict of the given dict composed solely of the given keys.
Example:
--------
>>> dict_obj = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> subdict = subdict_by_keys(dict_obj, ['b', 'd', 'e'])
>>> print(sorted(subdict.items()))
[('b', 2), ('d', 4)]
"""
return {k: dict_obj[k] for k in set(keys).intersection(dict_obj.keys())} |
0, module; 1, function_definition; 2, function_name:deep_merge_dict; 3, parameters; 4, block; 5, identifier:base; 6, identifier:priority; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, comment:"""Recursively merges the two given dicts into a single dict.
Treating base as the the initial point of the resulting merged dict,
and considering the nested dictionaries as trees, they are merged os:
1. Every path to every leaf in priority would be represented in the result.
2. Subtrees of base are overwritten if a leaf is found in the
corresponding path in priority.
3. The invariant that all priority leaf nodes remain leafs is maintained.
Parameters
----------
base : dict
The first, lower-priority, dict to merge.
priority : dict
The second, higher-priority, dict to merge.
Returns
-------
dict
A recursive merge of the two given dicts.
Example:
--------
>>> base = {'a': 1, 'b': 2, 'c': {'d': 4}, 'e': 5}
>>> priority = {'a': {'g': 7}, 'c': 3, 'e': 5, 'f': 6}
>>> result = deep_merge_dict(base, priority)
>>> print(sorted(result.items()))
[('a', {'g': 7}), ('b', 2), ('c', 3), ('e', 5), ('f', 6)]
"""; 13, boolean_operator; 14, block; 15, assignment; 16, identifier:key; 17, call; 18, block; 19, identifier:result; 20, not_operator; 21, not_operator; 22, return_statement; 23, identifier:result; 24, call; 25, attribute; 26, argument_list; 27, if_statement; 28, call; 29, call; 30, identifier:priority; 31, attribute; 32, argument_list; 33, identifier:priority; 34, identifier:keys; 35, comparison_operator:key in base; 36, block; 37, else_clause; 38, identifier:isinstance; 39, argument_list; 40, identifier:isinstance; 41, argument_list; 42, identifier:copy; 43, identifier:deepcopy; 44, identifier:base; 45, identifier:key; 46, identifier:base; 47, expression_statement; 48, block; 49, identifier:base; 50, identifier:dict; 51, identifier:priority; 52, identifier:dict; 53, assignment; 54, expression_statement; 55, subscript; 56, call; 57, assignment; 58, identifier:result; 59, identifier:key; 60, identifier:deep_merge_dict; 61, argument_list; 62, subscript; 63, subscript; 64, subscript; 65, subscript; 66, identifier:result; 67, identifier:key; 68, identifier:priority; 69, identifier:key; 70, identifier:base; 71, identifier:key; 72, identifier:priority; 73, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 8, 13; 8, 14; 9, 15; 10, 16; 10, 17; 10, 18; 11, 19; 13, 20; 13, 21; 14, 22; 15, 23; 15, 24; 17, 25; 17, 26; 18, 27; 20, 28; 21, 29; 22, 30; 24, 31; 24, 32; 25, 33; 25, 34; 27, 35; 27, 36; 27, 37; 28, 38; 28, 39; 29, 40; 29, 41; 31, 42; 31, 43; 32, 44; 35, 45; 35, 46; 36, 47; 37, 48; 39, 49; 39, 50; 41, 51; 41, 52; 47, 53; 48, 54; 53, 55; 53, 56; 54, 57; 55, 58; 55, 59; 56, 60; 56, 61; 57, 62; 57, 63; 61, 64; 61, 65; 62, 66; 62, 67; 63, 68; 63, 69; 64, 70; 64, 71; 65, 72; 65, 73 | def deep_merge_dict(base, priority):
"""Recursively merges the two given dicts into a single dict.
Treating base as the the initial point of the resulting merged dict,
and considering the nested dictionaries as trees, they are merged os:
1. Every path to every leaf in priority would be represented in the result.
2. Subtrees of base are overwritten if a leaf is found in the
corresponding path in priority.
3. The invariant that all priority leaf nodes remain leafs is maintained.
Parameters
----------
base : dict
The first, lower-priority, dict to merge.
priority : dict
The second, higher-priority, dict to merge.
Returns
-------
dict
A recursive merge of the two given dicts.
Example:
--------
>>> base = {'a': 1, 'b': 2, 'c': {'d': 4}, 'e': 5}
>>> priority = {'a': {'g': 7}, 'c': 3, 'e': 5, 'f': 6}
>>> result = deep_merge_dict(base, priority)
>>> print(sorted(result.items()))
[('a', {'g': 7}), ('b', 2), ('c', 3), ('e', 5), ('f', 6)]
"""
if not isinstance(base, dict) or not isinstance(priority, dict):
return priority
result = copy.deepcopy(base)
for key in priority.keys():
if key in base:
result[key] = deep_merge_dict(base[key], priority[key])
else:
result[key] = priority[key]
return result |
0, module; 1, function_definition; 2, function_name:norm_int_dict; 3, parameters; 4, block; 5, identifier:int_dict; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Normalizes values in the given dict with int values.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
Returns
-------
dict
A dict where each key is mapped to its relative part in the sum of
all dict values.
Example
-------
>>> dict_obj = {'a': 3, 'b': 5, 'c': 2}
>>> result = norm_int_dict(dict_obj)
>>> print(sorted(result.items()))
[('a', 0.3), ('b', 0.5), ('c', 0.2)]
"""; 12, assignment; 13, assignment; 14, identifier:key; 15, identifier:norm_dict; 16, block; 17, identifier:norm_dict; 18, identifier:norm_dict; 19, call; 20, identifier:val_sum; 21, call; 22, expression_statement; 23, attribute; 24, argument_list; 25, identifier:sum; 26, argument_list; 27, assignment; 28, identifier:int_dict; 29, identifier:copy; 30, call; 31, subscript; 32, binary_operator:norm_dict[key] / val_sum; 33, attribute; 34, argument_list; 35, identifier:norm_dict; 36, identifier:key; 37, subscript; 38, identifier:val_sum; 39, identifier:norm_dict; 40, identifier:values; 41, identifier:norm_dict; 42, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 12, 18; 12, 19; 13, 20; 13, 21; 16, 22; 19, 23; 19, 24; 21, 25; 21, 26; 22, 27; 23, 28; 23, 29; 26, 30; 27, 31; 27, 32; 30, 33; 30, 34; 31, 35; 31, 36; 32, 37; 32, 38; 33, 39; 33, 40; 37, 41; 37, 42 | def norm_int_dict(int_dict):
"""Normalizes values in the given dict with int values.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
Returns
-------
dict
A dict where each key is mapped to its relative part in the sum of
all dict values.
Example
-------
>>> dict_obj = {'a': 3, 'b': 5, 'c': 2}
>>> result = norm_int_dict(dict_obj)
>>> print(sorted(result.items()))
[('a', 0.3), ('b', 0.5), ('c', 0.2)]
"""
norm_dict = int_dict.copy()
val_sum = sum(norm_dict.values())
for key in norm_dict:
norm_dict[key] = norm_dict[key] / val_sum
return norm_dict |
0, module; 1, function_definition; 2, function_name:sum_num_dicts; 3, parameters; 4, block; 5, identifier:dicts; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, if_statement; 11, return_statement; 12, identifier:normalize; 13, False; 14, comment:"""Sums the given dicts into a single dict mapping each key to the sum
of its mappings in all given dicts.
Parameters
----------
dicts : list
A list of dict objects mapping each key to an numeric value.
normalize : bool, default False
Indicated whether to normalize all values by value sum.
Returns
-------
dict
A dict where each key is mapped to the sum of its mappings in all
given dicts.
Example
-------
>>> dict1 = {'a': 3, 'b': 2}
>>> dict2 = {'a':7, 'c': 8}
>>> result = sum_num_dicts([dict1, dict2])
>>> print(sorted(result.items()))
[('a', 10), ('b', 2), ('c', 8)]
>>> result = sum_num_dicts([dict1, dict2], normalize=True)
>>> print(sorted(result.items()))
[('a', 0.5), ('b', 0.1), ('c', 0.4)]
"""; 15, assignment; 16, identifier:dicti; 17, identifier:dicts; 18, block; 19, identifier:normalize; 20, block; 21, identifier:sum_dict; 22, identifier:sum_dict; 23, dictionary; 24, for_statement; 25, return_statement; 26, identifier:key; 27, identifier:dicti; 28, block; 29, call; 30, expression_statement; 31, identifier:norm_int_dict; 32, argument_list; 33, assignment; 34, identifier:sum_dict; 35, subscript; 36, binary_operator:sum_dict.get(key, 0) + dicti[key]; 37, identifier:sum_dict; 38, identifier:key; 39, call; 40, subscript; 41, attribute; 42, argument_list; 43, identifier:dicti; 44, identifier:key; 45, identifier:sum_dict; 46, identifier:get; 47, identifier:key; 48, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 9, 16; 9, 17; 9, 18; 10, 19; 10, 20; 11, 21; 15, 22; 15, 23; 18, 24; 20, 25; 24, 26; 24, 27; 24, 28; 25, 29; 28, 30; 29, 31; 29, 32; 30, 33; 32, 34; 33, 35; 33, 36; 35, 37; 35, 38; 36, 39; 36, 40; 39, 41; 39, 42; 40, 43; 40, 44; 41, 45; 41, 46; 42, 47; 42, 48 | def sum_num_dicts(dicts, normalize=False):
"""Sums the given dicts into a single dict mapping each key to the sum
of its mappings in all given dicts.
Parameters
----------
dicts : list
A list of dict objects mapping each key to an numeric value.
normalize : bool, default False
Indicated whether to normalize all values by value sum.
Returns
-------
dict
A dict where each key is mapped to the sum of its mappings in all
given dicts.
Example
-------
>>> dict1 = {'a': 3, 'b': 2}
>>> dict2 = {'a':7, 'c': 8}
>>> result = sum_num_dicts([dict1, dict2])
>>> print(sorted(result.items()))
[('a', 10), ('b', 2), ('c', 8)]
>>> result = sum_num_dicts([dict1, dict2], normalize=True)
>>> print(sorted(result.items()))
[('a', 0.5), ('b', 0.1), ('c', 0.4)]
"""
sum_dict = {}
for dicti in dicts:
for key in dicti:
sum_dict[key] = sum_dict.get(key, 0) + dicti[key]
if normalize:
return norm_int_dict(sum_dict)
return sum_dict |
0, module; 1, function_definition; 2, function_name:reverse_dict; 3, parameters; 4, block; 5, identifier:dict_obj; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, for_statement; 10, return_statement; 11, comment:"""Reverse a dict, so each value in it maps to a sorted list of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to a sorted list of all the unique keys
that mapped to it.
Example
-------
>>> dicti = {'a': 1, 'b': 3, 'c': 1}
>>> reverse_dict(dicti)
{1: ['a', 'c'], 3: ['b']}
"""; 12, assignment; 13, identifier:key; 14, identifier:dict_obj; 15, block; 16, identifier:key; 17, identifier:new_dict; 18, block; 19, identifier:new_dict; 20, identifier:new_dict; 21, dictionary; 22, expression_statement; 23, expression_statement; 24, call; 25, assignment; 26, identifier:add_to_dict_val_set; 27, argument_list; 28, subscript; 29, call; 30, keyword_argument; 31, keyword_argument; 32, keyword_argument; 33, identifier:new_dict; 34, identifier:key; 35, identifier:sorted; 36, argument_list; 37, identifier:dict_obj; 38, identifier:new_dict; 39, identifier:key; 40, subscript; 41, identifier:val; 42, identifier:key; 43, subscript; 44, keyword_argument; 45, identifier:dict_obj; 46, identifier:key; 47, identifier:new_dict; 48, identifier:key; 49, identifier:reverse; 50, False | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 8, 14; 8, 15; 9, 16; 9, 17; 9, 18; 10, 19; 12, 20; 12, 21; 15, 22; 18, 23; 22, 24; 23, 25; 24, 26; 24, 27; 25, 28; 25, 29; 27, 30; 27, 31; 27, 32; 28, 33; 28, 34; 29, 35; 29, 36; 30, 37; 30, 38; 31, 39; 31, 40; 32, 41; 32, 42; 36, 43; 36, 44; 40, 45; 40, 46; 43, 47; 43, 48; 44, 49; 44, 50 | def reverse_dict(dict_obj):
"""Reverse a dict, so each value in it maps to a sorted list of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to a sorted list of all the unique keys
that mapped to it.
Example
-------
>>> dicti = {'a': 1, 'b': 3, 'c': 1}
>>> reverse_dict(dicti)
{1: ['a', 'c'], 3: ['b']}
"""
new_dict = {}
for key in dict_obj:
add_to_dict_val_set(dict_obj=new_dict, key=dict_obj[key], val=key)
for key in new_dict:
new_dict[key] = sorted(new_dict[key], reverse=False)
return new_dict |
0, module; 1, function_definition; 2, function_name:flatten_dict; 3, parameters; 4, block; 5, identifier:dict_obj; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, function_definition; 12, function_definition; 13, expression_statement; 14, return_statement; 15, identifier:separator; 16, string; 17, identifier:flatten_lists; 18, False; 19, comment:"""Flattens the given dict into a single-level dict with flattend keys.
Parameters
----------
dict_obj : dict
A possibly nested dict.
separator : str, optional
The character to use as a separator between keys. Defaults to '.'.
flatten_lists : bool, optional
If True, list values are also flattened. False by default.
Returns
-------
dict
A shallow dict, where no value is a dict in itself, and keys are
concatenations of original key paths separated with the given
separator.
Example
-------
>>> dicti = {'a': 1, 'b': {'g': 4, 'o': 9}, 'x': [4, 'd']}
>>> flat = flatten_dict(dicti)
>>> sorted(flat.items())
[('a', 1), ('b.g', 4), ('b.o', 9), ('x.0', 4), ('x.1', 'd')]
"""; 20, assignment; 21, assignment; 22, function_name:_flatten_key_val; 23, parameters; 24, block; 25, function_name:_flatten; 26, parameters; 27, block; 28, call; 29, identifier:flat; 30, string_content:.; 31, identifier:reducer; 32, call; 33, identifier:flat; 34, dictionary; 35, identifier:key; 36, identifier:val; 37, identifier:parent; 38, expression_statement; 39, try_statement; 40, identifier:d; 41, default_parameter; 42, try_statement; 43, identifier:_flatten; 44, argument_list; 45, identifier:_get_key_reducer; 46, argument_list; 47, assignment; 48, block; 49, except_clause; 50, identifier:parent; 51, None; 52, block; 53, except_clause; 54, identifier:dict_obj; 55, identifier:separator; 56, identifier:flat_key; 57, call; 58, expression_statement; 59, identifier:TypeError; 60, block; 61, for_statement; 62, identifier:AttributeError; 63, block; 64, identifier:reducer; 65, argument_list; 66, call; 67, expression_statement; 68, pattern_list; 69, call; 70, block; 71, if_statement; 72, for_statement; 73, identifier:parent; 74, identifier:key; 75, identifier:_flatten; 76, argument_list; 77, assignment; 78, identifier:key; 79, identifier:val; 80, attribute; 81, argument_list; 82, expression_statement; 83, call; 84, block; 85, pattern_list; 86, call; 87, block; 88, identifier:val; 89, identifier:flat_key; 90, subscript; 91, identifier:val; 92, identifier:d; 93, identifier:items; 94, call; 95, identifier:isinstance; 96, argument_list; 97, raise_statement; 98, identifier:i; 99, identifier:value; 100, identifier:enumerate; 101, argument_list; 102, expression_statement; 103, identifier:flat; 104, identifier:flat_key; 105, identifier:_flatten_key_val; 106, argument_list; 107, identifier:d; 108, tuple; 109, identifier:TypeError; 110, identifier:d; 111, call; 112, identifier:key; 113, identifier:val; 114, identifier:parent; 115, identifier:str; 116, identifier:bytes; 117, identifier:_flatten_key_val; 118, argument_list; 119, call; 120, identifier:value; 121, identifier:parent; 122, identifier:str; 123, argument_list; 124, identifier:i | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 9, 20; 10, 21; 11, 22; 11, 23; 11, 24; 12, 25; 12, 26; 12, 27; 13, 28; 14, 29; 16, 30; 20, 31; 20, 32; 21, 33; 21, 34; 23, 35; 23, 36; 23, 37; 24, 38; 24, 39; 26, 40; 26, 41; 27, 42; 28, 43; 28, 44; 32, 45; 32, 46; 38, 47; 39, 48; 39, 49; 41, 50; 41, 51; 42, 52; 42, 53; 44, 54; 46, 55; 47, 56; 47, 57; 48, 58; 49, 59; 49, 60; 52, 61; 53, 62; 53, 63; 57, 64; 57, 65; 58, 66; 60, 67; 61, 68; 61, 69; 61, 70; 63, 71; 63, 72; 65, 73; 65, 74; 66, 75; 66, 76; 67, 77; 68, 78; 68, 79; 69, 80; 69, 81; 70, 82; 71, 83; 71, 84; 72, 85; 72, 86; 72, 87; 76, 88; 76, 89; 77, 90; 77, 91; 80, 92; 80, 93; 82, 94; 83, 95; 83, 96; 84, 97; 85, 98; 85, 99; 86, 100; 86, 101; 87, 102; 90, 103; 90, 104; 94, 105; 94, 106; 96, 107; 96, 108; 97, 109; 101, 110; 102, 111; 106, 112; 106, 113; 106, 114; 108, 115; 108, 116; 111, 117; 111, 118; 118, 119; 118, 120; 118, 121; 119, 122; 119, 123; 123, 124 | def flatten_dict(dict_obj, separator='.', flatten_lists=False):
"""Flattens the given dict into a single-level dict with flattend keys.
Parameters
----------
dict_obj : dict
A possibly nested dict.
separator : str, optional
The character to use as a separator between keys. Defaults to '.'.
flatten_lists : bool, optional
If True, list values are also flattened. False by default.
Returns
-------
dict
A shallow dict, where no value is a dict in itself, and keys are
concatenations of original key paths separated with the given
separator.
Example
-------
>>> dicti = {'a': 1, 'b': {'g': 4, 'o': 9}, 'x': [4, 'd']}
>>> flat = flatten_dict(dicti)
>>> sorted(flat.items())
[('a', 1), ('b.g', 4), ('b.o', 9), ('x.0', 4), ('x.1', 'd')]
"""
reducer = _get_key_reducer(separator)
flat = {}
def _flatten_key_val(key, val, parent):
flat_key = reducer(parent, key)
try:
_flatten(val, flat_key)
except TypeError:
flat[flat_key] = val
def _flatten(d, parent=None):
try:
for key, val in d.items():
_flatten_key_val(key, val, parent)
except AttributeError:
if isinstance(d, (str, bytes)):
raise TypeError
for i, value in enumerate(d):
_flatten_key_val(str(i), value, parent)
_flatten(dict_obj)
return flat |
0, module; 1, function_definition; 2, function_name:key_value_nested_generator; 3, parameters; 4, block; 5, identifier:dict_obj; 6, expression_statement; 7, for_statement; 8, comment:"""Recursively iterate over key-value pairs of nested dictionaries.
Parameters
----------
dict_obj : dict
The outer-most dict to iterate on.
Returns
-------
generator
A generator over key-value pairs in all nested dictionaries.
Example
-------
>>> dicti = {'a': 1, 'b': {'c': 3, 'd': 4}}
>>> print(sorted(list(key_value_nested_generator(dicti))))
[('a', 1), ('c', 3), ('d', 4)]
"""; 9, pattern_list; 10, call; 11, block; 12, identifier:key; 13, identifier:value; 14, attribute; 15, argument_list; 16, if_statement; 17, identifier:dict_obj; 18, identifier:items; 19, call; 20, block; 21, else_clause; 22, identifier:isinstance; 23, argument_list; 24, for_statement; 25, block; 26, identifier:value; 27, identifier:dict; 28, pattern_list; 29, call; 30, block; 31, expression_statement; 32, identifier:key; 33, identifier:value; 34, identifier:key_value_nested_generator; 35, argument_list; 36, expression_statement; 37, yield; 38, identifier:value; 39, yield; 40, expression_list; 41, expression_list; 42, identifier:key; 43, identifier:value; 44, identifier:key; 45, identifier:value | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 9, 12; 9, 13; 10, 14; 10, 15; 11, 16; 14, 17; 14, 18; 16, 19; 16, 20; 16, 21; 19, 22; 19, 23; 20, 24; 21, 25; 23, 26; 23, 27; 24, 28; 24, 29; 24, 30; 25, 31; 28, 32; 28, 33; 29, 34; 29, 35; 30, 36; 31, 37; 35, 38; 36, 39; 37, 40; 39, 41; 40, 42; 40, 43; 41, 44; 41, 45 | def key_value_nested_generator(dict_obj):
"""Recursively iterate over key-value pairs of nested dictionaries.
Parameters
----------
dict_obj : dict
The outer-most dict to iterate on.
Returns
-------
generator
A generator over key-value pairs in all nested dictionaries.
Example
-------
>>> dicti = {'a': 1, 'b': {'c': 3, 'd': 4}}
>>> print(sorted(list(key_value_nested_generator(dicti))))
[('a', 1), ('c', 3), ('d', 4)]
"""
for key, value in dict_obj.items():
if isinstance(value, dict):
for key, value in key_value_nested_generator(value):
yield key, value
else:
yield key, value |
0, module; 1, function_definition; 2, function_name:key_tuple_value_nested_generator; 3, parameters; 4, block; 5, identifier:dict_obj; 6, expression_statement; 7, for_statement; 8, comment:"""Recursively iterate over key-tuple-value pairs of nested dictionaries.
Parameters
----------
dict_obj : dict
The outer-most dict to iterate on.
Returns
-------
generator
A generator over key-tuple-value pairs in all nested dictionaries.
Example
-------
>>> dicti = {'a': 1, 'b': {'c': 3, 'd': 4}}
>>> print(sorted(list(key_tuple_value_nested_generator(dicti))))
[(('a',), 1), (('b', 'c'), 3), (('b', 'd'), 4)]
"""; 9, pattern_list; 10, call; 11, block; 12, identifier:key; 13, identifier:value; 14, attribute; 15, argument_list; 16, if_statement; 17, identifier:dict_obj; 18, identifier:items; 19, call; 20, block; 21, else_clause; 22, identifier:isinstance; 23, argument_list; 24, for_statement; 25, block; 26, identifier:value; 27, identifier:dict; 28, pattern_list; 29, call; 30, block; 31, expression_statement; 32, identifier:nested_key; 33, identifier:value; 34, identifier:key_tuple_value_nested_generator; 35, argument_list; 36, expression_statement; 37, yield; 38, identifier:value; 39, yield; 40, expression_list; 41, expression_list; 42, call; 43, identifier:value; 44, binary_operator:tuple([key]) + nested_key; 45, identifier:value; 46, identifier:tuple; 47, argument_list; 48, call; 49, identifier:nested_key; 50, list; 51, identifier:tuple; 52, argument_list; 53, identifier:key; 54, list; 55, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 9, 12; 9, 13; 10, 14; 10, 15; 11, 16; 14, 17; 14, 18; 16, 19; 16, 20; 16, 21; 19, 22; 19, 23; 20, 24; 21, 25; 23, 26; 23, 27; 24, 28; 24, 29; 24, 30; 25, 31; 28, 32; 28, 33; 29, 34; 29, 35; 30, 36; 31, 37; 35, 38; 36, 39; 37, 40; 39, 41; 40, 42; 40, 43; 41, 44; 41, 45; 42, 46; 42, 47; 44, 48; 44, 49; 47, 50; 48, 51; 48, 52; 50, 53; 52, 54; 54, 55 | def key_tuple_value_nested_generator(dict_obj):
"""Recursively iterate over key-tuple-value pairs of nested dictionaries.
Parameters
----------
dict_obj : dict
The outer-most dict to iterate on.
Returns
-------
generator
A generator over key-tuple-value pairs in all nested dictionaries.
Example
-------
>>> dicti = {'a': 1, 'b': {'c': 3, 'd': 4}}
>>> print(sorted(list(key_tuple_value_nested_generator(dicti))))
[(('a',), 1), (('b', 'c'), 3), (('b', 'd'), 4)]
"""
for key, value in dict_obj.items():
if isinstance(value, dict):
for nested_key, value in key_tuple_value_nested_generator(value):
yield tuple([key]) + nested_key, value
else:
yield tuple([key]), value |
0, module; 1, function_definition; 2, function_name:_sort_dd_skips; 3, parameters; 4, block; 5, identifier:configs; 6, identifier:dd_indices_all; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, comment:# determine skips; 11, expression_statement; 12, expression_statement; 13, comment:# now determine the configurations; 14, expression_statement; 15, for_statement; 16, return_statement; 17, comment:"""Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with the skip as keys, and arrays/lists with indices to
these skips.
"""; 18, assignment; 19, call; 20, block; 21, assignment; 22, assignment; 23, assignment; 24, identifier:skip; 25, identifier:available_skips; 26, block; 27, identifier:dd_configs_sorted; 28, identifier:config_current_skips; 29, call; 30, attribute; 31, argument_list; 32, return_statement; 33, identifier:available_skips_raw; 34, call; 35, identifier:available_skips; 36, call; 37, identifier:dd_configs_sorted; 38, dictionary; 39, expression_statement; 40, expression_statement; 41, attribute; 42, argument_list; 43, identifier:np; 44, identifier:all; 45, call; 46, dictionary; 47, attribute; 48, argument_list; 49, attribute; 50, argument_list; 51, assignment; 52, assignment; 53, identifier:np; 54, identifier:abs; 55, binary_operator:configs[:, 1] - configs[:, 0]; 56, attribute; 57, argument_list; 58, pair; 59, identifier:np; 60, identifier:unique; 61, identifier:config_current_skips; 62, subscript; 63, identifier:astype; 64, identifier:int; 65, identifier:indices; 66, subscript; 67, subscript; 68, subscript; 69, subscript; 70, subscript; 71, identifier:np; 72, identifier:isnan; 73, identifier:config_current_skips; 74, integer:0; 75, list; 76, identifier:available_skips_raw; 77, unary_operator; 78, call; 79, integer:0; 80, identifier:dd_configs_sorted; 81, binary_operator:skip - 1; 82, identifier:dd_indices_all; 83, identifier:indices; 84, identifier:configs; 85, slice; 86, integer:1; 87, identifier:configs; 88, slice; 89, integer:0; 90, call; 91, attribute; 92, argument_list; 93, identifier:skip; 94, integer:1; 95, attribute; 96, argument_list; 97, identifier:np; 98, identifier:where; 99, comparison_operator:config_current_skips == skip; 100, identifier:np; 101, identifier:isnan; 102, identifier:available_skips_raw; 103, identifier:config_current_skips; 104, identifier:skip | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 7, 17; 8, 18; 9, 19; 9, 20; 11, 21; 12, 22; 14, 23; 15, 24; 15, 25; 15, 26; 16, 27; 18, 28; 18, 29; 19, 30; 19, 31; 20, 32; 21, 33; 21, 34; 22, 35; 22, 36; 23, 37; 23, 38; 26, 39; 26, 40; 29, 41; 29, 42; 30, 43; 30, 44; 31, 45; 32, 46; 34, 47; 34, 48; 36, 49; 36, 50; 39, 51; 40, 52; 41, 53; 41, 54; 42, 55; 45, 56; 45, 57; 46, 58; 47, 59; 47, 60; 48, 61; 49, 62; 49, 63; 50, 64; 51, 65; 51, 66; 52, 67; 52, 68; 55, 69; 55, 70; 56, 71; 56, 72; 57, 73; 58, 74; 58, 75; 62, 76; 62, 77; 66, 78; 66, 79; 67, 80; 67, 81; 68, 82; 68, 83; 69, 84; 69, 85; 69, 86; 70, 87; 70, 88; 70, 89; 77, 90; 78, 91; 78, 92; 81, 93; 81, 94; 90, 95; 90, 96; 91, 97; 91, 98; 92, 99; 95, 100; 95, 101; 96, 102; 99, 103; 99, 104 | def _sort_dd_skips(configs, dd_indices_all):
"""Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with the skip as keys, and arrays/lists with indices to
these skips.
"""
config_current_skips = np.abs(configs[:, 1] - configs[:, 0])
if np.all(np.isnan(config_current_skips)):
return {0: []}
# determine skips
available_skips_raw = np.unique(config_current_skips)
available_skips = available_skips_raw[
~np.isnan(available_skips_raw)
].astype(int)
# now determine the configurations
dd_configs_sorted = {}
for skip in available_skips:
indices = np.where(config_current_skips == skip)[0]
dd_configs_sorted[skip - 1] = dd_indices_all[indices]
return dd_configs_sorted |
0, module; 1, function_definition; 2, function_name:plot_pseudodepths; 3, parameters; 4, block; 5, identifier:configs; 6, identifier:nr_electrodes; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, dictionary_splat_pattern; 12, expression_statement; 13, comment:# for each configuration type we have different ways of computing; 14, comment:# pseudodepths; 15, expression_statement; 16, expression_statement; 17, comment:# sort the configurations into the various types of configurations; 18, expression_statement; 19, expression_statement; 20, comment:# loop through all measurement types; 21, expression_statement; 22, expression_statement; 23, for_statement; 24, if_statement; 25, identifier:spacing; 26, integer:1; 27, identifier:grid; 28, None; 29, identifier:ctypes; 30, None; 31, identifier:dd_merge; 32, False; 33, identifier:kwargs; 34, comment:"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
configs: :class:`numpy.ndarray`
Nx4 array containing the quadrupoles for different measurements
nr_electrodes: int
The overall number of electrodes of the dataset. This is used to plot
the surface electrodes
spacing: float, optional
assumed distance between electrodes. Default=1
grid: crtomo.grid.crt_grid instance, optional
grid instance. Used to infer real electrode positions
ctypes: list of strings, optional
a list of configuration types that will be plotted. All
configurations that can not be sorted into these types will not be
plotted! Possible types:
* dd
* schlumberger
dd_merge: bool, optional
if True, merge all skips. Otherwise, generate individual plots for
each skip
Returns
-------
figs: matplotlib.figure.Figure instance or list of Figure instances
if only one type was plotted, then the figure instance is returned.
Otherwise, return a list of figure instances.
axes: axes object or list of axes ojects
plot axes
Examples
--------
.. plot::
:include-source:
from reda.plotters.plots2d import plot_pseudodepths
# define a few measurements
import numpy as np
configs = np.array((
(1, 2, 4, 3),
(1, 2, 5, 4),
(1, 2, 6, 5),
(2, 3, 5, 4),
(2, 3, 6, 5),
(3, 4, 6, 5),
))
# plot
fig, axes = plot_pseudodepths(configs, nr_electrodes=6, spacing=1,
ctypes=['dd', ])
.. plot::
:include-source:
from reda.plotters.plots2d import plot_pseudodepths
# define a few measurements
import numpy as np
configs = np.array((
(4, 7, 5, 6),
(3, 8, 5, 6),
(2, 9, 5, 6),
(1, 10, 5, 6),
))
# plot
fig, axes = plot_pseudodepths(configs, nr_electrodes=10, spacing=1,
ctypes=['schlumberger', ])
"""; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, assignment; 40, assignment; 41, identifier:key; 42, call; 43, block; 44, comparison_operator:len(figs) == 1; 45, block; 46, else_clause; 47, identifier:pseudo_d_functions; 48, dictionary; 49, identifier:titles; 50, dictionary; 51, identifier:only_types; 52, boolean_operator; 53, identifier:results; 54, call; 55, identifier:figs; 56, list; 57, identifier:axes; 58, list; 59, identifier:sorted; 60, argument_list; 61, expression_statement; 62, if_statement; 63, expression_statement; 64, comment:# it is possible that we want to generate multiple plots for one; 65, comment:# type of measurement, i.e., to separate skips of dipole-dipole; 66, comment:# measurements. Therefore we generate two lists:; 67, comment:# 1) list of list of indices to plot; 68, comment:# 2) corresponding labels; 69, if_statement; 70, expression_statement; 71, comment:# generate plots; 72, for_statement; 73, call; 74, integer:1; 75, return_statement; 76, block; 77, pair; 78, pair; 79, pair; 80, pair; 81, pair; 82, pair; 83, identifier:ctypes; 84, list; 85, attribute; 86, argument_list; 87, call; 88, call; 89, comparison_operator:key == 'not_sorted'; 90, block; 91, assignment; 92, boolean_operator; 93, block; 94, else_clause; 95, assignment; 96, pattern_list; 97, call; 98, block; 99, identifier:len; 100, argument_list; 101, expression_list; 102, return_statement; 103, string; 104, identifier:_pseudodepths_dd_simple; 105, string; 106, identifier:_pseudodepths_schlumberger; 107, string; 108, identifier:_pseudodepths_wenner; 109, string; 110, string; 111, string; 112, string; 113, string; 114, string; 115, string; 116, identifier:fT; 117, identifier:filter; 118, identifier:configs; 119, keyword_argument; 120, attribute; 121, argument_list; 122, identifier:print; 123, argument_list; 124, identifier:key; 125, string; 126, continue_statement; 127, identifier:index_dict; 128, subscript; 129, comparison_operator:key == 'dd'; 130, not_operator; 131, expression_statement; 132, expression_statement; 133, for_statement; 134, comment:# merge all indices; 135, block; 136, identifier:grid; 137, None; 138, identifier:indices; 139, identifier:label_add; 140, identifier:zip; 141, argument_list; 142, if_statement; 143, expression_statement; 144, expression_statement; 145, expression_statement; 146, expression_statement; 147, comment:# plot electrodes; 148, if_statement; 149, expression_statement; 150, expression_statement; 151, expression_statement; 152, expression_statement; 153, expression_statement; 154, expression_statement; 155, expression_statement; 156, identifier:figs; 157, subscript; 158, subscript; 159, expression_list; 160, string_content:dd; 161, string_content:schlumberger; 162, string_content:wenner; 163, string_content:dd; 164, string_content:dipole-dipole configurations; 165, string_content:schlumberger; 166, string_content:Schlumberger configurations; 167, string_content:wenner; 168, string_content:Wenner configurations; 169, string_content:dd; 170, identifier:settings; 171, dictionary; 172, identifier:results; 173, identifier:keys; 174, string; 175, identifier:key; 176, string_content:not_sorted; 177, identifier:results; 178, identifier:key; 179, identifier:key; 180, string; 181, identifier:dd_merge; 182, assignment; 183, assignment; 184, identifier:skip; 185, call; 186, block; 187, expression_statement; 188, expression_statement; 189, expression_statement; 190, identifier:plot_list; 191, identifier:labels_add; 192, comparison_operator:len(indices) == 0; 193, block; 194, assignment; 195, assignment; 196, assignment; 197, call; 198, comparison_operator:grid is not None; 199, block; 200, else_clause; 201, call; 202, call; 203, call; 204, call; 205, call; 206, call; 207, call; 208, identifier:figs; 209, integer:0; 210, identifier:axes; 211, integer:0; 212, identifier:figs; 213, identifier:axes; 214, pair; 215, string_content:plotting:; 216, string_content:dd; 217, identifier:plot_list; 218, list; 219, identifier:labels_add; 220, list; 221, identifier:sorted; 222, argument_list; 223, expression_statement; 224, expression_statement; 225, assignment; 226, call; 227, assignment; 228, call; 229, integer:0; 230, continue_statement; 231, identifier:ddc; 232, subscript; 233, pattern_list; 234, call; 235, pattern_list; 236, call; 237, attribute; 238, argument_list; 239, identifier:grid; 240, None; 241, expression_statement; 242, expression_statement; 243, block; 244, attribute; 245, argument_list; 246, attribute; 247, argument_list; 248, attribute; 249, argument_list; 250, attribute; 251, argument_list; 252, attribute; 253, argument_list; 254, attribute; 255, argument_list; 256, attribute; 257, argument_list; 258, string; 259, identifier:only_types; 260, call; 261, call; 262, call; 263, identifier:plot_list; 264, list; 265, identifier:print; 266, argument_list; 267, identifier:labels_add; 268, list; 269, identifier:len; 270, argument_list; 271, identifier:configs; 272, identifier:indices; 273, identifier:px; 274, identifier:pz; 275, subscript; 276, argument_list; 277, identifier:fig; 278, identifier:ax; 279, attribute; 280, argument_list; 281, identifier:ax; 282, identifier:scatter; 283, identifier:px; 284, identifier:pz; 285, keyword_argument; 286, keyword_argument; 287, assignment; 288, call; 289, expression_statement; 290, identifier:ax; 291, identifier:set_title; 292, binary_operator:titles[key] + label_add; 293, identifier:ax; 294, identifier:set_aspect; 295, string; 296, identifier:ax; 297, identifier:set_xlabel; 298, string; 299, identifier:ax; 300, identifier:set_ylabel; 301, string; 302, identifier:fig; 303, identifier:tight_layout; 304, identifier:figs; 305, identifier:append; 306, identifier:fig; 307, identifier:axes; 308, identifier:append; 309, identifier:ax; 310, string_content:only_types; 311, attribute; 312, argument_list; 313, attribute; 314, argument_list; 315, attribute; 316, argument_list; 317, call; 318, string; 319, identifier:plot_list; 320, string; 321, identifier:indices; 322, identifier:pseudo_d_functions; 323, identifier:key; 324, identifier:ddc; 325, identifier:spacing; 326, identifier:grid; 327, identifier:plt; 328, identifier:subplots; 329, keyword_argument; 330, identifier:color; 331, string; 332, identifier:alpha; 333, float:0.5; 334, identifier:electrodes; 335, call; 336, attribute; 337, argument_list; 338, call; 339, subscript; 340, identifier:label_add; 341, string_content:equal; 342, string_content:x [m]; 343, string_content:x [z]; 344, identifier:index_dict; 345, identifier:keys; 346, identifier:plot_list; 347, identifier:append; 348, subscript; 349, identifier:labels_add; 350, identifier:append; 351, call; 352, attribute; 353, argument_list; 354, string_content:schlumberger; 355, identifier:figsize; 356, tuple; 357, string_content:k; 358, attribute; 359, argument_list; 360, identifier:ax; 361, identifier:scatter; 362, subscript; 363, subscript; 364, keyword_argument; 365, keyword_argument; 366, attribute; 367, argument_list; 368, identifier:titles; 369, identifier:key; 370, identifier:index_dict; 371, identifier:skip; 372, attribute; 373, argument_list; 374, identifier:np; 375, identifier:hstack; 376, call; 377, binary_operator:15 / 2.54; 378, binary_operator:5 / 2.54; 379, identifier:grid; 380, identifier:get_electrode_positions; 381, identifier:electrodes; 382, slice; 383, integer:0; 384, identifier:electrodes; 385, slice; 386, integer:1; 387, identifier:color; 388, string; 389, identifier:label; 390, string; 391, identifier:ax; 392, identifier:scatter; 393, binary_operator:np.arange(0, nr_electrodes) * spacing; 394, call; 395, keyword_argument; 396, keyword_argument; 397, string; 398, identifier:format; 399, identifier:skip; 400, attribute; 401, argument_list; 402, integer:15; 403, float:2.54; 404, integer:5; 405, float:2.54; 406, string_content:b; 407, string_content:electrodes; 408, call; 409, identifier:spacing; 410, attribute; 411, argument_list; 412, identifier:color; 413, string; 414, identifier:label; 415, string; 416, string_content:- skip {0}; 417, identifier:index_dict; 418, identifier:values; 419, attribute; 420, argument_list; 421, identifier:np; 422, identifier:zeros; 423, identifier:nr_electrodes; 424, string_content:b; 425, string_content:electrodes; 426, identifier:np; 427, identifier:arange; 428, integer:0; 429, identifier:nr_electrodes | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 7, 25; 7, 26; 8, 27; 8, 28; 9, 29; 9, 30; 10, 31; 10, 32; 11, 33; 12, 34; 15, 35; 16, 36; 18, 37; 19, 38; 21, 39; 22, 40; 23, 41; 23, 42; 23, 43; 24, 44; 24, 45; 24, 46; 35, 47; 35, 48; 36, 49; 36, 50; 37, 51; 37, 52; 38, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 42, 59; 42, 60; 43, 61; 43, 62; 43, 63; 43, 64; 43, 65; 43, 66; 43, 67; 43, 68; 43, 69; 43, 70; 43, 71; 43, 72; 44, 73; 44, 74; 45, 75; 46, 76; 48, 77; 48, 78; 48, 79; 50, 80; 50, 81; 50, 82; 52, 83; 52, 84; 54, 85; 54, 86; 60, 87; 61, 88; 62, 89; 62, 90; 63, 91; 69, 92; 69, 93; 69, 94; 70, 95; 72, 96; 72, 97; 72, 98; 73, 99; 73, 100; 75, 101; 76, 102; 77, 103; 77, 104; 78, 105; 78, 106; 79, 107; 79, 108; 80, 109; 80, 110; 81, 111; 81, 112; 82, 113; 82, 114; 84, 115; 85, 116; 85, 117; 86, 118; 86, 119; 87, 120; 87, 121; 88, 122; 88, 123; 89, 124; 89, 125; 90, 126; 91, 127; 91, 128; 92, 129; 92, 130; 93, 131; 93, 132; 93, 133; 94, 134; 94, 135; 95, 136; 95, 137; 96, 138; 96, 139; 97, 140; 97, 141; 98, 142; 98, 143; 98, 144; 98, 145; 98, 146; 98, 147; 98, 148; 98, 149; 98, 150; 98, 151; 98, 152; 98, 153; 98, 154; 98, 155; 100, 156; 101, 157; 101, 158; 102, 159; 103, 160; 105, 161; 107, 162; 109, 163; 110, 164; 111, 165; 112, 166; 113, 167; 114, 168; 115, 169; 119, 170; 119, 171; 120, 172; 120, 173; 123, 174; 123, 175; 125, 176; 128, 177; 128, 178; 129, 179; 129, 180; 130, 181; 131, 182; 132, 183; 133, 184; 133, 185; 133, 186; 135, 187; 135, 188; 135, 189; 141, 190; 141, 191; 142, 192; 142, 193; 143, 194; 144, 195; 145, 196; 146, 197; 148, 198; 148, 199; 148, 200; 149, 201; 150, 202; 151, 203; 152, 204; 153, 205; 154, 206; 155, 207; 157, 208; 157, 209; 158, 210; 158, 211; 159, 212; 159, 213; 171, 214; 174, 215; 180, 216; 182, 217; 182, 218; 183, 219; 183, 220; 185, 221; 185, 222; 186, 223; 186, 224; 187, 225; 188, 226; 189, 227; 192, 228; 192, 229; 193, 230; 194, 231; 194, 232; 195, 233; 195, 234; 196, 235; 196, 236; 197, 237; 197, 238; 198, 239; 198, 240; 199, 241; 199, 242; 200, 243; 201, 244; 201, 245; 202, 246; 202, 247; 203, 248; 203, 249; 204, 250; 204, 251; 205, 252; 205, 253; 206, 254; 206, 255; 207, 256; 207, 257; 214, 258; 214, 259; 222, 260; 223, 261; 224, 262; 225, 263; 225, 264; 226, 265; 226, 266; 227, 267; 227, 268; 228, 269; 228, 270; 232, 271; 232, 272; 233, 273; 233, 274; 234, 275; 234, 276; 235, 277; 235, 278; 236, 279; 236, 280; 237, 281; 237, 282; 238, 283; 238, 284; 238, 285; 238, 286; 241, 287; 242, 288; 243, 289; 244, 290; 244, 291; 245, 292; 246, 293; 246, 294; 247, 295; 248, 296; 248, 297; 249, 298; 250, 299; 250, 300; 251, 301; 252, 302; 252, 303; 254, 304; 254, 305; 255, 306; 256, 307; 256, 308; 257, 309; 258, 310; 260, 311; 260, 312; 261, 313; 261, 314; 262, 315; 262, 316; 264, 317; 266, 318; 266, 319; 268, 320; 270, 321; 275, 322; 275, 323; 276, 324; 276, 325; 276, 326; 279, 327; 279, 328; 280, 329; 285, 330; 285, 331; 286, 332; 286, 333; 287, 334; 287, 335; 288, 336; 288, 337; 289, 338; 292, 339; 292, 340; 295, 341; 298, 342; 301, 343; 311, 344; 311, 345; 313, 346; 313, 347; 314, 348; 315, 349; 315, 350; 316, 351; 317, 352; 317, 353; 318, 354; 329, 355; 329, 356; 331, 357; 335, 358; 335, 359; 336, 360; 336, 361; 337, 362; 337, 363; 337, 364; 337, 365; 338, 366; 338, 367; 339, 368; 339, 369; 348, 370; 348, 371; 351, 372; 351, 373; 352, 374; 352, 375; 353, 376; 356, 377; 356, 378; 358, 379; 358, 380; 362, 381; 362, 382; 362, 383; 363, 384; 363, 385; 363, 386; 364, 387; 364, 388; 365, 389; 365, 390; 366, 391; 366, 392; 367, 393; 367, 394; 367, 395; 367, 396; 372, 397; 372, 398; 373, 399; 376, 400; 376, 401; 377, 402; 377, 403; 378, 404; 378, 405; 388, 406; 390, 407; 393, 408; 393, 409; 394, 410; 394, 411; 395, 412; 395, 413; 396, 414; 396, 415; 397, 416; 400, 417; 400, 418; 408, 419; 408, 420; 410, 421; 410, 422; 411, 423; 413, 424; 415, 425; 419, 426; 419, 427; 420, 428; 420, 429 | def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
configs: :class:`numpy.ndarray`
Nx4 array containing the quadrupoles for different measurements
nr_electrodes: int
The overall number of electrodes of the dataset. This is used to plot
the surface electrodes
spacing: float, optional
assumed distance between electrodes. Default=1
grid: crtomo.grid.crt_grid instance, optional
grid instance. Used to infer real electrode positions
ctypes: list of strings, optional
a list of configuration types that will be plotted. All
configurations that can not be sorted into these types will not be
plotted! Possible types:
* dd
* schlumberger
dd_merge: bool, optional
if True, merge all skips. Otherwise, generate individual plots for
each skip
Returns
-------
figs: matplotlib.figure.Figure instance or list of Figure instances
if only one type was plotted, then the figure instance is returned.
Otherwise, return a list of figure instances.
axes: axes object or list of axes ojects
plot axes
Examples
--------
.. plot::
:include-source:
from reda.plotters.plots2d import plot_pseudodepths
# define a few measurements
import numpy as np
configs = np.array((
(1, 2, 4, 3),
(1, 2, 5, 4),
(1, 2, 6, 5),
(2, 3, 5, 4),
(2, 3, 6, 5),
(3, 4, 6, 5),
))
# plot
fig, axes = plot_pseudodepths(configs, nr_electrodes=6, spacing=1,
ctypes=['dd', ])
.. plot::
:include-source:
from reda.plotters.plots2d import plot_pseudodepths
# define a few measurements
import numpy as np
configs = np.array((
(4, 7, 5, 6),
(3, 8, 5, 6),
(2, 9, 5, 6),
(1, 10, 5, 6),
))
# plot
fig, axes = plot_pseudodepths(configs, nr_electrodes=10, spacing=1,
ctypes=['schlumberger', ])
"""
# for each configuration type we have different ways of computing
# pseudodepths
pseudo_d_functions = {
'dd': _pseudodepths_dd_simple,
'schlumberger': _pseudodepths_schlumberger,
'wenner': _pseudodepths_wenner,
}
titles = {
'dd': 'dipole-dipole configurations',
'schlumberger': 'Schlumberger configurations',
'wenner': 'Wenner configurations',
}
# sort the configurations into the various types of configurations
only_types = ctypes or ['dd', ]
results = fT.filter(configs, settings={'only_types': only_types, })
# loop through all measurement types
figs = []
axes = []
for key in sorted(results.keys()):
print('plotting: ', key)
if key == 'not_sorted':
continue
index_dict = results[key]
# it is possible that we want to generate multiple plots for one
# type of measurement, i.e., to separate skips of dipole-dipole
# measurements. Therefore we generate two lists:
# 1) list of list of indices to plot
# 2) corresponding labels
if key == 'dd' and not dd_merge:
plot_list = []
labels_add = []
for skip in sorted(index_dict.keys()):
plot_list.append(index_dict[skip])
labels_add.append(' - skip {0}'.format(skip))
else:
# merge all indices
plot_list = [np.hstack(index_dict.values()), ]
print('schlumberger', plot_list)
labels_add = ['', ]
grid = None
# generate plots
for indices, label_add in zip(plot_list, labels_add):
if len(indices) == 0:
continue
ddc = configs[indices]
px, pz = pseudo_d_functions[key](ddc, spacing, grid)
fig, ax = plt.subplots(figsize=(15 / 2.54, 5 / 2.54))
ax.scatter(px, pz, color='k', alpha=0.5)
# plot electrodes
if grid is not None:
electrodes = grid.get_electrode_positions()
ax.scatter(
electrodes[:, 0],
electrodes[:, 1],
color='b',
label='electrodes', )
else:
ax.scatter(
np.arange(0, nr_electrodes) * spacing,
np.zeros(nr_electrodes),
color='b',
label='electrodes', )
ax.set_title(titles[key] + label_add)
ax.set_aspect('equal')
ax.set_xlabel('x [m]')
ax.set_ylabel('x [z]')
fig.tight_layout()
figs.append(fig)
axes.append(ax)
if len(figs) == 1:
return figs[0], axes[0]
else:
return figs, axes |
0, module; 1, function_definition; 2, function_name:gen_reciprocals; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, comment:# Switch AB and MN; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, comment:# # Sort by current dipoles; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, return_statement; 17, identifier:append; 18, False; 19, comment:""" Generate reciprocal configurations, sort by AB, and optionally
append to configurations.
Parameters
----------
append : bool
Append reciprocals to configs (the default is False).
Examples
--------
>>> cfgs = ConfigManager(nr_of_electrodes=5)
>>> nor = cfgs.gen_dipole_dipole(skipc=0)
>>> rec = cfgs.gen_reciprocals(append=True)
>>> print(cfgs.configs)
[[1 2 3 4]
[1 2 4 5]
[2 3 4 5]
[3 4 1 2]
[4 5 1 2]
[4 5 2 3]]
"""; 20, assignment; 21, assignment; 22, assignment; 23, assignment; 24, assignment; 25, identifier:append; 26, block; 27, identifier:reciprocals; 28, identifier:reciprocals; 29, subscript; 30, subscript; 31, call; 32, subscript; 33, call; 34, identifier:ind; 35, call; 36, identifier:reciprocals; 37, subscript; 38, expression_statement; 39, call; 40, slice; 41, slice; 42, identifier:reciprocals; 43, slice; 44, slice; 45, attribute; 46, argument_list; 47, identifier:reciprocals; 48, slice; 49, slice; 50, attribute; 51, argument_list; 52, attribute; 53, argument_list; 54, identifier:reciprocals; 55, identifier:ind; 56, assignment; 57, attribute; 58, argument_list; 59, unary_operator; 60, integer:0; 61, integer:2; 62, identifier:np; 63, identifier:sort; 64, subscript; 65, keyword_argument; 66, integer:2; 67, integer:4; 68, identifier:np; 69, identifier:sort; 70, subscript; 71, keyword_argument; 72, identifier:np; 73, identifier:lexsort; 74, tuple; 75, attribute; 76, call; 77, attribute; 78, identifier:copy; 79, integer:1; 80, identifier:reciprocals; 81, slice; 82, slice; 83, identifier:axis; 84, integer:1; 85, identifier:reciprocals; 86, slice; 87, slice; 88, identifier:axis; 89, integer:1; 90, subscript; 91, subscript; 92, subscript; 93, subscript; 94, identifier:self; 95, identifier:configs; 96, attribute; 97, argument_list; 98, identifier:self; 99, identifier:configs; 100, integer:0; 101, integer:2; 102, integer:2; 103, integer:4; 104, identifier:reciprocals; 105, slice; 106, integer:3; 107, identifier:reciprocals; 108, slice; 109, integer:2; 110, identifier:reciprocals; 111, slice; 112, integer:1; 113, identifier:reciprocals; 114, slice; 115, integer:0; 116, identifier:np; 117, identifier:vstack; 118, tuple; 119, attribute; 120, identifier:reciprocals; 121, identifier:self; 122, identifier:configs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 6, 17; 6, 18; 7, 19; 9, 20; 10, 21; 11, 22; 13, 23; 14, 24; 15, 25; 15, 26; 16, 27; 20, 28; 20, 29; 21, 30; 21, 31; 22, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 26, 38; 29, 39; 29, 40; 29, 41; 30, 42; 30, 43; 30, 44; 31, 45; 31, 46; 32, 47; 32, 48; 32, 49; 33, 50; 33, 51; 35, 52; 35, 53; 37, 54; 37, 55; 38, 56; 39, 57; 39, 58; 41, 59; 44, 60; 44, 61; 45, 62; 45, 63; 46, 64; 46, 65; 49, 66; 49, 67; 50, 68; 50, 69; 51, 70; 51, 71; 52, 72; 52, 73; 53, 74; 56, 75; 56, 76; 57, 77; 57, 78; 59, 79; 64, 80; 64, 81; 64, 82; 65, 83; 65, 84; 70, 85; 70, 86; 70, 87; 71, 88; 71, 89; 74, 90; 74, 91; 74, 92; 74, 93; 75, 94; 75, 95; 76, 96; 76, 97; 77, 98; 77, 99; 82, 100; 82, 101; 87, 102; 87, 103; 90, 104; 90, 105; 90, 106; 91, 107; 91, 108; 91, 109; 92, 110; 92, 111; 92, 112; 93, 113; 93, 114; 93, 115; 96, 116; 96, 117; 97, 118; 118, 119; 118, 120; 119, 121; 119, 122 | def gen_reciprocals(self, append=False):
""" Generate reciprocal configurations, sort by AB, and optionally
append to configurations.
Parameters
----------
append : bool
Append reciprocals to configs (the default is False).
Examples
--------
>>> cfgs = ConfigManager(nr_of_electrodes=5)
>>> nor = cfgs.gen_dipole_dipole(skipc=0)
>>> rec = cfgs.gen_reciprocals(append=True)
>>> print(cfgs.configs)
[[1 2 3 4]
[1 2 4 5]
[2 3 4 5]
[3 4 1 2]
[4 5 1 2]
[4 5 2 3]]
"""
# Switch AB and MN
reciprocals = self.configs.copy()[:, ::-1]
reciprocals[:, 0:2] = np.sort(reciprocals[:, 0:2], axis=1)
reciprocals[:, 2:4] = np.sort(reciprocals[:, 2:4], axis=1)
# # Sort by current dipoles
ind = np.lexsort((reciprocals[:, 3], reciprocals[:, 2],
reciprocals[:, 1], reciprocals[:, 0]))
reciprocals = reciprocals[ind]
if append:
self.configs = np.vstack((self.configs, reciprocals))
return reciprocals |
0, module; 1, function_definition; 2, function_name:load_seit_data; 3, parameters; 4, block; 5, identifier:directory; 6, default_parameter; 7, default_parameter; 8, dictionary_splat_pattern; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, comment:# check that the number of frequencies matches the number of data files; 13, if_statement; 14, comment:# load data; 15, expression_statement; 16, for_statement; 17, expression_statement; 18, return_statement; 19, identifier:frequency_file; 20, string; 21, identifier:data_prefix; 22, string; 23, identifier:kwargs; 24, comment:"""Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : string
input directory
frequency_file : string, optional
file (located in directory) that contains the frequencies
data_prefix: string, optional
for each frequency a corresponding data file must be present in the
input directory. Frequencies and files are matched by sorting the
frequencies AND the filenames, retrieved using glob and the
data_prefix
Returns
-------
df : pandas.DataFrame
A DataFrame suitable for the sEIT container
electrodes : None
No electrode data is imported
topography : None
No topography data is imported
"""; 25, assignment; 26, assignment; 27, comparison_operator:frequencies.size != len(data_files); 28, block; 29, assignment; 30, pattern_list; 31, call; 32, block; 33, assignment; 34, expression_list; 35, string_content:frequencies.dat; 36, string_content:volt_; 37, identifier:frequencies; 38, call; 39, identifier:data_files; 40, call; 41, attribute; 42, call; 43, raise_statement; 44, identifier:data_list; 45, list; 46, identifier:frequency; 47, identifier:filename; 48, identifier:zip; 49, argument_list; 50, expression_statement; 51, expression_statement; 52, expression_statement; 53, identifier:df; 54, call; 55, identifier:df; 56, None; 57, None; 58, attribute; 59, argument_list; 60, identifier:sorted; 61, argument_list; 62, identifier:frequencies; 63, identifier:size; 64, identifier:len; 65, argument_list; 66, call; 67, identifier:frequencies; 68, identifier:data_files; 69, assignment; 70, assignment; 71, call; 72, attribute; 73, argument_list; 74, identifier:np; 75, identifier:loadtxt; 76, binary_operator:directory + os.sep + frequency_file; 77, call; 78, identifier:data_files; 79, identifier:Exception; 80, argument_list; 81, identifier:subdata; 82, call; 83, subscript; 84, identifier:frequency; 85, attribute; 86, argument_list; 87, identifier:pd; 88, identifier:concat; 89, identifier:data_list; 90, binary_operator:directory + os.sep; 91, identifier:frequency_file; 92, identifier:glob; 93, argument_list; 94, string; 95, identifier:load_mod_file; 96, argument_list; 97, identifier:subdata; 98, string; 99, identifier:data_list; 100, identifier:append; 101, identifier:subdata; 102, identifier:directory; 103, attribute; 104, binary_operator:directory + os.sep + data_prefix + '*'; 105, string_content:number of frequencies does not match number of data files; 106, identifier:filename; 107, string_content:frequency; 108, identifier:os; 109, identifier:sep; 110, binary_operator:directory + os.sep + data_prefix; 111, string; 112, binary_operator:directory + os.sep; 113, identifier:data_prefix; 114, string_content:*; 115, identifier:directory; 116, attribute; 117, identifier:os; 118, identifier:sep | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 6, 19; 6, 20; 7, 21; 7, 22; 8, 23; 9, 24; 10, 25; 11, 26; 13, 27; 13, 28; 15, 29; 16, 30; 16, 31; 16, 32; 17, 33; 18, 34; 20, 35; 22, 36; 25, 37; 25, 38; 26, 39; 26, 40; 27, 41; 27, 42; 28, 43; 29, 44; 29, 45; 30, 46; 30, 47; 31, 48; 31, 49; 32, 50; 32, 51; 32, 52; 33, 53; 33, 54; 34, 55; 34, 56; 34, 57; 38, 58; 38, 59; 40, 60; 40, 61; 41, 62; 41, 63; 42, 64; 42, 65; 43, 66; 49, 67; 49, 68; 50, 69; 51, 70; 52, 71; 54, 72; 54, 73; 58, 74; 58, 75; 59, 76; 61, 77; 65, 78; 66, 79; 66, 80; 69, 81; 69, 82; 70, 83; 70, 84; 71, 85; 71, 86; 72, 87; 72, 88; 73, 89; 76, 90; 76, 91; 77, 92; 77, 93; 80, 94; 82, 95; 82, 96; 83, 97; 83, 98; 85, 99; 85, 100; 86, 101; 90, 102; 90, 103; 93, 104; 94, 105; 96, 106; 98, 107; 103, 108; 103, 109; 104, 110; 104, 111; 110, 112; 110, 113; 111, 114; 112, 115; 112, 116; 116, 117; 116, 118 | def load_seit_data(directory, frequency_file='frequencies.dat',
data_prefix='volt_', **kwargs):
"""Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : string
input directory
frequency_file : string, optional
file (located in directory) that contains the frequencies
data_prefix: string, optional
for each frequency a corresponding data file must be present in the
input directory. Frequencies and files are matched by sorting the
frequencies AND the filenames, retrieved using glob and the
data_prefix
Returns
-------
df : pandas.DataFrame
A DataFrame suitable for the sEIT container
electrodes : None
No electrode data is imported
topography : None
No topography data is imported
"""
frequencies = np.loadtxt(directory + os.sep + frequency_file)
data_files = sorted(glob(directory + os.sep + data_prefix + '*'))
# check that the number of frequencies matches the number of data files
if frequencies.size != len(data_files):
raise Exception(
'number of frequencies does not match number of data files')
# load data
data_list = []
for frequency, filename in zip(frequencies, data_files):
subdata = load_mod_file(filename)
subdata['frequency'] = frequency
data_list.append(subdata)
df = pd.concat(data_list)
return df, None, None |
0, module; 1, function_definition; 2, function_name:_query_attr_sort_fn; 3, parameters; 4, block; 5, identifier:self; 6, identifier:attr_val; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, comment:"""Used to order where keys by most selective key first"""; 11, assignment; 12, comparison_operator:attr in self._indexes; 13, block; 14, else_clause; 15, pattern_list; 16, identifier:attr_val; 17, identifier:attr; 18, attribute; 19, expression_statement; 20, if_statement; 21, block; 22, identifier:attr; 23, identifier:v; 24, identifier:self; 25, identifier:_indexes; 26, assignment; 27, comparison_operator:v in idx; 28, block; 29, else_clause; 30, return_statement; 31, identifier:idx; 32, subscript; 33, identifier:v; 34, identifier:idx; 35, return_statement; 36, block; 37, float:1e9; 38, attribute; 39, identifier:attr; 40, call; 41, return_statement; 42, identifier:self; 43, identifier:_indexes; 44, identifier:len; 45, argument_list; 46, integer:0; 47, subscript; 48, identifier:idx; 49, identifier:v | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 9, 13; 9, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 13, 20; 14, 21; 15, 22; 15, 23; 18, 24; 18, 25; 19, 26; 20, 27; 20, 28; 20, 29; 21, 30; 26, 31; 26, 32; 27, 33; 27, 34; 28, 35; 29, 36; 30, 37; 32, 38; 32, 39; 35, 40; 36, 41; 38, 42; 38, 43; 40, 44; 40, 45; 41, 46; 45, 47; 47, 48; 47, 49 | def _query_attr_sort_fn(self, attr_val):
"""Used to order where keys by most selective key first"""
attr, v = attr_val
if attr in self._indexes:
idx = self._indexes[attr]
if v in idx:
return len(idx[v])
else:
return 0
else:
return 1e9 |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:self; 6, identifier:key; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, return_statement; 11, identifier:reverse; 12, False; 13, comment:"""Sort Table in place, using given fields as sort key.
@param key: if this is a string, it is a comma-separated list of field names,
optionally followed by 'desc' to indicate descending sort instead of the
default ascending sort; if a list or tuple, it is a list or tuple of field names
or field names with ' desc' appended; if it is a function, then it is the
function to be used as the sort key function
@param reverse: (default=False) set to True if results should be in reverse order
@type reverse: bool
@return: self
"""; 14, call; 15, block; 16, else_clause; 17, identifier:self; 18, identifier:isinstance; 19, argument_list; 20, if_statement; 21, expression_statement; 22, comment:# special optimization if all orders are ascending or descending; 23, if_statement; 24, comment:# sorting given a sort key function; 25, block; 26, identifier:key; 27, tuple; 28, call; 29, block; 30, else_clause; 31, assignment; 32, call; 33, block; 34, elif_clause; 35, else_clause; 36, expression_statement; 37, expression_statement; 38, identifier:basestring; 39, identifier:list; 40, identifier:tuple; 41, identifier:isinstance; 42, argument_list; 43, expression_statement; 44, expression_statement; 45, comment:# attr definitions were already resolved to a sequence by the caller; 46, block; 47, identifier:attrs; 48, list_comprehension; 49, identifier:all; 50, generator_expression; 51, expression_statement; 52, call; 53, block; 54, comment:# mix of ascending and descending sorts, have to do succession of sorts; 55, comment:# leftmost attr is the most primary sort key, so reverse attr_orders to do; 56, comment:# succession of sorts from right to left; 57, block; 58, assignment; 59, call; 60, identifier:key; 61, identifier:basestring; 62, assignment; 63, assignment; 64, if_statement; 65, identifier:attr; 66, for_in_clause; 67, comparison_operator:order == 'asc'; 68, for_in_clause; 69, call; 70, identifier:all; 71, generator_expression; 72, expression_statement; 73, expression_statement; 74, identifier:keyfn; 75, identifier:key; 76, attribute; 77, argument_list; 78, identifier:attrdefs; 79, list_comprehension; 80, identifier:attr_orders; 81, list_comprehension; 82, call; 83, block; 84, else_clause; 85, pattern_list; 86, identifier:attr_orders; 87, identifier:order; 88, string; 89, pattern_list; 90, identifier:attr_orders; 91, attribute; 92, argument_list; 93, comparison_operator:order == 'desc'; 94, for_in_clause; 95, call; 96, call; 97, attribute; 98, identifier:sort; 99, keyword_argument; 100, keyword_argument; 101, call; 102, for_in_clause; 103, subscript; 104, for_in_clause; 105, identifier:isinstance; 106, argument_list; 107, expression_statement; 108, block; 109, identifier:attr; 110, identifier:order; 111, string_content:asc; 112, identifier:attr; 113, identifier:order; 114, attribute; 115, identifier:sort; 116, keyword_argument; 117, keyword_argument; 118, identifier:order; 119, string; 120, pattern_list; 121, identifier:attr_orders; 122, attribute; 123, argument_list; 124, identifier:do_all; 125, generator_expression; 126, identifier:self; 127, identifier:obs; 128, identifier:key; 129, identifier:keyfn; 130, identifier:reverse; 131, identifier:reverse; 132, attribute; 133, argument_list; 134, identifier:s; 135, call; 136, parenthesized_expression; 137, slice; 138, identifier:a; 139, identifier:attrdefs; 140, subscript; 141, identifier:basestring; 142, assignment; 143, expression_statement; 144, identifier:self; 145, identifier:obs; 146, identifier:key; 147, call; 148, identifier:reverse; 149, identifier:reverse; 150, string_content:desc; 151, identifier:attr; 152, identifier:order; 153, attribute; 154, identifier:sort; 155, keyword_argument; 156, keyword_argument; 157, call; 158, for_in_clause; 159, identifier:s; 160, identifier:strip; 161, attribute; 162, argument_list; 163, binary_operator:a.split()+['asc', ]; 164, integer:2; 165, identifier:key; 166, integer:0; 167, identifier:attr_orders; 168, list_comprehension; 169, assignment; 170, identifier:attrgetter; 171, argument_list; 172, identifier:self; 173, identifier:obs; 174, identifier:key; 175, call; 176, identifier:reverse; 177, not_operator; 178, attribute; 179, argument_list; 180, pattern_list; 181, call; 182, identifier:key; 183, identifier:split; 184, string; 185, call; 186, list; 187, subscript; 188, for_in_clause; 189, identifier:attr_orders; 190, identifier:key; 191, list_splat; 192, identifier:attrgetter; 193, argument_list; 194, identifier:reverse; 195, attribute; 196, identifier:sort; 197, keyword_argument; 198, keyword_argument; 199, identifier:attr; 200, identifier:order; 201, identifier:reversed; 202, argument_list; 203, string_content:,; 204, attribute; 205, argument_list; 206, string; 207, parenthesized_expression; 208, slice; 209, identifier:a; 210, identifier:key; 211, identifier:attrs; 212, list_splat; 213, identifier:self; 214, identifier:obs; 215, identifier:key; 216, call; 217, identifier:reverse; 218, parenthesized_expression; 219, identifier:attr_orders; 220, identifier:a; 221, identifier:split; 222, string_content:asc; 223, binary_operator:a.split()+['asc', ]; 224, integer:2; 225, identifier:attrs; 226, identifier:attrgetter; 227, argument_list; 228, comparison_operator:order == "desc"; 229, call; 230, list; 231, identifier:attr; 232, identifier:order; 233, string:"desc"; 234, attribute; 235, argument_list; 236, string; 237, identifier:a; 238, identifier:split; 239, string_content:asc | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 7, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 14, 18; 14, 19; 15, 20; 15, 21; 15, 22; 15, 23; 16, 24; 16, 25; 19, 26; 19, 27; 20, 28; 20, 29; 20, 30; 21, 31; 23, 32; 23, 33; 23, 34; 23, 35; 25, 36; 25, 37; 27, 38; 27, 39; 27, 40; 28, 41; 28, 42; 29, 43; 29, 44; 30, 45; 30, 46; 31, 47; 31, 48; 32, 49; 32, 50; 33, 51; 34, 52; 34, 53; 35, 54; 35, 55; 35, 56; 35, 57; 36, 58; 37, 59; 42, 60; 42, 61; 43, 62; 44, 63; 46, 64; 48, 65; 48, 66; 50, 67; 50, 68; 51, 69; 52, 70; 52, 71; 53, 72; 57, 73; 58, 74; 58, 75; 59, 76; 59, 77; 62, 78; 62, 79; 63, 80; 63, 81; 64, 82; 64, 83; 64, 84; 66, 85; 66, 86; 67, 87; 67, 88; 68, 89; 68, 90; 69, 91; 69, 92; 71, 93; 71, 94; 72, 95; 73, 96; 76, 97; 76, 98; 77, 99; 77, 100; 79, 101; 79, 102; 81, 103; 81, 104; 82, 105; 82, 106; 83, 107; 84, 108; 85, 109; 85, 110; 88, 111; 89, 112; 89, 113; 91, 114; 91, 115; 92, 116; 92, 117; 93, 118; 93, 119; 94, 120; 94, 121; 95, 122; 95, 123; 96, 124; 96, 125; 97, 126; 97, 127; 99, 128; 99, 129; 100, 130; 100, 131; 101, 132; 101, 133; 102, 134; 102, 135; 103, 136; 103, 137; 104, 138; 104, 139; 106, 140; 106, 141; 107, 142; 108, 143; 114, 144; 114, 145; 116, 146; 116, 147; 117, 148; 117, 149; 119, 150; 120, 151; 120, 152; 122, 153; 122, 154; 123, 155; 123, 156; 125, 157; 125, 158; 132, 159; 132, 160; 135, 161; 135, 162; 136, 163; 137, 164; 140, 165; 140, 166; 142, 167; 142, 168; 143, 169; 147, 170; 147, 171; 153, 172; 153, 173; 155, 174; 155, 175; 156, 176; 156, 177; 157, 178; 157, 179; 158, 180; 158, 181; 161, 182; 161, 183; 162, 184; 163, 185; 163, 186; 168, 187; 168, 188; 169, 189; 169, 190; 171, 191; 175, 192; 175, 193; 177, 194; 178, 195; 178, 196; 179, 197; 179, 198; 180, 199; 180, 200; 181, 201; 181, 202; 184, 203; 185, 204; 185, 205; 186, 206; 187, 207; 187, 208; 188, 209; 188, 210; 191, 211; 193, 212; 195, 213; 195, 214; 197, 215; 197, 216; 198, 217; 198, 218; 202, 219; 204, 220; 204, 221; 206, 222; 207, 223; 208, 224; 212, 225; 216, 226; 216, 227; 218, 228; 223, 229; 223, 230; 227, 231; 228, 232; 228, 233; 229, 234; 229, 235; 230, 236; 234, 237; 234, 238; 236, 239 | def sort(self, key, reverse=False):
"""Sort Table in place, using given fields as sort key.
@param key: if this is a string, it is a comma-separated list of field names,
optionally followed by 'desc' to indicate descending sort instead of the
default ascending sort; if a list or tuple, it is a list or tuple of field names
or field names with ' desc' appended; if it is a function, then it is the
function to be used as the sort key function
@param reverse: (default=False) set to True if results should be in reverse order
@type reverse: bool
@return: self
"""
if isinstance(key, (basestring, list, tuple)):
if isinstance(key, basestring):
attrdefs = [s.strip() for s in key.split(',')]
attr_orders = [(a.split()+['asc', ])[:2] for a in attrdefs]
else:
# attr definitions were already resolved to a sequence by the caller
if isinstance(key[0], basestring):
attr_orders = [(a.split()+['asc', ])[:2] for a in key]
else:
attr_orders = key
attrs = [attr for attr, order in attr_orders]
# special optimization if all orders are ascending or descending
if all(order == 'asc' for attr, order in attr_orders):
self.obs.sort(key=attrgetter(*attrs), reverse=reverse)
elif all(order == 'desc' for attr, order in attr_orders):
self.obs.sort(key=attrgetter(*attrs), reverse=not reverse)
else:
# mix of ascending and descending sorts, have to do succession of sorts
# leftmost attr is the most primary sort key, so reverse attr_orders to do
# succession of sorts from right to left
do_all(self.obs.sort(key=attrgetter(attr), reverse=(order == "desc"))
for attr, order in reversed(attr_orders))
else:
# sorting given a sort key function
keyfn = key
self.obs.sort(key=keyfn, reverse=reverse)
return self |
0, module; 1, function_definition; 2, function_name:sort_window_ids; 3, parameters; 4, block; 5, identifier:winid_list; 6, default_parameter; 7, expression_statement; 8, import_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:order; 13, string; 14, comment:"""
Orders window ids by most recently used
"""; 15, aliased_import; 16, assignment; 17, assignment; 18, identifier:sorted_win_ids; 19, string_content:mru; 20, dotted_name; 21, identifier:ut; 22, identifier:winid_order; 23, call; 24, identifier:sorted_win_ids; 25, call; 26, identifier:utool; 27, attribute; 28, argument_list; 29, attribute; 30, argument_list; 31, identifier:XCtrl; 32, identifier:sorted_window_ids; 33, identifier:order; 34, identifier:ut; 35, identifier:isect; 36, identifier:winid_order; 37, identifier:winid_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 13, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 17, 25; 20, 26; 23, 27; 23, 28; 25, 29; 25, 30; 27, 31; 27, 32; 28, 33; 29, 34; 29, 35; 30, 36; 30, 37 | def sort_window_ids(winid_list, order='mru'):
"""
Orders window ids by most recently used
"""
import utool as ut
winid_order = XCtrl.sorted_window_ids(order)
sorted_win_ids = ut.isect(winid_order, winid_list)
return sorted_win_ids |
0, module; 1, function_definition; 2, function_name:glob; 3, parameters; 4, block; 5, identifier:dpath; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, dictionary_splat_pattern; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, return_statement; 18, identifier:pattern; 19, None; 20, identifier:recursive; 21, False; 22, identifier:with_files; 23, True; 24, identifier:with_dirs; 25, True; 26, identifier:maxdepth; 27, None; 28, identifier:exclude_dirs; 29, list; 30, identifier:fullpath; 31, True; 32, identifier:kwargs; 33, comment:r"""
Globs directory for pattern
DEPRICATED:
use pathlib.glob instead
Args:
dpath (str): directory path or pattern
pattern (str or list): pattern or list of patterns
(use only if pattern is not in dpath)
recursive (bool): (default = False)
with_files (bool): (default = True)
with_dirs (bool): (default = True)
maxdepth (None): (default = None)
exclude_dirs (list): (default = [])
Returns:
list: path_list
SeeAlso:
iglob
CommandLine:
python -m utool.util_path --test-glob
python -m utool.util_path --exec-glob:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> from os.path import dirname
>>> import utool as ut
>>> dpath = dirname(ut.__file__)
>>> pattern = '__*.py'
>>> recursive = True
>>> with_files = True
>>> with_dirs = True
>>> maxdepth = None
>>> fullpath = False
>>> exclude_dirs = ['_internal', join(dpath, 'experimental')]
>>> print('exclude_dirs = ' + ut.repr2(exclude_dirs))
>>> path_list = glob(dpath, pattern, recursive, with_files, with_dirs,
>>> maxdepth, exclude_dirs, fullpath)
>>> path_list = sorted(path_list)
>>> result = ('path_list = %s' % (ut.repr3(path_list),))
>>> result = result.replace(r'\\', '/')
>>> print(result)
path_list = [
'__init__.py',
'__main__.py',
'tests/__init__.py',
]
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> dpath = dirname(ut.__file__) + '/__*.py'
>>> path_list = glob(dpath)
>>> result = ('path_list = %s' % (str(path_list),))
>>> print(result)
"""; 34, assignment; 35, assignment; 36, identifier:path_list; 37, identifier:gen; 38, call; 39, identifier:path_list; 40, call; 41, identifier:iglob; 42, argument_list; 43, identifier:list; 44, argument_list; 45, identifier:dpath; 46, identifier:pattern; 47, keyword_argument; 48, keyword_argument; 49, keyword_argument; 50, keyword_argument; 51, keyword_argument; 52, keyword_argument; 53, dictionary_splat; 54, identifier:gen; 55, identifier:recursive; 56, identifier:recursive; 57, identifier:with_files; 58, identifier:with_files; 59, identifier:with_dirs; 60, identifier:with_dirs; 61, identifier:maxdepth; 62, identifier:maxdepth; 63, identifier:fullpath; 64, identifier:fullpath; 65, identifier:exclude_dirs; 66, identifier:exclude_dirs; 67, identifier:kwargs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 4, 14; 4, 15; 4, 16; 4, 17; 6, 18; 6, 19; 7, 20; 7, 21; 8, 22; 8, 23; 9, 24; 9, 25; 10, 26; 10, 27; 11, 28; 11, 29; 12, 30; 12, 31; 13, 32; 14, 33; 15, 34; 16, 35; 17, 36; 34, 37; 34, 38; 35, 39; 35, 40; 38, 41; 38, 42; 40, 43; 40, 44; 42, 45; 42, 46; 42, 47; 42, 48; 42, 49; 42, 50; 42, 51; 42, 52; 42, 53; 44, 54; 47, 55; 47, 56; 48, 57; 48, 58; 49, 59; 49, 60; 50, 61; 50, 62; 51, 63; 51, 64; 52, 65; 52, 66; 53, 67 | def glob(dpath, pattern=None, recursive=False, with_files=True, with_dirs=True,
maxdepth=None, exclude_dirs=[], fullpath=True, **kwargs):
r"""
Globs directory for pattern
DEPRICATED:
use pathlib.glob instead
Args:
dpath (str): directory path or pattern
pattern (str or list): pattern or list of patterns
(use only if pattern is not in dpath)
recursive (bool): (default = False)
with_files (bool): (default = True)
with_dirs (bool): (default = True)
maxdepth (None): (default = None)
exclude_dirs (list): (default = [])
Returns:
list: path_list
SeeAlso:
iglob
CommandLine:
python -m utool.util_path --test-glob
python -m utool.util_path --exec-glob:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> from os.path import dirname
>>> import utool as ut
>>> dpath = dirname(ut.__file__)
>>> pattern = '__*.py'
>>> recursive = True
>>> with_files = True
>>> with_dirs = True
>>> maxdepth = None
>>> fullpath = False
>>> exclude_dirs = ['_internal', join(dpath, 'experimental')]
>>> print('exclude_dirs = ' + ut.repr2(exclude_dirs))
>>> path_list = glob(dpath, pattern, recursive, with_files, with_dirs,
>>> maxdepth, exclude_dirs, fullpath)
>>> path_list = sorted(path_list)
>>> result = ('path_list = %s' % (ut.repr3(path_list),))
>>> result = result.replace(r'\\', '/')
>>> print(result)
path_list = [
'__init__.py',
'__main__.py',
'tests/__init__.py',
]
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> dpath = dirname(ut.__file__) + '/__*.py'
>>> path_list = glob(dpath)
>>> result = ('path_list = %s' % (str(path_list),))
>>> print(result)
"""
gen = iglob(dpath, pattern, recursive=recursive,
with_files=with_files, with_dirs=with_dirs, maxdepth=maxdepth,
fullpath=fullpath, exclude_dirs=exclude_dirs, **kwargs)
path_list = list(gen)
return path_list |
0, module; 1, function_definition; 2, function_name:list_images; 3, parameters; 4, block; 5, identifier:img_dpath_; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, comment:#if not QUIET:; 13, comment:# print(ignore_list); 14, if_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, comment:# Get all the files in a directory recursively; 21, expression_statement; 22, for_statement; 23, if_statement; 24, return_statement; 25, identifier:ignore_list; 26, list; 27, identifier:recursive; 28, False; 29, identifier:fullpath; 30, False; 31, identifier:full; 32, None; 33, identifier:sort; 34, True; 35, comment:r"""
Returns a list of images in a directory. By default returns relative paths.
TODO: rename to ls_images
TODO: Change all instances of fullpath to full
Args:
img_dpath_ (str):
ignore_list (list): (default = [])
recursive (bool): (default = False)
fullpath (bool): (default = False)
full (None): (default = None)
sort (bool): (default = True)
Returns:
list: gname_list
CommandLine:
python -m utool.util_path --exec-list_images
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> img_dpath_ = '?'
>>> ignore_list = []
>>> recursive = False
>>> fullpath = False
>>> full = None
>>> sort = True
>>> gname_list = list_images(img_dpath_, ignore_list, recursive,
>>> fullpath, full, sort)
>>> result = ('gname_list = %s' % (str(gname_list),))
>>> print(result)
"""; 36, comparison_operator:full is not None; 37, block; 38, assignment; 39, assignment; 40, assignment; 41, assignment; 42, call; 43, assignment; 44, pattern_list; 45, call; 46, block; 47, identifier:sort; 48, block; 49, identifier:gname_list; 50, identifier:full; 51, None; 52, expression_statement; 53, identifier:img_dpath_; 54, call; 55, identifier:img_dpath; 56, call; 57, identifier:ignore_set; 58, call; 59, identifier:gname_list_; 60, list; 61, identifier:assertpath; 62, argument_list; 63, identifier:true_imgpath; 64, call; 65, identifier:root; 66, identifier:dlist; 67, identifier:flist; 68, attribute; 69, argument_list; 70, expression_statement; 71, expression_statement; 72, comment:# Ignore directories; 73, if_statement; 74, for_statement; 75, if_statement; 76, expression_statement; 77, assignment; 78, attribute; 79, argument_list; 80, identifier:realpath; 81, argument_list; 82, identifier:set; 83, argument_list; 84, identifier:img_dpath; 85, identifier:truepath; 86, argument_list; 87, identifier:os; 88, identifier:walk; 89, identifier:true_imgpath; 90, assignment; 91, assignment; 92, call; 93, block; 94, identifier:fname; 95, call; 96, block; 97, not_operator; 98, block; 99, assignment; 100, identifier:fullpath; 101, boolean_operator; 102, identifier:util_str; 103, identifier:ensure_unicode; 104, identifier:img_dpath_; 105, identifier:img_dpath_; 106, identifier:ignore_list; 107, identifier:img_dpath; 108, identifier:root; 109, call; 110, identifier:rel_dpath; 111, call; 112, identifier:any; 113, argument_list; 114, continue_statement; 115, identifier:iter; 116, argument_list; 117, expression_statement; 118, expression_statement; 119, if_statement; 120, if_statement; 121, identifier:recursive; 122, break_statement; 123, identifier:gname_list; 124, call; 125, identifier:fullpath; 126, identifier:full; 127, attribute; 128, argument_list; 129, identifier:relpath; 130, argument_list; 131, list_comprehension; 132, identifier:flist; 133, assignment; 134, assignment; 135, call; 136, block; 137, call; 138, comment:# Ignore Files; 139, block; 140, identifier:sorted; 141, argument_list; 142, identifier:util_str; 143, identifier:ensure_unicode; 144, identifier:root; 145, identifier:root; 146, identifier:img_dpath; 147, comparison_operator:dname in ignore_set; 148, for_in_clause; 149, identifier:fname; 150, call; 151, identifier:gname; 152, call; 153, attribute; 154, argument_list; 155, expression_statement; 156, identifier:fpath_has_imgext; 157, argument_list; 158, if_statement; 159, if_statement; 160, identifier:gname_list_; 161, identifier:dname; 162, identifier:ignore_set; 163, identifier:dname; 164, call; 165, attribute; 166, argument_list; 167, attribute; 168, argument_list; 169, identifier:gname; 170, identifier:startswith; 171, string; 172, assignment; 173, identifier:gname; 174, comparison_operator:gname in ignore_set; 175, block; 176, identifier:fullpath; 177, block; 178, else_clause; 179, identifier:dirsplit; 180, argument_list; 181, identifier:util_str; 182, identifier:ensure_unicode; 183, identifier:fname; 184, call; 185, identifier:replace; 186, string; 187, string; 188, string_content:./; 189, identifier:gname; 190, subscript; 191, identifier:gname; 192, identifier:ignore_set; 193, continue_statement; 194, expression_statement; 195, expression_statement; 196, block; 197, identifier:rel_dpath; 198, identifier:join; 199, argument_list; 200, string_content; 201, string_content:/; 202, identifier:gname; 203, slice; 204, assignment; 205, call; 206, expression_statement; 207, identifier:rel_dpath; 208, identifier:fname; 209, escape_sequence:\\; 210, integer:2; 211, identifier:gpath; 212, call; 213, attribute; 214, argument_list; 215, call; 216, identifier:join; 217, argument_list; 218, identifier:gname_list_; 219, identifier:append; 220, identifier:gpath; 221, attribute; 222, argument_list; 223, identifier:img_dpath; 224, identifier:gname; 225, identifier:gname_list_; 226, identifier:append; 227, identifier:gname | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 6, 25; 6, 26; 7, 27; 7, 28; 8, 29; 8, 30; 9, 31; 9, 32; 10, 33; 10, 34; 11, 35; 14, 36; 14, 37; 15, 38; 16, 39; 17, 40; 18, 41; 19, 42; 21, 43; 22, 44; 22, 45; 22, 46; 23, 47; 23, 48; 24, 49; 36, 50; 36, 51; 37, 52; 38, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 41, 60; 42, 61; 42, 62; 43, 63; 43, 64; 44, 65; 44, 66; 44, 67; 45, 68; 45, 69; 46, 70; 46, 71; 46, 72; 46, 73; 46, 74; 46, 75; 48, 76; 52, 77; 54, 78; 54, 79; 56, 80; 56, 81; 58, 82; 58, 83; 62, 84; 64, 85; 64, 86; 68, 87; 68, 88; 69, 89; 70, 90; 71, 91; 73, 92; 73, 93; 74, 94; 74, 95; 74, 96; 75, 97; 75, 98; 76, 99; 77, 100; 77, 101; 78, 102; 78, 103; 79, 104; 81, 105; 83, 106; 86, 107; 90, 108; 90, 109; 91, 110; 91, 111; 92, 112; 92, 113; 93, 114; 95, 115; 95, 116; 96, 117; 96, 118; 96, 119; 96, 120; 97, 121; 98, 122; 99, 123; 99, 124; 101, 125; 101, 126; 109, 127; 109, 128; 111, 129; 111, 130; 113, 131; 116, 132; 117, 133; 118, 134; 119, 135; 119, 136; 120, 137; 120, 138; 120, 139; 124, 140; 124, 141; 127, 142; 127, 143; 128, 144; 130, 145; 130, 146; 131, 147; 131, 148; 133, 149; 133, 150; 134, 151; 134, 152; 135, 153; 135, 154; 136, 155; 137, 156; 137, 157; 139, 158; 139, 159; 141, 160; 147, 161; 147, 162; 148, 163; 148, 164; 150, 165; 150, 166; 152, 167; 152, 168; 153, 169; 153, 170; 154, 171; 155, 172; 157, 173; 158, 174; 158, 175; 159, 176; 159, 177; 159, 178; 164, 179; 164, 180; 165, 181; 165, 182; 166, 183; 167, 184; 167, 185; 168, 186; 168, 187; 171, 188; 172, 189; 172, 190; 174, 191; 174, 192; 175, 193; 177, 194; 177, 195; 178, 196; 180, 197; 184, 198; 184, 199; 186, 200; 187, 201; 190, 202; 190, 203; 194, 204; 195, 205; 196, 206; 199, 207; 199, 208; 200, 209; 203, 210; 204, 211; 204, 212; 205, 213; 205, 214; 206, 215; 212, 216; 212, 217; 213, 218; 213, 219; 214, 220; 215, 221; 215, 222; 217, 223; 217, 224; 221, 225; 221, 226; 222, 227 | def list_images(img_dpath_, ignore_list=[], recursive=False, fullpath=False,
full=None, sort=True):
r"""
Returns a list of images in a directory. By default returns relative paths.
TODO: rename to ls_images
TODO: Change all instances of fullpath to full
Args:
img_dpath_ (str):
ignore_list (list): (default = [])
recursive (bool): (default = False)
fullpath (bool): (default = False)
full (None): (default = None)
sort (bool): (default = True)
Returns:
list: gname_list
CommandLine:
python -m utool.util_path --exec-list_images
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> img_dpath_ = '?'
>>> ignore_list = []
>>> recursive = False
>>> fullpath = False
>>> full = None
>>> sort = True
>>> gname_list = list_images(img_dpath_, ignore_list, recursive,
>>> fullpath, full, sort)
>>> result = ('gname_list = %s' % (str(gname_list),))
>>> print(result)
"""
#if not QUIET:
# print(ignore_list)
if full is not None:
fullpath = fullpath or full
img_dpath_ = util_str.ensure_unicode(img_dpath_)
img_dpath = realpath(img_dpath_)
ignore_set = set(ignore_list)
gname_list_ = []
assertpath(img_dpath)
# Get all the files in a directory recursively
true_imgpath = truepath(img_dpath)
for root, dlist, flist in os.walk(true_imgpath):
root = util_str.ensure_unicode(root)
rel_dpath = relpath(root, img_dpath)
# Ignore directories
if any([dname in ignore_set for dname in dirsplit(rel_dpath)]):
continue
for fname in iter(flist):
fname = util_str.ensure_unicode(fname)
gname = join(rel_dpath, fname).replace('\\', '/')
if gname.startswith('./'):
gname = gname[2:]
if fpath_has_imgext(gname):
# Ignore Files
if gname in ignore_set:
continue
if fullpath:
gpath = join(img_dpath, gname)
gname_list_.append(gpath)
else:
gname_list_.append(gname)
if not recursive:
break
if sort:
gname_list = sorted(gname_list_)
return gname_list |
0, module; 1, function_definition; 2, function_name:isect; 3, parameters; 4, block; 5, identifier:list1; 6, identifier:list2; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment: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)
"""; 11, assignment; 12, list_comprehension; 13, identifier:set2; 14, call; 15, identifier:item; 16, for_in_clause; 17, if_clause; 18, identifier:set; 19, argument_list; 20, identifier:item; 21, identifier:list1; 22, comparison_operator:item in set2; 23, identifier:list2; 24, identifier:item; 25, identifier:set2 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 11, 13; 11, 14; 12, 15; 12, 16; 12, 17; 14, 18; 14, 19; 16, 20; 16, 21; 17, 22; 19, 23; 22, 24; 22, 25 | 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] |
0, module; 1, function_definition; 2, function_name:argsort; 3, parameters; 4, block; 5, list_splat_pattern; 6, dictionary_splat_pattern; 7, expression_statement; 8, if_statement; 9, identifier:args; 10, identifier:kwargs; 11, comment:"""
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)
"""; 12, boolean_operator; 13, block; 14, else_clause; 15, comparison_operator:len(args) == 1; 16, call; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, return_statement; 21, block; 22, call; 23, integer:1; 24, identifier:isinstance; 25, argument_list; 26, assignment; 27, assignment; 28, assignment; 29, call; 30, expression_statement; 31, return_statement; 32, identifier:len; 33, argument_list; 34, subscript; 35, identifier:dict; 36, identifier:dict_; 37, subscript; 38, identifier:index_list; 39, call; 40, identifier:value_list; 41, call; 42, identifier:sortedby2; 43, argument_list; 44, assignment; 45, call; 46, identifier:args; 47, identifier:args; 48, integer:0; 49, identifier:args; 50, integer:0; 51, identifier:list; 52, argument_list; 53, identifier:list; 54, argument_list; 55, identifier:index_list; 56, identifier:value_list; 57, identifier:index_list; 58, call; 59, identifier:sortedby2; 60, argument_list; 61, call; 62, call; 63, identifier:list; 64, argument_list; 65, identifier:index_list; 66, list_splat; 67, dictionary_splat; 68, attribute; 69, argument_list; 70, attribute; 71, argument_list; 72, call; 73, identifier:args; 74, identifier:kwargs; 75, identifier:dict_; 76, identifier:keys; 77, identifier:dict_; 78, identifier:values; 79, identifier:range; 80, argument_list; 81, call; 82, identifier:len; 83, argument_list; 84, subscript; 85, identifier:args; 86, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 5, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 12, 15; 12, 16; 13, 17; 13, 18; 13, 19; 13, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 18, 27; 19, 28; 20, 29; 21, 30; 21, 31; 22, 32; 22, 33; 25, 34; 25, 35; 26, 36; 26, 37; 27, 38; 27, 39; 28, 40; 28, 41; 29, 42; 29, 43; 30, 44; 31, 45; 33, 46; 34, 47; 34, 48; 37, 49; 37, 50; 39, 51; 39, 52; 41, 53; 41, 54; 43, 55; 43, 56; 44, 57; 44, 58; 45, 59; 45, 60; 52, 61; 54, 62; 58, 63; 58, 64; 60, 65; 60, 66; 60, 67; 61, 68; 61, 69; 62, 70; 62, 71; 64, 72; 66, 73; 67, 74; 68, 75; 68, 76; 70, 77; 70, 78; 72, 79; 72, 80; 80, 81; 81, 82; 81, 83; 83, 84; 84, 85; 84, 86 | 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) |
0, module; 1, function_definition; 2, function_name:argsort2; 3, parameters; 4, block; 5, identifier:indexable; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, comment:# Create an iterator of value/key pairs; 10, if_statement; 11, comment:# Sort by values and extract the keys; 12, if_statement; 13, return_statement; 14, identifier:key; 15, None; 16, identifier:reverse; 17, False; 18, comment:"""
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
"""; 19, call; 20, block; 21, else_clause; 22, comparison_operator:key is None; 23, block; 24, else_clause; 25, identifier:indices; 26, identifier:isinstance; 27, argument_list; 28, expression_statement; 29, block; 30, identifier:key; 31, None; 32, expression_statement; 33, block; 34, identifier:indexable; 35, identifier:dict; 36, assignment; 37, expression_statement; 38, assignment; 39, expression_statement; 40, identifier:vk_iter; 41, generator_expression; 42, assignment; 43, identifier:indices; 44, list_comprehension; 45, assignment; 46, tuple; 47, for_in_clause; 48, identifier:vk_iter; 49, generator_expression; 50, identifier:k; 51, for_in_clause; 52, identifier:indices; 53, list_comprehension; 54, identifier:v; 55, identifier:k; 56, pattern_list; 57, call; 58, tuple; 59, for_in_clause; 60, pattern_list; 61, call; 62, identifier:k; 63, for_in_clause; 64, identifier:k; 65, identifier:v; 66, attribute; 67, argument_list; 68, identifier:v; 69, identifier:k; 70, pattern_list; 71, call; 72, identifier:v; 73, identifier:k; 74, identifier:sorted; 75, argument_list; 76, pattern_list; 77, call; 78, identifier:indexable; 79, identifier:items; 80, identifier:k; 81, identifier:v; 82, identifier:enumerate; 83, argument_list; 84, identifier:vk_iter; 85, keyword_argument; 86, identifier:v; 87, identifier:k; 88, identifier:sorted; 89, argument_list; 90, identifier:indexable; 91, identifier:reverse; 92, identifier:reverse; 93, identifier:vk_iter; 94, keyword_argument; 95, keyword_argument; 96, identifier:key; 97, lambda; 98, identifier:reverse; 99, identifier:reverse; 100, lambda_parameters; 101, call; 102, identifier:vk; 103, identifier:key; 104, argument_list; 105, subscript; 106, identifier:vk; 107, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 6, 15; 7, 16; 7, 17; 8, 18; 10, 19; 10, 20; 10, 21; 12, 22; 12, 23; 12, 24; 13, 25; 19, 26; 19, 27; 20, 28; 21, 29; 22, 30; 22, 31; 23, 32; 24, 33; 27, 34; 27, 35; 28, 36; 29, 37; 32, 38; 33, 39; 36, 40; 36, 41; 37, 42; 38, 43; 38, 44; 39, 45; 41, 46; 41, 47; 42, 48; 42, 49; 44, 50; 44, 51; 45, 52; 45, 53; 46, 54; 46, 55; 47, 56; 47, 57; 49, 58; 49, 59; 51, 60; 51, 61; 53, 62; 53, 63; 56, 64; 56, 65; 57, 66; 57, 67; 58, 68; 58, 69; 59, 70; 59, 71; 60, 72; 60, 73; 61, 74; 61, 75; 63, 76; 63, 77; 66, 78; 66, 79; 70, 80; 70, 81; 71, 82; 71, 83; 75, 84; 75, 85; 76, 86; 76, 87; 77, 88; 77, 89; 83, 90; 85, 91; 85, 92; 89, 93; 89, 94; 89, 95; 94, 96; 94, 97; 95, 98; 95, 99; 97, 100; 97, 101; 100, 102; 101, 103; 101, 104; 104, 105; 105, 106; 105, 107 | 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 |
0, module; 1, function_definition; 2, function_name:issorted; 3, parameters; 4, block; 5, identifier:list_; 6, default_parameter; 7, expression_statement; 8, return_statement; 9, identifier:op; 10, attribute; 11, comment:"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""; 12, call; 13, identifier:operator; 14, identifier:le; 15, identifier:all; 16, generator_expression; 17, call; 18, for_in_clause; 19, identifier:op; 20, argument_list; 21, identifier:ix; 22, call; 23, subscript; 24, subscript; 25, identifier:range; 26, argument_list; 27, identifier:list_; 28, identifier:ix; 29, identifier:list_; 30, binary_operator:ix + 1; 31, binary_operator:len(list_) - 1; 32, identifier:ix; 33, integer:1; 34, call; 35, integer:1; 36, identifier:len; 37, argument_list; 38, identifier:list_ | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 6, 9; 6, 10; 7, 11; 8, 12; 10, 13; 10, 14; 12, 15; 12, 16; 16, 17; 16, 18; 17, 19; 17, 20; 18, 21; 18, 22; 20, 23; 20, 24; 22, 25; 22, 26; 23, 27; 23, 28; 24, 29; 24, 30; 26, 31; 30, 32; 30, 33; 31, 34; 31, 35; 34, 36; 34, 37; 37, 38 | 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)) |
0, module; 1, function_definition; 2, function_name:list_alignment; 3, parameters; 4, block; 5, identifier:list1; 6, identifier:list2; 7, default_parameter; 8, expression_statement; 9, import_statement; 10, expression_statement; 11, if_statement; 12, return_statement; 13, identifier:missing; 14, False; 15, comment:"""
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]
"""; 16, aliased_import; 17, assignment; 18, identifier:missing; 19, block; 20, else_clause; 21, identifier:sortx; 22, dotted_name; 23, identifier:ut; 24, identifier:item1_to_idx; 25, call; 26, expression_statement; 27, block; 28, identifier:utool; 29, identifier:make_index_lookup; 30, argument_list; 31, assignment; 32, expression_statement; 33, identifier:list1; 34, identifier:sortx; 35, call; 36, assignment; 37, attribute; 38, argument_list; 39, identifier:sortx; 40, call; 41, identifier:ut; 42, identifier:dict_take; 43, identifier:item1_to_idx; 44, identifier:list2; 45, None; 46, attribute; 47, argument_list; 48, identifier:ut; 49, identifier:take; 50, identifier:item1_to_idx; 51, identifier:list2 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 11, 19; 11, 20; 12, 21; 16, 22; 16, 23; 17, 24; 17, 25; 19, 26; 20, 27; 22, 28; 25, 29; 25, 30; 26, 31; 27, 32; 30, 33; 31, 34; 31, 35; 32, 36; 35, 37; 35, 38; 36, 39; 36, 40; 37, 41; 37, 42; 38, 43; 38, 44; 38, 45; 40, 46; 40, 47; 46, 48; 46, 49; 47, 50; 47, 51 | 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 |
0, module; 1, function_definition; 2, function_name:hash_data; 3, parameters; 4, block; 5, identifier:data; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, if_statement; 11, if_statement; 12, identifier:hashlen; 13, None; 14, identifier:alphabet; 15, None; 16, comment:r"""
Get a unique hash depending on the state of the data.
Args:
data (object): any sort of loosely organized data
hashlen (None): (default = None)
alphabet (None): (default = None)
Returns:
str: text - hash string
CommandLine:
python -m utool.util_hash hash_data
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_hash import * # NOQA
>>> import utool as ut
>>> counter = [0]
>>> failed = []
>>> def check_hash(input_, want=None):
>>> count = counter[0] = counter[0] + 1
>>> got = ut.hash_data(input_)
>>> print('({}) {}'.format(count, got))
>>> if want is not None and not got.startswith(want):
>>> failed.append((got, input_, count, want))
>>> check_hash('1', 'wuvrng')
>>> check_hash(['1'], 'dekbfpby')
>>> check_hash(tuple(['1']), 'dekbfpby')
>>> check_hash(b'12', 'marreflbv')
>>> check_hash([b'1', b'2'], 'nwfs')
>>> check_hash(['1', '2', '3'], 'arfrp')
>>> check_hash(['1', np.array([1,2,3]), '3'], 'uyqwcq')
>>> check_hash('123', 'ehkgxk')
>>> check_hash(zip([1, 2, 3], [4, 5, 6]), 'mjcpwa')
>>> import numpy as np
>>> rng = np.random.RandomState(0)
>>> check_hash(rng.rand(100000), 'bdwosuey')
>>> for got, input_, count, want in failed:
>>> print('failed {} on {}'.format(count, input_))
>>> print('got={}, want={}'.format(got, want))
>>> assert not failed
"""; 17, comparison_operator:alphabet is None; 18, block; 19, comparison_operator:hashlen is None; 20, block; 21, boolean_operator; 22, comment:# Make a special hash for empty data; 23, block; 24, else_clause; 25, identifier:alphabet; 26, None; 27, expression_statement; 28, identifier:hashlen; 29, None; 30, expression_statement; 31, call; 32, comparison_operator:len(data) == 0; 33, expression_statement; 34, block; 35, assignment; 36, assignment; 37, identifier:isinstance; 38, argument_list; 39, call; 40, integer:0; 41, assignment; 42, expression_statement; 43, expression_statement; 44, comment:# Get a 128 character hex string; 45, expression_statement; 46, comment:# Shorten length of string (by increasing base); 47, expression_statement; 48, comment:# Truncate; 49, expression_statement; 50, return_statement; 51, identifier:alphabet; 52, identifier:ALPHABET_27; 53, identifier:hashlen; 54, identifier:HASH_LEN2; 55, identifier:data; 56, identifier:stringlike; 57, identifier:len; 58, argument_list; 59, identifier:text; 60, parenthesized_expression; 61, assignment; 62, call; 63, assignment; 64, assignment; 65, assignment; 66, identifier:text; 67, identifier:data; 68, binary_operator:alphabet[0] * hashlen; 69, identifier:hasher; 70, call; 71, identifier:_update_hasher; 72, argument_list; 73, identifier:text; 74, call; 75, identifier:hashstr2; 76, call; 77, identifier:text; 78, subscript; 79, subscript; 80, identifier:hashlen; 81, attribute; 82, argument_list; 83, identifier:hasher; 84, identifier:data; 85, attribute; 86, argument_list; 87, identifier:convert_hexstr_to_bigbase; 88, argument_list; 89, identifier:hashstr2; 90, slice; 91, identifier:alphabet; 92, integer:0; 93, identifier:hashlib; 94, identifier:sha512; 95, identifier:hasher; 96, identifier:hexdigest; 97, identifier:text; 98, identifier:alphabet; 99, keyword_argument; 100, identifier:hashlen; 101, identifier:bigbase; 102, call; 103, identifier:len; 104, argument_list; 105, identifier:alphabet | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 7, 15; 8, 16; 9, 17; 9, 18; 10, 19; 10, 20; 11, 21; 11, 22; 11, 23; 11, 24; 17, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 21, 31; 21, 32; 23, 33; 24, 34; 27, 35; 30, 36; 31, 37; 31, 38; 32, 39; 32, 40; 33, 41; 34, 42; 34, 43; 34, 44; 34, 45; 34, 46; 34, 47; 34, 48; 34, 49; 34, 50; 35, 51; 35, 52; 36, 53; 36, 54; 38, 55; 38, 56; 39, 57; 39, 58; 41, 59; 41, 60; 42, 61; 43, 62; 45, 63; 47, 64; 49, 65; 50, 66; 58, 67; 60, 68; 61, 69; 61, 70; 62, 71; 62, 72; 63, 73; 63, 74; 64, 75; 64, 76; 65, 77; 65, 78; 68, 79; 68, 80; 70, 81; 70, 82; 72, 83; 72, 84; 74, 85; 74, 86; 76, 87; 76, 88; 78, 89; 78, 90; 79, 91; 79, 92; 81, 93; 81, 94; 85, 95; 85, 96; 88, 97; 88, 98; 88, 99; 90, 100; 99, 101; 99, 102; 102, 103; 102, 104; 104, 105 | def hash_data(data, hashlen=None, alphabet=None):
r"""
Get a unique hash depending on the state of the data.
Args:
data (object): any sort of loosely organized data
hashlen (None): (default = None)
alphabet (None): (default = None)
Returns:
str: text - hash string
CommandLine:
python -m utool.util_hash hash_data
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_hash import * # NOQA
>>> import utool as ut
>>> counter = [0]
>>> failed = []
>>> def check_hash(input_, want=None):
>>> count = counter[0] = counter[0] + 1
>>> got = ut.hash_data(input_)
>>> print('({}) {}'.format(count, got))
>>> if want is not None and not got.startswith(want):
>>> failed.append((got, input_, count, want))
>>> check_hash('1', 'wuvrng')
>>> check_hash(['1'], 'dekbfpby')
>>> check_hash(tuple(['1']), 'dekbfpby')
>>> check_hash(b'12', 'marreflbv')
>>> check_hash([b'1', b'2'], 'nwfs')
>>> check_hash(['1', '2', '3'], 'arfrp')
>>> check_hash(['1', np.array([1,2,3]), '3'], 'uyqwcq')
>>> check_hash('123', 'ehkgxk')
>>> check_hash(zip([1, 2, 3], [4, 5, 6]), 'mjcpwa')
>>> import numpy as np
>>> rng = np.random.RandomState(0)
>>> check_hash(rng.rand(100000), 'bdwosuey')
>>> for got, input_, count, want in failed:
>>> print('failed {} on {}'.format(count, input_))
>>> print('got={}, want={}'.format(got, want))
>>> assert not failed
"""
if alphabet is None:
alphabet = ALPHABET_27
if hashlen is None:
hashlen = HASH_LEN2
if isinstance(data, stringlike) and len(data) == 0:
# Make a special hash for empty data
text = (alphabet[0] * hashlen)
else:
hasher = hashlib.sha512()
_update_hasher(hasher, data)
# Get a 128 character hex string
text = hasher.hexdigest()
# Shorten length of string (by increasing base)
hashstr2 = convert_hexstr_to_bigbase(text, alphabet, bigbase=len(alphabet))
# Truncate
text = hashstr2[:hashlen]
return text |
0, module; 1, function_definition; 2, function_name:quick_search; 3, parameters; 4, block; 5, identifier:self; 6, identifier:name; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, if_statement; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, return_statement; 16, identifier:platform; 17, None; 18, identifier:sort_by; 19, None; 20, identifier:desc; 21, True; 22, comment:"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:return: pybomb.clients.Response
"""; 23, comparison_operator:platform is None; 24, block; 25, else_clause; 26, assignment; 27, comparison_operator:sort_by is not None; 28, block; 29, assignment; 30, identifier:response; 31, identifier:platform; 32, None; 33, expression_statement; 34, block; 35, identifier:search_params; 36, dictionary; 37, identifier:sort_by; 38, None; 39, expression_statement; 40, if_statement; 41, expression_statement; 42, identifier:response; 43, call; 44, assignment; 45, expression_statement; 46, pair; 47, call; 48, identifier:desc; 49, block; 50, else_clause; 51, assignment; 52, attribute; 53, argument_list; 54, identifier:query_filter; 55, call; 56, assignment; 57, string:"filter"; 58, identifier:query_filter; 59, attribute; 60, argument_list; 61, expression_statement; 62, block; 63, subscript; 64, call; 65, identifier:self; 66, identifier:_query; 67, identifier:search_params; 68, attribute; 69, argument_list; 70, identifier:query_filter; 71, call; 72, identifier:self; 73, identifier:_validate_sort_field; 74, identifier:sort_by; 75, assignment; 76, expression_statement; 77, identifier:search_params; 78, string:"sort"; 79, attribute; 80, argument_list; 81, string:"name:{0}"; 82, identifier:format; 83, identifier:name; 84, attribute; 85, argument_list; 86, identifier:direction; 87, attribute; 88, assignment; 89, string:"{0}:{1}"; 90, identifier:format; 91, identifier:sort_by; 92, identifier:direction; 93, string:"name:{0},platforms:{1}"; 94, identifier:format; 95, identifier:name; 96, identifier:platform; 97, identifier:self; 98, identifier:SORT_ORDER_DESCENDING; 99, identifier:direction; 100, attribute; 101, identifier:self; 102, identifier:SORT_ORDER_ASCENDING | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 7, 16; 7, 17; 8, 18; 8, 19; 9, 20; 9, 21; 10, 22; 11, 23; 11, 24; 11, 25; 12, 26; 13, 27; 13, 28; 14, 29; 15, 30; 23, 31; 23, 32; 24, 33; 25, 34; 26, 35; 26, 36; 27, 37; 27, 38; 28, 39; 28, 40; 28, 41; 29, 42; 29, 43; 33, 44; 34, 45; 36, 46; 39, 47; 40, 48; 40, 49; 40, 50; 41, 51; 43, 52; 43, 53; 44, 54; 44, 55; 45, 56; 46, 57; 46, 58; 47, 59; 47, 60; 49, 61; 50, 62; 51, 63; 51, 64; 52, 65; 52, 66; 53, 67; 55, 68; 55, 69; 56, 70; 56, 71; 59, 72; 59, 73; 60, 74; 61, 75; 62, 76; 63, 77; 63, 78; 64, 79; 64, 80; 68, 81; 68, 82; 69, 83; 71, 84; 71, 85; 75, 86; 75, 87; 76, 88; 79, 89; 79, 90; 80, 91; 80, 92; 84, 93; 84, 94; 85, 95; 85, 96; 87, 97; 87, 98; 88, 99; 88, 100; 100, 101; 100, 102 | def quick_search(self, name, platform=None, sort_by=None, desc=True):
"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:return: pybomb.clients.Response
"""
if platform is None:
query_filter = "name:{0}".format(name)
else:
query_filter = "name:{0},platforms:{1}".format(name, platform)
search_params = {"filter": query_filter}
if sort_by is not None:
self._validate_sort_field(sort_by)
if desc:
direction = self.SORT_ORDER_DESCENDING
else:
direction = self.SORT_ORDER_ASCENDING
search_params["sort"] = "{0}:{1}".format(sort_by, direction)
response = self._query(search_params)
return response |
0, module; 1, function_definition; 2, function_name:sort_protein_group; 3, parameters; 4, block; 5, identifier:pgroup; 6, identifier:sortfunctions; 7, identifier:sortfunc_index; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, for_statement; 13, return_statement; 14, comment:"""Recursive function that sorts protein group by a number of sorting
functions."""; 15, assignment; 16, assignment; 17, augmented_assignment; 18, identifier:subgroup; 19, identifier:subgroups; 20, block; 21, identifier:pgroup_out; 22, identifier:pgroup_out; 23, list; 24, identifier:subgroups; 25, call; 26, identifier:sortfunc_index; 27, integer:1; 28, if_statement; 29, subscript; 30, argument_list; 31, boolean_operator; 32, block; 33, else_clause; 34, identifier:sortfunctions; 35, identifier:sortfunc_index; 36, identifier:pgroup; 37, comparison_operator:len(subgroup) > 1; 38, comparison_operator:sortfunc_index < len(sortfunctions); 39, expression_statement; 40, block; 41, call; 42, integer:1; 43, identifier:sortfunc_index; 44, call; 45, call; 46, expression_statement; 47, identifier:len; 48, argument_list; 49, identifier:len; 50, argument_list; 51, attribute; 52, argument_list; 53, call; 54, identifier:subgroup; 55, identifier:sortfunctions; 56, identifier:pgroup_out; 57, identifier:extend; 58, call; 59, attribute; 60, argument_list; 61, identifier:sort_protein_group; 62, argument_list; 63, identifier:pgroup_out; 64, identifier:extend; 65, identifier:subgroup; 66, identifier:subgroup; 67, identifier:sortfunctions; 68, identifier:sortfunc_index | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 8, 14; 9, 15; 10, 16; 11, 17; 12, 18; 12, 19; 12, 20; 13, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 20, 28; 25, 29; 25, 30; 28, 31; 28, 32; 28, 33; 29, 34; 29, 35; 30, 36; 31, 37; 31, 38; 32, 39; 33, 40; 37, 41; 37, 42; 38, 43; 38, 44; 39, 45; 40, 46; 41, 47; 41, 48; 44, 49; 44, 50; 45, 51; 45, 52; 46, 53; 48, 54; 50, 55; 51, 56; 51, 57; 52, 58; 53, 59; 53, 60; 58, 61; 58, 62; 59, 63; 59, 64; 60, 65; 62, 66; 62, 67; 62, 68 | def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
"""Recursive function that sorts protein group by a number of sorting
functions."""
pgroup_out = []
subgroups = sortfunctions[sortfunc_index](pgroup)
sortfunc_index += 1
for subgroup in subgroups:
if len(subgroup) > 1 and sortfunc_index < len(sortfunctions):
pgroup_out.extend(sort_protein_group(subgroup,
sortfunctions,
sortfunc_index))
else:
pgroup_out.extend(subgroup)
return pgroup_out |
0, module; 1, function_definition; 2, function_name:sort_amounts; 3, parameters; 4, block; 5, identifier:proteins; 6, identifier:sort_index; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein."""; 12, assignment; 13, identifier:protein; 14, identifier:proteins; 15, block; 16, list_comprehension; 17, identifier:amounts; 18, dictionary; 19, expression_statement; 20, try_statement; 21, identifier:v; 22, for_in_clause; 23, assignment; 24, block; 25, except_clause; 26, pattern_list; 27, call; 28, identifier:amount_x_for_protein; 29, subscript; 30, expression_statement; 31, identifier:KeyError; 32, block; 33, identifier:k; 34, identifier:v; 35, identifier:sorted; 36, argument_list; 37, identifier:protein; 38, identifier:sort_index; 39, call; 40, expression_statement; 41, call; 42, keyword_argument; 43, attribute; 44, argument_list; 45, assignment; 46, attribute; 47, argument_list; 48, identifier:reverse; 49, True; 50, subscript; 51, identifier:append; 52, identifier:protein; 53, subscript; 54, list; 55, identifier:amounts; 56, identifier:items; 57, identifier:amounts; 58, identifier:amount_x_for_protein; 59, identifier:amounts; 60, identifier:amount_x_for_protein; 61, identifier:protein | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 15, 19; 15, 20; 16, 21; 16, 22; 19, 23; 20, 24; 20, 25; 22, 26; 22, 27; 23, 28; 23, 29; 24, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 27, 36; 29, 37; 29, 38; 30, 39; 32, 40; 36, 41; 36, 42; 39, 43; 39, 44; 40, 45; 41, 46; 41, 47; 42, 48; 42, 49; 43, 50; 43, 51; 44, 52; 45, 53; 45, 54; 46, 55; 46, 56; 50, 57; 50, 58; 53, 59; 53, 60; 54, 61 | def sort_amounts(proteins, sort_index):
"""Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein."""
amounts = {}
for protein in proteins:
amount_x_for_protein = protein[sort_index]
try:
amounts[amount_x_for_protein].append(protein)
except KeyError:
amounts[amount_x_for_protein] = [protein]
return [v for k, v in sorted(amounts.items(), reverse=True)] |
0, module; 1, function_definition; 2, function_name:greedy_max_inden_setcover; 3, parameters; 4, block; 5, identifier:candidate_sets_dict; 6, identifier:items; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, while_statement; 14, expression_statement; 15, expression_statement; 16, return_statement; 17, identifier:max_covers; 18, None; 19, comment:"""
greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = None
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 9], ['a', 'c', 'd'])
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = 1
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 3, 4, 5, 8, 9], ['d'])
"""; 20, assignment; 21, assignment; 22, assignment; 23, assignment; 24, True; 25, comment:# Break if we have enough covers; 26, block; 27, assignment; 28, assignment; 29, identifier:covertup; 30, identifier:uncovered_set; 31, call; 32, identifier:rejected_keys; 33, call; 34, identifier:accepted_keys; 35, call; 36, identifier:covered_items_list; 37, list; 38, if_statement; 39, expression_statement; 40, expression_statement; 41, comment:# Loop over candidates to find the biggested unadded cover set; 42, for_statement; 43, comment:# Add the set to the cover; 44, if_statement; 45, expression_statement; 46, expression_statement; 47, expression_statement; 48, comment:# Add values in this key to the cover; 49, expression_statement; 50, identifier:uncovered_items; 51, call; 52, identifier:covertup; 53, expression_list; 54, identifier:set; 55, argument_list; 56, identifier:set; 57, argument_list; 58, identifier:set; 59, argument_list; 60, boolean_operator; 61, block; 62, assignment; 63, assignment; 64, pattern_list; 65, call; 66, block; 67, comparison_operator:maxkey is None; 68, block; 69, assignment; 70, call; 71, call; 72, call; 73, identifier:list; 74, argument_list; 75, identifier:uncovered_items; 76, identifier:covered_items_list; 77, identifier:accepted_keys; 78, identifier:items; 79, comparison_operator:max_covers is not None; 80, comparison_operator:len(covered_items_list) >= max_covers; 81, break_statement; 82, identifier:maxkey; 83, None; 84, identifier:maxlen; 85, unary_operator; 86, identifier:key; 87, identifier:candidate_items; 88, attribute; 89, argument_list; 90, if_statement; 91, comment:#print('Checking %r' % (key,)); 92, expression_statement; 93, comment:# len(uncovered_set.intersection(candidate_items)) == lenval:; 94, if_statement; 95, identifier:maxkey; 96, None; 97, break_statement; 98, identifier:maxval; 99, subscript; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, attribute; 105, argument_list; 106, identifier:uncovered_set; 107, identifier:max_covers; 108, None; 109, call; 110, identifier:max_covers; 111, integer:1; 112, identifier:six; 113, identifier:iteritems; 114, identifier:candidate_sets_dict; 115, boolean_operator; 116, block; 117, assignment; 118, call; 119, block; 120, else_clause; 121, identifier:candidate_sets_dict; 122, identifier:maxkey; 123, identifier:accepted_keys; 124, identifier:add; 125, identifier:maxkey; 126, identifier:covered_items_list; 127, identifier:append; 128, call; 129, identifier:uncovered_set; 130, identifier:difference_update; 131, identifier:maxval; 132, identifier:len; 133, argument_list; 134, comparison_operator:key in rejected_keys; 135, comparison_operator:key in accepted_keys; 136, continue_statement; 137, identifier:lenval; 138, call; 139, attribute; 140, argument_list; 141, if_statement; 142, block; 143, identifier:list; 144, argument_list; 145, identifier:covered_items_list; 146, identifier:key; 147, identifier:rejected_keys; 148, identifier:key; 149, identifier:accepted_keys; 150, identifier:len; 151, argument_list; 152, identifier:uncovered_set; 153, identifier:issuperset; 154, identifier:candidate_items; 155, comparison_operator:lenval > maxlen; 156, block; 157, expression_statement; 158, identifier:maxval; 159, identifier:candidate_items; 160, identifier:lenval; 161, identifier:maxlen; 162, expression_statement; 163, expression_statement; 164, call; 165, assignment; 166, assignment; 167, attribute; 168, argument_list; 169, identifier:maxkey; 170, identifier:key; 171, identifier:maxlen; 172, identifier:lenval; 173, identifier:rejected_keys; 174, identifier:add; 175, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 7, 17; 7, 18; 8, 19; 9, 20; 10, 21; 11, 22; 12, 23; 13, 24; 13, 25; 13, 26; 14, 27; 15, 28; 16, 29; 20, 30; 20, 31; 21, 32; 21, 33; 22, 34; 22, 35; 23, 36; 23, 37; 26, 38; 26, 39; 26, 40; 26, 41; 26, 42; 26, 43; 26, 44; 26, 45; 26, 46; 26, 47; 26, 48; 26, 49; 27, 50; 27, 51; 28, 52; 28, 53; 31, 54; 31, 55; 33, 56; 33, 57; 35, 58; 35, 59; 38, 60; 38, 61; 39, 62; 40, 63; 42, 64; 42, 65; 42, 66; 44, 67; 44, 68; 45, 69; 46, 70; 47, 71; 49, 72; 51, 73; 51, 74; 53, 75; 53, 76; 53, 77; 55, 78; 60, 79; 60, 80; 61, 81; 62, 82; 62, 83; 63, 84; 63, 85; 64, 86; 64, 87; 65, 88; 65, 89; 66, 90; 66, 91; 66, 92; 66, 93; 66, 94; 67, 95; 67, 96; 68, 97; 69, 98; 69, 99; 70, 100; 70, 101; 71, 102; 71, 103; 72, 104; 72, 105; 74, 106; 79, 107; 79, 108; 80, 109; 80, 110; 85, 111; 88, 112; 88, 113; 89, 114; 90, 115; 90, 116; 92, 117; 94, 118; 94, 119; 94, 120; 99, 121; 99, 122; 100, 123; 100, 124; 101, 125; 102, 126; 102, 127; 103, 128; 104, 129; 104, 130; 105, 131; 109, 132; 109, 133; 115, 134; 115, 135; 116, 136; 117, 137; 117, 138; 118, 139; 118, 140; 119, 141; 120, 142; 128, 143; 128, 144; 133, 145; 134, 146; 134, 147; 135, 148; 135, 149; 138, 150; 138, 151; 139, 152; 139, 153; 140, 154; 141, 155; 141, 156; 142, 157; 144, 158; 151, 159; 155, 160; 155, 161; 156, 162; 156, 163; 157, 164; 162, 165; 163, 166; 164, 167; 164, 168; 165, 169; 165, 170; 166, 171; 166, 172; 167, 173; 167, 174; 168, 175 | def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None):
"""
greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = None
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 9], ['a', 'c', 'd'])
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {'a': [5, 3], 'b': [2, 3, 5],
... 'c': [4, 8], 'd': [7, 6, 2, 1]}
>>> items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_covers = 1
>>> tup = greedy_max_inden_setcover(candidate_sets_dict, items, max_covers)
>>> (uncovered_items, covered_items_list, accepted_keys) = tup
>>> result = ut.repr4((uncovered_items, sorted(list(accepted_keys))), nl=False)
>>> print(result)
([0, 3, 4, 5, 8, 9], ['d'])
"""
uncovered_set = set(items)
rejected_keys = set()
accepted_keys = set()
covered_items_list = []
while True:
# Break if we have enough covers
if max_covers is not None and len(covered_items_list) >= max_covers:
break
maxkey = None
maxlen = -1
# Loop over candidates to find the biggested unadded cover set
for key, candidate_items in six.iteritems(candidate_sets_dict):
if key in rejected_keys or key in accepted_keys:
continue
#print('Checking %r' % (key,))
lenval = len(candidate_items)
# len(uncovered_set.intersection(candidate_items)) == lenval:
if uncovered_set.issuperset(candidate_items):
if lenval > maxlen:
maxkey = key
maxlen = lenval
else:
rejected_keys.add(key)
# Add the set to the cover
if maxkey is None:
break
maxval = candidate_sets_dict[maxkey]
accepted_keys.add(maxkey)
covered_items_list.append(list(maxval))
# Add values in this key to the cover
uncovered_set.difference_update(maxval)
uncovered_items = list(uncovered_set)
covertup = uncovered_items, covered_items_list, accepted_keys
return covertup |
0, module; 1, function_definition; 2, function_name:setcover_greedy; 3, parameters; 4, block; 5, identifier:candidate_sets_dict; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, import_statement; 12, expression_statement; 13, comment:# If candset_weights or item_values not given use the length as defaults; 14, if_statement; 15, if_statement; 16, if_statement; 17, if_statement; 18, expression_statement; 19, comment:# While we still need covers; 20, while_statement; 21, return_statement; 22, identifier:items; 23, None; 24, identifier:set_weights; 25, None; 26, identifier:item_values; 27, None; 28, identifier:max_weight; 29, None; 30, comment:r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
Weighted Maximum Cover: 1 - 1/e == .632 approximation algorithm
Generalized maximum coverage is not implemented
References:
https://en.wikipedia.org/wiki/Maximum_coverage_problem
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {
>>> 'a': [1, 2, 3, 8, 9, 0],
>>> 'b': [1, 2, 3, 4, 5],
>>> 'c': [4, 5, 7],
>>> 'd': [5, 6, 7],
>>> 'e': [6, 7, 8, 9, 0],
>>> }
>>> max_weight = None
>>> items = None
>>> set_weights = None
>>> item_values = None
>>> greedy_soln = ut.sort_dict(ut.setcover_greedy(candidate_sets_dict))
>>> exact_soln = ut.sort_dict(ut.setcover_ilp(candidate_sets_dict))
>>> print('greedy_soln = %r' % (greedy_soln,))
>>> print('exact_soln = %r' % (exact_soln,))
"""; 31, aliased_import; 32, assignment; 33, comparison_operator:items is None; 34, block; 35, comparison_operator:set_weights is None; 36, block; 37, else_clause; 38, comparison_operator:item_values is None; 39, block; 40, else_clause; 41, comparison_operator:max_weight is None; 42, block; 43, assignment; 44, boolean_operator; 45, comment:# Find candiate set with the most uncovered items; 46, block; 47, identifier:solution_cover; 48, dotted_name; 49, identifier:ut; 50, identifier:solution_cover; 51, dictionary; 52, identifier:items; 53, None; 54, expression_statement; 55, identifier:set_weights; 56, None; 57, expression_statement; 58, block; 59, identifier:item_values; 60, None; 61, expression_statement; 62, block; 63, identifier:max_weight; 64, None; 65, expression_statement; 66, identifier:avail_covers; 67, dictionary_comprehension; 68, comparison_operator:get_weight(solution_cover) < max_weight; 69, comparison_operator:len(avail_covers) > 0; 70, expression_statement; 71, expression_statement; 72, expression_statement; 73, if_statement; 74, expression_statement; 75, comment:# Add values in this key to the cover; 76, expression_statement; 77, expression_statement; 78, comment:# Remove chosen set from available options and covered items; 79, comment:# from remaining available sets; 80, delete_statement; 81, for_statement; 82, identifier:utool; 83, assignment; 84, assignment; 85, function_definition; 86, assignment; 87, function_definition; 88, assignment; 89, pair; 90, for_in_clause; 91, call; 92, identifier:max_weight; 93, call; 94, integer:0; 95, call; 96, assignment; 97, assignment; 98, comparison_operator:uncovered_values[chosen_idx] <= 0; 99, comment:# needlessly adding value-less items; 100, block; 101, assignment; 102, assignment; 103, assignment; 104, subscript; 105, identifier:vals; 106, call; 107, block; 108, identifier:items; 109, call; 110, identifier:get_weight; 111, identifier:len; 112, function_name:get_weight; 113, parameters; 114, block; 115, identifier:get_value; 116, identifier:len; 117, function_name:get_value; 118, parameters; 119, block; 120, identifier:max_weight; 121, call; 122, identifier:key; 123, call; 124, pattern_list; 125, call; 126, identifier:get_weight; 127, argument_list; 128, identifier:len; 129, argument_list; 130, attribute; 131, argument_list; 132, identifier:uncovered_values; 133, call; 134, identifier:chosen_idx; 135, call; 136, subscript; 137, integer:0; 138, break_statement; 139, identifier:chosen_key; 140, subscript; 141, identifier:chosen_set; 142, subscript; 143, subscript; 144, subscript; 145, identifier:avail_covers; 146, identifier:chosen_key; 147, attribute; 148, argument_list; 149, expression_statement; 150, attribute; 151, argument_list; 152, identifier:solution_cover; 153, expression_statement; 154, identifier:vals; 155, expression_statement; 156, identifier:get_weight; 157, argument_list; 158, identifier:set; 159, argument_list; 160, identifier:key; 161, identifier:val; 162, attribute; 163, argument_list; 164, identifier:solution_cover; 165, identifier:avail_covers; 166, identifier:avail_covers; 167, identifier:values; 168, identifier:list; 169, argument_list; 170, attribute; 171, argument_list; 172, identifier:uncovered_values; 173, identifier:chosen_idx; 174, call; 175, identifier:chosen_idx; 176, identifier:avail_covers; 177, identifier:chosen_key; 178, identifier:solution_cover; 179, identifier:chosen_key; 180, identifier:candidate_sets_dict; 181, identifier:chosen_key; 182, identifier:avail_covers; 183, identifier:values; 184, call; 185, identifier:ut; 186, identifier:flatten; 187, call; 188, call; 189, call; 190, identifier:candidate_sets_dict; 191, identifier:val; 192, identifier:candidate_sets_dict; 193, identifier:items; 194, call; 195, identifier:ut; 196, identifier:argmax; 197, identifier:uncovered_values; 198, identifier:list; 199, argument_list; 200, attribute; 201, argument_list; 202, attribute; 203, argument_list; 204, identifier:sum; 205, argument_list; 206, identifier:sum; 207, argument_list; 208, identifier:map; 209, argument_list; 210, call; 211, identifier:vals; 212, identifier:difference_update; 213, identifier:chosen_set; 214, identifier:candidate_sets_dict; 215, identifier:values; 216, list_comprehension; 217, list_comprehension; 218, identifier:get_value; 219, call; 220, attribute; 221, argument_list; 222, subscript; 223, for_in_clause; 224, subscript; 225, for_in_clause; 226, attribute; 227, argument_list; 228, identifier:avail_covers; 229, identifier:keys; 230, identifier:set_weights; 231, identifier:key; 232, identifier:key; 233, call; 234, identifier:item_values; 235, identifier:v; 236, identifier:v; 237, identifier:vals; 238, identifier:avail_covers; 239, identifier:values; 240, attribute; 241, argument_list; 242, identifier:solution_cover; 243, identifier:keys | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 6, 22; 6, 23; 7, 24; 7, 25; 8, 26; 8, 27; 9, 28; 9, 29; 10, 30; 11, 31; 12, 32; 14, 33; 14, 34; 15, 35; 15, 36; 15, 37; 16, 38; 16, 39; 16, 40; 17, 41; 17, 42; 18, 43; 20, 44; 20, 45; 20, 46; 21, 47; 31, 48; 31, 49; 32, 50; 32, 51; 33, 52; 33, 53; 34, 54; 35, 55; 35, 56; 36, 57; 37, 58; 38, 59; 38, 60; 39, 61; 40, 62; 41, 63; 41, 64; 42, 65; 43, 66; 43, 67; 44, 68; 44, 69; 46, 70; 46, 71; 46, 72; 46, 73; 46, 74; 46, 75; 46, 76; 46, 77; 46, 78; 46, 79; 46, 80; 46, 81; 48, 82; 54, 83; 57, 84; 58, 85; 61, 86; 62, 87; 65, 88; 67, 89; 67, 90; 68, 91; 68, 92; 69, 93; 69, 94; 70, 95; 71, 96; 72, 97; 73, 98; 73, 99; 73, 100; 74, 101; 76, 102; 77, 103; 80, 104; 81, 105; 81, 106; 81, 107; 83, 108; 83, 109; 84, 110; 84, 111; 85, 112; 85, 113; 85, 114; 86, 115; 86, 116; 87, 117; 87, 118; 87, 119; 88, 120; 88, 121; 89, 122; 89, 123; 90, 124; 90, 125; 91, 126; 91, 127; 93, 128; 93, 129; 95, 130; 95, 131; 96, 132; 96, 133; 97, 134; 97, 135; 98, 136; 98, 137; 100, 138; 101, 139; 101, 140; 102, 141; 102, 142; 103, 143; 103, 144; 104, 145; 104, 146; 106, 147; 106, 148; 107, 149; 109, 150; 109, 151; 113, 152; 114, 153; 118, 154; 119, 155; 121, 156; 121, 157; 123, 158; 123, 159; 124, 160; 124, 161; 125, 162; 125, 163; 127, 164; 129, 165; 130, 166; 130, 167; 133, 168; 133, 169; 135, 170; 135, 171; 136, 172; 136, 173; 140, 174; 140, 175; 142, 176; 142, 177; 143, 178; 143, 179; 144, 180; 144, 181; 147, 182; 147, 183; 149, 184; 150, 185; 150, 186; 151, 187; 153, 188; 155, 189; 157, 190; 159, 191; 162, 192; 162, 193; 169, 194; 170, 195; 170, 196; 171, 197; 174, 198; 174, 199; 184, 200; 184, 201; 187, 202; 187, 203; 188, 204; 188, 205; 189, 206; 189, 207; 194, 208; 194, 209; 199, 210; 200, 211; 200, 212; 201, 213; 202, 214; 202, 215; 205, 216; 207, 217; 209, 218; 209, 219; 210, 220; 210, 221; 216, 222; 216, 223; 217, 224; 217, 225; 219, 226; 219, 227; 220, 228; 220, 229; 222, 230; 222, 231; 223, 232; 223, 233; 224, 234; 224, 235; 225, 236; 225, 237; 226, 238; 226, 239; 233, 240; 233, 241; 240, 242; 240, 243 | def setcover_greedy(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None):
r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
Weighted Maximum Cover: 1 - 1/e == .632 approximation algorithm
Generalized maximum coverage is not implemented
References:
https://en.wikipedia.org/wiki/Maximum_coverage_problem
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> candidate_sets_dict = {
>>> 'a': [1, 2, 3, 8, 9, 0],
>>> 'b': [1, 2, 3, 4, 5],
>>> 'c': [4, 5, 7],
>>> 'd': [5, 6, 7],
>>> 'e': [6, 7, 8, 9, 0],
>>> }
>>> max_weight = None
>>> items = None
>>> set_weights = None
>>> item_values = None
>>> greedy_soln = ut.sort_dict(ut.setcover_greedy(candidate_sets_dict))
>>> exact_soln = ut.sort_dict(ut.setcover_ilp(candidate_sets_dict))
>>> print('greedy_soln = %r' % (greedy_soln,))
>>> print('exact_soln = %r' % (exact_soln,))
"""
import utool as ut
solution_cover = {}
# If candset_weights or item_values not given use the length as defaults
if items is None:
items = ut.flatten(candidate_sets_dict.values())
if set_weights is None:
get_weight = len
else:
def get_weight(solution_cover):
sum([set_weights[key] for key in solution_cover.keys()])
if item_values is None:
get_value = len
else:
def get_value(vals):
sum([item_values[v] for v in vals])
if max_weight is None:
max_weight = get_weight(candidate_sets_dict)
avail_covers = {key: set(val) for key, val in candidate_sets_dict.items()}
# While we still need covers
while get_weight(solution_cover) < max_weight and len(avail_covers) > 0:
# Find candiate set with the most uncovered items
avail_covers.values()
uncovered_values = list(map(get_value, avail_covers.values()))
chosen_idx = ut.argmax(uncovered_values)
if uncovered_values[chosen_idx] <= 0:
# needlessly adding value-less items
break
chosen_key = list(avail_covers.keys())[chosen_idx]
# Add values in this key to the cover
chosen_set = avail_covers[chosen_key]
solution_cover[chosen_key] = candidate_sets_dict[chosen_key]
# Remove chosen set from available options and covered items
# from remaining available sets
del avail_covers[chosen_key]
for vals in avail_covers.values():
vals.difference_update(chosen_set)
return solution_cover |
0, module; 1, function_definition; 2, function_name:knapsack_greedy; 3, parameters; 4, block; 5, identifier:items; 6, identifier:maxweight; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, comment:r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a non-negative integer, and `id_` is an
item identifier.
`maxweight` (scalar): is a non-negative integer.
CommandLine:
python -m utool.util_alg --exec-knapsack_greedy
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> items = [(4, 12, 0), (2, 1, 1), (6, 4, 2), (1, 1, 3), (2, 2, 4)]
>>> maxweight = 15
>>> total_value, items_subset = knapsack_greedy(items, maxweight)
>>> result = 'total_value = %r\n' % (total_value,)
>>> result += 'items_subset = %r' % (items_subset,)
>>> print(result)
total_value = 7
items_subset = [(4, 12, 0), (2, 1, 1), (1, 1, 3)]
"""; 14, assignment; 15, assignment; 16, assignment; 17, identifier:item; 18, identifier:items; 19, block; 20, expression_list; 21, identifier:items_subset; 22, list; 23, identifier:total_weight; 24, integer:0; 25, identifier:total_value; 26, integer:0; 27, expression_statement; 28, if_statement; 29, identifier:total_value; 30, identifier:items_subset; 31, assignment; 32, comparison_operator:total_weight + weight > maxweight; 33, block; 34, else_clause; 35, pattern_list; 36, subscript; 37, binary_operator:total_weight + weight; 38, identifier:maxweight; 39, continue_statement; 40, block; 41, identifier:value; 42, identifier:weight; 43, identifier:item; 44, slice; 45, identifier:total_weight; 46, identifier:weight; 47, expression_statement; 48, expression_statement; 49, expression_statement; 50, integer:0; 51, integer:2; 52, call; 53, augmented_assignment; 54, augmented_assignment; 55, attribute; 56, argument_list; 57, identifier:total_weight; 58, identifier:weight; 59, identifier:total_value; 60, identifier:value; 61, identifier:items_subset; 62, identifier:append; 63, identifier:item | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 11, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 15, 24; 16, 25; 16, 26; 19, 27; 19, 28; 20, 29; 20, 30; 27, 31; 28, 32; 28, 33; 28, 34; 31, 35; 31, 36; 32, 37; 32, 38; 33, 39; 34, 40; 35, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 40, 47; 40, 48; 40, 49; 44, 50; 44, 51; 47, 52; 48, 53; 49, 54; 52, 55; 52, 56; 53, 57; 53, 58; 54, 59; 54, 60; 55, 61; 55, 62; 56, 63 | def knapsack_greedy(items, maxweight):
r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a non-negative integer, and `id_` is an
item identifier.
`maxweight` (scalar): is a non-negative integer.
CommandLine:
python -m utool.util_alg --exec-knapsack_greedy
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> items = [(4, 12, 0), (2, 1, 1), (6, 4, 2), (1, 1, 3), (2, 2, 4)]
>>> maxweight = 15
>>> total_value, items_subset = knapsack_greedy(items, maxweight)
>>> result = 'total_value = %r\n' % (total_value,)
>>> result += 'items_subset = %r' % (items_subset,)
>>> print(result)
total_value = 7
items_subset = [(4, 12, 0), (2, 1, 1), (1, 1, 3)]
"""
items_subset = []
total_weight = 0
total_value = 0
for item in items:
value, weight = item[0:2]
if total_weight + weight > maxweight:
continue
else:
items_subset.append(item)
total_weight += weight
total_value += value
return total_value, items_subset |
0, module; 1, function_definition; 2, function_name:factors; 3, parameters; 4, block; 5, identifier:n; 6, expression_statement; 7, return_statement; 8, comment:"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
http://stackoverflow.com/questions/6800193/finding-all-the-factors
"""; 9, call; 10, identifier:set; 11, argument_list; 12, call; 13, identifier:reduce; 14, argument_list; 15, attribute; 16, generator_expression; 17, identifier:list; 18, identifier:__add__; 19, list; 20, for_in_clause; 21, if_clause; 22, identifier:i; 23, binary_operator:n // i; 24, identifier:i; 25, call; 26, comparison_operator:n % i == 0; 27, identifier:n; 28, identifier:i; 29, identifier:range; 30, argument_list; 31, binary_operator:n % i; 32, integer:0; 33, integer:1; 34, binary_operator:int(n ** 0.5) + 1; 35, identifier:n; 36, identifier:i; 37, call; 38, integer:1; 39, identifier:int; 40, argument_list; 41, binary_operator:n ** 0.5; 42, identifier:n; 43, float:0.5 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 11, 12; 12, 13; 12, 14; 14, 15; 14, 16; 15, 17; 15, 18; 16, 19; 16, 20; 16, 21; 19, 22; 19, 23; 20, 24; 20, 25; 21, 26; 23, 27; 23, 28; 25, 29; 25, 30; 26, 31; 26, 32; 30, 33; 30, 34; 31, 35; 31, 36; 34, 37; 34, 38; 37, 39; 37, 40; 40, 41; 41, 42; 41, 43 | def factors(n):
"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
http://stackoverflow.com/questions/6800193/finding-all-the-factors
"""
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))) |
0, module; 1, function_definition; 2, function_name:dict_stack; 3, parameters; 4, block; 5, identifier:dict_list; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, expression_statement; 11, return_statement; 12, identifier:key_prefix; 13, string; 14, comment:r"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacked
CommandLine:
python -m utool.util_dict --test-dict_stack
python -m utool.util_dict --test-dict_stack:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked = dict_stack([dict1_, dict2_])
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> # Get equivalent behavior with dict_stack2?
>>> # Almost, as long as None is not part of the list
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked_ = dict_stack2([dict1_, dict2_])
>>> dict_stacked = {key: ut.filter_Nones(val) for key, val in dict_stacked_.items()}
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
"""; 15, assignment; 16, identifier:dict_; 17, identifier:dict_list; 18, block; 19, assignment; 20, identifier:dict_stacked; 21, identifier:dict_stacked_; 22, call; 23, for_statement; 24, identifier:dict_stacked; 25, call; 26, identifier:defaultdict; 27, argument_list; 28, pattern_list; 29, call; 30, block; 31, identifier:dict; 32, argument_list; 33, identifier:list; 34, identifier:key; 35, identifier:val; 36, attribute; 37, argument_list; 38, expression_statement; 39, identifier:dict_stacked_; 40, identifier:six; 41, identifier:iteritems; 42, identifier:dict_; 43, call; 44, attribute; 45, argument_list; 46, subscript; 47, identifier:append; 48, identifier:val; 49, identifier:dict_stacked_; 50, binary_operator:key_prefix + key; 51, identifier:key_prefix; 52, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 9, 16; 9, 17; 9, 18; 10, 19; 11, 20; 15, 21; 15, 22; 18, 23; 19, 24; 19, 25; 22, 26; 22, 27; 23, 28; 23, 29; 23, 30; 25, 31; 25, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 30, 38; 32, 39; 36, 40; 36, 41; 37, 42; 38, 43; 43, 44; 43, 45; 44, 46; 44, 47; 45, 48; 46, 49; 46, 50; 50, 51; 50, 52 | def dict_stack(dict_list, key_prefix=''):
r"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacked
CommandLine:
python -m utool.util_dict --test-dict_stack
python -m utool.util_dict --test-dict_stack:1
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked = dict_stack([dict1_, dict2_])
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> # Get equivalent behavior with dict_stack2?
>>> # Almost, as long as None is not part of the list
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_stacked_ = dict_stack2([dict1_, dict2_])
>>> dict_stacked = {key: ut.filter_Nones(val) for key, val in dict_stacked_.items()}
>>> result = ut.repr2(dict_stacked, sorted_=True)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [4]}
"""
dict_stacked_ = defaultdict(list)
for dict_ in dict_list:
for key, val in six.iteritems(dict_):
dict_stacked_[key_prefix + key].append(val)
dict_stacked = dict(dict_stacked_)
return dict_stacked |
0, module; 1, function_definition; 2, function_name:invert_dict; 3, parameters; 4, block; 5, identifier:dict_; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, return_statement; 10, identifier:unique_vals; 11, True; 12, comment:"""
Reverses the keys and values in a dictionary. Set unique_vals to False if
the values in the dict are not unique.
Args:
dict_ (dict_): dictionary
unique_vals (bool): if False, inverted keys are returned in a list.
Returns:
dict: inverted_dict
CommandLine:
python -m utool.util_dict --test-invert_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 2}
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{1: 'a', 2: 'b'}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = OrderedDict([(2, 'good',), (1, 'ok',), (0, 'junk',), (None, 'UNKNOWN',)])
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{'good': 2, 'ok': 1, 'junk': 0, 'UNKNOWN': None}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 2}
>>> inverted_dict = invert_dict(dict_, unique_vals=False)
>>> inverted_dict = ut.map_dict_vals(sorted, inverted_dict)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{0: ['b', 'c', 'd', 'e'], 1: ['a'], 2: ['f']}
"""; 13, identifier:unique_vals; 14, block; 15, else_clause; 16, identifier:inverted_dict; 17, expression_statement; 18, expression_statement; 19, block; 20, assignment; 21, assignment; 22, expression_statement; 23, identifier:inverted_items; 24, list_comprehension; 25, identifier:inverted_dict; 26, call; 27, assignment; 28, tuple; 29, for_in_clause; 30, call; 31, argument_list; 32, identifier:inverted_dict; 33, call; 34, identifier:val; 35, identifier:key; 36, pattern_list; 37, call; 38, identifier:type; 39, argument_list; 40, identifier:inverted_items; 41, identifier:group_items; 42, argument_list; 43, identifier:key; 44, identifier:val; 45, attribute; 46, argument_list; 47, identifier:dict_; 48, call; 49, call; 50, identifier:six; 51, identifier:iteritems; 52, identifier:dict_; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, identifier:dict_; 58, identifier:keys; 59, identifier:dict_; 60, identifier:values | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 6, 10; 6, 11; 7, 12; 8, 13; 8, 14; 8, 15; 9, 16; 14, 17; 14, 18; 15, 19; 17, 20; 18, 21; 19, 22; 20, 23; 20, 24; 21, 25; 21, 26; 22, 27; 24, 28; 24, 29; 26, 30; 26, 31; 27, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 30, 38; 30, 39; 31, 40; 33, 41; 33, 42; 36, 43; 36, 44; 37, 45; 37, 46; 39, 47; 42, 48; 42, 49; 45, 50; 45, 51; 46, 52; 48, 53; 48, 54; 49, 55; 49, 56; 53, 57; 53, 58; 55, 59; 55, 60 | def invert_dict(dict_, unique_vals=True):
"""
Reverses the keys and values in a dictionary. Set unique_vals to False if
the values in the dict are not unique.
Args:
dict_ (dict_): dictionary
unique_vals (bool): if False, inverted keys are returned in a list.
Returns:
dict: inverted_dict
CommandLine:
python -m utool.util_dict --test-invert_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 2}
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{1: 'a', 2: 'b'}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = OrderedDict([(2, 'good',), (1, 'ok',), (0, 'junk',), (None, 'UNKNOWN',)])
>>> inverted_dict = invert_dict(dict_)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{'good': 2, 'ok': 1, 'junk': 0, 'UNKNOWN': None}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 2}
>>> inverted_dict = invert_dict(dict_, unique_vals=False)
>>> inverted_dict = ut.map_dict_vals(sorted, inverted_dict)
>>> result = ut.repr4(inverted_dict, nl=False)
>>> print(result)
{0: ['b', 'c', 'd', 'e'], 1: ['a'], 2: ['f']}
"""
if unique_vals:
inverted_items = [(val, key) for key, val in six.iteritems(dict_)]
inverted_dict = type(dict_)(inverted_items)
else:
inverted_dict = group_items(dict_.keys(), dict_.values())
return inverted_dict |
0, module; 1, function_definition; 2, function_name:groupby_tags; 3, parameters; 4, block; 5, identifier:item_list; 6, identifier:tags_list; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:r"""
case where an item can belong to multiple groups
Args:
item_list (list):
tags_list (list):
Returns:
dict: groupid_to_items
CommandLine:
python -m utool.util_dict --test-groupby_tags
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> tagged_item_list = {
>>> 'spam': ['meat', 'protein', 'food'],
>>> 'eggs': ['protein', 'food'],
>>> 'cheese': ['dairy', 'protein', 'food'],
>>> 'jam': ['fruit', 'food'],
>>> 'banana': ['weapon', 'fruit', 'food'],
>>> }
>>> item_list = list(tagged_item_list.keys())
>>> tags_list = list(tagged_item_list.values())
>>> groupid_to_items = groupby_tags(item_list, tags_list)
>>> groupid_to_items = ut.map_vals(sorted, groupid_to_items)
>>> result = ('groupid_to_items = %s' % (ut.repr4(groupid_to_items),))
>>> print(result)
groupid_to_items = {
'dairy': ['cheese'],
'food': ['banana', 'cheese', 'eggs', 'jam', 'spam'],
'fruit': ['banana', 'jam'],
'meat': ['spam'],
'protein': ['cheese', 'eggs', 'spam'],
'weapon': ['banana'],
}
"""; 12, assignment; 13, pattern_list; 14, call; 15, block; 16, identifier:groupid_to_items; 17, identifier:groupid_to_items; 18, call; 19, identifier:tags; 20, identifier:item; 21, identifier:zip; 22, argument_list; 23, for_statement; 24, identifier:defaultdict; 25, argument_list; 26, identifier:tags_list; 27, identifier:item_list; 28, identifier:tag; 29, identifier:tags; 30, block; 31, identifier:list; 32, expression_statement; 33, call; 34, attribute; 35, argument_list; 36, subscript; 37, identifier:append; 38, identifier:item; 39, identifier:groupid_to_items; 40, identifier:tag | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 13, 19; 13, 20; 14, 21; 14, 22; 15, 23; 18, 24; 18, 25; 22, 26; 22, 27; 23, 28; 23, 29; 23, 30; 25, 31; 30, 32; 32, 33; 33, 34; 33, 35; 34, 36; 34, 37; 35, 38; 36, 39; 36, 40 | def groupby_tags(item_list, tags_list):
r"""
case where an item can belong to multiple groups
Args:
item_list (list):
tags_list (list):
Returns:
dict: groupid_to_items
CommandLine:
python -m utool.util_dict --test-groupby_tags
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> tagged_item_list = {
>>> 'spam': ['meat', 'protein', 'food'],
>>> 'eggs': ['protein', 'food'],
>>> 'cheese': ['dairy', 'protein', 'food'],
>>> 'jam': ['fruit', 'food'],
>>> 'banana': ['weapon', 'fruit', 'food'],
>>> }
>>> item_list = list(tagged_item_list.keys())
>>> tags_list = list(tagged_item_list.values())
>>> groupid_to_items = groupby_tags(item_list, tags_list)
>>> groupid_to_items = ut.map_vals(sorted, groupid_to_items)
>>> result = ('groupid_to_items = %s' % (ut.repr4(groupid_to_items),))
>>> print(result)
groupid_to_items = {
'dairy': ['cheese'],
'food': ['banana', 'cheese', 'eggs', 'jam', 'spam'],
'fruit': ['banana', 'jam'],
'meat': ['spam'],
'protein': ['cheese', 'eggs', 'spam'],
'weapon': ['banana'],
}
"""
groupid_to_items = defaultdict(list)
for tags, item in zip(tags_list, item_list):
for tag in tags:
groupid_to_items[tag].append(item)
return groupid_to_items |
0, module; 1, function_definition; 2, function_name:group_items; 3, parameters; 4, block; 5, identifier:items; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, comment:# Initialize a dict of lists; 11, expression_statement; 12, comment:# Insert each item into the correct group; 13, for_statement; 14, return_statement; 15, identifier:by; 16, None; 17, identifier:sorted_; 18, True; 19, comment:"""
Groups a list of items by group id.
Args:
items (list): a list of the values to be grouped.
if `by` is None, then each item is assumed to be a
(groupid, value) pair.
by (list): a corresponding list to group items by.
if specified, these are used as the keys to group values
in `items`
sorted_ (bool): if True preserves the ordering of items within groups
(default = True) FIXME. the opposite is true
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_indices - first part of a a more fine grained grouping algorithm
apply_gropuing - second part of a more fine grained grouping algorithm
CommandLine:
python -m utool.util_dict --test-group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> items = ['ham', 'jam', 'spam', 'eggs', 'cheese', 'bannana']
>>> by = ['protein', 'fruit', 'protein', 'protein', 'dairy', 'fruit']
>>> groupid_to_items = ut.group_items(items, iter(by))
>>> result = ut.repr2(groupid_to_items)
>>> print(result)
{'dairy': ['cheese'], 'fruit': ['jam', 'bannana'], 'protein': ['ham', 'spam', 'eggs']}
"""; 20, comparison_operator:by is not None; 21, block; 22, else_clause; 23, assignment; 24, pattern_list; 25, identifier:pairs; 26, block; 27, identifier:groupid_to_items; 28, identifier:by; 29, None; 30, expression_statement; 31, if_statement; 32, block; 33, identifier:groupid_to_items; 34, call; 35, identifier:groupid; 36, identifier:item; 37, expression_statement; 38, assignment; 39, identifier:sorted_; 40, comment:# Sort by groupid for cache efficiency (does this even do anything?); 41, comment:# I forgot why this is needed? Determenism?; 42, block; 43, expression_statement; 44, identifier:defaultdict; 45, argument_list; 46, call; 47, identifier:pairs; 48, call; 49, try_statement; 50, assignment; 51, identifier:list; 52, attribute; 53, argument_list; 54, identifier:list; 55, argument_list; 56, block; 57, except_clause; 58, identifier:pairs; 59, identifier:items; 60, subscript; 61, identifier:append; 62, identifier:item; 63, call; 64, expression_statement; 65, identifier:TypeError; 66, comment:# Python 3 does not allow sorting mixed types; 67, block; 68, identifier:groupid_to_items; 69, identifier:groupid; 70, identifier:zip; 71, argument_list; 72, assignment; 73, expression_statement; 74, identifier:by; 75, identifier:items; 76, identifier:pairs; 77, call; 78, assignment; 79, identifier:sorted; 80, argument_list; 81, identifier:pairs; 82, call; 83, identifier:pairs; 84, keyword_argument; 85, identifier:sorted; 86, argument_list; 87, identifier:key; 88, call; 89, identifier:pairs; 90, keyword_argument; 91, attribute; 92, argument_list; 93, identifier:key; 94, lambda; 95, identifier:op; 96, identifier:itemgetter; 97, integer:0; 98, lambda_parameters; 99, call; 100, identifier:tup; 101, identifier:str; 102, argument_list; 103, subscript; 104, identifier:tup; 105, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 9, 20; 9, 21; 9, 22; 11, 23; 13, 24; 13, 25; 13, 26; 14, 27; 20, 28; 20, 29; 21, 30; 21, 31; 22, 32; 23, 33; 23, 34; 24, 35; 24, 36; 26, 37; 30, 38; 31, 39; 31, 40; 31, 41; 31, 42; 32, 43; 34, 44; 34, 45; 37, 46; 38, 47; 38, 48; 42, 49; 43, 50; 45, 51; 46, 52; 46, 53; 48, 54; 48, 55; 49, 56; 49, 57; 50, 58; 50, 59; 52, 60; 52, 61; 53, 62; 55, 63; 56, 64; 57, 65; 57, 66; 57, 67; 60, 68; 60, 69; 63, 70; 63, 71; 64, 72; 67, 73; 71, 74; 71, 75; 72, 76; 72, 77; 73, 78; 77, 79; 77, 80; 78, 81; 78, 82; 80, 83; 80, 84; 82, 85; 82, 86; 84, 87; 84, 88; 86, 89; 86, 90; 88, 91; 88, 92; 90, 93; 90, 94; 91, 95; 91, 96; 92, 97; 94, 98; 94, 99; 98, 100; 99, 101; 99, 102; 102, 103; 103, 104; 103, 105 | def group_items(items, by=None, sorted_=True):
"""
Groups a list of items by group id.
Args:
items (list): a list of the values to be grouped.
if `by` is None, then each item is assumed to be a
(groupid, value) pair.
by (list): a corresponding list to group items by.
if specified, these are used as the keys to group values
in `items`
sorted_ (bool): if True preserves the ordering of items within groups
(default = True) FIXME. the opposite is true
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_indices - first part of a a more fine grained grouping algorithm
apply_gropuing - second part of a more fine grained grouping algorithm
CommandLine:
python -m utool.util_dict --test-group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> items = ['ham', 'jam', 'spam', 'eggs', 'cheese', 'bannana']
>>> by = ['protein', 'fruit', 'protein', 'protein', 'dairy', 'fruit']
>>> groupid_to_items = ut.group_items(items, iter(by))
>>> result = ut.repr2(groupid_to_items)
>>> print(result)
{'dairy': ['cheese'], 'fruit': ['jam', 'bannana'], 'protein': ['ham', 'spam', 'eggs']}
"""
if by is not None:
pairs = list(zip(by, items))
if sorted_:
# Sort by groupid for cache efficiency (does this even do anything?)
# I forgot why this is needed? Determenism?
try:
pairs = sorted(pairs, key=op.itemgetter(0))
except TypeError:
# Python 3 does not allow sorting mixed types
pairs = sorted(pairs, key=lambda tup: str(tup[0]))
else:
pairs = items
# Initialize a dict of lists
groupid_to_items = defaultdict(list)
# Insert each item into the correct group
for groupid, item in pairs:
groupid_to_items[groupid].append(item)
return groupid_to_items |
0, module; 1, function_definition; 2, function_name:hierarchical_map_vals; 3, parameters; 4, block; 5, identifier:func; 6, identifier:node; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, comment:#if not isinstance(node, dict):; 11, if_statement; 12, identifier:max_depth; 13, None; 14, identifier:depth; 15, integer:0; 16, comment:"""
node is a dict tree like structure with leaves of type list
TODO: move to util_dict
CommandLine:
python -m utool.util_dict --exec-hierarchical_map_vals
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5, 6, 7, 8]
>>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]]
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> len_tree = ut.hierarchical_map_vals(len, tree)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=1))
>>> print(result)
len_tree = {
1: {1: 1, 2: 1, 3: 2},
2: {1: 2, 2: 2},
}
Example1:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> depth = 4
>>> item_list = list(range(2 ** (depth + 1)))
>>> num = len(item_list) // 2
>>> groupids_list = []
>>> total = 0
>>> for level in range(depth):
... num2 = len(item_list) // int((num * 2))
... #nonflat_levelids = [([total + 2 * x + 1] * num + [total + 2 * x + 2] * num) for x in range(num2)]
... nonflat_levelids = [([1] * num + [2] * num) for x in range(num2)]
... levelids = ut.flatten(nonflat_levelids)
... groupids_list.append(levelids)
... total += num2 * 2
... num //= 2
>>> print('groupids_list = %s' % (ut.repr4(groupids_list, nl=1),))
>>> print('depth = %r' % (len(groupids_list),))
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> print('tree = ' + ut.repr4(tree, nl=None))
>>> flat_tree_values = list(ut.iflatten_dict_values(tree))
>>> assert sorted(flat_tree_values) == sorted(item_list)
>>> print('flat_tree_values = ' + str(flat_tree_values))
>>> #print('flat_tree_keys = ' + str(list(ut.iflatten_dict_keys(tree))))
>>> #print('iflatten_dict_items = ' + str(list(ut.iflatten_dict_items(tree))))
>>> len_tree = ut.hierarchical_map_vals(len, tree, max_depth=4)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=None))
>>> print(result)
"""; 17, not_operator; 18, block; 19, elif_clause; 20, else_clause; 21, call; 22, return_statement; 23, boolean_operator; 24, comment:#return func(node); 25, block; 26, comment:# recursion; 27, comment:#return {key: hierarchical_map_vals(func, val, max_depth, depth + 1) for key, val in six.iteritems(node)}; 28, comment:#keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in six.iteritems(node)]; 29, block; 30, identifier:hasattr; 31, argument_list; 32, call; 33, comparison_operator:max_depth is not None; 34, comparison_operator:depth >= max_depth; 35, return_statement; 36, comment:#return {key: func(val) for key, val in six.iteritems(node)}; 37, expression_statement; 38, if_statement; 39, identifier:node; 40, string; 41, identifier:func; 42, argument_list; 43, identifier:max_depth; 44, None; 45, identifier:depth; 46, identifier:max_depth; 47, call; 48, assignment; 49, call; 50, block; 51, else_clause; 52, string_content:items; 53, identifier:node; 54, identifier:map_dict_vals; 55, argument_list; 56, identifier:keyval_list; 57, list_comprehension; 58, identifier:isinstance; 59, argument_list; 60, return_statement; 61, block; 62, identifier:func; 63, identifier:node; 64, tuple; 65, for_in_clause; 66, identifier:node; 67, identifier:OrderedDict; 68, call; 69, return_statement; 70, identifier:key; 71, call; 72, pattern_list; 73, call; 74, identifier:OrderedDict; 75, argument_list; 76, call; 77, identifier:hierarchical_map_vals; 78, argument_list; 79, identifier:key; 80, identifier:val; 81, attribute; 82, argument_list; 83, identifier:keyval_list; 84, identifier:dict; 85, argument_list; 86, identifier:func; 87, identifier:val; 88, identifier:max_depth; 89, binary_operator:depth + 1; 90, identifier:node; 91, identifier:items; 92, identifier:keyval_list; 93, identifier:depth; 94, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 7, 12; 7, 13; 8, 14; 8, 15; 9, 16; 11, 17; 11, 18; 11, 19; 11, 20; 17, 21; 18, 22; 19, 23; 19, 24; 19, 25; 20, 26; 20, 27; 20, 28; 20, 29; 21, 30; 21, 31; 22, 32; 23, 33; 23, 34; 25, 35; 25, 36; 29, 37; 29, 38; 31, 39; 31, 40; 32, 41; 32, 42; 33, 43; 33, 44; 34, 45; 34, 46; 35, 47; 37, 48; 38, 49; 38, 50; 38, 51; 40, 52; 42, 53; 47, 54; 47, 55; 48, 56; 48, 57; 49, 58; 49, 59; 50, 60; 51, 61; 55, 62; 55, 63; 57, 64; 57, 65; 59, 66; 59, 67; 60, 68; 61, 69; 64, 70; 64, 71; 65, 72; 65, 73; 68, 74; 68, 75; 69, 76; 71, 77; 71, 78; 72, 79; 72, 80; 73, 81; 73, 82; 75, 83; 76, 84; 76, 85; 78, 86; 78, 87; 78, 88; 78, 89; 81, 90; 81, 91; 85, 92; 89, 93; 89, 94 | def hierarchical_map_vals(func, node, max_depth=None, depth=0):
"""
node is a dict tree like structure with leaves of type list
TODO: move to util_dict
CommandLine:
python -m utool.util_dict --exec-hierarchical_map_vals
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5, 6, 7, 8]
>>> groupids_list = [[1, 2, 1, 2, 1, 2, 1, 2], [3, 2, 2, 2, 3, 1, 1, 1]]
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> len_tree = ut.hierarchical_map_vals(len, tree)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=1))
>>> print(result)
len_tree = {
1: {1: 1, 2: 1, 3: 2},
2: {1: 2, 2: 2},
}
Example1:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> depth = 4
>>> item_list = list(range(2 ** (depth + 1)))
>>> num = len(item_list) // 2
>>> groupids_list = []
>>> total = 0
>>> for level in range(depth):
... num2 = len(item_list) // int((num * 2))
... #nonflat_levelids = [([total + 2 * x + 1] * num + [total + 2 * x + 2] * num) for x in range(num2)]
... nonflat_levelids = [([1] * num + [2] * num) for x in range(num2)]
... levelids = ut.flatten(nonflat_levelids)
... groupids_list.append(levelids)
... total += num2 * 2
... num //= 2
>>> print('groupids_list = %s' % (ut.repr4(groupids_list, nl=1),))
>>> print('depth = %r' % (len(groupids_list),))
>>> tree = ut.hierarchical_group_items(item_list, groupids_list)
>>> print('tree = ' + ut.repr4(tree, nl=None))
>>> flat_tree_values = list(ut.iflatten_dict_values(tree))
>>> assert sorted(flat_tree_values) == sorted(item_list)
>>> print('flat_tree_values = ' + str(flat_tree_values))
>>> #print('flat_tree_keys = ' + str(list(ut.iflatten_dict_keys(tree))))
>>> #print('iflatten_dict_items = ' + str(list(ut.iflatten_dict_items(tree))))
>>> len_tree = ut.hierarchical_map_vals(len, tree, max_depth=4)
>>> result = ('len_tree = ' + ut.repr4(len_tree, nl=None))
>>> print(result)
"""
#if not isinstance(node, dict):
if not hasattr(node, 'items'):
return func(node)
elif max_depth is not None and depth >= max_depth:
#return func(node)
return map_dict_vals(func, node)
#return {key: func(val) for key, val in six.iteritems(node)}
else:
# recursion
#return {key: hierarchical_map_vals(func, val, max_depth, depth + 1) for key, val in six.iteritems(node)}
#keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in six.iteritems(node)]
keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in node.items()]
if isinstance(node, OrderedDict):
return OrderedDict(keyval_list)
else:
return dict(keyval_list) |
0, module; 1, function_definition; 2, function_name:sort_dict; 3, parameters; 4, block; 5, identifier:dict_; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, if_statement; 12, expression_statement; 13, expression_statement; 14, return_statement; 15, identifier:part; 16, string; 17, identifier:key; 18, None; 19, identifier:reverse; 20, False; 21, comment:"""
sorts a dictionary by its values or its keys
Args:
dict_ (dict_): a dictionary
part (str): specifies to sort by keys or values
key (Optional[func]): a function that takes specified part
and returns a sortable value
reverse (bool): (Defaults to False) - True for descinding order. False
for ascending order.
Returns:
OrderedDict: sorted dictionary
CommandLine:
python -m utool.util_dict sort_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 3, 'c': 2, 'b': 1}
>>> results = []
>>> results.append(sort_dict(dict_, 'keys'))
>>> results.append(sort_dict(dict_, 'vals'))
>>> results.append(sort_dict(dict_, 'vals', lambda x: -x))
>>> result = ut.repr4(results)
>>> print(result)
[
{'a': 3, 'b': 1, 'c': 2},
{'b': 1, 'c': 2, 'a': 3},
{'a': 3, 'c': 2, 'b': 1},
]
"""; 22, comparison_operator:part == 'keys'; 23, block; 24, elif_clause; 25, else_clause; 26, comparison_operator:key is None; 27, block; 28, else_clause; 29, assignment; 30, assignment; 31, identifier:sorted_dict; 32, string_content:keys; 33, identifier:part; 34, string; 35, expression_statement; 36, comparison_operator:part in {'vals', 'values'}; 37, block; 38, block; 39, identifier:key; 40, None; 41, expression_statement; 42, block; 43, identifier:sorted_items; 44, call; 45, identifier:sorted_dict; 46, call; 47, string_content:keys; 48, assignment; 49, identifier:part; 50, set; 51, expression_statement; 52, raise_statement; 53, assignment; 54, function_definition; 55, identifier:sorted; 56, argument_list; 57, identifier:OrderedDict; 58, argument_list; 59, identifier:index; 60, integer:0; 61, string; 62, string; 63, assignment; 64, call; 65, identifier:_key; 66, call; 67, function_name:_key; 68, parameters; 69, block; 70, call; 71, keyword_argument; 72, keyword_argument; 73, identifier:sorted_items; 74, string_content:vals; 75, string_content:values; 76, identifier:index; 77, integer:1; 78, identifier:ValueError; 79, argument_list; 80, attribute; 81, argument_list; 82, identifier:item; 83, return_statement; 84, attribute; 85, argument_list; 86, identifier:key; 87, identifier:_key; 88, identifier:reverse; 89, identifier:reverse; 90, binary_operator:'Unknown method part=%r' % (part,); 91, identifier:op; 92, identifier:itemgetter; 93, identifier:index; 94, call; 95, identifier:six; 96, identifier:iteritems; 97, identifier:dict_; 98, string; 99, tuple; 100, identifier:key; 101, argument_list; 102, string_content:Unknown method part=%r; 103, identifier:part; 104, subscript; 105, identifier:item; 106, identifier:index | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 10, 23; 10, 24; 10, 25; 11, 26; 11, 27; 11, 28; 12, 29; 13, 30; 14, 31; 16, 32; 22, 33; 22, 34; 23, 35; 24, 36; 24, 37; 25, 38; 26, 39; 26, 40; 27, 41; 28, 42; 29, 43; 29, 44; 30, 45; 30, 46; 34, 47; 35, 48; 36, 49; 36, 50; 37, 51; 38, 52; 41, 53; 42, 54; 44, 55; 44, 56; 46, 57; 46, 58; 48, 59; 48, 60; 50, 61; 50, 62; 51, 63; 52, 64; 53, 65; 53, 66; 54, 67; 54, 68; 54, 69; 56, 70; 56, 71; 56, 72; 58, 73; 61, 74; 62, 75; 63, 76; 63, 77; 64, 78; 64, 79; 66, 80; 66, 81; 68, 82; 69, 83; 70, 84; 70, 85; 71, 86; 71, 87; 72, 88; 72, 89; 79, 90; 80, 91; 80, 92; 81, 93; 83, 94; 84, 95; 84, 96; 85, 97; 90, 98; 90, 99; 94, 100; 94, 101; 98, 102; 99, 103; 101, 104; 104, 105; 104, 106 | def sort_dict(dict_, part='keys', key=None, reverse=False):
"""
sorts a dictionary by its values or its keys
Args:
dict_ (dict_): a dictionary
part (str): specifies to sort by keys or values
key (Optional[func]): a function that takes specified part
and returns a sortable value
reverse (bool): (Defaults to False) - True for descinding order. False
for ascending order.
Returns:
OrderedDict: sorted dictionary
CommandLine:
python -m utool.util_dict sort_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'a': 3, 'c': 2, 'b': 1}
>>> results = []
>>> results.append(sort_dict(dict_, 'keys'))
>>> results.append(sort_dict(dict_, 'vals'))
>>> results.append(sort_dict(dict_, 'vals', lambda x: -x))
>>> result = ut.repr4(results)
>>> print(result)
[
{'a': 3, 'b': 1, 'c': 2},
{'b': 1, 'c': 2, 'a': 3},
{'a': 3, 'c': 2, 'b': 1},
]
"""
if part == 'keys':
index = 0
elif part in {'vals', 'values'}:
index = 1
else:
raise ValueError('Unknown method part=%r' % (part,))
if key is None:
_key = op.itemgetter(index)
else:
def _key(item):
return key(item[index])
sorted_items = sorted(six.iteritems(dict_), key=_key, reverse=reverse)
sorted_dict = OrderedDict(sorted_items)
return sorted_dict |
0, module; 1, function_definition; 2, function_name:order_dict_by; 3, parameters; 4, block; 5, identifier:dict_; 6, identifier:key_order; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, comment:r"""
Reorders items in a dictionary according to a custom key order
Args:
dict_ (dict_): a dictionary
key_order (list): custom key order
Returns:
OrderedDict: sorted_dict
CommandLine:
python -m utool.util_dict --exec-order_dict_by
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 1, 2: 2, 3: 3, 4: 4}
>>> key_order = [4, 2, 3, 1]
>>> sorted_dict = order_dict_by(dict_, key_order)
>>> result = ('sorted_dict = %s' % (ut.repr4(sorted_dict, nl=False),))
>>> print(result)
>>> assert result == 'sorted_dict = {4: 4, 2: 2, 3: 3, 1: 1}'
"""; 14, assignment; 15, assignment; 16, assignment; 17, assignment; 18, identifier:sorted_dict; 19, identifier:dict_keys; 20, call; 21, identifier:other_keys; 22, binary_operator:dict_keys - set(key_order); 23, identifier:key_order; 24, call; 25, identifier:sorted_dict; 26, call; 27, identifier:set; 28, argument_list; 29, identifier:dict_keys; 30, call; 31, attribute; 32, argument_list; 33, identifier:OrderedDict; 34, generator_expression; 35, call; 36, identifier:set; 37, argument_list; 38, identifier:it; 39, identifier:chain; 40, identifier:key_order; 41, identifier:other_keys; 42, tuple; 43, for_in_clause; 44, if_clause; 45, attribute; 46, argument_list; 47, identifier:key_order; 48, identifier:key; 49, subscript; 50, identifier:key; 51, identifier:key_order; 52, comparison_operator:key in dict_keys; 53, identifier:dict_; 54, identifier:keys; 55, identifier:dict_; 56, identifier:key; 57, identifier:key; 58, identifier:dict_keys | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 12, 18; 14, 19; 14, 20; 15, 21; 15, 22; 16, 23; 16, 24; 17, 25; 17, 26; 20, 27; 20, 28; 22, 29; 22, 30; 24, 31; 24, 32; 26, 33; 26, 34; 28, 35; 30, 36; 30, 37; 31, 38; 31, 39; 32, 40; 32, 41; 34, 42; 34, 43; 34, 44; 35, 45; 35, 46; 37, 47; 42, 48; 42, 49; 43, 50; 43, 51; 44, 52; 45, 53; 45, 54; 49, 55; 49, 56; 52, 57; 52, 58 | def order_dict_by(dict_, key_order):
r"""
Reorders items in a dictionary according to a custom key order
Args:
dict_ (dict_): a dictionary
key_order (list): custom key order
Returns:
OrderedDict: sorted_dict
CommandLine:
python -m utool.util_dict --exec-order_dict_by
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 1, 2: 2, 3: 3, 4: 4}
>>> key_order = [4, 2, 3, 1]
>>> sorted_dict = order_dict_by(dict_, key_order)
>>> result = ('sorted_dict = %s' % (ut.repr4(sorted_dict, nl=False),))
>>> print(result)
>>> assert result == 'sorted_dict = {4: 4, 2: 2, 3: 3, 1: 1}'
"""
dict_keys = set(dict_.keys())
other_keys = dict_keys - set(key_order)
key_order = it.chain(key_order, other_keys)
sorted_dict = OrderedDict(
(key, dict_[key]) for key in key_order if key in dict_keys
)
return sorted_dict |
0, module; 1, function_definition; 2, function_name:iteritems_sorted; 3, parameters; 4, block; 5, identifier:dict_; 6, expression_statement; 7, if_statement; 8, comment:""" change to iteritems ordered """; 9, call; 10, block; 11, else_clause; 12, identifier:isinstance; 13, argument_list; 14, return_statement; 15, block; 16, identifier:dict_; 17, identifier:OrderedDict; 18, call; 19, return_statement; 20, attribute; 21, argument_list; 22, call; 23, identifier:six; 24, identifier:iteritems; 25, identifier:dict_; 26, identifier:iter; 27, argument_list; 28, call; 29, identifier:sorted; 30, argument_list; 31, call; 32, attribute; 33, argument_list; 34, identifier:six; 35, identifier:iteritems; 36, identifier:dict_ | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 9, 12; 9, 13; 10, 14; 11, 15; 13, 16; 13, 17; 14, 18; 15, 19; 18, 20; 18, 21; 19, 22; 20, 23; 20, 24; 21, 25; 22, 26; 22, 27; 27, 28; 28, 29; 28, 30; 30, 31; 31, 32; 31, 33; 32, 34; 32, 35; 33, 36 | def iteritems_sorted(dict_):
""" change to iteritems ordered """
if isinstance(dict_, OrderedDict):
return six.iteritems(dict_)
else:
return iter(sorted(six.iteritems(dict_))) |
0, module; 1, function_definition; 2, function_name:clean_line_profile_text; 3, parameters; 4, block; 5, identifier:text; 6, expression_statement; 7, comment:#; 8, expression_statement; 9, comment:#profile_block_list = fix_rawprofile_blocks(profile_block_list); 10, comment:#---; 11, comment:# FIXME can be written much nicer; 12, expression_statement; 13, comment:# Sort the blocks by time; 14, expression_statement; 15, expression_statement; 16, for_statement; 17, comment:# Rejoin output text; 18, expression_statement; 19, comment:#---; 20, comment:# Hack in a profile summary; 21, expression_statement; 22, expression_statement; 23, return_statement; 24, comment:"""
Sorts the output from line profile by execution time
Removes entries which were not run
"""; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, pattern_list; 30, identifier:sorted_lists; 31, block; 32, assignment; 33, assignment; 34, assignment; 35, expression_list; 36, identifier:profile_block_list; 37, call; 38, pattern_list; 39, call; 40, identifier:sorted_lists; 41, call; 42, identifier:newlist; 43, subscript; 44, identifier:key; 45, identifier:val; 46, expression_statement; 47, identifier:output_text; 48, call; 49, identifier:summary_text; 50, call; 51, identifier:output_text; 52, identifier:output_text; 53, identifier:output_text; 54, identifier:summary_text; 55, identifier:parse_rawprofile_blocks; 56, argument_list; 57, identifier:prefix_list; 58, identifier:timemap; 59, identifier:parse_timemap_from_blocks; 60, argument_list; 61, identifier:sorted; 62, argument_list; 63, identifier:prefix_list; 64, slice; 65, call; 66, attribute; 67, argument_list; 68, identifier:get_summary; 69, argument_list; 70, identifier:text; 71, identifier:profile_block_list; 72, call; 73, keyword_argument; 74, attribute; 75, argument_list; 76, string; 77, identifier:join; 78, identifier:newlist; 79, identifier:profile_block_list; 80, attribute; 81, argument_list; 82, identifier:key; 83, call; 84, identifier:newlist; 85, identifier:extend; 86, identifier:val; 87, string_content; 88, identifier:six; 89, identifier:iteritems; 90, identifier:timemap; 91, attribute; 92, argument_list; 93, escape_sequence:\n; 94, identifier:operator; 95, identifier:itemgetter; 96, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 6, 24; 8, 25; 12, 26; 14, 27; 15, 28; 16, 29; 16, 30; 16, 31; 18, 32; 21, 33; 22, 34; 23, 35; 25, 36; 25, 37; 26, 38; 26, 39; 27, 40; 27, 41; 28, 42; 28, 43; 29, 44; 29, 45; 31, 46; 32, 47; 32, 48; 33, 49; 33, 50; 34, 51; 34, 52; 35, 53; 35, 54; 37, 55; 37, 56; 38, 57; 38, 58; 39, 59; 39, 60; 41, 61; 41, 62; 43, 63; 43, 64; 46, 65; 48, 66; 48, 67; 50, 68; 50, 69; 56, 70; 60, 71; 62, 72; 62, 73; 65, 74; 65, 75; 66, 76; 66, 77; 67, 78; 69, 79; 72, 80; 72, 81; 73, 82; 73, 83; 74, 84; 74, 85; 75, 86; 76, 87; 80, 88; 80, 89; 81, 90; 83, 91; 83, 92; 87, 93; 91, 94; 91, 95; 92, 96 | def clean_line_profile_text(text):
"""
Sorts the output from line profile by execution time
Removes entries which were not run
"""
#
profile_block_list = parse_rawprofile_blocks(text)
#profile_block_list = fix_rawprofile_blocks(profile_block_list)
#---
# FIXME can be written much nicer
prefix_list, timemap = parse_timemap_from_blocks(profile_block_list)
# Sort the blocks by time
sorted_lists = sorted(six.iteritems(timemap), key=operator.itemgetter(0))
newlist = prefix_list[:]
for key, val in sorted_lists:
newlist.extend(val)
# Rejoin output text
output_text = '\n'.join(newlist)
#---
# Hack in a profile summary
summary_text = get_summary(profile_block_list)
output_text = output_text
return output_text, summary_text |
0, module; 1, function_definition; 2, function_name:list_str; 3, parameters; 4, block; 5, identifier:list_; 6, dictionary_splat_pattern; 7, expression_statement; 8, import_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, comment:# Doesn't actually put in trailing comma if on same line; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, if_statement; 25, if_statement; 26, if_statement; 27, comment:# TODO: rectify with dict_truncate; 28, expression_statement; 29, if_statement; 30, return_statement; 31, identifier:listkw; 32, comment:r"""
Makes a pretty list string
Args:
list_ (list): input list
**listkw: nl, newlines, packed, truncate, nobr, nobraces, itemsep,
trailing_sep, truncatekw, strvals, recursive,
indent_, precision, use_numpy, with_dtype, force_dtype,
stritems, strkeys, align, explicit, sorted_, key_order,
key_order_metric, maxlen
Returns:
str: retstr
CommandLine:
python -m utool.util_str --test-list_str
python -m utool.util_str --exec-list_str --truncate=True
python -m utool.util_str --exec-list_str --truncate=0
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> list_ = [[(('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, '')],
>>> [(['--nodyn'], 1, False, ''), (['--nodyn'], 1, False, '')]]
>>> listkw = {'nl': 2}
>>> result = list_str(list_, **listkw)
>>> print(result)
[
[
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
],
[
(['--nodyn'], 1, False, ''),
(['--nodyn'], 1, False, ''),
],
]
"""; 33, aliased_import; 34, assignment; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, assignment; 44, assignment; 45, assignment; 46, assignment; 47, assignment; 48, identifier:nobraces; 49, block; 50, elif_clause; 51, elif_clause; 52, else_clause; 53, comparison_operator:len(itemstr_list) == 0; 54, block; 55, boolean_operator; 56, block; 57, else_clause; 58, assignment; 59, identifier:do_truncate; 60, block; 61, identifier:retstr; 62, dotted_name; 63, identifier:ut; 64, identifier:newlines; 65, call; 66, identifier:packed; 67, call; 68, identifier:truncate; 69, call; 70, subscript; 71, call; 72, subscript; 73, call; 74, subscript; 75, call; 76, identifier:nobraces; 77, call; 78, identifier:itemsep; 79, call; 80, identifier:trailing_sep; 81, call; 82, identifier:with_comma; 83, True; 84, identifier:itemstr_list; 85, call; 86, identifier:is_tuple; 87, call; 88, identifier:is_set; 89, call; 90, identifier:is_onetup; 91, boolean_operator; 92, expression_statement; 93, identifier:is_tuple; 94, block; 95, identifier:is_set; 96, block; 97, block; 98, call; 99, integer:0; 100, expression_statement; 101, comparison_operator:newlines is not False; 102, parenthesized_expression; 103, expression_statement; 104, if_statement; 105, block; 106, identifier:do_truncate; 107, boolean_operator; 108, expression_statement; 109, expression_statement; 110, identifier:utool; 111, attribute; 112, argument_list; 113, attribute; 114, argument_list; 115, attribute; 116, argument_list; 117, identifier:listkw; 118, string; 119, identifier:_rectify_countdown_or_bool; 120, argument_list; 121, identifier:listkw; 122, string; 123, identifier:_rectify_countdown_or_bool; 124, argument_list; 125, identifier:listkw; 126, string; 127, identifier:_rectify_countdown_or_bool; 128, argument_list; 129, attribute; 130, argument_list; 131, attribute; 132, argument_list; 133, attribute; 134, argument_list; 135, identifier:get_itemstr_list; 136, argument_list; 137, identifier:isinstance; 138, argument_list; 139, identifier:isinstance; 140, argument_list; 141, call; 142, comparison_operator:len(list_) <= 1; 143, assignment; 144, expression_statement; 145, expression_statement; 146, expression_statement; 147, identifier:len; 148, argument_list; 149, assignment; 150, identifier:newlines; 151, False; 152, boolean_operator; 153, assignment; 154, identifier:nobraces; 155, block; 156, else_clause; 157, expression_statement; 158, expression_statement; 159, if_statement; 160, expression_statement; 161, comparison_operator:truncate is not False; 162, parenthesized_expression; 163, assignment; 164, assignment; 165, identifier:listkw; 166, identifier:pop; 167, string; 168, call; 169, identifier:listkw; 170, identifier:pop; 171, string; 172, False; 173, identifier:listkw; 174, identifier:pop; 175, string; 176, False; 177, string_content:nl; 178, identifier:newlines; 179, string_content:truncate; 180, identifier:truncate; 181, string_content:packed; 182, identifier:packed; 183, identifier:listkw; 184, identifier:pop; 185, string; 186, call; 187, identifier:listkw; 188, identifier:get; 189, string; 190, string; 191, identifier:listkw; 192, identifier:get; 193, string; 194, True; 195, identifier:list_; 196, dictionary_splat; 197, identifier:list_; 198, identifier:tuple; 199, identifier:list_; 200, tuple; 201, identifier:isinstance; 202, argument_list; 203, call; 204, integer:1; 205, pattern_list; 206, expression_list; 207, assignment; 208, assignment; 209, assignment; 210, identifier:itemstr_list; 211, identifier:newlines; 212, False; 213, comparison_operator:newlines is True; 214, comparison_operator:newlines > 0; 215, identifier:sep; 216, conditional_expression:',\n' if with_comma else '\n'; 217, expression_statement; 218, if_statement; 219, expression_statement; 220, block; 221, assignment; 222, assignment; 223, identifier:is_onetup; 224, block; 225, assignment; 226, identifier:truncate; 227, False; 228, boolean_operator; 229, identifier:truncatekw; 230, call; 231, identifier:retstr; 232, call; 233, string_content:nl; 234, attribute; 235, argument_list; 236, string_content:packed; 237, string_content:truncate; 238, string_content:nobr; 239, attribute; 240, argument_list; 241, string_content:itemsep; 242, string_content:; 243, string_content:trailing_sep; 244, identifier:listkw; 245, identifier:set; 246, identifier:frozenset; 247, attribute; 248, identifier:list_; 249, parenthesized_expression; 250, identifier:len; 251, argument_list; 252, identifier:lbr; 253, identifier:rbr; 254, string; 255, string; 256, pattern_list; 257, expression_list; 258, pattern_list; 259, expression_list; 260, pattern_list; 261, expression_list; 262, identifier:newlines; 263, True; 264, identifier:newlines; 265, integer:0; 266, string; 267, identifier:with_comma; 268, string; 269, assignment; 270, identifier:trailing_sep; 271, block; 272, assignment; 273, if_statement; 274, expression_statement; 275, identifier:sep; 276, conditional_expression:',' + itemsep if with_comma else itemsep; 277, identifier:body_str; 278, call; 279, expression_statement; 280, identifier:retstr; 281, parenthesized_expression; 282, comparison_operator:truncate is True; 283, comparison_operator:truncate == 0; 284, attribute; 285, argument_list; 286, identifier:truncate_str; 287, argument_list; 288, identifier:listkw; 289, identifier:pop; 290, string; 291, integer:1; 292, identifier:listkw; 293, identifier:pop; 294, string; 295, False; 296, identifier:ut; 297, identifier:oset; 298, identifier:tuple; 299, identifier:list_; 300, identifier:lbr; 301, identifier:rbr; 302, string; 303, string; 304, identifier:lbr; 305, identifier:rbr; 306, string; 307, string; 308, identifier:lbr; 309, identifier:rbr; 310, string; 311, string; 312, string_content; 313, string_content; 314, identifier:body_str; 315, call; 316, expression_statement; 317, identifier:retstr; 318, identifier:body_str; 319, identifier:packed; 320, comment:# DEPRICATE?; 321, block; 322, else_clause; 323, assignment; 324, binary_operator:',' + itemsep; 325, identifier:with_comma; 326, identifier:itemsep; 327, attribute; 328, argument_list; 329, augmented_assignment; 330, binary_operator:lbr + body_str + rbr; 331, identifier:truncate; 332, True; 333, identifier:truncate; 334, integer:0; 335, identifier:listkw; 336, identifier:get; 337, string; 338, dictionary; 339, identifier:retstr; 340, dictionary_splat; 341, string_content:newlines; 342, string_content:nobraces; 343, string_content:(; 344, string_content:); 345, string_content:{; 346, string_content:}; 347, string_content:[; 348, string_content:]; 349, escape_sequence:\n; 350, escape_sequence:\n; 351, attribute; 352, argument_list; 353, augmented_assignment; 354, expression_statement; 355, expression_statement; 356, if_statement; 357, expression_statement; 358, block; 359, identifier:retstr; 360, identifier:braced_body_str; 361, string; 362, identifier:itemsep; 363, identifier:sep; 364, identifier:join; 365, identifier:itemstr_list; 366, identifier:body_str; 367, string; 368, binary_operator:lbr + body_str; 369, identifier:rbr; 370, string_content:truncatekw; 371, identifier:truncatekw; 372, identifier:sep; 373, identifier:join; 374, identifier:itemstr_list; 375, identifier:body_str; 376, string; 377, assignment; 378, assignment; 379, identifier:trailing_sep; 380, block; 381, assignment; 382, expression_statement; 383, if_statement; 384, expression_statement; 385, string_content:,; 386, string_content:,; 387, identifier:lbr; 388, identifier:body_str; 389, string_content:,; 390, identifier:joinstr; 391, binary_operator:sep + itemsep * len(lbr); 392, identifier:body_str; 393, call; 394, expression_statement; 395, identifier:braced_body_str; 396, parenthesized_expression; 397, assignment; 398, identifier:trailing_sep; 399, block; 400, assignment; 401, identifier:sep; 402, binary_operator:itemsep * len(lbr); 403, attribute; 404, argument_list; 405, augmented_assignment; 406, binary_operator:lbr + '' + body_str + '' + rbr; 407, identifier:body_str; 408, call; 409, expression_statement; 410, identifier:braced_body_str; 411, parenthesized_expression; 412, identifier:itemsep; 413, call; 414, identifier:joinstr; 415, identifier:join; 416, list_comprehension; 417, identifier:body_str; 418, string; 419, binary_operator:lbr + '' + body_str + ''; 420, identifier:rbr; 421, attribute; 422, argument_list; 423, augmented_assignment; 424, binary_operator:lbr + '\n' + body_str + '\n' + rbr; 425, identifier:len; 426, argument_list; 427, identifier:itemstr; 428, for_in_clause; 429, string_content:,; 430, binary_operator:lbr + '' + body_str; 431, string; 432, identifier:sep; 433, identifier:join; 434, list_comprehension; 435, identifier:body_str; 436, string; 437, binary_operator:lbr + '\n' + body_str + '\n'; 438, identifier:rbr; 439, identifier:lbr; 440, identifier:itemstr; 441, identifier:itemstr_list; 442, binary_operator:lbr + ''; 443, identifier:body_str; 444, call; 445, for_in_clause; 446, string_content:,; 447, binary_operator:lbr + '\n' + body_str; 448, string; 449, identifier:lbr; 450, string; 451, attribute; 452, argument_list; 453, identifier:itemstr; 454, identifier:itemstr_list; 455, binary_operator:lbr + '\n'; 456, identifier:body_str; 457, string_content; 458, identifier:ut; 459, identifier:indent; 460, identifier:itemstr; 461, identifier:lbr; 462, string; 463, escape_sequence:\n; 464, string_content; 465, escape_sequence:\n | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 6, 31; 7, 32; 8, 33; 9, 34; 10, 35; 11, 36; 12, 37; 13, 38; 14, 39; 15, 40; 16, 41; 18, 42; 19, 43; 20, 44; 21, 45; 22, 46; 23, 47; 24, 48; 24, 49; 24, 50; 24, 51; 24, 52; 25, 53; 25, 54; 26, 55; 26, 56; 26, 57; 28, 58; 29, 59; 29, 60; 30, 61; 33, 62; 33, 63; 34, 64; 34, 65; 35, 66; 35, 67; 36, 68; 36, 69; 37, 70; 37, 71; 38, 72; 38, 73; 39, 74; 39, 75; 40, 76; 40, 77; 41, 78; 41, 79; 42, 80; 42, 81; 43, 82; 43, 83; 44, 84; 44, 85; 45, 86; 45, 87; 46, 88; 46, 89; 47, 90; 47, 91; 49, 92; 50, 93; 50, 94; 51, 95; 51, 96; 52, 97; 53, 98; 53, 99; 54, 100; 55, 101; 55, 102; 56, 103; 56, 104; 57, 105; 58, 106; 58, 107; 60, 108; 60, 109; 62, 110; 65, 111; 65, 112; 67, 113; 67, 114; 69, 115; 69, 116; 70, 117; 70, 118; 71, 119; 71, 120; 72, 121; 72, 122; 73, 123; 73, 124; 74, 125; 74, 126; 75, 127; 75, 128; 77, 129; 77, 130; 79, 131; 79, 132; 81, 133; 81, 134; 85, 135; 85, 136; 87, 137; 87, 138; 89, 139; 89, 140; 91, 141; 91, 142; 92, 143; 94, 144; 96, 145; 97, 146; 98, 147; 98, 148; 100, 149; 101, 150; 101, 151; 102, 152; 103, 153; 104, 154; 104, 155; 104, 156; 105, 157; 105, 158; 105, 159; 105, 160; 107, 161; 107, 162; 108, 163; 109, 164; 111, 165; 111, 166; 112, 167; 112, 168; 113, 169; 113, 170; 114, 171; 114, 172; 115, 173; 115, 174; 116, 175; 116, 176; 118, 177; 120, 178; 122, 179; 124, 180; 126, 181; 128, 182; 129, 183; 129, 184; 130, 185; 130, 186; 131, 187; 131, 188; 132, 189; 132, 190; 133, 191; 133, 192; 134, 193; 134, 194; 136, 195; 136, 196; 138, 197; 138, 198; 140, 199; 140, 200; 141, 201; 141, 202; 142, 203; 142, 204; 143, 205; 143, 206; 144, 207; 145, 208; 146, 209; 148, 210; 149, 211; 149, 212; 152, 213; 152, 214; 153, 215; 153, 216; 155, 217; 155, 218; 155, 219; 156, 220; 157, 221; 158, 222; 159, 223; 159, 224; 160, 225; 161, 226; 161, 227; 162, 228; 163, 229; 163, 230; 164, 231; 164, 232; 167, 233; 168, 234; 168, 235; 171, 236; 175, 237; 185, 238; 186, 239; 186, 240; 189, 241; 190, 242; 193, 243; 196, 244; 200, 245; 200, 246; 200, 247; 202, 248; 202, 249; 203, 250; 203, 251; 205, 252; 205, 253; 206, 254; 206, 255; 207, 256; 207, 257; 208, 258; 208, 259; 209, 260; 209, 261; 213, 262; 213, 263; 214, 264; 214, 265; 216, 266; 216, 267; 216, 268; 217, 269; 218, 270; 218, 271; 219, 272; 220, 273; 220, 274; 221, 275; 221, 276; 222, 277; 222, 278; 224, 279; 225, 280; 225, 281; 228, 282; 228, 283; 230, 284; 230, 285; 232, 286; 232, 287; 234, 288; 234, 289; 235, 290; 235, 291; 239, 292; 239, 293; 240, 294; 240, 295; 247, 296; 247, 297; 249, 298; 251, 299; 256, 300; 256, 301; 257, 302; 257, 303; 258, 304; 258, 305; 259, 306; 259, 307; 260, 308; 260, 309; 261, 310; 261, 311; 266, 312; 268, 313; 269, 314; 269, 315; 271, 316; 272, 317; 272, 318; 273, 319; 273, 320; 273, 321; 273, 322; 274, 323; 276, 324; 276, 325; 276, 326; 278, 327; 278, 328; 279, 329; 281, 330; 282, 331; 282, 332; 283, 333; 283, 334; 284, 335; 284, 336; 285, 337; 285, 338; 287, 339; 287, 340; 290, 341; 294, 342; 302, 343; 303, 344; 306, 345; 307, 346; 310, 347; 311, 348; 312, 349; 313, 350; 315, 351; 315, 352; 316, 353; 321, 354; 321, 355; 321, 356; 321, 357; 322, 358; 323, 359; 323, 360; 324, 361; 324, 362; 327, 363; 327, 364; 328, 365; 329, 366; 329, 367; 330, 368; 330, 369; 337, 370; 340, 371; 351, 372; 351, 373; 352, 374; 353, 375; 353, 376; 354, 377; 355, 378; 356, 379; 356, 380; 357, 381; 358, 382; 358, 383; 358, 384; 361, 385; 367, 386; 368, 387; 368, 388; 376, 389; 377, 390; 377, 391; 378, 392; 378, 393; 380, 394; 381, 395; 381, 396; 382, 397; 383, 398; 383, 399; 384, 400; 391, 401; 391, 402; 393, 403; 393, 404; 394, 405; 396, 406; 397, 407; 397, 408; 399, 409; 400, 410; 400, 411; 402, 412; 402, 413; 403, 414; 403, 415; 404, 416; 405, 417; 405, 418; 406, 419; 406, 420; 408, 421; 408, 422; 409, 423; 411, 424; 413, 425; 413, 426; 416, 427; 416, 428; 418, 429; 419, 430; 419, 431; 421, 432; 421, 433; 422, 434; 423, 435; 423, 436; 424, 437; 424, 438; 426, 439; 428, 440; 428, 441; 430, 442; 430, 443; 434, 444; 434, 445; 436, 446; 437, 447; 437, 448; 442, 449; 442, 450; 444, 451; 444, 452; 445, 453; 445, 454; 447, 455; 447, 456; 448, 457; 451, 458; 451, 459; 452, 460; 455, 461; 455, 462; 457, 463; 462, 464; 464, 465 | def list_str(list_, **listkw):
r"""
Makes a pretty list string
Args:
list_ (list): input list
**listkw: nl, newlines, packed, truncate, nobr, nobraces, itemsep,
trailing_sep, truncatekw, strvals, recursive,
indent_, precision, use_numpy, with_dtype, force_dtype,
stritems, strkeys, align, explicit, sorted_, key_order,
key_order_metric, maxlen
Returns:
str: retstr
CommandLine:
python -m utool.util_str --test-list_str
python -m utool.util_str --exec-list_str --truncate=True
python -m utool.util_str --exec-list_str --truncate=0
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> list_ = [[(('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, ''),
>>> (('--verbose-qt', '--verbqt'), 1, False, '')],
>>> [(['--nodyn'], 1, False, ''), (['--nodyn'], 1, False, '')]]
>>> listkw = {'nl': 2}
>>> result = list_str(list_, **listkw)
>>> print(result)
[
[
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
(('--verbose-qt', '--verbqt'), 1, False, ''),
],
[
(['--nodyn'], 1, False, ''),
(['--nodyn'], 1, False, ''),
],
]
"""
import utool as ut
newlines = listkw.pop('nl', listkw.pop('newlines', 1))
packed = listkw.pop('packed', False)
truncate = listkw.pop('truncate', False)
listkw['nl'] = _rectify_countdown_or_bool(newlines)
listkw['truncate'] = _rectify_countdown_or_bool(truncate)
listkw['packed'] = _rectify_countdown_or_bool(packed)
nobraces = listkw.pop('nobr', listkw.pop('nobraces', False))
itemsep = listkw.get('itemsep', ' ')
# Doesn't actually put in trailing comma if on same line
trailing_sep = listkw.get('trailing_sep', True)
with_comma = True
itemstr_list = get_itemstr_list(list_, **listkw)
is_tuple = isinstance(list_, tuple)
is_set = isinstance(list_, (set, frozenset, ut.oset))
is_onetup = isinstance(list_, (tuple)) and len(list_) <= 1
if nobraces:
lbr, rbr = '', ''
elif is_tuple:
lbr, rbr = '(', ')'
elif is_set:
lbr, rbr = '{', '}'
else:
lbr, rbr = '[', ']'
if len(itemstr_list) == 0:
newlines = False
if newlines is not False and (newlines is True or newlines > 0):
sep = ',\n' if with_comma else '\n'
if nobraces:
body_str = sep.join(itemstr_list)
if trailing_sep:
body_str += ','
retstr = body_str
else:
if packed:
# DEPRICATE?
joinstr = sep + itemsep * len(lbr)
body_str = joinstr.join([itemstr for itemstr in itemstr_list])
if trailing_sep:
body_str += ','
braced_body_str = (lbr + '' + body_str + '' + rbr)
else:
body_str = sep.join([
ut.indent(itemstr) for itemstr in itemstr_list])
if trailing_sep:
body_str += ','
braced_body_str = (lbr + '\n' + body_str + '\n' + rbr)
retstr = braced_body_str
else:
sep = ',' + itemsep if with_comma else itemsep
body_str = sep.join(itemstr_list)
if is_onetup:
body_str += ','
retstr = (lbr + body_str + rbr)
# TODO: rectify with dict_truncate
do_truncate = truncate is not False and (truncate is True or truncate == 0)
if do_truncate:
truncatekw = listkw.get('truncatekw', {})
retstr = truncate_str(retstr, **truncatekw)
return retstr |
0, module; 1, function_definition; 2, function_name:generate_psms_quanted; 3, parameters; 4, block; 5, identifier:quantdb; 6, identifier:tsvfn; 7, identifier:isob_header; 8, identifier:oldheader; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, for_statement; 15, identifier:isobaric; 16, False; 17, identifier:precursor; 18, False; 19, comment:"""Takes dbfn and connects, gets quants for each line in tsvfn, sorts
them in line by using keys in quantheader list."""; 20, assignment; 21, assignment; 22, pattern_list; 23, call; 24, block; 25, pattern_list; 26, call; 27, identifier:quant; 28, call; 29, identifier:rownr; 30, identifier:psm; 31, identifier:enumerate; 32, argument_list; 33, expression_statement; 34, if_statement; 35, if_statement; 36, expression_statement; 37, identifier:allquants; 38, identifier:sqlfields; 39, attribute; 40, argument_list; 41, identifier:next; 42, argument_list; 43, call; 44, assignment; 45, identifier:precursor; 46, block; 47, identifier:isobaric; 48, block; 49, else_clause; 50, yield; 51, identifier:quantdb; 52, identifier:select_all_psm_quants; 53, identifier:isobaric; 54, identifier:precursor; 55, identifier:allquants; 56, attribute; 57, argument_list; 58, identifier:outpsm; 59, dictionary_comprehension; 60, expression_statement; 61, if_statement; 62, expression_statement; 63, expression_statement; 64, while_statement; 65, expression_statement; 66, block; 67, identifier:outpsm; 68, identifier:readers; 69, identifier:generate_tsv_psms; 70, identifier:tsvfn; 71, identifier:oldheader; 72, pair; 73, for_in_clause; 74, assignment; 75, comparison_operator:pquant is None; 76, block; 77, call; 78, assignment; 79, comparison_operator:quant[0] == rownr; 80, block; 81, call; 82, try_statement; 83, identifier:x; 84, identifier:y; 85, pattern_list; 86, call; 87, identifier:pquant; 88, subscript; 89, identifier:pquant; 90, None; 91, expression_statement; 92, attribute; 93, argument_list; 94, identifier:isoquants; 95, dictionary; 96, subscript; 97, identifier:rownr; 98, expression_statement; 99, try_statement; 100, attribute; 101, argument_list; 102, block; 103, except_clause; 104, identifier:x; 105, identifier:y; 106, attribute; 107, argument_list; 108, identifier:quant; 109, subscript; 110, assignment; 111, identifier:outpsm; 112, identifier:update; 113, dictionary; 114, identifier:quant; 115, integer:0; 116, call; 117, block; 118, except_clause; 119, identifier:outpsm; 120, identifier:update; 121, call; 122, expression_statement; 123, identifier:StopIteration; 124, comment:# last PSM, needs explicit yield/break or it will not be yielded; 125, block; 126, identifier:psm; 127, identifier:items; 128, identifier:sqlfields; 129, string; 130, identifier:pquant; 131, string; 132, pair; 133, attribute; 134, argument_list; 135, expression_statement; 136, identifier:StopIteration; 137, comment:# last PSM, break from while loop or it is not yielded at all; 138, block; 139, identifier:get_quant_NAs; 140, argument_list; 141, assignment; 142, expression_statement; 143, break_statement; 144, string_content:precursor; 145, string_content:NA; 146, attribute; 147, call; 148, identifier:isoquants; 149, identifier:update; 150, dictionary; 151, assignment; 152, break_statement; 153, identifier:isoquants; 154, identifier:isob_header; 155, identifier:quant; 156, call; 157, yield; 158, identifier:mzidtsvdata; 159, identifier:HEADER_PRECURSOR_QUANT; 160, identifier:str; 161, argument_list; 162, pair; 163, identifier:quant; 164, call; 165, identifier:next; 166, argument_list; 167, identifier:outpsm; 168, identifier:pquant; 169, subscript; 170, call; 171, identifier:next; 172, argument_list; 173, identifier:allquants; 174, identifier:quant; 175, subscript; 176, identifier:str; 177, argument_list; 178, identifier:allquants; 179, identifier:sqlfields; 180, string; 181, subscript; 182, string_content:isochan; 183, identifier:quant; 184, subscript; 185, identifier:sqlfields; 186, string; 187, string_content:isoquant | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 9, 15; 9, 16; 10, 17; 10, 18; 11, 19; 12, 20; 13, 21; 14, 22; 14, 23; 14, 24; 20, 25; 20, 26; 21, 27; 21, 28; 22, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 24, 35; 24, 36; 25, 37; 25, 38; 26, 39; 26, 40; 28, 41; 28, 42; 32, 43; 33, 44; 34, 45; 34, 46; 35, 47; 35, 48; 35, 49; 36, 50; 39, 51; 39, 52; 40, 53; 40, 54; 42, 55; 43, 56; 43, 57; 44, 58; 44, 59; 46, 60; 46, 61; 46, 62; 48, 63; 48, 64; 48, 65; 49, 66; 50, 67; 56, 68; 56, 69; 57, 70; 57, 71; 59, 72; 59, 73; 60, 74; 61, 75; 61, 76; 62, 77; 63, 78; 64, 79; 64, 80; 65, 81; 66, 82; 72, 83; 72, 84; 73, 85; 73, 86; 74, 87; 74, 88; 75, 89; 75, 90; 76, 91; 77, 92; 77, 93; 78, 94; 78, 95; 79, 96; 79, 97; 80, 98; 80, 99; 81, 100; 81, 101; 82, 102; 82, 103; 85, 104; 85, 105; 86, 106; 86, 107; 88, 108; 88, 109; 91, 110; 92, 111; 92, 112; 93, 113; 96, 114; 96, 115; 98, 116; 99, 117; 99, 118; 100, 119; 100, 120; 101, 121; 102, 122; 103, 123; 103, 124; 103, 125; 106, 126; 106, 127; 109, 128; 109, 129; 110, 130; 110, 131; 113, 132; 116, 133; 116, 134; 117, 135; 118, 136; 118, 137; 118, 138; 121, 139; 121, 140; 122, 141; 125, 142; 125, 143; 129, 144; 131, 145; 132, 146; 132, 147; 133, 148; 133, 149; 134, 150; 135, 151; 138, 152; 140, 153; 140, 154; 141, 155; 141, 156; 142, 157; 146, 158; 146, 159; 147, 160; 147, 161; 150, 162; 151, 163; 151, 164; 156, 165; 156, 166; 157, 167; 161, 168; 162, 169; 162, 170; 164, 171; 164, 172; 166, 173; 169, 174; 169, 175; 170, 176; 170, 177; 172, 178; 175, 179; 175, 180; 177, 181; 180, 182; 181, 183; 181, 184; 184, 185; 184, 186; 186, 187 | def generate_psms_quanted(quantdb, tsvfn, isob_header, oldheader,
isobaric=False, precursor=False):
"""Takes dbfn and connects, gets quants for each line in tsvfn, sorts
them in line by using keys in quantheader list."""
allquants, sqlfields = quantdb.select_all_psm_quants(isobaric, precursor)
quant = next(allquants)
for rownr, psm in enumerate(readers.generate_tsv_psms(tsvfn, oldheader)):
outpsm = {x: y for x, y in psm.items()}
if precursor:
pquant = quant[sqlfields['precursor']]
if pquant is None:
pquant = 'NA'
outpsm.update({mzidtsvdata.HEADER_PRECURSOR_QUANT: str(pquant)})
if isobaric:
isoquants = {}
while quant[0] == rownr:
isoquants.update({quant[sqlfields['isochan']]:
str(quant[sqlfields['isoquant']])})
try:
quant = next(allquants)
except StopIteration:
# last PSM, break from while loop or it is not yielded at all
break
outpsm.update(get_quant_NAs(isoquants, isob_header))
else:
try:
quant = next(allquants)
except StopIteration:
# last PSM, needs explicit yield/break or it will not be yielded
yield outpsm
break
yield outpsm |
0, module; 1, function_definition; 2, function_name:nx_dag_node_rank; 3, parameters; 4, block; 5, identifier:graph; 6, default_parameter; 7, expression_statement; 8, import_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, identifier:nodes; 14, None; 15, comment:"""
Returns rank of nodes that define the "level" each node is on in a
topological sort. This is the same as the Graphviz dot rank.
Ignore:
simple_graph = ut.simplify_graph(exi_graph)
adj_dict = ut.nx_to_adj_dict(simple_graph)
import plottool as pt
pt.qt4ensure()
pt.show_nx(graph)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> adj_dict = {0: [5], 1: [5], 2: [1], 3: [4], 4: [0], 5: [], 6: [4], 7: [9], 8: [6], 9: [1]}
>>> nodes = [2, 1, 5]
>>> f_graph = ut.nx_from_adj_dict(adj_dict, nx.DiGraph)
>>> graph = f_graph.reverse()
>>> #ranks = ut.nx_dag_node_rank(graph, nodes)
>>> ranks = ut.nx_dag_node_rank(graph, nodes)
>>> result = ('ranks = %r' % (ranks,))
>>> print(result)
ranks = [3, 2, 1]
"""; 16, aliased_import; 17, assignment; 18, assignment; 19, assignment; 20, comparison_operator:nodes is None; 21, block; 22, else_clause; 23, dotted_name; 24, identifier:ut; 25, identifier:source; 26, subscript; 27, identifier:longest_paths; 28, call; 29, identifier:node_to_rank; 30, call; 31, identifier:nodes; 32, None; 33, return_statement; 34, block; 35, identifier:utool; 36, call; 37, integer:0; 38, identifier:dict; 39, argument_list; 40, attribute; 41, argument_list; 42, identifier:node_to_rank; 43, expression_statement; 44, return_statement; 45, identifier:list; 46, argument_list; 47, list_comprehension; 48, identifier:ut; 49, identifier:map_dict_vals; 50, identifier:len; 51, identifier:longest_paths; 52, assignment; 53, identifier:ranks; 54, call; 55, tuple; 56, for_in_clause; 57, identifier:ranks; 58, call; 59, attribute; 60, argument_list; 61, identifier:target; 62, call; 63, identifier:target; 64, call; 65, attribute; 66, argument_list; 67, identifier:ut; 68, identifier:nx_source_nodes; 69, identifier:graph; 70, identifier:dag_longest_path; 71, argument_list; 72, attribute; 73, argument_list; 74, identifier:ut; 75, identifier:dict_take; 76, identifier:node_to_rank; 77, identifier:nodes; 78, identifier:graph; 79, identifier:source; 80, identifier:target; 81, identifier:graph; 82, identifier:nodes | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 6, 14; 7, 15; 8, 16; 9, 17; 10, 18; 11, 19; 12, 20; 12, 21; 12, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 20, 32; 21, 33; 22, 34; 23, 35; 26, 36; 26, 37; 28, 38; 28, 39; 30, 40; 30, 41; 33, 42; 34, 43; 34, 44; 36, 45; 36, 46; 39, 47; 40, 48; 40, 49; 41, 50; 41, 51; 43, 52; 44, 53; 46, 54; 47, 55; 47, 56; 52, 57; 52, 58; 54, 59; 54, 60; 55, 61; 55, 62; 56, 63; 56, 64; 58, 65; 58, 66; 59, 67; 59, 68; 60, 69; 62, 70; 62, 71; 64, 72; 64, 73; 65, 74; 65, 75; 66, 76; 66, 77; 71, 78; 71, 79; 71, 80; 72, 81; 72, 82 | def nx_dag_node_rank(graph, nodes=None):
"""
Returns rank of nodes that define the "level" each node is on in a
topological sort. This is the same as the Graphviz dot rank.
Ignore:
simple_graph = ut.simplify_graph(exi_graph)
adj_dict = ut.nx_to_adj_dict(simple_graph)
import plottool as pt
pt.qt4ensure()
pt.show_nx(graph)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> adj_dict = {0: [5], 1: [5], 2: [1], 3: [4], 4: [0], 5: [], 6: [4], 7: [9], 8: [6], 9: [1]}
>>> nodes = [2, 1, 5]
>>> f_graph = ut.nx_from_adj_dict(adj_dict, nx.DiGraph)
>>> graph = f_graph.reverse()
>>> #ranks = ut.nx_dag_node_rank(graph, nodes)
>>> ranks = ut.nx_dag_node_rank(graph, nodes)
>>> result = ('ranks = %r' % (ranks,))
>>> print(result)
ranks = [3, 2, 1]
"""
import utool as ut
source = list(ut.nx_source_nodes(graph))[0]
longest_paths = dict([(target, dag_longest_path(graph, source, target))
for target in graph.nodes()])
node_to_rank = ut.map_dict_vals(len, longest_paths)
if nodes is None:
return node_to_rank
else:
ranks = ut.dict_take(node_to_rank, nodes)
return ranks |
0, module; 1, function_definition; 2, function_name:simplify_graph; 3, parameters; 4, block; 5, identifier:graph; 6, expression_statement; 7, import_statement; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, return_statement; 18, comment:"""
strips out everything but connectivity
Args:
graph (nx.Graph):
Returns:
nx.Graph: new_graph
CommandLine:
python3 -m utool.util_graph simplify_graph --show
python2 -m utool.util_graph simplify_graph --show
python2 -c "import networkx as nx; print(nx.__version__)"
python3 -c "import networkx as nx; print(nx.__version__)"
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> graph = nx.DiGraph([('a', 'b'), ('a', 'c'), ('a', 'e'),
>>> ('a', 'd'), ('b', 'd'), ('c', 'e'),
>>> ('d', 'e'), ('c', 'e'), ('c', 'd')])
>>> new_graph = simplify_graph(graph)
>>> result = ut.repr2(list(new_graph.edges()))
>>> #adj_list = sorted(list(nx.generate_adjlist(new_graph)))
>>> #result = ut.repr2(adj_list)
>>> print(result)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 3), (2, 3), (2, 4), (3, 4)]
['0 1 2 3 4', '1 3 4', '2 4', '3', '4 3']
"""; 19, aliased_import; 20, assignment; 21, assignment; 22, call; 23, block; 24, else_clause; 25, assignment; 26, call; 27, block; 28, else_clause; 29, assignment; 30, assignment; 31, call; 32, call; 33, identifier:new_graph; 34, dotted_name; 35, identifier:ut; 36, identifier:nodes; 37, call; 38, identifier:node_lookup; 39, call; 40, attribute; 41, argument_list; 42, expression_statement; 43, block; 44, identifier:new_nodes; 45, call; 46, attribute; 47, argument_list; 48, expression_statement; 49, block; 50, identifier:cls; 51, attribute; 52, identifier:new_graph; 53, call; 54, attribute; 55, argument_list; 56, attribute; 57, argument_list; 58, identifier:utool; 59, identifier:sorted; 60, argument_list; 61, attribute; 62, argument_list; 63, identifier:graph; 64, identifier:is_multigraph; 65, assignment; 66, expression_statement; 67, attribute; 68, argument_list; 69, identifier:graph; 70, identifier:is_multigraph; 71, assignment; 72, expression_statement; 73, identifier:graph; 74, identifier:__class__; 75, identifier:cls; 76, argument_list; 77, identifier:new_graph; 78, identifier:add_nodes_from; 79, identifier:new_nodes; 80, identifier:new_graph; 81, identifier:add_edges_from; 82, identifier:new_edges; 83, call; 84, identifier:ut; 85, identifier:make_index_lookup; 86, identifier:nodes; 87, identifier:edges; 88, call; 89, assignment; 90, identifier:ut; 91, identifier:take; 92, identifier:node_lookup; 93, identifier:nodes; 94, identifier:new_edges; 95, list_comprehension; 96, assignment; 97, identifier:list; 98, argument_list; 99, identifier:list; 100, argument_list; 101, identifier:edges; 102, call; 103, tuple; 104, for_in_clause; 105, identifier:new_edges; 106, list_comprehension; 107, call; 108, call; 109, identifier:list; 110, argument_list; 111, subscript; 112, subscript; 113, subscript; 114, dictionary; 115, identifier:e; 116, identifier:edges; 117, tuple; 118, for_in_clause; 119, attribute; 120, argument_list; 121, attribute; 122, argument_list; 123, call; 124, identifier:node_lookup; 125, subscript; 126, identifier:node_lookup; 127, subscript; 128, identifier:e; 129, integer:2; 130, subscript; 131, subscript; 132, identifier:e; 133, identifier:edges; 134, identifier:graph; 135, identifier:nodes; 136, identifier:graph; 137, identifier:edges; 138, keyword_argument; 139, attribute; 140, argument_list; 141, identifier:e; 142, integer:0; 143, identifier:e; 144, integer:1; 145, identifier:node_lookup; 146, subscript; 147, identifier:node_lookup; 148, subscript; 149, identifier:keys; 150, True; 151, identifier:graph; 152, identifier:edges; 153, identifier:e; 154, integer:0; 155, identifier:e; 156, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 6, 18; 7, 19; 8, 20; 9, 21; 10, 22; 10, 23; 10, 24; 11, 25; 12, 26; 12, 27; 12, 28; 13, 29; 14, 30; 15, 31; 16, 32; 17, 33; 19, 34; 19, 35; 20, 36; 20, 37; 21, 38; 21, 39; 22, 40; 22, 41; 23, 42; 24, 43; 25, 44; 25, 45; 26, 46; 26, 47; 27, 48; 28, 49; 29, 50; 29, 51; 30, 52; 30, 53; 31, 54; 31, 55; 32, 56; 32, 57; 34, 58; 37, 59; 37, 60; 39, 61; 39, 62; 40, 63; 40, 64; 42, 65; 43, 66; 45, 67; 45, 68; 46, 69; 46, 70; 48, 71; 49, 72; 51, 73; 51, 74; 53, 75; 53, 76; 54, 77; 54, 78; 55, 79; 56, 80; 56, 81; 57, 82; 60, 83; 61, 84; 61, 85; 62, 86; 65, 87; 65, 88; 66, 89; 67, 90; 67, 91; 68, 92; 68, 93; 71, 94; 71, 95; 72, 96; 83, 97; 83, 98; 88, 99; 88, 100; 89, 101; 89, 102; 95, 103; 95, 104; 96, 105; 96, 106; 98, 107; 100, 108; 102, 109; 102, 110; 103, 111; 103, 112; 103, 113; 103, 114; 104, 115; 104, 116; 106, 117; 106, 118; 107, 119; 107, 120; 108, 121; 108, 122; 110, 123; 111, 124; 111, 125; 112, 126; 112, 127; 113, 128; 113, 129; 117, 130; 117, 131; 118, 132; 118, 133; 119, 134; 119, 135; 121, 136; 121, 137; 122, 138; 123, 139; 123, 140; 125, 141; 125, 142; 127, 143; 127, 144; 130, 145; 130, 146; 131, 147; 131, 148; 138, 149; 138, 150; 139, 151; 139, 152; 146, 153; 146, 154; 148, 155; 148, 156 | def simplify_graph(graph):
"""
strips out everything but connectivity
Args:
graph (nx.Graph):
Returns:
nx.Graph: new_graph
CommandLine:
python3 -m utool.util_graph simplify_graph --show
python2 -m utool.util_graph simplify_graph --show
python2 -c "import networkx as nx; print(nx.__version__)"
python3 -c "import networkx as nx; print(nx.__version__)"
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_graph import * # NOQA
>>> import utool as ut
>>> graph = nx.DiGraph([('a', 'b'), ('a', 'c'), ('a', 'e'),
>>> ('a', 'd'), ('b', 'd'), ('c', 'e'),
>>> ('d', 'e'), ('c', 'e'), ('c', 'd')])
>>> new_graph = simplify_graph(graph)
>>> result = ut.repr2(list(new_graph.edges()))
>>> #adj_list = sorted(list(nx.generate_adjlist(new_graph)))
>>> #result = ut.repr2(adj_list)
>>> print(result)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 3), (2, 3), (2, 4), (3, 4)]
['0 1 2 3 4', '1 3 4', '2 4', '3', '4 3']
"""
import utool as ut
nodes = sorted(list(graph.nodes()))
node_lookup = ut.make_index_lookup(nodes)
if graph.is_multigraph():
edges = list(graph.edges(keys=True))
else:
edges = list(graph.edges())
new_nodes = ut.take(node_lookup, nodes)
if graph.is_multigraph():
new_edges = [(node_lookup[e[0]], node_lookup[e[1]], e[2], {}) for e in edges]
else:
new_edges = [(node_lookup[e[0]], node_lookup[e[1]]) for e in edges]
cls = graph.__class__
new_graph = cls()
new_graph.add_nodes_from(new_nodes)
new_graph.add_edges_from(new_edges)
return new_graph |
0, module; 1, function_definition; 2, function_name:get_uniprot_evidence_level; 3, parameters; 4, block; 5, identifier:header; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Returns uniprot protein existence evidence level for a fasta header.
Evidence levels are 1-5, but we return 5 - x since sorting still demands
that higher is better."""; 11, assignment; 12, identifier:item; 13, identifier:header; 14, block; 15, unary_operator; 16, identifier:header; 17, call; 18, expression_statement; 19, try_statement; 20, integer:1; 21, attribute; 22, argument_list; 23, assignment; 24, block; 25, except_clause; 26, identifier:header; 27, identifier:split; 28, identifier:item; 29, call; 30, if_statement; 31, identifier:IndexError; 32, block; 33, attribute; 34, argument_list; 35, comparison_operator:item[0] == 'PE'; 36, block; 37, continue_statement; 38, identifier:item; 39, identifier:split; 40, string; 41, subscript; 42, string; 43, return_statement; 44, string_content:=; 45, identifier:item; 46, integer:0; 47, string_content:PE; 48, binary_operator:5 - int(item[1]); 49, integer:5; 50, call; 51, identifier:int; 52, argument_list; 53, subscript; 54, identifier:item; 55, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 14, 18; 14, 19; 15, 20; 17, 21; 17, 22; 18, 23; 19, 24; 19, 25; 21, 26; 21, 27; 23, 28; 23, 29; 24, 30; 25, 31; 25, 32; 29, 33; 29, 34; 30, 35; 30, 36; 32, 37; 33, 38; 33, 39; 34, 40; 35, 41; 35, 42; 36, 43; 40, 44; 41, 45; 41, 46; 42, 47; 43, 48; 48, 49; 48, 50; 50, 51; 50, 52; 52, 53; 53, 54; 53, 55 | def get_uniprot_evidence_level(header):
"""Returns uniprot protein existence evidence level for a fasta header.
Evidence levels are 1-5, but we return 5 - x since sorting still demands
that higher is better."""
header = header.split()
for item in header:
item = item.split('=')
try:
if item[0] == 'PE':
return 5 - int(item[1])
except IndexError:
continue
return -1 |
0, module; 1, function_definition; 2, function_name:sorted; 3, parameters; 4, block; 5, identifier:self; 6, identifier:by; 7, dictionary_splat_pattern; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, identifier:kwargs; 12, comment:"""Sort array by a column.
Parameters
==========
by: str
Name of the columns to sort by(e.g. 'time').
"""; 13, assignment; 14, call; 15, identifier:sort_idc; 16, call; 17, attribute; 18, argument_list; 19, attribute; 20, argument_list; 21, identifier:self; 22, identifier:__class__; 23, subscript; 24, keyword_argument; 25, keyword_argument; 26, keyword_argument; 27, identifier:np; 28, identifier:argsort; 29, subscript; 30, dictionary_splat; 31, identifier:self; 32, identifier:sort_idc; 33, identifier:h5loc; 34, attribute; 35, identifier:split_h5; 36, attribute; 37, identifier:name; 38, attribute; 39, identifier:self; 40, identifier:by; 41, identifier:kwargs; 42, identifier:self; 43, identifier:h5loc; 44, identifier:self; 45, identifier:split_h5; 46, identifier:self; 47, identifier:name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 10, 14; 13, 15; 13, 16; 14, 17; 14, 18; 16, 19; 16, 20; 17, 21; 17, 22; 18, 23; 18, 24; 18, 25; 18, 26; 19, 27; 19, 28; 20, 29; 20, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 26, 37; 26, 38; 29, 39; 29, 40; 30, 41; 34, 42; 34, 43; 36, 44; 36, 45; 38, 46; 38, 47 | def sorted(self, by, **kwargs):
"""Sort array by a column.
Parameters
==========
by: str
Name of the columns to sort by(e.g. 'time').
"""
sort_idc = np.argsort(self[by], **kwargs)
return self.__class__(
self[sort_idc],
h5loc=self.h5loc,
split_h5=self.split_h5,
name=self.name
) |
0, module; 1, function_definition; 2, function_name:pmt_angles; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, if_statement; 8, return_statement; 9, comment:"""A list of PMT directions sorted by PMT channel, on DU-1, floor-1"""; 10, comparison_operator:self._pmt_angles == []; 11, block; 12, attribute; 13, attribute; 14, list; 15, expression_statement; 16, expression_statement; 17, identifier:self; 18, identifier:_pmt_angles; 19, identifier:self; 20, identifier:_pmt_angles; 21, assignment; 22, assignment; 23, identifier:mask; 24, binary_operator:(self.pmts.du == 1) & (self.pmts.floor == 1); 25, attribute; 26, subscript; 27, parenthesized_expression; 28, parenthesized_expression; 29, identifier:self; 30, identifier:_pmt_angles; 31, attribute; 32, identifier:mask; 33, comparison_operator:self.pmts.du == 1; 34, comparison_operator:self.pmts.floor == 1; 35, attribute; 36, identifier:dir; 37, attribute; 38, integer:1; 39, attribute; 40, integer:1; 41, identifier:self; 42, identifier:pmts; 43, attribute; 44, identifier:du; 45, attribute; 46, identifier:floor; 47, identifier:self; 48, identifier:pmts; 49, identifier:self; 50, identifier:pmts | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 7, 11; 8, 12; 10, 13; 10, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 13, 20; 15, 21; 16, 22; 21, 23; 21, 24; 22, 25; 22, 26; 24, 27; 24, 28; 25, 29; 25, 30; 26, 31; 26, 32; 27, 33; 28, 34; 31, 35; 31, 36; 33, 37; 33, 38; 34, 39; 34, 40; 35, 41; 35, 42; 37, 43; 37, 44; 39, 45; 39, 46; 43, 47; 43, 48; 45, 49; 45, 50 | def pmt_angles(self):
"""A list of PMT directions sorted by PMT channel, on DU-1, floor-1"""
if self._pmt_angles == []:
mask = (self.pmts.du == 1) & (self.pmts.floor == 1)
self._pmt_angles = self.pmts.dir[mask]
return self._pmt_angles |
0, module; 1, function_definition; 2, function_name:_get_point; 3, parameters; 4, block; 5, identifier:self; 6, identifier:profile; 7, identifier:point; 8, expression_statement; 9, expression_statement; 10, try_statement; 11, comment:"""
Finds the given point in the profile, or adds it in sorted z order.
"""; 12, assignment; 13, block; 14, except_clause; 15, identifier:cur_points_z; 16, list_comprehension; 17, expression_statement; 18, return_statement; 19, identifier:ValueError; 20, block; 21, attribute; 22, for_in_clause; 23, assignment; 24, subscript; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, return_statement; 31, attribute; 32, identifier:z; 33, identifier:p; 34, attribute; 35, identifier:cur_idx; 36, call; 37, attribute; 38, identifier:cur_idx; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, call; 44, identifier:new_point; 45, identifier:p; 46, identifier:location; 47, identifier:profile; 48, identifier:elements; 49, attribute; 50, argument_list; 51, identifier:profile; 52, identifier:elements; 53, identifier:new_idx; 54, call; 55, identifier:new_point; 56, call; 57, attribute; 58, call; 59, attribute; 60, attribute; 61, attribute; 62, argument_list; 63, identifier:cur_points_z; 64, identifier:index; 65, attribute; 66, identifier:bisect_left; 67, argument_list; 68, identifier:Point; 69, argument_list; 70, identifier:new_point; 71, identifier:location; 72, identifier:sPoint; 73, argument_list; 74, identifier:new_point; 75, identifier:time; 76, identifier:profile; 77, identifier:time; 78, attribute; 79, identifier:insert; 80, identifier:new_idx; 81, identifier:new_point; 82, identifier:point; 83, identifier:z; 84, identifier:cur_points_z; 85, attribute; 86, identifier:point; 87, identifier:profile; 88, identifier:elements; 89, identifier:point; 90, identifier:z | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 8, 11; 9, 12; 10, 13; 10, 14; 12, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 16, 21; 16, 22; 17, 23; 18, 24; 20, 25; 20, 26; 20, 27; 20, 28; 20, 29; 20, 30; 21, 31; 21, 32; 22, 33; 22, 34; 23, 35; 23, 36; 24, 37; 24, 38; 25, 39; 26, 40; 27, 41; 28, 42; 29, 43; 30, 44; 31, 45; 31, 46; 34, 47; 34, 48; 36, 49; 36, 50; 37, 51; 37, 52; 39, 53; 39, 54; 40, 55; 40, 56; 41, 57; 41, 58; 42, 59; 42, 60; 43, 61; 43, 62; 49, 63; 49, 64; 50, 65; 54, 66; 54, 67; 56, 68; 56, 69; 57, 70; 57, 71; 58, 72; 58, 73; 59, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 62, 80; 62, 81; 65, 82; 65, 83; 67, 84; 67, 85; 73, 86; 78, 87; 78, 88; 85, 89; 85, 90 | def _get_point(self, profile, point):
"""
Finds the given point in the profile, or adds it in sorted z order.
"""
cur_points_z = [p.location.z for p in profile.elements]
try:
cur_idx = cur_points_z.index(point.z)
return profile.elements[cur_idx]
except ValueError:
new_idx = bisect_left(cur_points_z, point.z)
new_point = Point()
new_point.location = sPoint(point)
new_point.time = profile.time
profile.elements.insert(new_idx, new_point)
return new_point |
0, module; 1, function_definition; 2, function_name:metadata_sorter; 3, parameters; 4, block; 5, identifier:x; 6, identifier:y; 7, expression_statement; 8, if_statement; 9, if_statement; 10, comment:""" Sort metadata keys by priority.
"""; 11, comparison_operator:x == y; 12, block; 13, boolean_operator; 14, block; 15, elif_clause; 16, elif_clause; 17, else_clause; 18, identifier:x; 19, identifier:y; 20, return_statement; 21, comparison_operator:x in METADATA_SORTER_FIRST; 22, comparison_operator:y in METADATA_SORTER_FIRST; 23, return_statement; 24, comparison_operator:x in METADATA_SORTER_FIRST; 25, block; 26, comparison_operator:y in METADATA_SORTER_FIRST; 27, block; 28, block; 29, integer:0; 30, identifier:x; 31, identifier:METADATA_SORTER_FIRST; 32, identifier:y; 33, identifier:METADATA_SORTER_FIRST; 34, conditional_expression:-1 if METADATA_SORTER_FIRST.index(x) < METADATA_SORTER_FIRST.index(y) else 1; 35, identifier:x; 36, identifier:METADATA_SORTER_FIRST; 37, return_statement; 38, identifier:y; 39, identifier:METADATA_SORTER_FIRST; 40, return_statement; 41, if_statement; 42, unary_operator; 43, comparison_operator:METADATA_SORTER_FIRST.index(x) < METADATA_SORTER_FIRST.index(y); 44, integer:1; 45, unary_operator; 46, integer:1; 47, boolean_operator; 48, block; 49, elif_clause; 50, elif_clause; 51, else_clause; 52, integer:1; 53, call; 54, call; 55, integer:1; 56, call; 57, call; 58, return_statement; 59, call; 60, block; 61, call; 62, block; 63, block; 64, attribute; 65, argument_list; 66, attribute; 67, argument_list; 68, attribute; 69, argument_list; 70, attribute; 71, argument_list; 72, call; 73, attribute; 74, argument_list; 75, return_statement; 76, attribute; 77, argument_list; 78, return_statement; 79, return_statement; 80, identifier:METADATA_SORTER_FIRST; 81, identifier:index; 82, identifier:x; 83, identifier:METADATA_SORTER_FIRST; 84, identifier:index; 85, identifier:y; 86, identifier:x; 87, identifier:startswith; 88, string; 89, identifier:y; 90, identifier:startswith; 91, string; 92, identifier:cmp; 93, argument_list; 94, identifier:x; 95, identifier:startswith; 96, string; 97, integer:1; 98, identifier:y; 99, identifier:startswith; 100, string; 101, unary_operator; 102, call; 103, string_content:_; 104, string_content:_; 105, subscript; 106, subscript; 107, string_content:_; 108, string_content:_; 109, integer:1; 110, identifier:cmp; 111, argument_list; 112, identifier:x; 113, slice; 114, identifier:y; 115, slice; 116, identifier:x; 117, identifier:y; 118, integer:1; 119, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 8, 12; 9, 13; 9, 14; 9, 15; 9, 16; 9, 17; 11, 18; 11, 19; 12, 20; 13, 21; 13, 22; 14, 23; 15, 24; 15, 25; 16, 26; 16, 27; 17, 28; 20, 29; 21, 30; 21, 31; 22, 32; 22, 33; 23, 34; 24, 35; 24, 36; 25, 37; 26, 38; 26, 39; 27, 40; 28, 41; 34, 42; 34, 43; 34, 44; 37, 45; 40, 46; 41, 47; 41, 48; 41, 49; 41, 50; 41, 51; 42, 52; 43, 53; 43, 54; 45, 55; 47, 56; 47, 57; 48, 58; 49, 59; 49, 60; 50, 61; 50, 62; 51, 63; 53, 64; 53, 65; 54, 66; 54, 67; 56, 68; 56, 69; 57, 70; 57, 71; 58, 72; 59, 73; 59, 74; 60, 75; 61, 76; 61, 77; 62, 78; 63, 79; 64, 80; 64, 81; 65, 82; 66, 83; 66, 84; 67, 85; 68, 86; 68, 87; 69, 88; 70, 89; 70, 90; 71, 91; 72, 92; 72, 93; 73, 94; 73, 95; 74, 96; 75, 97; 76, 98; 76, 99; 77, 100; 78, 101; 79, 102; 88, 103; 91, 104; 93, 105; 93, 106; 96, 107; 100, 108; 101, 109; 102, 110; 102, 111; 105, 112; 105, 113; 106, 114; 106, 115; 111, 116; 111, 117; 113, 118; 115, 119 | def metadata_sorter(x, y):
""" Sort metadata keys by priority.
"""
if x == y:
return 0
if x in METADATA_SORTER_FIRST and y in METADATA_SORTER_FIRST:
return -1 if METADATA_SORTER_FIRST.index(x) < METADATA_SORTER_FIRST.index(y) else 1
elif x in METADATA_SORTER_FIRST:
return -1
elif y in METADATA_SORTER_FIRST:
return 1
else:
if x.startswith('_') and y.startswith('_'):
return cmp(x[1:], y[1:])
elif x.startswith('_'):
return 1
elif y.startswith('_'):
return -1
else:
return cmp(x, y) |
0, module; 1, function_definition; 2, function_name:setRepayments; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, function_definition; 10, try_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:args; 15, identifier:kwargs; 16, comment:"""Adds the repayments for this loan to a 'repayments' field.
Repayments are MambuRepayment objects.
Repayments get sorted by due date.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""; 17, function_name:duedate; 18, parameters; 19, block; 20, block; 21, except_clause; 22, assignment; 23, assignment; 24, integer:1; 25, identifier:repayment; 26, expression_statement; 27, try_statement; 28, expression_statement; 29, as_pattern; 30, block; 31, attribute; 32, call; 33, subscript; 34, identifier:reps; 35, comment:"""Util function used for sorting repayments according to due Date"""; 36, block; 37, except_clause; 38, assignment; 39, identifier:AttributeError; 40, as_pattern_target; 41, import_from_statement; 42, expression_statement; 43, expression_statement; 44, identifier:reps; 45, identifier:attrs; 46, identifier:sorted; 47, argument_list; 48, identifier:self; 49, string; 50, return_statement; 51, as_pattern; 52, block; 53, identifier:reps; 54, call; 55, identifier:ae; 56, relative_import; 57, dotted_name; 58, assignment; 59, assignment; 60, attribute; 61, keyword_argument; 62, string_content:repayments; 63, subscript; 64, identifier:KeyError; 65, as_pattern_target; 66, return_statement; 67, attribute; 68, argument_list; 69, import_prefix; 70, dotted_name; 71, identifier:MambuRepayments; 72, attribute; 73, identifier:MambuRepayments; 74, identifier:reps; 75, call; 76, identifier:reps; 77, identifier:attrs; 78, identifier:key; 79, identifier:duedate; 80, identifier:repayment; 81, string; 82, identifier:kerr; 83, call; 84, identifier:self; 85, identifier:mamburepaymentsclass; 86, keyword_argument; 87, list_splat; 88, dictionary_splat; 89, identifier:mamburepayment; 90, identifier:self; 91, identifier:mamburepaymentsclass; 92, attribute; 93, argument_list; 94, string_content:dueDate; 95, attribute; 96, argument_list; 97, identifier:entid; 98, subscript; 99, identifier:args; 100, identifier:kwargs; 101, identifier:self; 102, identifier:mamburepaymentsclass; 103, keyword_argument; 104, list_splat; 105, dictionary_splat; 106, identifier:datetime; 107, identifier:now; 108, identifier:self; 109, string; 110, identifier:entid; 111, subscript; 112, identifier:args; 113, identifier:kwargs; 114, string_content:id; 115, identifier:self; 116, string; 117, string_content:id | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 9, 18; 9, 19; 10, 20; 10, 21; 11, 22; 12, 23; 13, 24; 18, 25; 19, 26; 19, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 23, 33; 23, 34; 26, 35; 27, 36; 27, 37; 28, 38; 29, 39; 29, 40; 30, 41; 30, 42; 30, 43; 31, 44; 31, 45; 32, 46; 32, 47; 33, 48; 33, 49; 36, 50; 37, 51; 37, 52; 38, 53; 38, 54; 40, 55; 41, 56; 41, 57; 42, 58; 43, 59; 47, 60; 47, 61; 49, 62; 50, 63; 51, 64; 51, 65; 52, 66; 54, 67; 54, 68; 56, 69; 56, 70; 57, 71; 58, 72; 58, 73; 59, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 63, 80; 63, 81; 65, 82; 66, 83; 67, 84; 67, 85; 68, 86; 68, 87; 68, 88; 70, 89; 72, 90; 72, 91; 75, 92; 75, 93; 81, 94; 83, 95; 83, 96; 86, 97; 86, 98; 87, 99; 88, 100; 92, 101; 92, 102; 93, 103; 93, 104; 93, 105; 95, 106; 95, 107; 98, 108; 98, 109; 103, 110; 103, 111; 104, 112; 105, 113; 109, 114; 111, 115; 111, 116; 116, 117 | def setRepayments(self, *args, **kwargs):
"""Adds the repayments for this loan to a 'repayments' field.
Repayments are MambuRepayment objects.
Repayments get sorted by due date.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def duedate(repayment):
"""Util function used for sorting repayments according to due Date"""
try:
return repayment['dueDate']
except KeyError as kerr:
return datetime.now()
try:
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mamburepayment import MambuRepayments
self.mamburepaymentsclass = MambuRepayments
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
reps.attrs = sorted(reps.attrs, key=duedate)
self['repayments'] = reps
return 1 |
0, module; 1, function_definition; 2, function_name:setTransactions; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, function_definition; 10, try_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:args; 15, identifier:kwargs; 16, comment:"""Adds the transactions for this loan to a 'transactions' field.
Transactions are MambuTransaction objects.
Transactions get sorted by transaction id.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""; 17, function_name:transactionid; 18, parameters; 19, block; 20, block; 21, except_clause; 22, assignment; 23, assignment; 24, integer:1; 25, identifier:transaction; 26, expression_statement; 27, try_statement; 28, expression_statement; 29, as_pattern; 30, block; 31, attribute; 32, call; 33, subscript; 34, identifier:trans; 35, comment:"""Util function used for sorting transactions according to id"""; 36, block; 37, except_clause; 38, assignment; 39, identifier:AttributeError; 40, as_pattern_target; 41, import_from_statement; 42, expression_statement; 43, expression_statement; 44, identifier:trans; 45, identifier:attrs; 46, identifier:sorted; 47, argument_list; 48, identifier:self; 49, string; 50, return_statement; 51, as_pattern; 52, block; 53, identifier:trans; 54, call; 55, identifier:ae; 56, relative_import; 57, dotted_name; 58, assignment; 59, assignment; 60, attribute; 61, keyword_argument; 62, string_content:transactions; 63, subscript; 64, identifier:KeyError; 65, as_pattern_target; 66, return_statement; 67, attribute; 68, argument_list; 69, import_prefix; 70, dotted_name; 71, identifier:MambuTransactions; 72, attribute; 73, identifier:MambuTransactions; 74, identifier:trans; 75, call; 76, identifier:trans; 77, identifier:attrs; 78, identifier:key; 79, identifier:transactionid; 80, identifier:transaction; 81, string; 82, identifier:kerr; 83, None; 84, identifier:self; 85, identifier:mambutransactionsclass; 86, keyword_argument; 87, list_splat; 88, dictionary_splat; 89, identifier:mambutransaction; 90, identifier:self; 91, identifier:mambutransactionsclass; 92, attribute; 93, argument_list; 94, string_content:transactionId; 95, identifier:entid; 96, subscript; 97, identifier:args; 98, identifier:kwargs; 99, identifier:self; 100, identifier:mambutransactionsclass; 101, keyword_argument; 102, list_splat; 103, dictionary_splat; 104, identifier:self; 105, string; 106, identifier:entid; 107, subscript; 108, identifier:args; 109, identifier:kwargs; 110, string_content:id; 111, identifier:self; 112, string; 113, string_content:id | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 9, 18; 9, 19; 10, 20; 10, 21; 11, 22; 12, 23; 13, 24; 18, 25; 19, 26; 19, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 23, 33; 23, 34; 26, 35; 27, 36; 27, 37; 28, 38; 29, 39; 29, 40; 30, 41; 30, 42; 30, 43; 31, 44; 31, 45; 32, 46; 32, 47; 33, 48; 33, 49; 36, 50; 37, 51; 37, 52; 38, 53; 38, 54; 40, 55; 41, 56; 41, 57; 42, 58; 43, 59; 47, 60; 47, 61; 49, 62; 50, 63; 51, 64; 51, 65; 52, 66; 54, 67; 54, 68; 56, 69; 56, 70; 57, 71; 58, 72; 58, 73; 59, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 63, 80; 63, 81; 65, 82; 66, 83; 67, 84; 67, 85; 68, 86; 68, 87; 68, 88; 70, 89; 72, 90; 72, 91; 75, 92; 75, 93; 81, 94; 86, 95; 86, 96; 87, 97; 88, 98; 92, 99; 92, 100; 93, 101; 93, 102; 93, 103; 96, 104; 96, 105; 101, 106; 101, 107; 102, 108; 103, 109; 105, 110; 107, 111; 107, 112; 112, 113 | def setTransactions(self, *args, **kwargs):
"""Adds the transactions for this loan to a 'transactions' field.
Transactions are MambuTransaction objects.
Transactions get sorted by transaction id.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def transactionid(transaction):
"""Util function used for sorting transactions according to id"""
try:
return transaction['transactionId']
except KeyError as kerr:
return None
try:
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mambutransaction import MambuTransactions
self.mambutransactionsclass = MambuTransactions
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
trans.attrs = sorted(trans.attrs, key=transactionid)
self['transactions'] = trans
return 1 |
0, module; 1, function_definition; 2, function_name:setActivities; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, function_definition; 10, try_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:args; 15, identifier:kwargs; 16, comment:"""Adds the activities for this group to a 'activities' field.
Activities are MambuActivity objects.
Activities get sorted by activity timestamp.
Returns the number of requests done to Mambu.
"""; 17, function_name:activityDate; 18, parameters; 19, block; 20, block; 21, except_clause; 22, assignment; 23, assignment; 24, integer:1; 25, identifier:activity; 26, expression_statement; 27, try_statement; 28, expression_statement; 29, as_pattern; 30, block; 31, attribute; 32, call; 33, subscript; 34, identifier:activities; 35, comment:"""Util function used for sorting activities according to timestamp"""; 36, block; 37, except_clause; 38, assignment; 39, identifier:AttributeError; 40, as_pattern_target; 41, import_from_statement; 42, expression_statement; 43, expression_statement; 44, identifier:activities; 45, identifier:attrs; 46, identifier:sorted; 47, argument_list; 48, identifier:self; 49, string; 50, return_statement; 51, as_pattern; 52, block; 53, identifier:activities; 54, call; 55, identifier:ae; 56, relative_import; 57, dotted_name; 58, assignment; 59, assignment; 60, attribute; 61, keyword_argument; 62, string_content:activities; 63, subscript; 64, identifier:KeyError; 65, as_pattern_target; 66, return_statement; 67, attribute; 68, argument_list; 69, import_prefix; 70, dotted_name; 71, identifier:MambuActivities; 72, attribute; 73, identifier:MambuActivities; 74, identifier:activities; 75, call; 76, identifier:activities; 77, identifier:attrs; 78, identifier:key; 79, identifier:activityDate; 80, subscript; 81, string; 82, identifier:kerr; 83, None; 84, identifier:self; 85, identifier:mambuactivitiesclass; 86, keyword_argument; 87, list_splat; 88, dictionary_splat; 89, identifier:mambuactivity; 90, identifier:self; 91, identifier:mambuactivitiesclass; 92, attribute; 93, argument_list; 94, identifier:activity; 95, string; 96, string_content:timestamp; 97, identifier:groupId; 98, subscript; 99, identifier:args; 100, identifier:kwargs; 101, identifier:self; 102, identifier:mambuactivitiesclass; 103, keyword_argument; 104, list_splat; 105, dictionary_splat; 106, string_content:activity; 107, identifier:self; 108, string; 109, identifier:groupId; 110, subscript; 111, identifier:args; 112, identifier:kwargs; 113, string_content:encodedKey; 114, identifier:self; 115, string; 116, string_content:encodedKey | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 9, 18; 9, 19; 10, 20; 10, 21; 11, 22; 12, 23; 13, 24; 18, 25; 19, 26; 19, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 23, 33; 23, 34; 26, 35; 27, 36; 27, 37; 28, 38; 29, 39; 29, 40; 30, 41; 30, 42; 30, 43; 31, 44; 31, 45; 32, 46; 32, 47; 33, 48; 33, 49; 36, 50; 37, 51; 37, 52; 38, 53; 38, 54; 40, 55; 41, 56; 41, 57; 42, 58; 43, 59; 47, 60; 47, 61; 49, 62; 50, 63; 51, 64; 51, 65; 52, 66; 54, 67; 54, 68; 56, 69; 56, 70; 57, 71; 58, 72; 58, 73; 59, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 63, 80; 63, 81; 65, 82; 66, 83; 67, 84; 67, 85; 68, 86; 68, 87; 68, 88; 70, 89; 72, 90; 72, 91; 75, 92; 75, 93; 80, 94; 80, 95; 81, 96; 86, 97; 86, 98; 87, 99; 88, 100; 92, 101; 92, 102; 93, 103; 93, 104; 93, 105; 95, 106; 98, 107; 98, 108; 103, 109; 103, 110; 104, 111; 105, 112; 108, 113; 110, 114; 110, 115; 115, 116 | def setActivities(self, *args, **kwargs):
"""Adds the activities for this group to a 'activities' field.
Activities are MambuActivity objects.
Activities get sorted by activity timestamp.
Returns the number of requests done to Mambu.
"""
def activityDate(activity):
"""Util function used for sorting activities according to timestamp"""
try:
return activity['activity']['timestamp']
except KeyError as kerr:
return None
try:
activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs)
except AttributeError as ae:
from .mambuactivity import MambuActivities
self.mambuactivitiesclass = MambuActivities
activities = self.mambuactivitiesclass(groupId=self['encodedKey'], *args, **kwargs)
activities.attrs = sorted(activities.attrs, key=activityDate)
self['activities'] = activities
return 1 |
0, module; 1, function_definition; 2, function_name:compactor; 3, parameters; 4, block; 5, identifier:conf; 6, expression_statement; 7, comment:# Get the database handle; 8, expression_statement; 9, comment:# Get the limits container; 10, expression_statement; 11, comment:# Get the compactor configuration; 12, expression_statement; 13, comment:# Make sure compaction is enabled; 14, if_statement; 15, comment:# Select the bucket key getter; 16, expression_statement; 17, expression_statement; 18, comment:# Now enter our loop; 19, while_statement; 20, comment:"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note that a
ControlDaemon is also started, so appropriate
configuration for that must also be present, as must
appropriate Redis connection information.
"""; 21, assignment; 22, assignment; 23, assignment; 24, comparison_operator:get_int(config, 'max_updates', 0) <= 0; 25, comment:# We'll just warn about it, since they could be running; 26, comment:# the compactor with a different configuration file; 27, block; 28, assignment; 29, call; 30, True; 31, comment:# Get a bucket key to compact; 32, block; 33, identifier:db; 34, call; 35, identifier:limit_map; 36, call; 37, identifier:config; 38, subscript; 39, call; 40, integer:0; 41, expression_statement; 42, identifier:key_getter; 43, call; 44, attribute; 45, argument_list; 46, try_statement; 47, comment:# Ignore version 1 keys--they can't be compacted; 48, if_statement; 49, comment:# Get the corresponding limit class; 50, try_statement; 51, expression_statement; 52, comment:# OK, we now have the limit (which we really only need for; 53, comment:# the bucket class); let's compact the bucket; 54, try_statement; 55, attribute; 56, argument_list; 57, identifier:LimitContainer; 58, argument_list; 59, identifier:conf; 60, string; 61, identifier:get_int; 62, argument_list; 63, call; 64, attribute; 65, argument_list; 66, identifier:LOG; 67, identifier:info; 68, string:"Compactor initialized"; 69, block; 70, except_clause; 71, comparison_operator:buck_key.version < 2; 72, block; 73, block; 74, except_clause; 75, call; 76, block; 77, except_clause; 78, else_clause; 79, identifier:conf; 80, identifier:get_database; 81, string; 82, identifier:conf; 83, identifier:db; 84, string_content:compactor; 85, identifier:config; 86, string; 87, integer:0; 88, attribute; 89, argument_list; 90, identifier:GetBucketKey; 91, identifier:factory; 92, identifier:config; 93, identifier:db; 94, expression_statement; 95, as_pattern; 96, comment:# Warn about invalid bucket keys; 97, block; 98, attribute; 99, integer:2; 100, continue_statement; 101, expression_statement; 102, identifier:KeyError; 103, comment:# Warn about missing limits; 104, block; 105, attribute; 106, argument_list; 107, expression_statement; 108, identifier:Exception; 109, block; 110, block; 111, string_content:compactor; 112, string_content:max_updates; 113, identifier:LOG; 114, identifier:warning; 115, concatenated_string; 116, assignment; 117, identifier:ValueError; 118, as_pattern_target; 119, expression_statement; 120, continue_statement; 121, identifier:buck_key; 122, identifier:version; 123, assignment; 124, expression_statement; 125, continue_statement; 126, identifier:LOG; 127, identifier:debug; 128, binary_operator:"Compacting bucket %s" % buck_key; 129, call; 130, expression_statement; 131, expression_statement; 132, string:"Compaction is not enabled. Enable it by "; 133, string:"setting a positive integer value for "; 134, string:"'compactor.max_updates' in the configuration."; 135, identifier:buck_key; 136, call; 137, identifier:exc; 138, call; 139, identifier:limit; 140, subscript; 141, call; 142, string:"Compacting bucket %s"; 143, identifier:buck_key; 144, identifier:compact_bucket; 145, argument_list; 146, call; 147, call; 148, attribute; 149, argument_list; 150, attribute; 151, argument_list; 152, identifier:limit_map; 153, attribute; 154, attribute; 155, argument_list; 156, identifier:db; 157, identifier:buck_key; 158, identifier:limit; 159, attribute; 160, argument_list; 161, attribute; 162, argument_list; 163, attribute; 164, identifier:decode; 165, call; 166, identifier:LOG; 167, identifier:warning; 168, binary_operator:"Error interpreting bucket key: %s" % exc; 169, identifier:buck_key; 170, identifier:uuid; 171, identifier:LOG; 172, identifier:warning; 173, binary_operator:"Unable to compact bucket for limit %s" %
buck_key.uuid; 174, identifier:LOG; 175, identifier:exception; 176, binary_operator:"Failed to compact bucket %s" % buck_key; 177, identifier:LOG; 178, identifier:debug; 179, binary_operator:"Finished compacting bucket %s" % buck_key; 180, identifier:limits; 181, identifier:BucketKey; 182, identifier:key_getter; 183, argument_list; 184, string:"Error interpreting bucket key: %s"; 185, identifier:exc; 186, string:"Unable to compact bucket for limit %s"; 187, attribute; 188, string:"Failed to compact bucket %s"; 189, identifier:buck_key; 190, string:"Finished compacting bucket %s"; 191, identifier:buck_key; 192, identifier:buck_key; 193, identifier:uuid | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 6, 20; 8, 21; 10, 22; 12, 23; 14, 24; 14, 25; 14, 26; 14, 27; 16, 28; 17, 29; 19, 30; 19, 31; 19, 32; 21, 33; 21, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 24, 40; 27, 41; 28, 42; 28, 43; 29, 44; 29, 45; 32, 46; 32, 47; 32, 48; 32, 49; 32, 50; 32, 51; 32, 52; 32, 53; 32, 54; 34, 55; 34, 56; 36, 57; 36, 58; 38, 59; 38, 60; 39, 61; 39, 62; 41, 63; 43, 64; 43, 65; 44, 66; 44, 67; 45, 68; 46, 69; 46, 70; 48, 71; 48, 72; 50, 73; 50, 74; 51, 75; 54, 76; 54, 77; 54, 78; 55, 79; 55, 80; 56, 81; 58, 82; 58, 83; 60, 84; 62, 85; 62, 86; 62, 87; 63, 88; 63, 89; 64, 90; 64, 91; 65, 92; 65, 93; 69, 94; 70, 95; 70, 96; 70, 97; 71, 98; 71, 99; 72, 100; 73, 101; 74, 102; 74, 103; 74, 104; 75, 105; 75, 106; 76, 107; 77, 108; 77, 109; 78, 110; 81, 111; 86, 112; 88, 113; 88, 114; 89, 115; 94, 116; 95, 117; 95, 118; 97, 119; 97, 120; 98, 121; 98, 122; 101, 123; 104, 124; 104, 125; 105, 126; 105, 127; 106, 128; 107, 129; 109, 130; 110, 131; 115, 132; 115, 133; 115, 134; 116, 135; 116, 136; 118, 137; 119, 138; 123, 139; 123, 140; 124, 141; 128, 142; 128, 143; 129, 144; 129, 145; 130, 146; 131, 147; 136, 148; 136, 149; 138, 150; 138, 151; 140, 152; 140, 153; 141, 154; 141, 155; 145, 156; 145, 157; 145, 158; 146, 159; 146, 160; 147, 161; 147, 162; 148, 163; 148, 164; 149, 165; 150, 166; 150, 167; 151, 168; 153, 169; 153, 170; 154, 171; 154, 172; 155, 173; 159, 174; 159, 175; 160, 176; 161, 177; 161, 178; 162, 179; 163, 180; 163, 181; 165, 182; 165, 183; 168, 184; 168, 185; 173, 186; 173, 187; 176, 188; 176, 189; 179, 190; 179, 191; 187, 192; 187, 193 | def compactor(conf):
"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note that a
ControlDaemon is also started, so appropriate
configuration for that must also be present, as must
appropriate Redis connection information.
"""
# Get the database handle
db = conf.get_database('compactor')
# Get the limits container
limit_map = LimitContainer(conf, db)
# Get the compactor configuration
config = conf['compactor']
# Make sure compaction is enabled
if get_int(config, 'max_updates', 0) <= 0:
# We'll just warn about it, since they could be running
# the compactor with a different configuration file
LOG.warning("Compaction is not enabled. Enable it by "
"setting a positive integer value for "
"'compactor.max_updates' in the configuration.")
# Select the bucket key getter
key_getter = GetBucketKey.factory(config, db)
LOG.info("Compactor initialized")
# Now enter our loop
while True:
# Get a bucket key to compact
try:
buck_key = limits.BucketKey.decode(key_getter())
except ValueError as exc:
# Warn about invalid bucket keys
LOG.warning("Error interpreting bucket key: %s" % exc)
continue
# Ignore version 1 keys--they can't be compacted
if buck_key.version < 2:
continue
# Get the corresponding limit class
try:
limit = limit_map[buck_key.uuid]
except KeyError:
# Warn about missing limits
LOG.warning("Unable to compact bucket for limit %s" %
buck_key.uuid)
continue
LOG.debug("Compacting bucket %s" % buck_key)
# OK, we now have the limit (which we really only need for
# the bucket class); let's compact the bucket
try:
compact_bucket(db, buck_key, limit)
except Exception:
LOG.exception("Failed to compact bucket %s" % buck_key)
else:
LOG.debug("Finished compacting bucket %s" % buck_key) |
0, module; 1, function_definition; 2, function_name:get; 3, parameters; 4, block; 5, identifier:self; 6, identifier:now; 7, expression_statement; 8, with_statement; 9, comment:"""
Get a bucket key to compact. If none are available, returns
None. This uses a configured lock to ensure that the bucket
key is popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficiently to be
quiescent.
:returns: A bucket key ready for compaction, or None if no
bucket keys are available or none have aged
sufficiently.
"""; 10, with_clause; 11, block; 12, with_item; 13, expression_statement; 14, comment:# Did we get any items?; 15, if_statement; 16, comment:# Drop the item we got; 17, expression_statement; 18, expression_statement; 19, return_statement; 20, attribute; 21, assignment; 22, not_operator; 23, block; 24, assignment; 25, call; 26, identifier:item; 27, identifier:self; 28, identifier:lock; 29, identifier:items; 30, call; 31, identifier:items; 32, return_statement; 33, identifier:item; 34, subscript; 35, attribute; 36, argument_list; 37, attribute; 38, argument_list; 39, None; 40, identifier:items; 41, integer:0; 42, attribute; 43, identifier:zrem; 44, identifier:item; 45, attribute; 46, identifier:zrangebyscore; 47, attribute; 48, integer:0; 49, binary_operator:now - self.min_age; 50, keyword_argument; 51, keyword_argument; 52, identifier:self; 53, identifier:db; 54, identifier:self; 55, identifier:db; 56, identifier:self; 57, identifier:key; 58, identifier:now; 59, attribute; 60, identifier:start; 61, integer:0; 62, identifier:num; 63, integer:1; 64, identifier:self; 65, identifier:min_age | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 8, 11; 10, 12; 11, 13; 11, 14; 11, 15; 11, 16; 11, 17; 11, 18; 11, 19; 12, 20; 13, 21; 15, 22; 15, 23; 17, 24; 18, 25; 19, 26; 20, 27; 20, 28; 21, 29; 21, 30; 22, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 30, 37; 30, 38; 32, 39; 34, 40; 34, 41; 35, 42; 35, 43; 36, 44; 37, 45; 37, 46; 38, 47; 38, 48; 38, 49; 38, 50; 38, 51; 42, 52; 42, 53; 45, 54; 45, 55; 47, 56; 47, 57; 49, 58; 49, 59; 50, 60; 50, 61; 51, 62; 51, 63; 59, 64; 59, 65 | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a configured lock to ensure that the bucket
key is popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficiently to be
quiescent.
:returns: A bucket key ready for compaction, or None if no
bucket keys are available or none have aged
sufficiently.
"""
with self.lock:
items = self.db.zrangebyscore(self.key, 0, now - self.min_age,
start=0, num=1)
# Did we get any items?
if not items:
return None
# Drop the item we got
item = items[0]
self.db.zrem(item)
return item |
0, module; 1, function_definition; 2, function_name:get; 3, parameters; 4, block; 5, identifier:self; 6, identifier:now; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficiently to be
quiescent.
:returns: A bucket key ready for compaction, or None if no
bucket keys are available or none have aged
sufficiently.
"""; 11, assignment; 12, conditional_expression:items[0] if items else None; 13, identifier:items; 14, call; 15, subscript; 16, identifier:items; 17, None; 18, attribute; 19, argument_list; 20, identifier:items; 21, integer:0; 22, identifier:self; 23, identifier:script; 24, keyword_argument; 25, keyword_argument; 26, identifier:keys; 27, list; 28, identifier:args; 29, list; 30, attribute; 31, binary_operator:now - self.min_age; 32, identifier:self; 33, identifier:key; 34, identifier:now; 35, attribute; 36, identifier:self; 37, identifier:min_age | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 11, 13; 11, 14; 12, 15; 12, 16; 12, 17; 14, 18; 14, 19; 15, 20; 15, 21; 18, 22; 18, 23; 19, 24; 19, 25; 24, 26; 24, 27; 25, 28; 25, 29; 27, 30; 29, 31; 30, 32; 30, 33; 31, 34; 31, 35; 35, 36; 35, 37 | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficiently to be
quiescent.
:returns: A bucket key ready for compaction, or None if no
bucket keys are available or none have aged
sufficiently.
"""
items = self.script(keys=[self.key], args=[now - self.min_age])
return items[0] if items else None |
0, module; 1, function_definition; 2, function_name:create; 3, parameters; 4, block; 5, identifier:self; 6, identifier:query; 7, keyword_separator; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, return_statement; 13, identifier:dc; 14, None; 15, comment:"""Creates a new prepared query
Parameters:
Query (Object): Query definition
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
Object: New query ID
The create operation expects a body that defines the prepared query,
like this example::
{
"Name": "my-query",
"Session": "adf4238a-882b-9ddc-4a9d-5b6758e4159e",
"Token": "",
"Near": "node1",
"Service": {
"Service": "redis",
"Failover": {
"NearestN": 3,
"Datacenters": ["dc1", "dc2"]
},
"OnlyPassing": False,
"Tags": ["master", "!experimental"]
},
"DNS": {
"TTL": timedelta(seconds=10)
}
}
Only the **Service** field inside the **Service** structure is
mandatory, all other fields will take their default values if they
are not included.
**Name** is an optional friendly name that can be used to execute a
query instead of using its ID.
**Session** provides a way to automatically remove a prepared query
when the given session is invalidated. This is optional, and if not
given the prepared query must be manually removed when no longer
needed.
**Token**, if specified, is a captured ACL Token that is reused as the
ACL Token every time the query is executed. This allows queries to be
executed by clients with lesser or even no ACL Token, so this should
be used with care. The token itself can only be seen by clients with a
management token. If the **Token** field is left blank or omitted, the
client's ACL Token will be used to determine if they have access to the
service being queried. If the client does not supply an ACL Token, the
anonymous token will be used.
**Near** allows specifying a particular node to sort near based on
distance sorting using Network Coordinates. The nearest instance to
the specified node will be returned first, and subsequent nodes in the
response will be sorted in ascending order of estimated round-trip
times. If the node given does not exist, the nodes in the response
will be shuffled. Using the magic **_agent** value is supported, and
will automatically return results nearest the agent servicing the
request. If unspecified, the response will be shuffled by default.
The set of fields inside the **Service** structure define the
query's behavior.
**Service** is the name of the service to query. This is required.
**Failover** contains two fields, both of which are optional, and
determine what happens if no healthy nodes are available in the local
datacenter when the query is executed. It allows the use of nodes in
other datacenters with very little configuration.
If **NearestN** is set to a value greater than zero, then the query
will be forwarded to up to **NearestN** other datacenters based on
their estimated network round trip time using Network Coordinates from
the WAN gossip pool. The median round trip time from the server
handling the query to the servers in the remote datacenter is used to
determine the priority. The default value is zero. All Consul servers
must be running version 0.6.0 or above in order for this feature to
work correctly. If any servers are not running the required version of
Consul they will be considered last since they won't have any
available network coordinate information.
**Datacenters** contains a fixed list of remote datacenters to forward
the query to if there are no healthy nodes in the local datacenter.
Datacenters are queried in the order given in the list. If this option
is combined with **NearestN**, then the **NearestN** queries will be
performed first, followed by the list given by **Datacenters**. A
given datacenter will only be queried one time during a failover, even
if it is selected by both **NearestN** and is listed in
**Datacenters**. The default value is an empty list.
**OnlyPassing** controls the behavior of the query's health check
filtering. If this is set to false, the results will include nodes
with checks in the passing as well as the warning states. If this is
set to true, only nodes with checks in the passing state will be
returned. The default value is False.
**Tags** provides a list of service tags to filter the query results.
For a service to pass the tag filter it must have all of the required
tags, and none of the excluded tags (prefixed with ``!``).
The default value is an empty list, which does no tag filtering.
**TTL** in the **DNS** structure is a duration string that can use "s"
as a suffix for seconds. It controls how the TTL is set when query
results are served over DNS. If this isn't specified, then the Consul
agent configuration for the given service will be used
(see DNS Caching). If this is specified, it will take precedence over
any Consul agent-specific configuration. If no TTL is specified here
or at the Consul agent level, then the TTL will default to 0.
It returns the ID of the created query::
{
"ID": "8f246b77-f3e1-ff88-5b48-8ec93abf3e05"
}
"""; 16, comparison_operator:"Token" in query; 17, comment:# in case of a full token object...; 18, block; 19, assignment; 20, attribute; 21, string:"Token"; 22, identifier:query; 23, expression_statement; 24, identifier:response; 25, await; 26, identifier:response; 27, identifier:body; 28, assignment; 29, call; 30, subscript; 31, call; 32, attribute; 33, argument_list; 34, identifier:query; 35, string:"Token"; 36, identifier:extract_attr; 37, argument_list; 38, attribute; 39, identifier:post; 40, string:"/v1/query"; 41, keyword_argument; 42, keyword_argument; 43, subscript; 44, keyword_argument; 45, identifier:self; 46, identifier:_api; 47, identifier:params; 48, dictionary; 49, identifier:data; 50, identifier:query; 51, identifier:query; 52, string:"Token"; 53, identifier:keys; 54, list; 55, pair; 56, string:"ID"; 57, string:"dc"; 58, identifier:dc | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 8, 13; 8, 14; 9, 15; 10, 16; 10, 17; 10, 18; 11, 19; 12, 20; 16, 21; 16, 22; 18, 23; 19, 24; 19, 25; 20, 26; 20, 27; 23, 28; 25, 29; 28, 30; 28, 31; 29, 32; 29, 33; 30, 34; 30, 35; 31, 36; 31, 37; 32, 38; 32, 39; 33, 40; 33, 41; 33, 42; 37, 43; 37, 44; 38, 45; 38, 46; 41, 47; 41, 48; 42, 49; 42, 50; 43, 51; 43, 52; 44, 53; 44, 54; 48, 55; 54, 56; 55, 57; 55, 58 | async def create(self, query, *, dc=None):
"""Creates a new prepared query
Parameters:
Query (Object): Query definition
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
Object: New query ID
The create operation expects a body that defines the prepared query,
like this example::
{
"Name": "my-query",
"Session": "adf4238a-882b-9ddc-4a9d-5b6758e4159e",
"Token": "",
"Near": "node1",
"Service": {
"Service": "redis",
"Failover": {
"NearestN": 3,
"Datacenters": ["dc1", "dc2"]
},
"OnlyPassing": False,
"Tags": ["master", "!experimental"]
},
"DNS": {
"TTL": timedelta(seconds=10)
}
}
Only the **Service** field inside the **Service** structure is
mandatory, all other fields will take their default values if they
are not included.
**Name** is an optional friendly name that can be used to execute a
query instead of using its ID.
**Session** provides a way to automatically remove a prepared query
when the given session is invalidated. This is optional, and if not
given the prepared query must be manually removed when no longer
needed.
**Token**, if specified, is a captured ACL Token that is reused as the
ACL Token every time the query is executed. This allows queries to be
executed by clients with lesser or even no ACL Token, so this should
be used with care. The token itself can only be seen by clients with a
management token. If the **Token** field is left blank or omitted, the
client's ACL Token will be used to determine if they have access to the
service being queried. If the client does not supply an ACL Token, the
anonymous token will be used.
**Near** allows specifying a particular node to sort near based on
distance sorting using Network Coordinates. The nearest instance to
the specified node will be returned first, and subsequent nodes in the
response will be sorted in ascending order of estimated round-trip
times. If the node given does not exist, the nodes in the response
will be shuffled. Using the magic **_agent** value is supported, and
will automatically return results nearest the agent servicing the
request. If unspecified, the response will be shuffled by default.
The set of fields inside the **Service** structure define the
query's behavior.
**Service** is the name of the service to query. This is required.
**Failover** contains two fields, both of which are optional, and
determine what happens if no healthy nodes are available in the local
datacenter when the query is executed. It allows the use of nodes in
other datacenters with very little configuration.
If **NearestN** is set to a value greater than zero, then the query
will be forwarded to up to **NearestN** other datacenters based on
their estimated network round trip time using Network Coordinates from
the WAN gossip pool. The median round trip time from the server
handling the query to the servers in the remote datacenter is used to
determine the priority. The default value is zero. All Consul servers
must be running version 0.6.0 or above in order for this feature to
work correctly. If any servers are not running the required version of
Consul they will be considered last since they won't have any
available network coordinate information.
**Datacenters** contains a fixed list of remote datacenters to forward
the query to if there are no healthy nodes in the local datacenter.
Datacenters are queried in the order given in the list. If this option
is combined with **NearestN**, then the **NearestN** queries will be
performed first, followed by the list given by **Datacenters**. A
given datacenter will only be queried one time during a failover, even
if it is selected by both **NearestN** and is listed in
**Datacenters**. The default value is an empty list.
**OnlyPassing** controls the behavior of the query's health check
filtering. If this is set to false, the results will include nodes
with checks in the passing as well as the warning states. If this is
set to true, only nodes with checks in the passing state will be
returned. The default value is False.
**Tags** provides a list of service tags to filter the query results.
For a service to pass the tag filter it must have all of the required
tags, and none of the excluded tags (prefixed with ``!``).
The default value is an empty list, which does no tag filtering.
**TTL** in the **DNS** structure is a duration string that can use "s"
as a suffix for seconds. It controls how the TTL is set when query
results are served over DNS. If this isn't specified, then the Consul
agent configuration for the given service will be used
(see DNS Caching). If this is specified, it will take precedence over
any Consul agent-specific configuration. If no TTL is specified here
or at the Consul agent level, then the TTL will default to 0.
It returns the ID of the created query::
{
"ID": "8f246b77-f3e1-ff88-5b48-8ec93abf3e05"
}
"""
if "Token" in query:
# in case of a full token object...
query["Token"] = extract_attr(query["Token"], keys=["ID"])
response = await self._api.post("/v1/query",
params={"dc": dc}, data=query)
return response.body |
0, module; 1, function_definition; 2, function_name:execute; 3, parameters; 4, block; 5, identifier:self; 6, identifier:query; 7, keyword_separator; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, return_statement; 16, identifier:dc; 17, None; 18, identifier:near; 19, None; 20, identifier:limit; 21, None; 22, identifier:consistency; 23, None; 24, comment:"""Executes a prepared query
Parameters:
query (ObjectID): Query ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): Sort the resulting list in ascending order based on
the estimated round trip time from that node
limit (int): Limit the list's size to the given number of nodes
consistency (Consistency): Force consistency
Returns:
Object:
Raises:
NotFound: the query does not exist
Returns a body like this::
{
"Service": "redis",
"Nodes": [
{
"Node": {
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.12",
"wan": "10.1.10.12"
}
},
"Service": {
"ID": "redis",
"Service": "redis",
"Tags": None,
"Port": 8000
},
"Checks": [
{
"Node": "foobar",
"CheckID": "service:redis",
"Name": "Service 'redis' check",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "redis",
"ServiceName": "redis"
},
{
"Node": "foobar",
"CheckID": "serfHealth",
"Name": "Serf Health Status",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "",
"ServiceName": ""
}
],
"DNS": {
"TTL": timedelta(seconds=10)
},
"Datacenter": "dc3",
"Failovers": 2
}
]
}
The **Nodes** section contains the list of healthy nodes providing
the given service, as specified by the constraints of the prepared
query.
**Service** has the service name that the query was selecting. This is
useful for context in case an empty list of nodes is returned.
**DNS** has information used when serving the results over DNS. This
is just a copy of the structure given when the prepared query was
created.
**Datacenter** has the datacenter that ultimately provided the list of
nodes and **Failovers** has the number of remote datacenters that were
queried while executing the query. This provides some insight into
where the data came from. This will be zero during non-failover
operations where there were healthy nodes found in the local
datacenter.
"""; 25, assignment; 26, assignment; 27, attribute; 28, identifier:query_id; 29, call; 30, identifier:response; 31, await; 32, identifier:response; 33, identifier:body; 34, identifier:extract_attr; 35, argument_list; 36, call; 37, identifier:query; 38, keyword_argument; 39, attribute; 40, argument_list; 41, identifier:keys; 42, list; 43, attribute; 44, identifier:get; 45, binary_operator:"/v1/query/%s/execute" % query_id; 46, keyword_argument; 47, keyword_argument; 48, string:"ID"; 49, identifier:self; 50, identifier:_api; 51, string:"/v1/query/%s/execute"; 52, identifier:query_id; 53, identifier:params; 54, dictionary; 55, identifier:consistency; 56, identifier:consistency; 57, pair; 58, pair; 59, pair; 60, string:"dc"; 61, identifier:dc; 62, string:"near"; 63, identifier:near; 64, string:"limit"; 65, identifier:limit | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 8, 16; 8, 17; 9, 18; 9, 19; 10, 20; 10, 21; 11, 22; 11, 23; 12, 24; 13, 25; 14, 26; 15, 27; 25, 28; 25, 29; 26, 30; 26, 31; 27, 32; 27, 33; 29, 34; 29, 35; 31, 36; 35, 37; 35, 38; 36, 39; 36, 40; 38, 41; 38, 42; 39, 43; 39, 44; 40, 45; 40, 46; 40, 47; 42, 48; 43, 49; 43, 50; 45, 51; 45, 52; 46, 53; 46, 54; 47, 55; 47, 56; 54, 57; 54, 58; 54, 59; 57, 60; 57, 61; 58, 62; 58, 63; 59, 64; 59, 65 | async def execute(self, query, *,
dc=None, near=None, limit=None, consistency=None):
"""Executes a prepared query
Parameters:
query (ObjectID): Query ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): Sort the resulting list in ascending order based on
the estimated round trip time from that node
limit (int): Limit the list's size to the given number of nodes
consistency (Consistency): Force consistency
Returns:
Object:
Raises:
NotFound: the query does not exist
Returns a body like this::
{
"Service": "redis",
"Nodes": [
{
"Node": {
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.12",
"wan": "10.1.10.12"
}
},
"Service": {
"ID": "redis",
"Service": "redis",
"Tags": None,
"Port": 8000
},
"Checks": [
{
"Node": "foobar",
"CheckID": "service:redis",
"Name": "Service 'redis' check",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "redis",
"ServiceName": "redis"
},
{
"Node": "foobar",
"CheckID": "serfHealth",
"Name": "Serf Health Status",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "",
"ServiceName": ""
}
],
"DNS": {
"TTL": timedelta(seconds=10)
},
"Datacenter": "dc3",
"Failovers": 2
}
]
}
The **Nodes** section contains the list of healthy nodes providing
the given service, as specified by the constraints of the prepared
query.
**Service** has the service name that the query was selecting. This is
useful for context in case an empty list of nodes is returned.
**DNS** has information used when serving the results over DNS. This
is just a copy of the structure given when the prepared query was
created.
**Datacenter** has the datacenter that ultimately provided the list of
nodes and **Failovers** has the number of remote datacenters that were
queried while executing the query. This provides some insight into
where the data came from. This will be zero during non-failover
operations where there were healthy nodes found in the local
datacenter.
"""
query_id = extract_attr(query, keys=["ID"])
response = await self._api.get(
"/v1/query/%s/execute" % query_id,
params={"dc": dc, "near": near, "limit": limit},
consistency=consistency)
return response.body |
0, module; 1, function_definition; 2, function_name:headerSortAscending; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, comment:"""
Sorts the column at the current header index by ascending order.
"""; 10, call; 11, call; 12, attribute; 13, argument_list; 14, attribute; 15, argument_list; 16, identifier:self; 17, identifier:setSortingEnabled; 18, True; 19, identifier:self; 20, identifier:sortByColumn; 21, attribute; 22, attribute; 23, identifier:self; 24, identifier:_headerIndex; 25, attribute; 26, identifier:AscendingOrder; 27, identifier:QtCore; 28, identifier:Qt | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 10, 12; 10, 13; 11, 14; 11, 15; 12, 16; 12, 17; 13, 18; 14, 19; 14, 20; 15, 21; 15, 22; 21, 23; 21, 24; 22, 25; 22, 26; 25, 27; 25, 28 | def headerSortAscending( self ):
"""
Sorts the column at the current header index by ascending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.AscendingOrder) |
0, module; 1, function_definition; 2, function_name:headerSortDescending; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, comment:"""
Sorts the column at the current header index by descending order.
"""; 10, call; 11, call; 12, attribute; 13, argument_list; 14, attribute; 15, argument_list; 16, identifier:self; 17, identifier:setSortingEnabled; 18, True; 19, identifier:self; 20, identifier:sortByColumn; 21, attribute; 22, attribute; 23, identifier:self; 24, identifier:_headerIndex; 25, attribute; 26, identifier:DescendingOrder; 27, identifier:QtCore; 28, identifier:Qt | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 10, 12; 10, 13; 11, 14; 11, 15; 12, 16; 12, 17; 13, 18; 14, 19; 14, 20; 15, 21; 15, 22; 21, 23; 21, 24; 22, 25; 22, 26; 25, 27; 25, 28 | def headerSortDescending( self ):
"""
Sorts the column at the current header index by descending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.DescendingOrder) |
0, module; 1, function_definition; 2, function_name:nodes; 3, parameters; 4, block; 5, identifier:self; 6, keyword_separator; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, return_statement; 15, identifier:dc; 16, None; 17, identifier:near; 18, None; 19, identifier:watch; 20, None; 21, identifier:consistency; 22, None; 23, comment:"""Lists nodes in a given DC
Parameters:
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): Sort the node list in ascending order based on the
estimated round trip time from that node.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list
It returns a body like this::
[
{
"Node": "baz",
"Address": "10.1.10.11",
"TaggedAddresses": {
"lan": "10.1.10.11",
"wan": "10.1.10.11"
}
},
{
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.11",
"wan": "10.1.10.12"
}
}
]
"""; 24, assignment; 25, assignment; 26, call; 27, identifier:params; 28, dictionary; 29, identifier:response; 30, await; 31, identifier:consul; 32, argument_list; 33, pair; 34, pair; 35, call; 36, identifier:response; 37, string:"dc"; 38, identifier:dc; 39, string:"near"; 40, identifier:near; 41, attribute; 42, argument_list; 43, attribute; 44, identifier:get; 45, string:"/v1/catalog/nodes"; 46, keyword_argument; 47, keyword_argument; 48, keyword_argument; 49, identifier:self; 50, identifier:_api; 51, identifier:params; 52, identifier:params; 53, identifier:watch; 54, identifier:watch; 55, identifier:consistency; 56, identifier:consistency | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 9, 20; 10, 21; 10, 22; 11, 23; 12, 24; 13, 25; 14, 26; 24, 27; 24, 28; 25, 29; 25, 30; 26, 31; 26, 32; 28, 33; 28, 34; 30, 35; 32, 36; 33, 37; 33, 38; 34, 39; 34, 40; 35, 41; 35, 42; 41, 43; 41, 44; 42, 45; 42, 46; 42, 47; 42, 48; 43, 49; 43, 50; 46, 51; 46, 52; 47, 53; 47, 54; 48, 55; 48, 56 | async def nodes(self, *,
dc=None, near=None, watch=None, consistency=None):
"""Lists nodes in a given DC
Parameters:
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): Sort the node list in ascending order based on the
estimated round trip time from that node.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list
It returns a body like this::
[
{
"Node": "baz",
"Address": "10.1.10.11",
"TaggedAddresses": {
"lan": "10.1.10.11",
"wan": "10.1.10.11"
}
},
{
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.11",
"wan": "10.1.10.12"
}
}
]
"""
params = {"dc": dc, "near": near}
response = await self._api.get("/v1/catalog/nodes",
params=params,
watch=watch,
consistency=consistency)
return consul(response) |
0, module; 1, function_definition; 2, function_name:checks; 3, parameters; 4, block; 5, identifier:self; 6, identifier:service; 7, keyword_separator; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, return_statement; 17, identifier:dc; 18, None; 19, identifier:near; 20, None; 21, identifier:watch; 22, None; 23, identifier:consistency; 24, None; 25, comment:"""Returns the checks of a service
Parameters:
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): With a node name will sort the node list in ascending
order based on the estimated round trip time from that
node
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list of checks
"""; 26, assignment; 27, assignment; 28, assignment; 29, call; 30, identifier:service_id; 31, call; 32, identifier:params; 33, dictionary; 34, identifier:response; 35, await; 36, identifier:consul; 37, argument_list; 38, identifier:extract_attr; 39, argument_list; 40, pair; 41, pair; 42, call; 43, identifier:response; 44, identifier:service; 45, keyword_argument; 46, string:"dc"; 47, identifier:dc; 48, string:"near"; 49, identifier:near; 50, attribute; 51, argument_list; 52, identifier:keys; 53, list; 54, attribute; 55, identifier:get; 56, string:"/v1/health/checks"; 57, identifier:service_id; 58, keyword_argument; 59, keyword_argument; 60, keyword_argument; 61, string:"ServiceID"; 62, string:"ID"; 63, identifier:self; 64, identifier:_api; 65, identifier:params; 66, identifier:params; 67, identifier:watch; 68, identifier:watch; 69, identifier:consistency; 70, identifier:consistency | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 8, 17; 8, 18; 9, 19; 9, 20; 10, 21; 10, 22; 11, 23; 11, 24; 12, 25; 13, 26; 14, 27; 15, 28; 16, 29; 26, 30; 26, 31; 27, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 31, 38; 31, 39; 33, 40; 33, 41; 35, 42; 37, 43; 39, 44; 39, 45; 40, 46; 40, 47; 41, 48; 41, 49; 42, 50; 42, 51; 45, 52; 45, 53; 50, 54; 50, 55; 51, 56; 51, 57; 51, 58; 51, 59; 51, 60; 53, 61; 53, 62; 54, 63; 54, 64; 58, 65; 58, 66; 59, 67; 59, 68; 60, 69; 60, 70 | async def checks(self, service, *,
dc=None, near=None, watch=None, consistency=None):
"""Returns the checks of a service
Parameters:
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
near (str): With a node name will sort the node list in ascending
order based on the estimated round trip time from that
node
watch (Blocking): Do a blocking query
consistency (Consistency): Force consistency
Returns:
CollectionMeta: where value is a list of checks
"""
service_id = extract_attr(service, keys=["ServiceID", "ID"])
params = {"dc": dc, "near": near}
response = await self._api.get("/v1/health/checks", service_id,
params=params,
watch=watch,
consistency=consistency)
return consul(response) |
0, module; 1, function_definition; 2, function_name:_get_alphabetical_members; 3, parameters; 4, block; 5, identifier:obj; 6, identifier:predicate; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, comment:"""Get members of an object, sorted alphabetically.
Parameters
----------
obj
An object.
predicate : callable
Callable that takes an attribute and returns a bool of whether the
attribute should be returned or not.
Returns
-------
members : `dict`
Dictionary of
- Keys: attribute name
- Values: attribute
The dictionary is ordered according to the attribute name.
Notes
-----
This uses the insertion-order-preserved nature of `dict` in Python 3.6+.
See also
--------
`inspect.getmembers`
"""; 13, assignment; 14, assignment; 15, call; 16, dictionary_comprehension; 17, identifier:fields; 18, call; 19, identifier:keys; 20, call; 21, attribute; 22, argument_list; 23, pair; 24, for_in_clause; 25, identifier:dict; 26, argument_list; 27, identifier:list; 28, argument_list; 29, identifier:keys; 30, identifier:sort; 31, identifier:k; 32, subscript; 33, identifier:k; 34, identifier:keys; 35, call; 36, call; 37, identifier:fields; 38, identifier:k; 39, attribute; 40, argument_list; 41, attribute; 42, argument_list; 43, identifier:inspect; 44, identifier:getmembers; 45, identifier:obj; 46, identifier:predicate; 47, identifier:fields; 48, identifier:keys | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 8, 13; 9, 14; 10, 15; 11, 16; 13, 17; 13, 18; 14, 19; 14, 20; 15, 21; 15, 22; 16, 23; 16, 24; 18, 25; 18, 26; 20, 27; 20, 28; 21, 29; 21, 30; 23, 31; 23, 32; 24, 33; 24, 34; 26, 35; 28, 36; 32, 37; 32, 38; 35, 39; 35, 40; 36, 41; 36, 42; 39, 43; 39, 44; 40, 45; 40, 46; 41, 47; 41, 48 | def _get_alphabetical_members(obj, predicate):
"""Get members of an object, sorted alphabetically.
Parameters
----------
obj
An object.
predicate : callable
Callable that takes an attribute and returns a bool of whether the
attribute should be returned or not.
Returns
-------
members : `dict`
Dictionary of
- Keys: attribute name
- Values: attribute
The dictionary is ordered according to the attribute name.
Notes
-----
This uses the insertion-order-preserved nature of `dict` in Python 3.6+.
See also
--------
`inspect.getmembers`
"""
fields = dict(inspect.getmembers(obj, predicate))
keys = list(fields.keys())
keys.sort()
return {k: fields[k] for k in keys} |
0, module; 1, function_definition; 2, function_name:_argsort; 3, parameters; 4, block; 5, identifier:y_score; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, return_statement; 12, identifier:k; 13, None; 14, comment:"""
Returns the indexes in descending order of the top k score
or all scores if k is None
"""; 15, assignment; 16, assignment; 17, comparison_operator:k is not None; 18, block; 19, identifier:argsort; 20, identifier:ranks; 21, call; 22, identifier:argsort; 23, subscript; 24, identifier:k; 25, None; 26, expression_statement; 27, attribute; 28, argument_list; 29, identifier:ranks; 30, slice; 31, assignment; 32, identifier:y_score; 33, identifier:argsort; 34, unary_operator; 35, identifier:argsort; 36, subscript; 37, integer:1; 38, identifier:argsort; 39, slice; 40, integer:0; 41, identifier:k | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 9, 16; 10, 17; 10, 18; 11, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 21, 27; 21, 28; 23, 29; 23, 30; 26, 31; 27, 32; 27, 33; 30, 34; 31, 35; 31, 36; 34, 37; 36, 38; 36, 39; 39, 40; 39, 41 | def _argsort(y_score, k=None):
"""
Returns the indexes in descending order of the top k score
or all scores if k is None
"""
ranks = y_score.argsort()
argsort = ranks[::-1]
if k is not None:
argsort = argsort[0:k]
return argsort |
0, module; 1, function_definition; 2, function_name:assemble; 3, parameters; 4, comment:# type: (AbstractModule, *AbstractModule, **Any) -> SeqRecord; 5, block; 6, identifier:self; 7, identifier:module; 8, list_splat_pattern; 9, dictionary_splat_pattern; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, identifier:modules; 14, identifier:kwargs; 15, comment:"""Assemble the provided modules into the vector.
Arguments:
module (`~moclo.base.modules.AbstractModule`): a module to insert
in the vector.
modules (`~moclo.base.modules.AbstractModule`, optional): additional
modules to insert in the vector. The order of the parameters
is not important, since modules will be sorted by their start
overhang in the function.
Returns:
`~Bio.SeqRecord.SeqRecord`: the assembled sequence with sequence
annotations inherited from the vector and the modules.
Raises:
`~moclo.errors.DuplicateModules`: when two different modules share
the same start overhang, leading in possibly non-deterministic
constructs.
`~moclo.errors.MissingModule`: when a module has an end overhang
that is not shared by any other module, leading to a partial
construct only
`~moclo.errors.InvalidSequence`: when one of the modules does not
match the required module structure (missing site, wrong
overhang, etc.).
`~moclo.errors.UnusedModules`: when some modules were not used
during the assembly (mostly caused by duplicate parts).
"""; 16, assignment; 17, call; 18, identifier:mgr; 19, call; 20, attribute; 21, argument_list; 22, identifier:AssemblyManager; 23, argument_list; 24, identifier:mgr; 25, identifier:assemble; 26, keyword_argument; 27, keyword_argument; 28, keyword_argument; 29, keyword_argument; 30, identifier:vector; 31, identifier:self; 32, identifier:modules; 33, binary_operator:[module] + list(modules); 34, identifier:name; 35, call; 36, identifier:id_; 37, call; 38, list; 39, call; 40, attribute; 41, argument_list; 42, attribute; 43, argument_list; 44, identifier:module; 45, identifier:list; 46, argument_list; 47, identifier:kwargs; 48, identifier:get; 49, string:"name"; 50, string:"assembly"; 51, identifier:kwargs; 52, identifier:get; 53, string:"id"; 54, string:"assembly"; 55, identifier:modules | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 3, 8; 3, 9; 5, 10; 5, 11; 5, 12; 8, 13; 9, 14; 10, 15; 11, 16; 12, 17; 16, 18; 16, 19; 17, 20; 17, 21; 19, 22; 19, 23; 20, 24; 20, 25; 23, 26; 23, 27; 23, 28; 23, 29; 26, 30; 26, 31; 27, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 33, 38; 33, 39; 35, 40; 35, 41; 37, 42; 37, 43; 38, 44; 39, 45; 39, 46; 40, 47; 40, 48; 41, 49; 41, 50; 42, 51; 42, 52; 43, 53; 43, 54; 46, 55 | def assemble(self, module, *modules, **kwargs):
# type: (AbstractModule, *AbstractModule, **Any) -> SeqRecord
"""Assemble the provided modules into the vector.
Arguments:
module (`~moclo.base.modules.AbstractModule`): a module to insert
in the vector.
modules (`~moclo.base.modules.AbstractModule`, optional): additional
modules to insert in the vector. The order of the parameters
is not important, since modules will be sorted by their start
overhang in the function.
Returns:
`~Bio.SeqRecord.SeqRecord`: the assembled sequence with sequence
annotations inherited from the vector and the modules.
Raises:
`~moclo.errors.DuplicateModules`: when two different modules share
the same start overhang, leading in possibly non-deterministic
constructs.
`~moclo.errors.MissingModule`: when a module has an end overhang
that is not shared by any other module, leading to a partial
construct only
`~moclo.errors.InvalidSequence`: when one of the modules does not
match the required module structure (missing site, wrong
overhang, etc.).
`~moclo.errors.UnusedModules`: when some modules were not used
during the assembly (mostly caused by duplicate parts).
"""
mgr = AssemblyManager(
vector=self,
modules=[module] + list(modules),
name=kwargs.get("name", "assembly"),
id_=kwargs.get("id", "assembly"),
)
return mgr.assemble() |
0, module; 1, function_definition; 2, function_name:getPortSideView; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, identifier:side; 8, generic_type; 9, expression_statement; 10, if_statement; 11, identifier:List; 12, type_parameter; 13, comment:"""
Returns a sublist view for all ports of given side.
:attention: Use this only after port sides are fixed!
This is currently the case after running the {@link org.eclipse.elk.alg.layered.intermediate.PortListSorter}.
Non-structural changes to this list are reflected in the original list. A structural modification is any
operation that adds or deletes one or more elements; merely setting the value of an element is not a structural
modification. Sublist indices can be cached using {@link LNode#cachePortSides()}.
:param side: a port side
:return: an iterable for the ports of given side
"""; 14, comparison_operator:side == PortSide.WEST; 15, block; 16, elif_clause; 17, elif_clause; 18, elif_clause; 19, else_clause; 20, type; 21, identifier:side; 22, attribute; 23, return_statement; 24, comparison_operator:side == PortSide.EAST; 25, block; 26, comparison_operator:side == PortSide.NORTH; 27, block; 28, comparison_operator:side == PortSide.SOUTH; 29, block; 30, block; 31, string:"LPort"; 32, identifier:PortSide; 33, identifier:WEST; 34, attribute; 35, identifier:side; 36, attribute; 37, return_statement; 38, identifier:side; 39, attribute; 40, return_statement; 41, identifier:side; 42, attribute; 43, return_statement; 44, raise_statement; 45, identifier:self; 46, identifier:west; 47, identifier:PortSide; 48, identifier:EAST; 49, attribute; 50, identifier:PortSide; 51, identifier:NORTH; 52, attribute; 53, identifier:PortSide; 54, identifier:SOUTH; 55, attribute; 56, call; 57, identifier:self; 58, identifier:east; 59, identifier:self; 60, identifier:north; 61, identifier:self; 62, identifier:south; 63, identifier:ValueError; 64, argument_list; 65, identifier:side | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 4, 8; 5, 9; 5, 10; 8, 11; 8, 12; 9, 13; 10, 14; 10, 15; 10, 16; 10, 17; 10, 18; 10, 19; 12, 20; 14, 21; 14, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 18, 28; 18, 29; 19, 30; 20, 31; 22, 32; 22, 33; 23, 34; 24, 35; 24, 36; 25, 37; 26, 38; 26, 39; 27, 40; 28, 41; 28, 42; 29, 43; 30, 44; 34, 45; 34, 46; 36, 47; 36, 48; 37, 49; 39, 50; 39, 51; 40, 52; 42, 53; 42, 54; 43, 55; 44, 56; 49, 57; 49, 58; 52, 59; 52, 60; 55, 61; 55, 62; 56, 63; 56, 64; 64, 65 | def getPortSideView(self, side) -> List["LPort"]:
"""
Returns a sublist view for all ports of given side.
:attention: Use this only after port sides are fixed!
This is currently the case after running the {@link org.eclipse.elk.alg.layered.intermediate.PortListSorter}.
Non-structural changes to this list are reflected in the original list. A structural modification is any
operation that adds or deletes one or more elements; merely setting the value of an element is not a structural
modification. Sublist indices can be cached using {@link LNode#cachePortSides()}.
:param side: a port side
:return: an iterable for the ports of given side
"""
if side == PortSide.WEST:
return self.west
elif side == PortSide.EAST:
return self.east
elif side == PortSide.NORTH:
return self.north
elif side == PortSide.SOUTH:
return self.south
else:
raise ValueError(side) |
0, module; 1, function_definition; 2, function_name:sort_untl; 3, parameters; 4, block; 5, identifier:self; 6, identifier:sort_structure; 7, expression_statement; 8, expression_statement; 9, comment:"""Sort the UNTL Python object by the index
of a sort structure pre-ordered list.
"""; 10, call; 11, attribute; 12, argument_list; 13, attribute; 14, identifier:sort; 15, keyword_argument; 16, identifier:self; 17, identifier:children; 18, identifier:key; 19, lambda; 20, lambda_parameters; 21, call; 22, identifier:obj; 23, attribute; 24, argument_list; 25, identifier:sort_structure; 26, identifier:index; 27, attribute; 28, identifier:obj; 29, identifier:tag | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 10, 11; 10, 12; 11, 13; 11, 14; 12, 15; 13, 16; 13, 17; 15, 18; 15, 19; 19, 20; 19, 21; 20, 22; 21, 23; 21, 24; 23, 25; 23, 26; 24, 27; 27, 28; 27, 29 | def sort_untl(self, sort_structure):
"""Sort the UNTL Python object by the index
of a sort structure pre-ordered list.
"""
self.children.sort(key=lambda obj: sort_structure.index(obj.tag)) |
0, module; 1, function_definition; 2, function_name:top; 3, parameters; 4, block; 5, identifier:self; 6, identifier:sort_by; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""Get the best results according to your custom sort method."""; 11, assignment; 12, identifier:sort; 13, identifier:sort; 14, call; 15, identifier:sorted; 16, argument_list; 17, attribute; 18, keyword_argument; 19, identifier:self; 20, identifier:results; 21, identifier:key; 22, identifier:sort_by | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 11, 13; 11, 14; 14, 15; 14, 16; 16, 17; 16, 18; 17, 19; 17, 20; 18, 21; 18, 22 | def top(self, sort_by):
"""Get the best results according to your custom sort method."""
sort = sorted(self.results, key=sort_by)
return sort |
0, module; 1, function_definition; 2, function_name:_read_elem_nodes; 3, parameters; 4, block; 5, identifier:self; 6, identifier:fid; 7, expression_statement; 8, expression_statement; 9, comment:# # prepare nodes; 10, comment:# nodes_sorted = np.zeros((number_of_nodes, 3), dtype=float); 11, comment:# nodes = np.zeros((number_of_nodes, 3), dtype=float); 12, comment:# read in nodes; 13, expression_statement; 14, for_statement; 15, comment:# round node coordinates to 5th decimal point. Sometimes this is; 16, comment:# important when we deal with mal-formatted node data; 17, expression_statement; 18, comment:# check for CutMcK; 19, comment:# The check is based on the first node, but if one node was renumbered,; 20, comment:# so were all the others.; 21, if_statement; 22, comment:# Rearrange nodes when CutMcK was used.; 23, if_statement; 24, comment:# prepare node dict; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, comment:""" Read the nodes from an opened elem.dat file. Correct for CutMcK
transformations.
We store three typed of nodes in the dict 'nodes':
* "raw" : as read from the elem.dat file
* "presort" : pre-sorted so we can directly read node numbers from
a elec.dat file and use them as indices.
* "sorted" : completely sorted as in the original grid (before any
CutMcK)
For completeness, we also store the following keys:
* "cutmck_index" : Array containing the indices in "presort" to
obtain the "sorted" values:
nodes['sorted'] = nodes['presort'] [nodes['cutmck_index'], :]
* "rev_cutmck_index" : argsort(cutmck_index)
"""; 30, assignment; 31, assignment; 32, identifier:nr; 33, call; 34, block; 35, assignment; 36, parenthesized_expression; 37, block; 38, else_clause; 39, parenthesized_expression; 40, block; 41, else_clause; 42, assignment; 43, assignment; 44, assignment; 45, assignment; 46, identifier:nodes; 47, dictionary; 48, identifier:nodes_raw; 49, call; 50, identifier:range; 51, argument_list; 52, expression_statement; 53, expression_statement; 54, subscript; 55, call; 56, comparison_operator:nodes_raw[:, 0] != list(range(1, nodes_raw.shape[0])); 57, expression_statement; 58, expression_statement; 59, block; 60, subscript; 61, expression_statement; 62, expression_statement; 63, for_statement; 64, comment:# sort them; 65, expression_statement; 66, expression_statement; 67, expression_statement; 68, expression_statement; 69, block; 70, subscript; 71, identifier:nodes_raw; 72, subscript; 73, identifier:nodes_sorted; 74, attribute; 75, identifier:nodes; 76, attribute; 77, subscript; 78, attribute; 79, argument_list; 80, integer:0; 81, subscript; 82, assignment; 83, assignment; 84, identifier:nodes_raw; 85, slice; 86, slice; 87, attribute; 88, argument_list; 89, subscript; 90, call; 91, assignment; 92, call; 93, expression_statement; 94, attribute; 95, string; 96, assignment; 97, assignment; 98, identifier:node; 99, call; 100, block; 101, assignment; 102, assignment; 103, assignment; 104, assignment; 105, expression_statement; 106, expression_statement; 107, identifier:nodes; 108, string; 109, identifier:nodes; 110, string; 111, identifier:self; 112, identifier:nodes; 113, identifier:self; 114, identifier:nr_of_nodes; 115, attribute; 116, integer:0; 117, identifier:np; 118, identifier:empty; 119, tuple; 120, keyword_argument; 121, attribute; 122, string; 123, identifier:node_line; 124, call; 125, subscript; 126, call; 127, integer:1; 128, integer:3; 129, identifier:np; 130, identifier:round; 131, subscript; 132, integer:5; 133, identifier:nodes_raw; 134, slice; 135, integer:0; 136, identifier:list; 137, argument_list; 138, subscript; 139, True; 140, identifier:print; 141, argument_list; 142, assignment; 143, identifier:self; 144, identifier:header; 145, string_content:cutmck; 146, identifier:nodes_cutmck; 147, call; 148, identifier:nodes_cutmck_index; 149, call; 150, identifier:range; 151, argument_list; 152, expression_statement; 153, expression_statement; 154, expression_statement; 155, expression_statement; 156, identifier:nodes_sorted; 157, subscript; 158, subscript; 159, identifier:nodes_cutmck; 160, subscript; 161, identifier:nodes_cutmck_index; 162, subscript; 163, call; 164, assignment; 165, assignment; 166, string_content:raw; 167, string_content:sorted; 168, subscript; 169, identifier:shape; 170, subscript; 171, integer:3; 172, identifier:dtype; 173, identifier:float; 174, identifier:self; 175, identifier:header; 176, string_content:nr_nodes; 177, attribute; 178, argument_list; 179, identifier:nodes_raw; 180, identifier:nr; 181, slice; 182, attribute; 183, argument_list; 184, identifier:nodes_raw; 185, slice; 186, slice; 187, call; 188, attribute; 189, string; 190, string; 191, subscript; 192, False; 193, attribute; 194, argument_list; 195, attribute; 196, argument_list; 197, integer:0; 198, subscript; 199, assignment; 200, assignment; 201, assignment; 202, assignment; 203, identifier:nodes_cutmck; 204, identifier:nodes_cutmck_index; 205, slice; 206, identifier:nodes; 207, string; 208, identifier:nodes; 209, string; 210, identifier:nodes; 211, string; 212, attribute; 213, argument_list; 214, identifier:nodes_sorted; 215, identifier:nodes_raw; 216, subscript; 217, identifier:nodes_raw; 218, identifier:nodes; 219, string; 220, attribute; 221, string; 222, call; 223, identifier:lstrip; 224, identifier:np; 225, identifier:fromstring; 226, identifier:node_line; 227, keyword_argument; 228, keyword_argument; 229, integer:1; 230, integer:3; 231, identifier:range; 232, argument_list; 233, identifier:self; 234, identifier:header; 235, string_content:cutmck; 236, string_content:This grid was sorted using CutMcK. The nodes were resorted!; 237, attribute; 238, string; 239, identifier:np; 240, identifier:empty_like; 241, identifier:nodes_raw; 242, identifier:np; 243, identifier:zeros; 244, subscript; 245, keyword_argument; 246, attribute; 247, string; 248, identifier:new_index; 249, call; 250, subscript; 251, subscript; 252, subscript; 253, subscript; 254, subscript; 255, subscript; 256, string_content:presort; 257, string_content:cutmck_index; 258, string_content:rev_cutmck_index; 259, identifier:np; 260, identifier:argsort; 261, identifier:nodes_cutmck_index; 262, identifier:nodes; 263, string; 264, string_content:raw; 265, identifier:self; 266, identifier:header; 267, string_content:nr_nodes; 268, attribute; 269, argument_list; 270, identifier:dtype; 271, identifier:float; 272, identifier:sep; 273, string; 274, integer:1; 275, subscript; 276, identifier:self; 277, identifier:header; 278, string_content:cutmck; 279, attribute; 280, integer:0; 281, identifier:dtype; 282, identifier:int; 283, identifier:self; 284, identifier:header; 285, string_content:nr_nodes; 286, attribute; 287, argument_list; 288, identifier:nodes_cutmck; 289, subscript; 290, slice; 291, identifier:nodes_raw; 292, identifier:node; 293, slice; 294, identifier:nodes_cutmck; 295, subscript; 296, integer:0; 297, identifier:new_index; 298, integer:0; 299, identifier:nodes_cutmck_index; 300, identifier:node; 301, identifier:new_index; 302, integer:0; 303, string_content:presort; 304, identifier:fid; 305, identifier:readline; 306, string_content:; 307, attribute; 308, integer:0; 309, identifier:nodes_raw; 310, identifier:shape; 311, identifier:np; 312, identifier:where; 313, comparison_operator:nodes_raw[:, 0].astype(int) == (node + 1); 314, identifier:new_index; 315, integer:0; 316, integer:1; 317, integer:3; 318, integer:1; 319, integer:3; 320, identifier:new_index; 321, integer:0; 322, identifier:nodes_raw; 323, identifier:shape; 324, call; 325, parenthesized_expression; 326, attribute; 327, argument_list; 328, binary_operator:node + 1; 329, subscript; 330, identifier:astype; 331, identifier:int; 332, identifier:node; 333, integer:1; 334, identifier:nodes_raw; 335, slice; 336, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 7, 29; 8, 30; 13, 31; 14, 32; 14, 33; 14, 34; 17, 35; 21, 36; 21, 37; 21, 38; 23, 39; 23, 40; 23, 41; 25, 42; 26, 43; 27, 44; 28, 45; 30, 46; 30, 47; 31, 48; 31, 49; 33, 50; 33, 51; 34, 52; 34, 53; 35, 54; 35, 55; 36, 56; 37, 57; 37, 58; 38, 59; 39, 60; 40, 61; 40, 62; 40, 63; 40, 64; 40, 65; 40, 66; 40, 67; 40, 68; 41, 69; 42, 70; 42, 71; 43, 72; 43, 73; 44, 74; 44, 75; 45, 76; 45, 77; 49, 78; 49, 79; 51, 80; 51, 81; 52, 82; 53, 83; 54, 84; 54, 85; 54, 86; 55, 87; 55, 88; 56, 89; 56, 90; 57, 91; 58, 92; 59, 93; 60, 94; 60, 95; 61, 96; 62, 97; 63, 98; 63, 99; 63, 100; 65, 101; 66, 102; 67, 103; 68, 104; 69, 105; 69, 106; 70, 107; 70, 108; 72, 109; 72, 110; 74, 111; 74, 112; 76, 113; 76, 114; 77, 115; 77, 116; 78, 117; 78, 118; 79, 119; 79, 120; 81, 121; 81, 122; 82, 123; 82, 124; 83, 125; 83, 126; 86, 127; 86, 128; 87, 129; 87, 130; 88, 131; 88, 132; 89, 133; 89, 134; 89, 135; 90, 136; 90, 137; 91, 138; 91, 139; 92, 140; 92, 141; 93, 142; 94, 143; 94, 144; 95, 145; 96, 146; 96, 147; 97, 148; 97, 149; 99, 150; 99, 151; 100, 152; 100, 153; 100, 154; 100, 155; 101, 156; 101, 157; 102, 158; 102, 159; 103, 160; 103, 161; 104, 162; 104, 163; 105, 164; 106, 165; 108, 166; 110, 167; 115, 168; 115, 169; 119, 170; 119, 171; 120, 172; 120, 173; 121, 174; 121, 175; 122, 176; 124, 177; 124, 178; 125, 179; 125, 180; 125, 181; 126, 182; 126, 183; 131, 184; 131, 185; 131, 186; 137, 187; 138, 188; 138, 189; 141, 190; 142, 191; 142, 192; 147, 193; 147, 194; 149, 195; 149, 196; 151, 197; 151, 198; 152, 199; 153, 200; 154, 201; 155, 202; 157, 203; 157, 204; 157, 205; 158, 206; 158, 207; 160, 208; 160, 209; 162, 210; 162, 211; 163, 212; 163, 213; 164, 214; 164, 215; 165, 216; 165, 217; 168, 218; 168, 219; 170, 220; 170, 221; 177, 222; 177, 223; 182, 224; 182, 225; 183, 226; 183, 227; 183, 228; 186, 229; 186, 230; 187, 231; 187, 232; 188, 233; 188, 234; 189, 235; 190, 236; 191, 237; 191, 238; 193, 239; 193, 240; 194, 241; 195, 242; 195, 243; 196, 244; 196, 245; 198, 246; 198, 247; 199, 248; 199, 249; 200, 250; 200, 251; 201, 252; 201, 253; 202, 254; 202, 255; 207, 256; 209, 257; 211, 258; 212, 259; 212, 260; 213, 261; 216, 262; 216, 263; 219, 264; 220, 265; 220, 266; 221, 267; 222, 268; 222, 269; 227, 270; 227, 271; 228, 272; 228, 273; 232, 274; 232, 275; 237, 276; 237, 277; 238, 278; 244, 279; 244, 280; 245, 281; 245, 282; 246, 283; 246, 284; 247, 285; 249, 286; 249, 287; 250, 288; 250, 289; 250, 290; 251, 291; 251, 292; 251, 293; 252, 294; 252, 295; 252, 296; 253, 297; 253, 298; 254, 299; 254, 300; 255, 301; 255, 302; 263, 303; 268, 304; 268, 305; 273, 306; 275, 307; 275, 308; 279, 309; 279, 310; 286, 311; 286, 312; 287, 313; 289, 314; 289, 315; 290, 316; 290, 317; 293, 318; 293, 319; 295, 320; 295, 321; 307, 322; 307, 323; 313, 324; 313, 325; 324, 326; 324, 327; 325, 328; 326, 329; 326, 330; 327, 331; 328, 332; 328, 333; 329, 334; 329, 335; 329, 336 | def _read_elem_nodes(self, fid):
""" Read the nodes from an opened elem.dat file. Correct for CutMcK
transformations.
We store three typed of nodes in the dict 'nodes':
* "raw" : as read from the elem.dat file
* "presort" : pre-sorted so we can directly read node numbers from
a elec.dat file and use them as indices.
* "sorted" : completely sorted as in the original grid (before any
CutMcK)
For completeness, we also store the following keys:
* "cutmck_index" : Array containing the indices in "presort" to
obtain the "sorted" values:
nodes['sorted'] = nodes['presort'] [nodes['cutmck_index'], :]
* "rev_cutmck_index" : argsort(cutmck_index)
"""
nodes = {}
# # prepare nodes
# nodes_sorted = np.zeros((number_of_nodes, 3), dtype=float)
# nodes = np.zeros((number_of_nodes, 3), dtype=float)
# read in nodes
nodes_raw = np.empty((self.header['nr_nodes'], 3), dtype=float)
for nr in range(0, self.header['nr_nodes']):
node_line = fid.readline().lstrip()
nodes_raw[nr, :] = np.fromstring(
node_line, dtype=float, sep=' ')
# round node coordinates to 5th decimal point. Sometimes this is
# important when we deal with mal-formatted node data
nodes_raw[:, 1:3] = np.round(nodes_raw[:, 1:3], 5)
# check for CutMcK
# The check is based on the first node, but if one node was renumbered,
# so were all the others.
if(nodes_raw[:, 0] != list(range(1, nodes_raw.shape[0]))):
self.header['cutmck'] = True
print(
'This grid was sorted using CutMcK. The nodes were resorted!')
else:
self.header['cutmck'] = False
# Rearrange nodes when CutMcK was used.
if(self.header['cutmck']):
nodes_cutmck = np.empty_like(nodes_raw)
nodes_cutmck_index = np.zeros(nodes_raw.shape[0], dtype=int)
for node in range(0, self.header['nr_nodes']):
new_index = np.where(nodes_raw[:, 0].astype(int) == (node + 1))
nodes_cutmck[new_index[0], 1:3] = nodes_raw[node, 1:3]
nodes_cutmck[new_index[0], 0] = new_index[0]
nodes_cutmck_index[node] = new_index[0]
# sort them
nodes_sorted = nodes_cutmck[nodes_cutmck_index, :]
nodes['presort'] = nodes_cutmck
nodes['cutmck_index'] = nodes_cutmck_index
nodes['rev_cutmck_index'] = np.argsort(nodes_cutmck_index)
else:
nodes_sorted = nodes_raw
nodes['presort'] = nodes_raw
# prepare node dict
nodes['raw'] = nodes_raw
nodes['sorted'] = nodes_sorted
self.nodes = nodes
self.nr_of_nodes = nodes['raw'].shape[0] |
0, module; 1, function_definition; 2, function_name:list; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, default_parameter; 16, default_parameter; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, if_statement; 22, if_statement; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, return_statement; 32, identifier:source_ids; 33, None; 34, identifier:seniority; 35, string:"all"; 36, identifier:stage; 37, None; 38, identifier:date_start; 39, string:"1494539999"; 40, identifier:date_end; 41, identifier:TIMESTAMP_NOW; 42, identifier:filter_id; 43, None; 44, identifier:page; 45, integer:1; 46, identifier:limit; 47, integer:30; 48, identifier:sort_by; 49, string; 50, identifier:filter_reference; 51, None; 52, identifier:order_by; 53, None; 54, comment:"""
Retreive all profiles that match the query param.
Args:
date_end: <string> REQUIRED (default to timestamp of now)
profiles' last date of reception
date_start: <string> REQUIRED (default to "1494539999")
profiles' first date of reception
filter_id: <string>
limit: <int> (default to 30)
number of fetched profiles/page
page: <int> REQUIRED default to 1
number of the page associated to the pagination
seniority: <string> defaut to "all"
profiles' seniority ("all", "senior", "junior")
sort_by: <string>
source_ids: <array of strings> REQUIRED
stage: <string>
Returns
Retrieve the profiles data as <dict>
"""; 55, assignment; 56, assignment; 57, assignment; 58, identifier:filter_id; 59, block; 60, identifier:filter_reference; 61, block; 62, assignment; 63, assignment; 64, assignment; 65, assignment; 66, assignment; 67, assignment; 68, assignment; 69, assignment; 70, call; 71, string_content:ranking; 72, identifier:query_params; 73, dictionary; 74, subscript; 75, call; 76, subscript; 77, call; 78, expression_statement; 79, expression_statement; 80, subscript; 81, call; 82, subscript; 83, call; 84, subscript; 85, call; 86, subscript; 87, call; 88, subscript; 89, call; 90, subscript; 91, call; 92, subscript; 93, identifier:order_by; 94, identifier:response; 95, call; 96, attribute; 97, argument_list; 98, identifier:query_params; 99, string:"date_end"; 100, identifier:_validate_timestamp; 101, argument_list; 102, identifier:query_params; 103, string:"date_start"; 104, identifier:_validate_timestamp; 105, argument_list; 106, assignment; 107, assignment; 108, identifier:query_params; 109, string:"limit"; 110, identifier:_validate_limit; 111, argument_list; 112, identifier:query_params; 113, string:"page"; 114, identifier:_validate_page; 115, argument_list; 116, identifier:query_params; 117, string:"seniority"; 118, identifier:_validate_seniority; 119, argument_list; 120, identifier:query_params; 121, string:"sort_by"; 122, identifier:_validate_sort_by; 123, argument_list; 124, identifier:query_params; 125, string:"source_ids"; 126, attribute; 127, argument_list; 128, identifier:query_params; 129, string:"stage"; 130, identifier:_validate_stage; 131, argument_list; 132, identifier:query_params; 133, string:"order_by"; 134, attribute; 135, argument_list; 136, identifier:response; 137, identifier:json; 138, identifier:date_end; 139, string:"date_end"; 140, identifier:date_start; 141, string:"date_start"; 142, subscript; 143, call; 144, subscript; 145, call; 146, identifier:limit; 147, identifier:page; 148, identifier:seniority; 149, identifier:sort_by; 150, identifier:json; 151, identifier:dumps; 152, call; 153, identifier:stage; 154, attribute; 155, identifier:get; 156, string:"profiles"; 157, identifier:query_params; 158, identifier:query_params; 159, string:"filter_id"; 160, identifier:_validate_filter_id; 161, argument_list; 162, identifier:query_params; 163, string:"filter_reference"; 164, identifier:_validate_filter_reference; 165, argument_list; 166, identifier:_validate_source_ids; 167, argument_list; 168, identifier:self; 169, identifier:client; 170, identifier:filter_id; 171, identifier:filter_reference; 172, identifier:source_ids | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 3, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 4, 31; 6, 32; 6, 33; 7, 34; 7, 35; 8, 36; 8, 37; 9, 38; 9, 39; 10, 40; 10, 41; 11, 42; 11, 43; 12, 44; 12, 45; 13, 46; 13, 47; 14, 48; 14, 49; 15, 50; 15, 51; 16, 52; 16, 53; 17, 54; 18, 55; 19, 56; 20, 57; 21, 58; 21, 59; 22, 60; 22, 61; 23, 62; 24, 63; 25, 64; 26, 65; 27, 66; 28, 67; 29, 68; 30, 69; 31, 70; 49, 71; 55, 72; 55, 73; 56, 74; 56, 75; 57, 76; 57, 77; 59, 78; 61, 79; 62, 80; 62, 81; 63, 82; 63, 83; 64, 84; 64, 85; 65, 86; 65, 87; 66, 88; 66, 89; 67, 90; 67, 91; 68, 92; 68, 93; 69, 94; 69, 95; 70, 96; 70, 97; 74, 98; 74, 99; 75, 100; 75, 101; 76, 102; 76, 103; 77, 104; 77, 105; 78, 106; 79, 107; 80, 108; 80, 109; 81, 110; 81, 111; 82, 112; 82, 113; 83, 114; 83, 115; 84, 116; 84, 117; 85, 118; 85, 119; 86, 120; 86, 121; 87, 122; 87, 123; 88, 124; 88, 125; 89, 126; 89, 127; 90, 128; 90, 129; 91, 130; 91, 131; 92, 132; 92, 133; 95, 134; 95, 135; 96, 136; 96, 137; 101, 138; 101, 139; 105, 140; 105, 141; 106, 142; 106, 143; 107, 144; 107, 145; 111, 146; 115, 147; 119, 148; 123, 149; 126, 150; 126, 151; 127, 152; 131, 153; 134, 154; 134, 155; 135, 156; 135, 157; 142, 158; 142, 159; 143, 160; 143, 161; 144, 162; 144, 163; 145, 164; 145, 165; 152, 166; 152, 167; 154, 168; 154, 169; 161, 170; 165, 171; 167, 172 | def list(self, source_ids=None, seniority="all", stage=None,
date_start="1494539999", date_end=TIMESTAMP_NOW, filter_id=None,
page=1, limit=30, sort_by='ranking', filter_reference=None, order_by=None):
"""
Retreive all profiles that match the query param.
Args:
date_end: <string> REQUIRED (default to timestamp of now)
profiles' last date of reception
date_start: <string> REQUIRED (default to "1494539999")
profiles' first date of reception
filter_id: <string>
limit: <int> (default to 30)
number of fetched profiles/page
page: <int> REQUIRED default to 1
number of the page associated to the pagination
seniority: <string> defaut to "all"
profiles' seniority ("all", "senior", "junior")
sort_by: <string>
source_ids: <array of strings> REQUIRED
stage: <string>
Returns
Retrieve the profiles data as <dict>
"""
query_params = {}
query_params["date_end"] = _validate_timestamp(date_end, "date_end")
query_params["date_start"] = _validate_timestamp(date_start, "date_start")
if filter_id:
query_params["filter_id"] = _validate_filter_id(filter_id)
if filter_reference:
query_params["filter_reference"] = _validate_filter_reference(filter_reference)
query_params["limit"] = _validate_limit(limit)
query_params["page"] = _validate_page(page)
query_params["seniority"] = _validate_seniority(seniority)
query_params["sort_by"] = _validate_sort_by(sort_by)
query_params["source_ids"] = json.dumps(_validate_source_ids(source_ids))
query_params["stage"] = _validate_stage(stage)
query_params["order_by"] = order_by
response = self.client.get("profiles", query_params)
return response.json() |
0, module; 1, function_definition; 2, function_name:get_hypergeometric_stats; 3, parameters; 4, block; 5, identifier:N; 6, identifier:indices; 7, expression_statement; 8, assert_statement; 9, assert_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, while_statement; 19, return_statement; 20, comment:"""Calculates hypergeom. p-values and fold enrichments for all cutoffs.
Parameters
----------
N: int
The length of the list
indices: `numpy.ndarray` with ``dtype=np.uint16``
The (sorted) indices of the "1's" in the list.
"""; 21, call; 22, boolean_operator; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, assignment; 30, assignment; 31, comparison_operator:n < N; 32, block; 33, expression_list; 34, identifier:isinstance; 35, argument_list; 36, call; 37, line_continuation:\; 38, call; 39, identifier:K; 40, attribute; 41, identifier:pvals; 42, call; 43, identifier:folds; 44, call; 45, subscript; 46, float:1.0; 47, subscript; 48, float:1.0; 49, identifier:n; 50, integer:0; 51, identifier:k; 52, integer:0; 53, identifier:p; 54, float:1.0; 55, identifier:n; 56, identifier:N; 57, if_statement; 58, expression_statement; 59, comment:# calculate hypergeometric p-value; 60, expression_statement; 61, comment:# calculate fold enrichment; 62, expression_statement; 63, identifier:pvals; 64, identifier:folds; 65, identifier:N; 66, tuple; 67, identifier:isinstance; 68, argument_list; 69, attribute; 70, argument_list; 71, identifier:indices; 72, identifier:size; 73, attribute; 74, argument_list; 75, attribute; 76, argument_list; 77, identifier:pvals; 78, integer:0; 79, identifier:folds; 80, integer:0; 81, boolean_operator; 82, comment:# "add one"; 83, comment:# calculate f(k+1; N,K,n+1) from f(k; N,K,n); 84, block; 85, else_clause; 86, augmented_assignment; 87, assignment; 88, assignment; 89, identifier:int; 90, attribute; 91, identifier:indices; 92, attribute; 93, identifier:np; 94, identifier:issubdtype; 95, attribute; 96, attribute; 97, identifier:np; 98, identifier:empty; 99, binary_operator:N+1; 100, keyword_argument; 101, identifier:np; 102, identifier:empty; 103, binary_operator:N+1; 104, keyword_argument; 105, comparison_operator:k < K; 106, comparison_operator:indices[k] == n; 107, expression_statement; 108, expression_statement; 109, comment:# "add zero"; 110, comment:# calculate f(k; N,K,n+1) from f(k; N,K,n); 111, block; 112, identifier:n; 113, integer:1; 114, subscript; 115, call; 116, subscript; 117, binary_operator:k / (K*(n/float(N))); 118, identifier:np; 119, identifier:integer; 120, identifier:np; 121, identifier:ndarray; 122, identifier:indices; 123, identifier:dtype; 124, identifier:np; 125, identifier:uint16; 126, identifier:N; 127, integer:1; 128, identifier:dtype; 129, attribute; 130, identifier:N; 131, integer:1; 132, identifier:dtype; 133, attribute; 134, identifier:k; 135, identifier:K; 136, subscript; 137, identifier:n; 138, augmented_assignment; 139, augmented_assignment; 140, expression_statement; 141, identifier:pvals; 142, identifier:n; 143, identifier:get_hgp; 144, argument_list; 145, identifier:folds; 146, identifier:n; 147, identifier:k; 148, parenthesized_expression; 149, identifier:np; 150, identifier:float64; 151, identifier:np; 152, identifier:float64; 153, identifier:indices; 154, identifier:k; 155, identifier:p; 156, parenthesized_expression; 157, identifier:k; 158, integer:1; 159, augmented_assignment; 160, identifier:p; 161, identifier:k; 162, identifier:N; 163, identifier:K; 164, identifier:n; 165, binary_operator:K*(n/float(N)); 166, binary_operator:float((n+1) * (K-k)) / \
float((N-n) * (k+1)); 167, identifier:p; 168, parenthesized_expression; 169, identifier:K; 170, parenthesized_expression; 171, call; 172, line_continuation:\; 173, call; 174, binary_operator:float((n+1) * (N-K-n+k)) /
float((N-n) * (n-k+1)); 175, binary_operator:n/float(N); 176, identifier:float; 177, argument_list; 178, identifier:float; 179, argument_list; 180, call; 181, call; 182, identifier:n; 183, call; 184, binary_operator:(n+1) * (K-k); 185, binary_operator:(N-n) * (k+1); 186, identifier:float; 187, argument_list; 188, identifier:float; 189, argument_list; 190, identifier:float; 191, argument_list; 192, parenthesized_expression; 193, parenthesized_expression; 194, parenthesized_expression; 195, parenthesized_expression; 196, binary_operator:(n+1) * (N-K-n+k); 197, binary_operator:(N-n) * (n-k+1); 198, identifier:N; 199, binary_operator:n+1; 200, binary_operator:K-k; 201, binary_operator:N-n; 202, binary_operator:k+1; 203, parenthesized_expression; 204, parenthesized_expression; 205, parenthesized_expression; 206, parenthesized_expression; 207, identifier:n; 208, integer:1; 209, identifier:K; 210, identifier:k; 211, identifier:N; 212, identifier:n; 213, identifier:k; 214, integer:1; 215, binary_operator:n+1; 216, binary_operator:N-K-n+k; 217, binary_operator:N-n; 218, binary_operator:n-k+1; 219, identifier:n; 220, integer:1; 221, binary_operator:N-K-n; 222, identifier:k; 223, identifier:N; 224, identifier:n; 225, binary_operator:n-k; 226, integer:1; 227, binary_operator:N-K; 228, identifier:n; 229, identifier:n; 230, identifier:k; 231, identifier:N; 232, identifier:K | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 7, 20; 8, 21; 9, 22; 10, 23; 11, 24; 12, 25; 13, 26; 14, 27; 15, 28; 16, 29; 17, 30; 18, 31; 18, 32; 19, 33; 21, 34; 21, 35; 22, 36; 22, 37; 22, 38; 23, 39; 23, 40; 24, 41; 24, 42; 25, 43; 25, 44; 26, 45; 26, 46; 27, 47; 27, 48; 28, 49; 28, 50; 29, 51; 29, 52; 30, 53; 30, 54; 31, 55; 31, 56; 32, 57; 32, 58; 32, 59; 32, 60; 32, 61; 32, 62; 33, 63; 33, 64; 35, 65; 35, 66; 36, 67; 36, 68; 38, 69; 38, 70; 40, 71; 40, 72; 42, 73; 42, 74; 44, 75; 44, 76; 45, 77; 45, 78; 47, 79; 47, 80; 57, 81; 57, 82; 57, 83; 57, 84; 57, 85; 58, 86; 60, 87; 62, 88; 66, 89; 66, 90; 68, 91; 68, 92; 69, 93; 69, 94; 70, 95; 70, 96; 73, 97; 73, 98; 74, 99; 74, 100; 75, 101; 75, 102; 76, 103; 76, 104; 81, 105; 81, 106; 84, 107; 84, 108; 85, 109; 85, 110; 85, 111; 86, 112; 86, 113; 87, 114; 87, 115; 88, 116; 88, 117; 90, 118; 90, 119; 92, 120; 92, 121; 95, 122; 95, 123; 96, 124; 96, 125; 99, 126; 99, 127; 100, 128; 100, 129; 103, 130; 103, 131; 104, 132; 104, 133; 105, 134; 105, 135; 106, 136; 106, 137; 107, 138; 108, 139; 111, 140; 114, 141; 114, 142; 115, 143; 115, 144; 116, 145; 116, 146; 117, 147; 117, 148; 129, 149; 129, 150; 133, 151; 133, 152; 136, 153; 136, 154; 138, 155; 138, 156; 139, 157; 139, 158; 140, 159; 144, 160; 144, 161; 144, 162; 144, 163; 144, 164; 148, 165; 156, 166; 159, 167; 159, 168; 165, 169; 165, 170; 166, 171; 166, 172; 166, 173; 168, 174; 170, 175; 171, 176; 171, 177; 173, 178; 173, 179; 174, 180; 174, 181; 175, 182; 175, 183; 177, 184; 179, 185; 180, 186; 180, 187; 181, 188; 181, 189; 183, 190; 183, 191; 184, 192; 184, 193; 185, 194; 185, 195; 187, 196; 189, 197; 191, 198; 192, 199; 193, 200; 194, 201; 195, 202; 196, 203; 196, 204; 197, 205; 197, 206; 199, 207; 199, 208; 200, 209; 200, 210; 201, 211; 201, 212; 202, 213; 202, 214; 203, 215; 204, 216; 205, 217; 206, 218; 215, 219; 215, 220; 216, 221; 216, 222; 217, 223; 217, 224; 218, 225; 218, 226; 221, 227; 221, 228; 225, 229; 225, 230; 227, 231; 227, 232 | def get_hypergeometric_stats(N, indices):
"""Calculates hypergeom. p-values and fold enrichments for all cutoffs.
Parameters
----------
N: int
The length of the list
indices: `numpy.ndarray` with ``dtype=np.uint16``
The (sorted) indices of the "1's" in the list.
"""
assert isinstance(N, (int, np.integer))
assert isinstance(indices, np.ndarray) and \
np.issubdtype(indices.dtype, np.uint16)
K = indices.size
pvals = np.empty(N+1, dtype=np.float64)
folds = np.empty(N+1, dtype=np.float64)
pvals[0] = 1.0
folds[0] = 1.0
n = 0
k = 0
p = 1.0
while n < N:
if k < K and indices[k] == n:
# "add one"
# calculate f(k+1; N,K,n+1) from f(k; N,K,n)
p *= (float((n+1) * (K-k)) / \
float((N-n) * (k+1)))
k += 1
else:
# "add zero"
# calculate f(k; N,K,n+1) from f(k; N,K,n)
p *= (float((n+1) * (N-K-n+k)) /
float((N-n) * (n-k+1)))
n += 1
# calculate hypergeometric p-value
pvals[n] = get_hgp(p, k, N, K, n)
# calculate fold enrichment
folds[n] = k / (K*(n/float(N)))
return pvals, folds |
0, module; 1, function_definition; 2, function_name:sort_dictionary_list; 3, parameters; 4, block; 5, identifier:dict_list; 6, identifier:sort_key; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, return_statement; 11, comment:"""
sorts a list of dictionaries based on the value of the sort_key
dict_list - a list of dictionaries
sort_key - a string that identifies the key to sort the dictionaries with.
Test sorting a list of dictionaries:
>>> sort_dictionary_list([{'b' : 1, 'value' : 2}, {'c' : 2, 'value' : 3}, {'a' : 3, 'value' : 1}], 'value')
[{'a': 3, 'value': 1}, {'b': 1, 'value': 2}, {'c': 2, 'value': 3}]
"""; 12, boolean_operator; 13, block; 14, call; 15, identifier:dict_list; 16, not_operator; 17, comparison_operator:len(dict_list) == 0; 18, return_statement; 19, attribute; 20, argument_list; 21, identifier:dict_list; 22, call; 23, integer:0; 24, identifier:dict_list; 25, identifier:dict_list; 26, identifier:sort; 27, keyword_argument; 28, identifier:len; 29, argument_list; 30, identifier:key; 31, call; 32, identifier:dict_list; 33, identifier:itemgetter; 34, argument_list; 35, identifier:sort_key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 8, 13; 9, 14; 10, 15; 12, 16; 12, 17; 13, 18; 14, 19; 14, 20; 16, 21; 17, 22; 17, 23; 18, 24; 19, 25; 19, 26; 20, 27; 22, 28; 22, 29; 27, 30; 27, 31; 29, 32; 31, 33; 31, 34; 34, 35 | def sort_dictionary_list(dict_list, sort_key):
"""
sorts a list of dictionaries based on the value of the sort_key
dict_list - a list of dictionaries
sort_key - a string that identifies the key to sort the dictionaries with.
Test sorting a list of dictionaries:
>>> sort_dictionary_list([{'b' : 1, 'value' : 2}, {'c' : 2, 'value' : 3}, {'a' : 3, 'value' : 1}], 'value')
[{'a': 3, 'value': 1}, {'b': 1, 'value': 2}, {'c': 2, 'value': 3}]
"""
if not dict_list or len(dict_list) == 0:
return dict_list
dict_list.sort(key=itemgetter(sort_key))
return dict_list |
0, module; 1, function_definition; 2, function_name:render; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:""" Render the menu into a sorted by order multi dict """; 12, assignment; 13, assignment; 14, pattern_list; 15, call; 16, block; 17, call; 18, identifier:menu_list; 19, list; 20, identifier:menu_index; 21, integer:0; 22, identifier:_; 23, identifier:menu; 24, attribute; 25, argument_list; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, if_statement; 30, for_statement; 31, expression_statement; 32, if_statement; 33, expression_statement; 34, attribute; 35, argument_list; 36, call; 37, identifier:items; 38, assignment; 39, assignment; 40, assignment; 41, comparison_operator:"visible" in menu["kwargs"]; 42, block; 43, identifier:s; 44, subscript; 45, block; 46, assignment; 47, subscript; 48, block; 49, else_clause; 50, augmented_assignment; 51, identifier:self; 52, identifier:_sort; 53, identifier:menu_list; 54, attribute; 55, argument_list; 56, identifier:subnav; 57, list; 58, subscript; 59, call; 60, subscript; 61, False; 62, string:"visible"; 63, subscript; 64, expression_statement; 65, identifier:menu; 66, string:"subnav"; 67, if_statement; 68, if_statement; 69, expression_statement; 70, expression_statement; 71, expression_statement; 72, expression_statement; 73, identifier:_kwargs; 74, subscript; 75, identifier:menu; 76, string:"title"; 77, expression_statement; 78, expression_statement; 79, block; 80, identifier:menu_index; 81, integer:1; 82, identifier:copy; 83, identifier:deepcopy; 84, attribute; 85, subscript; 86, string:"_id"; 87, identifier:str; 88, argument_list; 89, subscript; 90, string:"active"; 91, identifier:menu; 92, string:"kwargs"; 93, assignment; 94, subscript; 95, block; 96, comparison_operator:s["endpoint"] == request.endpoint; 97, block; 98, assignment; 99, augmented_assignment; 100, assignment; 101, call; 102, identifier:menu; 103, string:"kwargs"; 104, call; 105, call; 106, expression_statement; 107, identifier:self; 108, identifier:MENU; 109, identifier:menu; 110, string:"kwargs"; 111, identifier:menu_index; 112, identifier:menu; 113, string:"kwargs"; 114, subscript; 115, call; 116, identifier:s; 117, string:"title"; 118, expression_statement; 119, subscript; 120, attribute; 121, expression_statement; 122, expression_statement; 123, subscript; 124, call; 125, identifier:menu_index; 126, integer:1; 127, subscript; 128, call; 129, attribute; 130, argument_list; 131, attribute; 132, argument_list; 133, attribute; 134, argument_list; 135, augmented_assignment; 136, subscript; 137, string:"visible"; 138, attribute; 139, argument_list; 140, assignment; 141, identifier:s; 142, string:"endpoint"; 143, identifier:request; 144, identifier:endpoint; 145, assignment; 146, assignment; 147, identifier:s; 148, string:"visible"; 149, attribute; 150, argument_list; 151, identifier:s; 152, string:"_id"; 153, identifier:str; 154, argument_list; 155, identifier:subnav; 156, identifier:append; 157, identifier:s; 158, identifier:_kwargs; 159, identifier:update; 160, dictionary; 161, identifier:menu_list; 162, identifier:append; 163, identifier:_kwargs; 164, identifier:menu_list; 165, identifier:subnav; 166, identifier:menu; 167, string:"kwargs"; 168, identifier:self; 169, identifier:_test_visibility; 170, subscript; 171, subscript; 172, call; 173, subscript; 174, True; 175, subscript; 176, True; 177, identifier:self; 178, identifier:_test_visibility; 179, subscript; 180, identifier:menu_index; 181, pair; 182, pair; 183, pair; 184, subscript; 185, string:"visible"; 186, identifier:s; 187, string:"title"; 188, attribute; 189, argument_list; 190, identifier:s; 191, string:"active"; 192, subscript; 193, string:"active"; 194, identifier:s; 195, string:"visible"; 196, string:"subnav"; 197, call; 198, string:"order"; 199, subscript; 200, string:"title"; 201, call; 202, identifier:menu; 203, string:"kwargs"; 204, identifier:self; 205, identifier:_get_title; 206, subscript; 207, identifier:menu; 208, string:"kwargs"; 209, attribute; 210, argument_list; 211, identifier:menu; 212, string:"order"; 213, attribute; 214, argument_list; 215, identifier:s; 216, string:"title"; 217, identifier:self; 218, identifier:_sort; 219, identifier:subnav; 220, identifier:self; 221, identifier:_get_title; 222, subscript; 223, identifier:menu; 224, string:"title" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 12, 18; 12, 19; 13, 20; 13, 21; 14, 22; 14, 23; 15, 24; 15, 25; 16, 26; 16, 27; 16, 28; 16, 29; 16, 30; 16, 31; 16, 32; 16, 33; 17, 34; 17, 35; 24, 36; 24, 37; 26, 38; 27, 39; 28, 40; 29, 41; 29, 42; 30, 43; 30, 44; 30, 45; 31, 46; 32, 47; 32, 48; 32, 49; 33, 50; 34, 51; 34, 52; 35, 53; 36, 54; 36, 55; 38, 56; 38, 57; 39, 58; 39, 59; 40, 60; 40, 61; 41, 62; 41, 63; 42, 64; 44, 65; 44, 66; 45, 67; 45, 68; 45, 69; 45, 70; 45, 71; 45, 72; 46, 73; 46, 74; 47, 75; 47, 76; 48, 77; 48, 78; 49, 79; 50, 80; 50, 81; 54, 82; 54, 83; 55, 84; 58, 85; 58, 86; 59, 87; 59, 88; 60, 89; 60, 90; 63, 91; 63, 92; 64, 93; 67, 94; 67, 95; 68, 96; 68, 97; 69, 98; 70, 99; 71, 100; 72, 101; 74, 102; 74, 103; 77, 104; 78, 105; 79, 106; 84, 107; 84, 108; 85, 109; 85, 110; 88, 111; 89, 112; 89, 113; 93, 114; 93, 115; 94, 116; 94, 117; 95, 118; 96, 119; 96, 120; 97, 121; 97, 122; 98, 123; 98, 124; 99, 125; 99, 126; 100, 127; 100, 128; 101, 129; 101, 130; 104, 131; 104, 132; 105, 133; 105, 134; 106, 135; 114, 136; 114, 137; 115, 138; 115, 139; 118, 140; 119, 141; 119, 142; 120, 143; 120, 144; 121, 145; 122, 146; 123, 147; 123, 148; 124, 149; 124, 150; 127, 151; 127, 152; 128, 153; 128, 154; 129, 155; 129, 156; 130, 157; 131, 158; 131, 159; 132, 160; 133, 161; 133, 162; 134, 163; 135, 164; 135, 165; 136, 166; 136, 167; 138, 168; 138, 169; 139, 170; 140, 171; 140, 172; 145, 173; 145, 174; 146, 175; 146, 176; 149, 177; 149, 178; 150, 179; 154, 180; 160, 181; 160, 182; 160, 183; 170, 184; 170, 185; 171, 186; 171, 187; 172, 188; 172, 189; 173, 190; 173, 191; 175, 192; 175, 193; 179, 194; 179, 195; 181, 196; 181, 197; 182, 198; 182, 199; 183, 200; 183, 201; 184, 202; 184, 203; 188, 204; 188, 205; 189, 206; 192, 207; 192, 208; 197, 209; 197, 210; 199, 211; 199, 212; 201, 213; 201, 214; 206, 215; 206, 216; 209, 217; 209, 218; 210, 219; 213, 220; 213, 221; 214, 222; 222, 223; 222, 224 | def render(self):
""" Render the menu into a sorted by order multi dict """
menu_list = []
menu_index = 0
for _, menu in copy.deepcopy(self.MENU).items():
subnav = []
menu["kwargs"]["_id"] = str(menu_index)
menu["kwargs"]["active"] = False
if "visible" in menu["kwargs"]:
menu["kwargs"]["visible"] = self._test_visibility(menu["kwargs"]["visible"])
for s in menu["subnav"]:
if s["title"]:
s["title"] = self._get_title(s["title"])
if s["endpoint"] == request.endpoint:
s["active"] = True
menu["kwargs"]["active"] = True
s["visible"] = self._test_visibility(s["visible"])
menu_index += 1
s["_id"] = str(menu_index)
subnav.append(s)
_kwargs = menu["kwargs"]
if menu["title"]:
_kwargs.update({
"subnav": self._sort(subnav),
"order": menu["order"],
"title": self._get_title(menu["title"])
})
menu_list.append(_kwargs)
else:
menu_list += subnav
menu_index += 1
return self._sort(menu_list) |
0, module; 1, function_definition; 2, function_name:vote_mean; 3, parameters; 4, block; 5, identifier:candidates; 6, identifier:votes; 7, identifier:n_winners; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, for_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, for_statement; 17, return_statement; 18, comment:"""Perform mean voting based on votes.
Mean voting computes the mean preference for each of the artifact
candidates from the votes and sorts the candidates in the mean preference
order.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""; 19, assignment; 20, identifier:vote; 21, identifier:votes; 22, block; 23, identifier:s; 24, identifier:sums; 25, block; 26, assignment; 27, call; 28, assignment; 29, assignment; 30, identifier:e; 31, identifier:best; 32, block; 33, identifier:d; 34, identifier:sums; 35, dictionary_comprehension; 36, for_statement; 37, expression_statement; 38, identifier:ordering; 39, call; 40, attribute; 41, argument_list; 42, identifier:best; 43, subscript; 44, identifier:d; 45, list; 46, for_statement; 47, pair; 48, for_in_clause; 49, identifier:v; 50, identifier:vote; 51, block; 52, assignment; 53, identifier:list; 54, argument_list; 55, identifier:ordering; 56, identifier:sort; 57, keyword_argument; 58, keyword_argument; 59, identifier:ordering; 60, slice; 61, identifier:c; 62, identifier:candidates; 63, block; 64, call; 65, list; 66, identifier:candidate; 67, identifier:candidates; 68, expression_statement; 69, subscript; 70, binary_operator:sum(sums[s]) / len(sums[s]); 71, call; 72, identifier:key; 73, call; 74, identifier:reverse; 75, True; 76, call; 77, if_statement; 78, identifier:str; 79, argument_list; 80, call; 81, identifier:sums; 82, identifier:s; 83, call; 84, call; 85, attribute; 86, argument_list; 87, attribute; 88, argument_list; 89, identifier:min; 90, argument_list; 91, comparison_operator:str(c) == e[0]; 92, block; 93, identifier:candidate; 94, attribute; 95, argument_list; 96, identifier:sum; 97, argument_list; 98, identifier:len; 99, argument_list; 100, identifier:sums; 101, identifier:items; 102, identifier:operator; 103, identifier:itemgetter; 104, integer:1; 105, identifier:n_winners; 106, call; 107, call; 108, subscript; 109, expression_statement; 110, subscript; 111, identifier:append; 112, subscript; 113, subscript; 114, subscript; 115, identifier:len; 116, argument_list; 117, identifier:str; 118, argument_list; 119, identifier:e; 120, integer:0; 121, call; 122, identifier:sums; 123, call; 124, identifier:v; 125, integer:1; 126, identifier:sums; 127, identifier:s; 128, identifier:sums; 129, identifier:s; 130, identifier:ordering; 131, identifier:c; 132, attribute; 133, argument_list; 134, identifier:str; 135, argument_list; 136, identifier:d; 137, identifier:append; 138, tuple; 139, subscript; 140, identifier:c; 141, subscript; 142, identifier:v; 143, integer:0; 144, identifier:e; 145, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 8, 18; 9, 19; 10, 20; 10, 21; 10, 22; 11, 23; 11, 24; 11, 25; 12, 26; 13, 27; 14, 28; 15, 29; 16, 30; 16, 31; 16, 32; 17, 33; 19, 34; 19, 35; 22, 36; 25, 37; 26, 38; 26, 39; 27, 40; 27, 41; 28, 42; 28, 43; 29, 44; 29, 45; 32, 46; 35, 47; 35, 48; 36, 49; 36, 50; 36, 51; 37, 52; 39, 53; 39, 54; 40, 55; 40, 56; 41, 57; 41, 58; 43, 59; 43, 60; 46, 61; 46, 62; 46, 63; 47, 64; 47, 65; 48, 66; 48, 67; 51, 68; 52, 69; 52, 70; 54, 71; 57, 72; 57, 73; 58, 74; 58, 75; 60, 76; 63, 77; 64, 78; 64, 79; 68, 80; 69, 81; 69, 82; 70, 83; 70, 84; 71, 85; 71, 86; 73, 87; 73, 88; 76, 89; 76, 90; 77, 91; 77, 92; 79, 93; 80, 94; 80, 95; 83, 96; 83, 97; 84, 98; 84, 99; 85, 100; 85, 101; 87, 102; 87, 103; 88, 104; 90, 105; 90, 106; 91, 107; 91, 108; 92, 109; 94, 110; 94, 111; 95, 112; 97, 113; 99, 114; 106, 115; 106, 116; 107, 117; 107, 118; 108, 119; 108, 120; 109, 121; 110, 122; 110, 123; 112, 124; 112, 125; 113, 126; 113, 127; 114, 128; 114, 129; 116, 130; 118, 131; 121, 132; 121, 133; 123, 134; 123, 135; 132, 136; 132, 137; 133, 138; 135, 139; 138, 140; 138, 141; 139, 142; 139, 143; 141, 144; 141, 145 | def vote_mean(candidates, votes, n_winners):
"""Perform mean voting based on votes.
Mean voting computes the mean preference for each of the artifact
candidates from the votes and sorts the candidates in the mean preference
order.
Ties are resolved randomly.
:param candidates: All candidates in the vote
:param votes: Votes from the agents
:param int n_winners: The number of vote winners
"""
sums = {str(candidate): [] for candidate in candidates}
for vote in votes:
for v in vote:
sums[str(v[0])].append(v[1])
for s in sums:
sums[s] = sum(sums[s]) / len(sums[s])
ordering = list(sums.items())
ordering.sort(key=operator.itemgetter(1), reverse=True)
best = ordering[:min(n_winners, len(ordering))]
d = []
for e in best:
for c in candidates:
if str(c) == e[0]:
d.append((c, e[1]))
return d |
0, module; 1, function_definition; 2, function_name:vote; 3, parameters; 4, block; 5, identifier:self; 6, identifier:candidates; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, comment:"""Rank artifact candidates.
The voting is needed for the agents living in societies using
social decision making. The function should return a sorted list
of (candidate, evaluation)-tuples. Depending on the social choice
function used, the evaluation might be omitted from the actual decision
making, or only a number of (the highest ranking) candidates may be
used.
This basic implementation ranks candidates based on
:meth:`~creamas.core.agent.CreativeAgent.evaluate`.
:param candidates:
list of :py:class:`~creamas.core.artifact.Artifact` objects to be
ranked
:returns:
Ordered list of (candidate, evaluation)-tuples
"""; 12, assignment; 13, call; 14, identifier:ranks; 15, identifier:ranks; 16, list_comprehension; 17, attribute; 18, argument_list; 19, tuple; 20, for_in_clause; 21, identifier:ranks; 22, identifier:sort; 23, keyword_argument; 24, keyword_argument; 25, identifier:c; 26, subscript; 27, identifier:c; 28, identifier:candidates; 29, identifier:key; 30, call; 31, identifier:reverse; 32, True; 33, call; 34, integer:0; 35, attribute; 36, argument_list; 37, attribute; 38, argument_list; 39, identifier:operator; 40, identifier:itemgetter; 41, integer:1; 42, identifier:self; 43, identifier:evaluate; 44, identifier:c | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 10, 14; 12, 15; 12, 16; 13, 17; 13, 18; 16, 19; 16, 20; 17, 21; 17, 22; 18, 23; 18, 24; 19, 25; 19, 26; 20, 27; 20, 28; 23, 29; 23, 30; 24, 31; 24, 32; 26, 33; 26, 34; 30, 35; 30, 36; 33, 37; 33, 38; 35, 39; 35, 40; 36, 41; 37, 42; 37, 43; 38, 44 | def vote(self, candidates):
"""Rank artifact candidates.
The voting is needed for the agents living in societies using
social decision making. The function should return a sorted list
of (candidate, evaluation)-tuples. Depending on the social choice
function used, the evaluation might be omitted from the actual decision
making, or only a number of (the highest ranking) candidates may be
used.
This basic implementation ranks candidates based on
:meth:`~creamas.core.agent.CreativeAgent.evaluate`.
:param candidates:
list of :py:class:`~creamas.core.artifact.Artifact` objects to be
ranked
:returns:
Ordered list of (candidate, evaluation)-tuples
"""
ranks = [(c, self.evaluate(c)[0]) for c in candidates]
ranks.sort(key=operator.itemgetter(1), reverse=True)
return ranks |
0, module; 1, function_definition; 2, function_name:gather_votes; 3, parameters; 4, block; 5, identifier:self; 6, identifier:candidates; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifact, preference)``
-tuples sorted in a preference order of a single agent.
"""; 12, assignment; 13, identifier:a; 14, call; 15, block; 16, identifier:votes; 17, identifier:votes; 18, list; 19, attribute; 20, argument_list; 21, expression_statement; 22, expression_statement; 23, identifier:self; 24, identifier:get_agents; 25, keyword_argument; 26, assignment; 27, call; 28, identifier:addr; 29, False; 30, identifier:vote; 31, call; 32, attribute; 33, argument_list; 34, attribute; 35, argument_list; 36, identifier:votes; 37, identifier:append; 38, identifier:vote; 39, identifier:a; 40, identifier:vote; 41, identifier:candidates | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 14, 19; 14, 20; 15, 21; 15, 22; 19, 23; 19, 24; 20, 25; 21, 26; 22, 27; 25, 28; 25, 29; 26, 30; 26, 31; 27, 32; 27, 33; 31, 34; 31, 35; 32, 36; 32, 37; 33, 38; 34, 39; 34, 40; 35, 41 | def gather_votes(self, candidates):
"""Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifact, preference)``
-tuples sorted in a preference order of a single agent.
"""
votes = []
for a in self.get_agents(addr=False):
vote = a.vote(candidates)
votes.append(vote)
return votes |
0, module; 1, function_definition; 2, function_name:sort_by; 3, parameters; 4, block; 5, identifier:self; 6, identifier:fieldName; 7, default_parameter; 8, expression_statement; 9, return_statement; 10, identifier:reverse; 11, False; 12, string; 13, call; 14, string_content:sort_by - Return a copy of this collection, sorted by the given fieldName.
The fieldName is accessed the same way as other filtering, so it supports custom properties, etc.
@param fieldName <str> - The name of the field on which to sort by
@param reverse <bool> Default False - If True, list will be in reverse order.
@return <QueryableList> - A QueryableList of the same type with the elements sorted based on arguments.; 15, attribute; 16, argument_list; 17, identifier:self; 18, identifier:__class__; 19, call; 20, identifier:sorted; 21, argument_list; 22, identifier:self; 23, keyword_argument; 24, keyword_argument; 25, identifier:key; 26, lambda; 27, identifier:reverse; 28, identifier:reverse; 29, lambda_parameters; 30, call; 31, identifier:item; 32, attribute; 33, argument_list; 34, identifier:self; 35, identifier:_get_item_value; 36, identifier:item; 37, identifier:fieldName | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 7, 10; 7, 11; 8, 12; 9, 13; 12, 14; 13, 15; 13, 16; 15, 17; 15, 18; 16, 19; 19, 20; 19, 21; 21, 22; 21, 23; 21, 24; 23, 25; 23, 26; 24, 27; 24, 28; 26, 29; 26, 30; 29, 31; 30, 32; 30, 33; 32, 34; 32, 35; 33, 36; 33, 37 | def sort_by(self, fieldName, reverse=False):
'''
sort_by - Return a copy of this collection, sorted by the given fieldName.
The fieldName is accessed the same way as other filtering, so it supports custom properties, etc.
@param fieldName <str> - The name of the field on which to sort by
@param reverse <bool> Default False - If True, list will be in reverse order.
@return <QueryableList> - A QueryableList of the same type with the elements sorted based on arguments.
'''
return self.__class__(
sorted(self, key = lambda item : self._get_item_value(item, fieldName), reverse=reverse)
) |
0, module; 1, function_definition; 2, function_name:sorted_items; 3, parameters; 4, block; 5, identifier:d; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, comment:# wrap the key func so it operates on the first element of each item; 10, function_definition; 11, return_statement; 12, identifier:key; 13, identifier:__identity; 14, identifier:reverse; 15, False; 16, comment:"""
Return the items of the dictionary sorted by the keys
>>> sample = dict(foo=20, bar=42, baz=10)
>>> tuple(sorted_items(sample))
(('bar', 42), ('baz', 10), ('foo', 20))
>>> reverse_string = lambda s: ''.join(reversed(s))
>>> tuple(sorted_items(sample, key=reverse_string))
(('foo', 20), ('bar', 42), ('baz', 10))
>>> tuple(sorted_items(sample, reverse=True))
(('foo', 20), ('baz', 10), ('bar', 42))
"""; 17, function_name:pairkey_key; 18, parameters; 19, block; 20, call; 21, identifier:item; 22, return_statement; 23, identifier:sorted; 24, argument_list; 25, call; 26, call; 27, keyword_argument; 28, keyword_argument; 29, identifier:key; 30, argument_list; 31, attribute; 32, argument_list; 33, identifier:key; 34, identifier:pairkey_key; 35, identifier:reverse; 36, identifier:reverse; 37, subscript; 38, identifier:d; 39, identifier:items; 40, identifier:item; 41, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 7, 15; 8, 16; 10, 17; 10, 18; 10, 19; 11, 20; 18, 21; 19, 22; 20, 23; 20, 24; 22, 25; 24, 26; 24, 27; 24, 28; 25, 29; 25, 30; 26, 31; 26, 32; 27, 33; 27, 34; 28, 35; 28, 36; 30, 37; 31, 38; 31, 39; 37, 40; 37, 41 | def sorted_items(d, key=__identity, reverse=False):
"""
Return the items of the dictionary sorted by the keys
>>> sample = dict(foo=20, bar=42, baz=10)
>>> tuple(sorted_items(sample))
(('bar', 42), ('baz', 10), ('foo', 20))
>>> reverse_string = lambda s: ''.join(reversed(s))
>>> tuple(sorted_items(sample, key=reverse_string))
(('foo', 20), ('bar', 42), ('baz', 10))
>>> tuple(sorted_items(sample, reverse=True))
(('foo', 20), ('baz', 10), ('bar', 42))
"""
# wrap the key func so it operates on the first element of each item
def pairkey_key(item):
return key(item[0])
return sorted(d.items(), key=pairkey_key, reverse=reverse) |
0, module; 1, function_definition; 2, function_name:merge_range_pairs; 3, parameters; 4, block; 5, identifier:prs; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, while_statement; 13, return_statement; 14, string; 15, assignment; 16, assignment; 17, assignment; 18, assignment; 19, assignment; 20, comparison_operator:x < len(sprs); 21, block; 22, identifier:new_prs; 23, string_content:Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.; 24, identifier:new_prs; 25, list; 26, identifier:sprs; 27, list_comprehension; 28, identifier:sprs; 29, call; 30, identifier:merged; 31, False; 32, identifier:x; 33, integer:0; 34, identifier:x; 35, call; 36, expression_statement; 37, expression_statement; 38, for_statement; 39, if_statement; 40, expression_statement; 41, call; 42, for_in_clause; 43, identifier:sorted; 44, argument_list; 45, identifier:len; 46, argument_list; 47, assignment; 48, assignment; 49, identifier:y; 50, call; 51, block; 52, comparison_operator:new_pair not in new_prs; 53, block; 54, assignment; 55, identifier:sorted; 56, argument_list; 57, identifier:p; 58, identifier:prs; 59, identifier:sprs; 60, identifier:sprs; 61, identifier:newx; 62, binary_operator:x + 1; 63, identifier:new_pair; 64, call; 65, identifier:range; 66, argument_list; 67, if_statement; 68, identifier:new_pair; 69, identifier:new_prs; 70, expression_statement; 71, identifier:x; 72, identifier:newx; 73, identifier:p; 74, identifier:x; 75, integer:1; 76, identifier:list; 77, argument_list; 78, binary_operator:x + 1; 79, call; 80, comparison_operator:new_pair[0] <= sprs[y][0] - 1 <= new_pair[1]; 81, block; 82, call; 83, subscript; 84, identifier:x; 85, integer:1; 86, identifier:len; 87, argument_list; 88, subscript; 89, binary_operator:sprs[y][0] - 1; 90, subscript; 91, expression_statement; 92, expression_statement; 93, expression_statement; 94, attribute; 95, argument_list; 96, identifier:sprs; 97, identifier:x; 98, identifier:sprs; 99, identifier:new_pair; 100, integer:0; 101, subscript; 102, integer:1; 103, identifier:new_pair; 104, integer:1; 105, assignment; 106, assignment; 107, assignment; 108, identifier:new_prs; 109, identifier:append; 110, identifier:new_pair; 111, subscript; 112, integer:0; 113, subscript; 114, call; 115, subscript; 116, call; 117, identifier:newx; 118, binary_operator:y + 1; 119, identifier:sprs; 120, identifier:y; 121, identifier:new_pair; 122, integer:0; 123, identifier:min; 124, argument_list; 125, identifier:new_pair; 126, integer:1; 127, identifier:max; 128, argument_list; 129, identifier:y; 130, integer:1; 131, subscript; 132, subscript; 133, subscript; 134, subscript; 135, identifier:new_pair; 136, integer:0; 137, subscript; 138, integer:0; 139, identifier:new_pair; 140, integer:1; 141, subscript; 142, integer:1; 143, identifier:sprs; 144, identifier:y; 145, identifier:sprs; 146, identifier:y | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 10, 18; 11, 19; 12, 20; 12, 21; 13, 22; 14, 23; 15, 24; 15, 25; 16, 26; 16, 27; 17, 28; 17, 29; 18, 30; 18, 31; 19, 32; 19, 33; 20, 34; 20, 35; 21, 36; 21, 37; 21, 38; 21, 39; 21, 40; 27, 41; 27, 42; 29, 43; 29, 44; 35, 45; 35, 46; 36, 47; 37, 48; 38, 49; 38, 50; 38, 51; 39, 52; 39, 53; 40, 54; 41, 55; 41, 56; 42, 57; 42, 58; 44, 59; 46, 60; 47, 61; 47, 62; 48, 63; 48, 64; 50, 65; 50, 66; 51, 67; 52, 68; 52, 69; 53, 70; 54, 71; 54, 72; 56, 73; 62, 74; 62, 75; 64, 76; 64, 77; 66, 78; 66, 79; 67, 80; 67, 81; 70, 82; 77, 83; 78, 84; 78, 85; 79, 86; 79, 87; 80, 88; 80, 89; 80, 90; 81, 91; 81, 92; 81, 93; 82, 94; 82, 95; 83, 96; 83, 97; 87, 98; 88, 99; 88, 100; 89, 101; 89, 102; 90, 103; 90, 104; 91, 105; 92, 106; 93, 107; 94, 108; 94, 109; 95, 110; 101, 111; 101, 112; 105, 113; 105, 114; 106, 115; 106, 116; 107, 117; 107, 118; 111, 119; 111, 120; 113, 121; 113, 122; 114, 123; 114, 124; 115, 125; 115, 126; 116, 127; 116, 128; 118, 129; 118, 130; 124, 131; 124, 132; 128, 133; 128, 134; 131, 135; 131, 136; 132, 137; 132, 138; 133, 139; 133, 140; 134, 141; 134, 142; 137, 143; 137, 144; 141, 145; 141, 146 | def merge_range_pairs(prs):
'''Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.'''
new_prs = []
sprs = [sorted(p) for p in prs]
sprs = sorted(sprs)
merged = False
x = 0
while x < len(sprs):
newx = x + 1
new_pair = list(sprs[x])
for y in range(x + 1, len(sprs)):
if new_pair[0] <= sprs[y][0] - 1 <= new_pair[1]:
new_pair[0] = min(new_pair[0], sprs[y][0])
new_pair[1] = max(new_pair[1], sprs[y][1])
newx = y + 1
if new_pair not in new_prs:
new_prs.append(new_pair)
x = newx
return new_prs |
0, module; 1, function_definition; 2, function_name:fixed_point; 3, parameters; 4, block; 5, identifier:is_zero; 6, identifier:plus; 7, identifier:minus; 8, identifier:f; 9, identifier:x; 10, expression_statement; 11, decorated_definition; 12, return_statement; 13, comment:"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs + ys,
... minus=lambda xs, ys: [x for x in xs if x not in ys],
... f=lambda xs: [x + 1 for x in xs if x < 10],
... x=[0, 5, 8]
... ))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Args:
is_zero: function returning True if the given value is zero
plus: function taking two values and returning their addition
minus: function taking two values and returning ther difference
f: function computing the expected value
x: initial value
Returns:
The least fixed point.
"""; 14, decorator; 15, function_definition; 16, call; 17, identifier:memo_Y; 18, function_name:_fixed_point; 19, parameters; 20, block; 21, identifier:_fixed_point; 22, argument_list; 23, identifier:fixed_point_fun; 24, function_definition; 25, return_statement; 26, identifier:x; 27, call; 28, function_name:__fixed_point; 29, parameters; 30, block; 31, identifier:__fixed_point; 32, identifier:f; 33, argument_list; 34, identifier:collected; 35, identifier:new; 36, expression_statement; 37, if_statement; 38, return_statement; 39, identifier:x; 40, assignment; 41, call; 42, block; 43, call; 44, identifier:diff; 45, call; 46, identifier:is_zero; 47, argument_list; 48, return_statement; 49, identifier:fixed_point_fun; 50, argument_list; 51, identifier:minus; 52, argument_list; 53, identifier:diff; 54, identifier:collected; 55, call; 56, call; 57, identifier:new; 58, identifier:collected; 59, identifier:plus; 60, argument_list; 61, identifier:f; 62, argument_list; 63, identifier:collected; 64, identifier:diff; 65, identifier:diff | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 10, 13; 11, 14; 11, 15; 12, 16; 14, 17; 15, 18; 15, 19; 15, 20; 16, 21; 16, 22; 19, 23; 20, 24; 20, 25; 22, 26; 22, 27; 24, 28; 24, 29; 24, 30; 25, 31; 27, 32; 27, 33; 29, 34; 29, 35; 30, 36; 30, 37; 30, 38; 33, 39; 36, 40; 37, 41; 37, 42; 38, 43; 40, 44; 40, 45; 41, 46; 41, 47; 42, 48; 43, 49; 43, 50; 45, 51; 45, 52; 47, 53; 48, 54; 50, 55; 50, 56; 52, 57; 52, 58; 55, 59; 55, 60; 56, 61; 56, 62; 60, 63; 60, 64; 62, 65 | def fixed_point(is_zero, plus, minus, f, x):
"""
Get the least fixed point when it can be computed piecewise.
.. testsetup::
from proso.func import fixed_point
.. doctest::
>>> sorted(fixed_point(
... is_zero=lambda xs: len(xs) == 0,
... plus=lambda xs, ys: xs + ys,
... minus=lambda xs, ys: [x for x in xs if x not in ys],
... f=lambda xs: [x + 1 for x in xs if x < 10],
... x=[0, 5, 8]
... ))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Args:
is_zero: function returning True if the given value is zero
plus: function taking two values and returning their addition
minus: function taking two values and returning ther difference
f: function computing the expected value
x: initial value
Returns:
The least fixed point.
"""
@memo_Y
def _fixed_point(fixed_point_fun):
def __fixed_point(collected, new):
diff = minus(new, collected)
if is_zero(diff):
return collected
return fixed_point_fun(plus(collected, diff), f(diff))
return __fixed_point
return _fixed_point(x, f(x)) |
0, module; 1, function_definition; 2, function_name:connections_from_graph; 3, parameters; 4, block; 5, identifier:env; 6, identifier:G; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, if_statement; 11, expression_statement; 12, if_statement; 13, comment:# Sort agent addresses to the order they were added to the environment.; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, identifier:edge_data; 19, False; 20, comment:"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironment`.
:param G:
NetworkX graph structure, either :class:`networkx.graph.Graph` or
:class:`networkx.digraph.DiGraph`. The graph needs to have the same
number of nodes as the environment has agents (excluding the managers).
:param bool edge_data:
If ``True``, edge data from the given graph is copied to the agents'
:attr:`connections`.
.. note::
By design, manager agents are excluded from the connections and should
not be counted towards environment's agent count.
The created connections are stored in each agent's
:attr:`~creamas.core.agent.CreativeAgent.connections` and the possible
edge data is stored as key-value pairs in the connection dictionary.
The agents are sorted by their environments' hosts and ports before each
agent is mapped to a node in **G**. This should cause some network
generation methods in NetworkX, e.g.
:func:`~networkx.generators.random_graphs.connected_watts_strogatz_graph`,
to create more connections between agents in the same environment and/or
node when using :class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironment`.
"""; 21, not_operator; 22, block; 23, not_operator; 24, block; 25, assignment; 26, comparison_operator:len(addrs) != len(G); 27, block; 28, assignment; 29, call; 30, assignment; 31, call; 32, call; 33, raise_statement; 34, call; 35, raise_statement; 36, identifier:addrs; 37, call; 38, call; 39, call; 40, raise_statement; 41, identifier:addrs; 42, call; 43, identifier:_addrs2nodes; 44, argument_list; 45, identifier:conn_map; 46, call; 47, attribute; 48, argument_list; 49, identifier:issubclass; 50, argument_list; 51, call; 52, identifier:hasattr; 53, argument_list; 54, call; 55, attribute; 56, argument_list; 57, identifier:len; 58, argument_list; 59, identifier:len; 60, argument_list; 61, call; 62, identifier:sort_addrs; 63, argument_list; 64, identifier:addrs; 65, identifier:G; 66, identifier:_edges2conns; 67, argument_list; 68, identifier:env; 69, identifier:create_connections; 70, identifier:conn_map; 71, attribute; 72, tuple; 73, identifier:TypeError; 74, argument_list; 75, identifier:env; 76, string; 77, identifier:TypeError; 78, argument_list; 79, identifier:env; 80, identifier:get_agents; 81, keyword_argument; 82, identifier:addrs; 83, identifier:G; 84, identifier:ValueError; 85, argument_list; 86, identifier:addrs; 87, identifier:G; 88, identifier:edge_data; 89, identifier:G; 90, identifier:__class__; 91, identifier:Graph; 92, identifier:DiGraph; 93, concatenated_string; 94, string_content:get_agents; 95, string:"Parameter 'env' must have get_agents."; 96, identifier:addr; 97, True; 98, call; 99, string:"Graph structure must be derived from Networkx's "; 100, string:"Graph or DiGraph."; 101, attribute; 102, argument_list; 103, concatenated_string; 104, identifier:format; 105, call; 106, call; 107, string:"The number of graph nodes and agents in the "; 108, string:"environment (excluding the manager agent) must "; 109, string:"match. Now got {} nodes and {} agents."; 110, identifier:len; 111, argument_list; 112, identifier:len; 113, argument_list; 114, identifier:G; 115, identifier:addrs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 7, 18; 7, 19; 8, 20; 9, 21; 9, 22; 10, 23; 10, 24; 11, 25; 12, 26; 12, 27; 14, 28; 15, 29; 16, 30; 17, 31; 21, 32; 22, 33; 23, 34; 24, 35; 25, 36; 25, 37; 26, 38; 26, 39; 27, 40; 28, 41; 28, 42; 29, 43; 29, 44; 30, 45; 30, 46; 31, 47; 31, 48; 32, 49; 32, 50; 33, 51; 34, 52; 34, 53; 35, 54; 37, 55; 37, 56; 38, 57; 38, 58; 39, 59; 39, 60; 40, 61; 42, 62; 42, 63; 44, 64; 44, 65; 46, 66; 46, 67; 47, 68; 47, 69; 48, 70; 50, 71; 50, 72; 51, 73; 51, 74; 53, 75; 53, 76; 54, 77; 54, 78; 55, 79; 55, 80; 56, 81; 58, 82; 60, 83; 61, 84; 61, 85; 63, 86; 67, 87; 67, 88; 71, 89; 71, 90; 72, 91; 72, 92; 74, 93; 76, 94; 78, 95; 81, 96; 81, 97; 85, 98; 93, 99; 93, 100; 98, 101; 98, 102; 101, 103; 101, 104; 102, 105; 102, 106; 103, 107; 103, 108; 103, 109; 105, 110; 105, 111; 106, 112; 106, 113; 111, 114; 113, 115 | def connections_from_graph(env, G, edge_data=False):
"""Create connections for agents in the given environment from the given
NetworkX graph structure.
:param env:
Environment where the agents live. The environment should be derived
from :class:`~creamas.core.environment.Environment`,
:class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironment`.
:param G:
NetworkX graph structure, either :class:`networkx.graph.Graph` or
:class:`networkx.digraph.DiGraph`. The graph needs to have the same
number of nodes as the environment has agents (excluding the managers).
:param bool edge_data:
If ``True``, edge data from the given graph is copied to the agents'
:attr:`connections`.
.. note::
By design, manager agents are excluded from the connections and should
not be counted towards environment's agent count.
The created connections are stored in each agent's
:attr:`~creamas.core.agent.CreativeAgent.connections` and the possible
edge data is stored as key-value pairs in the connection dictionary.
The agents are sorted by their environments' hosts and ports before each
agent is mapped to a node in **G**. This should cause some network
generation methods in NetworkX, e.g.
:func:`~networkx.generators.random_graphs.connected_watts_strogatz_graph`,
to create more connections between agents in the same environment and/or
node when using :class:`~creamas.mp.MultiEnvironment` or
:class:`~creamas.ds.DistributedEnvironment`.
"""
if not issubclass(G.__class__, (Graph, DiGraph)):
raise TypeError("Graph structure must be derived from Networkx's "
"Graph or DiGraph.")
if not hasattr(env, 'get_agents'):
raise TypeError("Parameter 'env' must have get_agents.")
addrs = env.get_agents(addr=True)
if len(addrs) != len(G):
raise ValueError("The number of graph nodes and agents in the "
"environment (excluding the manager agent) must "
"match. Now got {} nodes and {} agents."
.format(len(G), len(addrs)))
# Sort agent addresses to the order they were added to the environment.
addrs = sort_addrs(addrs)
_addrs2nodes(addrs, G)
conn_map = _edges2conns(G, edge_data)
env.create_connections(conn_map) |
0, module; 1, function_definition; 2, function_name:is_python_script; 3, parameters; 4, block; 5, identifier:filename; 6, expression_statement; 7, if_statement; 8, if_statement; 9, try_statement; 10, return_statement; 11, string; 12, call; 13, block; 14, not_operator; 15, block; 16, block; 17, except_clause; 18, False; 19, string_content:Checks a file to see if it's a python script of some sort.; 20, attribute; 21, argument_list; 22, return_statement; 23, call; 24, return_statement; 25, with_statement; 26, identifier:IOError; 27, block; 28, call; 29, identifier:endswith; 30, string; 31, True; 32, attribute; 33, argument_list; 34, False; 35, with_clause; 36, block; 37, pass_statement; 38, attribute; 39, argument_list; 40, string_content:.py; 41, attribute; 42, identifier:isfile; 43, identifier:filename; 44, with_item; 45, if_statement; 46, return_statement; 47, identifier:filename; 48, identifier:lower; 49, identifier:os; 50, identifier:path; 51, as_pattern; 52, comparison_operator:fp.read(2) != b'#!'; 53, block; 54, call; 55, call; 56, as_pattern_target; 57, call; 58, string; 59, return_statement; 60, attribute; 61, argument_list; 62, identifier:open; 63, argument_list; 64, identifier:fp; 65, attribute; 66, argument_list; 67, string_content:#!; 68, False; 69, identifier:re; 70, identifier:match; 71, string; 72, call; 73, identifier:filename; 74, string; 75, identifier:fp; 76, identifier:read; 77, integer:2; 78, string_content:.*python; 79, identifier:str_; 80, argument_list; 81, string_content:rb; 82, call; 83, attribute; 84, argument_list; 85, identifier:fp; 86, identifier:readline | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 7, 13; 8, 14; 8, 15; 9, 16; 9, 17; 10, 18; 11, 19; 12, 20; 12, 21; 13, 22; 14, 23; 15, 24; 16, 25; 17, 26; 17, 27; 20, 28; 20, 29; 21, 30; 22, 31; 23, 32; 23, 33; 24, 34; 25, 35; 25, 36; 27, 37; 28, 38; 28, 39; 30, 40; 32, 41; 32, 42; 33, 43; 35, 44; 36, 45; 36, 46; 38, 47; 38, 48; 41, 49; 41, 50; 44, 51; 45, 52; 45, 53; 46, 54; 51, 55; 51, 56; 52, 57; 52, 58; 53, 59; 54, 60; 54, 61; 55, 62; 55, 63; 56, 64; 57, 65; 57, 66; 58, 67; 59, 68; 60, 69; 60, 70; 61, 71; 61, 72; 63, 73; 63, 74; 65, 75; 65, 76; 66, 77; 71, 78; 72, 79; 72, 80; 74, 81; 80, 82; 82, 83; 82, 84; 83, 85; 83, 86 | def is_python_script(filename):
'''Checks a file to see if it's a python script of some sort.
'''
if filename.lower().endswith('.py'):
return True
if not os.path.isfile(filename):
return False
try:
with open(filename, 'rb') as fp:
if fp.read(2) != b'#!':
return False
return re.match(r'.*python', str_(fp.readline()))
except IOError:
pass
return False |
0, module; 1, function_definition; 2, function_name:_prepare_data; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, expression_statement; 11, for_statement; 12, comment:"""Prepare data before rendering
When plotting very large datasets, we don't want to include data points
which are outside the x-axis limits. LaTeX is very slow and consumes a
lot of memory otherwise. Limiting the data points is only (easily)
possible when the data are sorted.
"""; 13, assignment; 14, assignment; 15, identifier:series; 16, attribute; 17, block; 18, assignment; 19, identifier:series; 20, attribute; 21, block; 22, pattern_list; 23, expression_list; 24, attribute; 25, list; 26, identifier:self; 27, identifier:plot_series_list; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, comment:# only limit data when the data is sorted; 32, if_statement; 33, expression_statement; 34, attribute; 35, list; 36, identifier:self; 37, identifier:shaded_regions_list; 38, expression_statement; 39, expression_statement; 40, expression_statement; 41, comment:# only limit data when the data is sorted; 42, if_statement; 43, expression_statement; 44, identifier:xmin; 45, identifier:xmax; 46, subscript; 47, subscript; 48, identifier:self; 49, identifier:prepared_plot_series_list; 50, assignment; 51, assignment; 52, assignment; 53, comparison_operator:sorted(x) == list(x); 54, block; 55, call; 56, identifier:self; 57, identifier:prepared_shaded_regions_list; 58, assignment; 59, assignment; 60, assignment; 61, comparison_operator:sorted(x) == list(x); 62, block; 63, call; 64, attribute; 65, string; 66, attribute; 67, string; 68, identifier:prepared_series; 69, call; 70, identifier:data; 71, subscript; 72, pattern_list; 73, call; 74, call; 75, call; 76, expression_statement; 77, if_statement; 78, if_statement; 79, expression_statement; 80, attribute; 81, argument_list; 82, identifier:prepared_series; 83, call; 84, identifier:data; 85, subscript; 86, pattern_list; 87, call; 88, call; 89, call; 90, expression_statement; 91, if_statement; 92, if_statement; 93, expression_statement; 94, attribute; 95, argument_list; 96, identifier:self; 97, identifier:limits; 98, string_content:xmin; 99, identifier:self; 100, identifier:limits; 101, string_content:xmax; 102, attribute; 103, argument_list; 104, identifier:prepared_series; 105, string; 106, identifier:x; 107, identifier:_; 108, identifier:_; 109, identifier:_; 110, identifier:zip; 111, argument_list; 112, identifier:sorted; 113, argument_list; 114, identifier:list; 115, argument_list; 116, assignment; 117, comparison_operator:xmin is not None; 118, block; 119, else_clause; 120, comparison_operator:xmax is not None; 121, block; 122, else_clause; 123, assignment; 124, attribute; 125, identifier:append; 126, identifier:prepared_series; 127, attribute; 128, argument_list; 129, identifier:prepared_series; 130, string; 131, identifier:x; 132, identifier:_; 133, identifier:_; 134, identifier:zip; 135, argument_list; 136, identifier:sorted; 137, argument_list; 138, identifier:list; 139, argument_list; 140, assignment; 141, comparison_operator:xmin is not None; 142, block; 143, else_clause; 144, comparison_operator:xmax is not None; 145, block; 146, else_clause; 147, assignment; 148, attribute; 149, identifier:append; 150, identifier:prepared_series; 151, identifier:series; 152, identifier:copy; 153, string_content:data; 154, list_splat; 155, identifier:x; 156, identifier:x; 157, identifier:x; 158, call; 159, identifier:xmin; 160, None; 161, expression_statement; 162, if_statement; 163, block; 164, identifier:xmax; 165, None; 166, expression_statement; 167, block; 168, subscript; 169, subscript; 170, identifier:self; 171, identifier:prepared_plot_series_list; 172, identifier:series; 173, identifier:copy; 174, string_content:data; 175, list_splat; 176, identifier:x; 177, identifier:x; 178, identifier:x; 179, call; 180, identifier:xmin; 181, None; 182, expression_statement; 183, if_statement; 184, block; 185, identifier:xmax; 186, None; 187, expression_statement; 188, block; 189, subscript; 190, subscript; 191, identifier:self; 192, identifier:prepared_shaded_regions_list; 193, identifier:data; 194, attribute; 195, argument_list; 196, assignment; 197, comparison_operator:min_idx > 0; 198, block; 199, expression_statement; 200, assignment; 201, expression_statement; 202, identifier:prepared_series; 203, string; 204, identifier:data; 205, slice; 206, identifier:data; 207, attribute; 208, argument_list; 209, assignment; 210, comparison_operator:min_idx > 0; 211, block; 212, expression_statement; 213, assignment; 214, expression_statement; 215, identifier:prepared_series; 216, string; 217, identifier:data; 218, slice; 219, identifier:np; 220, identifier:array; 221, identifier:x; 222, identifier:min_idx; 223, call; 224, identifier:min_idx; 225, integer:0; 226, expression_statement; 227, assignment; 228, identifier:max_idx; 229, binary_operator:x.searchsorted(xmax) + 1; 230, assignment; 231, string_content:data; 232, identifier:min_idx; 233, identifier:max_idx; 234, identifier:np; 235, identifier:array; 236, identifier:x; 237, identifier:min_idx; 238, call; 239, identifier:min_idx; 240, integer:0; 241, expression_statement; 242, assignment; 243, identifier:max_idx; 244, binary_operator:x.searchsorted(xmax) + 1; 245, assignment; 246, string_content:data; 247, identifier:min_idx; 248, identifier:max_idx; 249, attribute; 250, argument_list; 251, augmented_assignment; 252, identifier:min_idx; 253, None; 254, call; 255, integer:1; 256, identifier:max_idx; 257, None; 258, attribute; 259, argument_list; 260, augmented_assignment; 261, identifier:min_idx; 262, None; 263, call; 264, integer:1; 265, identifier:max_idx; 266, None; 267, identifier:x; 268, identifier:searchsorted; 269, identifier:xmin; 270, identifier:min_idx; 271, integer:1; 272, attribute; 273, argument_list; 274, identifier:x; 275, identifier:searchsorted; 276, identifier:xmin; 277, identifier:min_idx; 278, integer:1; 279, attribute; 280, argument_list; 281, identifier:x; 282, identifier:searchsorted; 283, identifier:xmax; 284, identifier:x; 285, identifier:searchsorted; 286, identifier:xmax | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 7, 13; 8, 14; 9, 15; 9, 16; 9, 17; 10, 18; 11, 19; 11, 20; 11, 21; 13, 22; 13, 23; 14, 24; 14, 25; 16, 26; 16, 27; 17, 28; 17, 29; 17, 30; 17, 31; 17, 32; 17, 33; 18, 34; 18, 35; 20, 36; 20, 37; 21, 38; 21, 39; 21, 40; 21, 41; 21, 42; 21, 43; 22, 44; 22, 45; 23, 46; 23, 47; 24, 48; 24, 49; 28, 50; 29, 51; 30, 52; 32, 53; 32, 54; 33, 55; 34, 56; 34, 57; 38, 58; 39, 59; 40, 60; 42, 61; 42, 62; 43, 63; 46, 64; 46, 65; 47, 66; 47, 67; 50, 68; 50, 69; 51, 70; 51, 71; 52, 72; 52, 73; 53, 74; 53, 75; 54, 76; 54, 77; 54, 78; 54, 79; 55, 80; 55, 81; 58, 82; 58, 83; 59, 84; 59, 85; 60, 86; 60, 87; 61, 88; 61, 89; 62, 90; 62, 91; 62, 92; 62, 93; 63, 94; 63, 95; 64, 96; 64, 97; 65, 98; 66, 99; 66, 100; 67, 101; 69, 102; 69, 103; 71, 104; 71, 105; 72, 106; 72, 107; 72, 108; 72, 109; 73, 110; 73, 111; 74, 112; 74, 113; 75, 114; 75, 115; 76, 116; 77, 117; 77, 118; 77, 119; 78, 120; 78, 121; 78, 122; 79, 123; 80, 124; 80, 125; 81, 126; 83, 127; 83, 128; 85, 129; 85, 130; 86, 131; 86, 132; 86, 133; 87, 134; 87, 135; 88, 136; 88, 137; 89, 138; 89, 139; 90, 140; 91, 141; 91, 142; 91, 143; 92, 144; 92, 145; 92, 146; 93, 147; 94, 148; 94, 149; 95, 150; 102, 151; 102, 152; 105, 153; 111, 154; 113, 155; 115, 156; 116, 157; 116, 158; 117, 159; 117, 160; 118, 161; 118, 162; 119, 163; 120, 164; 120, 165; 121, 166; 122, 167; 123, 168; 123, 169; 124, 170; 124, 171; 127, 172; 127, 173; 130, 174; 135, 175; 137, 176; 139, 177; 140, 178; 140, 179; 141, 180; 141, 181; 142, 182; 142, 183; 143, 184; 144, 185; 144, 186; 145, 187; 146, 188; 147, 189; 147, 190; 148, 191; 148, 192; 154, 193; 158, 194; 158, 195; 161, 196; 162, 197; 162, 198; 163, 199; 166, 200; 167, 201; 168, 202; 168, 203; 169, 204; 169, 205; 175, 206; 179, 207; 179, 208; 182, 209; 183, 210; 183, 211; 184, 212; 187, 213; 188, 214; 189, 215; 189, 216; 190, 217; 190, 218; 194, 219; 194, 220; 195, 221; 196, 222; 196, 223; 197, 224; 197, 225; 198, 226; 199, 227; 200, 228; 200, 229; 201, 230; 203, 231; 205, 232; 205, 233; 207, 234; 207, 235; 208, 236; 209, 237; 209, 238; 210, 239; 210, 240; 211, 241; 212, 242; 213, 243; 213, 244; 214, 245; 216, 246; 218, 247; 218, 248; 223, 249; 223, 250; 226, 251; 227, 252; 227, 253; 229, 254; 229, 255; 230, 256; 230, 257; 238, 258; 238, 259; 241, 260; 242, 261; 242, 262; 244, 263; 244, 264; 245, 265; 245, 266; 249, 267; 249, 268; 250, 269; 251, 270; 251, 271; 254, 272; 254, 273; 258, 274; 258, 275; 259, 276; 260, 277; 260, 278; 263, 279; 263, 280; 272, 281; 272, 282; 273, 283; 279, 284; 279, 285; 280, 286 | def _prepare_data(self):
"""Prepare data before rendering
When plotting very large datasets, we don't want to include data points
which are outside the x-axis limits. LaTeX is very slow and consumes a
lot of memory otherwise. Limiting the data points is only (easily)
possible when the data are sorted.
"""
xmin, xmax = self.limits['xmin'], self.limits['xmax']
self.prepared_plot_series_list = []
for series in self.plot_series_list:
prepared_series = series.copy()
data = prepared_series['data']
x, _, _, _ = zip(*data)
# only limit data when the data is sorted
if sorted(x) == list(x):
x = np.array(x)
if xmin is not None:
min_idx = x.searchsorted(xmin)
if min_idx > 0:
min_idx -= 1
else:
min_idx = None
if xmax is not None:
max_idx = x.searchsorted(xmax) + 1
else:
max_idx = None
prepared_series['data'] = data[min_idx:max_idx]
self.prepared_plot_series_list.append(prepared_series)
self.prepared_shaded_regions_list = []
for series in self.shaded_regions_list:
prepared_series = series.copy()
data = prepared_series['data']
x, _, _ = zip(*data)
# only limit data when the data is sorted
if sorted(x) == list(x):
x = np.array(x)
if xmin is not None:
min_idx = x.searchsorted(xmin)
if min_idx > 0:
min_idx -= 1
else:
min_idx = None
if xmax is not None:
max_idx = x.searchsorted(xmax) + 1
else:
max_idx = None
prepared_series['data'] = data[min_idx:max_idx]
self.prepared_shaded_regions_list.append(prepared_series) |
0, module; 1, function_definition; 2, function_name:by_user; 3, parameters; 4, block; 5, identifier:config; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, comment:"""Display LDAP group membership sorted by user."""; 12, assignment; 13, call; 14, assignment; 15, call; 16, identifier:client; 17, call; 18, attribute; 19, argument_list; 20, identifier:audit_api; 21, call; 22, attribute; 23, argument_list; 24, identifier:Client; 25, argument_list; 26, identifier:client; 27, identifier:prepare_connection; 28, identifier:API; 29, argument_list; 30, identifier:CLI; 31, identifier:parse_membership; 32, string; 33, call; 34, identifier:client; 35, string_content:Groups by User; 36, attribute; 37, argument_list; 38, identifier:audit_api; 39, identifier:by_user | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 9, 14; 10, 15; 12, 16; 12, 17; 13, 18; 13, 19; 14, 20; 14, 21; 15, 22; 15, 23; 17, 24; 17, 25; 18, 26; 18, 27; 21, 28; 21, 29; 22, 30; 22, 31; 23, 32; 23, 33; 29, 34; 32, 35; 33, 36; 33, 37; 36, 38; 36, 39 | def by_user(config):
"""Display LDAP group membership sorted by user."""
client = Client()
client.prepare_connection()
audit_api = API(client)
CLI.parse_membership('Groups by User', audit_api.by_user()) |
Subsets and Splits