def stream_write(): cmd_title('Thread starting in WRITE mode', newlines=False) global n_val while n_val < MAX_ITERATIONS: time.sleep(ADD_INTERVAL) data_stream.add(n_val) n_val += 1
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 stream_read(): cmd_title('Thread starting in READ mode', newlines=False) # Force an initial warm up so it doesn't terminate early. time.sleep(0.2) # Here (in the while loop), we use a different termination strategy # so we can simulate draining the stream until all items are clear. while data_stream.not_empty(): time.sleep(READ_INTERVAL) data_stream.read()
def __init__(self, program=None): """Setup initial conditions Function argument reference [From Wikipedia] ------------------------------------------------------------------ Register #2 contains "2", (initially) Registers #0, #1 and #3 are empty (contain "0"). Register #0 remains unchanged throughout calculations because it is used for the unconditional jump. Register #1 is a scratch pad. 4 registers, plus 'scratch pad register'" `z` = [z]ero aka, jump register (0) `s` = [s]cratch register (1) `c` = [c]urrent register (2) `d` = [d]estination register (3) Example instruction set used for the initial program. ------------------------------------------------------------------ 1 2 3 4 5 6 7 8 9 10 <- Instruction (address) JZ DEC INC INC JZ JZ DEC INC JZ H <- Instruction 2 2 3 1 0 1 1 2 0 <- Register 6 1 10 6 <- Jump-to instruction """ self.DEBUG = True # Time delay, only used for effect in demonstration. self.DELAY = 0 if self.DEBUG: cmd_title('Prepping') if program is None: self.program = { 1: {'code': 'JZ', 'fn': self.jz, 'reg': 2, 'jump': 6}, 2: {'code': 'DEC', 'fn': self.dec, 'reg': 2, 'jump': None}, 3: {'code': 'INC', 'fn': self.inc, 'reg': 3, 'jump': None}, 4: {'code': 'INC', 'fn': self.inc, 'reg': 1, 'jump': None}, 5: {'code': 'JZ', 'fn': self.jz, 'reg': 0, 'jump': 1}, 6: {'code': 'JZ', 'fn': self.jz, 'reg': 1, 'jump': 10}, 7: {'code': 'DEC', 'fn': self.dec, 'reg': 1, 'jump': None}, 8: {'code': 'INC', 'fn': self.inc, 'reg': 2, 'jump': 0}, 9: {'code': 'JZ', 'fn': self.jz, 'reg': 0, 'jump': 6}, 10: {'code': 'H', 'fn': self.halt, 'reg': None, 'jump': None}, } else: self.program = program self.halted = False # Internal tracking of how many steps have been run - has no bearing # on the actual control flow or outcome of the program. self._step = 0 self.default_register_count = 2 self.curr_register = self.default_register_count # The program begins with instruction 1 # (aka index 1 -- if the index is off, the program # will not run correctly, and may raise KeyErrors). self.curr_instruction = 1 self.registers = {'z': 0, 's': 0, 'c': 2, 'd': 0, '': 0}
def read(self): try: end = self.items.pop() except IndexError: cmd_title('All items have been read.') return None if DEBUG: print('Reading new item from stream... {}\n'.format(end)) print('[CURRENT STREAM] {}\n'.format(' -- '.join(self.items))) self.total_read += 1 return end
def halt(self): """Whether or not this machine actually does halt, this method must be called to prevent stack overflow (for infinite examples).""" cmd_title('HALTING') self.running = False # Reset any state self.tape = None self.transitions = None self.current_state = None self.tape_index = None self.result = ''
def halt(self): if self.DEBUG: cmd_title('Halting') self.halted = True # From Wikipedia: # The program HALTs with the contents of register #2 # at its original count and the contents of register #3 # equal to the original contents of register #2... cnt = self.registers['c'] # Update register three self.registers['d'] = cnt # Reset register 2 after transferring contents to register #3 self.registers['c'] = self.default_register_count if self.DEBUG: print('Final contents of all registers: {}'.format(self.registers))
def print_nodes(node): def _fmt(node): return '[<{}.{}>] {divider} '.format( node.title, node.cargo, divider='....' if node.next is not None else '') \ if node is not None else '' path, count = '', 0 cmd_title('Printing Nodes') # Follows a node along it's next target, until next is None. while node is not None: path += _fmt(node) count += 1 node = node.next prnt('Linked List\n', path, newlines=False)
def _run(self): cmd_title('STARTING VISUALIZATION') while self.running: for _ in range(self.max_states): # Sleep so that each step is delayed, for effect. time.sleep(self.DELAY) if self.DEBUG: print('Old state {}'.format(self.current_state)) self.transition() if self.DEBUG: print('New state {}'.format(self.current_state)) self._show_program() self._get_tape_visualization() if self.DEBUG: print('Ending with state: {}'.format(self.current_state)) # Eventually time out, since it can't *really* run forever. self.halt()
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!'}) assert tree.get_root().get('val') == 'i am still the root!' cmd_title('Testing: has_sibling', newlines=False) assert not tree.has_sibling(7, sibling_name=9) assert tree.has_sibling(8, sibling_name=9)
def _show_program(self): cmd_title('PROGRAM') print_simple('States list', self.states) print_simple('Transitions', self.transitions) print_simple('Tape', self.tape)
of only being able to use the preset register, for copy/updates.""" self.registers[reg] = val if __name__ == '__main__': with Section('Counter Machines'): classes = [ SheperdsonSturgis, Minsky, Program, Abacus, Lambek, Successor, SuccessorRAM, ElgotRobinsonRASP, ] for klass in classes: prnt('Testing machine...', repr(klass)) klass().run() cmd_title('New program') singleton = CounterMachine() singleton._generate_program() ppr(singleton.program) try: singleton.run() except TypeError: print('Inoperable program was generated :(') except NotImplementedError: print_error('Not implemented: {}'.format(klass)) finally: singleton.halt() print_h2('Random Access Machine (multi-register counter machine)') ram = RandomAccessMachine() ram.run()
def activate(self): cmd_title('ACTIVATING') self.running = True
def halt(self): if self.DEBUG: cmd_title('Halting') self.halted = True
class JonesIOne(PointerMachine): pass class JonesITwo(PointerMachine): pass if __name__ == '__main__': with Section('Pointer Machines'): classes = [ KolmogorovUspenskii, KnuthLinking, SchonhageStorageModification, AtomisticPureLISP, AtomisticFullLISP, GeneralAtomistic, JonesIOne, JonesITwo, ] for _class in classes: # Decouple abstract class / stubbing from demo by suppression. try: cmd_title('Testing machine... {}'.format(repr(_class))) _class().run() except NotImplementedError: continue
class GeneralAtomistic(PointerMachine): pass class JonesIOne(PointerMachine): pass class JonesITwo(PointerMachine): pass if __name__ == '__main__': with Section('Pointer Machines'): classes = [ KolmogorovUspenskii, KnuthLinking, SchonhageStorageModification, AtomisticPureLISP, AtomisticFullLISP, GeneralAtomistic, JonesIOne, JonesITwo, ] for _class in classes: # Decouple abstract class / stubbing from demo by suppression. try: cmd_title('Testing machine... {}'.format(repr(_class))) _class().run() except NotImplementedError: continue
'edges': [], 'parent': 1 }, 4: { 'edges': [], 'parent': 2 }, 5: { 'edges': [], 'parent': 2 }, } btree = BinaryTree(data) print(btree) print_h4('Binary trees', desc=('They can have no more than two nodes, ' 'so adding new edges that do not conform' ' should throw an error.')) try: btree[6] = {'edges': [7, 8, 9], 'parent': 3} except InvalidChildNodeCount: cmd_title('Error called successfully', newlines=False) bst = NaiveBinarySearchTree(data) print(bst) bst.add_child(5, 6) bst.add_siblings(5, [10, 11]) print(bst)
data = { 0: {"edges": [1, 2], "is_root": True}, 1: {"edges": [3], "parent": 0}, 2: {"edges": [4, 5], "parent": 0}, 3: {"edges": [], "parent": 1}, 4: {"edges": [], "parent": 2}, 5: {"edges": [], "parent": 2}, } btree = BinaryTree(data) print(btree) print_h4( "Binary trees", desc=( "They can have no more than two nodes, " "so adding new edges that do not conform" " should throw an error." ), ) try: btree[6] = {"edges": [7, 8, 9], "parent": 3} except InvalidChildNodeCount: cmd_title("Error called successfully", newlines=False) bst = NaiveBinarySearchTree(data) print(bst) bst.add_child(5, 6) bst.add_siblings(5, [10, 11]) print(bst)
from MOAL.helpers.display import cmd_title from parsimonious.grammar import Grammar DEBUG = True if __name__ == '__main__' else False if DEBUG: with Section('Embedded Domain Specific Language (EDSL)'): print_h2('Parsing a grammar using the "parsimonious" library') button_grammar = Grammar(r""" btn = btn1 / btn2 btn2 = "[" text "]" btn1 = "((" text "))" text = ~"[A-Z 0-9]*"i """) cmd_title('Printing [mybutton] and ((mybutton)) &', newlines=False) print(button_grammar.parse('[ mybutton ]')) print(button_grammar.parse('(( mybutton ))')) # Order matters - e.g. `tag` must come first, as it builds from the # previous tokens. This is obviously extremely naive, as it doesn't # check valid HTML-matching elements, nesting, single + wrapped # combos, attributes, etc.... html = Grammar(r""" html = wrapped_tag+ / single_tag+ wrapped_tag = opening content closing_wrapped single_tag = left content closing left = "<" right = ">" closer = "/" opening = left content right