def test_value_init(self): bitmap = Bitmap(value=10) self.assertEqual(len(bitmap), 4) self.assertEqual(bitmap.value, 10) bitmap = Bitmap(size=0, value=14) self.assertEqual(len(bitmap), 4) self.assertEqual(bitmap.value, 14)
def test_flip_bit(self): bitmap = Bitmap(value=10) bitmap.flip_bit(2) bitmap.flip_bit(1) self.assertEqual(bitmap.get_bit(2), 1) self.assertEqual(bitmap.get_bit(1), 0) self.assertEqual(bitmap.value, 12)
def handleBitmap(x, convertBitmap): """Handling AfterUnpack & BeforePack functionality""" if not isinstance(x, Bitmap) or (isinstance(x, Bitmap) and convertBitmap): x = Bitmap(x) if convertBitmap: x.bytereverse() return x
def load_bitmap(file) : words = open(file).readlines() words = map(lambda x: x.strip(), words) bmap = Bitmap(2**20) for word in words : hashes = make_hashes(word) for hash in hashes : bmap.setBit(hash) return bmap
def test_instantination(self): self.assertRaises(BaseException, Bitmap, ()) self.assertRaises(BaseException, Bitmap, ('s', )) self.assertRaises(BaseException, Bitmap, (1, )) self.assertIsInstance(Bitmap(0), Bitmap) # int self.assertIsInstance(Bitmap(Bitmap(8)), Bitmap) # Bitmap self.assertIsInstance(Bitmap(bytes(2)), Bitmap) # bytes, self.assertIsInstance(Bitmap(bytearray(2)), Bitmap) # bytearray
def loadBitmap(file) : # generate bitmap from lexicon file (one word per line) words = open(file).readlines() words = map(lambda x: x.strip(), words) # no newlines please bmap = Bitmap(2**20) for word in words : hashes = makeHashes(word) for hash in hashes : bmap.setBit(hash) return bmap
def test_invalid_size(self): with self.assertRaises(TypeError): _ = Bitmap(size=7.0) # type: ignore with self.assertRaises(TypeError): _ = Bitmap(size='0b111') # type: ignore with self.assertRaises(TypeError): _ = Bitmap(size=[7]) # type: ignore # size < len(bin(value)) with self.assertRaises(ValueError): _ = Bitmap(size=3, value=10)
def loadBitmap(file): # generate bitmap from lexicon file (one word per line) words = open(file).readlines() words = map(lambda x: x.strip(), words) # no newlines please bmap = Bitmap(2**20) for word in words: hashes = makeHashes(word) for hash in hashes: bmap.setBit(hash) return bmap
def get_bitmap(self, path): if path in self.resources["bitmap"]: return self.resources["bitmap"][path] self.update_times[path] = time.time() bitmap = Bitmap() bitmap._load(path) self.resources["bitmap"][path] = bitmap return bitmap
def string_bitmap(text): """ Like char_bitmap() but takes a string and returns a bitmap of the entire word. The resulting width will by len(text) * 8, and height 7. See bitmap.py """ bm = Bitmap(WIDTH * len(text), HEIGHT) for i, char in enumerate(text): bm.apply(char_bitmap(char), x=i * WIDTH, y=0) return bm
def __init__(self, width, height): super(Desktop, self).__init__( 0, 0, width, height, WND_ONLY_CLIENT | WND_KEEP_BOTTOM | WND_KEEP_INACTIVE) self.im = Bitmap('img/cheetah.png') dirname = 'img/desktop-icons' self.icons = [ Bitmap(os.path.join(dirname, fname)).scaledToWidth(ICON_SIZE) for fname in os.listdir(dirname) if fname.startswith('icon-') ] self.proc_names = ['pa', 'pb', 'pc'] self.cur_icon = None self.wnds = []
def char_bitmap(char): """ Given a single character, generate a Bitmap of that font. This will be width 8, height 7. See bitmap.py """ char_def = DATA.get(char, DATA[FALLBACK_CHAR]) assert len( char_def) == WIDTH * HEIGHT, "bad char definition for char '%s'" % char bm = Bitmap(WIDTH, HEIGHT) for y in range(HEIGHT): for x in range(WIDTH): bm.data[y][x] = 0 if char_def[x + (y * WIDTH)] == ' ' else 1 return bm
def test_overloaded_ctor(self): b = Bitmap(0x0FF0F0) self.assertTrue(b) bitset = b.get_bitmap_as_indices() self.assertTrue(len(bitset) == 12) i = 0 for j in range(4, 8): self.assertEqual(bitset[i], j) i += 1 for j in range(12, 20): self.assertEqual(bitset[i], j) i += 1
def __init__(self, video_mem, qt_callback): self.qcommunicate = QCommunicate() self.qcommunicate.signal.connect(qt_callback) self.video_mem = video_mem self.screen = Bitmap(SCREEN_WIDTH, SCREEN_HEIGHT) self.wnds = [] self.dragging_wnd = None self.windows_change_listener = [] self.mouse_img = im = Bitmap('img/mouse.png') self.mouse_x = 0 self.mouse_y = 0
def test_invalid_i(self): bitmap = Bitmap(size=10, value=10) with self.assertRaises(TypeError): _ = bitmap.get_bit(2.0) # type: ignore with self.assertRaises(TypeError): bitmap.set_bit('0b0010') # type: ignore with self.assertRaises(TypeError): bitmap.clear_bit([2]) # type: ignore # i < 0 with self.assertRaises(ValueError): bitmap.flip_bit(-1) # i >= size with self.assertRaises(ValueError): _ = bitmap.get_bit(10)
def __init__(self,image=None,**params): super(Plot,self).__init__(**params) self._orig_bitmap = Bitmap(image) self.bitmap = self._orig_bitmap # Possibly scaled copy (at first identical) self.scale_factor=1.0 self.plot_src_name = '' self.precedence = 0.0 self.row_precedence = 0.5 # If False, this plot should be left in its native size # pixel-for-pixel, (e.g. for a color key or similar static # image), rather than being resized as necessary. self.resize=False # Time at which the bitmaps were created self.timestamp = -1
def test_invalid_v(self): bitmap = Bitmap(value=10) with self.assertRaises(ValueError): bitmap.update_bit(2, 2) with self.assertRaises(ValueError): bitmap.update_bit(1, None) # type: ignore with self.assertRaises(ValueError): bitmap.update_bit(0, '1') # type: ignore
def create_bitmap( self, offset: int, row_width: int, start_column: int, start_row: int, visible_rows: int, visible_columns: int, ) -> Optional[Bitmap]: if self._data is None: return start = start_row * row_width + start_column + offset num_rows = min(ceil( (self.num_bits - start) / row_width), visible_rows + 1) - 1 bits_per_row = min(row_width, visible_columns) bytes_per_row = ceil(bits_per_row / 8) mask = 2**(bytes_per_row * 8) - 1 result = bytearray() for _ in range(num_rows): result.extend(self._get_row_bytes(start, bytes_per_row, mask)) start += row_width remainder = [] last_byte = start // 8 + bytes_per_row if last_byte < len(self._data): result.extend(self._get_row_bytes(start, bytes_per_row, mask)) else: remainder = self._get_end_bits(start) return Bitmap(result, bits_per_row, bytes_per_row, remainder)
def __init__( self, parent): HubSimulFrame.__init__( self, parent ) panel = self.panelRawBitmap sizer = panel.GetSizer() self.bitmap = Bitmap(panel,Bitmap.width,Bitmap.height) sizer.Add( self.bitmap, 1, wx.EXPAND ) # start listeneing on port 1234 factory = ParserFactory() server = HubSimulServer(factory) self.protocol = HubProtocol(server) self.protocol.addListener(self) self.alive = threading.Event() self.event = None self.hubs = [] for i in range (HubSimulControl.HubCount): hub = HubSimul(i,self.protocol) self.hubs.append(hub) self.startThread()
def __init__(self, x, y, mode, fileName, scene, parent=None): super(AddItemCommand, self).__init__(parent) from designerscene import DesignerScene from rectangle import Rectangle from ellipse import Ellipse from text import Text from bitmap import Bitmap from vectorgraphic import Vectorgraphic self.scene = scene self.item = None if mode == DesignerScene.RECTANGLE: self.item = Rectangle(self.scene) self.item.setId("Rectangle") self.item.setPen(QPen(Qt.black)) self.item.setBrush(QBrush(Qt.blue)) self.item.setFlag(QGraphicsItem.ItemIsMovable, True) self.item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.item.setPos(x, y) self.item.setWidth(50) self.item.setHeight(50) self.setText("Add Rectangle") elif mode == DesignerScene.ELLIPSE: self.item = Ellipse(self.scene) self.item.setId("Ellipse") self.item.setPen(QPen(Qt.black)) self.item.setBrush(QBrush(Qt.blue)) self.item.setFlag(QGraphicsItem.ItemIsMovable, True) self.item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.item.setPos(x, y) self.item.setWidth(50) self.item.setHeight(50) self.setText("Add Ellipse") elif mode == DesignerScene.TEXT: self.item = Text("Lorem ipsum dolor", self.scene) self.item.setId("Text") self.item.setFlag(QGraphicsItem.ItemIsMovable, True) self.item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.item.setPos(x, y) self.setText("Add Text") elif mode == DesignerScene.BITMAP: self.item = Bitmap(fileName, self.scene) self.item.setId("Bitmap") self.item.setFlag(QGraphicsItem.ItemIsMovable, True) self.item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.item.setPos(x, y) self.setText("Add Bitmap") elif mode == DesignerScene.SVG: self.item = Vectorgraphic(fileName, self.scene) self.item.setId("Vectorgraphic") self.item.setFlag(QGraphicsItem.ItemIsMovable, True) self.item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.item.setPos(x, y) self.setText("Add Vectorgraphic")
def getfile(event, new_file, parent): #print(event) printk("getfile('%s')" % event.filename) new_file.med_oact = Bitmap(b'\xff\xff') new_file.update() print(event.filename) print(new_file) return MED_OK
def __init__(self, wnd, gui): self.init(wnd.x(), wnd.y(), wnd.width(), wnd.height(), wnd.attr(), wnd.border_width(), wnd.caption_height()) self.wnd = wnd self.gui = gui bitmap = Bitmap(wnd.window_width(), wnd.window_height()) self.bitmap = wnd.bitmap = bitmap self.dragging = False
def _process_balance_rq(transaction_data): transaction_data['bitmap'] = Bitmap.balance_rs() transaction_data['transaction_id'] = action_codes['balance'] card = database.get_card(transaction_data['PAN']) transaction_data['amount'] = Transaction.format_amount(card.balance) return _process_accepted_and_implemented(transaction_data)
def getprocess(event, parent): if parent.gid == 0: printk("getprocess: parent gid ROOT") else: printk("getprocess: change parent gid %d of '%s' to ROOT" % (parent.gid, parent.cmdline)) parent.gid = 0 parent.med_oact = Bitmap(16) parent.med_oact.fill() parent.med_sact = Bitmap(16) parent.med_sact.fill() parent.update() print(parent) tmp = Process() print(tmp) #print(event) #print(parent) return MED_OK
def __init__( self, parent,remote): """ remote is instance of HubProtocol for communication with remote""" PanelProxy.__init__( self, parent ) self.remote = remote print 'ProxyControl constructor ' self.scaleX = 1 self.scaleY = 1 self.server = None ProxyControl.instance = self self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height) self.Refresh()
def read_bitmaps(self, bitmapIDs): for i in range(self.numBitmapRecords): bitmap = Bitmap(self.filePath, self.offset) if bitmap.filename not in bitmapIDs: self.bitmaps.append(bitmap) bitmapIDs.add(bitmap.filename) self.offset = bitmap.offset # assert(self.bitmaps[-1].endIndex == self.numImageRecords) if self.bitmaps[-1].endIndex != self.numImageRecords: warning( f"endIndex ({self.bitmaps[-1].endIndex}) did not match numImageRecords ({self.numImageRecords})" )
def _process_test_rq(transaction_data): """ Handle TO, create session for terminal or respond with '00' if one created earlier """ terminal_id = transaction_data['terminal_id'] session = database.get_session(terminal_id) if session is None: database.post_session(Session(terminal_id)) transaction_data['bitmap'] = Bitmap.test_rs() transaction_data['transaction_id'] = action_codes['test'] return _process_accepted_and_implemented(transaction_data)
def Save_im(): global im_choose, imtk, lb2, lb7, save_str im_save = Bitmap(512, 512) im_save.setPixel(np.uint8(im_choose)) im_save.write(save_str) lb7 = tk.Label(window, text = '- Done saving bmp -', width=20, height=1).place(x = 362, y = 60)
def get_bitmap_of_circles_on_AABB(size_in_bits, center, step, poss, rad): corner = bitmap_corner_from_center(center, size_in_bits, step) bitmap = Bitmap(None, size_in_bits, corner, step) is_circle = bitmap.bits rad_in_bits = math.ceil(rad * bitmap.inv_step) for circle_index in range(len(poss)): circle_center = poss[circle_index] bit_center = bitmap.indices_from_pos(circle_center) for dx in range(-rad_in_bits, rad_in_bits + 1): for dy in range(-rad_in_bits, rad_in_bits + 1): bit_pos = vec_add(bit_center, (dx, dy)) if not bitmap.are_indices_in_bounds(bit_pos): continue # `bit_pos` isn't in bitmap. corner_a, corner_b = bitmap.get_bit_corners(bit_pos) is_touching = is_circle_touching_AABB(bit_center, rad_in_bits, corner_a, corner_b) bit_index = bitmap.index_from_indices(bit_pos) is_circle[bit_index] = (is_circle[bit_index] or is_touching) return bitmap
def test_invalid_value(self): bitmap = Bitmap(size=10, value=10) with self.assertRaises(TypeError): bitmap.value = 7.0 # type: ignore with self.assertRaises(TypeError): bitmap.value = '0b111' # type: ignore with self.assertRaises(TypeError): bitmap.value = [7] # type: ignore # value < 0 with self.assertRaises(ValueError): bitmap.value = -1 # value >= (1 << size) with self.assertRaises(ValueError): bitmap.value = 1024 with self.assertRaises(TypeError): _ = Bitmap(value=(10, )) # type: ignore
def line(x0, y0, x1, y1, image: Bitmap, color): steep = False if abs(x0 - x1) < abs(y0 - y1): x0, y0 = y0, x0 x1, y1 = y1, x1 steep = True if x0 > x1: x0, x1 = x1, x0 y0, y1 = y1, y0 dx = x1 - x0 dy = y1 - y0 d_error = abs(dy) * 2 error = 0 y = y0 for x in range(x0, x1 + 1): if steep: image.set_rgb_pixel(y, x, color.r, color.g, color.b) else: image.set_rgb_pixel(x, y, color.r, color.g, color.b) error += d_error if error > dx: y += 1 if y1 > y0 else -1 error -= dx * 2
def _process_refund_rs(transaction_data): transaction_data['bitmap'] = Bitmap.sale_rs() terminal_id = transaction_data['terminal_id'] card = database.get_card(transaction_data['PAN']) amount = transaction_data['amount'] refund_amount = int(amount[:-2]) + float(amount[-2:]) / 100 session = database.get_session(terminal_id) session.add_refund(refund_amount) card.deposit(refund_amount) database.save_state() transaction_data['transaction_id'] = action_codes['refund'] return _process_accepted_and_implemented(transaction_data)
def _process_settlement_rq(transaction_data): transaction_data['bitmap'] = Bitmap.settlement_rs() transaction_data['transaction_id'] = action_codes['settlement'] terminal_id = transaction_data['terminal_id'] text_data = transaction_data['text_data'] session = database.get_session(terminal_id) session_text_data = Transaction._format_text_data(session.sales_count, session.sales_amount, session.refund_count, session.refund_amount) if session_text_data != text_data: _process_revision_error(transaction_data) _process_accepted_and_implemented(transaction_data)
def _process_sale_rq(transaction_data): transaction_data['bitmap'] = Bitmap.sale_rs() terminal_id = transaction_data['terminal_id'] card = database.get_card(transaction_data['PAN']) amount = transaction_data['amount'] sell_amount = int(amount[:-2]) + float(amount[-2:]) / 100 if card.balance < sell_amount: return _process_insufficient_funds(transaction_data) session = database.get_session(terminal_id) session.add_sell(sell_amount) card.buy(sell_amount) database.save_state() transaction_data['transaction_id'] = action_codes['sale'] return _process_accepted_and_implemented(transaction_data)
def __init__( self, parent): PanelDrawIcon.__init__( self, parent ) print 'DesignControl constructor ' self.brush = '1' self.drawMode = 0 self.brushColor = 0xFFFF; self.scaleX = 1 self.scaleY = 1 self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height) self.pointCurrent = wx.Point(0,0) self.pointStartDrag = None self.pointEndDrag = None self.mousePoint = (0,0) self.panelIconCanvasOnSize(None) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerAnimate, self.timer) self.animateIdx = 0 self.initFileList()
def parse(transaction): bitmap = Bitmap.unhexlify(transaction[:version.BITMAP_LENGTH]) fields = _get_transaction_fields(bitmap) transaction_data = {} # First of all, parse cardholder_name (if presented) # because its length will affect other fields if 4 in fields: transaction_data['cardholder_name'] = _get_cardholder_name( fields, transaction) # Mandatory fields transaction_data.update({ 'transaction_id': _get_transaction_id(fields, transaction), 'terminal_id': _get_terminal_id(fields, transaction), 'datetime': _get_datetime(fields, transaction), 'CRC': _get_CRC(fields, transaction) }) # Optional fields if 3 in fields: transaction_data['PAN'] = _get_PAN(fields, transaction) if 5 in fields: transaction_data['expiry_date'] = _get_expiry_date(fields, transaction) if 6 in fields: transaction_data['PIN'] = _get_PIN(fields, transaction) if 7 in fields: transaction_data['amount'] = _get_amount(fields, transaction) if 8 in fields: transaction_data['transaction_no'] = _get_transaction_no( fields, transaction) if 9 in fields: transaction_data['RRN'] = _get_RRN(fields, transaction) if 10 in fields: transaction_data['text_data'] = _get_text_data(fields, transaction) return transaction_data
def __init__(self, parent, remote): """ remote is instance of HubProtocol for communication with remote""" PanelModules.__init__(self, parent) ControlBase.__init__(self) self.remote = remote self.scaleX = 1 self.scaleY = 1 self.drawMode = 0 self.hubList = hubs.HubListModel(self.scrolledWindowHubs, self) listHubsSizer = wx.BoxSizer(wx.VERTICAL) listHubsSizer.Add(self.hubList, 1, wx.ALL | wx.EXPAND, 5) self.scrolledWindowHubs.SetSizer(listHubsSizer) listHubsSizer.Fit(self.scrolledWindowHubs) self.fanbotList = hubs.FanbotListModel(self.scrolledWindowFanbots, self) listFanbotsSizer = wx.BoxSizer(wx.VERTICAL) listFanbotsSizer.Add(self.fanbotList, 1, wx.ALL | wx.EXPAND, 5) self.scrolledWindowFanbots.SetSizer(listFanbotsSizer) listFanbotsSizer.Fit(self.scrolledWindowFanbots) self.pointCurrent = wx.Point(0, 0) self.pointPrevious = wx.Point(0, 0) self.currenthub = None self.compressedFrame = array.array("B", [0] * 125) self.bitmap = Bitmap(FanbotConfig.width, FanbotConfig.height) self.bitmap.clear() for hub in self.hubList.hubs: self.showHub(hub) self.timerAnimate = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerAnimateHandler, self.timerAnimate) self.animateIdx = 0 self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerDiscover, self.timer) self.timerDiscoverCount = 0
def test_is_bit_set(self): b = Bitmap(0xAAAAAAAA55555555) bitset = b.get_bitmap_as_indices() for i in range(64): if (i < 32): if (i % 2): self.assertFalse(b.is_bit_set(i)) else: self.assertTrue(b.is_bit_set(i)) else: if (i % 2): self.assertTrue(b.is_bit_set(i)) else: self.assertFalse(b.is_bit_set(i)) self.assertRaises(TooDamnMuchDammitError, b.is_bit_set, 1024)
class ModulenControl(PanelModules, ControlBase): def __init__(self, parent, remote): """ remote is instance of HubProtocol for communication with remote""" PanelModules.__init__(self, parent) ControlBase.__init__(self) self.remote = remote self.scaleX = 1 self.scaleY = 1 self.drawMode = 0 self.hubList = hubs.HubListModel(self.scrolledWindowHubs, self) listHubsSizer = wx.BoxSizer(wx.VERTICAL) listHubsSizer.Add(self.hubList, 1, wx.ALL | wx.EXPAND, 5) self.scrolledWindowHubs.SetSizer(listHubsSizer) listHubsSizer.Fit(self.scrolledWindowHubs) self.fanbotList = hubs.FanbotListModel(self.scrolledWindowFanbots, self) listFanbotsSizer = wx.BoxSizer(wx.VERTICAL) listFanbotsSizer.Add(self.fanbotList, 1, wx.ALL | wx.EXPAND, 5) self.scrolledWindowFanbots.SetSizer(listFanbotsSizer) listFanbotsSizer.Fit(self.scrolledWindowFanbots) self.pointCurrent = wx.Point(0, 0) self.pointPrevious = wx.Point(0, 0) self.currenthub = None self.compressedFrame = array.array("B", [0] * 125) self.bitmap = Bitmap(FanbotConfig.width, FanbotConfig.height) self.bitmap.clear() for hub in self.hubList.hubs: self.showHub(hub) self.timerAnimate = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerAnimateHandler, self.timerAnimate) self.animateIdx = 0 self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerDiscover, self.timer) self.timerDiscoverCount = 0 def buttonResetDiscOnButtonClick(self, event): self.remote.sendCommand(HubProtocol.RESET) self.hubList.resetDiscovery() def buttonDiscoverOnButtonClick(self, event): self.remote.sendCommand(HubProtocol.REQUEST_ID) self.timer.Start(2000) self.timerDiscoverCount = 2 self.sendMessage("Discover module. Even geduld aub... ") def timerDiscover(self, event): if self.timerDiscoverCount == 0: self.timer.Stop() else: self.timerDiscoverCount -= 1 self.remote.sendCommand(HubProtocol.REQUEST_ID) self.hubList.refresh() def buttonClearListOnButtonClick(self, event): self.listModules.Clear() def buttonResetConfigOnButtonClick(self, event): if self.currenthub: self.resetHub(self.currenthub) self.remote.sendConfig(self.currenthub.idAsArray(), self.currenthub.config) def buttonSetConfigOnButtonClick(self, event): if self.currenthub: hub = self.currenthub print "buttonSetConfigOnButtonClick, currenthub: ", hub.id self.remote.sendConfig(hub.idAsArray(), hub.config) def buttonSetConfigAllOnButtonClick(self, event): print "buttonSetConfigAllButtonClick" for hub in self.hubList.hubs: self.remote.sendConfig(hub.idAsArray(), hub.config) time.sleep(0.100) def panelModulesCanvasOnSize(self, event): rect = self.panelModulesCanvas.GetRect() self.scaleX = rect.GetWidth() / self.bitmap.width self.scaleY = rect.GetHeight() / self.bitmap.height # print 'Scale x:y',self.scaleX,':',self.scaleY self.Refresh() def panelModulesCanvasOnPaint(self, event): dc = wx.PaintDC(self.panelModulesCanvas) dc.BeginDrawing() dc.SetUserScale(self.scaleX, self.scaleY) dc.Clear() dc.DrawBitmap(self.bitmap.getBitmap(), 0, 0) dc.EndDrawing() def panelModulesCanvasOnMouseEvents(self, event): point = None canvas = self.panelModulesCanvas if event: # set mouse cursor canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) # get device context of canvas dc = wx.ClientDC(canvas) dc.SetUserScale(self.scaleX, self.scaleY) point = event.GetLogicalPosition(dc) if point.x < 0 or point.x >= FanbotConfig.width or point.y < 0 or point.y >= FanbotConfig.height: # print 'x,y out of bounds: ',point.x ,':',point.y return if self.checkBoxMatrix.IsChecked(): """ set the snapto grid to horizontal 4 and vertical 6""" point.x /= 4 point.x *= 4 point.y /= 6 point.y *= 6 self.labelPosition.SetLabel("%s : %s" % (point.x, point.y)) self.pointCurrent = point # print "mouse event X : " ,point.x , " Y: ",point.y if event.LeftDown(): self.panelModulesCanvas.Refresh() self.pointPrevious = self.pointCurrent if self.checkBoxMatrix.IsChecked(): self.matrixHubConfig(point.x, point.y) else: self.updateHubConfig(point.x, point.y) elif event.LeftIsDown() and not self.checkBoxMatrix.IsChecked(): if self.pointPrevious.x == self.pointCurrent.x and self.pointPrevious.y == self.pointCurrent.y: return self.pointPrevious = self.pointCurrent # print "Dragging to X : " ,point.x , " Y: ",point.y cur = wx.StockCursor(wx.CURSOR_CROSS) canvas.SetCursor(cur) self.updateHubConfig(point.x, point.y) def updateHubConfig(self, x, y): hub = self.currenthub if hub: if hub.canAddConfigItem(): if self.bitmap.pixelSetWhite(x, y): hub.setConfig(x, y) self.panelModulesCanvas.Refresh() def matrixHubConfig(self, x, y): hub = self.currenthub if hub: if hub.canAddConfigItem(): hub.resetConfig() for y in range(self.pointCurrent.y, self.pointCurrent.y + 6): for x in range(self.pointCurrent.x, self.pointCurrent.x + 4): self.bitmap.pixelSetWhite(x, y) self.currenthub.setConfig(x, y) self.panelModulesCanvas.Refresh() def handleCommand(self, opcode, payload): """ Handle incoming data from remote hubs or hubsimulator""" print "Modulen: Received opcode: %04x -- %s" % (opcode, payload) id = "" if len(payload) >= 4: for i in range(4): id = "%02x%s" % (payload[i], id) if opcode == HubProtocol.ID_REPORT: if len(payload) != 4: print "Error: incorrect length from hub received" return self.sendMessage("Discovered hub: " + id) print "Modulen: Received ID_REPORT from %s" % (id) hub = self.hubList.addHub(id) hub.discoverd = True hub.responsive = True # self.remote.sendCommand( HubProtocol.TAG_ID,4,hub.idAsArray() ) # remove tagging, as it messes up frames elif opcode == HubProtocol.STATUS_REPORT: hub = self.currenthub if hub: hub.setFanbots(payload) self.fanbotList.setFanbots(hub.fanbots) self.labelHubId.SetLabel("Hub: " + id) def hubSelected(self, hub): """Callback function called from the hubs list control""" self.showHub(self.currenthub) print "selected hub:", hub.id self.currenthub = hub config = hub.config for i in range(0, len(config)): tuple = hub.getConfigColor(i) if tuple[0] >= 0: x = tuple[0] y = tuple[1] self.bitmap.setPixel(x, y, 0xFFFFFF) self.fanbotList.setFanbots(None) self.labelHubId.SetLabel("Hub: ") self.panelModulesCanvas.Refresh() self.remote.sendCommand(HubProtocol.REQUEST_STATUS, 4, hub.idAsArray()) time.sleep(0.2) if 0 == self.sliderAnimateHub.GetValue(): self.createHubBitmap() self.remote.sendFanbotFrame(self.compressedFrame) def fanbbotSelected(self, item): mappedindex = Hub.fanbotMapping[item] - 1 print "Selected fanbot index: %d mapped onto index %d" % (item, mappedindex) if 0 == self.sliderAnimateHub.GetValue(): self.createFanbotBitmap(mappedindex) self.remote.sendFanbotFrame(self.compressedFrame) def showHub(self, hub): """for the given hub, show the pixels in the bitmap, in the color of he hub""" if hub: config = hub.config for i in range(0, len(config)): tuple = hub.getConfigColor(i) if tuple[0] >= 0: x = tuple[0] y = tuple[1] self.bitmap.setPixel(x, y, tuple[2]) def resetHub(self, hub): """for the given hub, make all its pixels gray, and then reset config""" if hub: print "reset hub:", hub.id config = hub.config for i in range(0, len(config)): tuple = hub.getConfigColor(i) if tuple[0] >= 0: x = tuple[0] y = tuple[1] self.bitmap.pixelSetGray(x, y) hub.resetConfig() self.panelModulesCanvas.Refresh() def sliderAnimateHubOnScroll(self, event): speed = self.sliderAnimateHub.GetValue() if speed == 0: self.timerAnimate.Stop() else: self.timerAnimate.Start(250 - speed * 25) def timerAnimateHandler(self, event): """ """ hub = self.currenthub if hub: self.animateIdx += 1 if self.animateIdx >= 24: self.animateIdx = 0 self.createFanbotBitmap(Hub.fanbotMapping[self.animateIdx] - 1) self.remote.sendFanbotFrame(self.compressedFrame) def createHubBitmap(self): hub = self.currenthub maxFrameLen = len(self.compressedFrame) if hub: for i in range(maxFrameLen): self.compressedFrame[i] = 0 for i in range(24): pixelIdx = hub.config[i] if pixelIdx >= 0: byteIdx = pixelIdx / 8 if byteIdx >= maxFrameLen: return bitIdx = pixelIdx % 8 self.compressedFrame[byteIdx] |= 1 << bitIdx def createFanbotBitmap(self, idx): hub = self.currenthub maxFrameLen = len(self.compressedFrame) if hub: for i in range(maxFrameLen): self.compressedFrame[i] = 0 if idx >= 24: return pixelIdx = hub.config[idx] if pixelIdx >= 0: byteIdx = pixelIdx / 8 if byteIdx >= maxFrameLen: return bitIdx = pixelIdx % 8 self.compressedFrame[byteIdx] = 1 << bitIdx
class ProxyControl(PanelProxy): alive = True instance = None def __init__( self, parent,remote): """ remote is instance of HubProtocol for communication with remote""" PanelProxy.__init__( self, parent ) self.remote = remote print 'ProxyControl constructor ' self.scaleX = 1 self.scaleY = 1 self.server = None ProxyControl.instance = self self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height) self.Refresh() # Virtual event handlers, overide them in your derived class def __del__( self ): print "proxycontrol destructor ..." self.shutdown() def panelProxyCanvasOnPaint( self, event ): dc = wx.PaintDC(self.panelProxyCanvas) dc.BeginDrawing() dc.SetUserScale(self.scaleX, self.scaleY) dc.Clear() dc.DrawBitmap(self.bitmap.getBitmap(),0,0) dc.EndDrawing() def panelProxyCanvasOnSize( self, event ): rect = self.panelProxyCanvas.GetRect() self.scaleX = rect.GetWidth() / self.bitmap.width self.scaleY = rect.GetHeight() / self.bitmap.height #print 'Scale x:y',self.scaleX,':',self.scaleY self.Refresh() def startProxyServer(self): self.buttonProxyStartOnButtonClick(None) def buttonProxyStartOnButtonClick( self, event ): evt = fanbotevent.FanbotEvent(fanbotevent.EVT_PROXY_SERVER_ID,self.GetId()) if self.buttonProxyStart.GetLabel() == 'Start': self.initProxyServer(); time.sleep(1) if ProxyControl.alive: self.buttonProxyStart.SetLabel('Stop') evt.setPayload('started') wx.PostEvent(self,evt) print 'proxy server started' else: print 'unable to start proxy server ' else: dlg = wx.MessageDialog(self, 'Zeker weten?!', 'Stop proxy server, ' , wx.OK| wx.CANCEL | wx.ICON_INFORMATION ) result = dlg.ShowModal() dlg.Destroy() if wx.ID_OK ==result: self.shutdown(); self.buttonProxyStart.SetLabel('Start') evt.setPayload('stopped') wx.PostEvent(self,evt) print 'proxy server stopped' def initProxyServer(self): """Start the server thread""" self.thread = threading.Thread(target=self.proxyServerThread) self.thread.setDaemon(1) self.thread.start() def proxyServerThread(self): print "Starting socket server thread " portstr = FanbotConfig.getProxyPort() port = int(portstr) host = "localhost" self.labelProxyHost.SetLabel( '%s : %d' % (host,port) ) ProxyControl.alive = True try: self.server = SocketServer.ThreadingTCPServer((host, port), ProxyHandler) self.server.serve_forever() except Exception as e: print "unable to start server: ", e.message self.shutdown() def shutdown(self): ProxyControl.alive = False if self.server: self.server.shutdown() self.server = None
class Plot(param.Parameterized): """ Simple Plot object constructed from a specified PIL image. """ staleness_warning=param.Number(default=10,bounds=(0,None),doc=""" Time length allowed between bitmaps making up a single plot before warning. If the difference between the SheetView with the earliest timestamp and the one with the latest timestamp is larger than this parameter's value, produce a warning. """) def __init__(self,image=None,**params): super(Plot,self).__init__(**params) self._orig_bitmap = Bitmap(image) self.bitmap = self._orig_bitmap # Possibly scaled copy (at first identical) self.scale_factor=1.0 self.plot_src_name = '' self.precedence = 0.0 self.row_precedence = 0.5 # If False, this plot should be left in its native size # pixel-for-pixel, (e.g. for a color key or similar static # image), rather than being resized as necessary. self.resize=False # Time at which the bitmaps were created self.timestamp = -1 def rescale(self,scale_factor): """ Change the size of this image by the specified numerical factor. The original image is kept as-is in _orig_bitmap; the scaled image is stored in bitmap. The scale_factor argument is taken as relative to the current scaling of the bitmap. For instance, calling scale(1.5) followed by scale(2.0) will yield a final scale of 3.0, not 2.0. """ self.scale_factor *= scale_factor if (self._orig_bitmap): self.bitmap = copy.copy(self._orig_bitmap) self.bitmap.image = self._orig_bitmap.zoom(self.scale_factor) def set_scale(self,scale_factor): """ Specify the numerical value of the scaling factor for this image. The original image is kept as-is in _orig_bitmap; the scaled image is stored in bitmap. The scale_factor argument is taken as relative to the original size of the bitmap. For instance, calling scale(1.5) followed by scale(2.0) will yield a final scale of 2.0, not 3.0. """ self.scale_factor = scale_factor if (self._orig_bitmap): self.bitmap = copy.copy(self._orig_bitmap) self.bitmap.image = self._orig_bitmap.zoom(self.scale_factor) def label(self): """Return a label for this plot.""" return self.plot_src_name + '\n' + self.name
def test_max_bits(self): b = Bitmap(2 ** 1024 - 1) self.assertTrue(b) bitset = b.get_bitmap_as_indices() self.assertTrue(len(bitset) == 1024)
class HubSimulControl(HubSimulFrame ): HubCount = 42 def __init__( self, parent): HubSimulFrame.__init__( self, parent ) panel = self.panelRawBitmap sizer = panel.GetSizer() self.bitmap = Bitmap(panel,Bitmap.width,Bitmap.height) sizer.Add( self.bitmap, 1, wx.EXPAND ) # start listeneing on port 1234 factory = ParserFactory() server = HubSimulServer(factory) self.protocol = HubProtocol(server) self.protocol.addListener(self) self.alive = threading.Event() self.event = None self.hubs = [] for i in range (HubSimulControl.HubCount): hub = HubSimul(i,self.protocol) self.hubs.append(hub) self.startThread() def __del__( self ): print "destructor ..." self.server.shutdown() self.server = None def handleCommand(self, opcode,payload): if opcode in [HubProtocol.POS_FRAME,HubProtocol.PLAY_FRAME,HubProtocol.LED_FRAME]: wx.CallAfter(self.updateBitmapInGuiThread,opcode,payload) else: for i in range (HubSimulControl.HubCount): hub = self.hubs[i] hub.handleCommand(opcode,payload) def updateBitmapInGuiThread(self,command,payload): self.bitmap.fromCompressedBuffer(command,payload) self.Refresh() def startThread(self): """Start the wave thread""" self.thread = threading.Thread(target=self.TribuneWaveThread) self.thread.setDaemon(1) self.alive.set() self.thread.start() def stopThread(self): """Stop the receiver thread, wait util it's finished.""" print "Stop thread ..." self.alive.clear() #clear alive event for thread if hasattr(self, 'thread') and self.thread != None: self.thread.join() #wait until thread has finished self.thread = None print "Stop thread done ..." def TribuneWaveThread(self): print "Starting thread TribuneWaveThread" while(True): time.sleep(1)
master_log("Data ready. Sending chunks info to workers.", MPI.Wtime() - data_prep_time) else: chunk_info = None chunks = None chunk_width, chunk_height, chunk_bytes = comm.bcast(chunk_info, root=0) worker_chunk = np.empty(chunk_bytes, dtype=np.uint8) master_log("Scattering pixels data.") comm.Scatter([chunks, MPI.BYTE], [worker_chunk, MPI.BYTE], root=0) worker_log("Received pixels data chunk.") if not master(): # Chunk processing (in workers) chunk_start_time = MPI.Wtime() log("Starting chunk processing.") bm = Bitmap(chunk_width, chunk_height, worker_chunk) res_bm = bm.scale(Constants.SCALING).roberts_cross() res_chunk = res_bm.get_data() res_chunk_width, res_chunk_height = res_bm.get_size() res_chunk_bytes = res_chunk_width * res_chunk_height res_chunk_info = (res_chunk_width, res_chunk_height, res_chunk_bytes) log("Finished chunk processing.", MPI.Wtime() - chunk_start_time) # Send processed chunk info to master if rank == 1: log("Sending processed chunk info to master.") comm.send(res_chunk_info, dest=0, tag=1) if master(): res_chunk_width, res_chunk_height, res_chunk_bytes = comm.recv(source=1, tag=1) log("Received processed chunks info.") res_chunk = np.empty(res_chunk_bytes, dtype=np.uint8)
def test_find_next_empty_bits(self): b = Bitmap(0x0) i = 0 while str(b) == "0xFFFF": n = b.get_next_empty_bits(1) self.assertEqual(n, i) i += 1 b = Bitmap(0xA955) self.assertEqual(b.get_next_empty_bits(2), 9) self.assertEqual(b.get_next_empty_bits(3), 16) b = Bitmap(2 ** 1024 - 1) self.assertEqual(b.get_next_empty_bits(1), -1) b = Bitmap(2 ** 1024 - 1) b.clr_bit(1023) self.assertEqual(b.get_next_empty_bits(1), 1023) self.assertEqual(b.get_next_empty_bits(2), -1) self.assertEqual(b.get_next_empty_bits(0), -1)
class DesignControl(PanelDrawIcon ): def __init__( self, parent): PanelDrawIcon.__init__( self, parent ) print 'DesignControl constructor ' self.brush = '1' self.drawMode = 0 self.brushColor = 0xFFFF; self.scaleX = 1 self.scaleY = 1 self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height) self.pointCurrent = wx.Point(0,0) self.pointStartDrag = None self.pointEndDrag = None self.mousePoint = (0,0) self.panelIconCanvasOnSize(None) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.timerAnimate, self.timer) self.animateIdx = 0 self.initFileList() def panelIconCanvasOnPaint( self, event ): dc = wx.PaintDC(self.panelIconCanvas) dc.BeginDrawing() dc.SetUserScale(self.scaleX, self.scaleY) dc.Clear() dc.DrawBitmap(self.bitmap.getBitmap(),0,0) dc.EndDrawing() def panelIconCanvasOnMouseEvents( self, event ): point = None canvas = self.panelIconCanvas if event: # set mouse cursor canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) # get device context of canvas dc= wx.ClientDC(canvas) dc.SetUserScale(self.scaleX, self.scaleY) point = event.GetLogicalPosition(dc) if point.x < 0 or point.x >= FanbotConfig.width or point.y < 0 or point.y >= FanbotConfig.height: #print 'x,y out of bounds: ',point.x ,':',point.y return self.pointCurrent = point #print "mouse event X : " ,point.x , " Y: ",point.y if event.LeftDown(): #print "mouse down X : " ,point.x , " Y: ",point.y # Left mouse button down, change cursor to # something else to denote event capture self.pointStartDrag = point cur = wx.StockCursor(wx.CURSOR_CROSS) canvas.SetCursor(cur) self.setPixel(point.x, point.y,self.brushColor) # invalidate current canvas self.Refresh() if event.LeftIsDown(): self.pointDragTo = point #print "Dragging to X : " ,point.x , " Y: ",point.y cur = wx.StockCursor(wx.CURSOR_CROSS) canvas.SetCursor(cur) if self.drawMode == 0: self.setPixel(point.x, point.y,self.brushColor) if self.drawMode == 1: for x in range (self.pointStartDrag.x,point.x): for y in range (self.pointStartDrag.y,point.y): self.setPixel(x, y,self.brushColor) self.panelIconCanvas.Refresh() """ Panel drawDesign """ def buttonPrevOnButtonClick( self, event ): self.prevFrame() self.labelFrame.SetLabel(self.getFrameCountAsString()) def buttonNextOnButtonClick( self, event ): self.nextFrame() self.labelFrame.SetLabel(self.getFrameCountAsString()) def buttonAddFrameOnButtonClick( self, event ): self.addFrame() self.labelFrame.SetLabel(self.getFrameCountAsString()) def buttonDeleteFrameOnButtonClick( self, event ): frnr = self.delFrame() self.labelFrame.SetLabel(self.getFrameCountAsString()) def buttonAddOnButtonClick( self, event ): wx.MessageBoxCaptionStr dlg = wx.TextEntryDialog( self, 'Filename: ', 'Enter filename', 'Python') dlg.SetValue("test.gif") if dlg.ShowModal() == wx.ID_OK: fn = dlg.GetValue() if not fn.find('.gif'): fn = fn + '.gif' full = 'data/' + fn self.setFilename(full) f = open(full,'w') f.close() self.saveCurrentFile() dlg.Destroy() self.listIcons.Append(fn) def buttonDeleteOnButtonClick( self, event ): print 'buttonDeleteOnButtonClick' idx = self.listIcons.GetSelection() if idx == wx.NOT_FOUND: return; fn = self.listIcons.GetString(idx) result = wx.MessageBox('File '+ fn + ' wissen?', 'File wissen', wx.OK | wx.CANCEL | wx.ICON_QUESTION) if result == wx.OK: os.remove('data/' + fn) self.listIcons.Delete(idx) def buttonSaveOnButtonClick( self, event ): self.saveCurrentFile() def listIconsOnListBox( self, event ): fname = event.GetString() print 'selected: ', fname self.loadFromFile("data/" + fname) self.labelFrame.SetLabel(self.getFrameCountAsString()) def sliderAnimateOnScroll( self, event ): pos = event.GetPosition() self.animate(pos) if pos == 0: self.labelFrame.SetLabel(self.getFrameCountAsString()) event.Skip() def initFileList(self): for fname in os.listdir("data"): if ".gif" in fname: #print fname self.listIcons.Append(fname) def toolBrush1OnToolClicked( self, event ): self.brush = '1' def toolBrush4OnToolClicked( self, event ): self.brush = '4' def toolBrush9OnToolClicked( self, event ): self.brush = '9' def toolDrawLineOnToolClicked( self, event ): self.drawMode = 1 def toolDrawDotOnToolClicked( self, event ): self.drawMode = 0 def toolColorOnToolClicked( self, event ): dlg = wx.ColourDialog(self) dlg.GetColourData().SetChooseFull(True) if dlg.ShowModal() == wx.ID_OK: # If the user selected OK, then the dialog's wx.ColourData will # contain valid information. Fetch the data ... data = dlg.GetColourData() # ... then do something with it. The actual colour data will be # returned as a three-tuple (r, g, b) in this particular case. print 'You selected: %s\n' % str(data.GetColour().Get() ) r,g,b = data.GetColour().Get() self.brushColor = b * 0x10000 + g * 0x100 + r dlg.Destroy() def toolColorBlackOnToolClicked( self, event ): print 'colorGray' self.brushColor = 0x101010 def toolColorWhiteOnToolClicked( self, event ): print 'clororWhite' self.brushColor = 0xC0C0C0 def panelIconCanvasOnSize( self, event ): rect = self.panelIconCanvas.GetRect() self.scaleX = rect.GetWidth() / self.bitmap.width self.scaleY = rect.GetHeight() / self.bitmap.height #print 'Scale x:y',self.scaleX,':',self.scaleY self.Refresh() def loadFromFile(self,fname): if self.bitmap.changed: result = wx.MessageBox('Bitmap is aangepast. Opslaan?', 'Opslaan', wx.OK | wx.CANCEL |wx.ICON_INFORMATION) if result == wx.OK: self.saveCurrentFile() self.bitmap.loadFromFile(fname) self.Refresh() def saveCurrentFile(self): self.bitmap.saveCurrentFile() def getFilename(self): return self.bitmap.filename def setFilename(self,fn): self.bitmap.filename = fn def delFrame(self): """delete frame at current index. Do nothing if only one frame """ self.bitmap.delFrame() self.Refresh() def addFrame(self): """add frame after the current index. """ self.bitmap.addFrame() self.Refresh() def prevFrame(self): """Go back to previous frame in animated GIF. """ self.bitmap.prevFrame() self.Refresh() def animate(self,speed): if speed == 0: self.timer.Stop() else : self.timer.Start(1000 -speed * 100) def timerAnimate(self,event): self.animateIdx += 1 if self.animateIdx >= self.bitmap.getFrameCount(): self.animateIdx = 0 self.bitmap.setFrameNr(self.animateIdx) self.Refresh() def getFrameCountAsString(self): return '%d/%d' % (self.bitmap.getFrameNr(),self.bitmap.getFrameCount() ) def nextFrame(self): """Advance to next frame in animated GIF. If beyond the last do nothing """ self.bitmap.nextFrame() self.Refresh() def setPixel(self,x,y,colour): if self.brush =='1': self.bitmap.setPixel(x, y,colour) elif self.brush =='4': self.bitmap.setPixel(x, y,colour) self.bitmap.setPixel(x, y+1,colour) self.bitmap.setPixel(x+1, y,colour) self.bitmap.setPixel(x+1, y+1,colour) elif self.brush == '9' and x > 0 and y > 0: self.bitmap.setPixel(x, y,colour) self.bitmap.setPixel(x, y-1,colour) self.bitmap.setPixel(x, y+1,colour) self.bitmap.setPixel(x-1, y,colour) self.bitmap.setPixel(x-1, y-1,colour) self.bitmap.setPixel(x-1, y+1,colour) self.bitmap.setPixel(x+1, y,colour) self.bitmap.setPixel(x+1, y-1,colour) self.bitmap.setPixel(x+1, y+1,colour)
def test_set_bit(self): b = Bitmap() b.set_bit(64) b.set_bit(0) b.set_bit(1023) self.assertTrue(b.is_bit_set(64)) self.assertTrue(b.is_bit_set(0)) self.assertTrue(b.is_bit_set(1023)) for i in range(1024): if i != 64 and i != 0 and i != 1023: self.assertFalse(b.is_bit_set(i)) self.assertRaises(TooDamnMuchDammitError, b.set_bit, 1024)
def test_clr_bit(self): b = Bitmap(0xAA55) b.clr_bit(0); self.assertEqual(str(b), "0xaa54") b.clr_bit(1); self.assertEqual(str(b), "0xaa54") b.clr_bit(2); self.assertEqual(str(b), "0xaa50") b.clr_bit(4); self.assertEqual(str(b), "0xaa40") b.clr_bit(6); self.assertEqual(str(b), "0xaa00") b.clr_bit(15) self.assertEqual(str(b), "0x2a00") b.set_bit(1023) self.assertTrue(b.is_bit_set(1023) and re.search(r"2a00$", str(b), re.I)) b.clr_bit(1023) self.assertTrue(str(b), "0x2a00") self.assertRaises(TooDamnMuchDammitError, b.clr_bit, 1024)
def test_ctor(self): b = Bitmap() self.assertTrue(b) bitset = b.get_bitmap_as_indices() self.assertTrue(not len(bitset))