repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Erotemic/utool | utool/util_dict.py | dict_stack | 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 | python | 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 | [
"def",
"dict_stack",
"(",
"dict_list",
",",
"key_prefix",
"=",
"''",
")",
":",
"r",
"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"
] | 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]} | [
"r",
"stacks",
"values",
"from",
"two",
"dicts",
"into",
"a",
"new",
"dict",
"where",
"the",
"values",
"are",
"list",
"of",
"the",
"input",
"values",
".",
"the",
"keys",
"are",
"the",
"same",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L332-L379 | train |
Erotemic/utool | utool/util_dict.py | dict_stack2 | def dict_stack2(dict_list, key_suffix=None, default=None):
"""
Stacks vals from a list of dicts into a dict of lists. Inserts Nones in
place of empty items to preserve order.
Args:
dict_list (list): list of dicts
key_suffix (str): (default = None)
Returns:
dict: stacked_dict
Example:
>>> # ENABLE_DOCTEST
>>> # Usual case: multiple dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [None, 4]}
Example1:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict_list = [dict1_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1], 'b': [2]}
Example2:
>>> # ENABLE_DOCTEST
>>> # Corner case: zero dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = []
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example3:
>>> # ENABLE_DOCTEST
>>> # Corner case: empty dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{}]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example4:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict is empty
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None]}
Example5:
>>> # ENABLE_DOCTEST
>>> # Corner case: disjoint dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None], 'c': [None, 4]}
Example6:
>>> # ENABLE_DOCTEST
>>> # Corner case: 3 dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{'a': 1}, {'b': 1}, {'c': 1}, {'b': 2}]
>>> default = None
>>> dict_stacked = dict_stack2(dict_list, default=default)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, None, None, None], 'b': [None, 1, None, 2], 'c': [None, None, 1, None]}
"""
if len(dict_list) > 0:
dict_list_ = [map_dict_vals(lambda x: [x], kw) for kw in dict_list]
# Reduce does not handle default quite correctly
default1 = []
default2 = [default]
accum_ = dict_list_[0]
for dict_ in dict_list_[1:]:
default1.append(default)
accum_ = dict_union_combine(accum_, dict_, default=default1,
default2=default2)
stacked_dict = accum_
# stacked_dict = reduce(partial(dict_union_combine, default=[default]), dict_list_)
else:
stacked_dict = {}
# Augment keys if requested
if key_suffix is not None:
stacked_dict = map_dict_keys(lambda x: x + key_suffix, stacked_dict)
return stacked_dict | python | def dict_stack2(dict_list, key_suffix=None, default=None):
"""
Stacks vals from a list of dicts into a dict of lists. Inserts Nones in
place of empty items to preserve order.
Args:
dict_list (list): list of dicts
key_suffix (str): (default = None)
Returns:
dict: stacked_dict
Example:
>>> # ENABLE_DOCTEST
>>> # Usual case: multiple dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [None, 4]}
Example1:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict_list = [dict1_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1], 'b': [2]}
Example2:
>>> # ENABLE_DOCTEST
>>> # Corner case: zero dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = []
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example3:
>>> # ENABLE_DOCTEST
>>> # Corner case: empty dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{}]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example4:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict is empty
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None]}
Example5:
>>> # ENABLE_DOCTEST
>>> # Corner case: disjoint dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None], 'c': [None, 4]}
Example6:
>>> # ENABLE_DOCTEST
>>> # Corner case: 3 dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{'a': 1}, {'b': 1}, {'c': 1}, {'b': 2}]
>>> default = None
>>> dict_stacked = dict_stack2(dict_list, default=default)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, None, None, None], 'b': [None, 1, None, 2], 'c': [None, None, 1, None]}
"""
if len(dict_list) > 0:
dict_list_ = [map_dict_vals(lambda x: [x], kw) for kw in dict_list]
# Reduce does not handle default quite correctly
default1 = []
default2 = [default]
accum_ = dict_list_[0]
for dict_ in dict_list_[1:]:
default1.append(default)
accum_ = dict_union_combine(accum_, dict_, default=default1,
default2=default2)
stacked_dict = accum_
# stacked_dict = reduce(partial(dict_union_combine, default=[default]), dict_list_)
else:
stacked_dict = {}
# Augment keys if requested
if key_suffix is not None:
stacked_dict = map_dict_keys(lambda x: x + key_suffix, stacked_dict)
return stacked_dict | [
"def",
"dict_stack2",
"(",
"dict_list",
",",
"key_suffix",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"len",
"(",
"dict_list",
")",
">",
"0",
":",
"dict_list_",
"=",
"[",
"map_dict_vals",
"(",
"lambda",
"x",
":",
"[",
"x",
"]",
",",
"kw",
")",
"for",
"kw",
"in",
"dict_list",
"]",
"default1",
"=",
"[",
"]",
"default2",
"=",
"[",
"default",
"]",
"accum_",
"=",
"dict_list_",
"[",
"0",
"]",
"for",
"dict_",
"in",
"dict_list_",
"[",
"1",
":",
"]",
":",
"default1",
".",
"append",
"(",
"default",
")",
"accum_",
"=",
"dict_union_combine",
"(",
"accum_",
",",
"dict_",
",",
"default",
"=",
"default1",
",",
"default2",
"=",
"default2",
")",
"stacked_dict",
"=",
"accum_",
"else",
":",
"stacked_dict",
"=",
"{",
"}",
"if",
"key_suffix",
"is",
"not",
"None",
":",
"stacked_dict",
"=",
"map_dict_keys",
"(",
"lambda",
"x",
":",
"x",
"+",
"key_suffix",
",",
"stacked_dict",
")",
"return",
"stacked_dict"
] | Stacks vals from a list of dicts into a dict of lists. Inserts Nones in
place of empty items to preserve order.
Args:
dict_list (list): list of dicts
key_suffix (str): (default = None)
Returns:
dict: stacked_dict
Example:
>>> # ENABLE_DOCTEST
>>> # Usual case: multiple dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict2_ = {'a': 2, 'b': 3, 'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, 2], 'b': [2, 3], 'c': [None, 4]}
Example1:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': 1, 'b': 2}
>>> dict_list = [dict1_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1], 'b': [2]}
Example2:
>>> # ENABLE_DOCTEST
>>> # Corner case: zero dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = []
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example3:
>>> # ENABLE_DOCTEST
>>> # Corner case: empty dicts as input
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{}]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{}
Example4:
>>> # ENABLE_DOCTEST
>>> # Corner case: one dict is empty
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None]}
Example5:
>>> # ENABLE_DOCTEST
>>> # Corner case: disjoint dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict1_ = {'a': [1, 2], 'b': [2, 3]}
>>> dict2_ = {'c': 4}
>>> dict_list = [dict1_, dict2_]
>>> dict_stacked = dict_stack2(dict_list)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [[1, 2], None], 'b': [[2, 3], None], 'c': [None, 4]}
Example6:
>>> # ENABLE_DOCTEST
>>> # Corner case: 3 dicts
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_list = [{'a': 1}, {'b': 1}, {'c': 1}, {'b': 2}]
>>> default = None
>>> dict_stacked = dict_stack2(dict_list, default=default)
>>> result = ut.repr2(dict_stacked)
>>> print(result)
{'a': [1, None, None, None], 'b': [None, 1, None, 2], 'c': [None, None, 1, None]} | [
"Stacks",
"vals",
"from",
"a",
"list",
"of",
"dicts",
"into",
"a",
"dict",
"of",
"lists",
".",
"Inserts",
"Nones",
"in",
"place",
"of",
"empty",
"items",
"to",
"preserve",
"order",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L382-L496 | train |
Erotemic/utool | utool/util_dict.py | invert_dict | 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 | python | 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 | [
"def",
"invert_dict",
"(",
"dict_",
",",
"unique_vals",
"=",
"True",
")",
":",
"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"
] | 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']} | [
"Reverses",
"the",
"keys",
"and",
"values",
"in",
"a",
"dictionary",
".",
"Set",
"unique_vals",
"to",
"False",
"if",
"the",
"values",
"in",
"the",
"dict",
"are",
"not",
"unique",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L499-L550 | train |
Erotemic/utool | utool/util_dict.py | iter_all_dict_combinations_ordered | def iter_all_dict_combinations_ordered(varied_dict):
"""
Same as all_dict_combinations but preserves order
"""
tups_list = [[(key, val) for val in val_list]
for (key, val_list) in six.iteritems(varied_dict)]
dict_iter = (OrderedDict(tups) for tups in it.product(*tups_list))
return dict_iter | python | def iter_all_dict_combinations_ordered(varied_dict):
"""
Same as all_dict_combinations but preserves order
"""
tups_list = [[(key, val) for val in val_list]
for (key, val_list) in six.iteritems(varied_dict)]
dict_iter = (OrderedDict(tups) for tups in it.product(*tups_list))
return dict_iter | [
"def",
"iter_all_dict_combinations_ordered",
"(",
"varied_dict",
")",
":",
"tups_list",
"=",
"[",
"[",
"(",
"key",
",",
"val",
")",
"for",
"val",
"in",
"val_list",
"]",
"for",
"(",
"key",
",",
"val_list",
")",
"in",
"six",
".",
"iteritems",
"(",
"varied_dict",
")",
"]",
"dict_iter",
"=",
"(",
"OrderedDict",
"(",
"tups",
")",
"for",
"tups",
"in",
"it",
".",
"product",
"(",
"*",
"tups_list",
")",
")",
"return",
"dict_iter"
] | Same as all_dict_combinations but preserves order | [
"Same",
"as",
"all_dict_combinations",
"but",
"preserves",
"order"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L553-L560 | train |
Erotemic/utool | utool/util_dict.py | all_dict_combinations_lbls | def all_dict_combinations_lbls(varied_dict, remove_singles=True, allow_lone_singles=False):
"""
returns a label for each variation in a varydict.
It tries to not be oververbose and returns only what parameters are varied
in each label.
CommandLine:
python -m utool.util_dict --test-all_dict_combinations_lbls
python -m utool.util_dict --exec-all_dict_combinations_lbls:1
Example:
>>> # ENABLE_DOCTEST
>>> import utool
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0, 1.0], 'pipeline_root': ['vsmany'], 'sv_on': [True, False, None]}
>>> comb_lbls = utool.all_dict_combinations_lbls(varied_dict)
>>> result = (utool.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,sv_on=True',
'logdist_weight=0.0,sv_on=False',
'logdist_weight=0.0,sv_on=None',
'logdist_weight=1.0,sv_on=True',
'logdist_weight=1.0,sv_on=False',
'logdist_weight=1.0,sv_on=None',
]
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0], 'pipeline_root': ['vsmany'], 'sv_on': [True]}
>>> allow_lone_singles = True
>>> comb_lbls = ut.all_dict_combinations_lbls(varied_dict, allow_lone_singles=allow_lone_singles)
>>> result = (ut.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,pipeline_root=vsmany,sv_on=True',
]
"""
is_lone_single = all([
isinstance(val_list, (list, tuple)) and len(val_list) == 1
for key, val_list in iteritems_sorted(varied_dict)
])
if not remove_singles or (allow_lone_singles and is_lone_single):
# all entries have one length
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
]
else:
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
if isinstance(val_list, (list, tuple)) and len(val_list) > 1]
combtup_list = list(it.product(*multitups_list))
combtup_list2 = [
[(key, val) if isinstance(val, six.string_types) else (key, repr(val))
for (key, val) in combtup]
for combtup in combtup_list]
comb_lbls = [','.join(['%s=%s' % (key, val) for (key, val) in combtup])
for combtup in combtup_list2]
#comb_lbls = list(map(str, comb_pairs))
return comb_lbls | python | def all_dict_combinations_lbls(varied_dict, remove_singles=True, allow_lone_singles=False):
"""
returns a label for each variation in a varydict.
It tries to not be oververbose and returns only what parameters are varied
in each label.
CommandLine:
python -m utool.util_dict --test-all_dict_combinations_lbls
python -m utool.util_dict --exec-all_dict_combinations_lbls:1
Example:
>>> # ENABLE_DOCTEST
>>> import utool
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0, 1.0], 'pipeline_root': ['vsmany'], 'sv_on': [True, False, None]}
>>> comb_lbls = utool.all_dict_combinations_lbls(varied_dict)
>>> result = (utool.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,sv_on=True',
'logdist_weight=0.0,sv_on=False',
'logdist_weight=0.0,sv_on=None',
'logdist_weight=1.0,sv_on=True',
'logdist_weight=1.0,sv_on=False',
'logdist_weight=1.0,sv_on=None',
]
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0], 'pipeline_root': ['vsmany'], 'sv_on': [True]}
>>> allow_lone_singles = True
>>> comb_lbls = ut.all_dict_combinations_lbls(varied_dict, allow_lone_singles=allow_lone_singles)
>>> result = (ut.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,pipeline_root=vsmany,sv_on=True',
]
"""
is_lone_single = all([
isinstance(val_list, (list, tuple)) and len(val_list) == 1
for key, val_list in iteritems_sorted(varied_dict)
])
if not remove_singles or (allow_lone_singles and is_lone_single):
# all entries have one length
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
]
else:
multitups_list = [
[(key, val) for val in val_list]
for key, val_list in iteritems_sorted(varied_dict)
if isinstance(val_list, (list, tuple)) and len(val_list) > 1]
combtup_list = list(it.product(*multitups_list))
combtup_list2 = [
[(key, val) if isinstance(val, six.string_types) else (key, repr(val))
for (key, val) in combtup]
for combtup in combtup_list]
comb_lbls = [','.join(['%s=%s' % (key, val) for (key, val) in combtup])
for combtup in combtup_list2]
#comb_lbls = list(map(str, comb_pairs))
return comb_lbls | [
"def",
"all_dict_combinations_lbls",
"(",
"varied_dict",
",",
"remove_singles",
"=",
"True",
",",
"allow_lone_singles",
"=",
"False",
")",
":",
"is_lone_single",
"=",
"all",
"(",
"[",
"isinstance",
"(",
"val_list",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"len",
"(",
"val_list",
")",
"==",
"1",
"for",
"key",
",",
"val_list",
"in",
"iteritems_sorted",
"(",
"varied_dict",
")",
"]",
")",
"if",
"not",
"remove_singles",
"or",
"(",
"allow_lone_singles",
"and",
"is_lone_single",
")",
":",
"multitups_list",
"=",
"[",
"[",
"(",
"key",
",",
"val",
")",
"for",
"val",
"in",
"val_list",
"]",
"for",
"key",
",",
"val_list",
"in",
"iteritems_sorted",
"(",
"varied_dict",
")",
"]",
"else",
":",
"multitups_list",
"=",
"[",
"[",
"(",
"key",
",",
"val",
")",
"for",
"val",
"in",
"val_list",
"]",
"for",
"key",
",",
"val_list",
"in",
"iteritems_sorted",
"(",
"varied_dict",
")",
"if",
"isinstance",
"(",
"val_list",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"len",
"(",
"val_list",
")",
">",
"1",
"]",
"combtup_list",
"=",
"list",
"(",
"it",
".",
"product",
"(",
"*",
"multitups_list",
")",
")",
"combtup_list2",
"=",
"[",
"[",
"(",
"key",
",",
"val",
")",
"if",
"isinstance",
"(",
"val",
",",
"six",
".",
"string_types",
")",
"else",
"(",
"key",
",",
"repr",
"(",
"val",
")",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"combtup",
"]",
"for",
"combtup",
"in",
"combtup_list",
"]",
"comb_lbls",
"=",
"[",
"','",
".",
"join",
"(",
"[",
"'%s=%s'",
"%",
"(",
"key",
",",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"combtup",
"]",
")",
"for",
"combtup",
"in",
"combtup_list2",
"]",
"return",
"comb_lbls"
] | returns a label for each variation in a varydict.
It tries to not be oververbose and returns only what parameters are varied
in each label.
CommandLine:
python -m utool.util_dict --test-all_dict_combinations_lbls
python -m utool.util_dict --exec-all_dict_combinations_lbls:1
Example:
>>> # ENABLE_DOCTEST
>>> import utool
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0, 1.0], 'pipeline_root': ['vsmany'], 'sv_on': [True, False, None]}
>>> comb_lbls = utool.all_dict_combinations_lbls(varied_dict)
>>> result = (utool.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,sv_on=True',
'logdist_weight=0.0,sv_on=False',
'logdist_weight=0.0,sv_on=None',
'logdist_weight=1.0,sv_on=True',
'logdist_weight=1.0,sv_on=False',
'logdist_weight=1.0,sv_on=None',
]
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> from utool.util_dict import * # NOQA
>>> varied_dict = {'logdist_weight': [0.0], 'pipeline_root': ['vsmany'], 'sv_on': [True]}
>>> allow_lone_singles = True
>>> comb_lbls = ut.all_dict_combinations_lbls(varied_dict, allow_lone_singles=allow_lone_singles)
>>> result = (ut.repr4(comb_lbls))
>>> print(result)
[
'logdist_weight=0.0,pipeline_root=vsmany,sv_on=True',
] | [
"returns",
"a",
"label",
"for",
"each",
"variation",
"in",
"a",
"varydict",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L617-L681 | train |
Erotemic/utool | utool/util_dict.py | build_conflict_dict | def build_conflict_dict(key_list, val_list):
"""
Builds dict where a list of values is associated with more than one key
Args:
key_list (list):
val_list (list):
Returns:
dict: key_to_vals
CommandLine:
python -m utool.util_dict --test-build_conflict_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> key_list = [ 1, 2, 2, 3, 1]
>>> val_list = ['a', 'b', 'c', 'd', 'e']
>>> key_to_vals = build_conflict_dict(key_list, val_list)
>>> result = ut.repr4(key_to_vals)
>>> print(result)
{
1: ['a', 'e'],
2: ['b', 'c'],
3: ['d'],
}
"""
key_to_vals = defaultdict(list)
for key, val in zip(key_list, val_list):
key_to_vals[key].append(val)
return key_to_vals | python | def build_conflict_dict(key_list, val_list):
"""
Builds dict where a list of values is associated with more than one key
Args:
key_list (list):
val_list (list):
Returns:
dict: key_to_vals
CommandLine:
python -m utool.util_dict --test-build_conflict_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> key_list = [ 1, 2, 2, 3, 1]
>>> val_list = ['a', 'b', 'c', 'd', 'e']
>>> key_to_vals = build_conflict_dict(key_list, val_list)
>>> result = ut.repr4(key_to_vals)
>>> print(result)
{
1: ['a', 'e'],
2: ['b', 'c'],
3: ['d'],
}
"""
key_to_vals = defaultdict(list)
for key, val in zip(key_list, val_list):
key_to_vals[key].append(val)
return key_to_vals | [
"def",
"build_conflict_dict",
"(",
"key_list",
",",
"val_list",
")",
":",
"key_to_vals",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"key_list",
",",
"val_list",
")",
":",
"key_to_vals",
"[",
"key",
"]",
".",
"append",
"(",
"val",
")",
"return",
"key_to_vals"
] | Builds dict where a list of values is associated with more than one key
Args:
key_list (list):
val_list (list):
Returns:
dict: key_to_vals
CommandLine:
python -m utool.util_dict --test-build_conflict_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> key_list = [ 1, 2, 2, 3, 1]
>>> val_list = ['a', 'b', 'c', 'd', 'e']
>>> key_to_vals = build_conflict_dict(key_list, val_list)
>>> result = ut.repr4(key_to_vals)
>>> print(result)
{
1: ['a', 'e'],
2: ['b', 'c'],
3: ['d'],
} | [
"Builds",
"dict",
"where",
"a",
"list",
"of",
"values",
"is",
"associated",
"with",
"more",
"than",
"one",
"key"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L692-L724 | train |
Erotemic/utool | utool/util_dict.py | update_existing | def update_existing(dict1, dict2, copy=False, assert_exists=False,
iswarning=False, alias_dict=None):
r"""
updates vals in dict1 using vals from dict2 only if the
key is already in dict1.
Args:
dict1 (dict):
dict2 (dict):
copy (bool): if true modifies dictionary in place (default = False)
assert_exists (bool): if True throws error if new key specified (default = False)
alias_dict (dict): dictionary of alias keys for dict2 (default = None)
Returns:
dict - updated dictionary
CommandLine:
python -m utool.util_dict --test-update_existing
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 2, 'd': 3}
>>> dict1_ = update_existing(dict1, dict2)
>>> assert 'd' not in dict1
>>> assert dict1['a'] == 2
>>> assert dict1_ is dict1
"""
if assert_exists:
try:
assert_keys_are_subset(dict1, dict2)
except AssertionError as ex:
from utool import util_dbg
util_dbg.printex(ex, iswarning=iswarning, N=1)
if not iswarning:
raise
if copy:
dict1 = dict(dict1)
if alias_dict is None:
alias_dict = {}
for key, val in six.iteritems(dict2):
key = alias_dict.get(key, key)
if key in dict1:
dict1[key] = val
return dict1 | python | def update_existing(dict1, dict2, copy=False, assert_exists=False,
iswarning=False, alias_dict=None):
r"""
updates vals in dict1 using vals from dict2 only if the
key is already in dict1.
Args:
dict1 (dict):
dict2 (dict):
copy (bool): if true modifies dictionary in place (default = False)
assert_exists (bool): if True throws error if new key specified (default = False)
alias_dict (dict): dictionary of alias keys for dict2 (default = None)
Returns:
dict - updated dictionary
CommandLine:
python -m utool.util_dict --test-update_existing
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 2, 'd': 3}
>>> dict1_ = update_existing(dict1, dict2)
>>> assert 'd' not in dict1
>>> assert dict1['a'] == 2
>>> assert dict1_ is dict1
"""
if assert_exists:
try:
assert_keys_are_subset(dict1, dict2)
except AssertionError as ex:
from utool import util_dbg
util_dbg.printex(ex, iswarning=iswarning, N=1)
if not iswarning:
raise
if copy:
dict1 = dict(dict1)
if alias_dict is None:
alias_dict = {}
for key, val in six.iteritems(dict2):
key = alias_dict.get(key, key)
if key in dict1:
dict1[key] = val
return dict1 | [
"def",
"update_existing",
"(",
"dict1",
",",
"dict2",
",",
"copy",
"=",
"False",
",",
"assert_exists",
"=",
"False",
",",
"iswarning",
"=",
"False",
",",
"alias_dict",
"=",
"None",
")",
":",
"r",
"if",
"assert_exists",
":",
"try",
":",
"assert_keys_are_subset",
"(",
"dict1",
",",
"dict2",
")",
"except",
"AssertionError",
"as",
"ex",
":",
"from",
"utool",
"import",
"util_dbg",
"util_dbg",
".",
"printex",
"(",
"ex",
",",
"iswarning",
"=",
"iswarning",
",",
"N",
"=",
"1",
")",
"if",
"not",
"iswarning",
":",
"raise",
"if",
"copy",
":",
"dict1",
"=",
"dict",
"(",
"dict1",
")",
"if",
"alias_dict",
"is",
"None",
":",
"alias_dict",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"dict2",
")",
":",
"key",
"=",
"alias_dict",
".",
"get",
"(",
"key",
",",
"key",
")",
"if",
"key",
"in",
"dict1",
":",
"dict1",
"[",
"key",
"]",
"=",
"val",
"return",
"dict1"
] | r"""
updates vals in dict1 using vals from dict2 only if the
key is already in dict1.
Args:
dict1 (dict):
dict2 (dict):
copy (bool): if true modifies dictionary in place (default = False)
assert_exists (bool): if True throws error if new key specified (default = False)
alias_dict (dict): dictionary of alias keys for dict2 (default = None)
Returns:
dict - updated dictionary
CommandLine:
python -m utool.util_dict --test-update_existing
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 2, 'd': 3}
>>> dict1_ = update_existing(dict1, dict2)
>>> assert 'd' not in dict1
>>> assert dict1['a'] == 2
>>> assert dict1_ is dict1 | [
"r",
"updates",
"vals",
"in",
"dict1",
"using",
"vals",
"from",
"dict2",
"only",
"if",
"the",
"key",
"is",
"already",
"in",
"dict1",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L751-L796 | train |
Erotemic/utool | utool/util_dict.py | dict_update_newkeys | def dict_update_newkeys(dict_, dict2):
""" Like dict.update, but does not overwrite items """
for key, val in six.iteritems(dict2):
if key not in dict_:
dict_[key] = val | python | def dict_update_newkeys(dict_, dict2):
""" Like dict.update, but does not overwrite items """
for key, val in six.iteritems(dict2):
if key not in dict_:
dict_[key] = val | [
"def",
"dict_update_newkeys",
"(",
"dict_",
",",
"dict2",
")",
":",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"dict2",
")",
":",
"if",
"key",
"not",
"in",
"dict_",
":",
"dict_",
"[",
"key",
"]",
"=",
"val"
] | Like dict.update, but does not overwrite items | [
"Like",
"dict",
".",
"update",
"but",
"does",
"not",
"overwrite",
"items"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L810-L814 | train |
Erotemic/utool | utool/util_dict.py | is_dicteq | def is_dicteq(dict1_, dict2_, almosteq_ok=True, verbose_err=True):
""" Checks to see if dicts are the same. Performs recursion. Handles numpy """
import utool as ut
assert len(dict1_) == len(dict2_), 'dicts are not of same length'
try:
for (key1, val1), (key2, val2) in zip(dict1_.items(), dict2_.items()):
assert key1 == key2, 'key mismatch'
assert type(val1) == type(val2), 'vals are not same type'
if HAVE_NUMPY and np.iterable(val1):
if almosteq_ok and ut.is_float(val1):
assert np.all(ut.almost_eq(val1, val2)), 'float vals are not within thresh'
else:
assert all([np.all(x1 == x2) for (x1, x2) in zip(val1, val2)]), 'np vals are different'
elif isinstance(val1, dict):
is_dicteq(val1, val2, almosteq_ok=almosteq_ok, verbose_err=verbose_err)
else:
assert val1 == val2, 'vals are different'
except AssertionError as ex:
if verbose_err:
ut.printex(ex)
return False
return True | python | def is_dicteq(dict1_, dict2_, almosteq_ok=True, verbose_err=True):
""" Checks to see if dicts are the same. Performs recursion. Handles numpy """
import utool as ut
assert len(dict1_) == len(dict2_), 'dicts are not of same length'
try:
for (key1, val1), (key2, val2) in zip(dict1_.items(), dict2_.items()):
assert key1 == key2, 'key mismatch'
assert type(val1) == type(val2), 'vals are not same type'
if HAVE_NUMPY and np.iterable(val1):
if almosteq_ok and ut.is_float(val1):
assert np.all(ut.almost_eq(val1, val2)), 'float vals are not within thresh'
else:
assert all([np.all(x1 == x2) for (x1, x2) in zip(val1, val2)]), 'np vals are different'
elif isinstance(val1, dict):
is_dicteq(val1, val2, almosteq_ok=almosteq_ok, verbose_err=verbose_err)
else:
assert val1 == val2, 'vals are different'
except AssertionError as ex:
if verbose_err:
ut.printex(ex)
return False
return True | [
"def",
"is_dicteq",
"(",
"dict1_",
",",
"dict2_",
",",
"almosteq_ok",
"=",
"True",
",",
"verbose_err",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"assert",
"len",
"(",
"dict1_",
")",
"==",
"len",
"(",
"dict2_",
")",
",",
"'dicts are not of same length'",
"try",
":",
"for",
"(",
"key1",
",",
"val1",
")",
",",
"(",
"key2",
",",
"val2",
")",
"in",
"zip",
"(",
"dict1_",
".",
"items",
"(",
")",
",",
"dict2_",
".",
"items",
"(",
")",
")",
":",
"assert",
"key1",
"==",
"key2",
",",
"'key mismatch'",
"assert",
"type",
"(",
"val1",
")",
"==",
"type",
"(",
"val2",
")",
",",
"'vals are not same type'",
"if",
"HAVE_NUMPY",
"and",
"np",
".",
"iterable",
"(",
"val1",
")",
":",
"if",
"almosteq_ok",
"and",
"ut",
".",
"is_float",
"(",
"val1",
")",
":",
"assert",
"np",
".",
"all",
"(",
"ut",
".",
"almost_eq",
"(",
"val1",
",",
"val2",
")",
")",
",",
"'float vals are not within thresh'",
"else",
":",
"assert",
"all",
"(",
"[",
"np",
".",
"all",
"(",
"x1",
"==",
"x2",
")",
"for",
"(",
"x1",
",",
"x2",
")",
"in",
"zip",
"(",
"val1",
",",
"val2",
")",
"]",
")",
",",
"'np vals are different'",
"elif",
"isinstance",
"(",
"val1",
",",
"dict",
")",
":",
"is_dicteq",
"(",
"val1",
",",
"val2",
",",
"almosteq_ok",
"=",
"almosteq_ok",
",",
"verbose_err",
"=",
"verbose_err",
")",
"else",
":",
"assert",
"val1",
"==",
"val2",
",",
"'vals are different'",
"except",
"AssertionError",
"as",
"ex",
":",
"if",
"verbose_err",
":",
"ut",
".",
"printex",
"(",
"ex",
")",
"return",
"False",
"return",
"True"
] | Checks to see if dicts are the same. Performs recursion. Handles numpy | [
"Checks",
"to",
"see",
"if",
"dicts",
"are",
"the",
"same",
".",
"Performs",
"recursion",
".",
"Handles",
"numpy"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L817-L838 | train |
Erotemic/utool | utool/util_dict.py | dict_setdiff | def dict_setdiff(dict_, negative_keys):
r"""
returns a copy of dict_ without keys in the negative_keys list
Args:
dict_ (dict):
negative_keys (list):
"""
keys = [key for key in six.iterkeys(dict_)
if key not in set(negative_keys)]
subdict_ = dict_subset(dict_, keys)
return subdict_ | python | def dict_setdiff(dict_, negative_keys):
r"""
returns a copy of dict_ without keys in the negative_keys list
Args:
dict_ (dict):
negative_keys (list):
"""
keys = [key for key in six.iterkeys(dict_)
if key not in set(negative_keys)]
subdict_ = dict_subset(dict_, keys)
return subdict_ | [
"def",
"dict_setdiff",
"(",
"dict_",
",",
"negative_keys",
")",
":",
"r",
"keys",
"=",
"[",
"key",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"dict_",
")",
"if",
"key",
"not",
"in",
"set",
"(",
"negative_keys",
")",
"]",
"subdict_",
"=",
"dict_subset",
"(",
"dict_",
",",
"keys",
")",
"return",
"subdict_"
] | r"""
returns a copy of dict_ without keys in the negative_keys list
Args:
dict_ (dict):
negative_keys (list): | [
"r",
"returns",
"a",
"copy",
"of",
"dict_",
"without",
"keys",
"in",
"the",
"negative_keys",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L877-L888 | train |
Erotemic/utool | utool/util_dict.py | delete_dict_keys | def delete_dict_keys(dict_, key_list):
r"""
Removes items from a dictionary inplace. Keys that do not exist are
ignored.
Args:
dict_ (dict): dict like object with a __del__ attribute
key_list (list): list of keys that specify the items to remove
CommandLine:
python -m utool.util_dict --test-delete_dict_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'bread': 1, 'churches': 1, 'cider': 2, 'very small rocks': 2}
>>> key_list = ['duck', 'bread', 'cider']
>>> delete_dict_keys(dict_, key_list)
>>> result = ut.repr4(dict_, nl=False)
>>> print(result)
{'churches': 1, 'very small rocks': 2}
"""
invalid_keys = set(key_list) - set(dict_.keys())
valid_keys = set(key_list) - invalid_keys
for key in valid_keys:
del dict_[key]
return dict_ | python | def delete_dict_keys(dict_, key_list):
r"""
Removes items from a dictionary inplace. Keys that do not exist are
ignored.
Args:
dict_ (dict): dict like object with a __del__ attribute
key_list (list): list of keys that specify the items to remove
CommandLine:
python -m utool.util_dict --test-delete_dict_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'bread': 1, 'churches': 1, 'cider': 2, 'very small rocks': 2}
>>> key_list = ['duck', 'bread', 'cider']
>>> delete_dict_keys(dict_, key_list)
>>> result = ut.repr4(dict_, nl=False)
>>> print(result)
{'churches': 1, 'very small rocks': 2}
"""
invalid_keys = set(key_list) - set(dict_.keys())
valid_keys = set(key_list) - invalid_keys
for key in valid_keys:
del dict_[key]
return dict_ | [
"def",
"delete_dict_keys",
"(",
"dict_",
",",
"key_list",
")",
":",
"r",
"invalid_keys",
"=",
"set",
"(",
"key_list",
")",
"-",
"set",
"(",
"dict_",
".",
"keys",
"(",
")",
")",
"valid_keys",
"=",
"set",
"(",
"key_list",
")",
"-",
"invalid_keys",
"for",
"key",
"in",
"valid_keys",
":",
"del",
"dict_",
"[",
"key",
"]",
"return",
"dict_"
] | r"""
Removes items from a dictionary inplace. Keys that do not exist are
ignored.
Args:
dict_ (dict): dict like object with a __del__ attribute
key_list (list): list of keys that specify the items to remove
CommandLine:
python -m utool.util_dict --test-delete_dict_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {'bread': 1, 'churches': 1, 'cider': 2, 'very small rocks': 2}
>>> key_list = ['duck', 'bread', 'cider']
>>> delete_dict_keys(dict_, key_list)
>>> result = ut.repr4(dict_, nl=False)
>>> print(result)
{'churches': 1, 'very small rocks': 2} | [
"r",
"Removes",
"items",
"from",
"a",
"dictionary",
"inplace",
".",
"Keys",
"that",
"do",
"not",
"exist",
"are",
"ignored",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L891-L919 | train |
Erotemic/utool | utool/util_dict.py | dict_take_gen | def dict_take_gen(dict_, keys, *d):
r"""
generate multiple values from a dictionary
Args:
dict_ (dict):
keys (list):
Varargs:
d: if specified is default for key errors
CommandLine:
python -m utool.util_dict --test-dict_take_gen
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> result = list(dict_take_gen(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> try:
>>> print(list(dict_take_gen(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> print(result)
correctly got key error
"""
if isinstance(keys, six.string_types):
# hack for string keys that makes copy-past easier
keys = keys.split(', ')
if len(d) == 0:
# no default given throws key error
dictget = dict_.__getitem__
elif len(d) == 1:
# default given does not throw key erro
dictget = dict_.get
else:
raise ValueError('len(d) must be 1 or 0')
for key in keys:
if HAVE_NUMPY and isinstance(key, np.ndarray):
# recursive call
yield list(dict_take_gen(dict_, key, *d))
else:
yield dictget(key, *d) | python | def dict_take_gen(dict_, keys, *d):
r"""
generate multiple values from a dictionary
Args:
dict_ (dict):
keys (list):
Varargs:
d: if specified is default for key errors
CommandLine:
python -m utool.util_dict --test-dict_take_gen
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> result = list(dict_take_gen(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> try:
>>> print(list(dict_take_gen(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> print(result)
correctly got key error
"""
if isinstance(keys, six.string_types):
# hack for string keys that makes copy-past easier
keys = keys.split(', ')
if len(d) == 0:
# no default given throws key error
dictget = dict_.__getitem__
elif len(d) == 1:
# default given does not throw key erro
dictget = dict_.get
else:
raise ValueError('len(d) must be 1 or 0')
for key in keys:
if HAVE_NUMPY and isinstance(key, np.ndarray):
# recursive call
yield list(dict_take_gen(dict_, key, *d))
else:
yield dictget(key, *d) | [
"def",
"dict_take_gen",
"(",
"dict_",
",",
"keys",
",",
"*",
"d",
")",
":",
"r",
"if",
"isinstance",
"(",
"keys",
",",
"six",
".",
"string_types",
")",
":",
"keys",
"=",
"keys",
".",
"split",
"(",
"', '",
")",
"if",
"len",
"(",
"d",
")",
"==",
"0",
":",
"dictget",
"=",
"dict_",
".",
"__getitem__",
"elif",
"len",
"(",
"d",
")",
"==",
"1",
":",
"dictget",
"=",
"dict_",
".",
"get",
"else",
":",
"raise",
"ValueError",
"(",
"'len(d) must be 1 or 0'",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"key",
",",
"np",
".",
"ndarray",
")",
":",
"yield",
"list",
"(",
"dict_take_gen",
"(",
"dict_",
",",
"key",
",",
"*",
"d",
")",
")",
"else",
":",
"yield",
"dictget",
"(",
"key",
",",
"*",
"d",
")"
] | r"""
generate multiple values from a dictionary
Args:
dict_ (dict):
keys (list):
Varargs:
d: if specified is default for key errors
CommandLine:
python -m utool.util_dict --test-dict_take_gen
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> result = list(dict_take_gen(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> try:
>>> print(list(dict_take_gen(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> print(result)
correctly got key error | [
"r",
"generate",
"multiple",
"values",
"from",
"a",
"dictionary"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L925-L979 | train |
Erotemic/utool | utool/util_dict.py | dict_take | def dict_take(dict_, keys, *d):
""" get multiple values from a dictionary """
try:
return list(dict_take_gen(dict_, keys, *d))
except TypeError:
return list(dict_take_gen(dict_, keys, *d))[0] | python | def dict_take(dict_, keys, *d):
""" get multiple values from a dictionary """
try:
return list(dict_take_gen(dict_, keys, *d))
except TypeError:
return list(dict_take_gen(dict_, keys, *d))[0] | [
"def",
"dict_take",
"(",
"dict_",
",",
"keys",
",",
"*",
"d",
")",
":",
"try",
":",
"return",
"list",
"(",
"dict_take_gen",
"(",
"dict_",
",",
"keys",
",",
"*",
"d",
")",
")",
"except",
"TypeError",
":",
"return",
"list",
"(",
"dict_take_gen",
"(",
"dict_",
",",
"keys",
",",
"*",
"d",
")",
")",
"[",
"0",
"]"
] | get multiple values from a dictionary | [
"get",
"multiple",
"values",
"from",
"a",
"dictionary"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L982-L987 | train |
Erotemic/utool | utool/util_dict.py | dict_take_pop | def dict_take_pop(dict_, keys, *d):
""" like dict_take but pops values off
CommandLine:
python -m utool.util_dict --test-dict_take_pop
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 'other': None, 'another': 'foo', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> result = list(dict_take_pop(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print('after: ' + ut.repr4(dict_))
>>> assert len(dict_) == 2
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> try:
>>> print(list(dict_take_pop(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> assert len(dict_) == 0
>>> print('after: ' + ut.repr4(dict_))
>>> print(result)
correctly got key error
"""
if len(d) == 0:
return [dict_.pop(key) for key in keys]
elif len(d) == 1:
default = d[0]
return [dict_.pop(key, default) for key in keys]
else:
raise ValueError('len(d) must be 1 or 0') | python | def dict_take_pop(dict_, keys, *d):
""" like dict_take but pops values off
CommandLine:
python -m utool.util_dict --test-dict_take_pop
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 'other': None, 'another': 'foo', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> result = list(dict_take_pop(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print('after: ' + ut.repr4(dict_))
>>> assert len(dict_) == 2
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> try:
>>> print(list(dict_take_pop(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> assert len(dict_) == 0
>>> print('after: ' + ut.repr4(dict_))
>>> print(result)
correctly got key error
"""
if len(d) == 0:
return [dict_.pop(key) for key in keys]
elif len(d) == 1:
default = d[0]
return [dict_.pop(key, default) for key in keys]
else:
raise ValueError('len(d) must be 1 or 0') | [
"def",
"dict_take_pop",
"(",
"dict_",
",",
"keys",
",",
"*",
"d",
")",
":",
"if",
"len",
"(",
"d",
")",
"==",
"0",
":",
"return",
"[",
"dict_",
".",
"pop",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
"]",
"elif",
"len",
"(",
"d",
")",
"==",
"1",
":",
"default",
"=",
"d",
"[",
"0",
"]",
"return",
"[",
"dict_",
".",
"pop",
"(",
"key",
",",
"default",
")",
"for",
"key",
"in",
"keys",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'len(d) must be 1 or 0'",
")"
] | like dict_take but pops values off
CommandLine:
python -m utool.util_dict --test-dict_take_pop
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 'other': None, 'another': 'foo', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> result = list(dict_take_pop(dict_, keys, None))
>>> result = ut.repr4(result, nl=False)
>>> print('after: ' + ut.repr4(dict_))
>>> assert len(dict_) == 2
>>> print(result)
['a', 'b', 'c', None, None]
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: 'a', 2: 'b', 3: 'c'}
>>> keys = [1, 2, 3, 4, 5]
>>> print('before: ' + ut.repr4(dict_))
>>> try:
>>> print(list(dict_take_pop(dict_, keys)))
>>> result = 'did not get key error'
>>> except KeyError:
>>> result = 'correctly got key error'
>>> assert len(dict_) == 0
>>> print('after: ' + ut.repr4(dict_))
>>> print(result)
correctly got key error | [
"like",
"dict_take",
"but",
"pops",
"values",
"off"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1014-L1057 | train |
Erotemic/utool | utool/util_dict.py | dict_assign | def dict_assign(dict_, keys, vals):
""" simple method for assigning or setting values with a similar interface
to dict_take """
for key, val in zip(keys, vals):
dict_[key] = val | python | def dict_assign(dict_, keys, vals):
""" simple method for assigning or setting values with a similar interface
to dict_take """
for key, val in zip(keys, vals):
dict_[key] = val | [
"def",
"dict_assign",
"(",
"dict_",
",",
"keys",
",",
"vals",
")",
":",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"keys",
",",
"vals",
")",
":",
"dict_",
"[",
"key",
"]",
"=",
"val"
] | simple method for assigning or setting values with a similar interface
to dict_take | [
"simple",
"method",
"for",
"assigning",
"or",
"setting",
"values",
"with",
"a",
"similar",
"interface",
"to",
"dict_take"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1060-L1064 | train |
Erotemic/utool | utool/util_dict.py | dict_where_len0 | def dict_where_len0(dict_):
"""
Accepts a dict of lists. Returns keys that have vals with no length
"""
keys = np.array(dict_.keys())
flags = np.array(list(map(len, dict_.values()))) == 0
indices = np.where(flags)[0]
return keys[indices] | python | def dict_where_len0(dict_):
"""
Accepts a dict of lists. Returns keys that have vals with no length
"""
keys = np.array(dict_.keys())
flags = np.array(list(map(len, dict_.values()))) == 0
indices = np.where(flags)[0]
return keys[indices] | [
"def",
"dict_where_len0",
"(",
"dict_",
")",
":",
"keys",
"=",
"np",
".",
"array",
"(",
"dict_",
".",
"keys",
"(",
")",
")",
"flags",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"map",
"(",
"len",
",",
"dict_",
".",
"values",
"(",
")",
")",
")",
")",
"==",
"0",
"indices",
"=",
"np",
".",
"where",
"(",
"flags",
")",
"[",
"0",
"]",
"return",
"keys",
"[",
"indices",
"]"
] | Accepts a dict of lists. Returns keys that have vals with no length | [
"Accepts",
"a",
"dict",
"of",
"lists",
".",
"Returns",
"keys",
"that",
"have",
"vals",
"with",
"no",
"length"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1067-L1074 | train |
Erotemic/utool | utool/util_dict.py | dict_hist | def dict_hist(item_list, weight_list=None, ordered=False, labels=None):
r"""
Builds a histogram of items in item_list
Args:
item_list (list): list with hashable items (usually containing duplicates)
Returns:
dict : dictionary where the keys are items in item_list, and the values
are the number of times the item appears in item_list.
CommandLine:
python -m utool.util_dict --test-dict_hist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]
>>> hist_ = dict_hist(item_list)
>>> result = ut.repr2(hist_)
>>> print(result)
{1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}
"""
if labels is None:
# hist_ = defaultdict(lambda: 0)
hist_ = defaultdict(int)
else:
hist_ = {k: 0 for k in labels}
if weight_list is None:
# weight_list = it.repeat(1)
for item in item_list:
hist_[item] += 1
else:
for item, weight in zip(item_list, weight_list):
hist_[item] += weight
# hist_ = dict(hist_)
if ordered:
# import utool as ut
# key_order = ut.sortedby(list(hist_.keys()), list(hist_.values()))
getval = op.itemgetter(1)
key_order = [key for (key, value) in sorted(hist_.items(), key=getval)]
hist_ = order_dict_by(hist_, key_order)
return hist_ | python | def dict_hist(item_list, weight_list=None, ordered=False, labels=None):
r"""
Builds a histogram of items in item_list
Args:
item_list (list): list with hashable items (usually containing duplicates)
Returns:
dict : dictionary where the keys are items in item_list, and the values
are the number of times the item appears in item_list.
CommandLine:
python -m utool.util_dict --test-dict_hist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]
>>> hist_ = dict_hist(item_list)
>>> result = ut.repr2(hist_)
>>> print(result)
{1: 1, 2: 4, 39: 1, 900: 3, 1232: 2}
"""
if labels is None:
# hist_ = defaultdict(lambda: 0)
hist_ = defaultdict(int)
else:
hist_ = {k: 0 for k in labels}
if weight_list is None:
# weight_list = it.repeat(1)
for item in item_list:
hist_[item] += 1
else:
for item, weight in zip(item_list, weight_list):
hist_[item] += weight
# hist_ = dict(hist_)
if ordered:
# import utool as ut
# key_order = ut.sortedby(list(hist_.keys()), list(hist_.values()))
getval = op.itemgetter(1)
key_order = [key for (key, value) in sorted(hist_.items(), key=getval)]
hist_ = order_dict_by(hist_, key_order)
return hist_ | [
"def",
"dict_hist",
"(",
"item_list",
",",
"weight_list",
"=",
"None",
",",
"ordered",
"=",
"False",
",",
"labels",
"=",
"None",
")",
":",
"r",
"if",
"labels",
"is",
"None",
":",
"hist_",
"=",
"defaultdict",
"(",
"int",
")",
"else",
":",
"hist_",
"=",
"{",
"k",
":",
"0",
"for",
"k",
"in",
"labels",
"}",
"if",
"weight_list",
"is",
"None",
":",
"for",
"item",
"in",
"item_list",
":",
"hist_",
"[",
"item",
"]",
"+=",
"1",
"else",
":",
"for",
"item",
",",
"weight",
"in",
"zip",
"(",
"item_list",
",",
"weight_list",
")",
":",
"hist_",
"[",
"item",
"]",
"+=",
"weight",
"if",
"ordered",
":",
"getval",
"=",
"op",
".",
"itemgetter",
"(",
"1",
")",
"key_order",
"=",
"[",
"key",
"for",
"(",
"key",
",",
"value",
")",
"in",
"sorted",
"(",
"hist_",
".",
"items",
"(",
")",
",",
"key",
"=",
"getval",
")",
"]",
"hist_",
"=",
"order_dict_by",
"(",
"hist_",
",",
"key_order",
")",
"return",
"hist_"
] | r"""
Builds a histogram of items in item_list
Args:
item_list (list): list with hashable items (usually containing duplicates)
Returns:
dict : dictionary where the keys are items in item_list, and the values
are the number of times the item appears in item_list.
CommandLine:
python -m utool.util_dict --test-dict_hist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 39, 900, 1232, 900, 1232, 2, 2, 2, 900]
>>> hist_ = dict_hist(item_list)
>>> result = ut.repr2(hist_)
>>> print(result)
{1: 1, 2: 4, 39: 1, 900: 3, 1232: 2} | [
"r",
"Builds",
"a",
"histogram",
"of",
"items",
"in",
"item_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1236-L1279 | train |
Erotemic/utool | utool/util_dict.py | dict_isect_combine | def dict_isect_combine(dict1, dict2, combine_op=op.add):
""" Intersection of dict keys and combination of dict values """
keys3 = set(dict1.keys()).intersection(set(dict2.keys()))
dict3 = {key: combine_op(dict1[key], dict2[key]) for key in keys3}
return dict3 | python | def dict_isect_combine(dict1, dict2, combine_op=op.add):
""" Intersection of dict keys and combination of dict values """
keys3 = set(dict1.keys()).intersection(set(dict2.keys()))
dict3 = {key: combine_op(dict1[key], dict2[key]) for key in keys3}
return dict3 | [
"def",
"dict_isect_combine",
"(",
"dict1",
",",
"dict2",
",",
"combine_op",
"=",
"op",
".",
"add",
")",
":",
"keys3",
"=",
"set",
"(",
"dict1",
".",
"keys",
"(",
")",
")",
".",
"intersection",
"(",
"set",
"(",
"dict2",
".",
"keys",
"(",
")",
")",
")",
"dict3",
"=",
"{",
"key",
":",
"combine_op",
"(",
"dict1",
"[",
"key",
"]",
",",
"dict2",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"keys3",
"}",
"return",
"dict3"
] | Intersection of dict keys and combination of dict values | [
"Intersection",
"of",
"dict",
"keys",
"and",
"combination",
"of",
"dict",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1438-L1442 | train |
Erotemic/utool | utool/util_dict.py | dict_union_combine | def dict_union_combine(dict1, dict2, combine_op=op.add,
default=util_const.NoParam,
default2=util_const.NoParam):
"""
Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead
"""
keys3 = set(dict1.keys()).union(set(dict2.keys()))
if default is util_const.NoParam:
dict3 = {key: combine_op(dict1[key], dict2[key]) for key in keys3}
else:
if default2 is util_const.NoParam:
default2 = default
dict3 = {key: combine_op(dict1.get(key, default), dict2.get(key, default2))
for key in keys3}
return dict3 | python | def dict_union_combine(dict1, dict2, combine_op=op.add,
default=util_const.NoParam,
default2=util_const.NoParam):
"""
Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead
"""
keys3 = set(dict1.keys()).union(set(dict2.keys()))
if default is util_const.NoParam:
dict3 = {key: combine_op(dict1[key], dict2[key]) for key in keys3}
else:
if default2 is util_const.NoParam:
default2 = default
dict3 = {key: combine_op(dict1.get(key, default), dict2.get(key, default2))
for key in keys3}
return dict3 | [
"def",
"dict_union_combine",
"(",
"dict1",
",",
"dict2",
",",
"combine_op",
"=",
"op",
".",
"add",
",",
"default",
"=",
"util_const",
".",
"NoParam",
",",
"default2",
"=",
"util_const",
".",
"NoParam",
")",
":",
"keys3",
"=",
"set",
"(",
"dict1",
".",
"keys",
"(",
")",
")",
".",
"union",
"(",
"set",
"(",
"dict2",
".",
"keys",
"(",
")",
")",
")",
"if",
"default",
"is",
"util_const",
".",
"NoParam",
":",
"dict3",
"=",
"{",
"key",
":",
"combine_op",
"(",
"dict1",
"[",
"key",
"]",
",",
"dict2",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"keys3",
"}",
"else",
":",
"if",
"default2",
"is",
"util_const",
".",
"NoParam",
":",
"default2",
"=",
"default",
"dict3",
"=",
"{",
"key",
":",
"combine_op",
"(",
"dict1",
".",
"get",
"(",
"key",
",",
"default",
")",
",",
"dict2",
".",
"get",
"(",
"key",
",",
"default2",
")",
")",
"for",
"key",
"in",
"keys3",
"}",
"return",
"dict3"
] | Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead | [
"Combine",
"of",
"dict",
"keys",
"and",
"uses",
"dfault",
"value",
"when",
"key",
"does",
"not",
"exist"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1445-L1461 | train |
Erotemic/utool | utool/util_dict.py | dict_filter_nones | def dict_filter_nones(dict_):
r"""
Removes None values
Args:
dict_ (dict): a dictionary
Returns:
dict:
CommandLine:
python -m utool.util_dict --exec-dict_filter_nones
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # fails on python 3 because of dict None order
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: None, 2: 'blue', 3: 'four', None: 'fun'}
>>> dict2_ = dict_filter_nones(dict_)
>>> result = ut.repr4(dict2_, nl=False)
>>> print(result)
{None: 'fun', 2: 'blue', 3: 'four'}
"""
dict2_ = {
key: val
for key, val in six.iteritems(dict_)
if val is not None
}
return dict2_ | python | def dict_filter_nones(dict_):
r"""
Removes None values
Args:
dict_ (dict): a dictionary
Returns:
dict:
CommandLine:
python -m utool.util_dict --exec-dict_filter_nones
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # fails on python 3 because of dict None order
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: None, 2: 'blue', 3: 'four', None: 'fun'}
>>> dict2_ = dict_filter_nones(dict_)
>>> result = ut.repr4(dict2_, nl=False)
>>> print(result)
{None: 'fun', 2: 'blue', 3: 'four'}
"""
dict2_ = {
key: val
for key, val in six.iteritems(dict_)
if val is not None
}
return dict2_ | [
"def",
"dict_filter_nones",
"(",
"dict_",
")",
":",
"r",
"dict2_",
"=",
"{",
"key",
":",
"val",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"dict_",
")",
"if",
"val",
"is",
"not",
"None",
"}",
"return",
"dict2_"
] | r"""
Removes None values
Args:
dict_ (dict): a dictionary
Returns:
dict:
CommandLine:
python -m utool.util_dict --exec-dict_filter_nones
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # fails on python 3 because of dict None order
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> dict_ = {1: None, 2: 'blue', 3: 'four', None: 'fun'}
>>> dict2_ = dict_filter_nones(dict_)
>>> result = ut.repr4(dict2_, nl=False)
>>> print(result)
{None: 'fun', 2: 'blue', 3: 'four'} | [
"r",
"Removes",
"None",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1474-L1504 | train |
Erotemic/utool | utool/util_dict.py | groupby_tags | 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 | python | 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 | [
"def",
"groupby_tags",
"(",
"item_list",
",",
"tags_list",
")",
":",
"r",
"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"
] | 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'],
} | [
"r",
"case",
"where",
"an",
"item",
"can",
"belong",
"to",
"multiple",
"groups"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1507-L1552 | train |
Erotemic/utool | utool/util_dict.py | group_pairs | def group_pairs(pair_list):
"""
Groups a list of items using the first element in each pair as the item and
the second element as the groupid.
Args:
pair_list (list): list of 2-tuples (item, groupid)
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_items
"""
# Initialize dict of lists
groupid_to_items = defaultdict(list)
# Insert each item into the correct group
for item, groupid in pair_list:
groupid_to_items[groupid].append(item)
return groupid_to_items | python | def group_pairs(pair_list):
"""
Groups a list of items using the first element in each pair as the item and
the second element as the groupid.
Args:
pair_list (list): list of 2-tuples (item, groupid)
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_items
"""
# Initialize dict of lists
groupid_to_items = defaultdict(list)
# Insert each item into the correct group
for item, groupid in pair_list:
groupid_to_items[groupid].append(item)
return groupid_to_items | [
"def",
"group_pairs",
"(",
"pair_list",
")",
":",
"groupid_to_items",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"item",
",",
"groupid",
"in",
"pair_list",
":",
"groupid_to_items",
"[",
"groupid",
"]",
".",
"append",
"(",
"item",
")",
"return",
"groupid_to_items"
] | Groups a list of items using the first element in each pair as the item and
the second element as the groupid.
Args:
pair_list (list): list of 2-tuples (item, groupid)
Returns:
dict: groupid_to_items: maps a groupid to a list of items
SeeAlso:
group_items | [
"Groups",
"a",
"list",
"of",
"items",
"using",
"the",
"first",
"element",
"in",
"each",
"pair",
"as",
"the",
"item",
"and",
"the",
"second",
"element",
"as",
"the",
"groupid",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1560-L1579 | train |
Erotemic/utool | utool/util_dict.py | group_items | 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 | python | 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 | [
"def",
"group_items",
"(",
"items",
",",
"by",
"=",
"None",
",",
"sorted_",
"=",
"True",
")",
":",
"if",
"by",
"is",
"not",
"None",
":",
"pairs",
"=",
"list",
"(",
"zip",
"(",
"by",
",",
"items",
")",
")",
"if",
"sorted_",
":",
"try",
":",
"pairs",
"=",
"sorted",
"(",
"pairs",
",",
"key",
"=",
"op",
".",
"itemgetter",
"(",
"0",
")",
")",
"except",
"TypeError",
":",
"pairs",
"=",
"sorted",
"(",
"pairs",
",",
"key",
"=",
"lambda",
"tup",
":",
"str",
"(",
"tup",
"[",
"0",
"]",
")",
")",
"else",
":",
"pairs",
"=",
"items",
"groupid_to_items",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"groupid",
",",
"item",
"in",
"pairs",
":",
"groupid_to_items",
"[",
"groupid",
"]",
".",
"append",
"(",
"item",
")",
"return",
"groupid_to_items"
] | 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']} | [
"Groups",
"a",
"list",
"of",
"items",
"by",
"group",
"id",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1582-L1635 | train |
Erotemic/utool | utool/util_dict.py | hierarchical_group_items | def hierarchical_group_items(item_list, groupids_list):
"""
Generalization of group_item. Convert a flast list of ids into a heirarchical dictionary.
TODO: move to util_dict
Reference:
http://stackoverflow.com/questions/10193235/python-translate-a-table-to-a-hierarchical-dictionary
Args:
item_list (list):
groupids_list (list):
CommandLine:
python -m utool.util_dict --exec-hierarchical_group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 2, 2]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {1: [1, 2], 2: [3, 4]}
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 = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {1: [7], 2: [3], 3: [1, 5]},
2: {1: [6, 8], 2: [2, 4]},
}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 1, 2], [1, 2, 2, 2], [1, 3, 1, 1]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {
1: {1: [1]},
2: {1: [3], 3: [2]},
},
2: {
2: {1: [4]},
},
}
"""
# Construct a defaultdict type with the appropriate number of levels
num_groups = len(groupids_list)
leaf_type = partial(defaultdict, list)
if num_groups > 1:
node_type = leaf_type
for _ in range(len(groupids_list) - 2):
node_type = partial(defaultdict, node_type)
root_type = node_type
elif num_groups == 1:
root_type = list
else:
raise ValueError('must suply groupids')
tree = defaultdict(root_type)
#
groupid_tuple_list = list(zip(*groupids_list))
for groupid_tuple, item in zip(groupid_tuple_list, item_list):
node = tree
for groupid in groupid_tuple:
node = node[groupid]
node.append(item)
return tree | python | def hierarchical_group_items(item_list, groupids_list):
"""
Generalization of group_item. Convert a flast list of ids into a heirarchical dictionary.
TODO: move to util_dict
Reference:
http://stackoverflow.com/questions/10193235/python-translate-a-table-to-a-hierarchical-dictionary
Args:
item_list (list):
groupids_list (list):
CommandLine:
python -m utool.util_dict --exec-hierarchical_group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 2, 2]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {1: [1, 2], 2: [3, 4]}
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 = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {1: [7], 2: [3], 3: [1, 5]},
2: {1: [6, 8], 2: [2, 4]},
}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 1, 2], [1, 2, 2, 2], [1, 3, 1, 1]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {
1: {1: [1]},
2: {1: [3], 3: [2]},
},
2: {
2: {1: [4]},
},
}
"""
# Construct a defaultdict type with the appropriate number of levels
num_groups = len(groupids_list)
leaf_type = partial(defaultdict, list)
if num_groups > 1:
node_type = leaf_type
for _ in range(len(groupids_list) - 2):
node_type = partial(defaultdict, node_type)
root_type = node_type
elif num_groups == 1:
root_type = list
else:
raise ValueError('must suply groupids')
tree = defaultdict(root_type)
#
groupid_tuple_list = list(zip(*groupids_list))
for groupid_tuple, item in zip(groupid_tuple_list, item_list):
node = tree
for groupid in groupid_tuple:
node = node[groupid]
node.append(item)
return tree | [
"def",
"hierarchical_group_items",
"(",
"item_list",
",",
"groupids_list",
")",
":",
"num_groups",
"=",
"len",
"(",
"groupids_list",
")",
"leaf_type",
"=",
"partial",
"(",
"defaultdict",
",",
"list",
")",
"if",
"num_groups",
">",
"1",
":",
"node_type",
"=",
"leaf_type",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"groupids_list",
")",
"-",
"2",
")",
":",
"node_type",
"=",
"partial",
"(",
"defaultdict",
",",
"node_type",
")",
"root_type",
"=",
"node_type",
"elif",
"num_groups",
"==",
"1",
":",
"root_type",
"=",
"list",
"else",
":",
"raise",
"ValueError",
"(",
"'must suply groupids'",
")",
"tree",
"=",
"defaultdict",
"(",
"root_type",
")",
"groupid_tuple_list",
"=",
"list",
"(",
"zip",
"(",
"*",
"groupids_list",
")",
")",
"for",
"groupid_tuple",
",",
"item",
"in",
"zip",
"(",
"groupid_tuple_list",
",",
"item_list",
")",
":",
"node",
"=",
"tree",
"for",
"groupid",
"in",
"groupid_tuple",
":",
"node",
"=",
"node",
"[",
"groupid",
"]",
"node",
".",
"append",
"(",
"item",
")",
"return",
"tree"
] | Generalization of group_item. Convert a flast list of ids into a heirarchical dictionary.
TODO: move to util_dict
Reference:
http://stackoverflow.com/questions/10193235/python-translate-a-table-to-a-hierarchical-dictionary
Args:
item_list (list):
groupids_list (list):
CommandLine:
python -m utool.util_dict --exec-hierarchical_group_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 2, 2]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {1: [1, 2], 2: [3, 4]}
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 = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {1: [7], 2: [3], 3: [1, 5]},
2: {1: [6, 8], 2: [2, 4]},
}
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4]
>>> groupids_list = [[1, 1, 1, 2], [1, 2, 2, 2], [1, 3, 1, 1]]
>>> tree = hierarchical_group_items(item_list, groupids_list)
>>> result = ('tree = ' + ut.repr4(tree, nl=len(groupids_list) - 1))
>>> print(result)
tree = {
1: {
1: {1: [1]},
2: {1: [3], 3: [2]},
},
2: {
2: {1: [4]},
},
} | [
"Generalization",
"of",
"group_item",
".",
"Convert",
"a",
"flast",
"list",
"of",
"ids",
"into",
"a",
"heirarchical",
"dictionary",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1638-L1719 | train |
Erotemic/utool | utool/util_dict.py | hierarchical_map_vals | 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) | python | 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) | [
"def",
"hierarchical_map_vals",
"(",
"func",
",",
"node",
",",
"max_depth",
"=",
"None",
",",
"depth",
"=",
"0",
")",
":",
"if",
"not",
"hasattr",
"(",
"node",
",",
"'items'",
")",
":",
"return",
"func",
"(",
"node",
")",
"elif",
"max_depth",
"is",
"not",
"None",
"and",
"depth",
">=",
"max_depth",
":",
"return",
"map_dict_vals",
"(",
"func",
",",
"node",
")",
"else",
":",
"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",
")"
] | 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) | [
"node",
"is",
"a",
"dict",
"tree",
"like",
"structure",
"with",
"leaves",
"of",
"type",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1750-L1821 | train |
Erotemic/utool | utool/util_dict.py | sort_dict | 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 | python | 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 | [
"def",
"sort_dict",
"(",
"dict_",
",",
"part",
"=",
"'keys'",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"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"
] | 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},
] | [
"sorts",
"a",
"dictionary",
"by",
"its",
"values",
"or",
"its",
"keys"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1955-L2003 | train |
Erotemic/utool | utool/util_dict.py | order_dict_by | 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 | python | 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 | [
"def",
"order_dict_by",
"(",
"dict_",
",",
"key_order",
")",
":",
"r",
"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"
] | 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}' | [
"r",
"Reorders",
"items",
"in",
"a",
"dictionary",
"according",
"to",
"a",
"custom",
"key",
"order"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2006-L2038 | train |
Erotemic/utool | utool/util_dict.py | iteritems_sorted | def iteritems_sorted(dict_):
""" change to iteritems ordered """
if isinstance(dict_, OrderedDict):
return six.iteritems(dict_)
else:
return iter(sorted(six.iteritems(dict_))) | python | def iteritems_sorted(dict_):
""" change to iteritems ordered """
if isinstance(dict_, OrderedDict):
return six.iteritems(dict_)
else:
return iter(sorted(six.iteritems(dict_))) | [
"def",
"iteritems_sorted",
"(",
"dict_",
")",
":",
"if",
"isinstance",
"(",
"dict_",
",",
"OrderedDict",
")",
":",
"return",
"six",
".",
"iteritems",
"(",
"dict_",
")",
"else",
":",
"return",
"iter",
"(",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"dict_",
")",
")",
")"
] | change to iteritems ordered | [
"change",
"to",
"iteritems",
"ordered"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2041-L2046 | train |
Erotemic/utool | utool/util_dict.py | flatten_dict_vals | def flatten_dict_vals(dict_):
"""
Flattens only values in a heirarchical dictionary, keys are nested.
"""
if isinstance(dict_, dict):
return dict([
((key, augkey), augval)
for key, val in dict_.items()
for augkey, augval in flatten_dict_vals(val).items()
])
else:
return {None: dict_} | python | def flatten_dict_vals(dict_):
"""
Flattens only values in a heirarchical dictionary, keys are nested.
"""
if isinstance(dict_, dict):
return dict([
((key, augkey), augval)
for key, val in dict_.items()
for augkey, augval in flatten_dict_vals(val).items()
])
else:
return {None: dict_} | [
"def",
"flatten_dict_vals",
"(",
"dict_",
")",
":",
"if",
"isinstance",
"(",
"dict_",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"(",
"key",
",",
"augkey",
")",
",",
"augval",
")",
"for",
"key",
",",
"val",
"in",
"dict_",
".",
"items",
"(",
")",
"for",
"augkey",
",",
"augval",
"in",
"flatten_dict_vals",
"(",
"val",
")",
".",
"items",
"(",
")",
"]",
")",
"else",
":",
"return",
"{",
"None",
":",
"dict_",
"}"
] | Flattens only values in a heirarchical dictionary, keys are nested. | [
"Flattens",
"only",
"values",
"in",
"a",
"heirarchical",
"dictionary",
"keys",
"are",
"nested",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2054-L2065 | train |
Erotemic/utool | utool/util_dict.py | depth_atleast | def depth_atleast(list_, depth):
r"""
Returns if depth of list is at least ``depth``
Args:
list_ (list):
depth (int):
Returns:
bool: True
CommandLine:
python -m utool.util_dict --exec-depth_atleast --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> list_ = [[[[0]]], [[0]]]
>>> depth = 0
>>> result = [depth_atleast(list_, depth) for depth in range(0, 7)]
>>> print(result)
"""
if depth == 0:
return True
else:
try:
return all([depth_atleast(item, depth - 1) for item in list_])
except TypeError:
return False | python | def depth_atleast(list_, depth):
r"""
Returns if depth of list is at least ``depth``
Args:
list_ (list):
depth (int):
Returns:
bool: True
CommandLine:
python -m utool.util_dict --exec-depth_atleast --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> list_ = [[[[0]]], [[0]]]
>>> depth = 0
>>> result = [depth_atleast(list_, depth) for depth in range(0, 7)]
>>> print(result)
"""
if depth == 0:
return True
else:
try:
return all([depth_atleast(item, depth - 1) for item in list_])
except TypeError:
return False | [
"def",
"depth_atleast",
"(",
"list_",
",",
"depth",
")",
":",
"r",
"if",
"depth",
"==",
"0",
":",
"return",
"True",
"else",
":",
"try",
":",
"return",
"all",
"(",
"[",
"depth_atleast",
"(",
"item",
",",
"depth",
"-",
"1",
")",
"for",
"item",
"in",
"list_",
"]",
")",
"except",
"TypeError",
":",
"return",
"False"
] | r"""
Returns if depth of list is at least ``depth``
Args:
list_ (list):
depth (int):
Returns:
bool: True
CommandLine:
python -m utool.util_dict --exec-depth_atleast --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>> import utool as ut
>>> list_ = [[[[0]]], [[0]]]
>>> depth = 0
>>> result = [depth_atleast(list_, depth) for depth in range(0, 7)]
>>> print(result) | [
"r",
"Returns",
"if",
"depth",
"of",
"list",
"is",
"at",
"least",
"depth"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2096-L2125 | train |
glormph/msstitch | src/app/actions/mzidtsv/splitmerge.py | get_splitcolnr | def get_splitcolnr(header, bioset, splitcol):
"""Returns column nr on which to split PSM table. Chooses from flags
given via bioset and splitcol"""
if bioset:
return header.index(mzidtsvdata.HEADER_SETNAME)
elif splitcol is not None:
return splitcol - 1
else:
raise RuntimeError('Must specify either --bioset or --splitcol') | python | def get_splitcolnr(header, bioset, splitcol):
"""Returns column nr on which to split PSM table. Chooses from flags
given via bioset and splitcol"""
if bioset:
return header.index(mzidtsvdata.HEADER_SETNAME)
elif splitcol is not None:
return splitcol - 1
else:
raise RuntimeError('Must specify either --bioset or --splitcol') | [
"def",
"get_splitcolnr",
"(",
"header",
",",
"bioset",
",",
"splitcol",
")",
":",
"if",
"bioset",
":",
"return",
"header",
".",
"index",
"(",
"mzidtsvdata",
".",
"HEADER_SETNAME",
")",
"elif",
"splitcol",
"is",
"not",
"None",
":",
"return",
"splitcol",
"-",
"1",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Must specify either --bioset or --splitcol'",
")"
] | Returns column nr on which to split PSM table. Chooses from flags
given via bioset and splitcol | [
"Returns",
"column",
"nr",
"on",
"which",
"to",
"split",
"PSM",
"table",
".",
"Chooses",
"from",
"flags",
"given",
"via",
"bioset",
"and",
"splitcol"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/splitmerge.py#L14-L22 | train |
glormph/msstitch | src/app/actions/mzidtsv/splitmerge.py | generate_psms_split | def generate_psms_split(fn, oldheader, bioset, splitcol):
"""Loops PSMs and outputs dictionaries passed to writer. Dictionaries
contain the PSMs and info to which split pool the
respective PSM belongs"""
try:
splitcolnr = get_splitcolnr(oldheader, bioset, splitcol)
except IndexError:
raise RuntimeError('Cannot find bioset header column in '
'input file {}, though --bioset has '
'been passed'.format(fn))
for psm in tsvreader.generate_tsv_psms(fn, oldheader):
yield {'psm': psm,
'split_pool': psm[oldheader[splitcolnr]]
} | python | def generate_psms_split(fn, oldheader, bioset, splitcol):
"""Loops PSMs and outputs dictionaries passed to writer. Dictionaries
contain the PSMs and info to which split pool the
respective PSM belongs"""
try:
splitcolnr = get_splitcolnr(oldheader, bioset, splitcol)
except IndexError:
raise RuntimeError('Cannot find bioset header column in '
'input file {}, though --bioset has '
'been passed'.format(fn))
for psm in tsvreader.generate_tsv_psms(fn, oldheader):
yield {'psm': psm,
'split_pool': psm[oldheader[splitcolnr]]
} | [
"def",
"generate_psms_split",
"(",
"fn",
",",
"oldheader",
",",
"bioset",
",",
"splitcol",
")",
":",
"try",
":",
"splitcolnr",
"=",
"get_splitcolnr",
"(",
"oldheader",
",",
"bioset",
",",
"splitcol",
")",
"except",
"IndexError",
":",
"raise",
"RuntimeError",
"(",
"'Cannot find bioset header column in '",
"'input file {}, though --bioset has '",
"'been passed'",
".",
"format",
"(",
"fn",
")",
")",
"for",
"psm",
"in",
"tsvreader",
".",
"generate_tsv_psms",
"(",
"fn",
",",
"oldheader",
")",
":",
"yield",
"{",
"'psm'",
":",
"psm",
",",
"'split_pool'",
":",
"psm",
"[",
"oldheader",
"[",
"splitcolnr",
"]",
"]",
"}"
] | Loops PSMs and outputs dictionaries passed to writer. Dictionaries
contain the PSMs and info to which split pool the
respective PSM belongs | [
"Loops",
"PSMs",
"and",
"outputs",
"dictionaries",
"passed",
"to",
"writer",
".",
"Dictionaries",
"contain",
"the",
"PSMs",
"and",
"info",
"to",
"which",
"split",
"pool",
"the",
"respective",
"PSM",
"belongs"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/splitmerge.py#L25-L38 | train |
Erotemic/utool | utool/_internal/randomwrap.py | rnumlistwithoutreplacement | def rnumlistwithoutreplacement(min, max):
"""Returns a randomly ordered list of the integers between min and max"""
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
requestparam = build_request_parameterNR(min, max)
request = urllib.request.Request(requestparam)
request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
opener = urllib.request.build_opener()
numlist = opener.open(request).read()
return numlist.split() | python | def rnumlistwithoutreplacement(min, max):
"""Returns a randomly ordered list of the integers between min and max"""
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
requestparam = build_request_parameterNR(min, max)
request = urllib.request.Request(requestparam)
request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
opener = urllib.request.build_opener()
numlist = opener.open(request).read()
return numlist.split() | [
"def",
"rnumlistwithoutreplacement",
"(",
"min",
",",
"max",
")",
":",
"if",
"checkquota",
"(",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Your www.random.org quota has already run out.\"",
")",
"requestparam",
"=",
"build_request_parameterNR",
"(",
"min",
",",
"max",
")",
"request",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"requestparam",
")",
"request",
".",
"add_header",
"(",
"'User-Agent'",
",",
"'randomwrapy/0.1 very alpha'",
")",
"opener",
"=",
"urllib",
".",
"request",
".",
"build_opener",
"(",
")",
"numlist",
"=",
"opener",
".",
"open",
"(",
"request",
")",
".",
"read",
"(",
")",
"return",
"numlist",
".",
"split",
"(",
")"
] | Returns a randomly ordered list of the integers between min and max | [
"Returns",
"a",
"randomly",
"ordered",
"list",
"of",
"the",
"integers",
"between",
"min",
"and",
"max"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/randomwrap.py#L54-L63 | train |
Erotemic/utool | utool/_internal/randomwrap.py | rnumlistwithreplacement | def rnumlistwithreplacement(howmany, max, min=0):
"""Returns a list of howmany integers with a maximum value = max.
The minimum value defaults to zero."""
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
requestparam = build_request_parameterWR(howmany, min, max)
request = urllib.request.Request(requestparam)
request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
opener = urllib.request.build_opener()
numlist = opener.open(request).read()
return numlist.split() | python | def rnumlistwithreplacement(howmany, max, min=0):
"""Returns a list of howmany integers with a maximum value = max.
The minimum value defaults to zero."""
if checkquota() < 1:
raise Exception("Your www.random.org quota has already run out.")
requestparam = build_request_parameterWR(howmany, min, max)
request = urllib.request.Request(requestparam)
request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
opener = urllib.request.build_opener()
numlist = opener.open(request).read()
return numlist.split() | [
"def",
"rnumlistwithreplacement",
"(",
"howmany",
",",
"max",
",",
"min",
"=",
"0",
")",
":",
"if",
"checkquota",
"(",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Your www.random.org quota has already run out.\"",
")",
"requestparam",
"=",
"build_request_parameterWR",
"(",
"howmany",
",",
"min",
",",
"max",
")",
"request",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"requestparam",
")",
"request",
".",
"add_header",
"(",
"'User-Agent'",
",",
"'randomwrapy/0.1 very alpha'",
")",
"opener",
"=",
"urllib",
".",
"request",
".",
"build_opener",
"(",
")",
"numlist",
"=",
"opener",
".",
"open",
"(",
"request",
")",
".",
"read",
"(",
")",
"return",
"numlist",
".",
"split",
"(",
")"
] | Returns a list of howmany integers with a maximum value = max.
The minimum value defaults to zero. | [
"Returns",
"a",
"list",
"of",
"howmany",
"integers",
"with",
"a",
"maximum",
"value",
"=",
"max",
".",
"The",
"minimum",
"value",
"defaults",
"to",
"zero",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/randomwrap.py#L75-L85 | train |
Erotemic/utool | utool/util_num.py | num_fmt | def num_fmt(num, max_digits=None):
r"""
Weird function. Not very well written. Very special case-y
Args:
num (int or float):
max_digits (int):
Returns:
str:
CommandLine:
python -m utool.util_num --test-num_fmt
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_num import * # NOQA
>>> # build test data
>>> num_list = [0, 0.0, 1.2, 1003232, 41431232., .0000000343, -.443243]
>>> max_digits = None
>>> # execute function
>>> result = [num_fmt(num, max_digits) for num in num_list]
>>> # verify results
>>> print(result)
['0', '0.0', '1.2', '1,003,232', '41431232.0', '0.0', '-0.443']
"""
if num is None:
return 'None'
def num_in_mag(num, mag):
return mag > num and num > (-1 * mag)
if max_digits is None:
# TODO: generalize
if num_in_mag(num, 1):
if num_in_mag(num, .1):
max_digits = 4
else:
max_digits = 3
else:
max_digits = 1
if util_type.is_float(num):
num_str = ('%.' + str(max_digits) + 'f') % num
# Handle trailing and leading zeros
num_str = num_str.rstrip('0').lstrip('0')
if num_str.startswith('.'):
num_str = '0' + num_str
if num_str.endswith('.'):
num_str = num_str + '0'
return num_str
elif util_type.is_int(num):
return int_comma_str(num)
else:
return '%r' | python | def num_fmt(num, max_digits=None):
r"""
Weird function. Not very well written. Very special case-y
Args:
num (int or float):
max_digits (int):
Returns:
str:
CommandLine:
python -m utool.util_num --test-num_fmt
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_num import * # NOQA
>>> # build test data
>>> num_list = [0, 0.0, 1.2, 1003232, 41431232., .0000000343, -.443243]
>>> max_digits = None
>>> # execute function
>>> result = [num_fmt(num, max_digits) for num in num_list]
>>> # verify results
>>> print(result)
['0', '0.0', '1.2', '1,003,232', '41431232.0', '0.0', '-0.443']
"""
if num is None:
return 'None'
def num_in_mag(num, mag):
return mag > num and num > (-1 * mag)
if max_digits is None:
# TODO: generalize
if num_in_mag(num, 1):
if num_in_mag(num, .1):
max_digits = 4
else:
max_digits = 3
else:
max_digits = 1
if util_type.is_float(num):
num_str = ('%.' + str(max_digits) + 'f') % num
# Handle trailing and leading zeros
num_str = num_str.rstrip('0').lstrip('0')
if num_str.startswith('.'):
num_str = '0' + num_str
if num_str.endswith('.'):
num_str = num_str + '0'
return num_str
elif util_type.is_int(num):
return int_comma_str(num)
else:
return '%r' | [
"def",
"num_fmt",
"(",
"num",
",",
"max_digits",
"=",
"None",
")",
":",
"r",
"if",
"num",
"is",
"None",
":",
"return",
"'None'",
"def",
"num_in_mag",
"(",
"num",
",",
"mag",
")",
":",
"return",
"mag",
">",
"num",
"and",
"num",
">",
"(",
"-",
"1",
"*",
"mag",
")",
"if",
"max_digits",
"is",
"None",
":",
"if",
"num_in_mag",
"(",
"num",
",",
"1",
")",
":",
"if",
"num_in_mag",
"(",
"num",
",",
".1",
")",
":",
"max_digits",
"=",
"4",
"else",
":",
"max_digits",
"=",
"3",
"else",
":",
"max_digits",
"=",
"1",
"if",
"util_type",
".",
"is_float",
"(",
"num",
")",
":",
"num_str",
"=",
"(",
"'%.'",
"+",
"str",
"(",
"max_digits",
")",
"+",
"'f'",
")",
"%",
"num",
"num_str",
"=",
"num_str",
".",
"rstrip",
"(",
"'0'",
")",
".",
"lstrip",
"(",
"'0'",
")",
"if",
"num_str",
".",
"startswith",
"(",
"'.'",
")",
":",
"num_str",
"=",
"'0'",
"+",
"num_str",
"if",
"num_str",
".",
"endswith",
"(",
"'.'",
")",
":",
"num_str",
"=",
"num_str",
"+",
"'0'",
"return",
"num_str",
"elif",
"util_type",
".",
"is_int",
"(",
"num",
")",
":",
"return",
"int_comma_str",
"(",
"num",
")",
"else",
":",
"return",
"'%r'"
] | r"""
Weird function. Not very well written. Very special case-y
Args:
num (int or float):
max_digits (int):
Returns:
str:
CommandLine:
python -m utool.util_num --test-num_fmt
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_num import * # NOQA
>>> # build test data
>>> num_list = [0, 0.0, 1.2, 1003232, 41431232., .0000000343, -.443243]
>>> max_digits = None
>>> # execute function
>>> result = [num_fmt(num, max_digits) for num in num_list]
>>> # verify results
>>> print(result)
['0', '0.0', '1.2', '1,003,232', '41431232.0', '0.0', '-0.443'] | [
"r",
"Weird",
"function",
".",
"Not",
"very",
"well",
"written",
".",
"Very",
"special",
"case",
"-",
"y"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_num.py#L82-L133 | train |
YuriyGuts/pygoose | pygoose/kg/project.py | Project.load_feature_lists | def load_feature_lists(self, feature_lists):
"""
Load pickled features for train and test sets, assuming they are saved
in the `features` folder along with their column names.
Args:
feature_lists: A list containing the names of the feature lists to load.
Returns:
A tuple containing 3 items: train dataframe, test dataframe,
and a list describing the index ranges for the feature lists.
"""
column_names = []
feature_ranges = []
running_feature_count = 0
for list_id in feature_lists:
feature_list_names = load_lines(self.features_dir + 'X_train_{}.names'.format(list_id))
column_names.extend(feature_list_names)
start_index = running_feature_count
end_index = running_feature_count + len(feature_list_names) - 1
running_feature_count += len(feature_list_names)
feature_ranges.append([list_id, start_index, end_index])
X_train = np.hstack([
load(self.features_dir + 'X_train_{}.pickle'.format(list_id))
for list_id in feature_lists
])
X_test = np.hstack([
load(self.features_dir + 'X_test_{}.pickle'.format(list_id))
for list_id in feature_lists
])
df_train = pd.DataFrame(X_train, columns=column_names)
df_test = pd.DataFrame(X_test, columns=column_names)
return df_train, df_test, feature_ranges | python | def load_feature_lists(self, feature_lists):
"""
Load pickled features for train and test sets, assuming they are saved
in the `features` folder along with their column names.
Args:
feature_lists: A list containing the names of the feature lists to load.
Returns:
A tuple containing 3 items: train dataframe, test dataframe,
and a list describing the index ranges for the feature lists.
"""
column_names = []
feature_ranges = []
running_feature_count = 0
for list_id in feature_lists:
feature_list_names = load_lines(self.features_dir + 'X_train_{}.names'.format(list_id))
column_names.extend(feature_list_names)
start_index = running_feature_count
end_index = running_feature_count + len(feature_list_names) - 1
running_feature_count += len(feature_list_names)
feature_ranges.append([list_id, start_index, end_index])
X_train = np.hstack([
load(self.features_dir + 'X_train_{}.pickle'.format(list_id))
for list_id in feature_lists
])
X_test = np.hstack([
load(self.features_dir + 'X_test_{}.pickle'.format(list_id))
for list_id in feature_lists
])
df_train = pd.DataFrame(X_train, columns=column_names)
df_test = pd.DataFrame(X_test, columns=column_names)
return df_train, df_test, feature_ranges | [
"def",
"load_feature_lists",
"(",
"self",
",",
"feature_lists",
")",
":",
"column_names",
"=",
"[",
"]",
"feature_ranges",
"=",
"[",
"]",
"running_feature_count",
"=",
"0",
"for",
"list_id",
"in",
"feature_lists",
":",
"feature_list_names",
"=",
"load_lines",
"(",
"self",
".",
"features_dir",
"+",
"'X_train_{}.names'",
".",
"format",
"(",
"list_id",
")",
")",
"column_names",
".",
"extend",
"(",
"feature_list_names",
")",
"start_index",
"=",
"running_feature_count",
"end_index",
"=",
"running_feature_count",
"+",
"len",
"(",
"feature_list_names",
")",
"-",
"1",
"running_feature_count",
"+=",
"len",
"(",
"feature_list_names",
")",
"feature_ranges",
".",
"append",
"(",
"[",
"list_id",
",",
"start_index",
",",
"end_index",
"]",
")",
"X_train",
"=",
"np",
".",
"hstack",
"(",
"[",
"load",
"(",
"self",
".",
"features_dir",
"+",
"'X_train_{}.pickle'",
".",
"format",
"(",
"list_id",
")",
")",
"for",
"list_id",
"in",
"feature_lists",
"]",
")",
"X_test",
"=",
"np",
".",
"hstack",
"(",
"[",
"load",
"(",
"self",
".",
"features_dir",
"+",
"'X_test_{}.pickle'",
".",
"format",
"(",
"list_id",
")",
")",
"for",
"list_id",
"in",
"feature_lists",
"]",
")",
"df_train",
"=",
"pd",
".",
"DataFrame",
"(",
"X_train",
",",
"columns",
"=",
"column_names",
")",
"df_test",
"=",
"pd",
".",
"DataFrame",
"(",
"X_test",
",",
"columns",
"=",
"column_names",
")",
"return",
"df_train",
",",
"df_test",
",",
"feature_ranges"
] | Load pickled features for train and test sets, assuming they are saved
in the `features` folder along with their column names.
Args:
feature_lists: A list containing the names of the feature lists to load.
Returns:
A tuple containing 3 items: train dataframe, test dataframe,
and a list describing the index ranges for the feature lists. | [
"Load",
"pickled",
"features",
"for",
"train",
"and",
"test",
"sets",
"assuming",
"they",
"are",
"saved",
"in",
"the",
"features",
"folder",
"along",
"with",
"their",
"column",
"names",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L89-L126 | train |
YuriyGuts/pygoose | pygoose/kg/project.py | Project.save_features | def save_features(self, train_features, test_features, feature_names, feature_list_id):
"""
Save features for the training and test sets to disk, along with their metadata.
Args:
train_features: A NumPy array of features for the training set.
test_features: A NumPy array of features for the test set.
feature_names: A list containing the names of the feature columns.
feature_list_id: The name for this feature list.
"""
self.save_feature_names(feature_names, feature_list_id)
self.save_feature_list(train_features, 'train', feature_list_id)
self.save_feature_list(test_features, 'test', feature_list_id) | python | def save_features(self, train_features, test_features, feature_names, feature_list_id):
"""
Save features for the training and test sets to disk, along with their metadata.
Args:
train_features: A NumPy array of features for the training set.
test_features: A NumPy array of features for the test set.
feature_names: A list containing the names of the feature columns.
feature_list_id: The name for this feature list.
"""
self.save_feature_names(feature_names, feature_list_id)
self.save_feature_list(train_features, 'train', feature_list_id)
self.save_feature_list(test_features, 'test', feature_list_id) | [
"def",
"save_features",
"(",
"self",
",",
"train_features",
",",
"test_features",
",",
"feature_names",
",",
"feature_list_id",
")",
":",
"self",
".",
"save_feature_names",
"(",
"feature_names",
",",
"feature_list_id",
")",
"self",
".",
"save_feature_list",
"(",
"train_features",
",",
"'train'",
",",
"feature_list_id",
")",
"self",
".",
"save_feature_list",
"(",
"test_features",
",",
"'test'",
",",
"feature_list_id",
")"
] | Save features for the training and test sets to disk, along with their metadata.
Args:
train_features: A NumPy array of features for the training set.
test_features: A NumPy array of features for the test set.
feature_names: A list containing the names of the feature columns.
feature_list_id: The name for this feature list. | [
"Save",
"features",
"for",
"the",
"training",
"and",
"test",
"sets",
"to",
"disk",
"along",
"with",
"their",
"metadata",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L128-L141 | train |
YuriyGuts/pygoose | pygoose/kg/project.py | Project.discover | def discover():
"""
Automatically discover the paths to various data folders in this project
and compose a Project instance.
Returns:
A constructed Project object.
Raises:
ValueError: if the paths could not be figured out automatically.
In this case, you have to create a Project manually using the initializer.
"""
# Try ../data: we're most likely running a Jupyter notebook from the 'notebooks' directory
candidate_path = os.path.abspath(os.path.join(os.curdir, os.pardir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.path.join(candidate_path, os.pardir)))
# Try ./data
candidate_path = os.path.abspath(os.path.join(os.curdir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.curdir))
# Try ../../data
candidate_path = os.path.abspath(os.path.join(os.curdir, os.pardir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.path.join(candidate_path, os.pardir, os.pardir)))
# Out of ideas at this point.
raise ValueError('Cannot discover the structure of the project. Make sure that the data directory exists') | python | def discover():
"""
Automatically discover the paths to various data folders in this project
and compose a Project instance.
Returns:
A constructed Project object.
Raises:
ValueError: if the paths could not be figured out automatically.
In this case, you have to create a Project manually using the initializer.
"""
# Try ../data: we're most likely running a Jupyter notebook from the 'notebooks' directory
candidate_path = os.path.abspath(os.path.join(os.curdir, os.pardir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.path.join(candidate_path, os.pardir)))
# Try ./data
candidate_path = os.path.abspath(os.path.join(os.curdir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.curdir))
# Try ../../data
candidate_path = os.path.abspath(os.path.join(os.curdir, os.pardir, 'data'))
if os.path.exists(candidate_path):
return Project(os.path.abspath(os.path.join(candidate_path, os.pardir, os.pardir)))
# Out of ideas at this point.
raise ValueError('Cannot discover the structure of the project. Make sure that the data directory exists') | [
"def",
"discover",
"(",
")",
":",
"candidate_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"curdir",
",",
"os",
".",
"pardir",
",",
"'data'",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"candidate_path",
")",
":",
"return",
"Project",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"candidate_path",
",",
"os",
".",
"pardir",
")",
")",
")",
"candidate_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"curdir",
",",
"'data'",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"candidate_path",
")",
":",
"return",
"Project",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"curdir",
")",
")",
"candidate_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"curdir",
",",
"os",
".",
"pardir",
",",
"'data'",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"candidate_path",
")",
":",
"return",
"Project",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"candidate_path",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
")",
")",
")",
"raise",
"ValueError",
"(",
"'Cannot discover the structure of the project. Make sure that the data directory exists'",
")"
] | Automatically discover the paths to various data folders in this project
and compose a Project instance.
Returns:
A constructed Project object.
Raises:
ValueError: if the paths could not be figured out automatically.
In this case, you have to create a Project manually using the initializer. | [
"Automatically",
"discover",
"the",
"paths",
"to",
"various",
"data",
"folders",
"in",
"this",
"project",
"and",
"compose",
"a",
"Project",
"instance",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L170-L199 | train |
YuriyGuts/pygoose | pygoose/kg/project.py | Project.init | def init():
"""
Creates the project infrastructure assuming the current directory is the project root.
Typically used as a command-line entry point called by `pygoose init`.
"""
project = Project(os.path.abspath(os.getcwd()))
paths_to_create = [
project.data_dir,
project.notebooks_dir,
project.aux_dir,
project.features_dir,
project.preprocessed_data_dir,
project.submissions_dir,
project.trained_model_dir,
project.temp_dir,
]
for path in paths_to_create:
os.makedirs(path, exist_ok=True) | python | def init():
"""
Creates the project infrastructure assuming the current directory is the project root.
Typically used as a command-line entry point called by `pygoose init`.
"""
project = Project(os.path.abspath(os.getcwd()))
paths_to_create = [
project.data_dir,
project.notebooks_dir,
project.aux_dir,
project.features_dir,
project.preprocessed_data_dir,
project.submissions_dir,
project.trained_model_dir,
project.temp_dir,
]
for path in paths_to_create:
os.makedirs(path, exist_ok=True) | [
"def",
"init",
"(",
")",
":",
"project",
"=",
"Project",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"paths_to_create",
"=",
"[",
"project",
".",
"data_dir",
",",
"project",
".",
"notebooks_dir",
",",
"project",
".",
"aux_dir",
",",
"project",
".",
"features_dir",
",",
"project",
".",
"preprocessed_data_dir",
",",
"project",
".",
"submissions_dir",
",",
"project",
".",
"trained_model_dir",
",",
"project",
".",
"temp_dir",
",",
"]",
"for",
"path",
"in",
"paths_to_create",
":",
"os",
".",
"makedirs",
"(",
"path",
",",
"exist_ok",
"=",
"True",
")"
] | Creates the project infrastructure assuming the current directory is the project root.
Typically used as a command-line entry point called by `pygoose init`. | [
"Creates",
"the",
"project",
"infrastructure",
"assuming",
"the",
"current",
"directory",
"is",
"the",
"project",
"root",
".",
"Typically",
"used",
"as",
"a",
"command",
"-",
"line",
"entry",
"point",
"called",
"by",
"pygoose",
"init",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L202-L221 | train |
tmr232/awesomelib | awesome/iterator.py | unique_justseen | def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
return imap(next, imap(operator.itemgetter(1), groupby(iterable, key))) | python | def unique_justseen(iterable, key=None):
"List unique elements, preserving order. Remember only the element just seen."
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
return imap(next, imap(operator.itemgetter(1), groupby(iterable, key))) | [
"def",
"unique_justseen",
"(",
"iterable",
",",
"key",
"=",
"None",
")",
":",
"\"List unique elements, preserving order. Remember only the element just seen.\"",
"return",
"imap",
"(",
"next",
",",
"imap",
"(",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"groupby",
"(",
"iterable",
",",
"key",
")",
")",
")"
] | List unique elements, preserving order. Remember only the element just seen. | [
"List",
"unique",
"elements",
"preserving",
"order",
".",
"Remember",
"only",
"the",
"element",
"just",
"seen",
"."
] | 69a63466a63679f9e2abac8a719853a5e527219c | https://github.com/tmr232/awesomelib/blob/69a63466a63679f9e2abac8a719853a5e527219c/awesome/iterator.py#L122-L126 | train |
Erotemic/utool | utool/util_inject.py | _get_module | def _get_module(module_name=None, module=None, register=True):
""" finds module in sys.modules based on module name unless the module has
already been found and is passed in """
if module is None and module_name is not None:
try:
module = sys.modules[module_name]
except KeyError as ex:
print(ex)
raise KeyError(('module_name=%r must be loaded before ' +
'receiving injections') % module_name)
elif module is not None and module_name is None:
pass
else:
raise ValueError('module_name or module must be exclusively specified')
if register is True:
_add_injected_module(module)
return module | python | def _get_module(module_name=None, module=None, register=True):
""" finds module in sys.modules based on module name unless the module has
already been found and is passed in """
if module is None and module_name is not None:
try:
module = sys.modules[module_name]
except KeyError as ex:
print(ex)
raise KeyError(('module_name=%r must be loaded before ' +
'receiving injections') % module_name)
elif module is not None and module_name is None:
pass
else:
raise ValueError('module_name or module must be exclusively specified')
if register is True:
_add_injected_module(module)
return module | [
"def",
"_get_module",
"(",
"module_name",
"=",
"None",
",",
"module",
"=",
"None",
",",
"register",
"=",
"True",
")",
":",
"if",
"module",
"is",
"None",
"and",
"module_name",
"is",
"not",
"None",
":",
"try",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"except",
"KeyError",
"as",
"ex",
":",
"print",
"(",
"ex",
")",
"raise",
"KeyError",
"(",
"(",
"'module_name=%r must be loaded before '",
"+",
"'receiving injections'",
")",
"%",
"module_name",
")",
"elif",
"module",
"is",
"not",
"None",
"and",
"module_name",
"is",
"None",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"'module_name or module must be exclusively specified'",
")",
"if",
"register",
"is",
"True",
":",
"_add_injected_module",
"(",
"module",
")",
"return",
"module"
] | finds module in sys.modules based on module name unless the module has
already been found and is passed in | [
"finds",
"module",
"in",
"sys",
".",
"modules",
"based",
"on",
"module",
"name",
"unless",
"the",
"module",
"has",
"already",
"been",
"found",
"and",
"is",
"passed",
"in"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L86-L102 | train |
Erotemic/utool | utool/util_inject.py | inject_colored_exceptions | def inject_colored_exceptions():
"""
Causes exceptions to be colored if not already
Hooks into sys.excepthook
CommandLine:
python -m utool.util_inject --test-inject_colored_exceptions
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> print('sys.excepthook = %r ' % (sys.excepthook,))
>>> #assert sys.excepthook is colored_pygments_excepthook, 'bad excepthook'
>>> raise Exception('should be in color')
"""
#COLORED_INJECTS = '--nocolorex' not in sys.argv
#COLORED_INJECTS = '--colorex' in sys.argv
# Ignore colored exceptions on win32
if VERBOSE:
print('[inject] injecting colored exceptions')
if not sys.platform.startswith('win32'):
if VERYVERBOSE:
print('[inject] injecting colored exceptions')
if '--noinject-color' in sys.argv:
print('Not injecting color')
else:
sys.excepthook = colored_pygments_excepthook
else:
if VERYVERBOSE:
print('[inject] cannot inject colored exceptions') | python | def inject_colored_exceptions():
"""
Causes exceptions to be colored if not already
Hooks into sys.excepthook
CommandLine:
python -m utool.util_inject --test-inject_colored_exceptions
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> print('sys.excepthook = %r ' % (sys.excepthook,))
>>> #assert sys.excepthook is colored_pygments_excepthook, 'bad excepthook'
>>> raise Exception('should be in color')
"""
#COLORED_INJECTS = '--nocolorex' not in sys.argv
#COLORED_INJECTS = '--colorex' in sys.argv
# Ignore colored exceptions on win32
if VERBOSE:
print('[inject] injecting colored exceptions')
if not sys.platform.startswith('win32'):
if VERYVERBOSE:
print('[inject] injecting colored exceptions')
if '--noinject-color' in sys.argv:
print('Not injecting color')
else:
sys.excepthook = colored_pygments_excepthook
else:
if VERYVERBOSE:
print('[inject] cannot inject colored exceptions') | [
"def",
"inject_colored_exceptions",
"(",
")",
":",
"if",
"VERBOSE",
":",
"print",
"(",
"'[inject] injecting colored exceptions'",
")",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win32'",
")",
":",
"if",
"VERYVERBOSE",
":",
"print",
"(",
"'[inject] injecting colored exceptions'",
")",
"if",
"'--noinject-color'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"'Not injecting color'",
")",
"else",
":",
"sys",
".",
"excepthook",
"=",
"colored_pygments_excepthook",
"else",
":",
"if",
"VERYVERBOSE",
":",
"print",
"(",
"'[inject] cannot inject colored exceptions'",
")"
] | Causes exceptions to be colored if not already
Hooks into sys.excepthook
CommandLine:
python -m utool.util_inject --test-inject_colored_exceptions
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> print('sys.excepthook = %r ' % (sys.excepthook,))
>>> #assert sys.excepthook is colored_pygments_excepthook, 'bad excepthook'
>>> raise Exception('should be in color') | [
"Causes",
"exceptions",
"to",
"be",
"colored",
"if",
"not",
"already"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L135-L166 | train |
Erotemic/utool | utool/util_inject.py | inject_print_functions | def inject_print_functions(module_name=None, module_prefix='[???]',
DEBUG=False, module=None):
"""
makes print functions to be injected into the module
"""
module = _get_module(module_name, module)
if SILENT:
def print(*args):
""" silent builtins.print """
pass
def printDBG(*args):
""" silent debug print """
pass
def print_(*args):
""" silent stdout.write """
pass
else:
if DEBUG_PRINT:
# Turns on printing where a message came from
def print(*args):
""" debugging logging builtins.print """
from utool._internal.meta_util_dbg import get_caller_name
calltag = ''.join(('[caller:', get_caller_name(N=DEBUG_PRINT_N), ']' ))
util_logging._utool_print()(calltag, *args)
else:
def print(*args):
""" logging builtins.print """
util_logging._utool_print()(*args)
if __AGGROFLUSH__:
def print_(*args):
""" aggressive logging stdout.write """
util_logging._utool_write()(*args)
util_logging._utool_flush()()
else:
def print_(*args):
""" logging stdout.write """
util_logging._utool_write()(*args)
# turn on module debugging with command line flags
dotpos = module.__name__.rfind('.')
if dotpos == -1:
module_name = module.__name__
else:
module_name = module.__name__[dotpos + 1:]
def _replchars(str_):
return str_.replace('_', '-').replace(']', '').replace('[', '')
flag1 = '--debug-%s' % _replchars(module_name)
flag2 = '--debug-%s' % _replchars(module_prefix)
DEBUG_FLAG = any([flag in sys.argv for flag in [flag1, flag2]])
for curflag in ARGV_DEBUG_FLAGS:
if curflag in module_prefix:
DEBUG_FLAG = True
if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG:
print('INJECT_PRINT: %r == %r' % (module_name, module_prefix))
def printDBG(*args):
""" debug logging print """
msg = ', '.join(map(str, args))
util_logging.__UTOOL_PRINTDBG__(module_prefix + ' DEBUG ' + msg)
else:
def printDBG(*args):
""" silent debug logging print """
pass
#_inject_funcs(module, print, print_, printDBG)
print_funcs = (print, print_, printDBG)
return print_funcs | python | def inject_print_functions(module_name=None, module_prefix='[???]',
DEBUG=False, module=None):
"""
makes print functions to be injected into the module
"""
module = _get_module(module_name, module)
if SILENT:
def print(*args):
""" silent builtins.print """
pass
def printDBG(*args):
""" silent debug print """
pass
def print_(*args):
""" silent stdout.write """
pass
else:
if DEBUG_PRINT:
# Turns on printing where a message came from
def print(*args):
""" debugging logging builtins.print """
from utool._internal.meta_util_dbg import get_caller_name
calltag = ''.join(('[caller:', get_caller_name(N=DEBUG_PRINT_N), ']' ))
util_logging._utool_print()(calltag, *args)
else:
def print(*args):
""" logging builtins.print """
util_logging._utool_print()(*args)
if __AGGROFLUSH__:
def print_(*args):
""" aggressive logging stdout.write """
util_logging._utool_write()(*args)
util_logging._utool_flush()()
else:
def print_(*args):
""" logging stdout.write """
util_logging._utool_write()(*args)
# turn on module debugging with command line flags
dotpos = module.__name__.rfind('.')
if dotpos == -1:
module_name = module.__name__
else:
module_name = module.__name__[dotpos + 1:]
def _replchars(str_):
return str_.replace('_', '-').replace(']', '').replace('[', '')
flag1 = '--debug-%s' % _replchars(module_name)
flag2 = '--debug-%s' % _replchars(module_prefix)
DEBUG_FLAG = any([flag in sys.argv for flag in [flag1, flag2]])
for curflag in ARGV_DEBUG_FLAGS:
if curflag in module_prefix:
DEBUG_FLAG = True
if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG:
print('INJECT_PRINT: %r == %r' % (module_name, module_prefix))
def printDBG(*args):
""" debug logging print """
msg = ', '.join(map(str, args))
util_logging.__UTOOL_PRINTDBG__(module_prefix + ' DEBUG ' + msg)
else:
def printDBG(*args):
""" silent debug logging print """
pass
#_inject_funcs(module, print, print_, printDBG)
print_funcs = (print, print_, printDBG)
return print_funcs | [
"def",
"inject_print_functions",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"'[???]'",
",",
"DEBUG",
"=",
"False",
",",
"module",
"=",
"None",
")",
":",
"module",
"=",
"_get_module",
"(",
"module_name",
",",
"module",
")",
"if",
"SILENT",
":",
"def",
"print",
"(",
"*",
"args",
")",
":",
"pass",
"def",
"printDBG",
"(",
"*",
"args",
")",
":",
"pass",
"def",
"print_",
"(",
"*",
"args",
")",
":",
"pass",
"else",
":",
"if",
"DEBUG_PRINT",
":",
"def",
"print",
"(",
"*",
"args",
")",
":",
"from",
"utool",
".",
"_internal",
".",
"meta_util_dbg",
"import",
"get_caller_name",
"calltag",
"=",
"''",
".",
"join",
"(",
"(",
"'[caller:'",
",",
"get_caller_name",
"(",
"N",
"=",
"DEBUG_PRINT_N",
")",
",",
"']'",
")",
")",
"util_logging",
".",
"_utool_print",
"(",
")",
"(",
"calltag",
",",
"*",
"args",
")",
"else",
":",
"def",
"print",
"(",
"*",
"args",
")",
":",
"util_logging",
".",
"_utool_print",
"(",
")",
"(",
"*",
"args",
")",
"if",
"__AGGROFLUSH__",
":",
"def",
"print_",
"(",
"*",
"args",
")",
":",
"util_logging",
".",
"_utool_write",
"(",
")",
"(",
"*",
"args",
")",
"util_logging",
".",
"_utool_flush",
"(",
")",
"(",
")",
"else",
":",
"def",
"print_",
"(",
"*",
"args",
")",
":",
"util_logging",
".",
"_utool_write",
"(",
")",
"(",
"*",
"args",
")",
"dotpos",
"=",
"module",
".",
"__name__",
".",
"rfind",
"(",
"'.'",
")",
"if",
"dotpos",
"==",
"-",
"1",
":",
"module_name",
"=",
"module",
".",
"__name__",
"else",
":",
"module_name",
"=",
"module",
".",
"__name__",
"[",
"dotpos",
"+",
"1",
":",
"]",
"def",
"_replchars",
"(",
"str_",
")",
":",
"return",
"str_",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
".",
"replace",
"(",
"']'",
",",
"''",
")",
".",
"replace",
"(",
"'['",
",",
"''",
")",
"flag1",
"=",
"'--debug-%s'",
"%",
"_replchars",
"(",
"module_name",
")",
"flag2",
"=",
"'--debug-%s'",
"%",
"_replchars",
"(",
"module_prefix",
")",
"DEBUG_FLAG",
"=",
"any",
"(",
"[",
"flag",
"in",
"sys",
".",
"argv",
"for",
"flag",
"in",
"[",
"flag1",
",",
"flag2",
"]",
"]",
")",
"for",
"curflag",
"in",
"ARGV_DEBUG_FLAGS",
":",
"if",
"curflag",
"in",
"module_prefix",
":",
"DEBUG_FLAG",
"=",
"True",
"if",
"__DEBUG_ALL__",
"or",
"DEBUG",
"or",
"DEBUG_FLAG",
":",
"print",
"(",
"'INJECT_PRINT: %r == %r'",
"%",
"(",
"module_name",
",",
"module_prefix",
")",
")",
"def",
"printDBG",
"(",
"*",
"args",
")",
":",
"msg",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"args",
")",
")",
"util_logging",
".",
"__UTOOL_PRINTDBG__",
"(",
"module_prefix",
"+",
"' DEBUG '",
"+",
"msg",
")",
"else",
":",
"def",
"printDBG",
"(",
"*",
"args",
")",
":",
"pass",
"print_funcs",
"=",
"(",
"print",
",",
"print_",
",",
"printDBG",
")",
"return",
"print_funcs"
] | makes print functions to be injected into the module | [
"makes",
"print",
"functions",
"to",
"be",
"injected",
"into",
"the",
"module"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L207-L272 | train |
Erotemic/utool | utool/util_inject.py | make_module_reload_func | def make_module_reload_func(module_name=None, module_prefix='[???]', module=None):
""" Injects dynamic module reloading """
module = _get_module(module_name, module, register=False)
if module_name is None:
module_name = str(module.__name__)
def rrr(verbose=True):
""" Dynamic module reloading """
if not __RELOAD_OK__:
raise Exception('Reloading has been forced off')
try:
import imp
if verbose and not QUIET:
builtins.print('RELOAD: ' + str(module_prefix) + ' __name__=' + module_name)
imp.reload(module)
except Exception as ex:
print(ex)
print('%s Failed to reload' % module_prefix)
raise
# this doesn't seem to set anything on import *
#_inject_funcs(module, rrr)
return rrr | python | def make_module_reload_func(module_name=None, module_prefix='[???]', module=None):
""" Injects dynamic module reloading """
module = _get_module(module_name, module, register=False)
if module_name is None:
module_name = str(module.__name__)
def rrr(verbose=True):
""" Dynamic module reloading """
if not __RELOAD_OK__:
raise Exception('Reloading has been forced off')
try:
import imp
if verbose and not QUIET:
builtins.print('RELOAD: ' + str(module_prefix) + ' __name__=' + module_name)
imp.reload(module)
except Exception as ex:
print(ex)
print('%s Failed to reload' % module_prefix)
raise
# this doesn't seem to set anything on import *
#_inject_funcs(module, rrr)
return rrr | [
"def",
"make_module_reload_func",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"'[???]'",
",",
"module",
"=",
"None",
")",
":",
"module",
"=",
"_get_module",
"(",
"module_name",
",",
"module",
",",
"register",
"=",
"False",
")",
"if",
"module_name",
"is",
"None",
":",
"module_name",
"=",
"str",
"(",
"module",
".",
"__name__",
")",
"def",
"rrr",
"(",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"__RELOAD_OK__",
":",
"raise",
"Exception",
"(",
"'Reloading has been forced off'",
")",
"try",
":",
"import",
"imp",
"if",
"verbose",
"and",
"not",
"QUIET",
":",
"builtins",
".",
"print",
"(",
"'RELOAD: '",
"+",
"str",
"(",
"module_prefix",
")",
"+",
"' __name__='",
"+",
"module_name",
")",
"imp",
".",
"reload",
"(",
"module",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"ex",
")",
"print",
"(",
"'%s Failed to reload'",
"%",
"module_prefix",
")",
"raise",
"return",
"rrr"
] | Injects dynamic module reloading | [
"Injects",
"dynamic",
"module",
"reloading"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L298-L318 | train |
Erotemic/utool | utool/util_inject.py | noinject | def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0, via=None):
"""
Use in modules that do not have inject in them
Does not inject anything into the module. Just lets utool know that a module
is being imported so the import order can be debuged
"""
if PRINT_INJECT_ORDER:
from utool._internal import meta_util_dbg
callername = meta_util_dbg.get_caller_name(N=N + 1, strict=False)
lineno = meta_util_dbg.get_caller_lineno(N=N + 1, strict=False)
suff = ' via %s' % (via,) if via else ''
fmtdict = dict(N=N, lineno=lineno, callername=callername,
modname=module_name, suff=suff)
msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'.format(**fmtdict)
if DEBUG_SLOW_IMPORT:
global PREV_MODNAME
seconds = tt.toc()
import_times[(PREV_MODNAME, module_name)] = seconds
PREV_MODNAME = module_name
builtins.print(msg)
if DEBUG_SLOW_IMPORT:
tt.tic()
# builtins.print(elapsed)
if EXIT_ON_INJECT_MODNAME == module_name:
builtins.print('...exiting')
assert False, 'exit in inject requested' | python | def noinject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=0, via=None):
"""
Use in modules that do not have inject in them
Does not inject anything into the module. Just lets utool know that a module
is being imported so the import order can be debuged
"""
if PRINT_INJECT_ORDER:
from utool._internal import meta_util_dbg
callername = meta_util_dbg.get_caller_name(N=N + 1, strict=False)
lineno = meta_util_dbg.get_caller_lineno(N=N + 1, strict=False)
suff = ' via %s' % (via,) if via else ''
fmtdict = dict(N=N, lineno=lineno, callername=callername,
modname=module_name, suff=suff)
msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'.format(**fmtdict)
if DEBUG_SLOW_IMPORT:
global PREV_MODNAME
seconds = tt.toc()
import_times[(PREV_MODNAME, module_name)] = seconds
PREV_MODNAME = module_name
builtins.print(msg)
if DEBUG_SLOW_IMPORT:
tt.tic()
# builtins.print(elapsed)
if EXIT_ON_INJECT_MODNAME == module_name:
builtins.print('...exiting')
assert False, 'exit in inject requested' | [
"def",
"noinject",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"'[???]'",
",",
"DEBUG",
"=",
"False",
",",
"module",
"=",
"None",
",",
"N",
"=",
"0",
",",
"via",
"=",
"None",
")",
":",
"if",
"PRINT_INJECT_ORDER",
":",
"from",
"utool",
".",
"_internal",
"import",
"meta_util_dbg",
"callername",
"=",
"meta_util_dbg",
".",
"get_caller_name",
"(",
"N",
"=",
"N",
"+",
"1",
",",
"strict",
"=",
"False",
")",
"lineno",
"=",
"meta_util_dbg",
".",
"get_caller_lineno",
"(",
"N",
"=",
"N",
"+",
"1",
",",
"strict",
"=",
"False",
")",
"suff",
"=",
"' via %s'",
"%",
"(",
"via",
",",
")",
"if",
"via",
"else",
"''",
"fmtdict",
"=",
"dict",
"(",
"N",
"=",
"N",
",",
"lineno",
"=",
"lineno",
",",
"callername",
"=",
"callername",
",",
"modname",
"=",
"module_name",
",",
"suff",
"=",
"suff",
")",
"msg",
"=",
"'[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}'",
".",
"format",
"(",
"**",
"fmtdict",
")",
"if",
"DEBUG_SLOW_IMPORT",
":",
"global",
"PREV_MODNAME",
"seconds",
"=",
"tt",
".",
"toc",
"(",
")",
"import_times",
"[",
"(",
"PREV_MODNAME",
",",
"module_name",
")",
"]",
"=",
"seconds",
"PREV_MODNAME",
"=",
"module_name",
"builtins",
".",
"print",
"(",
"msg",
")",
"if",
"DEBUG_SLOW_IMPORT",
":",
"tt",
".",
"tic",
"(",
")",
"if",
"EXIT_ON_INJECT_MODNAME",
"==",
"module_name",
":",
"builtins",
".",
"print",
"(",
"'...exiting'",
")",
"assert",
"False",
",",
"'exit in inject requested'"
] | Use in modules that do not have inject in them
Does not inject anything into the module. Just lets utool know that a module
is being imported so the import order can be debuged | [
"Use",
"in",
"modules",
"that",
"do",
"not",
"have",
"inject",
"in",
"them"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L441-L470 | train |
Erotemic/utool | utool/util_inject.py | inject | def inject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=1):
"""
Injects your module with utool magic
Utool magic is not actually magic. It just turns your ``print`` statments into
logging statments, allows for your module to be used with the utool.Indent
context manager and the and utool.indent_func decorator. ``printDBG`` will soon
be deprecated as will ``print_``. The function rrr is a developer convinience for
reloading the module dynamically durring runtime. The profile decorator is
a no-op if not using kernprof.py, otherwise it is kernprof.py's profile
decorator.
Args:
module_name (str): the __name__ varaible in your module
module_prefix (str): a user defined module prefix
DEBUG (bool):
module (None): the actual module (optional)
Returns:
tuple : (print, print_, printDBG, rrr, profile_)
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>> from util.util_inject import inject
>>> print, rrr, profile = inject2(__name__, '[mod]')
"""
#noinject(module_name, module_prefix, DEBUG, module, N=1)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, module)
rrr = make_module_reload_func(None, module_prefix, module)
profile_ = make_module_profile_func(None, module_prefix, module)
print_funcs = inject_print_functions(None, module_prefix, DEBUG, module)
(print, print_, printDBG) = print_funcs
return (print, print_, printDBG, rrr, profile_) | python | def inject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=1):
"""
Injects your module with utool magic
Utool magic is not actually magic. It just turns your ``print`` statments into
logging statments, allows for your module to be used with the utool.Indent
context manager and the and utool.indent_func decorator. ``printDBG`` will soon
be deprecated as will ``print_``. The function rrr is a developer convinience for
reloading the module dynamically durring runtime. The profile decorator is
a no-op if not using kernprof.py, otherwise it is kernprof.py's profile
decorator.
Args:
module_name (str): the __name__ varaible in your module
module_prefix (str): a user defined module prefix
DEBUG (bool):
module (None): the actual module (optional)
Returns:
tuple : (print, print_, printDBG, rrr, profile_)
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>> from util.util_inject import inject
>>> print, rrr, profile = inject2(__name__, '[mod]')
"""
#noinject(module_name, module_prefix, DEBUG, module, N=1)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, module)
rrr = make_module_reload_func(None, module_prefix, module)
profile_ = make_module_profile_func(None, module_prefix, module)
print_funcs = inject_print_functions(None, module_prefix, DEBUG, module)
(print, print_, printDBG) = print_funcs
return (print, print_, printDBG, rrr, profile_) | [
"def",
"inject",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"'[???]'",
",",
"DEBUG",
"=",
"False",
",",
"module",
"=",
"None",
",",
"N",
"=",
"1",
")",
":",
"noinject",
"(",
"module_name",
",",
"module_prefix",
",",
"DEBUG",
",",
"module",
",",
"N",
"=",
"N",
")",
"module",
"=",
"_get_module",
"(",
"module_name",
",",
"module",
")",
"rrr",
"=",
"make_module_reload_func",
"(",
"None",
",",
"module_prefix",
",",
"module",
")",
"profile_",
"=",
"make_module_profile_func",
"(",
"None",
",",
"module_prefix",
",",
"module",
")",
"print_funcs",
"=",
"inject_print_functions",
"(",
"None",
",",
"module_prefix",
",",
"DEBUG",
",",
"module",
")",
"(",
"print",
",",
"print_",
",",
"printDBG",
")",
"=",
"print_funcs",
"return",
"(",
"print",
",",
"print_",
",",
"printDBG",
",",
"rrr",
",",
"profile_",
")"
] | Injects your module with utool magic
Utool magic is not actually magic. It just turns your ``print`` statments into
logging statments, allows for your module to be used with the utool.Indent
context manager and the and utool.indent_func decorator. ``printDBG`` will soon
be deprecated as will ``print_``. The function rrr is a developer convinience for
reloading the module dynamically durring runtime. The profile decorator is
a no-op if not using kernprof.py, otherwise it is kernprof.py's profile
decorator.
Args:
module_name (str): the __name__ varaible in your module
module_prefix (str): a user defined module prefix
DEBUG (bool):
module (None): the actual module (optional)
Returns:
tuple : (print, print_, printDBG, rrr, profile_)
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inject import * # NOQA
>>> from __future__ import absolute_import, division, print_function, unicode_literals
>>> from util.util_inject import inject
>>> print, rrr, profile = inject2(__name__, '[mod]') | [
"Injects",
"your",
"module",
"with",
"utool",
"magic"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L473-L508 | train |
Erotemic/utool | utool/util_inject.py | inject2 | def inject2(module_name=None, module_prefix=None, DEBUG=False, module=None, N=1):
""" wrapper that depricates print_ and printDBG """
if module_prefix is None:
module_prefix = '[%s]' % (module_name,)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, module)
rrr = make_module_reload_func(None, module_prefix, module)
profile_ = make_module_profile_func(None, module_prefix, module)
print = make_module_print_func(module)
return print, rrr, profile_ | python | def inject2(module_name=None, module_prefix=None, DEBUG=False, module=None, N=1):
""" wrapper that depricates print_ and printDBG """
if module_prefix is None:
module_prefix = '[%s]' % (module_name,)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, module)
rrr = make_module_reload_func(None, module_prefix, module)
profile_ = make_module_profile_func(None, module_prefix, module)
print = make_module_print_func(module)
return print, rrr, profile_ | [
"def",
"inject2",
"(",
"module_name",
"=",
"None",
",",
"module_prefix",
"=",
"None",
",",
"DEBUG",
"=",
"False",
",",
"module",
"=",
"None",
",",
"N",
"=",
"1",
")",
":",
"if",
"module_prefix",
"is",
"None",
":",
"module_prefix",
"=",
"'[%s]'",
"%",
"(",
"module_name",
",",
")",
"noinject",
"(",
"module_name",
",",
"module_prefix",
",",
"DEBUG",
",",
"module",
",",
"N",
"=",
"N",
")",
"module",
"=",
"_get_module",
"(",
"module_name",
",",
"module",
")",
"rrr",
"=",
"make_module_reload_func",
"(",
"None",
",",
"module_prefix",
",",
"module",
")",
"profile_",
"=",
"make_module_profile_func",
"(",
"None",
",",
"module_prefix",
",",
"module",
")",
"print",
"=",
"make_module_print_func",
"(",
"module",
")",
"return",
"print",
",",
"rrr",
",",
"profile_"
] | wrapper that depricates print_ and printDBG | [
"wrapper",
"that",
"depricates",
"print_",
"and",
"printDBG"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L511-L520 | train |
Erotemic/utool | utool/util_inject.py | inject_python_code2 | def inject_python_code2(fpath, patch_code, tag):
""" Does autogeneration stuff """
import utool as ut
text = ut.readfrom(fpath)
start_tag = '# <%s>' % tag
end_tag = '# </%s>' % tag
new_text = ut.replace_between_tags(text, patch_code, start_tag, end_tag)
ut.writeto(fpath, new_text) | python | def inject_python_code2(fpath, patch_code, tag):
""" Does autogeneration stuff """
import utool as ut
text = ut.readfrom(fpath)
start_tag = '# <%s>' % tag
end_tag = '# </%s>' % tag
new_text = ut.replace_between_tags(text, patch_code, start_tag, end_tag)
ut.writeto(fpath, new_text) | [
"def",
"inject_python_code2",
"(",
"fpath",
",",
"patch_code",
",",
"tag",
")",
":",
"import",
"utool",
"as",
"ut",
"text",
"=",
"ut",
".",
"readfrom",
"(",
"fpath",
")",
"start_tag",
"=",
"'# <%s>'",
"%",
"tag",
"end_tag",
"=",
"'# </%s>'",
"%",
"tag",
"new_text",
"=",
"ut",
".",
"replace_between_tags",
"(",
"text",
",",
"patch_code",
",",
"start_tag",
",",
"end_tag",
")",
"ut",
".",
"writeto",
"(",
"fpath",
",",
"new_text",
")"
] | Does autogeneration stuff | [
"Does",
"autogeneration",
"stuff"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L561-L568 | train |
Erotemic/utool | utool/util_inject.py | inject_python_code | def inject_python_code(fpath, patch_code, tag=None,
inject_location='after_imports'):
"""
DEPRICATE
puts code into files on disk
"""
import utool as ut
assert tag is not None, 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT'
text = ut.read_from(fpath)
comment_start_tag = '# <util_inject:%s>' % tag
comment_end_tag = '# </util_inject:%s>' % tag
tagstart_txtpos = text.find(comment_start_tag)
tagend_txtpos = text.find(comment_end_tag)
text_lines = ut.split_python_text_into_lines(text)
# split the file into two parts and inject code between them
if tagstart_txtpos != -1 or tagend_txtpos != -1:
assert tagstart_txtpos != -1, 'both tags must not be found'
assert tagend_txtpos != -1, 'both tags must not be found'
for pos, line in enumerate(text_lines):
if line.startswith(comment_start_tag):
tagstart_pos = pos
if line.startswith(comment_end_tag):
tagend_pos = pos
part1 = text_lines[0:tagstart_pos]
part2 = text_lines[tagend_pos + 1:]
else:
if inject_location == 'after_imports':
first_nonimport_pos = 0
for line in text_lines:
list_ = ['import ', 'from ', '#', ' ']
isvalid = (len(line) == 0 or
any(line.startswith(str_) for str_ in list_))
if not isvalid:
break
first_nonimport_pos += 1
part1 = text_lines[0:first_nonimport_pos]
part2 = text_lines[first_nonimport_pos:]
else:
raise AssertionError('Unknown inject location')
newtext = (
'\n'.join(part1 + [comment_start_tag]) +
'\n' + patch_code + '\n' +
'\n'.join( [comment_end_tag] + part2)
)
text_backup_fname = fpath + '.' + ut.get_timestamp() + '.bak'
ut.write_to(text_backup_fname, text)
ut.write_to(fpath, newtext) | python | def inject_python_code(fpath, patch_code, tag=None,
inject_location='after_imports'):
"""
DEPRICATE
puts code into files on disk
"""
import utool as ut
assert tag is not None, 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT'
text = ut.read_from(fpath)
comment_start_tag = '# <util_inject:%s>' % tag
comment_end_tag = '# </util_inject:%s>' % tag
tagstart_txtpos = text.find(comment_start_tag)
tagend_txtpos = text.find(comment_end_tag)
text_lines = ut.split_python_text_into_lines(text)
# split the file into two parts and inject code between them
if tagstart_txtpos != -1 or tagend_txtpos != -1:
assert tagstart_txtpos != -1, 'both tags must not be found'
assert tagend_txtpos != -1, 'both tags must not be found'
for pos, line in enumerate(text_lines):
if line.startswith(comment_start_tag):
tagstart_pos = pos
if line.startswith(comment_end_tag):
tagend_pos = pos
part1 = text_lines[0:tagstart_pos]
part2 = text_lines[tagend_pos + 1:]
else:
if inject_location == 'after_imports':
first_nonimport_pos = 0
for line in text_lines:
list_ = ['import ', 'from ', '#', ' ']
isvalid = (len(line) == 0 or
any(line.startswith(str_) for str_ in list_))
if not isvalid:
break
first_nonimport_pos += 1
part1 = text_lines[0:first_nonimport_pos]
part2 = text_lines[first_nonimport_pos:]
else:
raise AssertionError('Unknown inject location')
newtext = (
'\n'.join(part1 + [comment_start_tag]) +
'\n' + patch_code + '\n' +
'\n'.join( [comment_end_tag] + part2)
)
text_backup_fname = fpath + '.' + ut.get_timestamp() + '.bak'
ut.write_to(text_backup_fname, text)
ut.write_to(fpath, newtext) | [
"def",
"inject_python_code",
"(",
"fpath",
",",
"patch_code",
",",
"tag",
"=",
"None",
",",
"inject_location",
"=",
"'after_imports'",
")",
":",
"import",
"utool",
"as",
"ut",
"assert",
"tag",
"is",
"not",
"None",
",",
"'TAG MUST BE SPECIFIED IN INJECTED CODETEXT'",
"text",
"=",
"ut",
".",
"read_from",
"(",
"fpath",
")",
"comment_start_tag",
"=",
"'# <util_inject:%s>'",
"%",
"tag",
"comment_end_tag",
"=",
"'# </util_inject:%s>'",
"%",
"tag",
"tagstart_txtpos",
"=",
"text",
".",
"find",
"(",
"comment_start_tag",
")",
"tagend_txtpos",
"=",
"text",
".",
"find",
"(",
"comment_end_tag",
")",
"text_lines",
"=",
"ut",
".",
"split_python_text_into_lines",
"(",
"text",
")",
"if",
"tagstart_txtpos",
"!=",
"-",
"1",
"or",
"tagend_txtpos",
"!=",
"-",
"1",
":",
"assert",
"tagstart_txtpos",
"!=",
"-",
"1",
",",
"'both tags must not be found'",
"assert",
"tagend_txtpos",
"!=",
"-",
"1",
",",
"'both tags must not be found'",
"for",
"pos",
",",
"line",
"in",
"enumerate",
"(",
"text_lines",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"comment_start_tag",
")",
":",
"tagstart_pos",
"=",
"pos",
"if",
"line",
".",
"startswith",
"(",
"comment_end_tag",
")",
":",
"tagend_pos",
"=",
"pos",
"part1",
"=",
"text_lines",
"[",
"0",
":",
"tagstart_pos",
"]",
"part2",
"=",
"text_lines",
"[",
"tagend_pos",
"+",
"1",
":",
"]",
"else",
":",
"if",
"inject_location",
"==",
"'after_imports'",
":",
"first_nonimport_pos",
"=",
"0",
"for",
"line",
"in",
"text_lines",
":",
"list_",
"=",
"[",
"'import '",
",",
"'from '",
",",
"'#'",
",",
"' '",
"]",
"isvalid",
"=",
"(",
"len",
"(",
"line",
")",
"==",
"0",
"or",
"any",
"(",
"line",
".",
"startswith",
"(",
"str_",
")",
"for",
"str_",
"in",
"list_",
")",
")",
"if",
"not",
"isvalid",
":",
"break",
"first_nonimport_pos",
"+=",
"1",
"part1",
"=",
"text_lines",
"[",
"0",
":",
"first_nonimport_pos",
"]",
"part2",
"=",
"text_lines",
"[",
"first_nonimport_pos",
":",
"]",
"else",
":",
"raise",
"AssertionError",
"(",
"'Unknown inject location'",
")",
"newtext",
"=",
"(",
"'\\n'",
".",
"join",
"(",
"part1",
"+",
"[",
"comment_start_tag",
"]",
")",
"+",
"'\\n'",
"+",
"patch_code",
"+",
"'\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"[",
"comment_end_tag",
"]",
"+",
"part2",
")",
")",
"text_backup_fname",
"=",
"fpath",
"+",
"'.'",
"+",
"ut",
".",
"get_timestamp",
"(",
")",
"+",
"'.bak'",
"ut",
".",
"write_to",
"(",
"text_backup_fname",
",",
"text",
")",
"ut",
".",
"write_to",
"(",
"fpath",
",",
"newtext",
")"
] | DEPRICATE
puts code into files on disk | [
"DEPRICATE",
"puts",
"code",
"into",
"files",
"on",
"disk"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L571-L622 | train |
Erotemic/utool | utool/Printable.py | printableType | def printableType(val, name=None, parent=None):
"""
Tries to make a nice type string for a value.
Can also pass in a Printable parent object
"""
import numpy as np
if parent is not None and hasattr(parent, 'customPrintableType'):
# Hack for non - trivial preference types
_typestr = parent.customPrintableType(name)
if _typestr is not None:
return _typestr
if isinstance(val, np.ndarray):
info = npArrInfo(val)
_typestr = info.dtypestr
elif isinstance(val, object):
_typestr = val.__class__.__name__
else:
_typestr = str(type(val))
_typestr = _typestr.replace('type', '')
_typestr = re.sub('[\'><]', '', _typestr)
_typestr = re.sub(' *', ' ', _typestr)
_typestr = _typestr.strip()
return _typestr | python | def printableType(val, name=None, parent=None):
"""
Tries to make a nice type string for a value.
Can also pass in a Printable parent object
"""
import numpy as np
if parent is not None and hasattr(parent, 'customPrintableType'):
# Hack for non - trivial preference types
_typestr = parent.customPrintableType(name)
if _typestr is not None:
return _typestr
if isinstance(val, np.ndarray):
info = npArrInfo(val)
_typestr = info.dtypestr
elif isinstance(val, object):
_typestr = val.__class__.__name__
else:
_typestr = str(type(val))
_typestr = _typestr.replace('type', '')
_typestr = re.sub('[\'><]', '', _typestr)
_typestr = re.sub(' *', ' ', _typestr)
_typestr = _typestr.strip()
return _typestr | [
"def",
"printableType",
"(",
"val",
",",
"name",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"parent",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"parent",
",",
"'customPrintableType'",
")",
":",
"_typestr",
"=",
"parent",
".",
"customPrintableType",
"(",
"name",
")",
"if",
"_typestr",
"is",
"not",
"None",
":",
"return",
"_typestr",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"info",
"=",
"npArrInfo",
"(",
"val",
")",
"_typestr",
"=",
"info",
".",
"dtypestr",
"elif",
"isinstance",
"(",
"val",
",",
"object",
")",
":",
"_typestr",
"=",
"val",
".",
"__class__",
".",
"__name__",
"else",
":",
"_typestr",
"=",
"str",
"(",
"type",
"(",
"val",
")",
")",
"_typestr",
"=",
"_typestr",
".",
"replace",
"(",
"'type'",
",",
"''",
")",
"_typestr",
"=",
"re",
".",
"sub",
"(",
"'[\\'><]'",
",",
"''",
",",
"_typestr",
")",
"_typestr",
"=",
"re",
".",
"sub",
"(",
"' *'",
",",
"' '",
",",
"_typestr",
")",
"_typestr",
"=",
"_typestr",
".",
"strip",
"(",
")",
"return",
"_typestr"
] | Tries to make a nice type string for a value.
Can also pass in a Printable parent object | [
"Tries",
"to",
"make",
"a",
"nice",
"type",
"string",
"for",
"a",
"value",
".",
"Can",
"also",
"pass",
"in",
"a",
"Printable",
"parent",
"object"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L96-L118 | train |
Erotemic/utool | utool/Printable.py | printableVal | def printableVal(val, type_bit=True, justlength=False):
"""
Very old way of doing pretty printing. Need to update and refactor.
DEPRICATE
"""
from utool import util_dev
# Move to util_dev
# NUMPY ARRAY
import numpy as np
if type(val) is np.ndarray:
info = npArrInfo(val)
if info.dtypestr.startswith('bool'):
_valstr = '{ shape:' + info.shapestr + ' bittotal: ' + info.bittotal + '}'
# + '\n |_____'
elif info.dtypestr.startswith('float'):
_valstr = util_dev.get_stats_str(val)
else:
_valstr = '{ shape:' + info.shapestr + ' mM:' + info.minmaxstr + ' }' # + '\n |_____'
# String
elif isinstance(val, (str, unicode)): # NOQA
_valstr = '\'%s\'' % val
# List
elif isinstance(val, list):
if justlength or len(val) > 30:
_valstr = 'len=' + str(len(val))
else:
_valstr = '[ ' + (', \n '.join([str(v) for v in val])) + ' ]'
# ??? isinstance(val, AbstractPrintable):
elif hasattr(val, 'get_printable') and type(val) != type:
_valstr = val.get_printable(type_bit=type_bit)
elif isinstance(val, dict):
_valstr = '{\n'
for val_key in val.keys():
val_val = val[val_key]
_valstr += ' ' + str(val_key) + ' : ' + str(val_val) + '\n'
_valstr += '}'
else:
_valstr = str(val)
if _valstr.find('\n') > 0: # Indent if necessary
_valstr = _valstr.replace('\n', '\n ')
_valstr = '\n ' + _valstr
_valstr = re.sub('\n *$', '', _valstr) # Replace empty lines
return _valstr | python | def printableVal(val, type_bit=True, justlength=False):
"""
Very old way of doing pretty printing. Need to update and refactor.
DEPRICATE
"""
from utool import util_dev
# Move to util_dev
# NUMPY ARRAY
import numpy as np
if type(val) is np.ndarray:
info = npArrInfo(val)
if info.dtypestr.startswith('bool'):
_valstr = '{ shape:' + info.shapestr + ' bittotal: ' + info.bittotal + '}'
# + '\n |_____'
elif info.dtypestr.startswith('float'):
_valstr = util_dev.get_stats_str(val)
else:
_valstr = '{ shape:' + info.shapestr + ' mM:' + info.minmaxstr + ' }' # + '\n |_____'
# String
elif isinstance(val, (str, unicode)): # NOQA
_valstr = '\'%s\'' % val
# List
elif isinstance(val, list):
if justlength or len(val) > 30:
_valstr = 'len=' + str(len(val))
else:
_valstr = '[ ' + (', \n '.join([str(v) for v in val])) + ' ]'
# ??? isinstance(val, AbstractPrintable):
elif hasattr(val, 'get_printable') and type(val) != type:
_valstr = val.get_printable(type_bit=type_bit)
elif isinstance(val, dict):
_valstr = '{\n'
for val_key in val.keys():
val_val = val[val_key]
_valstr += ' ' + str(val_key) + ' : ' + str(val_val) + '\n'
_valstr += '}'
else:
_valstr = str(val)
if _valstr.find('\n') > 0: # Indent if necessary
_valstr = _valstr.replace('\n', '\n ')
_valstr = '\n ' + _valstr
_valstr = re.sub('\n *$', '', _valstr) # Replace empty lines
return _valstr | [
"def",
"printableVal",
"(",
"val",
",",
"type_bit",
"=",
"True",
",",
"justlength",
"=",
"False",
")",
":",
"from",
"utool",
"import",
"util_dev",
"import",
"numpy",
"as",
"np",
"if",
"type",
"(",
"val",
")",
"is",
"np",
".",
"ndarray",
":",
"info",
"=",
"npArrInfo",
"(",
"val",
")",
"if",
"info",
".",
"dtypestr",
".",
"startswith",
"(",
"'bool'",
")",
":",
"_valstr",
"=",
"'{ shape:'",
"+",
"info",
".",
"shapestr",
"+",
"' bittotal: '",
"+",
"info",
".",
"bittotal",
"+",
"'}'",
"elif",
"info",
".",
"dtypestr",
".",
"startswith",
"(",
"'float'",
")",
":",
"_valstr",
"=",
"util_dev",
".",
"get_stats_str",
"(",
"val",
")",
"else",
":",
"_valstr",
"=",
"'{ shape:'",
"+",
"info",
".",
"shapestr",
"+",
"' mM:'",
"+",
"info",
".",
"minmaxstr",
"+",
"' }'",
"elif",
"isinstance",
"(",
"val",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"_valstr",
"=",
"'\\'%s\\''",
"%",
"val",
"elif",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"if",
"justlength",
"or",
"len",
"(",
"val",
")",
">",
"30",
":",
"_valstr",
"=",
"'len='",
"+",
"str",
"(",
"len",
"(",
"val",
")",
")",
"else",
":",
"_valstr",
"=",
"'[ '",
"+",
"(",
"', \\n '",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"val",
"]",
")",
")",
"+",
"' ]'",
"elif",
"hasattr",
"(",
"val",
",",
"'get_printable'",
")",
"and",
"type",
"(",
"val",
")",
"!=",
"type",
":",
"_valstr",
"=",
"val",
".",
"get_printable",
"(",
"type_bit",
"=",
"type_bit",
")",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"_valstr",
"=",
"'{\\n'",
"for",
"val_key",
"in",
"val",
".",
"keys",
"(",
")",
":",
"val_val",
"=",
"val",
"[",
"val_key",
"]",
"_valstr",
"+=",
"' '",
"+",
"str",
"(",
"val_key",
")",
"+",
"' : '",
"+",
"str",
"(",
"val_val",
")",
"+",
"'\\n'",
"_valstr",
"+=",
"'}'",
"else",
":",
"_valstr",
"=",
"str",
"(",
"val",
")",
"if",
"_valstr",
".",
"find",
"(",
"'\\n'",
")",
">",
"0",
":",
"_valstr",
"=",
"_valstr",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n '",
")",
"_valstr",
"=",
"'\\n '",
"+",
"_valstr",
"_valstr",
"=",
"re",
".",
"sub",
"(",
"'\\n *$'",
",",
"''",
",",
"_valstr",
")",
"return",
"_valstr"
] | Very old way of doing pretty printing. Need to update and refactor.
DEPRICATE | [
"Very",
"old",
"way",
"of",
"doing",
"pretty",
"printing",
".",
"Need",
"to",
"update",
"and",
"refactor",
".",
"DEPRICATE"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L121-L163 | train |
Erotemic/utool | utool/Printable.py | npArrInfo | def npArrInfo(arr):
"""
OLD update and refactor
"""
from utool.DynamicStruct import DynStruct
info = DynStruct()
info.shapestr = '[' + ' x '.join([str(x) for x in arr.shape]) + ']'
info.dtypestr = str(arr.dtype)
if info.dtypestr == 'bool':
info.bittotal = 'T=%d, F=%d' % (sum(arr), sum(1 - arr))
elif info.dtypestr == 'object':
info.minmaxstr = 'NA'
elif info.dtypestr[0] == '|':
info.minmaxstr = 'NA'
else:
if arr.size > 0:
info.minmaxstr = '(%r, %r)' % (arr.min(), arr.max())
else:
info.minmaxstr = '(None)'
return info | python | def npArrInfo(arr):
"""
OLD update and refactor
"""
from utool.DynamicStruct import DynStruct
info = DynStruct()
info.shapestr = '[' + ' x '.join([str(x) for x in arr.shape]) + ']'
info.dtypestr = str(arr.dtype)
if info.dtypestr == 'bool':
info.bittotal = 'T=%d, F=%d' % (sum(arr), sum(1 - arr))
elif info.dtypestr == 'object':
info.minmaxstr = 'NA'
elif info.dtypestr[0] == '|':
info.minmaxstr = 'NA'
else:
if arr.size > 0:
info.minmaxstr = '(%r, %r)' % (arr.min(), arr.max())
else:
info.minmaxstr = '(None)'
return info | [
"def",
"npArrInfo",
"(",
"arr",
")",
":",
"from",
"utool",
".",
"DynamicStruct",
"import",
"DynStruct",
"info",
"=",
"DynStruct",
"(",
")",
"info",
".",
"shapestr",
"=",
"'['",
"+",
"' x '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"arr",
".",
"shape",
"]",
")",
"+",
"']'",
"info",
".",
"dtypestr",
"=",
"str",
"(",
"arr",
".",
"dtype",
")",
"if",
"info",
".",
"dtypestr",
"==",
"'bool'",
":",
"info",
".",
"bittotal",
"=",
"'T=%d, F=%d'",
"%",
"(",
"sum",
"(",
"arr",
")",
",",
"sum",
"(",
"1",
"-",
"arr",
")",
")",
"elif",
"info",
".",
"dtypestr",
"==",
"'object'",
":",
"info",
".",
"minmaxstr",
"=",
"'NA'",
"elif",
"info",
".",
"dtypestr",
"[",
"0",
"]",
"==",
"'|'",
":",
"info",
".",
"minmaxstr",
"=",
"'NA'",
"else",
":",
"if",
"arr",
".",
"size",
">",
"0",
":",
"info",
".",
"minmaxstr",
"=",
"'(%r, %r)'",
"%",
"(",
"arr",
".",
"min",
"(",
")",
",",
"arr",
".",
"max",
"(",
")",
")",
"else",
":",
"info",
".",
"minmaxstr",
"=",
"'(None)'",
"return",
"info"
] | OLD update and refactor | [
"OLD",
"update",
"and",
"refactor"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L166-L185 | train |
glormph/msstitch | src/app/actions/mzidtsv/isonormalize.py | get_isobaric_ratios | def get_isobaric_ratios(psmfn, psmheader, channels, denom_channels, min_int,
targetfn, accessioncol, normalize, normratiofn):
"""Main function to calculate ratios for PSMs, peptides, proteins, genes.
Can do simple ratios, median-of-ratios and median-centering
normalization."""
psm_or_feat_ratios = get_psmratios(psmfn, psmheader, channels,
denom_channels, min_int, accessioncol)
if normalize and normratiofn:
normheader = reader.get_tsv_header(normratiofn)
normratios = get_ratios_from_fn(normratiofn, normheader, channels)
ch_medians = get_medians(channels, normratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
elif normalize:
flatratios = [[feat[ch] for ch in channels]
for feat in psm_or_feat_ratios]
ch_medians = get_medians(channels, flatratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
else:
outratios = psm_or_feat_ratios
# at this point, outratios look like:
# [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ]
if accessioncol and targetfn:
outratios = {x[ISOQUANTRATIO_FEAT_ACC]: x for x in outratios}
return output_to_target_accession_table(targetfn, outratios, channels)
elif not accessioncol and not targetfn:
return paste_to_psmtable(psmfn, psmheader, outratios)
elif accessioncol and not targetfn:
# generate new table with accessions
return ({(k if not k == ISOQUANTRATIO_FEAT_ACC
else prottabledata.HEADER_ACCESSION): v
for k, v in ratio.items()} for ratio in outratios) | python | def get_isobaric_ratios(psmfn, psmheader, channels, denom_channels, min_int,
targetfn, accessioncol, normalize, normratiofn):
"""Main function to calculate ratios for PSMs, peptides, proteins, genes.
Can do simple ratios, median-of-ratios and median-centering
normalization."""
psm_or_feat_ratios = get_psmratios(psmfn, psmheader, channels,
denom_channels, min_int, accessioncol)
if normalize and normratiofn:
normheader = reader.get_tsv_header(normratiofn)
normratios = get_ratios_from_fn(normratiofn, normheader, channels)
ch_medians = get_medians(channels, normratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
elif normalize:
flatratios = [[feat[ch] for ch in channels]
for feat in psm_or_feat_ratios]
ch_medians = get_medians(channels, flatratios, report=True)
outratios = calculate_normalized_ratios(psm_or_feat_ratios, ch_medians,
channels)
else:
outratios = psm_or_feat_ratios
# at this point, outratios look like:
# [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ]
if accessioncol and targetfn:
outratios = {x[ISOQUANTRATIO_FEAT_ACC]: x for x in outratios}
return output_to_target_accession_table(targetfn, outratios, channels)
elif not accessioncol and not targetfn:
return paste_to_psmtable(psmfn, psmheader, outratios)
elif accessioncol and not targetfn:
# generate new table with accessions
return ({(k if not k == ISOQUANTRATIO_FEAT_ACC
else prottabledata.HEADER_ACCESSION): v
for k, v in ratio.items()} for ratio in outratios) | [
"def",
"get_isobaric_ratios",
"(",
"psmfn",
",",
"psmheader",
",",
"channels",
",",
"denom_channels",
",",
"min_int",
",",
"targetfn",
",",
"accessioncol",
",",
"normalize",
",",
"normratiofn",
")",
":",
"psm_or_feat_ratios",
"=",
"get_psmratios",
"(",
"psmfn",
",",
"psmheader",
",",
"channels",
",",
"denom_channels",
",",
"min_int",
",",
"accessioncol",
")",
"if",
"normalize",
"and",
"normratiofn",
":",
"normheader",
"=",
"reader",
".",
"get_tsv_header",
"(",
"normratiofn",
")",
"normratios",
"=",
"get_ratios_from_fn",
"(",
"normratiofn",
",",
"normheader",
",",
"channels",
")",
"ch_medians",
"=",
"get_medians",
"(",
"channels",
",",
"normratios",
",",
"report",
"=",
"True",
")",
"outratios",
"=",
"calculate_normalized_ratios",
"(",
"psm_or_feat_ratios",
",",
"ch_medians",
",",
"channels",
")",
"elif",
"normalize",
":",
"flatratios",
"=",
"[",
"[",
"feat",
"[",
"ch",
"]",
"for",
"ch",
"in",
"channels",
"]",
"for",
"feat",
"in",
"psm_or_feat_ratios",
"]",
"ch_medians",
"=",
"get_medians",
"(",
"channels",
",",
"flatratios",
",",
"report",
"=",
"True",
")",
"outratios",
"=",
"calculate_normalized_ratios",
"(",
"psm_or_feat_ratios",
",",
"ch_medians",
",",
"channels",
")",
"else",
":",
"outratios",
"=",
"psm_or_feat_ratios",
"if",
"accessioncol",
"and",
"targetfn",
":",
"outratios",
"=",
"{",
"x",
"[",
"ISOQUANTRATIO_FEAT_ACC",
"]",
":",
"x",
"for",
"x",
"in",
"outratios",
"}",
"return",
"output_to_target_accession_table",
"(",
"targetfn",
",",
"outratios",
",",
"channels",
")",
"elif",
"not",
"accessioncol",
"and",
"not",
"targetfn",
":",
"return",
"paste_to_psmtable",
"(",
"psmfn",
",",
"psmheader",
",",
"outratios",
")",
"elif",
"accessioncol",
"and",
"not",
"targetfn",
":",
"return",
"(",
"{",
"(",
"k",
"if",
"not",
"k",
"==",
"ISOQUANTRATIO_FEAT_ACC",
"else",
"prottabledata",
".",
"HEADER_ACCESSION",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"ratio",
".",
"items",
"(",
")",
"}",
"for",
"ratio",
"in",
"outratios",
")"
] | Main function to calculate ratios for PSMs, peptides, proteins, genes.
Can do simple ratios, median-of-ratios and median-centering
normalization. | [
"Main",
"function",
"to",
"calculate",
"ratios",
"for",
"PSMs",
"peptides",
"proteins",
"genes",
".",
"Can",
"do",
"simple",
"ratios",
"median",
"-",
"of",
"-",
"ratios",
"and",
"median",
"-",
"centering",
"normalization",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/isonormalize.py#L13-L45 | train |
timedata-org/loady | loady/files.py | sanitize | def sanitize(value):
"""Strips all undesirable characters out of potential file paths."""
value = unicodedata.normalize('NFKD', value)
value = value.strip()
value = re.sub('[^./\w\s-]', '', value)
value = re.sub('[-\s]+', '-', value)
return value | python | def sanitize(value):
"""Strips all undesirable characters out of potential file paths."""
value = unicodedata.normalize('NFKD', value)
value = value.strip()
value = re.sub('[^./\w\s-]', '', value)
value = re.sub('[-\s]+', '-', value)
return value | [
"def",
"sanitize",
"(",
"value",
")",
":",
"value",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"value",
")",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"'[^./\\w\\s-]'",
",",
"''",
",",
"value",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"'[-\\s]+'",
",",
"'-'",
",",
"value",
")",
"return",
"value"
] | Strips all undesirable characters out of potential file paths. | [
"Strips",
"all",
"undesirable",
"characters",
"out",
"of",
"potential",
"file",
"paths",
"."
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/files.py#L10-L18 | train |
timedata-org/loady | loady/files.py | remove_on_exception | def remove_on_exception(dirname, remove=True):
"""Creates a directory, yields to the caller, and removes that directory
if an exception is thrown."""
os.makedirs(dirname)
try:
yield
except:
if remove:
shutil.rmtree(dirname, ignore_errors=True)
raise | python | def remove_on_exception(dirname, remove=True):
"""Creates a directory, yields to the caller, and removes that directory
if an exception is thrown."""
os.makedirs(dirname)
try:
yield
except:
if remove:
shutil.rmtree(dirname, ignore_errors=True)
raise | [
"def",
"remove_on_exception",
"(",
"dirname",
",",
"remove",
"=",
"True",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"try",
":",
"yield",
"except",
":",
"if",
"remove",
":",
"shutil",
".",
"rmtree",
"(",
"dirname",
",",
"ignore_errors",
"=",
"True",
")",
"raise"
] | Creates a directory, yields to the caller, and removes that directory
if an exception is thrown. | [
"Creates",
"a",
"directory",
"yields",
"to",
"the",
"caller",
"and",
"removes",
"that",
"directory",
"if",
"an",
"exception",
"is",
"thrown",
"."
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/files.py#L22-L31 | train |
glormph/msstitch | src/app/actions/mzidtsv/percolator.py | add_percolator_to_mzidtsv | def add_percolator_to_mzidtsv(mzidfn, tsvfn, multipsm, oldheader):
"""Takes a MSGF+ tsv and corresponding mzId, adds percolatordata
to tsv lines. Generator yields the lines. Multiple PSMs per scan
can be delivered, in which case rank is also reported.
"""
namespace = readers.get_mzid_namespace(mzidfn)
try:
xmlns = '{%s}' % namespace['xmlns']
except TypeError:
xmlns = ''
specfnids = readers.get_mzid_specfile_ids(mzidfn, namespace)
mzidpepmap = {}
for peptide in readers.generate_mzid_peptides(mzidfn, namespace):
pep_id, seq = readers.get_mzid_peptidedata(peptide, xmlns)
mzidpepmap[pep_id] = seq
mzidpercomap = {}
for specid_data in readers.generate_mzid_spec_id_items(mzidfn, namespace,
xmlns, specfnids):
scan, fn, pepid, spec_id = specid_data
percodata = readers.get_specidentitem_percolator_data(spec_id, xmlns)
try:
mzidpercomap[fn][scan][mzidpepmap[pepid]] = percodata
except KeyError:
try:
mzidpercomap[fn][scan] = {mzidpepmap[pepid]: percodata}
except KeyError:
mzidpercomap[fn] = {scan: {mzidpepmap[pepid]: percodata}}
for line in tsvreader.generate_tsv_psms(tsvfn, oldheader):
outline = {k: v for k, v in line.items()}
fn = line[mzidtsvdata.HEADER_SPECFILE]
scan = line[mzidtsvdata.HEADER_SCANNR]
seq = line[mzidtsvdata.HEADER_PEPTIDE]
outline.update(mzidpercomap[fn][scan][seq])
yield outline | python | def add_percolator_to_mzidtsv(mzidfn, tsvfn, multipsm, oldheader):
"""Takes a MSGF+ tsv and corresponding mzId, adds percolatordata
to tsv lines. Generator yields the lines. Multiple PSMs per scan
can be delivered, in which case rank is also reported.
"""
namespace = readers.get_mzid_namespace(mzidfn)
try:
xmlns = '{%s}' % namespace['xmlns']
except TypeError:
xmlns = ''
specfnids = readers.get_mzid_specfile_ids(mzidfn, namespace)
mzidpepmap = {}
for peptide in readers.generate_mzid_peptides(mzidfn, namespace):
pep_id, seq = readers.get_mzid_peptidedata(peptide, xmlns)
mzidpepmap[pep_id] = seq
mzidpercomap = {}
for specid_data in readers.generate_mzid_spec_id_items(mzidfn, namespace,
xmlns, specfnids):
scan, fn, pepid, spec_id = specid_data
percodata = readers.get_specidentitem_percolator_data(spec_id, xmlns)
try:
mzidpercomap[fn][scan][mzidpepmap[pepid]] = percodata
except KeyError:
try:
mzidpercomap[fn][scan] = {mzidpepmap[pepid]: percodata}
except KeyError:
mzidpercomap[fn] = {scan: {mzidpepmap[pepid]: percodata}}
for line in tsvreader.generate_tsv_psms(tsvfn, oldheader):
outline = {k: v for k, v in line.items()}
fn = line[mzidtsvdata.HEADER_SPECFILE]
scan = line[mzidtsvdata.HEADER_SCANNR]
seq = line[mzidtsvdata.HEADER_PEPTIDE]
outline.update(mzidpercomap[fn][scan][seq])
yield outline | [
"def",
"add_percolator_to_mzidtsv",
"(",
"mzidfn",
",",
"tsvfn",
",",
"multipsm",
",",
"oldheader",
")",
":",
"namespace",
"=",
"readers",
".",
"get_mzid_namespace",
"(",
"mzidfn",
")",
"try",
":",
"xmlns",
"=",
"'{%s}'",
"%",
"namespace",
"[",
"'xmlns'",
"]",
"except",
"TypeError",
":",
"xmlns",
"=",
"''",
"specfnids",
"=",
"readers",
".",
"get_mzid_specfile_ids",
"(",
"mzidfn",
",",
"namespace",
")",
"mzidpepmap",
"=",
"{",
"}",
"for",
"peptide",
"in",
"readers",
".",
"generate_mzid_peptides",
"(",
"mzidfn",
",",
"namespace",
")",
":",
"pep_id",
",",
"seq",
"=",
"readers",
".",
"get_mzid_peptidedata",
"(",
"peptide",
",",
"xmlns",
")",
"mzidpepmap",
"[",
"pep_id",
"]",
"=",
"seq",
"mzidpercomap",
"=",
"{",
"}",
"for",
"specid_data",
"in",
"readers",
".",
"generate_mzid_spec_id_items",
"(",
"mzidfn",
",",
"namespace",
",",
"xmlns",
",",
"specfnids",
")",
":",
"scan",
",",
"fn",
",",
"pepid",
",",
"spec_id",
"=",
"specid_data",
"percodata",
"=",
"readers",
".",
"get_specidentitem_percolator_data",
"(",
"spec_id",
",",
"xmlns",
")",
"try",
":",
"mzidpercomap",
"[",
"fn",
"]",
"[",
"scan",
"]",
"[",
"mzidpepmap",
"[",
"pepid",
"]",
"]",
"=",
"percodata",
"except",
"KeyError",
":",
"try",
":",
"mzidpercomap",
"[",
"fn",
"]",
"[",
"scan",
"]",
"=",
"{",
"mzidpepmap",
"[",
"pepid",
"]",
":",
"percodata",
"}",
"except",
"KeyError",
":",
"mzidpercomap",
"[",
"fn",
"]",
"=",
"{",
"scan",
":",
"{",
"mzidpepmap",
"[",
"pepid",
"]",
":",
"percodata",
"}",
"}",
"for",
"line",
"in",
"tsvreader",
".",
"generate_tsv_psms",
"(",
"tsvfn",
",",
"oldheader",
")",
":",
"outline",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"line",
".",
"items",
"(",
")",
"}",
"fn",
"=",
"line",
"[",
"mzidtsvdata",
".",
"HEADER_SPECFILE",
"]",
"scan",
"=",
"line",
"[",
"mzidtsvdata",
".",
"HEADER_SCANNR",
"]",
"seq",
"=",
"line",
"[",
"mzidtsvdata",
".",
"HEADER_PEPTIDE",
"]",
"outline",
".",
"update",
"(",
"mzidpercomap",
"[",
"fn",
"]",
"[",
"scan",
"]",
"[",
"seq",
"]",
")",
"yield",
"outline"
] | Takes a MSGF+ tsv and corresponding mzId, adds percolatordata
to tsv lines. Generator yields the lines. Multiple PSMs per scan
can be delivered, in which case rank is also reported. | [
"Takes",
"a",
"MSGF",
"+",
"tsv",
"and",
"corresponding",
"mzId",
"adds",
"percolatordata",
"to",
"tsv",
"lines",
".",
"Generator",
"yields",
"the",
"lines",
".",
"Multiple",
"PSMs",
"per",
"scan",
"can",
"be",
"delivered",
"in",
"which",
"case",
"rank",
"is",
"also",
"reported",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/percolator.py#L6-L39 | train |
Erotemic/utool | utool/util_profile.py | parse_rawprofile_blocks | def parse_rawprofile_blocks(text):
"""
Split the file into blocks along delimters and and put delimeters back in
the list
"""
# The total time reported in the raw output is from pystone not kernprof
# The pystone total time is actually the average time spent in the function
delim = 'Total time: '
delim2 = 'Pystone time: '
#delim = 'File: '
profile_block_list = ut.regex_split('^' + delim, text)
for ix in range(1, len(profile_block_list)):
profile_block_list[ix] = delim2 + profile_block_list[ix]
return profile_block_list | python | def parse_rawprofile_blocks(text):
"""
Split the file into blocks along delimters and and put delimeters back in
the list
"""
# The total time reported in the raw output is from pystone not kernprof
# The pystone total time is actually the average time spent in the function
delim = 'Total time: '
delim2 = 'Pystone time: '
#delim = 'File: '
profile_block_list = ut.regex_split('^' + delim, text)
for ix in range(1, len(profile_block_list)):
profile_block_list[ix] = delim2 + profile_block_list[ix]
return profile_block_list | [
"def",
"parse_rawprofile_blocks",
"(",
"text",
")",
":",
"delim",
"=",
"'Total time: '",
"delim2",
"=",
"'Pystone time: '",
"profile_block_list",
"=",
"ut",
".",
"regex_split",
"(",
"'^'",
"+",
"delim",
",",
"text",
")",
"for",
"ix",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"profile_block_list",
")",
")",
":",
"profile_block_list",
"[",
"ix",
"]",
"=",
"delim2",
"+",
"profile_block_list",
"[",
"ix",
"]",
"return",
"profile_block_list"
] | Split the file into blocks along delimters and and put delimeters back in
the list | [
"Split",
"the",
"file",
"into",
"blocks",
"along",
"delimters",
"and",
"and",
"put",
"delimeters",
"back",
"in",
"the",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L78-L91 | train |
Erotemic/utool | utool/util_profile.py | parse_timemap_from_blocks | def parse_timemap_from_blocks(profile_block_list):
"""
Build a map from times to line_profile blocks
"""
prefix_list = []
timemap = ut.ddict(list)
for ix in range(len(profile_block_list)):
block = profile_block_list[ix]
total_time = get_block_totaltime(block)
# Blocks without time go at the front of sorted output
if total_time is None:
prefix_list.append(block)
# Blocks that are not run are not appended to output
elif total_time != 0:
timemap[total_time].append(block)
return prefix_list, timemap | python | def parse_timemap_from_blocks(profile_block_list):
"""
Build a map from times to line_profile blocks
"""
prefix_list = []
timemap = ut.ddict(list)
for ix in range(len(profile_block_list)):
block = profile_block_list[ix]
total_time = get_block_totaltime(block)
# Blocks without time go at the front of sorted output
if total_time is None:
prefix_list.append(block)
# Blocks that are not run are not appended to output
elif total_time != 0:
timemap[total_time].append(block)
return prefix_list, timemap | [
"def",
"parse_timemap_from_blocks",
"(",
"profile_block_list",
")",
":",
"prefix_list",
"=",
"[",
"]",
"timemap",
"=",
"ut",
".",
"ddict",
"(",
"list",
")",
"for",
"ix",
"in",
"range",
"(",
"len",
"(",
"profile_block_list",
")",
")",
":",
"block",
"=",
"profile_block_list",
"[",
"ix",
"]",
"total_time",
"=",
"get_block_totaltime",
"(",
"block",
")",
"if",
"total_time",
"is",
"None",
":",
"prefix_list",
".",
"append",
"(",
"block",
")",
"elif",
"total_time",
"!=",
"0",
":",
"timemap",
"[",
"total_time",
"]",
".",
"append",
"(",
"block",
")",
"return",
"prefix_list",
",",
"timemap"
] | Build a map from times to line_profile blocks | [
"Build",
"a",
"map",
"from",
"times",
"to",
"line_profile",
"blocks"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L123-L138 | train |
Erotemic/utool | utool/util_profile.py | clean_line_profile_text | 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 | python | 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 | [
"def",
"clean_line_profile_text",
"(",
"text",
")",
":",
"profile_block_list",
"=",
"parse_rawprofile_blocks",
"(",
"text",
")",
"prefix_list",
",",
"timemap",
"=",
"parse_timemap_from_blocks",
"(",
"profile_block_list",
")",
"sorted_lists",
"=",
"sorted",
"(",
"six",
".",
"iteritems",
"(",
"timemap",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"newlist",
"=",
"prefix_list",
"[",
":",
"]",
"for",
"key",
",",
"val",
"in",
"sorted_lists",
":",
"newlist",
".",
"extend",
"(",
"val",
")",
"output_text",
"=",
"'\\n'",
".",
"join",
"(",
"newlist",
")",
"summary_text",
"=",
"get_summary",
"(",
"profile_block_list",
")",
"output_text",
"=",
"output_text",
"return",
"output_text",
",",
"summary_text"
] | Sorts the output from line profile by execution time
Removes entries which were not run | [
"Sorts",
"the",
"output",
"from",
"line",
"profile",
"by",
"execution",
"time",
"Removes",
"entries",
"which",
"were",
"not",
"run"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L191-L213 | train |
Erotemic/utool | utool/util_profile.py | clean_lprof_file | def clean_lprof_file(input_fname, output_fname=None):
""" Reads a .lprof file and cleans it """
# Read the raw .lprof text dump
text = ut.read_from(input_fname)
# Sort and clean the text
output_text = clean_line_profile_text(text)
return output_text | python | def clean_lprof_file(input_fname, output_fname=None):
""" Reads a .lprof file and cleans it """
# Read the raw .lprof text dump
text = ut.read_from(input_fname)
# Sort and clean the text
output_text = clean_line_profile_text(text)
return output_text | [
"def",
"clean_lprof_file",
"(",
"input_fname",
",",
"output_fname",
"=",
"None",
")",
":",
"text",
"=",
"ut",
".",
"read_from",
"(",
"input_fname",
")",
"output_text",
"=",
"clean_line_profile_text",
"(",
"text",
")",
"return",
"output_text"
] | Reads a .lprof file and cleans it | [
"Reads",
"a",
".",
"lprof",
"file",
"and",
"cleans",
"it"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L216-L222 | train |
YuriyGuts/pygoose | pygoose/kg/keras.py | get_class_weights | def get_class_weights(y, smooth_factor=0):
"""
Returns the weights for each class based on the frequencies of the samples.
Args:
y: A list of true labels (the labels must be hashable).
smooth_factor: A factor that smooths extremely uneven weights.
Returns:
A dictionary with the weight for each class.
"""
from collections import Counter
counter = Counter(y)
if smooth_factor > 0:
p = max(counter.values()) * smooth_factor
for k in counter.keys():
counter[k] += p
majority = max(counter.values())
return {cls: float(majority / count) for cls, count in counter.items()} | python | def get_class_weights(y, smooth_factor=0):
"""
Returns the weights for each class based on the frequencies of the samples.
Args:
y: A list of true labels (the labels must be hashable).
smooth_factor: A factor that smooths extremely uneven weights.
Returns:
A dictionary with the weight for each class.
"""
from collections import Counter
counter = Counter(y)
if smooth_factor > 0:
p = max(counter.values()) * smooth_factor
for k in counter.keys():
counter[k] += p
majority = max(counter.values())
return {cls: float(majority / count) for cls, count in counter.items()} | [
"def",
"get_class_weights",
"(",
"y",
",",
"smooth_factor",
"=",
"0",
")",
":",
"from",
"collections",
"import",
"Counter",
"counter",
"=",
"Counter",
"(",
"y",
")",
"if",
"smooth_factor",
">",
"0",
":",
"p",
"=",
"max",
"(",
"counter",
".",
"values",
"(",
")",
")",
"*",
"smooth_factor",
"for",
"k",
"in",
"counter",
".",
"keys",
"(",
")",
":",
"counter",
"[",
"k",
"]",
"+=",
"p",
"majority",
"=",
"max",
"(",
"counter",
".",
"values",
"(",
")",
")",
"return",
"{",
"cls",
":",
"float",
"(",
"majority",
"/",
"count",
")",
"for",
"cls",
",",
"count",
"in",
"counter",
".",
"items",
"(",
")",
"}"
] | Returns the weights for each class based on the frequencies of the samples.
Args:
y: A list of true labels (the labels must be hashable).
smooth_factor: A factor that smooths extremely uneven weights.
Returns:
A dictionary with the weight for each class. | [
"Returns",
"the",
"weights",
"for",
"each",
"class",
"based",
"on",
"the",
"frequencies",
"of",
"the",
"samples",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/keras.py#L4-L26 | train |
YuriyGuts/pygoose | pygoose/kg/keras.py | plot_loss_history | def plot_loss_history(history, figsize=(15, 8)):
"""
Plots the learning history for a Keras model,
assuming the validation data was provided to the 'fit' function.
Args:
history: The return value from the 'fit' function.
figsize: The size of the plot.
"""
plt.figure(figsize=figsize)
plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.xlabel("# Epochs")
plt.ylabel("Loss")
plt.legend(["Training", "Validation"])
plt.title("Loss over time")
plt.show() | python | def plot_loss_history(history, figsize=(15, 8)):
"""
Plots the learning history for a Keras model,
assuming the validation data was provided to the 'fit' function.
Args:
history: The return value from the 'fit' function.
figsize: The size of the plot.
"""
plt.figure(figsize=figsize)
plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.xlabel("# Epochs")
plt.ylabel("Loss")
plt.legend(["Training", "Validation"])
plt.title("Loss over time")
plt.show() | [
"def",
"plot_loss_history",
"(",
"history",
",",
"figsize",
"=",
"(",
"15",
",",
"8",
")",
")",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"plot",
"(",
"history",
".",
"history",
"[",
"\"loss\"",
"]",
")",
"plt",
".",
"plot",
"(",
"history",
".",
"history",
"[",
"\"val_loss\"",
"]",
")",
"plt",
".",
"xlabel",
"(",
"\"# Epochs\"",
")",
"plt",
".",
"ylabel",
"(",
"\"Loss\"",
")",
"plt",
".",
"legend",
"(",
"[",
"\"Training\"",
",",
"\"Validation\"",
"]",
")",
"plt",
".",
"title",
"(",
"\"Loss over time\"",
")",
"plt",
".",
"show",
"(",
")"
] | Plots the learning history for a Keras model,
assuming the validation data was provided to the 'fit' function.
Args:
history: The return value from the 'fit' function.
figsize: The size of the plot. | [
"Plots",
"the",
"learning",
"history",
"for",
"a",
"Keras",
"model",
"assuming",
"the",
"validation",
"data",
"was",
"provided",
"to",
"the",
"fit",
"function",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/keras.py#L29-L49 | train |
Erotemic/utool | utool/util_iter.py | iter_window | def iter_window(iterable, size=2, step=1, wrap=False):
r"""
iterates through iterable with a window size
generalizeation of itertwo
Args:
iterable (iter): an iterable sequence
size (int): window size (default = 2)
wrap (bool): wraparound (default = False)
Returns:
iter: returns windows in a sequence
CommandLine:
python -m utool.util_iter --exec-iter_window
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 1, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 1), (6, 1, 2)]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 2, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (3, 4, 5), (5, 6, 1)]
"""
# it.tee may be slow, but works on all iterables
iter_list = it.tee(iterable, size)
if wrap:
# Secondary iterables need to be cycled for wraparound
iter_list = [iter_list[0]] + list(map(it.cycle, iter_list[1:]))
# Step each iterator the approprate number of times
try:
for count, iter_ in enumerate(iter_list[1:], start=1):
for _ in range(count):
six.next(iter_)
except StopIteration:
return iter(())
else:
_window_iter = zip(*iter_list)
# Account for the step size
window_iter = it.islice(_window_iter, 0, None, step)
return window_iter | python | def iter_window(iterable, size=2, step=1, wrap=False):
r"""
iterates through iterable with a window size
generalizeation of itertwo
Args:
iterable (iter): an iterable sequence
size (int): window size (default = 2)
wrap (bool): wraparound (default = False)
Returns:
iter: returns windows in a sequence
CommandLine:
python -m utool.util_iter --exec-iter_window
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 1, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 1), (6, 1, 2)]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 2, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (3, 4, 5), (5, 6, 1)]
"""
# it.tee may be slow, but works on all iterables
iter_list = it.tee(iterable, size)
if wrap:
# Secondary iterables need to be cycled for wraparound
iter_list = [iter_list[0]] + list(map(it.cycle, iter_list[1:]))
# Step each iterator the approprate number of times
try:
for count, iter_ in enumerate(iter_list[1:], start=1):
for _ in range(count):
six.next(iter_)
except StopIteration:
return iter(())
else:
_window_iter = zip(*iter_list)
# Account for the step size
window_iter = it.islice(_window_iter, 0, None, step)
return window_iter | [
"def",
"iter_window",
"(",
"iterable",
",",
"size",
"=",
"2",
",",
"step",
"=",
"1",
",",
"wrap",
"=",
"False",
")",
":",
"r",
"iter_list",
"=",
"it",
".",
"tee",
"(",
"iterable",
",",
"size",
")",
"if",
"wrap",
":",
"iter_list",
"=",
"[",
"iter_list",
"[",
"0",
"]",
"]",
"+",
"list",
"(",
"map",
"(",
"it",
".",
"cycle",
",",
"iter_list",
"[",
"1",
":",
"]",
")",
")",
"try",
":",
"for",
"count",
",",
"iter_",
"in",
"enumerate",
"(",
"iter_list",
"[",
"1",
":",
"]",
",",
"start",
"=",
"1",
")",
":",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"six",
".",
"next",
"(",
"iter_",
")",
"except",
"StopIteration",
":",
"return",
"iter",
"(",
"(",
")",
")",
"else",
":",
"_window_iter",
"=",
"zip",
"(",
"*",
"iter_list",
")",
"window_iter",
"=",
"it",
".",
"islice",
"(",
"_window_iter",
",",
"0",
",",
"None",
",",
"step",
")",
"return",
"window_iter"
] | r"""
iterates through iterable with a window size
generalizeation of itertwo
Args:
iterable (iter): an iterable sequence
size (int): window size (default = 2)
wrap (bool): wraparound (default = False)
Returns:
iter: returns windows in a sequence
CommandLine:
python -m utool.util_iter --exec-iter_window
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 1, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 1), (6, 1, 2)]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6]
>>> size, step, wrap = 3, 2, True
>>> window_iter = iter_window(iterable, size, step, wrap)
>>> window_list = list(window_iter)
>>> result = ('window_list = %r' % (window_list,))
>>> print(result)
window_list = [(1, 2, 3), (3, 4, 5), (5, 6, 1)] | [
"r",
"iterates",
"through",
"iterable",
"with",
"a",
"window",
"size",
"generalizeation",
"of",
"itertwo"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L89-L143 | train |
Erotemic/utool | utool/util_iter.py | iter_compress | def iter_compress(item_iter, flag_iter):
"""
iter_compress - like numpy compress
Args:
item_iter (list):
flag_iter (list): of bools
Returns:
list: true_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> item_iter = [1, 2, 3, 4, 5]
>>> flag_iter = [False, True, True, False, True]
>>> true_items = iter_compress(item_iter, flag_iter)
>>> result = list(true_items)
>>> print(result)
[2, 3, 5]
"""
# TODO: Just use it.compress
true_items = (item for (item, flag) in zip(item_iter, flag_iter) if flag)
return true_items | python | def iter_compress(item_iter, flag_iter):
"""
iter_compress - like numpy compress
Args:
item_iter (list):
flag_iter (list): of bools
Returns:
list: true_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> item_iter = [1, 2, 3, 4, 5]
>>> flag_iter = [False, True, True, False, True]
>>> true_items = iter_compress(item_iter, flag_iter)
>>> result = list(true_items)
>>> print(result)
[2, 3, 5]
"""
# TODO: Just use it.compress
true_items = (item for (item, flag) in zip(item_iter, flag_iter) if flag)
return true_items | [
"def",
"iter_compress",
"(",
"item_iter",
",",
"flag_iter",
")",
":",
"true_items",
"=",
"(",
"item",
"for",
"(",
"item",
",",
"flag",
")",
"in",
"zip",
"(",
"item_iter",
",",
"flag_iter",
")",
"if",
"flag",
")",
"return",
"true_items"
] | iter_compress - like numpy compress
Args:
item_iter (list):
flag_iter (list): of bools
Returns:
list: true_items
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> item_iter = [1, 2, 3, 4, 5]
>>> flag_iter = [False, True, True, False, True]
>>> true_items = iter_compress(item_iter, flag_iter)
>>> result = list(true_items)
>>> print(result)
[2, 3, 5] | [
"iter_compress",
"-",
"like",
"numpy",
"compress"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L232-L255 | train |
Erotemic/utool | utool/util_iter.py | ichunks | def ichunks(iterable, chunksize, bordermode=None):
r"""
generates successive n-sized chunks from ``iterable``.
Args:
iterable (list): input to iterate over
chunksize (int): size of sublist to return
bordermode (str): None, 'cycle', or 'replicate'
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks
SeeAlso:
util_progress.get_num_chunks
CommandLine:
python -m utool.util_iter --exec-ichunks --show
Timeit:
>>> import utool as ut
>>> setup = ut.codeblock('''
from utool.util_iter import * # NOQA
iterable = list(range(100))
chunksize = 8
''')
>>> stmt_list = [
... 'list(ichunks(iterable, chunksize))',
... 'list(ichunks_noborder(iterable, chunksize))',
... 'list(ichunks_list(iterable, chunksize))',
... ]
>>> (passed, times, results) = ut.timeit_compare(stmt_list, setup)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6, 7]
>>> chunksize = 3
>>> genresult = ichunks(iterable, chunksize)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'cycle'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 1, 2]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'replicate'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 7, 7]]
"""
if bordermode is None:
return ichunks_noborder(iterable, chunksize)
elif bordermode == 'cycle':
return ichunks_cycle(iterable, chunksize)
elif bordermode == 'replicate':
return ichunks_replicate(iterable, chunksize)
else:
raise ValueError('unknown bordermode=%r' % (bordermode,)) | python | def ichunks(iterable, chunksize, bordermode=None):
r"""
generates successive n-sized chunks from ``iterable``.
Args:
iterable (list): input to iterate over
chunksize (int): size of sublist to return
bordermode (str): None, 'cycle', or 'replicate'
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks
SeeAlso:
util_progress.get_num_chunks
CommandLine:
python -m utool.util_iter --exec-ichunks --show
Timeit:
>>> import utool as ut
>>> setup = ut.codeblock('''
from utool.util_iter import * # NOQA
iterable = list(range(100))
chunksize = 8
''')
>>> stmt_list = [
... 'list(ichunks(iterable, chunksize))',
... 'list(ichunks_noborder(iterable, chunksize))',
... 'list(ichunks_list(iterable, chunksize))',
... ]
>>> (passed, times, results) = ut.timeit_compare(stmt_list, setup)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6, 7]
>>> chunksize = 3
>>> genresult = ichunks(iterable, chunksize)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'cycle'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 1, 2]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'replicate'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 7, 7]]
"""
if bordermode is None:
return ichunks_noborder(iterable, chunksize)
elif bordermode == 'cycle':
return ichunks_cycle(iterable, chunksize)
elif bordermode == 'replicate':
return ichunks_replicate(iterable, chunksize)
else:
raise ValueError('unknown bordermode=%r' % (bordermode,)) | [
"def",
"ichunks",
"(",
"iterable",
",",
"chunksize",
",",
"bordermode",
"=",
"None",
")",
":",
"r",
"if",
"bordermode",
"is",
"None",
":",
"return",
"ichunks_noborder",
"(",
"iterable",
",",
"chunksize",
")",
"elif",
"bordermode",
"==",
"'cycle'",
":",
"return",
"ichunks_cycle",
"(",
"iterable",
",",
"chunksize",
")",
"elif",
"bordermode",
"==",
"'replicate'",
":",
"return",
"ichunks_replicate",
"(",
"iterable",
",",
"chunksize",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown bordermode=%r'",
"%",
"(",
"bordermode",
",",
")",
")"
] | r"""
generates successive n-sized chunks from ``iterable``.
Args:
iterable (list): input to iterate over
chunksize (int): size of sublist to return
bordermode (str): None, 'cycle', or 'replicate'
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks
SeeAlso:
util_progress.get_num_chunks
CommandLine:
python -m utool.util_iter --exec-ichunks --show
Timeit:
>>> import utool as ut
>>> setup = ut.codeblock('''
from utool.util_iter import * # NOQA
iterable = list(range(100))
chunksize = 8
''')
>>> stmt_list = [
... 'list(ichunks(iterable, chunksize))',
... 'list(ichunks_noborder(iterable, chunksize))',
... 'list(ichunks_list(iterable, chunksize))',
... ]
>>> (passed, times, results) = ut.timeit_compare(stmt_list, setup)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = [1, 2, 3, 4, 5, 6, 7]
>>> chunksize = 3
>>> genresult = ichunks(iterable, chunksize)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'cycle'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 1, 2]]
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> iterable = (1, 2, 3, 4, 5, 6, 7)
>>> chunksize = 3
>>> bordermode = 'replicate'
>>> genresult = ichunks(iterable, chunksize, bordermode)
>>> result = list(genresult)
>>> print(result)
[[1, 2, 3], [4, 5, 6], [7, 7, 7]] | [
"r",
"generates",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"iterable",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L340-L411 | train |
Erotemic/utool | utool/util_iter.py | ichunks_list | def ichunks_list(list_, chunksize):
"""
input must be a list.
SeeAlso:
ichunks
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks
"""
return (list_[ix:ix + chunksize] for ix in range(0, len(list_), chunksize)) | python | def ichunks_list(list_, chunksize):
"""
input must be a list.
SeeAlso:
ichunks
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks
"""
return (list_[ix:ix + chunksize] for ix in range(0, len(list_), chunksize)) | [
"def",
"ichunks_list",
"(",
"list_",
",",
"chunksize",
")",
":",
"return",
"(",
"list_",
"[",
"ix",
":",
"ix",
"+",
"chunksize",
"]",
"for",
"ix",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"list_",
")",
",",
"chunksize",
")",
")"
] | input must be a list.
SeeAlso:
ichunks
References:
http://stackoverflow.com/questions/434287/iterate-over-a-list-in-chunks | [
"input",
"must",
"be",
"a",
"list",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L458-L468 | train |
Erotemic/utool | utool/util_iter.py | interleave | def interleave(args):
r"""
zip followed by flatten
Args:
args (tuple): tuple of lists to interleave
SeeAlso:
You may actually be better off doing something like this:
a, b, = args
ut.flatten(ut.bzip(a, b))
ut.flatten(ut.bzip([1, 2, 3], ['-']))
[1, '-', 2, '-', 3, '-']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> args = ([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])
>>> genresult = interleave(args)
>>> result = ut.repr4(list(genresult), nl=False)
>>> print(result)
[1, 'A', 2, 'B', 3, 'C', 4, 'D', 5, 'E']
"""
arg_iters = list(map(iter, args))
cycle_iter = it.cycle(arg_iters)
for iter_ in cycle_iter:
yield six.next(iter_) | python | def interleave(args):
r"""
zip followed by flatten
Args:
args (tuple): tuple of lists to interleave
SeeAlso:
You may actually be better off doing something like this:
a, b, = args
ut.flatten(ut.bzip(a, b))
ut.flatten(ut.bzip([1, 2, 3], ['-']))
[1, '-', 2, '-', 3, '-']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> args = ([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])
>>> genresult = interleave(args)
>>> result = ut.repr4(list(genresult), nl=False)
>>> print(result)
[1, 'A', 2, 'B', 3, 'C', 4, 'D', 5, 'E']
"""
arg_iters = list(map(iter, args))
cycle_iter = it.cycle(arg_iters)
for iter_ in cycle_iter:
yield six.next(iter_) | [
"def",
"interleave",
"(",
"args",
")",
":",
"r",
"arg_iters",
"=",
"list",
"(",
"map",
"(",
"iter",
",",
"args",
")",
")",
"cycle_iter",
"=",
"it",
".",
"cycle",
"(",
"arg_iters",
")",
"for",
"iter_",
"in",
"cycle_iter",
":",
"yield",
"six",
".",
"next",
"(",
"iter_",
")"
] | r"""
zip followed by flatten
Args:
args (tuple): tuple of lists to interleave
SeeAlso:
You may actually be better off doing something like this:
a, b, = args
ut.flatten(ut.bzip(a, b))
ut.flatten(ut.bzip([1, 2, 3], ['-']))
[1, '-', 2, '-', 3, '-']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> args = ([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E', 'F', 'G'])
>>> genresult = interleave(args)
>>> result = ut.repr4(list(genresult), nl=False)
>>> print(result)
[1, 'A', 2, 'B', 3, 'C', 4, 'D', 5, 'E'] | [
"r",
"zip",
"followed",
"by",
"flatten"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L477-L505 | train |
Erotemic/utool | utool/util_iter.py | random_product | def random_product(items, num=None, rng=None):
"""
Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:
import utool as ut
items = [(1, 2, 3), (4, 5, 6, 7)]
rng = 0
list(ut.random_product(items, rng=0))
list(ut.random_product(items, num=3, rng=0))
"""
import utool as ut
rng = ut.ensure_rng(rng, 'python')
seen = set()
items = [list(g) for g in items]
max_num = ut.prod(map(len, items))
if num is None:
num = max_num
if num > max_num:
raise ValueError('num exceedes maximum number of products')
# TODO: make this more efficient when num is large
if num > max_num // 2:
for prod in ut.shuffle(list(it.product(*items)), rng=rng):
yield prod
else:
while len(seen) < num:
# combo = tuple(sorted(rng.choice(items, size, replace=False)))
idxs = tuple(rng.randint(0, len(g) - 1) for g in items)
if idxs not in seen:
seen.add(idxs)
prod = tuple(g[x] for g, x in zip(items, idxs))
yield prod | python | def random_product(items, num=None, rng=None):
"""
Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:
import utool as ut
items = [(1, 2, 3), (4, 5, 6, 7)]
rng = 0
list(ut.random_product(items, rng=0))
list(ut.random_product(items, num=3, rng=0))
"""
import utool as ut
rng = ut.ensure_rng(rng, 'python')
seen = set()
items = [list(g) for g in items]
max_num = ut.prod(map(len, items))
if num is None:
num = max_num
if num > max_num:
raise ValueError('num exceedes maximum number of products')
# TODO: make this more efficient when num is large
if num > max_num // 2:
for prod in ut.shuffle(list(it.product(*items)), rng=rng):
yield prod
else:
while len(seen) < num:
# combo = tuple(sorted(rng.choice(items, size, replace=False)))
idxs = tuple(rng.randint(0, len(g) - 1) for g in items)
if idxs not in seen:
seen.add(idxs)
prod = tuple(g[x] for g, x in zip(items, idxs))
yield prod | [
"def",
"random_product",
"(",
"items",
",",
"num",
"=",
"None",
",",
"rng",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"rng",
"=",
"ut",
".",
"ensure_rng",
"(",
"rng",
",",
"'python'",
")",
"seen",
"=",
"set",
"(",
")",
"items",
"=",
"[",
"list",
"(",
"g",
")",
"for",
"g",
"in",
"items",
"]",
"max_num",
"=",
"ut",
".",
"prod",
"(",
"map",
"(",
"len",
",",
"items",
")",
")",
"if",
"num",
"is",
"None",
":",
"num",
"=",
"max_num",
"if",
"num",
">",
"max_num",
":",
"raise",
"ValueError",
"(",
"'num exceedes maximum number of products'",
")",
"if",
"num",
">",
"max_num",
"//",
"2",
":",
"for",
"prod",
"in",
"ut",
".",
"shuffle",
"(",
"list",
"(",
"it",
".",
"product",
"(",
"*",
"items",
")",
")",
",",
"rng",
"=",
"rng",
")",
":",
"yield",
"prod",
"else",
":",
"while",
"len",
"(",
"seen",
")",
"<",
"num",
":",
"idxs",
"=",
"tuple",
"(",
"rng",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"g",
")",
"-",
"1",
")",
"for",
"g",
"in",
"items",
")",
"if",
"idxs",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"idxs",
")",
"prod",
"=",
"tuple",
"(",
"g",
"[",
"x",
"]",
"for",
"g",
",",
"x",
"in",
"zip",
"(",
"items",
",",
"idxs",
")",
")",
"yield",
"prod"
] | Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:
import utool as ut
items = [(1, 2, 3), (4, 5, 6, 7)]
rng = 0
list(ut.random_product(items, rng=0))
list(ut.random_product(items, num=3, rng=0)) | [
"Yields",
"num",
"items",
"from",
"the",
"cartesian",
"product",
"of",
"items",
"in",
"a",
"random",
"order",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L512-L549 | train |
Erotemic/utool | utool/util_iter.py | random_combinations | def random_combinations(items, size, num=None, rng=None):
"""
Yields `num` combinations of length `size` from items in random order
Args:
items (?):
size (?):
num (None): (default = None)
rng (RandomState): random number generator(default = None)
Yields:
tuple: combo
CommandLine:
python -m utool.util_iter random_combinations
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(range(10))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(zip(range(10), range(10)))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result)
"""
import scipy.misc
import numpy as np
import utool as ut
rng = ut.ensure_rng(rng, impl='python')
num_ = np.inf if num is None else num
# Ensure we dont request more than is possible
n_max = int(scipy.misc.comb(len(items), size))
num_ = min(n_max, num_)
if num is not None and num_ > n_max // 2:
# If num is too big just generate all combinations and shuffle them
combos = list(it.combinations(items, size))
rng.shuffle(combos)
for combo in combos[:num]:
yield combo
else:
# Otherwise yield randomly until we get something we havent seen
items = list(items)
combos = set()
while len(combos) < num_:
# combo = tuple(sorted(rng.choice(items, size, replace=False)))
combo = tuple(sorted(rng.sample(items, size)))
if combo not in combos:
# TODO: store indices instead of combo values
combos.add(combo)
yield combo | python | def random_combinations(items, size, num=None, rng=None):
"""
Yields `num` combinations of length `size` from items in random order
Args:
items (?):
size (?):
num (None): (default = None)
rng (RandomState): random number generator(default = None)
Yields:
tuple: combo
CommandLine:
python -m utool.util_iter random_combinations
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(range(10))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(zip(range(10), range(10)))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result)
"""
import scipy.misc
import numpy as np
import utool as ut
rng = ut.ensure_rng(rng, impl='python')
num_ = np.inf if num is None else num
# Ensure we dont request more than is possible
n_max = int(scipy.misc.comb(len(items), size))
num_ = min(n_max, num_)
if num is not None and num_ > n_max // 2:
# If num is too big just generate all combinations and shuffle them
combos = list(it.combinations(items, size))
rng.shuffle(combos)
for combo in combos[:num]:
yield combo
else:
# Otherwise yield randomly until we get something we havent seen
items = list(items)
combos = set()
while len(combos) < num_:
# combo = tuple(sorted(rng.choice(items, size, replace=False)))
combo = tuple(sorted(rng.sample(items, size)))
if combo not in combos:
# TODO: store indices instead of combo values
combos.add(combo)
yield combo | [
"def",
"random_combinations",
"(",
"items",
",",
"size",
",",
"num",
"=",
"None",
",",
"rng",
"=",
"None",
")",
":",
"import",
"scipy",
".",
"misc",
"import",
"numpy",
"as",
"np",
"import",
"utool",
"as",
"ut",
"rng",
"=",
"ut",
".",
"ensure_rng",
"(",
"rng",
",",
"impl",
"=",
"'python'",
")",
"num_",
"=",
"np",
".",
"inf",
"if",
"num",
"is",
"None",
"else",
"num",
"n_max",
"=",
"int",
"(",
"scipy",
".",
"misc",
".",
"comb",
"(",
"len",
"(",
"items",
")",
",",
"size",
")",
")",
"num_",
"=",
"min",
"(",
"n_max",
",",
"num_",
")",
"if",
"num",
"is",
"not",
"None",
"and",
"num_",
">",
"n_max",
"//",
"2",
":",
"combos",
"=",
"list",
"(",
"it",
".",
"combinations",
"(",
"items",
",",
"size",
")",
")",
"rng",
".",
"shuffle",
"(",
"combos",
")",
"for",
"combo",
"in",
"combos",
"[",
":",
"num",
"]",
":",
"yield",
"combo",
"else",
":",
"items",
"=",
"list",
"(",
"items",
")",
"combos",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"combos",
")",
"<",
"num_",
":",
"combo",
"=",
"tuple",
"(",
"sorted",
"(",
"rng",
".",
"sample",
"(",
"items",
",",
"size",
")",
")",
")",
"if",
"combo",
"not",
"in",
"combos",
":",
"combos",
".",
"add",
"(",
"combo",
")",
"yield",
"combo"
] | Yields `num` combinations of length `size` from items in random order
Args:
items (?):
size (?):
num (None): (default = None)
rng (RandomState): random number generator(default = None)
Yields:
tuple: combo
CommandLine:
python -m utool.util_iter random_combinations
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(range(10))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result)
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> items = list(zip(range(10), range(10)))
>>> size = 3
>>> num = 5
>>> rng = 0
>>> combos = list(random_combinations(items, size, num, rng))
>>> result = ('combos = %s' % (ut.repr2(combos),))
>>> print(result) | [
"Yields",
"num",
"combinations",
"of",
"length",
"size",
"from",
"items",
"in",
"random",
"order"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L552-L616 | train |
chriso/gauged | gauged/drivers/__init__.py | parse_dsn | def parse_dsn(dsn_string):
"""Parse a connection string and return the associated driver"""
dsn = urlparse(dsn_string)
scheme = dsn.scheme.split('+')[0]
username = password = host = port = None
host = dsn.netloc
if '@' in host:
username, host = host.split('@')
if ':' in username:
username, password = username.split(':')
password = unquote(password)
username = unquote(username)
if ':' in host:
host, port = host.split(':')
port = int(port)
database = dsn.path.split('?')[0][1:]
query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query
kwargs = dict(parse_qsl(query, True))
if scheme == 'sqlite':
return SQLiteDriver, [dsn.path], {}
elif scheme == 'mysql':
kwargs['user'] = username or 'root'
kwargs['db'] = database
if port:
kwargs['port'] = port
if host:
kwargs['host'] = host
if password:
kwargs['passwd'] = password
return MySQLDriver, [], kwargs
elif scheme == 'postgresql':
kwargs['user'] = username or 'postgres'
kwargs['database'] = database
if port:
kwargs['port'] = port
if 'unix_socket' in kwargs:
kwargs['host'] = kwargs.pop('unix_socket')
elif host:
kwargs['host'] = host
if password:
kwargs['password'] = password
return PostgreSQLDriver, [], kwargs
else:
raise ValueError('Unknown driver %s' % dsn_string) | python | def parse_dsn(dsn_string):
"""Parse a connection string and return the associated driver"""
dsn = urlparse(dsn_string)
scheme = dsn.scheme.split('+')[0]
username = password = host = port = None
host = dsn.netloc
if '@' in host:
username, host = host.split('@')
if ':' in username:
username, password = username.split(':')
password = unquote(password)
username = unquote(username)
if ':' in host:
host, port = host.split(':')
port = int(port)
database = dsn.path.split('?')[0][1:]
query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query
kwargs = dict(parse_qsl(query, True))
if scheme == 'sqlite':
return SQLiteDriver, [dsn.path], {}
elif scheme == 'mysql':
kwargs['user'] = username or 'root'
kwargs['db'] = database
if port:
kwargs['port'] = port
if host:
kwargs['host'] = host
if password:
kwargs['passwd'] = password
return MySQLDriver, [], kwargs
elif scheme == 'postgresql':
kwargs['user'] = username or 'postgres'
kwargs['database'] = database
if port:
kwargs['port'] = port
if 'unix_socket' in kwargs:
kwargs['host'] = kwargs.pop('unix_socket')
elif host:
kwargs['host'] = host
if password:
kwargs['password'] = password
return PostgreSQLDriver, [], kwargs
else:
raise ValueError('Unknown driver %s' % dsn_string) | [
"def",
"parse_dsn",
"(",
"dsn_string",
")",
":",
"dsn",
"=",
"urlparse",
"(",
"dsn_string",
")",
"scheme",
"=",
"dsn",
".",
"scheme",
".",
"split",
"(",
"'+'",
")",
"[",
"0",
"]",
"username",
"=",
"password",
"=",
"host",
"=",
"port",
"=",
"None",
"host",
"=",
"dsn",
".",
"netloc",
"if",
"'@'",
"in",
"host",
":",
"username",
",",
"host",
"=",
"host",
".",
"split",
"(",
"'@'",
")",
"if",
"':'",
"in",
"username",
":",
"username",
",",
"password",
"=",
"username",
".",
"split",
"(",
"':'",
")",
"password",
"=",
"unquote",
"(",
"password",
")",
"username",
"=",
"unquote",
"(",
"username",
")",
"if",
"':'",
"in",
"host",
":",
"host",
",",
"port",
"=",
"host",
".",
"split",
"(",
"':'",
")",
"port",
"=",
"int",
"(",
"port",
")",
"database",
"=",
"dsn",
".",
"path",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"query",
"=",
"dsn",
".",
"path",
".",
"split",
"(",
"'?'",
")",
"[",
"1",
"]",
"if",
"'?'",
"in",
"dsn",
".",
"path",
"else",
"dsn",
".",
"query",
"kwargs",
"=",
"dict",
"(",
"parse_qsl",
"(",
"query",
",",
"True",
")",
")",
"if",
"scheme",
"==",
"'sqlite'",
":",
"return",
"SQLiteDriver",
",",
"[",
"dsn",
".",
"path",
"]",
",",
"{",
"}",
"elif",
"scheme",
"==",
"'mysql'",
":",
"kwargs",
"[",
"'user'",
"]",
"=",
"username",
"or",
"'root'",
"kwargs",
"[",
"'db'",
"]",
"=",
"database",
"if",
"port",
":",
"kwargs",
"[",
"'port'",
"]",
"=",
"port",
"if",
"host",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"host",
"if",
"password",
":",
"kwargs",
"[",
"'passwd'",
"]",
"=",
"password",
"return",
"MySQLDriver",
",",
"[",
"]",
",",
"kwargs",
"elif",
"scheme",
"==",
"'postgresql'",
":",
"kwargs",
"[",
"'user'",
"]",
"=",
"username",
"or",
"'postgres'",
"kwargs",
"[",
"'database'",
"]",
"=",
"database",
"if",
"port",
":",
"kwargs",
"[",
"'port'",
"]",
"=",
"port",
"if",
"'unix_socket'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'unix_socket'",
")",
"elif",
"host",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"host",
"if",
"password",
":",
"kwargs",
"[",
"'password'",
"]",
"=",
"password",
"return",
"PostgreSQLDriver",
",",
"[",
"]",
",",
"kwargs",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown driver %s'",
"%",
"dsn_string",
")"
] | Parse a connection string and return the associated driver | [
"Parse",
"a",
"connection",
"string",
"and",
"return",
"the",
"associated",
"driver"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/__init__.py#L14-L57 | train |
Thermondo/django-heroku-connect | heroku_connect/db/router.py | HerokuConnectRouter.db_for_write | def db_for_write(self, model, **hints):
"""
Prevent write actions on read-only tables.
Raises:
WriteNotSupportedError: If models.sf_access is ``read_only``.
"""
try:
if model.sf_access == READ_ONLY:
raise WriteNotSupportedError("%r is a read-only model." % model)
except AttributeError:
pass
return None | python | def db_for_write(self, model, **hints):
"""
Prevent write actions on read-only tables.
Raises:
WriteNotSupportedError: If models.sf_access is ``read_only``.
"""
try:
if model.sf_access == READ_ONLY:
raise WriteNotSupportedError("%r is a read-only model." % model)
except AttributeError:
pass
return None | [
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"**",
"hints",
")",
":",
"try",
":",
"if",
"model",
".",
"sf_access",
"==",
"READ_ONLY",
":",
"raise",
"WriteNotSupportedError",
"(",
"\"%r is a read-only model.\"",
"%",
"model",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"None"
] | Prevent write actions on read-only tables.
Raises:
WriteNotSupportedError: If models.sf_access is ``read_only``. | [
"Prevent",
"write",
"actions",
"on",
"read",
"-",
"only",
"tables",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/db/router.py#L26-L39 | train |
product-definition-center/pdc-client | pdc_client/runner.py | Runner.run_hook | def run_hook(self, hook, *args, **kwargs):
"""
Loop over all plugins and invoke function `hook` with `args` and
`kwargs` in each of them. If the plugin does not have the function, it
is skipped.
"""
for plugin in self.raw_plugins:
if hasattr(plugin, hook):
self.logger.debug('Calling hook {0} in plugin {1}'.format(hook, plugin.__name__))
getattr(plugin, hook)(*args, **kwargs) | python | def run_hook(self, hook, *args, **kwargs):
"""
Loop over all plugins and invoke function `hook` with `args` and
`kwargs` in each of them. If the plugin does not have the function, it
is skipped.
"""
for plugin in self.raw_plugins:
if hasattr(plugin, hook):
self.logger.debug('Calling hook {0} in plugin {1}'.format(hook, plugin.__name__))
getattr(plugin, hook)(*args, **kwargs) | [
"def",
"run_hook",
"(",
"self",
",",
"hook",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"plugin",
"in",
"self",
".",
"raw_plugins",
":",
"if",
"hasattr",
"(",
"plugin",
",",
"hook",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Calling hook {0} in plugin {1}'",
".",
"format",
"(",
"hook",
",",
"plugin",
".",
"__name__",
")",
")",
"getattr",
"(",
"plugin",
",",
"hook",
")",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Loop over all plugins and invoke function `hook` with `args` and
`kwargs` in each of them. If the plugin does not have the function, it
is skipped. | [
"Loop",
"over",
"all",
"plugins",
"and",
"invoke",
"function",
"hook",
"with",
"args",
"and",
"kwargs",
"in",
"each",
"of",
"them",
".",
"If",
"the",
"plugin",
"does",
"not",
"have",
"the",
"function",
"it",
"is",
"skipped",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/runner.py#L134-L143 | train |
glormph/msstitch | src/app/writers/tsv.py | write_tsv | def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with open(outfn, 'w') as fp:
write_tsv_line_from_list(headerfields, fp)
for line in features:
write_tsv_line_from_list([str(line[field]) for field
in headerfields], fp) | python | def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with open(outfn, 'w') as fp:
write_tsv_line_from_list(headerfields, fp)
for line in features:
write_tsv_line_from_list([str(line[field]) for field
in headerfields], fp) | [
"def",
"write_tsv",
"(",
"headerfields",
",",
"features",
",",
"outfn",
")",
":",
"with",
"open",
"(",
"outfn",
",",
"'w'",
")",
"as",
"fp",
":",
"write_tsv_line_from_list",
"(",
"headerfields",
",",
"fp",
")",
"for",
"line",
"in",
"features",
":",
"write_tsv_line_from_list",
"(",
"[",
"str",
"(",
"line",
"[",
"field",
"]",
")",
"for",
"field",
"in",
"headerfields",
"]",
",",
"fp",
")"
] | Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists | [
"Writes",
"header",
"and",
"generator",
"of",
"lines",
"to",
"tab",
"separated",
"file",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/writers/tsv.py#L1-L12 | train |
glormph/msstitch | src/app/writers/tsv.py | write_tsv_line_from_list | def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n') | python | def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n') | [
"def",
"write_tsv_line_from_list",
"(",
"linelist",
",",
"outfp",
")",
":",
"line",
"=",
"'\\t'",
".",
"join",
"(",
"linelist",
")",
"outfp",
".",
"write",
"(",
"line",
")",
"outfp",
".",
"write",
"(",
"'\\n'",
")"
] | Utility method to convert list to tsv line with carriage return | [
"Utility",
"method",
"to",
"convert",
"list",
"to",
"tsv",
"line",
"with",
"carriage",
"return"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/writers/tsv.py#L15-L19 | train |
Erotemic/utool | utool/util_str.py | replace_between_tags | def replace_between_tags(text, repl_, start_tag, end_tag=None):
r"""
Replaces text between sentinal lines in a block of text.
Args:
text (str):
repl_ (str):
start_tag (str):
end_tag (str): (default=None)
Returns:
str: new_text
CommandLine:
python -m utool.util_str --exec-replace_between_tags
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> text = ut.codeblock(
'''
class:
# <FOO>
bar
# </FOO>
baz
''')
>>> repl_ = 'spam'
>>> start_tag = '# <FOO>'
>>> end_tag = '# </FOO>'
>>> new_text = replace_between_tags(text, repl_, start_tag, end_tag)
>>> result = ('new_text =\n%s' % (str(new_text),))
>>> print(result)
new_text =
class:
# <FOO>
spam
# </FOO>
baz
"""
new_lines = []
editing = False
lines = text.split('\n')
for line in lines:
if not editing:
new_lines.append(line)
if line.strip().startswith(start_tag):
new_lines.append(repl_)
editing = True
if end_tag is not None and line.strip().startswith(end_tag):
editing = False
new_lines.append(line)
new_text = '\n'.join(new_lines)
return new_text | python | def replace_between_tags(text, repl_, start_tag, end_tag=None):
r"""
Replaces text between sentinal lines in a block of text.
Args:
text (str):
repl_ (str):
start_tag (str):
end_tag (str): (default=None)
Returns:
str: new_text
CommandLine:
python -m utool.util_str --exec-replace_between_tags
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> text = ut.codeblock(
'''
class:
# <FOO>
bar
# </FOO>
baz
''')
>>> repl_ = 'spam'
>>> start_tag = '# <FOO>'
>>> end_tag = '# </FOO>'
>>> new_text = replace_between_tags(text, repl_, start_tag, end_tag)
>>> result = ('new_text =\n%s' % (str(new_text),))
>>> print(result)
new_text =
class:
# <FOO>
spam
# </FOO>
baz
"""
new_lines = []
editing = False
lines = text.split('\n')
for line in lines:
if not editing:
new_lines.append(line)
if line.strip().startswith(start_tag):
new_lines.append(repl_)
editing = True
if end_tag is not None and line.strip().startswith(end_tag):
editing = False
new_lines.append(line)
new_text = '\n'.join(new_lines)
return new_text | [
"def",
"replace_between_tags",
"(",
"text",
",",
"repl_",
",",
"start_tag",
",",
"end_tag",
"=",
"None",
")",
":",
"r",
"new_lines",
"=",
"[",
"]",
"editing",
"=",
"False",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"editing",
":",
"new_lines",
".",
"append",
"(",
"line",
")",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"start_tag",
")",
":",
"new_lines",
".",
"append",
"(",
"repl_",
")",
"editing",
"=",
"True",
"if",
"end_tag",
"is",
"not",
"None",
"and",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"end_tag",
")",
":",
"editing",
"=",
"False",
"new_lines",
".",
"append",
"(",
"line",
")",
"new_text",
"=",
"'\\n'",
".",
"join",
"(",
"new_lines",
")",
"return",
"new_text"
] | r"""
Replaces text between sentinal lines in a block of text.
Args:
text (str):
repl_ (str):
start_tag (str):
end_tag (str): (default=None)
Returns:
str: new_text
CommandLine:
python -m utool.util_str --exec-replace_between_tags
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> text = ut.codeblock(
'''
class:
# <FOO>
bar
# </FOO>
baz
''')
>>> repl_ = 'spam'
>>> start_tag = '# <FOO>'
>>> end_tag = '# </FOO>'
>>> new_text = replace_between_tags(text, repl_, start_tag, end_tag)
>>> result = ('new_text =\n%s' % (str(new_text),))
>>> print(result)
new_text =
class:
# <FOO>
spam
# </FOO>
baz | [
"r",
"Replaces",
"text",
"between",
"sentinal",
"lines",
"in",
"a",
"block",
"of",
"text",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L75-L128 | train |
Erotemic/utool | utool/util_str.py | theta_str | def theta_str(theta, taustr=TAUSTR, fmtstr='{coeff:,.1f}{taustr}'):
r"""
Format theta so it is interpretable in base 10
Args:
theta (float) angle in radians
taustr (str): default 2pi
Returns:
str : theta_str - the angle in tau units
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 3.1415
>>> result = theta_str(theta)
>>> print(result)
0.5*2pi
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 6.9932
>>> taustr = 'tau'
>>> result = theta_str(theta, taustr)
>>> print(result)
1.1tau
"""
coeff = theta / TAU
theta_str = fmtstr.format(coeff=coeff, taustr=taustr)
return theta_str | python | def theta_str(theta, taustr=TAUSTR, fmtstr='{coeff:,.1f}{taustr}'):
r"""
Format theta so it is interpretable in base 10
Args:
theta (float) angle in radians
taustr (str): default 2pi
Returns:
str : theta_str - the angle in tau units
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 3.1415
>>> result = theta_str(theta)
>>> print(result)
0.5*2pi
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 6.9932
>>> taustr = 'tau'
>>> result = theta_str(theta, taustr)
>>> print(result)
1.1tau
"""
coeff = theta / TAU
theta_str = fmtstr.format(coeff=coeff, taustr=taustr)
return theta_str | [
"def",
"theta_str",
"(",
"theta",
",",
"taustr",
"=",
"TAUSTR",
",",
"fmtstr",
"=",
"'{coeff:,.1f}{taustr}'",
")",
":",
"r",
"coeff",
"=",
"theta",
"/",
"TAU",
"theta_str",
"=",
"fmtstr",
".",
"format",
"(",
"coeff",
"=",
"coeff",
",",
"taustr",
"=",
"taustr",
")",
"return",
"theta_str"
] | r"""
Format theta so it is interpretable in base 10
Args:
theta (float) angle in radians
taustr (str): default 2pi
Returns:
str : theta_str - the angle in tau units
Example1:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 3.1415
>>> result = theta_str(theta)
>>> print(result)
0.5*2pi
Example2:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> theta = 6.9932
>>> taustr = 'tau'
>>> result = theta_str(theta, taustr)
>>> print(result)
1.1tau | [
"r",
"Format",
"theta",
"so",
"it",
"is",
"interpretable",
"in",
"base",
"10"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L131-L161 | train |
Erotemic/utool | utool/util_str.py | bbox_str | def bbox_str(bbox, pad=4, sep=', '):
r""" makes a string from an integer bounding box """
if bbox is None:
return 'None'
fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4)
return '(' + fmtstr % tuple(bbox) + ')' | python | def bbox_str(bbox, pad=4, sep=', '):
r""" makes a string from an integer bounding box """
if bbox is None:
return 'None'
fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4)
return '(' + fmtstr % tuple(bbox) + ')' | [
"def",
"bbox_str",
"(",
"bbox",
",",
"pad",
"=",
"4",
",",
"sep",
"=",
"', '",
")",
":",
"r",
"if",
"bbox",
"is",
"None",
":",
"return",
"'None'",
"fmtstr",
"=",
"sep",
".",
"join",
"(",
"[",
"'%'",
"+",
"six",
".",
"text_type",
"(",
"pad",
")",
"+",
"'d'",
"]",
"*",
"4",
")",
"return",
"'('",
"+",
"fmtstr",
"%",
"tuple",
"(",
"bbox",
")",
"+",
"')'"
] | r""" makes a string from an integer bounding box | [
"r",
"makes",
"a",
"string",
"from",
"an",
"integer",
"bounding",
"box"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L164-L169 | train |
Erotemic/utool | utool/util_str.py | verts_str | def verts_str(verts, pad=1):
r""" makes a string from a list of integer verticies """
if verts is None:
return 'None'
fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' +
', %' + six.text_type(pad) + 'd'] * 1)
return ', '.join(['(' + fmtstr % vert + ')' for vert in verts]) | python | def verts_str(verts, pad=1):
r""" makes a string from a list of integer verticies """
if verts is None:
return 'None'
fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' +
', %' + six.text_type(pad) + 'd'] * 1)
return ', '.join(['(' + fmtstr % vert + ')' for vert in verts]) | [
"def",
"verts_str",
"(",
"verts",
",",
"pad",
"=",
"1",
")",
":",
"r",
"if",
"verts",
"is",
"None",
":",
"return",
"'None'",
"fmtstr",
"=",
"', '",
".",
"join",
"(",
"[",
"'%'",
"+",
"six",
".",
"text_type",
"(",
"pad",
")",
"+",
"'d'",
"+",
"', %'",
"+",
"six",
".",
"text_type",
"(",
"pad",
")",
"+",
"'d'",
"]",
"*",
"1",
")",
"return",
"', '",
".",
"join",
"(",
"[",
"'('",
"+",
"fmtstr",
"%",
"vert",
"+",
"')'",
"for",
"vert",
"in",
"verts",
"]",
")"
] | r""" makes a string from a list of integer verticies | [
"r",
"makes",
"a",
"string",
"from",
"a",
"list",
"of",
"integer",
"verticies"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L172-L178 | train |
Erotemic/utool | utool/util_str.py | remove_chars | def remove_chars(str_, char_list):
"""
removes all chars in char_list from str_
Args:
str_ (str):
char_list (list):
Returns:
str: outstr
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = '1, 2, 3, 4'
>>> char_list = [',']
>>> result = remove_chars(str_, char_list)
>>> print(result)
1 2 3 4
"""
outstr = str_[:]
for char in char_list:
outstr = outstr.replace(char, '')
return outstr | python | def remove_chars(str_, char_list):
"""
removes all chars in char_list from str_
Args:
str_ (str):
char_list (list):
Returns:
str: outstr
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = '1, 2, 3, 4'
>>> char_list = [',']
>>> result = remove_chars(str_, char_list)
>>> print(result)
1 2 3 4
"""
outstr = str_[:]
for char in char_list:
outstr = outstr.replace(char, '')
return outstr | [
"def",
"remove_chars",
"(",
"str_",
",",
"char_list",
")",
":",
"outstr",
"=",
"str_",
"[",
":",
"]",
"for",
"char",
"in",
"char_list",
":",
"outstr",
"=",
"outstr",
".",
"replace",
"(",
"char",
",",
"''",
")",
"return",
"outstr"
] | removes all chars in char_list from str_
Args:
str_ (str):
char_list (list):
Returns:
str: outstr
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = '1, 2, 3, 4'
>>> char_list = [',']
>>> result = remove_chars(str_, char_list)
>>> print(result)
1 2 3 4 | [
"removes",
"all",
"chars",
"in",
"char_list",
"from",
"str_"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L195-L218 | train |
Erotemic/utool | utool/util_str.py | get_minimum_indentation | def get_minimum_indentation(text):
r"""
returns the number of preceding spaces
Args:
text (str): unicode text
Returns:
int: indentation
CommandLine:
python -m utool.util_str --exec-get_minimum_indentation --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> text = ' foo\n bar'
>>> result = get_minimum_indentation(text)
>>> print(result)
3
"""
lines = text.split('\n')
indentations = [get_indentation(line_)
for line_ in lines if len(line_.strip()) > 0]
if len(indentations) == 0:
return 0
return min(indentations) | python | def get_minimum_indentation(text):
r"""
returns the number of preceding spaces
Args:
text (str): unicode text
Returns:
int: indentation
CommandLine:
python -m utool.util_str --exec-get_minimum_indentation --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> text = ' foo\n bar'
>>> result = get_minimum_indentation(text)
>>> print(result)
3
"""
lines = text.split('\n')
indentations = [get_indentation(line_)
for line_ in lines if len(line_.strip()) > 0]
if len(indentations) == 0:
return 0
return min(indentations) | [
"def",
"get_minimum_indentation",
"(",
"text",
")",
":",
"r",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"indentations",
"=",
"[",
"get_indentation",
"(",
"line_",
")",
"for",
"line_",
"in",
"lines",
"if",
"len",
"(",
"line_",
".",
"strip",
"(",
")",
")",
">",
"0",
"]",
"if",
"len",
"(",
"indentations",
")",
"==",
"0",
":",
"return",
"0",
"return",
"min",
"(",
"indentations",
")"
] | r"""
returns the number of preceding spaces
Args:
text (str): unicode text
Returns:
int: indentation
CommandLine:
python -m utool.util_str --exec-get_minimum_indentation --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> text = ' foo\n bar'
>>> result = get_minimum_indentation(text)
>>> print(result)
3 | [
"r",
"returns",
"the",
"number",
"of",
"preceding",
"spaces"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L228-L255 | train |
Erotemic/utool | utool/util_str.py | indentjoin | def indentjoin(strlist, indent='\n ', suffix=''):
r"""
Convineince indentjoin
similar to '\n '.join(strlist) but indent is also prefixed
Args:
strlist (?):
indent (str):
suffix (str):
Returns:
str: joined list
"""
indent_ = indent
strlist = list(strlist)
if len(strlist) == 0:
return ''
return indent_ + indent_.join([six.text_type(str_) + suffix
for str_ in strlist]) | python | def indentjoin(strlist, indent='\n ', suffix=''):
r"""
Convineince indentjoin
similar to '\n '.join(strlist) but indent is also prefixed
Args:
strlist (?):
indent (str):
suffix (str):
Returns:
str: joined list
"""
indent_ = indent
strlist = list(strlist)
if len(strlist) == 0:
return ''
return indent_ + indent_.join([six.text_type(str_) + suffix
for str_ in strlist]) | [
"def",
"indentjoin",
"(",
"strlist",
",",
"indent",
"=",
"'\\n '",
",",
"suffix",
"=",
"''",
")",
":",
"r",
"indent_",
"=",
"indent",
"strlist",
"=",
"list",
"(",
"strlist",
")",
"if",
"len",
"(",
"strlist",
")",
"==",
"0",
":",
"return",
"''",
"return",
"indent_",
"+",
"indent_",
".",
"join",
"(",
"[",
"six",
".",
"text_type",
"(",
"str_",
")",
"+",
"suffix",
"for",
"str_",
"in",
"strlist",
"]",
")"
] | r"""
Convineince indentjoin
similar to '\n '.join(strlist) but indent is also prefixed
Args:
strlist (?):
indent (str):
suffix (str):
Returns:
str: joined list | [
"r",
"Convineince",
"indentjoin"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L357-L376 | train |
Erotemic/utool | utool/util_str.py | truncate_str | def truncate_str(str_, maxlen=110, truncmsg=' ~~~TRUNCATED~~~ '):
"""
Removes the middle part of any string over maxlen characters.
"""
if NO_TRUNCATE:
return str_
if maxlen is None or maxlen == -1 or len(str_) < maxlen:
return str_
else:
maxlen_ = maxlen - len(truncmsg)
lowerb = int(maxlen_ * .8)
upperb = maxlen_ - lowerb
tup = (str_[:lowerb], truncmsg, str_[-upperb:])
return ''.join(tup) | python | def truncate_str(str_, maxlen=110, truncmsg=' ~~~TRUNCATED~~~ '):
"""
Removes the middle part of any string over maxlen characters.
"""
if NO_TRUNCATE:
return str_
if maxlen is None or maxlen == -1 or len(str_) < maxlen:
return str_
else:
maxlen_ = maxlen - len(truncmsg)
lowerb = int(maxlen_ * .8)
upperb = maxlen_ - lowerb
tup = (str_[:lowerb], truncmsg, str_[-upperb:])
return ''.join(tup) | [
"def",
"truncate_str",
"(",
"str_",
",",
"maxlen",
"=",
"110",
",",
"truncmsg",
"=",
"' ~~~TRUNCATED~~~ '",
")",
":",
"if",
"NO_TRUNCATE",
":",
"return",
"str_",
"if",
"maxlen",
"is",
"None",
"or",
"maxlen",
"==",
"-",
"1",
"or",
"len",
"(",
"str_",
")",
"<",
"maxlen",
":",
"return",
"str_",
"else",
":",
"maxlen_",
"=",
"maxlen",
"-",
"len",
"(",
"truncmsg",
")",
"lowerb",
"=",
"int",
"(",
"maxlen_",
"*",
".8",
")",
"upperb",
"=",
"maxlen_",
"-",
"lowerb",
"tup",
"=",
"(",
"str_",
"[",
":",
"lowerb",
"]",
",",
"truncmsg",
",",
"str_",
"[",
"-",
"upperb",
":",
"]",
")",
"return",
"''",
".",
"join",
"(",
"tup",
")"
] | Removes the middle part of any string over maxlen characters. | [
"Removes",
"the",
"middle",
"part",
"of",
"any",
"string",
"over",
"maxlen",
"characters",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L379-L392 | train |
Erotemic/utool | utool/util_str.py | packstr | def packstr(instr, textwidth=160, breakchars=' ', break_words=True,
newline_prefix='', indentation='', nlprefix=None, wordsep=' ',
remove_newlines=True):
""" alias for pack_into. has more up to date kwargs """
if not isinstance(instr, six.string_types):
instr = repr(instr)
if nlprefix is not None:
newline_prefix = nlprefix
str_ = pack_into(instr, textwidth, breakchars, break_words, newline_prefix,
wordsep, remove_newlines)
if indentation != '':
str_ = indent(str_, indentation)
return str_ | python | def packstr(instr, textwidth=160, breakchars=' ', break_words=True,
newline_prefix='', indentation='', nlprefix=None, wordsep=' ',
remove_newlines=True):
""" alias for pack_into. has more up to date kwargs """
if not isinstance(instr, six.string_types):
instr = repr(instr)
if nlprefix is not None:
newline_prefix = nlprefix
str_ = pack_into(instr, textwidth, breakchars, break_words, newline_prefix,
wordsep, remove_newlines)
if indentation != '':
str_ = indent(str_, indentation)
return str_ | [
"def",
"packstr",
"(",
"instr",
",",
"textwidth",
"=",
"160",
",",
"breakchars",
"=",
"' '",
",",
"break_words",
"=",
"True",
",",
"newline_prefix",
"=",
"''",
",",
"indentation",
"=",
"''",
",",
"nlprefix",
"=",
"None",
",",
"wordsep",
"=",
"' '",
",",
"remove_newlines",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"instr",
",",
"six",
".",
"string_types",
")",
":",
"instr",
"=",
"repr",
"(",
"instr",
")",
"if",
"nlprefix",
"is",
"not",
"None",
":",
"newline_prefix",
"=",
"nlprefix",
"str_",
"=",
"pack_into",
"(",
"instr",
",",
"textwidth",
",",
"breakchars",
",",
"break_words",
",",
"newline_prefix",
",",
"wordsep",
",",
"remove_newlines",
")",
"if",
"indentation",
"!=",
"''",
":",
"str_",
"=",
"indent",
"(",
"str_",
",",
"indentation",
")",
"return",
"str_"
] | alias for pack_into. has more up to date kwargs | [
"alias",
"for",
"pack_into",
".",
"has",
"more",
"up",
"to",
"date",
"kwargs"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L468-L480 | train |
Erotemic/utool | utool/util_str.py | byte_str | def byte_str(nBytes, unit='bytes', precision=2):
"""
representing the number of bytes with the chosen unit
Returns:
str
"""
#return (nBytes * ureg.byte).to(unit.upper())
if unit.lower().startswith('b'):
nUnit = nBytes
elif unit.lower().startswith('k'):
nUnit = nBytes / (2.0 ** 10)
elif unit.lower().startswith('m'):
nUnit = nBytes / (2.0 ** 20)
elif unit.lower().startswith('g'):
nUnit = nBytes / (2.0 ** 30)
elif unit.lower().startswith('t'):
nUnit = nBytes / (2.0 ** 40)
else:
raise NotImplementedError('unknown nBytes=%r unit=%r' % (nBytes, unit))
return repr2(nUnit, precision=precision) + ' ' + unit | python | def byte_str(nBytes, unit='bytes', precision=2):
"""
representing the number of bytes with the chosen unit
Returns:
str
"""
#return (nBytes * ureg.byte).to(unit.upper())
if unit.lower().startswith('b'):
nUnit = nBytes
elif unit.lower().startswith('k'):
nUnit = nBytes / (2.0 ** 10)
elif unit.lower().startswith('m'):
nUnit = nBytes / (2.0 ** 20)
elif unit.lower().startswith('g'):
nUnit = nBytes / (2.0 ** 30)
elif unit.lower().startswith('t'):
nUnit = nBytes / (2.0 ** 40)
else:
raise NotImplementedError('unknown nBytes=%r unit=%r' % (nBytes, unit))
return repr2(nUnit, precision=precision) + ' ' + unit | [
"def",
"byte_str",
"(",
"nBytes",
",",
"unit",
"=",
"'bytes'",
",",
"precision",
"=",
"2",
")",
":",
"if",
"unit",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'b'",
")",
":",
"nUnit",
"=",
"nBytes",
"elif",
"unit",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'k'",
")",
":",
"nUnit",
"=",
"nBytes",
"/",
"(",
"2.0",
"**",
"10",
")",
"elif",
"unit",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'m'",
")",
":",
"nUnit",
"=",
"nBytes",
"/",
"(",
"2.0",
"**",
"20",
")",
"elif",
"unit",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'g'",
")",
":",
"nUnit",
"=",
"nBytes",
"/",
"(",
"2.0",
"**",
"30",
")",
"elif",
"unit",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'t'",
")",
":",
"nUnit",
"=",
"nBytes",
"/",
"(",
"2.0",
"**",
"40",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'unknown nBytes=%r unit=%r'",
"%",
"(",
"nBytes",
",",
"unit",
")",
")",
"return",
"repr2",
"(",
"nUnit",
",",
"precision",
"=",
"precision",
")",
"+",
"' '",
"+",
"unit"
] | representing the number of bytes with the chosen unit
Returns:
str | [
"representing",
"the",
"number",
"of",
"bytes",
"with",
"the",
"chosen",
"unit"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L671-L691 | train |
Erotemic/utool | utool/util_str.py | func_str | def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False,
packkw=None, truncate=False):
"""
string representation of function definition
Returns:
str: a representation of func with args, kwargs, and type_aliases
Args:
func (function):
args (list): argument values (default = [])
kwargs (dict): kwargs values (default = {})
type_aliases (list): (default = [])
packed (bool): (default = False)
packkw (None): (default = None)
Returns:
str: func_str
CommandLine:
python -m utool.util_str --exec-func_str
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = byte_str
>>> args = [1024, 'MB']
>>> kwargs = dict(precision=2)
>>> type_aliases = []
>>> packed = False
>>> packkw = None
>>> _str = func_str(func, args, kwargs, type_aliases, packed, packkw)
>>> result = _str
>>> print(result)
byte_str(1024, 'MB', precision=2)
"""
import utool as ut
# if truncate:
# truncatekw = {'maxlen': 20}
# else:
truncatekw = {}
argrepr_list = ([] if args is None else
ut.get_itemstr_list(args, nl=False, truncate=truncate,
truncatekw=truncatekw))
kwrepr_list = ([] if kwargs is None else
ut.dict_itemstr_list(kwargs, explicit=True, nl=False,
truncate=truncate,
truncatekw=truncatekw))
repr_list = argrepr_list + kwrepr_list
argskwargs_str = ', '.join(repr_list)
_str = '%s(%s)' % (meta_util_six.get_funcname(func), argskwargs_str)
if packed:
packkw_ = dict(textwidth=80, nlprefix=' ', break_words=False)
if packkw is not None:
packkw_.update(packkw_)
_str = packstr(_str, **packkw_)
return _str | python | def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False,
packkw=None, truncate=False):
"""
string representation of function definition
Returns:
str: a representation of func with args, kwargs, and type_aliases
Args:
func (function):
args (list): argument values (default = [])
kwargs (dict): kwargs values (default = {})
type_aliases (list): (default = [])
packed (bool): (default = False)
packkw (None): (default = None)
Returns:
str: func_str
CommandLine:
python -m utool.util_str --exec-func_str
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = byte_str
>>> args = [1024, 'MB']
>>> kwargs = dict(precision=2)
>>> type_aliases = []
>>> packed = False
>>> packkw = None
>>> _str = func_str(func, args, kwargs, type_aliases, packed, packkw)
>>> result = _str
>>> print(result)
byte_str(1024, 'MB', precision=2)
"""
import utool as ut
# if truncate:
# truncatekw = {'maxlen': 20}
# else:
truncatekw = {}
argrepr_list = ([] if args is None else
ut.get_itemstr_list(args, nl=False, truncate=truncate,
truncatekw=truncatekw))
kwrepr_list = ([] if kwargs is None else
ut.dict_itemstr_list(kwargs, explicit=True, nl=False,
truncate=truncate,
truncatekw=truncatekw))
repr_list = argrepr_list + kwrepr_list
argskwargs_str = ', '.join(repr_list)
_str = '%s(%s)' % (meta_util_six.get_funcname(func), argskwargs_str)
if packed:
packkw_ = dict(textwidth=80, nlprefix=' ', break_words=False)
if packkw is not None:
packkw_.update(packkw_)
_str = packstr(_str, **packkw_)
return _str | [
"def",
"func_str",
"(",
"func",
",",
"args",
"=",
"[",
"]",
",",
"kwargs",
"=",
"{",
"}",
",",
"type_aliases",
"=",
"[",
"]",
",",
"packed",
"=",
"False",
",",
"packkw",
"=",
"None",
",",
"truncate",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"truncatekw",
"=",
"{",
"}",
"argrepr_list",
"=",
"(",
"[",
"]",
"if",
"args",
"is",
"None",
"else",
"ut",
".",
"get_itemstr_list",
"(",
"args",
",",
"nl",
"=",
"False",
",",
"truncate",
"=",
"truncate",
",",
"truncatekw",
"=",
"truncatekw",
")",
")",
"kwrepr_list",
"=",
"(",
"[",
"]",
"if",
"kwargs",
"is",
"None",
"else",
"ut",
".",
"dict_itemstr_list",
"(",
"kwargs",
",",
"explicit",
"=",
"True",
",",
"nl",
"=",
"False",
",",
"truncate",
"=",
"truncate",
",",
"truncatekw",
"=",
"truncatekw",
")",
")",
"repr_list",
"=",
"argrepr_list",
"+",
"kwrepr_list",
"argskwargs_str",
"=",
"', '",
".",
"join",
"(",
"repr_list",
")",
"_str",
"=",
"'%s(%s)'",
"%",
"(",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
",",
"argskwargs_str",
")",
"if",
"packed",
":",
"packkw_",
"=",
"dict",
"(",
"textwidth",
"=",
"80",
",",
"nlprefix",
"=",
"' '",
",",
"break_words",
"=",
"False",
")",
"if",
"packkw",
"is",
"not",
"None",
":",
"packkw_",
".",
"update",
"(",
"packkw_",
")",
"_str",
"=",
"packstr",
"(",
"_str",
",",
"**",
"packkw_",
")",
"return",
"_str"
] | string representation of function definition
Returns:
str: a representation of func with args, kwargs, and type_aliases
Args:
func (function):
args (list): argument values (default = [])
kwargs (dict): kwargs values (default = {})
type_aliases (list): (default = [])
packed (bool): (default = False)
packkw (None): (default = None)
Returns:
str: func_str
CommandLine:
python -m utool.util_str --exec-func_str
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = byte_str
>>> args = [1024, 'MB']
>>> kwargs = dict(precision=2)
>>> type_aliases = []
>>> packed = False
>>> packkw = None
>>> _str = func_str(func, args, kwargs, type_aliases, packed, packkw)
>>> result = _str
>>> print(result)
byte_str(1024, 'MB', precision=2) | [
"string",
"representation",
"of",
"function",
"definition"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L720-L778 | train |
Erotemic/utool | utool/util_str.py | func_defsig | def func_defsig(func, with_name=True):
"""
String of function definition signature
Args:
func (function): live python function
Returns:
str: defsig
CommandLine:
python -m utool.util_str --exec-func_defsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> defsig = func_defsig(func)
>>> result = str(defsig)
>>> print(result)
func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False)
"""
import inspect
argspec = inspect.getargspec(func)
(args, varargs, varkw, defaults) = argspec
defsig = inspect.formatargspec(*argspec)
if with_name:
defsig = get_callable_name(func) + defsig
return defsig | python | def func_defsig(func, with_name=True):
"""
String of function definition signature
Args:
func (function): live python function
Returns:
str: defsig
CommandLine:
python -m utool.util_str --exec-func_defsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> defsig = func_defsig(func)
>>> result = str(defsig)
>>> print(result)
func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False)
"""
import inspect
argspec = inspect.getargspec(func)
(args, varargs, varkw, defaults) = argspec
defsig = inspect.formatargspec(*argspec)
if with_name:
defsig = get_callable_name(func) + defsig
return defsig | [
"def",
"func_defsig",
"(",
"func",
",",
"with_name",
"=",
"True",
")",
":",
"import",
"inspect",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
")",
"=",
"argspec",
"defsig",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"argspec",
")",
"if",
"with_name",
":",
"defsig",
"=",
"get_callable_name",
"(",
"func",
")",
"+",
"defsig",
"return",
"defsig"
] | String of function definition signature
Args:
func (function): live python function
Returns:
str: defsig
CommandLine:
python -m utool.util_str --exec-func_defsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> defsig = func_defsig(func)
>>> result = str(defsig)
>>> print(result)
func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False) | [
"String",
"of",
"function",
"definition",
"signature"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L781-L809 | train |
Erotemic/utool | utool/util_str.py | func_callsig | def func_callsig(func, with_name=True):
"""
String of function call signature
Args:
func (function): live python function
Returns:
str: callsig
CommandLine:
python -m utool.util_str --exec-func_callsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> callsig = func_callsig(func)
>>> result = str(callsig)
>>> print(result)
func_str(func, args, kwargs, type_aliases, packed, packkw, truncate)
"""
import inspect
argspec = inspect.getargspec(func)
(args, varargs, varkw, defaults) = argspec
callsig = inspect.formatargspec(*argspec[0:3])
if with_name:
callsig = get_callable_name(func) + callsig
return callsig | python | def func_callsig(func, with_name=True):
"""
String of function call signature
Args:
func (function): live python function
Returns:
str: callsig
CommandLine:
python -m utool.util_str --exec-func_callsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> callsig = func_callsig(func)
>>> result = str(callsig)
>>> print(result)
func_str(func, args, kwargs, type_aliases, packed, packkw, truncate)
"""
import inspect
argspec = inspect.getargspec(func)
(args, varargs, varkw, defaults) = argspec
callsig = inspect.formatargspec(*argspec[0:3])
if with_name:
callsig = get_callable_name(func) + callsig
return callsig | [
"def",
"func_callsig",
"(",
"func",
",",
"with_name",
"=",
"True",
")",
":",
"import",
"inspect",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
")",
"=",
"argspec",
"callsig",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"argspec",
"[",
"0",
":",
"3",
"]",
")",
"if",
"with_name",
":",
"callsig",
"=",
"get_callable_name",
"(",
"func",
")",
"+",
"callsig",
"return",
"callsig"
] | String of function call signature
Args:
func (function): live python function
Returns:
str: callsig
CommandLine:
python -m utool.util_str --exec-func_callsig
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = func_str
>>> callsig = func_callsig(func)
>>> result = str(callsig)
>>> print(result)
func_str(func, args, kwargs, type_aliases, packed, packkw, truncate) | [
"String",
"of",
"function",
"call",
"signature"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L812-L840 | train |
Erotemic/utool | utool/util_str.py | numpy_str | def numpy_str(arr, strvals=False, precision=None, pr=None,
force_dtype=False,
with_dtype=None, suppress_small=None, max_line_width=None,
threshold=None, **kwargs):
"""
suppress_small = False turns off scientific representation
"""
# strvals = kwargs.get('strvals', False)
itemsep = kwargs.get('itemsep', ' ')
# precision = kwargs.get('precision', None)
# suppress_small = kwargs.get('supress_small', None)
# max_line_width = kwargs.get('max_line_width', None)
# with_dtype = kwargs.get('with_dtype', False)
newlines = kwargs.pop('nl', kwargs.pop('newlines', 1))
data = arr
# if with_dtype and strvals:
# raise ValueError('cannot format with strvals and dtype')
separator = ',' + itemsep
if strvals:
prefix = ''
suffix = ''
else:
modname = type(data).__module__
# substitute shorthand for numpy module names
np_nice = 'np'
modname = re.sub('\\bnumpy\\b', np_nice, modname)
modname = re.sub('\\bma.core\\b', 'ma', modname)
class_name = type(data).__name__
if class_name == 'ndarray':
class_name = 'array'
prefix = modname + '.' + class_name + '('
if with_dtype:
dtype_repr = data.dtype.name
# dtype_repr = np.core.arrayprint.dtype_short_repr(data.dtype)
suffix = ',{}dtype={}.{})'.format(itemsep, np_nice, dtype_repr)
else:
suffix = ')'
if not strvals and data.size == 0 and data.shape != (0,):
# Special case for displaying empty data
prefix = modname + '.empty('
body = repr(tuple(map(int, data.shape)))
else:
body = np.array2string(data, precision=precision,
separator=separator,
suppress_small=suppress_small,
prefix=prefix,
max_line_width=max_line_width)
if not newlines:
# remove newlines if we need to
body = re.sub('\n *', '', body)
formatted = prefix + body + suffix
return formatted | python | def numpy_str(arr, strvals=False, precision=None, pr=None,
force_dtype=False,
with_dtype=None, suppress_small=None, max_line_width=None,
threshold=None, **kwargs):
"""
suppress_small = False turns off scientific representation
"""
# strvals = kwargs.get('strvals', False)
itemsep = kwargs.get('itemsep', ' ')
# precision = kwargs.get('precision', None)
# suppress_small = kwargs.get('supress_small', None)
# max_line_width = kwargs.get('max_line_width', None)
# with_dtype = kwargs.get('with_dtype', False)
newlines = kwargs.pop('nl', kwargs.pop('newlines', 1))
data = arr
# if with_dtype and strvals:
# raise ValueError('cannot format with strvals and dtype')
separator = ',' + itemsep
if strvals:
prefix = ''
suffix = ''
else:
modname = type(data).__module__
# substitute shorthand for numpy module names
np_nice = 'np'
modname = re.sub('\\bnumpy\\b', np_nice, modname)
modname = re.sub('\\bma.core\\b', 'ma', modname)
class_name = type(data).__name__
if class_name == 'ndarray':
class_name = 'array'
prefix = modname + '.' + class_name + '('
if with_dtype:
dtype_repr = data.dtype.name
# dtype_repr = np.core.arrayprint.dtype_short_repr(data.dtype)
suffix = ',{}dtype={}.{})'.format(itemsep, np_nice, dtype_repr)
else:
suffix = ')'
if not strvals and data.size == 0 and data.shape != (0,):
# Special case for displaying empty data
prefix = modname + '.empty('
body = repr(tuple(map(int, data.shape)))
else:
body = np.array2string(data, precision=precision,
separator=separator,
suppress_small=suppress_small,
prefix=prefix,
max_line_width=max_line_width)
if not newlines:
# remove newlines if we need to
body = re.sub('\n *', '', body)
formatted = prefix + body + suffix
return formatted | [
"def",
"numpy_str",
"(",
"arr",
",",
"strvals",
"=",
"False",
",",
"precision",
"=",
"None",
",",
"pr",
"=",
"None",
",",
"force_dtype",
"=",
"False",
",",
"with_dtype",
"=",
"None",
",",
"suppress_small",
"=",
"None",
",",
"max_line_width",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"itemsep",
"=",
"kwargs",
".",
"get",
"(",
"'itemsep'",
",",
"' '",
")",
"newlines",
"=",
"kwargs",
".",
"pop",
"(",
"'nl'",
",",
"kwargs",
".",
"pop",
"(",
"'newlines'",
",",
"1",
")",
")",
"data",
"=",
"arr",
"separator",
"=",
"','",
"+",
"itemsep",
"if",
"strvals",
":",
"prefix",
"=",
"''",
"suffix",
"=",
"''",
"else",
":",
"modname",
"=",
"type",
"(",
"data",
")",
".",
"__module__",
"np_nice",
"=",
"'np'",
"modname",
"=",
"re",
".",
"sub",
"(",
"'\\\\bnumpy\\\\b'",
",",
"np_nice",
",",
"modname",
")",
"modname",
"=",
"re",
".",
"sub",
"(",
"'\\\\bma.core\\\\b'",
",",
"'ma'",
",",
"modname",
")",
"class_name",
"=",
"type",
"(",
"data",
")",
".",
"__name__",
"if",
"class_name",
"==",
"'ndarray'",
":",
"class_name",
"=",
"'array'",
"prefix",
"=",
"modname",
"+",
"'.'",
"+",
"class_name",
"+",
"'('",
"if",
"with_dtype",
":",
"dtype_repr",
"=",
"data",
".",
"dtype",
".",
"name",
"suffix",
"=",
"',{}dtype={}.{})'",
".",
"format",
"(",
"itemsep",
",",
"np_nice",
",",
"dtype_repr",
")",
"else",
":",
"suffix",
"=",
"')'",
"if",
"not",
"strvals",
"and",
"data",
".",
"size",
"==",
"0",
"and",
"data",
".",
"shape",
"!=",
"(",
"0",
",",
")",
":",
"prefix",
"=",
"modname",
"+",
"'.empty('",
"body",
"=",
"repr",
"(",
"tuple",
"(",
"map",
"(",
"int",
",",
"data",
".",
"shape",
")",
")",
")",
"else",
":",
"body",
"=",
"np",
".",
"array2string",
"(",
"data",
",",
"precision",
"=",
"precision",
",",
"separator",
"=",
"separator",
",",
"suppress_small",
"=",
"suppress_small",
",",
"prefix",
"=",
"prefix",
",",
"max_line_width",
"=",
"max_line_width",
")",
"if",
"not",
"newlines",
":",
"body",
"=",
"re",
".",
"sub",
"(",
"'\\n *'",
",",
"''",
",",
"body",
")",
"formatted",
"=",
"prefix",
"+",
"body",
"+",
"suffix",
"return",
"formatted"
] | suppress_small = False turns off scientific representation | [
"suppress_small",
"=",
"False",
"turns",
"off",
"scientific",
"representation"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1112-L1170 | train |
Erotemic/utool | utool/util_str.py | list_str_summarized | def list_str_summarized(list_, list_name, maxlen=5):
"""
prints the list members when the list is small and the length when it is
large
"""
if len(list_) > maxlen:
return 'len(%s)=%d' % (list_name, len(list_))
else:
return '%s=%r' % (list_name, list_) | python | def list_str_summarized(list_, list_name, maxlen=5):
"""
prints the list members when the list is small and the length when it is
large
"""
if len(list_) > maxlen:
return 'len(%s)=%d' % (list_name, len(list_))
else:
return '%s=%r' % (list_name, list_) | [
"def",
"list_str_summarized",
"(",
"list_",
",",
"list_name",
",",
"maxlen",
"=",
"5",
")",
":",
"if",
"len",
"(",
"list_",
")",
">",
"maxlen",
":",
"return",
"'len(%s)=%d'",
"%",
"(",
"list_name",
",",
"len",
"(",
"list_",
")",
")",
"else",
":",
"return",
"'%s=%r'",
"%",
"(",
"list_name",
",",
"list_",
")"
] | prints the list members when the list is small and the length when it is
large | [
"prints",
"the",
"list",
"members",
"when",
"the",
"list",
"is",
"small",
"and",
"the",
"length",
"when",
"it",
"is",
"large"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1251-L1259 | train |
Erotemic/utool | utool/util_str.py | _rectify_countdown_or_bool | def _rectify_countdown_or_bool(count_or_bool):
"""
used by recrusive functions to specify which level to turn a bool on in
counting down yeilds True, True, ..., False
conting up yeilds False, False, False, ... True
Args:
count_or_bool (bool or int): if positive will count down, if negative
will count up, if bool will remain same
Returns:
int or bool: count_or_bool_
CommandLine:
python -m utool.util_str --test-_rectify_countdown_or_bool
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import _rectify_countdown_or_bool # NOQA
>>> count_or_bool = True
>>> a1 = (_rectify_countdown_or_bool(2))
>>> a2 = (_rectify_countdown_or_bool(1))
>>> a3 = (_rectify_countdown_or_bool(0))
>>> a4 = (_rectify_countdown_or_bool(-1))
>>> a5 = (_rectify_countdown_or_bool(-2))
>>> a6 = (_rectify_countdown_or_bool(True))
>>> a7 = (_rectify_countdown_or_bool(False))
>>> result = [a1, a2, a3, a4, a5, a6, a7]
>>> print(result)
[1.0, 0.0, 0, 0.0, -1.0, True, False]
[1.0, True, False, False, -1.0, True, False]
"""
if count_or_bool is True or count_or_bool is False:
count_or_bool_ = count_or_bool
elif isinstance(count_or_bool, int):
if count_or_bool == 0:
return 0
sign_ = math.copysign(1, count_or_bool)
count_or_bool_ = int(count_or_bool - sign_)
#if count_or_bool_ == 0:
# return sign_ == 1
else:
count_or_bool_ = False
return count_or_bool_ | python | def _rectify_countdown_or_bool(count_or_bool):
"""
used by recrusive functions to specify which level to turn a bool on in
counting down yeilds True, True, ..., False
conting up yeilds False, False, False, ... True
Args:
count_or_bool (bool or int): if positive will count down, if negative
will count up, if bool will remain same
Returns:
int or bool: count_or_bool_
CommandLine:
python -m utool.util_str --test-_rectify_countdown_or_bool
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import _rectify_countdown_or_bool # NOQA
>>> count_or_bool = True
>>> a1 = (_rectify_countdown_or_bool(2))
>>> a2 = (_rectify_countdown_or_bool(1))
>>> a3 = (_rectify_countdown_or_bool(0))
>>> a4 = (_rectify_countdown_or_bool(-1))
>>> a5 = (_rectify_countdown_or_bool(-2))
>>> a6 = (_rectify_countdown_or_bool(True))
>>> a7 = (_rectify_countdown_or_bool(False))
>>> result = [a1, a2, a3, a4, a5, a6, a7]
>>> print(result)
[1.0, 0.0, 0, 0.0, -1.0, True, False]
[1.0, True, False, False, -1.0, True, False]
"""
if count_or_bool is True or count_or_bool is False:
count_or_bool_ = count_or_bool
elif isinstance(count_or_bool, int):
if count_or_bool == 0:
return 0
sign_ = math.copysign(1, count_or_bool)
count_or_bool_ = int(count_or_bool - sign_)
#if count_or_bool_ == 0:
# return sign_ == 1
else:
count_or_bool_ = False
return count_or_bool_ | [
"def",
"_rectify_countdown_or_bool",
"(",
"count_or_bool",
")",
":",
"if",
"count_or_bool",
"is",
"True",
"or",
"count_or_bool",
"is",
"False",
":",
"count_or_bool_",
"=",
"count_or_bool",
"elif",
"isinstance",
"(",
"count_or_bool",
",",
"int",
")",
":",
"if",
"count_or_bool",
"==",
"0",
":",
"return",
"0",
"sign_",
"=",
"math",
".",
"copysign",
"(",
"1",
",",
"count_or_bool",
")",
"count_or_bool_",
"=",
"int",
"(",
"count_or_bool",
"-",
"sign_",
")",
"else",
":",
"count_or_bool_",
"=",
"False",
"return",
"count_or_bool_"
] | used by recrusive functions to specify which level to turn a bool on in
counting down yeilds True, True, ..., False
conting up yeilds False, False, False, ... True
Args:
count_or_bool (bool or int): if positive will count down, if negative
will count up, if bool will remain same
Returns:
int or bool: count_or_bool_
CommandLine:
python -m utool.util_str --test-_rectify_countdown_or_bool
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import _rectify_countdown_or_bool # NOQA
>>> count_or_bool = True
>>> a1 = (_rectify_countdown_or_bool(2))
>>> a2 = (_rectify_countdown_or_bool(1))
>>> a3 = (_rectify_countdown_or_bool(0))
>>> a4 = (_rectify_countdown_or_bool(-1))
>>> a5 = (_rectify_countdown_or_bool(-2))
>>> a6 = (_rectify_countdown_or_bool(True))
>>> a7 = (_rectify_countdown_or_bool(False))
>>> result = [a1, a2, a3, a4, a5, a6, a7]
>>> print(result)
[1.0, 0.0, 0, 0.0, -1.0, True, False]
[1.0, True, False, False, -1.0, True, False] | [
"used",
"by",
"recrusive",
"functions",
"to",
"specify",
"which",
"level",
"to",
"turn",
"a",
"bool",
"on",
"in",
"counting",
"down",
"yeilds",
"True",
"True",
"...",
"False",
"conting",
"up",
"yeilds",
"False",
"False",
"False",
"...",
"True"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1266-L1310 | train |
Erotemic/utool | utool/util_str.py | repr2 | def repr2(obj_, **kwargs):
"""
Attempt to replace repr more configurable
pretty version that works the same in both 2 and 3
"""
kwargs['nl'] = kwargs.pop('nl', kwargs.pop('newlines', False))
val_str = _make_valstr(**kwargs)
return val_str(obj_) | python | def repr2(obj_, **kwargs):
"""
Attempt to replace repr more configurable
pretty version that works the same in both 2 and 3
"""
kwargs['nl'] = kwargs.pop('nl', kwargs.pop('newlines', False))
val_str = _make_valstr(**kwargs)
return val_str(obj_) | [
"def",
"repr2",
"(",
"obj_",
",",
"**",
"kwargs",
")",
":",
"kwargs",
"[",
"'nl'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'nl'",
",",
"kwargs",
".",
"pop",
"(",
"'newlines'",
",",
"False",
")",
")",
"val_str",
"=",
"_make_valstr",
"(",
"**",
"kwargs",
")",
"return",
"val_str",
"(",
"obj_",
")"
] | Attempt to replace repr more configurable
pretty version that works the same in both 2 and 3 | [
"Attempt",
"to",
"replace",
"repr",
"more",
"configurable",
"pretty",
"version",
"that",
"works",
"the",
"same",
"in",
"both",
"2",
"and",
"3"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1317-L1324 | train |
Erotemic/utool | utool/util_str.py | repr2_json | def repr2_json(obj_, **kwargs):
""" hack for json reprs """
import utool as ut
kwargs['trailing_sep'] = False
json_str = ut.repr2(obj_, **kwargs)
json_str = str(json_str.replace('\'', '"'))
json_str = json_str.replace('(', '[')
json_str = json_str.replace(')', ']')
json_str = json_str.replace('None', 'null')
return json_str | python | def repr2_json(obj_, **kwargs):
""" hack for json reprs """
import utool as ut
kwargs['trailing_sep'] = False
json_str = ut.repr2(obj_, **kwargs)
json_str = str(json_str.replace('\'', '"'))
json_str = json_str.replace('(', '[')
json_str = json_str.replace(')', ']')
json_str = json_str.replace('None', 'null')
return json_str | [
"def",
"repr2_json",
"(",
"obj_",
",",
"**",
"kwargs",
")",
":",
"import",
"utool",
"as",
"ut",
"kwargs",
"[",
"'trailing_sep'",
"]",
"=",
"False",
"json_str",
"=",
"ut",
".",
"repr2",
"(",
"obj_",
",",
"**",
"kwargs",
")",
"json_str",
"=",
"str",
"(",
"json_str",
".",
"replace",
"(",
"'\\''",
",",
"'\"'",
")",
")",
"json_str",
"=",
"json_str",
".",
"replace",
"(",
"'('",
",",
"'['",
")",
"json_str",
"=",
"json_str",
".",
"replace",
"(",
"')'",
",",
"']'",
")",
"json_str",
"=",
"json_str",
".",
"replace",
"(",
"'None'",
",",
"'null'",
")",
"return",
"json_str"
] | hack for json reprs | [
"hack",
"for",
"json",
"reprs"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1327-L1336 | train |
Erotemic/utool | utool/util_str.py | list_str | 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 | python | 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 | [
"def",
"list_str",
"(",
"list_",
",",
"**",
"listkw",
")",
":",
"r",
"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'",
",",
"' '",
")",
"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",
":",
"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",
")",
"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"
] | 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, ''),
],
] | [
"r",
"Makes",
"a",
"pretty",
"list",
"string"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1582-L1694 | train |
Erotemic/utool | utool/util_str.py | horiz_string | def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
"""
import unicodedata
precision = kwargs.get('precision', None)
sep = kwargs.get('sep', '')
if len(args) == 1 and not isinstance(args[0], six.string_types):
val_list = args[0]
else:
val_list = args
val_list = [unicodedata.normalize('NFC', ensure_unicode(val))
for val in val_list]
all_lines = []
hpos = 0
# for each value in the list or args
for sx in range(len(val_list)):
# Ensure value is a string
val = val_list[sx]
str_ = None
if precision is not None:
# Hack in numpy precision
if util_type.HAVE_NUMPY:
try:
if isinstance(val, np.ndarray):
str_ = np.array_str(val, precision=precision,
suppress_small=True)
except ImportError:
pass
if str_ is None:
str_ = six.text_type(val_list[sx])
# continue with formating
lines = str_.split('\n')
line_diff = len(lines) - len(all_lines)
# Vertical padding
if line_diff > 0:
all_lines += [' ' * hpos] * line_diff
# Add strings
for lx, line in enumerate(lines):
all_lines[lx] += line
hpos = max(hpos, len(all_lines[lx]))
# Horizontal padding
for lx in range(len(all_lines)):
hpos_diff = hpos - len(all_lines[lx])
all_lines[lx] += ' ' * hpos_diff + sep
all_lines = [line.rstrip(' ') for line in all_lines]
ret = '\n'.join(all_lines)
return ret | python | def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]]
"""
import unicodedata
precision = kwargs.get('precision', None)
sep = kwargs.get('sep', '')
if len(args) == 1 and not isinstance(args[0], six.string_types):
val_list = args[0]
else:
val_list = args
val_list = [unicodedata.normalize('NFC', ensure_unicode(val))
for val in val_list]
all_lines = []
hpos = 0
# for each value in the list or args
for sx in range(len(val_list)):
# Ensure value is a string
val = val_list[sx]
str_ = None
if precision is not None:
# Hack in numpy precision
if util_type.HAVE_NUMPY:
try:
if isinstance(val, np.ndarray):
str_ = np.array_str(val, precision=precision,
suppress_small=True)
except ImportError:
pass
if str_ is None:
str_ = six.text_type(val_list[sx])
# continue with formating
lines = str_.split('\n')
line_diff = len(lines) - len(all_lines)
# Vertical padding
if line_diff > 0:
all_lines += [' ' * hpos] * line_diff
# Add strings
for lx, line in enumerate(lines):
all_lines[lx] += line
hpos = max(hpos, len(all_lines[lx]))
# Horizontal padding
for lx in range(len(all_lines)):
hpos_diff = hpos - len(all_lines[lx])
all_lines[lx] += ' ' * hpos_diff + sep
all_lines = [line.rstrip(' ') for line in all_lines]
ret = '\n'.join(all_lines)
return ret | [
"def",
"horiz_string",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"import",
"unicodedata",
"precision",
"=",
"kwargs",
".",
"get",
"(",
"'precision'",
",",
"None",
")",
"sep",
"=",
"kwargs",
".",
"get",
"(",
"'sep'",
",",
"''",
")",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"six",
".",
"string_types",
")",
":",
"val_list",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"val_list",
"=",
"args",
"val_list",
"=",
"[",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"ensure_unicode",
"(",
"val",
")",
")",
"for",
"val",
"in",
"val_list",
"]",
"all_lines",
"=",
"[",
"]",
"hpos",
"=",
"0",
"for",
"sx",
"in",
"range",
"(",
"len",
"(",
"val_list",
")",
")",
":",
"val",
"=",
"val_list",
"[",
"sx",
"]",
"str_",
"=",
"None",
"if",
"precision",
"is",
"not",
"None",
":",
"if",
"util_type",
".",
"HAVE_NUMPY",
":",
"try",
":",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"str_",
"=",
"np",
".",
"array_str",
"(",
"val",
",",
"precision",
"=",
"precision",
",",
"suppress_small",
"=",
"True",
")",
"except",
"ImportError",
":",
"pass",
"if",
"str_",
"is",
"None",
":",
"str_",
"=",
"six",
".",
"text_type",
"(",
"val_list",
"[",
"sx",
"]",
")",
"lines",
"=",
"str_",
".",
"split",
"(",
"'\\n'",
")",
"line_diff",
"=",
"len",
"(",
"lines",
")",
"-",
"len",
"(",
"all_lines",
")",
"if",
"line_diff",
">",
"0",
":",
"all_lines",
"+=",
"[",
"' '",
"*",
"hpos",
"]",
"*",
"line_diff",
"for",
"lx",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"all_lines",
"[",
"lx",
"]",
"+=",
"line",
"hpos",
"=",
"max",
"(",
"hpos",
",",
"len",
"(",
"all_lines",
"[",
"lx",
"]",
")",
")",
"for",
"lx",
"in",
"range",
"(",
"len",
"(",
"all_lines",
")",
")",
":",
"hpos_diff",
"=",
"hpos",
"-",
"len",
"(",
"all_lines",
"[",
"lx",
"]",
")",
"all_lines",
"[",
"lx",
"]",
"+=",
"' '",
"*",
"hpos_diff",
"+",
"sep",
"all_lines",
"=",
"[",
"line",
".",
"rstrip",
"(",
"' '",
")",
"for",
"line",
"in",
"all_lines",
"]",
"ret",
"=",
"'\\n'",
".",
"join",
"(",
"all_lines",
")",
"return",
"ret"
] | Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util_str --test-horiz_string
Example1:
>>> # ENABLE_DOCTEST
>>> # Pretty printing of matrices demo / test
>>> import utool
>>> import numpy as np
>>> # Wouldn't it be nice if we could print this operation easily?
>>> B = np.array(((1, 2), (3, 4)))
>>> C = np.array(((5, 6), (7, 8)))
>>> A = B.dot(C)
>>> # Eg 1:
>>> result = (utool.hz_str('A = ', A, ' = ', B, ' * ', C))
>>> print(result)
A = [[19 22] = [[1 2] * [[5 6]
[43 50]] [3 4]] [7 8]]
Exam2:
>>> # Eg 2:
>>> str_list = ['A = ', str(B), ' * ', str(C)]
>>> horizstr = (utool.horiz_string(*str_list))
>>> result = (horizstr)
>>> print(result)
A = [[1 2] * [[5 6]
[3 4]] [7 8]] | [
"Horizontally",
"concatenates",
"strings",
"reprs",
"preserving",
"indentation"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1795-L1879 | train |
Erotemic/utool | utool/util_str.py | str_between | def str_between(str_, startstr, endstr):
r"""
gets substring between two sentianl strings
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> str_ = '\n INSERT INTO vsone(\n'
>>> startstr = 'INSERT'
>>> endstr = '('
>>> result = str_between(str_, startstr, endstr)
>>> print(result)
"""
if startstr is None:
startpos = 0
else:
startpos = str_.find(startstr) + len(startstr)
if endstr is None:
endpos = None
else:
endpos = str_.find(endstr)
if endpos == -1:
endpos = None
newstr = str_[startpos:endpos]
return newstr | python | def str_between(str_, startstr, endstr):
r"""
gets substring between two sentianl strings
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> str_ = '\n INSERT INTO vsone(\n'
>>> startstr = 'INSERT'
>>> endstr = '('
>>> result = str_between(str_, startstr, endstr)
>>> print(result)
"""
if startstr is None:
startpos = 0
else:
startpos = str_.find(startstr) + len(startstr)
if endstr is None:
endpos = None
else:
endpos = str_.find(endstr)
if endpos == -1:
endpos = None
newstr = str_[startpos:endpos]
return newstr | [
"def",
"str_between",
"(",
"str_",
",",
"startstr",
",",
"endstr",
")",
":",
"r",
"if",
"startstr",
"is",
"None",
":",
"startpos",
"=",
"0",
"else",
":",
"startpos",
"=",
"str_",
".",
"find",
"(",
"startstr",
")",
"+",
"len",
"(",
"startstr",
")",
"if",
"endstr",
"is",
"None",
":",
"endpos",
"=",
"None",
"else",
":",
"endpos",
"=",
"str_",
".",
"find",
"(",
"endstr",
")",
"if",
"endpos",
"==",
"-",
"1",
":",
"endpos",
"=",
"None",
"newstr",
"=",
"str_",
"[",
"startpos",
":",
"endpos",
"]",
"return",
"newstr"
] | r"""
gets substring between two sentianl strings
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> str_ = '\n INSERT INTO vsone(\n'
>>> startstr = 'INSERT'
>>> endstr = '('
>>> result = str_between(str_, startstr, endstr)
>>> print(result) | [
"r",
"gets",
"substring",
"between",
"two",
"sentianl",
"strings"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1885-L1910 | train |
Erotemic/utool | utool/util_str.py | get_callable_name | def get_callable_name(func):
""" Works on must functionlike objects including str, which has no func_name
Args:
func (function):
Returns:
str:
CommandLine:
python -m utool.util_str --exec-get_callable_name
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = len
>>> result = get_callable_name(func)
>>> print(result)
len
"""
try:
return meta_util_six.get_funcname(func)
except AttributeError:
if isinstance(func, type):
return repr(func).replace('<type \'', '').replace('\'>', '')
elif hasattr(func, '__name__'):
return func.__name__
else:
raise NotImplementedError(('cannot get func_name of func=%r'
'type(func)=%r') % (func, type(func))) | python | def get_callable_name(func):
""" Works on must functionlike objects including str, which has no func_name
Args:
func (function):
Returns:
str:
CommandLine:
python -m utool.util_str --exec-get_callable_name
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = len
>>> result = get_callable_name(func)
>>> print(result)
len
"""
try:
return meta_util_six.get_funcname(func)
except AttributeError:
if isinstance(func, type):
return repr(func).replace('<type \'', '').replace('\'>', '')
elif hasattr(func, '__name__'):
return func.__name__
else:
raise NotImplementedError(('cannot get func_name of func=%r'
'type(func)=%r') % (func, type(func))) | [
"def",
"get_callable_name",
"(",
"func",
")",
":",
"try",
":",
"return",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
"except",
"AttributeError",
":",
"if",
"isinstance",
"(",
"func",
",",
"type",
")",
":",
"return",
"repr",
"(",
"func",
")",
".",
"replace",
"(",
"'<type \\''",
",",
"''",
")",
".",
"replace",
"(",
"'\\'>'",
",",
"''",
")",
"elif",
"hasattr",
"(",
"func",
",",
"'__name__'",
")",
":",
"return",
"func",
".",
"__name__",
"else",
":",
"raise",
"NotImplementedError",
"(",
"(",
"'cannot get func_name of func=%r'",
"'type(func)=%r'",
")",
"%",
"(",
"func",
",",
"type",
"(",
"func",
")",
")",
")"
] | Works on must functionlike objects including str, which has no func_name
Args:
func (function):
Returns:
str:
CommandLine:
python -m utool.util_str --exec-get_callable_name
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> func = len
>>> result = get_callable_name(func)
>>> print(result)
len | [
"Works",
"on",
"must",
"functionlike",
"objects",
"including",
"str",
"which",
"has",
"no",
"func_name"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1913-L1942 | train |
Erotemic/utool | utool/util_str.py | multi_replace | def multi_replace(str_, search_list, repl_list):
r"""
Performs multiple replace functions foreach item in search_list and
repl_list.
Args:
str_ (str): string to search
search_list (list): list of search strings
repl_list (list or str): one or multiple replace strings
Returns:
str: str_
CommandLine:
python -m utool.util_str --exec-multi_replace
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = 'foo. bar: baz; spam-eggs --- eggs+spam'
>>> search_list = ['.', ':', '---']
>>> repl_list = '@'
>>> str_ = multi_replace(str_, search_list, repl_list)
>>> result = ('str_ = %s' % (str(str_),))
>>> print(result)
str_ = foo@ bar@ baz; spam-eggs @ eggs+spam
"""
if isinstance(repl_list, six.string_types):
repl_list_ = [repl_list] * len(search_list)
else:
repl_list_ = repl_list
newstr = str_
assert len(search_list) == len(repl_list_), 'bad lens'
for search, repl in zip(search_list, repl_list_):
newstr = newstr.replace(search, repl)
return newstr | python | def multi_replace(str_, search_list, repl_list):
r"""
Performs multiple replace functions foreach item in search_list and
repl_list.
Args:
str_ (str): string to search
search_list (list): list of search strings
repl_list (list or str): one or multiple replace strings
Returns:
str: str_
CommandLine:
python -m utool.util_str --exec-multi_replace
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = 'foo. bar: baz; spam-eggs --- eggs+spam'
>>> search_list = ['.', ':', '---']
>>> repl_list = '@'
>>> str_ = multi_replace(str_, search_list, repl_list)
>>> result = ('str_ = %s' % (str(str_),))
>>> print(result)
str_ = foo@ bar@ baz; spam-eggs @ eggs+spam
"""
if isinstance(repl_list, six.string_types):
repl_list_ = [repl_list] * len(search_list)
else:
repl_list_ = repl_list
newstr = str_
assert len(search_list) == len(repl_list_), 'bad lens'
for search, repl in zip(search_list, repl_list_):
newstr = newstr.replace(search, repl)
return newstr | [
"def",
"multi_replace",
"(",
"str_",
",",
"search_list",
",",
"repl_list",
")",
":",
"r",
"if",
"isinstance",
"(",
"repl_list",
",",
"six",
".",
"string_types",
")",
":",
"repl_list_",
"=",
"[",
"repl_list",
"]",
"*",
"len",
"(",
"search_list",
")",
"else",
":",
"repl_list_",
"=",
"repl_list",
"newstr",
"=",
"str_",
"assert",
"len",
"(",
"search_list",
")",
"==",
"len",
"(",
"repl_list_",
")",
",",
"'bad lens'",
"for",
"search",
",",
"repl",
"in",
"zip",
"(",
"search_list",
",",
"repl_list_",
")",
":",
"newstr",
"=",
"newstr",
".",
"replace",
"(",
"search",
",",
"repl",
")",
"return",
"newstr"
] | r"""
Performs multiple replace functions foreach item in search_list and
repl_list.
Args:
str_ (str): string to search
search_list (list): list of search strings
repl_list (list or str): one or multiple replace strings
Returns:
str: str_
CommandLine:
python -m utool.util_str --exec-multi_replace
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> str_ = 'foo. bar: baz; spam-eggs --- eggs+spam'
>>> search_list = ['.', ':', '---']
>>> repl_list = '@'
>>> str_ = multi_replace(str_, search_list, repl_list)
>>> result = ('str_ = %s' % (str(str_),))
>>> print(result)
str_ = foo@ bar@ baz; spam-eggs @ eggs+spam | [
"r",
"Performs",
"multiple",
"replace",
"functions",
"foreach",
"item",
"in",
"search_list",
"and",
"repl_list",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2213-L2248 | train |
Erotemic/utool | utool/util_str.py | pluralize | def pluralize(wordtext, num=2, plural_suffix='s'):
r"""
Heuristically changes a word to its plural form if `num` is not 1
Args:
wordtext (str): word in singular form
num (int): a length of an associated list if applicable (default = 2)
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: pluralized form. Can handle some genitive cases
CommandLine:
python -m utool.util_str pluralize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> wordtext = 'foo'
>>> result = pluralize(wordtext)
>>> print(result)
foos
"""
if num == 1:
return wordtext
else:
if wordtext.endswith('\'s'):
return wordtext[:-2] + 's\''
else:
return wordtext + plural_suffix
return (wordtext + plural_suffix) if num != 1 else wordtext | python | def pluralize(wordtext, num=2, plural_suffix='s'):
r"""
Heuristically changes a word to its plural form if `num` is not 1
Args:
wordtext (str): word in singular form
num (int): a length of an associated list if applicable (default = 2)
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: pluralized form. Can handle some genitive cases
CommandLine:
python -m utool.util_str pluralize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> wordtext = 'foo'
>>> result = pluralize(wordtext)
>>> print(result)
foos
"""
if num == 1:
return wordtext
else:
if wordtext.endswith('\'s'):
return wordtext[:-2] + 's\''
else:
return wordtext + plural_suffix
return (wordtext + plural_suffix) if num != 1 else wordtext | [
"def",
"pluralize",
"(",
"wordtext",
",",
"num",
"=",
"2",
",",
"plural_suffix",
"=",
"'s'",
")",
":",
"r",
"if",
"num",
"==",
"1",
":",
"return",
"wordtext",
"else",
":",
"if",
"wordtext",
".",
"endswith",
"(",
"'\\'s'",
")",
":",
"return",
"wordtext",
"[",
":",
"-",
"2",
"]",
"+",
"'s\\''",
"else",
":",
"return",
"wordtext",
"+",
"plural_suffix",
"return",
"(",
"wordtext",
"+",
"plural_suffix",
")",
"if",
"num",
"!=",
"1",
"else",
"wordtext"
] | r"""
Heuristically changes a word to its plural form if `num` is not 1
Args:
wordtext (str): word in singular form
num (int): a length of an associated list if applicable (default = 2)
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: pluralized form. Can handle some genitive cases
CommandLine:
python -m utool.util_str pluralize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> wordtext = 'foo'
>>> result = pluralize(wordtext)
>>> print(result)
foos | [
"r",
"Heuristically",
"changes",
"a",
"word",
"to",
"its",
"plural",
"form",
"if",
"num",
"is",
"not",
"1"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2251-L2281 | train |
Erotemic/utool | utool/util_str.py | quantstr | def quantstr(typestr, num, plural_suffix='s'):
r"""
Heuristically generates an english phrase relating to the quantity of
something. This is useful for writing user messages.
Args:
typestr (str): singular form of the word
num (int): quanity of the type
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: quantity phrase
CommandLine:
python -m utool.util_str quantity_str
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> items = [1, 2, 3]
>>> result = 'The list contains ' + (quantstr('item', len(items)))
>>> items = [1]
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> items = []
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> print(result)
The list contains 3 items
The list contains 1 item
The list contains 0 items
"""
return six.text_type(num) + ' ' + pluralize(typestr, num, plural_suffix) | python | def quantstr(typestr, num, plural_suffix='s'):
r"""
Heuristically generates an english phrase relating to the quantity of
something. This is useful for writing user messages.
Args:
typestr (str): singular form of the word
num (int): quanity of the type
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: quantity phrase
CommandLine:
python -m utool.util_str quantity_str
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> items = [1, 2, 3]
>>> result = 'The list contains ' + (quantstr('item', len(items)))
>>> items = [1]
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> items = []
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> print(result)
The list contains 3 items
The list contains 1 item
The list contains 0 items
"""
return six.text_type(num) + ' ' + pluralize(typestr, num, plural_suffix) | [
"def",
"quantstr",
"(",
"typestr",
",",
"num",
",",
"plural_suffix",
"=",
"'s'",
")",
":",
"r",
"return",
"six",
".",
"text_type",
"(",
"num",
")",
"+",
"' '",
"+",
"pluralize",
"(",
"typestr",
",",
"num",
",",
"plural_suffix",
")"
] | r"""
Heuristically generates an english phrase relating to the quantity of
something. This is useful for writing user messages.
Args:
typestr (str): singular form of the word
num (int): quanity of the type
plural_suffix (str): heurstic plural form (default = 's')
Returns:
str: quantity phrase
CommandLine:
python -m utool.util_str quantity_str
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> items = [1, 2, 3]
>>> result = 'The list contains ' + (quantstr('item', len(items)))
>>> items = [1]
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> items = []
>>> result += '\nThe list contains ' + (quantstr('item', len(items)))
>>> print(result)
The list contains 3 items
The list contains 1 item
The list contains 0 items | [
"r",
"Heuristically",
"generates",
"an",
"english",
"phrase",
"relating",
"to",
"the",
"quantity",
"of",
"something",
".",
"This",
"is",
"useful",
"for",
"writing",
"user",
"messages",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2284-L2314 | train |
Erotemic/utool | utool/util_str.py | msgblock | def msgblock(key, text, side='|'):
""" puts text inside a visual ascii block """
blocked_text = ''.join(
[' + --- ', key, ' ---\n'] +
[' ' + side + ' ' + line + '\n' for line in text.split('\n')] +
[' L ___ ', key, ' ___\n']
)
return blocked_text | python | def msgblock(key, text, side='|'):
""" puts text inside a visual ascii block """
blocked_text = ''.join(
[' + --- ', key, ' ---\n'] +
[' ' + side + ' ' + line + '\n' for line in text.split('\n')] +
[' L ___ ', key, ' ___\n']
)
return blocked_text | [
"def",
"msgblock",
"(",
"key",
",",
"text",
",",
"side",
"=",
"'|'",
")",
":",
"blocked_text",
"=",
"''",
".",
"join",
"(",
"[",
"' + --- '",
",",
"key",
",",
"' ---\\n'",
"]",
"+",
"[",
"' '",
"+",
"side",
"+",
"' '",
"+",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
"]",
"+",
"[",
"' L ",
" '",
",",
"key",
",",
"' ",
"\\n'",
"]",
")",
"return",
"blocked_text"
] | puts text inside a visual ascii block | [
"puts",
"text",
"inside",
"a",
"visual",
"ascii",
"block"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2317-L2324 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.