Esempio n. 1
0
 def check(self):
     rep = dict()
     roots = list(self.roots())
     nodes = set(self.nodes[item].ident for item in self.nodes)
     parents = set(
         self.parent(item)
         for item in filter(lambda i: not self.is_root(i), self.nodes))
     children = list()
     for item in self.nodes:
         children.extend(self.children(item))
     children = set(children)
     rep['nonempty'] = self.size() > 0
     rep['single_root'] = len(roots) == 1
     rep['defined_ids'] = all(nodes)
     rep['unique_ids'] = len(nodes) == len(self.nodes)
     rep['valid_ids'] = nodes == set(self.nodes)
     rep['valid_parents'] = parents.issubset(self.nodes)
     rep['valid_children'] = children.issubset(self.nodes)
     rep['no_root_reference'] = children.isdisjoint(roots)
     rep['no_self_reference'] = all(
         self.parent(item) not in self.children(item)
         for item in self.nodes)
     rep['valid_links'] = all(item in self.children(self.parent(item))
                              for item in self.nodes
                              if self.parent(item) is not None)
     rep['traversable_data'] = set(self.nodes) == set(self.traverse())
     return rep
Esempio n. 2
0
 def __eq__(self, other):
     if isinstance(other, Dyad):
         return builtins.all(self.notes[i] == other.notes[i]
                    for i in range(len(self.notes)))
     else:
         if builtins.all(isinstance(other[i], Note) for i in range(len(other))):
             return self.notes == other
Esempio n. 3
0
 def __contains__(self, k):
     if isinstance(k, Note):
         return k.to_octave(0) in self.notes
     elif isinstance(k, Chord):
         return builtins.all(n in self for n in k.notes)
     elif isinstance(k, (list, set, tuple)):
         return builtins.all(x in self for x in k)
     else:
         return False
Esempio n. 4
0
 def test_chain(self):
     list1 = ['A', 'B', 'C']
     list2 = ['D', 'E', 'F']
     chain1 = evaluate(chain(make_deferrable(list1), list2))
     chain2 = itertools.chain(list1, list2)
     self.assertTrue(
         builtins.all((a == b for a, b in builtins.zip(chain1, chain2))))
def eliminate(values, s, d):
    """Eliminate d from values[s]; propagate when values or places <=2.
    Return values, except return False if a contradiction is detected."""
    if d not in values[s]:
        return values  # Already eliminated.

    values[s] = values[s].replace(d, '')

    # (1) if a square s is reduced to one value d2, then eliminated d2 from the peers.
    if len(values[s]) == 0:
        return False  # Contradiction is detected
    elif len(values[s]) == 1:
        d2 = values[s]
        if not all(eliminate(values, s2, d2) for s2 in peers[s]):
            return False

    # (2) if a unit u is reduced to only one place for a value d, then put it there.
    for u in units[s]:
        dplaces = [s1 for s1 in u if d in values[s1]]
        if len(dplaces) == 0:
            return False  # Contradiction: No place for this value
        elif len(dplaces) == 1:
            # d can only be in one place is unit; assign it there
            if not assign(values, dplaces[0], d):
                return False

    return values
Esempio n. 6
0
 def has_perms(self, perm_list, obj=None):
     """
     Returns True if the user has each of the specified permissions. If
     object is passed, it checks if the user has all required perms for this
     object.
     """
     return all(self.has_perm(perm, obj) for perm in perm_list)
Esempio n. 7
0
 def wrapped(tup_arg, **kwargs):
     types = tuple(a.dtype for a in tup_arg)
     if builtins.all(t == types[0] for t in types):
         return func(tup_arg, **kwargs)
     max_rank = max(TYPES_TO_RANK[t] for t in types)
     max_type = TYPES_BY_RANK[max_rank]
     tup_arg = tuple(a.to(max_type) for a in tup_arg)
     return func(tup_arg, **kwargs)
def test():
    """A set of unit tests"""
    assert len(squares) == 81
    assert len(unit_list) == 27
    assert all(len(units[s]) == 3 for s in squares)
    assert all(len(peers[s]) == 20 for s in peers)

    assert units['C2'] == [[
        'A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'
    ], ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8',
        'C9'], ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']]

    assert peers['C2'] == set([
        'A2', 'B2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2', 'C1', 'C3', 'C4', 'C5',
        'C6', 'C7', 'C8', 'C9', 'A1', 'A3', 'B1', 'B3'
    ])
    print('All test pass')
Esempio n. 9
0
    def __init__(self, data):
        if not isinstance(data, Sequence):
            raise TypeError('data argument is not a sequence')

        if not builtins.all(isinstance(v, numbers.Number) for v in data):
            raise ValueError('data argument contains an element that is not a number')

        self.data = list(data)
