Пример #1
0
 def run(self, node, max=10):
     val = ''
     count, node = 0, self[node]
     print_info('[RUN]: node: {}'.format(node), prefix='[Running]')
     absorbing_states = False
     while count < max and not absorbing_states:
         # Once the node transitions from a probability edge,
         # the optional generator function allows any arbitrary data to be
         # generated. It can be deterministic or not
         # -- whatever the user wants to do.
         if 'generator' in node:
             val += '{}'.format(node['generator']())
         highest = 0
         # Update the active node based on which probability of the outgoing
         # edges for this node is the highest, then transition to that node.
         for edge, probability in node['edges'].iteritems():
             if probability == 1:
                 absorbing_states = True
                 break
             if probability > highest:
                 highest = probability
                 node = self[edge]
             self._step()
         print('{}Current node: {}, highest probability: {}'.format(
             count * ' ', edge, highest))
         count += 1
     print('Final value: {}'.format(val))
     return val
Пример #2
0
 def run(self, node, max=10):
     val = ''
     count, node = 0, self[node]
     print_info('[RUN]: node: {}'.format(node), prefix='[Running]')
     absorbing_states = False
     while count < max and not absorbing_states:
         # Once the node transitions from a probability edge,
         # the optional generator function allows any arbitrary data to be
         # generated. It can be deterministic or not
         # -- whatever the user wants to do.
         if 'generator' in node:
             val += '{}'.format(node['generator']())
         highest = 0
         # Update the active node based on which probability of the outgoing
         # edges for this node is the highest, then transition to that node.
         for edge, probability in node['edges'].iteritems():
             if probability == 1:
                 absorbing_states = True
                 break
             if probability > highest:
                 highest = probability
                 node = self[edge]
             self._step()
         print('{}Current node: {}, highest probability: {}'.format(
             count * ' ', edge, highest))
         count += 1
     print('Final value: {}'.format(val))
     return val
Пример #3
0
def cleanup(cur, conn):
    print_info('Cleaning up...')
    # Always clean up DB for this demo.
    try:
        cur.execute("""DROP TABLE cache_table;""")
    except psycopg2.ProgrammingError:
        conn.commit()
    # Clean up cache as well.
    mclient.delete(CACHE_KEY)
Пример #4
0
def cleanup(cur, conn):
    print_info('Cleaning up...')
    # Always clean up DB for this demo.
    try:
        cur.execute("""DROP TABLE cache_table;""")
    except psycopg2.ProgrammingError:
        conn.commit()
    # Clean up cache as well.
    mclient.delete(CACHE_KEY)
Пример #5
0
 def test(self, string):
     try:
         print_info('{}'.format(string), prefix='[TESTING]')
         chars = list(str(string))
         for char in chars:
             self.step += 1
             self.transition(char)
         self.reset()
         print_success(''.join(chars), prefix='[FOUND]')
         return True
     except InvalidTransition:
         print_error(''.join(chars), prefix='[NOT-FOUND]')
         return False
Пример #6
0
def on_open(ch, method, properties, body):
    key = method.routing_key
    message = '* Received! {}'.format(body)
    if key == 'info':
        print_info(message)
    if key == 'warning':
        print_warning(message)
    if key == 'error':
        print_error(message)
    if key == 'success':
        print_success(message)

    if not start.USE_EXCHANGE:
        # Specify ACK to prevent failures from disappearing.
        ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #7
0
def on_open(ch, method, properties, body):
    key = method.routing_key
    message = '* Received! {}'.format(body)
    if key == 'info':
        print_info(message)
    if key == 'warning':
        print_warning(message)
    if key == 'error':
        print_error(message)
    if key == 'success':
        print_success(message)

    if not start.USE_EXCHANGE:
        # Specify ACK to prevent failures from disappearing.
        ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #8
0
 def _divvy_ram(self, ram):
     """This is an arbitrary, somewhat meaningless method, to simulate
     the notion of free blocks of ram that must be allocated and
     referenced via pointer. A given program may require X ram, but
     the location of available ram may be disparate, so various blocks have
     to be stored as a free linked list, or similar data structure.
     Since we've already covered linked lists, association lists, etc...,
     there isn't much value outside learning the context of this data
     structure, which tends to be in memory management."""
     subdivisions = rr(2, 20)  # Arbitrary number
     flist = []
     while subdivisions > 0:
         diff = rr(0, ram)
         # Store ram as [current block of memory, location]
         flist.append([diff, str(self.last_block).zfill(4)])
         ram = ram - diff
         self.last_block += 1
         subdivisions -= 1
         if DEBUG:
             print_info('Ram: {} / diff: {}'.format(ram, diff))
     return flist
