Example #1
0
 def run_all(self):
     for node, data in self.states.iteritems():
         divider(newline=False)
         if data['transitions'] is None:
             continue
         for transition in data['transitions']:
             self.run(node=node, edge=transition)
    def evaluate(self, value, fromkey=None):
        """Evaluate a value against the tree.

        Evaluations start from the top if no fromkey is specified.
        A sum is returned for the total of all resulting path evaluations."""
        total = 0

        def _eval(node):
            print('func', node['func'](value))
            res = node['func'](value)
            # Update based on evaluation function results.
            path = 0 if res else 1
            total = node['next'][path]
            print('took path: {} with val {}'.format(path, value))
            return total

        for k, v in self.vertices.items():
            divider()
            cmd_title('NODE: {}'.format(k))
            node = self.vertices[k]['fork']
            if fromkey is not None:
                if k == fromkey:
                    total += _eval(node)
                    print('new total: ', total)
                else:
                    continue
            else:
                total += _eval(node)
                print('new total: ', total)
        print('FINAL value ', total)
    def evaluate(self, value, fromkey=None):
        """Evaluate a value against the tree.

        Evaluations start from the top if no fromkey is specified.
        A sum is returned for the total of all resulting path evaluations."""
        total = 0

        def _eval(node):
            print('func', node['func'](value))
            res = node['func'](value)
            # Update based on evaluation function results.
            path = 0 if res else 1
            total = node['next'][path]
            print('took path: {} with val {}'.format(path, value))
            return total

        for k, v in self.vertices.items():
            divider()
            cmd_title('NODE: {}'.format(k))
            node = self.vertices[k]['fork']
            if fromkey is not None:
                if k == fromkey:
                    total += _eval(node)
                    print('new total: ', total)
                else:
                    continue
            else:
                total += _eval(node)
                print('new total: ', total)
        print('FINAL value ', total)
Example #4
0
def check_model(model, **ruleset):
    """Evaluate the model and prints results."""
    res = evaluate_model(model, **ruleset)
    if res:
        map(ppr, res)
    else:
        print('No results -- model is error free!')
    divider('.')
Example #5
0
File: fsm.py Project: terry07/MoAL
 def __str__(self):
     for node, data in self.states.iteritems():
         print('State {}'.format(node))
         if type(data) != dict:
             divider(newline=False)
             continue
         for state, transition in data['transitions'].iteritems():
             print('   {} --> ({})'.format(state, transition))
         divider(newline=False)
     return ''
Example #6
0
    def decide(self, start, end):

        def _conv(val):
            return 1 if val else 0

        v = self._dfs(start, end)
        if 'decision' in v:
            if DEBUG:
                path = self.walk(start, end)
                rows = [self[vert]['val'] for vert
                        in path if self[vert]['val']] + ['result']
                vals = [_conv(self[vert]['bool']) for vert
                        in path if self[vert]['val']]
                vals = vals + [v['decision']]
                print(' | '.join(map(str, rows)))
                print('-' * 80)
                print('  | '.join(map(str, vals)))
                divider('#', newline=False)
            return v['decision']
        else:
            raise ValueError('Invalid decision node.')
Example #7
0
    def decide(self, start, end):
        def _conv(val):
            return 1 if val else 0

        v = self._dfs(start, end)
        if 'decision' in v:
            if DEBUG:
                path = self.walk(start, end)
                rows = [
                    self[vert]['val'] for vert in path if self[vert]['val']
                ] + ['result']
                vals = [
                    _conv(self[vert]['bool']) for vert in path
                    if self[vert]['val']
                ]
                vals = vals + [v['decision']]
                print(' | '.join(map(str, rows)))
                print('-' * 80)
                print('  | '.join(map(str, vals)))
                divider('#', newline=False)
            return v['decision']
        else:
            raise ValueError('Invalid decision node.')
Example #8
0
try:
    test_db = couch.create('test_db')
except couchdb.http.PreconditionFailed:
    couch.delete('test_db')
    test_db = couch.create('test_db')


def make_person():
    return {
        'name': faker.name(),
        'email': faker.email(),
        'address': faker.address(),
        'url': faker.url(),
        'created': str(dt.now())
    }


@test_speed
def insert_all(max_records):
    for n in range(max_records):
        test_db.save(make_person())


if DEBUG:
    with Section('CouchDB (via python-couchdb)'):
        run_trials(insert_all, trials=10)
        print_h2('Result from CouchDB execution: ')
        for res in test_db:
            divider()
            ppr(test_db[res])