Esempio n. 10
0
 def check(self):
     rep = Nodes.check(self)
     rep['increasing_id_order'] = all(self.parent(item) < item
         for item in filter(lambda i: not self.is_root(i), self.nodes))
     rep['valid_types'] = all(self.type(item) in Point.TYPES for item in self.nodes)
     rep['nonzero_diam'] = all(self.diam(item) != 0 for item in self.nodes)
     rep['sequential_ids'] = sorted(self.nodes) == list(range(min(self.nodes), max(self.nodes)+1))
     rep['no_forks'] = all(len(self.nodes[ident].children) == 2 for ident in self.forks() if not self.is_root(ident))
     soma = list(filter(self.is_soma, self.nodes))
     if soma:
         rep['unit_id_in_soma'] = 1 in soma
         rep['unit_id_is_root'] = 1 == self.root()
         path = list()
         for ident in self.stems():
             path.extend(self.traverse(ident))
         rep['unit_id_is_origin'] = set(path) == set(self.nodes).difference(soma)
     return rep
Esempio n. 11
0
def test_max_to_ord():
    try:
        from lesson import max_to_ord
    except ImportError:
        _import_error('max_to_ord')
        return False
    args_and_expected = {'': -1, '23l4km2l3k4234': 109, 'a': 97, 'thbjgk': 116}
    return all([v == max_to_ord(k) for k, v in args_and_expected.items()])
Esempio n. 12
0
def all(iterable, pred):
    """Returns True if ALL elements in the given iterable are true for the
    given pred function"""
    warnings.warn(
        "pipe.all is deprecated, use the builtin all(...) instead.",
        DeprecationWarning,
        stacklevel=4,
    )
    return builtins.all(pred(x) for x in iterable)
Esempio n. 13
0
    def _testing(x, __args_raw=None):
        x = __args_raw["x"]  # x as a series, dtype has been compromised
        if is_scalar_pd(x):
            return isinstance(x, scalar_types)

        if hasattr(x, "dtype"):
            return dtype_checker(x)

        return builtins.all(isinstance(elem, scalar_types) for elem in x)
Esempio n. 14
0
def test_is_number_positive():
    try:
        from lesson import is_number_positive
    except ImportError:
        _import_error('is_number_positive')
        return False
    falses = [is_number_positive(x) for x in [-1, -2, -3, -4, -5]]
    trues = [is_number_positive(x) for x in [1, 2, 3, 4, 5]]
    return not any(falses) and all(trues) and is_number_positive(
        0) == "Neither"
Esempio n. 15
0
def all(f, lst):
    """Returns `true` if all elements of the list match the predicate, `false` if there are any that don't.
    
    Args:
        f (function): The predicate function.
        lst (list): The list to consider.
    
    Returns:
        bool: `true` if the predicate is satisfied by every element, `false` otherwise.
    """
    return builtins.all(map(f, lst))
Esempio n. 16
0
def _validate_axis(axis, ndim, argname):
    try:
        axis = [operator.index(axis)]
    except TypeError:
        axis = list(axis)
    axis = [a + ndim if a < 0 else a for a in axis]
    if not builtins.all(0 <= a < ndim for a in axis):
        raise ValueError(f"invalid axis for this array in {argname} argument")
    if len(set(axis)) != len(axis):
        raise ValueError(f"repeated axis in {argname} argument")
    return axis
Esempio n. 17
0
    def generate_parameter_list(self, projectId, phaseId=None):
        """
        generate offset parameter list

        todo: collect outputs somewhere else!
        """
        # go for a particular project
        theProject_id = projectId
        allProjects = self.myContext.allProjects
        timelineStart = self.myContext.timelineStart
        timelineLength = self.myContext.timelineLength

        # determine the combined length of the phases,
        # the maximal sum of times in between
        thePhases = next(p.phases for p in allProjects
                         if p.id == theProject_id)
        thePhases.sort(key=lambda ph: ph.start_date)

        origOffsets = [
            monthsDifference(ph2.start_date,
                             (timelineStart if ph1 is None else
                              (ph1.end_date + datetime.timedelta(days=1))))
            for ph1, ph2 in zip([None] + thePhases[:-1], thePhases)
        ]

        # check for overlapping phases
        assert builtins.all(o >= 0 for o in origOffsets)

        phaseLengths = [
            monthsDifference(ph.end_date + datetime.timedelta(days=1),
                             ph.start_date) for ph in thePhases
        ]

        if phaseId is None:
            # act on the project, so change all phases
            offsetMax = timelineLength - sum(phaseLengths)
            possibleOffsets = list(
                offset_generator(offsetMax, len(phaseLengths)))
        else:
            # act on one phase, so change the offset before and after
            phaseIdx = next(i for i, ph in enumerate(thePhases)
                            if ph.id == phaseId)
            ooList = origOffsets + [
                timelineLength - sum(phaseLengths) - sum(origOffsets)
            ]
            possibleOffsets = []
            for o in range(-ooList[phaseIdx], ooList[phaseIdx + 1] + 1):
                newOffset = ooList[:]  # copy
                newOffset[phaseIdx] += o
                newOffset[phaseIdx + 1] -= o
                possibleOffsets.append(tuple(newOffset[:-1]))

        return origOffsets, possibleOffsets
