Esempio n. 1
0
class JobScheduler(object):
    """ Job scheduler."""
    def __init__(self):
        self._pq = HeapPriorityQueue()
        self._pq.add(IDLE_TASK_PRIORITY, ('task_idle', 0))  # idle task
        self._lock = threading.Lock()
        self._cmd_handler = CommandHandler(self._pq, self._lock)
        self._simulator = Simulator(self._pq, self._lock)
        self._predefine_tasks()
        # register signal handlers
        signal.signal(signal.SIGTERM, service_shutdown)
        signal.signal(signal.SIGINT, service_shutdown)

    def _predefine_tasks(self):
        self._pq.add(-19, ['Bitcoin', 6])
        self._pq.add(-18, ['Ethereum', 5])
        self._pq.add(0, ['Ripple', 2])
        self._pq.add(2, ['Power', 1])

    def action(self):
        try:
            self._cmd_handler.start()
            self._simulator.start()
            # Keep the main thread running, otherwise signals are ignored.
            while (True):
                time.sleep(0.5)
        except ServiceExit:
            self._cmd_handler.shutdown_flag.set()
            self._simulator.shutdown_flag.set()
            self._cmd_handler.join()
            self._simulator.join()
        print('Exit scheduler!\n')
Esempio n. 2
0
class MaxPriorityQueue(object):
    """ An implementation of maximum-oriented priority queue."""
    class _Key(object):
        """ Adaptor key for invert comparisons."""
        __slots__ = '_key'

        def __init__(self, key):
            self._key = key

        def __lt__(self, other):
            return self._key > other._key

    def __init__(self):
        self._data = HeapPriorityQueue()

    def __len__(self):
        return len(self._data)

    def is_empty(self):
        return len(self) == 0

    def add(self, key, value):
        key = self._Key(key)
        self._data.add(key, value)

    def max(self):
        key, value = self._data.min()
        return (key._key, value)

    def remove_max(self):
        key, value = self._data.remove_min()
        return (key._key, value)
Esempio n. 3
0
def pq_sort(L):
    """ Sort a collection of elements stored in a python list."""
    n = len(L)
    P = HeapPriorityQueue()
    for j in range(n):
        P.add(L[j], L[j])  # use element as key and value
    for j in range(n):
        (k, v) = P.remove_min()
        L[j] = v
    return
Esempio n. 4
0
 def __init__(self):
     self._pq = HeapPriorityQueue()
     self._pq.add(IDLE_TASK_PRIORITY, ('task_idle', 0))  # idle task
     self._lock = threading.Lock()
     self._cmd_handler = CommandHandler(self._pq, self._lock)
     self._simulator = Simulator(self._pq, self._lock)
     self._predefine_tasks()
     # register signal handlers
     signal.signal(signal.SIGTERM, service_shutdown)
     signal.signal(signal.SIGINT, service_shutdown)
Esempio n. 5
0
    def __init__(self, orders):
        """ Construct two heaps from orders.

        NOTE: the quantiry of all orders are the same for now.
        """
        self._orders = orders
        self._traded = []
        self._max_heap = MaxHeapPriorityQueue()
        self._min_heap = HeapPriorityQueue()
        self._construct_heaps()
Esempio n. 6
0
class Stack(object):
    """ A stack implementation base on heap priority queue."""

    def __init__(self):
        """ Create an empty stack."""
        self._key = 0  # keep the key minimum
        self._pq = HeapPriorityQueue()

    def __len__(self):
        """ Return the number of elements in the stack."""
        return len(self._pq)

    def is_empty(self):
        """ Return True if the stack is empty."""
        return len(self) == 0

    def push(self, e):
        """ Add element e to the top of the stack."""
        self._pq.add(self._key, e)
        self._key -= 1

    def pop(self):
        """ Remove and return the element from the top of the stack.

        Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Empty('Stack is empty')
        key, value = self._pq.remove_min()
        return value

    def top(self):
        """ Return (but do not remove) the element at the top of the stack.

        Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Empty('Stack is empty')
        key, value = self._pq.min()
        return value
Esempio n. 7
0
class OnlineStockTrade(object):
    def __init__(self, orders):
        """ Construct two heaps from orders.

        NOTE: the quantiry of all orders are the same for now.
        """
        self._orders = orders
        self._traded = []
        self._max_heap = MaxHeapPriorityQueue()
        self._min_heap = HeapPriorityQueue()
        self._construct_heaps()

    def _construct_heaps(self):
        """ construct the max-oriented heap for buying order and the
        min-oriented heap for selling order."""
        for (movement, price, quantity) in self._orders:
            if movement == 'buy':
                self._max_heap.add(price, quantity)
            elif movement == 'sell':
                self._min_heap.add(price, quantity)
        return

    def do_trade(self):
        """ Do the trade process."""
        buy_price, qunt = self._max_heap.max()
        sell_price, qunt = self._min_heap.min()
        while buy_price >= sell_price:
            self._max_heap.remove_max()
            self._min_heap.remove_min()
            self._traded.append(('trade', sell_price, qunt))
            if self._max_heap.is_empty() or self._min_heap.is_empty():
                break
            else:
                buy_price, qunt = self._max_heap.max()
                sell_price, qunt = self._min_heap.min()
        print('Trading Done!')
        print(self._traded)
        return
Esempio n. 8
0
 def __init__(self):
     self._data = HeapPriorityQueue()
Esempio n. 9
0
 def __init__(self):
     """ Create an empty stack."""
     self._key = 0  # keep the key minimum
     self._pq = HeapPriorityQueue()