def test_heappop(): n = 1000 a = [randrange(1000) for _ in range(n)] heapify(a) previous = heappop(a) pop_count = 1 while a: assert previous <= (previous := heappop(a)) pop_count += 1 assert pop_count == n assert len(a) == 0
def unplan_call(self, h): # remove a call from the queue q = self.q rv = 0 for i in range(len(q)): try: if q[i][1] is h: q[i] = (0, 0) except IndexError: break heapq.heapify(q) while q and q[0] == (0, 0): heapq.heappop(q) rv += 1 return rv
def run_forever(self): while True: if self.q: t, cnt, cb, args = heapq.heappop(self.q) if __debug__: log.debug("Next coroutine to run: %s", (t, cnt, cb, args)) # __main__.mem_info() tnow = self.time() delay = t - tnow if delay > 0: self.wait(delay) else: self.wait(-1) # Assuming IO completion scheduled some tasks continue if callable(cb): cb(*args) else: delay = 0 try: if __debug__: log.debug("Coroutine %s send args: %s", cb, args) if args == (): ret = next(cb) else: ret = cb.send(*args) if __debug__: log.debug("Coroutine %s yield result: %s", cb, ret) if isinstance(ret, SysCall1): arg = ret.arg if isinstance(ret, Sleep): delay = arg elif isinstance(ret, IORead): # self.add_reader(ret.obj.fileno(), lambda self, c, f: self.call_soon(c, f), self, cb, ret.obj) # self.add_reader(ret.obj.fileno(), lambda c, f: self.call_soon(c, f), cb, ret.obj) # self.add_reader(arg.fileno(), lambda cb: self.call_soon(cb), cb) self.add_reader(arg.fileno(), cb) continue elif isinstance(ret, IOWrite): # self.add_writer(arg.fileno(), lambda cb: self.call_soon(cb), cb) self.add_writer(arg.fileno(), cb) continue elif isinstance(ret, IOReadDone): self.remove_reader(arg.fileno()) elif isinstance(ret, IOWriteDone): self.remove_writer(arg.fileno()) elif isinstance(ret, StopLoop): return arg elif isinstance(ret, type_gen): self.call_soon(ret) elif ret is None: # Just reschedule pass else: assert False, "Unsupported coroutine yield value: %r (of type %r)" % (ret, type(ret)) except StopIteration as e: if __debug__: log.debug("Coroutine finished: %s", cb) continue self.call_later(delay, cb, *args)
def play_audio(self): if self.queue_data is None: return False try: # dequeue a data data = heapq.heappop(self.queue_data) print("pop {}".format(len(data))) # TODO: play data except: #print("play_audio exception ") return False return True
def process_configuration(): configuration = uheapq.heappop(heap) sensors = [] for item in configuration["sensors"]: # string name_type = item["name_type"] # integer sampling_frequency = int(item["sampling_frequency"]) # array microcontroller_pins = item["microcontroller_pins"] # array field_name = item["field_name"] # array data_type = item["data_type"] # sensor type sensor_type = name_type[name_type.index("(") + 1:name_type.rindex(")")] if sensor_type == "BUTTON": sensor = Button_LED(name_type, sampling_frequency, microcontroller_pins, field_name, data_type) sensors.append(sensor) if sensor_type == "DHT11": sensor = Temperature_Humidity(name_type, sampling_frequency, microcontroller_pins, field_name, data_type) sensors.append(sensor) if sensor_type == "ACCELEROMETER": sensor = Accelerometer(name_type, sampling_frequency, microcontroller_pins, field_name, data_type) sensors.append(sensor) if sensor_type == "PH": sensor = Ph(name_type, sampling_frequency, microcontroller_pins, field_name, data_type) sensors.append(sensor) return sensors
try: import uheapq as heapq except: try: import heapq except ImportError: import sys print("SKIP") sys.exit() try: heapq.heappop([]) except IndexError: print("IndexError") try: heapq.heappush((), 1) except TypeError: print("TypeError") def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) print(' '.join(l)) h = [] heapq.heappush(h, 3) heapq.heappush(h, 1)
def move_train(t): global head, tail if head == 0: print(f'move = {time.monotonic():.2f}') PIXELS[head] = BLUE PIXELS[tail] = BLACK head = (head + DIRECTION) % 10 tail = (tail + DIRECTION) % 10 uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, move_train)) def blink_on(t): print(f'blink_on: {time.monotonic():.2f}') RED_LED.value = True uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, blink_off)) def blink_off(t): RED_LED.value = False uheapq.heappush(EVENT_QUEUE, (t + 900 * MILLISECOND, blink_on)) start = time.monotonic_ns() uheapq.heappush(EVENT_QUEUE, (start + SECOND, move_train)) uheapq.heappush(EVENT_QUEUE, (start + SECOND + 1, blink_on)) while EVENT_QUEUE: t, fn = uheapq.heappop(EVENT_QUEUE) time.sleep(max((t - time.monotonic_ns()) / SECOND, 0)) fn(t)
def run_forever(self): while True: if self.q: t, cnt, cb, args = heapq.heappop(self.q) if __debug__: log.debug("Next coroutine to run: %s", (t, cnt, cb, args)) # __main__.mem_info() tnow = self.time() delay = t - tnow if delay > 0: self.wait(delay) else: self.wait(-1) # Assuming IO completion scheduled some tasks continue if callable(cb): cb(*args) else: delay = 0 try: if args == (): args = (None, ) if __debug__: log.debug("Coroutine %s send args: %s", cb, args) ret = cb.send(*args) if __debug__: log.debug("Coroutine %s yield result: %s", cb, ret) if isinstance(ret, SysCall1): arg = ret.arg if isinstance(ret, Sleep): delay = arg elif isinstance(ret, IORead): # self.add_reader(ret.obj.fileno(), lambda self, c, f: self.call_soon(c, f), self, cb, ret.obj) # self.add_reader(ret.obj.fileno(), lambda c, f: self.call_soon(c, f), cb, ret.obj) # self.add_reader(arg.fileno(), lambda cb: self.call_soon(cb), cb) self.add_reader(arg.fileno(), cb) continue elif isinstance(ret, IOWrite): # self.add_writer(arg.fileno(), lambda cb: self.call_soon(cb), cb) self.add_writer(arg.fileno(), cb) continue elif isinstance(ret, IOReadDone): self.remove_reader(arg.fileno()) elif isinstance(ret, IOWriteDone): self.remove_writer(arg.fileno()) elif isinstance(ret, StopLoop): return arg elif isinstance(ret, type_gen): self.call_soon(ret) elif ret is None: # Just reschedule pass else: assert False, "Unsupported coroutine yield value: %r (of type %r)" % ( ret, type(ret)) except StopIteration as e: if __debug__: log.debug("Coroutine finished: %s", cb) continue self.call_later(delay, cb, *args)
def run_forever(self): self.idle_us = 0 t0_ms = pyb.millis() while True: if self.q: t, cnt, cb, args = heapq.heappop(self.q) if __debug__: log.debug("Next coroutine to run: %s", (t, cnt, cb, args)) # __main__.mem_info() tnow = self.time() delay = t - tnow if delay > 0: self.wait(delay) else: self.wait(-1) # Assuming IO completion scheduled some tasks continue if callable(cb): cb(*args) else: delay = 0 try: if args == (): args = (None, ) if __debug__: log.debug("Coroutine %s send args: %s", cb, args) ret = cb.send(*args) if __debug__: log.debug("Coroutine %s yield result: %s", cb, ret) if isinstance(ret, SysCall): arg = ret.args[0] if isinstance(ret, Sleep): delay = arg elif isinstance(ret, IORead): # self.add_reader(ret.obj.fileno(), lambda self, c, f: self.call_soon(c, f), self, cb, ret.obj) # self.add_reader(ret.obj.fileno(), lambda c, f: self.call_soon(c, f), cb, ret.obj) self.add_reader( arg.fileno(), lambda cb, f: self.call_soon(cb, f), cb, arg) continue elif isinstance(ret, IOWrite): self.add_writer( arg.fileno(), lambda cb, f: self.call_soon(cb, f), cb, arg) continue elif isinstance(ret, IOReadDone): self.remove_reader(arg.fileno()) elif isinstance(ret, IOWriteDone): self.remove_writer(arg.fileno()) # EXPERIMENTAL elif isinstance(ret, GetRunningCoro): args = [cb] elif isinstance(ret, GetRunningLoop): args = [self] elif isinstance(ret, BlockUntilDone): if __debug__: log.debug('BlockUntilDone(%s)', repr(ret.args)) #if not hasattr(ret.args[0], 'clear_unblocking_callbacks'): # raise NotImplementedError("BlockUntilDone only on a future") handle = None # assume a Future instance assert hasattr(ret.args[0], 'clear_unblocking_callback') fut = ret.args[0] tl = None if len(ret.args) > 1: timeout = ret.args[1] #if timeout and timeout > 0: if timeout is not None: tl = [] fto = self.future_timeout_closure( cb, fut, tl) #print("fto", fto, end=' ') handle = self.call_later(timeout, fto) fcb = self.future_callback_closure(cb, handle) #print("fcb", fcb, end=' ') arg.add_unblocking_callback(fcb) #print("ubcbs", arg.ubcbs) if tl is not None: tl.append(fcb) #print("tl", tl) continue # end EXPERIMENTAL elif isinstance(ret, StopLoop): self.d_ms = pyb.elapsed_millis(t0_ms) return arg elif isinstance(ret, type_gen): self.call_soon(ret) elif ret is None: # Just reschedule pass else: assert False, "Unsupported coroutine yield value: %r (of type %r)" % ( ret, type(ret)) except StopIteration as e: if __debug__: log.debug("Coroutine finished: %s", cb) continue self.call_later(delay, cb, *args)
def dprint(*v): pass # Try not to crash on invalid data h = [] heapq.heappush(h, 1) try: heapq.heappush(h, 2, True) assert False except TypeError: pass heapq.heappush(h, 2) try: heapq.heappop(h, True) assert False except TypeError: pass def pop_all(h): l = [] while h: l.append(heapq.heappop(h, True)) dprint(l) return l def add(h, v): heapq.heappush(h, (v, None), True)
try: import uheapq as heapq except: try: import heapq except ImportError: print("SKIP") raise SystemExit try: heapq.heappop([]) except IndexError: print("IndexError") try: heapq.heappush((), 1) except TypeError: print("TypeError") def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) print(' '.join(l)) h = [] heapq.heappush(h, 3) heapq.heappush(h, 1) heapq.heappush(h, 2) print(h) pop_and_print(h)
def pop_all(h): l = [] while h: l.append(heapq.heappop(h, True)) dprint(l) return l
else: def dprint(*v): pass # Try not to crash on invalid data h = [] heapq.heappush(h, 1) try: heapq.heappush(h, 2, True) assert False except TypeError: pass heapq.heappush(h, 2) try: heapq.heappop(h, True) assert False except TypeError: pass def pop_all(h): l = [] while h: l.append(heapq.heappop(h, True)) dprint(l) return l def add(h, v): heapq.heappush(h, (v, None), True)
def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) print(' '.join(l))
def kmain(server=SERVER): global sub_flag, i_pum, i_snd, i_data f_snd = 0 c = MQTTClient(CLIENT_ID, server) try: hello_i = ESP_init(DATA_TP) c.connect() c.publish(TOPIC, hello_i, retain=True, qos=1) sleep_ms(10) c.disconnect() sleep_ms(50) c.connect() c.set_last_will(DATA_TP, b"<Connect_lost>", retain=True, qos=1) sleep_ms(10) c.publish(DATA_TP, b"<Data_begin>", retain=True, qos=1) sleep_ms(10) gc.collect() while sub_flag != 404: foobar = Foo() f_snd = 0 while button.value() != 0 and sub_flag == 100: try: if f_snd == 0 or i_pum - i_snd > 60: str_data = uheapq.heappop(i_data) try: c.publish(DATA_TP, str_data, retain=True, qos=1) sleep_ms(10) f_snd = 0 i_snd += 1 except: f_snd += 1 gc.collect() if f_snd > 30: sub_flag = 104 else: try: c.connect() sleep_ms(200) except: try: import boot except: pass sleep_ms(200) pass pass except: i_snd = i_pum sleep_ms(10) pass if sub_flag == 104: sub_flag = 404 raise sleep_ms(50) if button.value() == 0 and sub_flag == 101: sleep_ms(2000) if button.value() == 0: sub_flag = 100 sleep_ms(2000) if button.value() == 0 and sub_flag == 100: sleep_ms(2000) if button.value() == 0: sub_flag = 101 sleep_ms(2000) except: pass finally: try: del foobar except: pass c.publish(DATA_TP, b"<Data_end>", retain=True, qos=1) sleep_ms(50) c.disconnect() raise
def get_command(self): if len(self.queue): return uheapq.heappop(self.queue) return None