Esempio n. 18
0
def test_pretty_format():
    try:
        from lesson import pretty_format
    except ImportError:
        _import_error('pretty_format')
        return False
    args_and_expected = {
        '': 'No data found!',
        '       23l4km2l3k4234': '23l4km2l3k4234',
        'a': 'a'
    }
    return all([v == pretty_format(k) for k, v in args_and_expected.items()])
Esempio n. 19
0
    def _set_mark(self, mark, toggle=False, all=False):
        if toggle:
            focused = self.focused_widget
            if focused is not None:
                mark = not focused.is_marked

        def get_widget(pos):
            return self._listbox.body[pos]

        def mark_leaves(pos, mark):
            get_widget(pos).is_marked = mark

            for subpos,widget in self.all_children(pos):
                if widget.nodetype == 'leaf':
                    widget.is_marked = mark
                    if mark:
                        self._marked.add(widget)
                    else:
                        self._marked.discard(widget)

                elif widget.nodetype == 'parent':
                    if pos != subpos:  # Avoid infinite recursion
                        mark_leaves(subpos, mark)

        if all:
            # Top ancestor node positions are (0,), (1,), (3,) etc
            for pos in self._filetree.positions():
                if len(pos) == 1:
                    mark_leaves(pos, mark)
        else:
            mark_leaves(self._listbox.focus_position, mark)
        assert builtins.all(m.nodetype == 'leaf' for m in self._marked)

        # A parent node is marked only if all its children are marked.  To check
        # that, we walk through every ancestor up to the top and check all its
        # children.  There is no need to check the children of other parent
        # nodes (uncles, great uncles, etc) because they should already be
        # marked properly from previous runs.

        def all_children_marked(pos):
            marked = True
            childpos = self._filetree.first_child_position(pos)
            while childpos is not None:
                marked = marked and get_widget(childpos).is_marked
                childpos = self._filetree.next_sibling_position(childpos)
            return marked

        parpos = self._filetree.parent_position(self._listbox.focus_position)
        while parpos is not None:
            parwidget = get_widget(parpos)
            parwidget.is_marked = all_children_marked(parpos)
            parpos = self._filetree.parent_position(parpos)
Esempio n. 20
0
async def all(itr: AnyIterable[MaybeAwaitable[Any]]) -> bool:
    """
    Return True if all values are truthy in a mixed iterable, else False.
    The iterable will be fully consumed and any awaitables will
    automatically be awaited.

    Example:

        if await all(it):
            ...

    """
    return builtins.all(await ait_asyncio.gather_iter(itr))
Esempio n. 21
0
def test_sort_chars():
    try:
        from lesson import sort_chars
    except ImportError:
        _import_error('sort_chars')
        return False
    args_and_expected = {
        '': '',
        'a;lsidjf;asd': ';;aaddfijlss',
        '23l4km2l3k4234': '222333444kkllm',
        'a': 'a'
    }
    return all([v == sort_chars(k) for k, v in args_and_expected.items()])
def assign(values, s, d):
    """Eliminate all the other values (except d) from values[s] and propagate.
    Return values, except return False if a contradiction is detected.
    """
    """heuristic: 
    (1) If a square has only one possible value, then eliminate that value from the square's peers.
    (2) If a unit has only one possible place for a value, then put the value there.
    """
    other_values = values[s].replace(d, '')
    if all(eliminate(values, s, d2) for d2 in other_values):
        return values
    else:
        return False
Esempio n. 23
0
def test_char_count():
    try:
        from lesson import char_count
    except ImportError:
        _import_error('char_count')
        return False
    args_and_expected = {
        ('', 'x'): 0,
        ('23l4km2l3k4234', '2'): 3,
        ('a', 'a'): 1,
        ('thbjgk', 'a'): 0
    }
    return all([v == char_count(*k) for k, v in args_and_expected.items()])
Esempio n. 24
0
def test_dobby_search():
    try:
        from lesson import dobby_search
    except ImportError:
        _import_error('dobby_search')
        return False
    args_and_expected = {
        '': 'Dobby',
        'abcdef': 'd',
        '23l4krm2l3k4234': '3',
        'a': 'Dobby'
    }
    return all([dobby_search(k) for k, v in args_and_expected.items()])
