diff --git a/Python-Examples/README.md b/Python-Examples/README.md index 2314157..73e2f10 100644 --- a/Python-Examples/README.md +++ b/Python-Examples/README.md @@ -21,7 +21,10 @@ Various Code Snippets on different topics about Python 1. [merge_sort] (merge_sort.py) +3. **Color in terminal** + ![Color in terminal](terminal/color_in_terminal.png) + 4. Requests - Requests-futures A small example in terms of demonstrating the parallelization of diff --git a/Python-Examples/mmap/shared_memory_read.py b/Python-Examples/mmap/shared_memory_read.py index fbae3bd..b936f2e 100644 --- a/Python-Examples/mmap/shared_memory_read.py +++ b/Python-Examples/mmap/shared_memory_read.py @@ -15,13 +15,13 @@ def main(): s = None while 1: - new_i = struct.unpack('i', buf[:4]) - new_s = struct.unpack('3s', buf[4:7]) + new_i, = struct.unpack('i', buf[:4]) + new_s, = struct.unpack('3s', buf[4:7]) if i != new_i or s != new_s: - print "i: {} => {}".format(i, new_i) - print "s: {} => {}".format(s, new_s) - print 'Press Ctrl-C to exit' + print('i: %s => %d' % (i, new_i)) + print('s: %s => %s' % (s, new_s)) + print('Press Ctrl-C to exit') i = new_i s = new_s diff --git a/Python-Examples/mmap/shared_memory_write.py b/Python-Examples/mmap/shared_memory_write.py index 4321769..b3be5db 100644 --- a/Python-Examples/mmap/shared_memory_write.py +++ b/Python-Examples/mmap/shared_memory_write.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python3 import ctypes import mmap import os @@ -9,7 +10,7 @@ def main(): fd = os.open('/tmp/mmaptest', os.O_CREAT | os.O_TRUNC | os.O_RDWR) # Zero out the file to insure it's the right size - assert os.write(fd, '\x00' * mmap.PAGESIZE) == mmap.PAGESIZE + assert os.write(fd, bytes('\x00' * mmap.PAGESIZE,'utf8')) == mmap.PAGESIZE # Create the mmap instace with the following params: # fd: File descriptor which backs the mapping or -1 for anonymous mapping @@ -30,33 +31,35 @@ def main(): assert i.value == 11 # Before we create a new value, we need to find the offset of the next free - # memory address within the map + # memory address within the mmap offset = struct.calcsize(i._type_) # The offset should be uninitialized ('\x00') - assert buf[offset] == '\x00' + print(buf[offset]) + assert buf[offset] == 0 - # Now create a string containing 'foo' by first creating a c_char array - s_type = ctypes.c_char * (len('foo')) + # Now ceate a string containing 'foo' by first creating a c_char array + s_type = ctypes.c_char * len('foo') # Now create the ctypes instance s = s_type.from_buffer(buf, offset) # And finally set it - s.raw = 'foo' + s.raw = bytes('foo','utf8') - print 'First 10 bytes of memory mapping: %r' % buf[:10] - raw_input('Now run shared_memory_read.py and press ENTER') + print('First 10 bytes of memory mapping: %r' % buf[:10]) + # input('Now run b.py and press ENTER') - print - print 'Changing i' + print('Now i:', i.value) + print('Changing i') i.value *= i.value - print 'Changing s' - s.raw = 'bar' + print('Changing s') + s.raw = bytes('bar','utf8') - new_i = raw_input('Enter a new value for i: ') + new_i = input('Enter a new value for i: ') i.value = int(new_i) + print('Now i:', i.value) if __name__ == '__main__': main() diff --git a/Python-Examples/pyqt/colorsModel.py b/Python-Examples/pyqt/colorsModel.py new file mode 100644 index 0000000..fb6523b --- /dev/null +++ b/Python-Examples/pyqt/colorsModel.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from PyQt5.QtWidgets import (QWidget, QDataWidgetMapper, + QLineEdit, QApplication, QGridLayout, QListView) +from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex + + +class Window(QWidget): + def __init__(self, parent=None): + super(Window, self).__init__(parent) + + # Set up the widgets. + self.nameEdit = QLineEdit() + self.nameEdit2 = QLineEdit() + + # set up the layout + layout = QGridLayout() + layout.addWidget(self.nameEdit, 0, 1, 1, 1) + layout.addWidget(self.nameEdit2, 0, 2, 1, 1) + self.setLayout(layout) + + self.mapper = None + + def setModel(self, model): + # Set up the mapper. + self.mapper = QDataWidgetMapper(self) + self.mapper.setModel(model) + self.mapper.addMapping(self.nameEdit, 0) + self.mapper.addMapping(self.nameEdit2, 1) + self.mapper.toFirst() + + +class MyModel(QAbstractTableModel): + def __init__(self, data, parent=None): + QAbstractTableModel.__init__(self, parent) + self.lst = data + + def columnCount(self, parent=QModelIndex()): + return len(self.lst[0]) + + def rowCount(self, parent=QModelIndex()): + return len(self.lst) + + def data(self, index, role=Qt.DisplayRole): + row = index.row() + col = index.column() + + if role == Qt.EditRole: + return self.lst[row][col] + elif role == Qt.DisplayRole: + return self.lst[row][col] + + def flags(self, index): + flags = super(MyModel, self).flags(index) + + if index.isValid(): + flags |= Qt.ItemIsEditable + flags |= Qt.ItemIsDragEnabled + else: + flags = Qt.ItemIsDropEnabled + + return flags + + def setData(self, index, value, role=Qt.EditRole): + + if not index.isValid() or role != Qt.EditRole: + return False + + self.lst[index.row()][index.column()] = value + self.dataChanged.emit(index, index) + return True + + +if __name__ == '__main__': + import sys + + app = QApplication(sys.argv) + + myModel = MyModel([['row 1 col1', 'row 1 col2'], + ['row 2 col1', 'row 2 col2'], + ['row 3 col1', 'row 3 col2'], + ['row 4 col1', 'row 4 col2']]) + + # myModel = MyModel() + mywindow = Window() + mywindow.setModel(myModel) + + qlistview2 = QListView() + qlistview2.setModel(myModel) + + mywindow.show() + qlistview2.show() + + sys.exit(app.exec_()) diff --git a/Python-Examples/singleton/main.py b/Python-Examples/singleton/main.py new file mode 100644 index 0000000..794f77f --- /dev/null +++ b/Python-Examples/singleton/main.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +longqi 22/Dec/16 15:12 +Description: +To create a singleton class, you subclass from Singleton; each subclass will have a single instance, no matter how many +times its constructor is called. To further initialize the subclass instance, subclasses should override 'init' instead +of __init__ - the __init__ method is called each time the constructor is called + +""" + + +class Singleton(object): + def __new__(cls, *args, **kwargs): + it = cls.__dict__.get("__it__") + print('******* new *****') + + # print(it) + # print(cls) + # print(cls.__dict__) + if it is not None: + return it + cls.__it__ = it = object.__new__(cls) + # it = object.__new__(cls) + it.init(*args, **kwargs) + return it + + def init(self, *args, **kwargs): + print('init', args) + self.data = args + pass + + def __init__(self, *args): + self.data = [] + print('__init__') + + +a = Singleton('a') +b = Singleton('b') +c = Singleton('c') + +assert a == b == c diff --git a/Python-Examples/terminal/color_in_terminal.png b/Python-Examples/terminal/color_in_terminal.png new file mode 100644 index 0000000..ff9a476 Binary files /dev/null and b/Python-Examples/terminal/color_in_terminal.png differ diff --git a/Python-Examples/terminal/color_output.py b/Python-Examples/terminal/color_output.py new file mode 100644 index 0000000..d2a0d32 --- /dev/null +++ b/Python-Examples/terminal/color_output.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +longqi 22/Nov/16 14:19 +Description: + +https://en.wikipedia.org/wiki/ANSI_escape_code + +ESC[ … 38;2;;; … m Select RGB foreground color +ESC[ … 48;2;;; … m Select RGB background color + +In 256-color mode (ESC[38;5;m and ESC[48;5;m), the color-codes are the following:[citation needed] +0x00-0x07: standard colors (as in ESC [ 30–37 m) +0x08-0x0F: high intensity colors (as in ESC [ 90–97 m) +0x10-0xE7: 6 × 6 × 6 = 216 colors: 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5) +0xE8-0xFF: gray scale from black to white in 24 steps +ESC is (ASCII decimal 27/hex 0x1B/octal 033) + +################################################################# +### Please set the width of your terminal as wide as possible ### +################################################################# +""" +print('\x1b[1m bold text\x1b[0m') # bold + +print('\x1b[1m standard eight colors \x1b[0m') +for color_code in range(30, 38): + print('\x1b[' + str(color_code) + 'm' + str(color_code) + '\x1b[0m', end='\t') +print('\x1b[0m\n') # reset color + +print('\x1b[1m high intensity colors \x1b[0m') +for color_code in range(90, 98): + print('\x1b[' + str(color_code) + 'm' + str(color_code) + '\x1b[0m', end='\t') +print('\x1b[0m\n') + +print('\x1b[1m 256-color, foreground \x1b[0m') +for color_code in range(00, 256): + print('\x1b[38;5;' + str(color_code) + 'm' + str(color_code).zfill(3) + '\x1b[0m', end='\t') + if (color_code + 1) % 8 == 0: + print('') +print('\x1b[0m\n') + +print('\x1b[1m 256-color, background \x1b[0m') +for color_code in range(00, 256): + print('\x1b[48;5;' + str(color_code) + 'm' + str(color_code).zfill(3) + '\x1b[0m', end='\t') + if (color_code + 1) % 8 == 0: + print('') +print('\x1b[0m\n') + +print('\x1b[1m RGB-color, foreground \x1b[0m') +for R in range(0, 256, 32): + for G in range(0, 256, 32): + for B in range(0, 256, 32): + print('\x1b[38;2;' + str(R) + ';' + str(G) + ';' + str(B) + 'm' + + str(R).zfill(3) + '.' + str(G).zfill(3) + '.' + str(B).zfill(3) + '\x1b[0m', + end='\t') + print('') +print('\x1b[0m\n') + +print('\x1b[1m RGB-color, background \x1b[0m') +for R in range(0, 256, 32): + for G in range(0, 256, 32): + for B in range(0, 256, 32): + print('\x1b[48;2;' + str(R) + ';' + str(G) + ';' + str(B) + 'm' + + str(R).zfill(3) + '.' + str(G).zfill(3) + '.' + str(B).zfill(3) + '\x1b[0m', + end='\t') + print('') + +print('\x1b[0m\n')