Пример #9
0
 def _divvy_ram(self, ram):
     """This is an arbitrary, somewhat meaningless method, to simulate
     the notion of free blocks of ram that must be allocated and
     referenced via pointer. A given program may require X ram, but
     the location of available ram may be disparate, so various blocks have
     to be stored as a free linked list, or similar data structure.
     Since we've already covered linked lists, association lists, etc...,
     there isn't much value outside learning the context of this data
     structure, which tends to be in memory management."""
     subdivisions = rr(2, 20)  # Arbitrary number
     flist = []
     while subdivisions > 0:
         diff = rr(0, ram)
         # Store ram as [current block of memory, location]
         flist.append([diff, str(self.last_block).zfill(4)])
         ram = ram - diff
         self.last_block += 1
         subdivisions -= 1
         if DEBUG:
             print_info('Ram: {} / diff: {}'.format(ram, diff))
     return flist
Пример #10
0
       [+]
       / \
     [2] [2]

    etc... `foo = 3 * 9`

        (ROOT)
         /  \
       [=]  [*]
       /    /  \
     [foo] [3] [9]

    """

if DEBUG:
    with Section('Abstract Syntax Tree (AST)'):
        print_h2('Reading functions and then building ast and executing.')
        src1 = inspect.getsource(foo)
        src2 = inspect.getsource(bar)
        tree = ast.parse(src1 + '\nfoo()\n' + src2 + '\nbar()')
        print_info(tree)
        exec(compile(tree, filename='<ast>', mode='exec'))

        drawing = ast.parse(inspect.getsource(ast_drawing), filename='<ast>')
        print_info('Printing AST docstring, a drawing of an AST (such meta)')
        for node in ast.walk(drawing):
            try:
                print(ast.get_docstring(node))
            except TypeError:
                continue
Пример #11
0
        map(classes_map.enroll_all, classes_map.schedules())
        print_h3('All fields')

        print(classes_map)

        print_h3('\nClasses for Ella Tabor')
        print('Classes: {}'.format(classes_map.get_classes('Ms. Ella Tabor')))

        del classes_map['Ms. Ella Tabor']

        # Too young to be taking classes right now anyway.
        assert classes_map['Ms. Ella Tabor'] is None

        print(classes_map)

        assert 'Ms. Ella Tabor' not in classes_map

        print_h3('Bi-directional', desc='A map ADT that maps to key OR value.')

        bdmap = BidirectionalMap(
            {1: 'Foo', 2: 'Bar', 'Foo': 'Bar', 'Bar': 'Foo'})
        print(bdmap)
        try:
            bdmap['Bar'] = 'Foo'
            bdmap['Foo'] = 'Bar'
        except ValueError:
            print_info('Test raising error for duplicate values Foo and Bar')
        print(bdmap)
        assert 'Bar' in bdmap
        assert 'Foo' in bdmap
Пример #12
0
        print_h3('\nClasses for Ella Tabor')
        print('Classes: {}'.format(classes_map.get_classes('Ms. Ella Tabor')))

        del classes_map['Ms. Ella Tabor']

        # Too young to be taking classes right now anyway.
        assert classes_map['Ms. Ella Tabor'] is None

        print(classes_map)

        assert 'Ms. Ella Tabor' not in classes_map

        print_h3('Bi-directional', desc='A map ADT that maps to key OR value.')

        bdmap = BidirectionalMap({
            1: 'Foo',
            2: 'Bar',
            'Foo': 'Bar',
            'Bar': 'Foo'
        })
        print(bdmap)
        try:
            bdmap['Bar'] = 'Foo'
            bdmap['Foo'] = 'Bar'
        except ValueError:
            print_info('Test raising error for duplicate values Foo and Bar')
        print(bdmap)
        assert 'Bar' in bdmap
        assert 'Foo' in bdmap