Esempio n. 25
0
def get_paretoFront(resultSpace):

    # collect all tuples of result space, which are at the Pareto Frontier
    paretoFront = []
    for r in resultSpace:
        if builtins.all(
            (not isParetoDominant(rr, r)) for rr in resultSpace if rr != r):
            paretoFront.append(r)


#     successfulParameters = [k for k, v in changedChoiceMap.items()
#                             if v in paretoFront]
    return paretoFront
def search(values):
    if values is False:
        return False

    if all(len(values[s]) == 1 for s in squares):
        return values  # Solved

    n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)

    for d in values[s]:
        result = search(assign(values.copy(), s, d))
        if result:
            return result

    return False
Esempio n. 27
0
 def __setitem__(self, idx, val):
     if not isinstance(idx, (int, slice)):
         raise TypeError('only integers and slices are valid indices')
     elif isinstance(idx, int):
         if not isinstance(val, numbers.Number):
             raise TypeError('value argument is not a number')
         self.data[idx] = val
     else:
         if isinstance(val, Sequence):            
             if not builtins.all(isinstance(v, numbers.Number) for v in val):
                 raise ValueError('value argument contains an element that is not a number')
             if len(self.data[idx]) != len(val):
                 raise ValueError("number of indices doesn't match the number of values")
             self.data[idx] = val
         elif isinstance(val, numbers.Number):
             self.data[idx] = [val] * len(range(*idx.indices(self.dim)))
         else:
             raise TypeError('value argument is not a sequence or a number') 
Esempio n. 28
0
    def __init__(self, a, unique_keys, sort_by, iter_with=None):
        self.a = a
        self.sort_by = sort_by
        self.a_sorter = np.argsort(self.sort_by)

        unique_keys_sorter = np.argsort(unique_keys)
        self.sorted_unique_keys = unique_keys[unique_keys_sorter]
        self.unique_keys_unsorter = np.argsort(unique_keys_sorter)

        edges_matched_in_sorted_a = np.append(
            np.searchsorted(self.sort_by,
                            self.sorted_unique_keys,
                            sorter=self.a_sorter), a.size)
        self.left_edges_matched_in_sorted_a = edges_matched_in_sorted_a[:-1]
        self.right_edges_matched_in_sorted_a = edges_matched_in_sorted_a[1:]

        self.iter_with = iter_with
        if iter_with is not None:
            assert builtins.all(len(item) == len(a) for item in iter_with)
Esempio n. 29
0
    def __init__(self,
                 url_builder,
                 consumer_key=None,
                 consumer_secret=None,
                 access_token_key=None,
                 access_token_secret=None,
                 base_url=None):

        if not all([
                access_token_key, access_token_secret, consumer_key,
                consumer_secret
        ]):
            raise AssertionError

        self._url_builder = url_builder(base_url
                                        or 'https://api.twitter.com/1.1')
        self._auth = OAuth1(consumer_key, consumer_secret, access_token_key,
                            access_token_secret)
        self._session = requests.Session()
Esempio n. 30
0
def prepare(*fields, elemwise=True, **kwargs):
    """
    Prepares a set of fields for a calculation and 
    creates the field where to store the output.

    Returns:
    --------
    raw_fields, out_field
    where raw_fields is a tuple of the raw fields (e.g. field.field)
    to be used in the calculation and out_field is a Field type where
    to store the result (e.g. out_field.field = add(*raw_fields))

    Parameters
    ----------
    fields: Field(s)
       List of fields involved in the calculation.
    elemwise: bool
       Wether the calculation is performed element-wise,
       i.e. all the fields must have the common axes in the same order
       and the other axes with shape 1.
    kwargs: dict
       List of parameters to use for the creation of the new field
    """
    from .field import Field
    from builtins import all
    assert all([isinstance(field, Field) for field in fields])
    
    kwargs["zeros_init"] = True
    raw_fields = tuple(field.field for field in fields)
    
    if len(fields)==1:
        return raw_fields, Field(fields[0], **kwargs)
    
    # TODO
    # - should compute the final dtype if not given
    # - should reshape the fields in case of element-wise operation
    # - should take into account coords
    return raw_fields, Field(fields[0], **kwargs)
 def check(self, value):
     return builtins.all([hasattr(value, attr) for attr in self._attrs])
Esempio n. 32
0
def all(*args):
    return builtins.all(args)
Esempio n. 33
0
def cmp_all(val, *tests):
    return builtins.all([val == test for test in tests])
Esempio n. 34
0
def all(function_or_iterable, *args):
	if len(args) == 0:
		return builtins.all(function_or_iterable)
	else:
		return builtins.all(map(function_or_iterable, args[0]))
Esempio n. 35
0
File: pipe.py Progetto: safwank/Pipe
def all(iterable, pred):
    "Returns True if ALL elements in the given iterable are true for the given pred function"
    return builtins.all(pred(x) for x in iterable)