Example #9
0
def _show_bcd(num, decimals, binary, bcd):
    print('Value = {}\nD {}\nB {}\nC {}'.format(num, decimals, binary, bcd))
    divider(atom='<')
Example #10
0
File: tree.py Project: terry07/MoAL
            4: {'edges': [], 'parent': 1},
            5: {'edges': [8, 9], 'parent': 2},
            6: {'edges': [10], 'parent': 3},
            7: {'edges': [], 'val': 'lucky number 7', 'parent': 3},
            8: {'edges': [], 'parent': 5},
            9: {'edges': [], 'parent': 5},
            10: {'edges': [11, 12], 'parent': 6},
            11: {'edges': [], 'parent': 10},
            12: {'edges': [], 'parent': 10},
        }

        tree = Tree(graph)
        tree[9] = {'edges': [], 'parent': 5}
        prnt('Tree, subclassed from graph', tree)
        tree.render_tree('tree-example.png')
        divider(newline=False)

        for n in range(len(graph)):
            print('Testing get: {} ... {}'.format(n, graph[n]))

        cmd_title('Testing: children_count', newlines=False)
        assert tree.children_count(1) == 2
        assert tree.children_count(2) == 1
        assert tree.children_count(3) == 2
        assert tree.children_count(9) == 0

        # Correctness testing

        cmd_title('Testing: get_root', newlines=False)
        assert tree.get_root().get('val') == 'i am the root!'
        tree[0].update({'val': 'i am still the root!'})
Example #11
0
        #   - more input
        #   - pay
        #   - archive
        #   - closed
        data = {
            'Submit Claim': (submit_claim, []),
            'Evaluate': (evaluate_claim, ['Submit Claim', 'More Input']),
            'More Input': (evaluate_claim, ['Evaluate']),
            'Closed': (close_claim, ['Rejected?', 'Archive']),
            'Archive': (pay_claim, ['Pay']),
            'Pay': (pay_claim, ['Accepted?']),
            'Accepted?': (accept_claim, ['Evaluate']),
            'Rejected?': (reject_claim, ['Evaluate'])
        }
        submit_claim = ProcessVirtualMachine(data)
        print(submit_claim)
        submit_claim.render_graph('pvmachine-viz.png', directed=True)

        workflow_1 = [
            'Submit Claim', 'More Input', 'Accepted?',
            'Pay', 'Archive', 'Closed']
        workflow_2 = [
            'Submit Claim', 'Evaluate', 'Accepted?', 'Pay', 'Archive', 'Closed']
        workflow_3 = ['Submit Claim', 'Evaluate', 'Rejected?', 'Closed']

        for workflow in [workflow_1, workflow_2, workflow_3]:
            divider('~+', newline=False)
            print('=== New workflow...')
            for task in workflow:
                submit_claim.proceed(task)
Example #12
0
    return ''.join(binary)


def twos_complement(binary):
    """Conversion algorithm from
    cs.cornell.edu/~tomf/notes/cps104/twoscomp.html#twotwo"""
    old = binary
    binary = ones_complement(binary)
    ones = binary
    binary = BaseDataType.increment(''.join(binary))
    if DEBUG:
        print('Complements: one: {}, two: {}, (original: {})'.format(
            ''.join(ones), binary, ''.join(old)))
    dec = bin_to_dec(binary)
    sign, res = ('neg', -dec) if list(binary)[0] == '1' else (
        'pos',
        dec,
    )
    res_bin = dec_to_bin(res)
    if DEBUG:
        print('Final decimal is {}: {} ({})'.format(sign, res, res_bin))
    return res_bin


if __name__ == '__main__':
    with Section('Computer organization - one, two\'s complement'):
        evens = [n for n in range(2, 16) if n % 4 == 0]
        for _ in range(8):
            twos_complement(random_binary(choice(evens)))
            divider(atom='-')
Example #13
0
File: bcd.py Project: Androbos/MoAL
def _show_bcd(num, decimals, binary, bcd):
    print('Value = {}\nD {}\nB {}\nC {}'.format(num, decimals, binary, bcd))
    divider(atom='<')
Example #14
0
File: map.py Project: Androbos/MoAL
 def enroll_all(self, schedules):
     for student, classes in schedules.iteritems():
         for klass in classes:
             self.enroll(student, klass)
     if DEBUG:
         divider(atom='.')
