return self.fields.decode(key) def __delitem__(self, key): self.fields.remove(key) def __setitem__(self, key, bitvalue): code = {str(value): bitarray(True) for value in list(key)} self.fields.encode(code, key) def __str__(self): print("Bit field") for field in self.fields: print("Field: {}".format(field)) return "" class FlagField(BitField): """Using bit field as a set of flags, e.g. options, boolean values, etc""" pass if __name__ == "__main__": with Section("Computer organization - Bit field/flag field"): print_h3("A bit field/flag field class representation", desc="Using bitarray C/Python library") user_flags = FlagField() user_flags["foo"] = 1 user_flags["bar"] = 1 print(user_flags)
class HypgerGraph(Graph): """ From mathworld.wolfram.com/Hypergraph.html: "A hypergraph is a graph in which generalized edges (called hyperedges) may connect more than two nodes." Also interesting, from en.wikipedia.org/wiki/Hypergraph "The collection of hypergraphs is a category with hypergraph homomorphisms as morphisms." """ if DEBUG: with Section('Multi-graph'): hypergraph = HypgerGraph(dmkr.random_graph(max_edges=10)) print_h3('Random multi-graph') print(hypergraph) # Multiple edges pointing to each other hypergraph2 = HypgerGraph({ 0: { 'edges': [1, 2, 3], 'val': 'A' }, 1: { 'edges': [0, 3, 2, 1], 'val': 'B' }, 2: { 'edges': [0, 1, 3, 2], 'val': 'C' },
def __getitem__(self, piece): return self.boards[piece] def move(self, piece, player, old_position, new_position): print('Moving {} piece `{}` from {} to {}'.format( player, piece, old_position, new_position)) # Set old position to inactive in bitarray self.boards[piece][old_position] = False # Set new position to active in bitarray self.boards[piece][new_position] = True if DEBUG: with Section('BitBoards'): print_h3('Chess bit board') chess_board = ChessBoard() # A rather... fast game. from: chess.about.com # /od/tipsforbeginners/ss/Foolsmate.htm#step-heading moves = ( ('pawn_6', 'white', 'f2', 'f3'), ('pawn_5', 'black', 'e6', 'e5'), ('pawn_7', 'white', 'g2', 'g4'), ('queen', 'black', 'd8', 'h4'), # checkmate! ) for info in moves: piece, player, old, new = info chess_board.move(piece, player, old, new) print(chess_board['king']) print(chess_board)
for vertex, data in vertices.iteritems(): if vertex in data["edges"]: raise ValueError('Loop "{}" is not allowed on vertices.'.format(vertex)) return super(LooplessMultiGraph, self).__init__(vertices=vertices) def __setitem__(self, *args): key, vertices = args if key in vertices["edges"]: raise ValueError("Loop {} is not allowed on vertices.".format(key)) return super(LooplessMultiGraph, self).__setitem__(*args) if DEBUG: with Section("Multi-graph"): mgraph_rand = MultiGraph(dmkr.random_graph(max_edges=5)) print_h3("Random multi-graph") print(mgraph_rand) # Multiple edges pointing to each other mgraph = MultiGraph( { 0: {"edges": [1, 2, 3], "val": "A"}, 1: {"edges": [0, 3, 2, 1], "val": "B"}, 2: {"edges": [0, 1, 3, 2], "val": "C"}, 3: {"edges": [0, 1, 2, 3], "val": "D"}, } ) print_h3("Specific multi-graph") print(mgraph) mgraph.render_graph("mgraph.png", strict=False)
for _ in range(steps): sleep(0.05) instance.value = func(instance.value) bin_inc = BaseDataType.increment bin_dec = BaseDataType.decrement if __name__ == '__main__': with Section('Computer organization - Data types'): print_h4('Bit', desc='The simplest unit of information.') bit = Bit('0') assert bit.get_max_binvals() == 2 print_h3('Nibble', desc='4 bits = 1/2 byte.') nibble = Nibble('0000') print(nibble) assert nibble.get_max_binvals() == 24 print_h3('Byte', desc='8 bits = one byte.') byte = Byte('00000000') print(byte) assert byte.get_max_binvals() == 40320 orig = byte.value # Flip bits then reverse and check the value to test things # are working correctly. update_animation(32, byte.increment, byte) update_animation(32, byte.decrement, byte) assert byte.value == orig
for n in range(4): key = 'map_item-{}'.format(n) multimap[key] = ''.join(randchars(4)) print(multimap) print(multimap['map_item-1']) print_h2('Multimap', desc='Used contextually for school enrollment.') classes_map = Enrollment( classes=['English', 'Comp Sci', 'History', 'Math', 'Art'], students=[faker.name() for _ in range(3)] + ['Ms. Ella Tabor']) 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
class HypgerGraph(Graph): """ From mathworld.wolfram.com/Hypergraph.html: "A hypergraph is a graph in which generalized edges (called hyperedges) may connect more than two nodes." Also interesting, from en.wikipedia.org/wiki/Hypergraph "The collection of hypergraphs is a category with hypergraph homomorphisms as morphisms." """ if DEBUG: with Section('Multi-graph'): hypergraph = HypgerGraph(dmkr.random_graph(max_edges=10)) print_h3('Random multi-graph') print(hypergraph) # Multiple edges pointing to each other hypergraph2 = HypgerGraph({ 0: {'edges': [1, 2, 3], 'val': 'A'}, 1: {'edges': [0, 3, 2, 1], 'val': 'B'}, 2: {'edges': [0, 1, 3, 2], 'val': 'C'}, 3: {'edges': [0, 1, 2, 3], 'val': 'D'}, }) print(hypergraph2) if raw_input('Save graph images? Y/N: ') == 'Y': hypergraph.render_graph('hypergraph-test.png') hypergraph2.render_graph('hypergraph2-test.png')
def store_little_endian(self, bits): return self._store(bits[::-1]) if __name__ == '__main__': with Section('Computer organization - Byte ordering, endianness'): endian = Endian() chars_little = ['Glumdalclitch', 'Munodi', 'Struldbruggs', 'Houyhnhnms'] chars_big = ['Lemuel Gulliver', 'Flimnap', 'Reldresal', 'Skyresh Bolgolam', 'Slamecksan'] for character in chars_little: endian.store_little_endian(character) for character in chars_big: endian.store_big_endian(character) assert 'idonuM' in endian assert 'Glumdalclitch' not in endian assert 'panmilF' not in endian assert 'Skyresh Bolgolam' in endian assert endian.add_bom('Hello world') == '<<BOMHello world' assert endian.read_bom('<<BOMHello world') print_h3('Big endian', desc='memory view with big ordering') print(endian) print_h3('Little endian', desc='memory view with little ordering') print(endian)
if vertex in data['edges']: raise ValueError( 'Loop "{}" is not allowed on vertices.'.format(vertex)) return super(LooplessMultiGraph, self).__init__(vertices=vertices) def __setitem__(self, *args): key, vertices = args if key in vertices['edges']: raise ValueError('Loop {} is not allowed on vertices.'.format(key)) return super(LooplessMultiGraph, self).__setitem__(*args) if DEBUG: with Section('Multi-graph'): mgraph_rand = MultiGraph(dmkr.random_graph(max_edges=5)) print_h3('Random multi-graph') print(mgraph_rand) # Multiple edges pointing to each other mgraph = MultiGraph({ 0: { 'edges': [1, 2, 3], 'val': 'A' }, 1: { 'edges': [0, 3, 2, 1], 'val': 'B' }, 2: { 'edges': [0, 1, 3, 2], 'val': 'C' },
return self.fields.decode(key) def __delitem__(self, key): self.fields.remove(key) def __setitem__(self, key, bitvalue): code = {str(value): bitarray(True) for value in list(key)} self.fields.encode(code, key) def __str__(self): print('Bit field') for field in self.fields: print('Field: {}'.format(field)) return '' class FlagField(BitField): """Using bit field as a set of flags, e.g. options, boolean values, etc""" pass if __name__ == '__main__': with Section('Computer organization - Bit field/flag field'): print_h3('A bit field/flag field class representation', desc='Using bitarray C/Python library') user_flags = FlagField() user_flags['foo'] = 1 user_flags['bar'] = 1 print(user_flags)