Example #15
0
 def call(self):
     prnt('Calling opcode: "{}"'.format(self.code), '')
     for line in self.assembly:
         print_success(line, prefix='[ASSEMBLY]')
     divider()
Example #16
0
    for n in nums:
        f += n ** n
    return f


if DEBUG:
    with Section('Type checking via python decorators!'):
        # Correct types
        concat('cat', 'dog')
        add2(1, 2)
        combine_dict({'dog': 1, 'cat': 1}, {'cat': 0})
        combine_lists([1, 2, 3], [2, 3], [40, 30, 20, 10])
        sum_square(*range(1, 100))

        print('Type checking worked!')
        divider()
        # Incorrect types
        try:
            concat('cat', 0)
        except AssertionError:
            print('Type checking worked with failure!')

        try:
            add2(1, None)
        except AssertionError:
            print('Type checking worked with failure!')

        try:
            combine_dict({}, None)
        except AssertionError:
            print('Type checking worked with failure!')
Example #17
0
    binary = list(binary)
    for k, digit in enumerate(binary):
        binary[k] = '1' if digit == '0' else '0'
    return ''.join(binary)


def twos_complement(binary):
    """Conversion algorithm from
    cs.cornell.edu/~tomf/notes/cps104/twoscomp.html#twotwo"""
    old = binary
    binary = ones_complement(binary)
    ones = binary
    binary = BaseDataType.increment(''.join(binary))
    if DEBUG:
        print('Complements: one: {}, two: {}, (original: {})'.format(
            ''.join(ones), binary, ''.join(old)))
    dec = bin_to_dec(binary)
    sign, res = ('neg', -dec) if list(binary)[0] == '1' else ('pos', dec,)
    res_bin = dec_to_bin(res)
    if DEBUG:
        print('Final decimal is {}: {} ({})'.format(sign, res, res_bin))
    return res_bin


if __name__ == '__main__':
    with Section('Computer organization - one, two\'s complement'):
        evens = [n for n in range(2, 16) if n % 4 == 0]
        for _ in range(8):
            twos_complement(random_binary(choice(evens)))
            divider(atom='-')
Example #18
0
        #   - archive
        #   - closed
        data = {
            'Submit Claim': (submit_claim, []),
            'Evaluate': (evaluate_claim, ['Submit Claim', 'More Input']),
            'More Input': (evaluate_claim, ['Evaluate']),
            'Closed': (close_claim, ['Rejected?', 'Archive']),
            'Archive': (pay_claim, ['Pay']),
            'Pay': (pay_claim, ['Accepted?']),
            'Accepted?': (accept_claim, ['Evaluate']),
            'Rejected?': (reject_claim, ['Evaluate'])
        }
        submit_claim = ProcessVirtualMachine(data)
        print(submit_claim)
        submit_claim.render_graph('pvmachine-viz.png', directed=True)

        workflow_1 = [
            'Submit Claim', 'More Input', 'Accepted?', 'Pay', 'Archive',
            'Closed'
        ]
        workflow_2 = [
            'Submit Claim', 'Evaluate', 'Accepted?', 'Pay', 'Archive', 'Closed'
        ]
        workflow_3 = ['Submit Claim', 'Evaluate', 'Rejected?', 'Closed']

        for workflow in [workflow_1, workflow_2, workflow_3]:
            divider('~+', newline=False)
            print('=== New workflow...')
            for task in workflow:
                submit_claim.proceed(task)
        self.db["name"] = name
        if self.db["name"] == "mongo":
            self.db["adapter"] = MongoAdapter()
        elif self.db["name"] == "postgres":
            self.db["adapter"] = PostgresSQLAdapter()

    def get(self, pk):
        if self.db["name"] == "mongo":
            collections = self.db["adapter"].collections()
            return collections["get"](pk)
        elif self.db["name"] == "postgres":
            sql = """SELECT * FROM documents doc
                  WHERE doc.id == {} LIMIT;""".format(
                pk
            )
            self.db["adapter"].conn().cursor().execute(sql).commit()


class Document(ConnectionMixin):
    pass


if DEBUG:
    with Section("GRASP protected variation pattern"):
        doc = Document()
        doc.set_adapter("mongo")
        doc.get(991)
        divider(newline=False)
        doc.set_adapter("postgres")
        doc.get(991)
Example #20
0
 def enroll_all(self, schedules):
     for student, classes in schedules.iteritems():
         for klass in classes:
             self.enroll(student, klass)
     if DEBUG:
         divider(atom='.')