Python源码示例:queue.LifoQueue()
示例1
def test_subscribe_transactions(self, alice):
gen_and_sync_lnd(alice.bitcoin, [alice])
subscription = alice.subscribe_transactions()
alice.add_funds(alice.bitcoin, 1)
assert isinstance(subscription, grpc._channel._Rendezvous)
assert isinstance(subscription.__next__(), rpc_pb2.Transaction)
# gen_and_sync_lnd(alice.bitcoin, [alice])
# transaction_updates = queue.LifoQueue()
#
# def sub_transactions():
# try:
# for response in alice.subscribe_transactions():
# transaction_updates.put(response)
# except StopIteration:
# pass
#
# alice_sub = threading.Thread(target=sub_transactions(), daemon=True)
# alice_sub.start()
# time.sleep(1)
# while not alice_sub.is_alive():
# time.sleep(0.1)
# alice.add_funds(alice.bitcoin, 1)
#
# assert any(isinstance(update) == rpc_pb2.Transaction for update in get_updates(transaction_updates))
示例2
def test_subscribe_channel_events(self, bitcoind, bob, carol):
bob, carol = setup_nodes(bitcoind, [bob, carol])
gen_and_sync_lnd(bitcoind, [bob, carol])
chan_updates = queue.LifoQueue()
def sub_channel_events():
try:
for response in bob.subscribe_channel_events():
chan_updates.put(response)
except grpc._channel._Rendezvous:
pass
bob_sub = threading.Thread(target=sub_channel_events, daemon=True)
bob_sub.start()
time.sleep(1)
while not bob_sub.is_alive():
time.sleep(0.1)
channel_point = bob.list_channels()[0].channel_point
bob.close_channel(channel_point=channel_point).__next__()
generate(bitcoind, 3)
gen_and_sync_lnd(bitcoind, [bob, carol])
assert any(
update.closed_channel is not None for update in get_updates(chan_updates)
)
示例3
def find_index(self, value, starting_node=0):
"""Find the index of the first node that matches value in a BFS
Performs a breadth-first search of the graph starting at node index
starting_node. Returns the index or None if no match is found
Args:
value(Node Value) - Value to match against in the graph
starting_node(int) - Node index to start search from
"""
if starting_node > self.node_count():
raise IndexError("Node ID out of range.")
node_queue = queue.LifoQueue()
node_queue.put(starting_node)
visited = [starting_node]
while not node_queue.empty():
next_id = node_queue.get()
if (self.nodes[next_id].value == value):
return next_id # Success
for uid in self.neighbors[next_id]:
if (self.uid_to_index[uid] not in visited):
node_queue.put(self.uid_to_index[uid])
visited += [self.uid_to_index[uid]]
return None
示例4
def ispar(s):
# code here
import queue
stack = queue.LifoQueue()
for i in range(len(s)):
if ((s[i] == '{') | (s[i] == '[') | (s[i] == '(')):
stack.put(s[i])
if ((s[i] == '}') | (s[i] == ']') | (s[i] == ')')):
if stack.empty():
return False
elif not isMatchingPair(stack.get(),s[i]):
return False
if stack.empty():
return True
else:
return False
示例5
def __init__(self, host=DEFAULT_LISTEN_HOST, port=DEFAULT_LISTEN_PORT, ssl_context: Optional[SSLContext] = None,
default_waiting_settings: Optional[WaitingSettings] = None):
"""
Initializes the instance.
"""
self.host = host
self.port = port
self.server = None
self.server_thread = None
self.assertions = []
self.log = []
self.ordered_handlers = []
self.oneshot_handlers = RequestHandlerList()
self.handlers = RequestHandlerList()
self.permanently_failed = False
self.ssl_context = ssl_context
if default_waiting_settings is not None:
self.default_waiting_settings = default_waiting_settings
else:
self.default_waiting_settings = WaitingSettings()
self._waiting_settings = copy(self.default_waiting_settings)
self._waiting_result = queue.LifoQueue(maxsize=1)
示例6
def __init__(self):
super().__init__()
self._handling_lock = Lock()
self._teardown_callback_stack = LifoQueue() # we execute callbacks in the reverse order that they were added
self._logger = log.get_logger(__name__)
self._handled_exceptions = Queue()
self._teardown_callback_raised_exception = False
# Set up handlers to be called when the application process receives certain signals.
# Note: this will raise if called on a non-main thread, but we should NOT work around that here. (That could
# prevent the teardown handler from ever being registered!) Calling code should be organized so that this
# singleton is only ever initialized on the main thread.
signal.signal(signal.SIGTERM, self._application_teardown_signal_handler)
signal.signal(signal.SIGINT, self._application_teardown_signal_handler)
try:
signal.signal(process_utils.SIGINFO, self._application_info_dump_signal_handler)
except ValueError:
self._logger.warning('Failed to register signal handler for SIGINFO. This is expected if ClusterRunner '
'is running on Windows.')
示例7
def __init__(self, mode):
self.mode = mode
self.conf = capture_conf.env[mode]
self.init_sources(self.conf.source_paths)
self.detector = Predict.instance()
self.trackers = [Tracker(nn_matching.NearestNeighborDistanceMetric("cosine", self.conf.track_max_cosine_distance, self.conf.track_nn_budget),
max_iou_distance=self.conf.track_max_iou_distance,
max_age=self.conf.track_max_age,
n_init=self.conf.track_n_init)
for _ in self.sources_parsed]
self.track_pool = new_pools(self.conf.pool_size)
self.save_pool = new_pools(self.conf.pool_size)
self.frame_index = 0
self.video_state = False
if self.conf.video_on:
self.box_queue = queue.LifoQueue(100)
if self.conf.is_async:
submit(self.video_on)
self.debug = mode == 'dev'
if self.debug:
self.last_time = datetime.now()
self.fps = 0
self.pids = set()
示例8
def __init__(self, dataloder, batchSize=1, queueSize=1024):
# initialize the file video stream along with the boolean
# used to indicate if the thread should be stopped or not
self.det_model = Darknet("yolo/cfg/yolov3-spp.cfg")
self.det_model.load_weights('models/yolo/yolov3-spp.weights')
self.det_model.net_info['height'] = opt.inp_dim
self.det_inp_dim = int(self.det_model.net_info['height'])
assert self.det_inp_dim % 32 == 0
assert self.det_inp_dim > 32
self.det_model.cuda()
self.det_model.eval()
self.stopped = False
self.dataloder = dataloder
self.batchSize = batchSize
# initialize the queue used to store frames read from
# the video file
self.Q = LifoQueue(maxsize=queueSize)
示例9
def __init__(self, webcam = 0, batchSize=1, queueSize=256):
# initialize the file video stream along with the boolean
# used to indicate if the thread should be stopped or not
self.det_model = Darknet("yolo/cfg/yolov3-spp.cfg")
self.det_model.load_weights('models/yolo/yolov3-spp.weights')
self.det_model.net_info['height'] = opt.inp_dim
self.det_inp_dim = int(self.det_model.net_info['height'])
assert self.det_inp_dim % 32 == 0
assert self.det_inp_dim > 32
self.det_model.cuda()
self.det_model.eval()
self.stream = cv2.VideoCapture(int(webcam))
assert self.stream.isOpened(), 'Cannot open webcam'
self.stopped = False
self.batchSize = batchSize
# initialize the queue used to store frames read from
# the video file
self.Q = LifoQueue(maxsize=queueSize)
示例10
def test_subscribe_invoices(self, alice):
"""
Invoice subscription run as a thread
"""
gen_and_sync_lnd(alice.bitcoin, [alice])
invoice_updates = queue.LifoQueue()
def sub_invoices():
try:
for response in alice.subscribe_invoices():
invoice_updates.put(response)
except grpc._channel._Rendezvous:
pass
alice_sub = threading.Thread(target=sub_invoices, daemon=True)
alice_sub.start()
time.sleep(1)
while not alice_sub.is_alive():
time.sleep(0.1)
alice.add_invoice(value=SEND_AMT)
alice.daemon.wait_for_log("AddIndex")
time.sleep(0.1)
assert any(
isinstance(update, rpc_pb2.Invoice)
for update in get_updates(invoice_updates)
)
示例11
def __init__(self, configs, stopper: threading.Event):
super().__init__()
self.configs = configs
self.stopper = stopper
self.input_q = LifoQueue()
self.output_q = LifoQueue()
示例12
def removePair(s):
# code here
import queue
stack = queue.LifoQueue()
r = ''
stack.put(s[0])
for i in range(1,len(s)):
if stack.empty():
stack.put(s[i])
else:
f = stack.get()
if f != s[i]:
stack.put(f)
stack.put(s[i])
else:
stack.put(f)
g = stack.get()
if g == s[i]:
pass
while (stack.empty() is not True):
x = stack.get()
r = x + r
if r != '':
return r
else:
return "Empty String"
示例13
def _create_session_pool(self):
# Create a pool to reuse sessions containing connections to the server
session_pool = LifoQueue()
for _ in range(self._session_pool_size):
session_pool.put(self.create_session(), block=False)
return session_pool
示例14
def __iter__(self):
stack = LifoQueue()
for element in self._iterable:
stack.put(element)
while not stack.empty():
yield stack.get()
示例15
def __init__(self, playerManager):
self.playerManager = playerManager
self.is_menu_shown = False
self.menu_title = ""
self.menu_stack = LifoQueue()
self.menu_list = []
self.menu_selection = 0
self.menu_tmp = None
self.original_osd_color = playerManager._player.osd_back_color
self.original_osd_size = playerManager._player.osd_font_size
# The menu is a bit of a hack...
# It works using multiline OSD.
# We also have to force the window to open.
示例16
def __init__(self):
self.db = Database(MONGODB)
self.ID_queue = queue.LifoQueue()
示例17
def __init__(self, sources_parsed, max_queue_size=5):
procs, queues, shape = [], [], []
for source in sources_parsed:
shape.append((int(source.h), int(source.w), 3))
if source.url.startswith("rtsp"):
procs.append(sp.Popen(['ffmpeg',
'-loglevel', 'error',
'-hwaccel', 'cuvid',
'-c:v', 'h264_cuvid',
'-rtsp_transport', 'tcp',
'-i', os.path.expanduser(source.url),
'-vf', 'hwdownload,format=nv12',
'-c:v', 'rawvideo',
'-f', 'rawvideo',
'-pix_fmt', 'bgr24',
'pipe:1'], stdin=sp.PIPE, stdout=sp.PIPE, shell=False, bufsize=int(source.h) * int(source.w) * 3 * 10))
else:
procs.append(sp.Popen(['ffmpeg',
'-loglevel', 'error',
'-hwaccel', 'cuvid',
'-c:v', 'h264_cuvid',
'-re',
'-i', os.path.expanduser(source.url),
'-vf', 'hwdownload,format=nv12',
'-c:v', 'rawvideo',
'-f', 'rawvideo',
'-pix_fmt', 'bgr24',
'pipe:1'], stdin=sp.PIPE, stdout=sp.PIPE, shell=False, bufsize=int(source.h) * int(source.w) * 3 * 10))
queues.append(queue.LifoQueue(max_queue_size))
self.shape = shape
self.procs = procs
self.queues = queues
submit(self.source_queue, self.procs, self.queues)
示例18
def __init__(self, webcam, batchSize=1, queueSize=256):
# initialize the file video stream along with the boolean
# used to indicate if the thread should be stopped or not
self.stream = cv2.VideoCapture(int(webcam))
assert self.stream.isOpened(), 'Cannot capture source'
self.stopped = False
# initialize the queue used to store frames read from
# the video file
self.batchSize = batchSize
self.Q = LifoQueue(maxsize=queueSize)
示例19
def __init__(self, detectionLoader, queueSize=1024):
# initialize the file video stream along with the boolean
# used to indicate if the thread should be stopped or not
self.detectionLoader = detectionLoader
self.stopped = False
# initialize the queue used to store data
self.Q = LifoQueue(maxsize=queueSize)
示例20
def __init__(self, webcam, queueSize=256):
# initialize the file video stream along with the boolean
# used to indicate if the thread should be stopped or not
self.stream = cv2.VideoCapture(int(webcam))
assert self.stream.isOpened(), 'Cannot capture source'
self.stopped = False
# initialize the queue used to store frames read from
# the video file
self.Q = LifoQueue(maxsize=queueSize)
示例21
def test_all_invoice(self, bitcoind, bob, carol):
bob, carol = setup_nodes(bitcoind, [bob, carol])
_hash, preimage = random_32_byte_hash()
invoice_queue = queue.LifoQueue()
invoice = carol.add_hold_invoice(
memo="pytest hold invoice", hash=_hash, value=SEND_AMT
)
decoded_invoice = carol.decode_pay_req(pay_req=invoice.payment_request)
assert isinstance(invoice, invoices_pb2.AddHoldInvoiceResp)
# thread functions
def inv_sub_worker(_hash):
try:
for _response in carol.subscribe_single_invoice(_hash):
invoice_queue.put(_response)
except grpc._channel._Rendezvous:
pass
def pay_hold_inv_worker(payment_request):
try:
bob.pay_invoice(payment_request=payment_request)
except grpc._channel._Rendezvous:
pass
def settle_inv_worker(_preimage):
try:
carol.settle_invoice(preimage=_preimage)
except grpc._channel._Rendezvous:
pass
# setup the threads
inv_sub = threading.Thread(
target=inv_sub_worker, name="inv_sub", args=[_hash], daemon=True
)
pay_inv = threading.Thread(
target=pay_hold_inv_worker, args=[invoice.payment_request]
)
settle_inv = threading.Thread(target=settle_inv_worker, args=[preimage])
# start the threads
inv_sub.start()
# wait for subscription to start
while not inv_sub.is_alive():
time.sleep(0.1)
pay_inv.start()
time.sleep(2)
# carol.daemon.wait_for_log(regex=f'Invoice({decoded_invoice.payment_hash}): accepted,')
settle_inv.start()
while settle_inv.is_alive():
time.sleep(0.1)
inv_sub.join(timeout=1)
assert any(invoice.settled is True for invoice in get_updates(invoice_queue))
示例22
def shortest_path(self, node_id1, node_id2):
"""Find the shortest path between node1 and node2 on the graph
Args:
node_id1(int): Index of first node
node_id2(int): Index of second node
Returns(list): List of nodes from node_id1 to node_id2 that constitute
the shortest possible path in the graph between those two nodes.
"""
if node_id1 >= self.node_count() or node_id2 >= self.node_count():
raise IndexError("Node ID out of range for graph")
# Treat special case of equal inputs
if node_id1 == node_id2:
return [node_id1]
# Initialize two arrays for backtracking the shortest path found
previous = [None] * self.node_count() # Tracks the moves
distances = [None] * self.node_count() # Records distance to nodes
distances[node_id1] = 0
node_queue = queue.LifoQueue()
node_queue.put(node_id1)
while not node_queue.empty():
next_id = node_queue.get()
if next_id == node_id2:
break # Success
new_distance = distances[next_id] + 1
# On each iteration, check if going to a neighbor node was
# shortest path to that node, if so, add that node to the queue
# and record distance and path that is being taken.
for uid in self.neighbors[next_id]:
if ((distances[self.uid_to_index[uid]] is None) or
(distances[self.uid_to_index[uid]] > new_distance)):
distances[self.uid_to_index[uid]] = new_distance
previous[self.uid_to_index[uid]] = next_id
node_queue.put(self.uid_to_index[uid])
# Backtrack to get path
if previous[node_id2] is None:
raise IndexError("Unable to find target node, "
"possibly disconnected graph.")
path = []
next = node_id2
while next is not None:
path.append(next)
next = previous[next]
# Return reversed backtrack path to get in order from node 1 to 2
return path[::-1]
示例23
def simple_queue_test(self, q):
if q.qsize():
raise RuntimeError("Call this function with an empty queue")
self.assertTrue(q.empty())
self.assertFalse(q.full())
# I guess we better check things actually queue correctly a little :)
q.put(111)
q.put(333)
q.put(222)
target_order = dict(Queue = [111, 333, 222],
LifoQueue = [222, 333, 111],
PriorityQueue = [111, 222, 333])
actual_order = [q.get(), q.get(), q.get()]
self.assertEqual(actual_order, target_order[q.__class__.__name__],
"Didn't seem to queue the correct data!")
for i in range(QUEUE_SIZE-1):
q.put(i)
self.assertTrue(q.qsize(), "Queue should not be empty")
self.assertTrue(not qfull(q), "Queue should not be full")
last = 2 * QUEUE_SIZE
full = 3 * 2 * QUEUE_SIZE
q.put(last)
self.assertTrue(qfull(q), "Queue should be full")
self.assertFalse(q.empty())
self.assertTrue(q.full())
try:
q.put(full, block=0)
self.fail("Didn't appear to block with a full queue")
except queue.Full:
pass
try:
q.put(full, timeout=0.01)
self.fail("Didn't appear to time-out with a full queue")
except queue.Full:
pass
# Test a blocking put
self.do_blocking_test(q.put, (full,), q.get, ())
self.do_blocking_test(q.put, (full, True, 10), q.get, ())
# Empty it
for i in range(QUEUE_SIZE):
q.get()
self.assertTrue(not q.qsize(), "Queue should be empty")
try:
q.get(block=0)
self.fail("Didn't appear to block with an empty queue")
except queue.Empty:
pass
try:
q.get(timeout=0.01)
self.fail("Didn't appear to time-out with an empty queue")
except queue.Empty:
pass
# Test a blocking get
self.do_blocking_test(q.get, (), q.put, ('empty',))
self.do_blocking_test(q.get, (True, 10), q.put, ('empty',))
示例24
def __init__(self, args):
self.target_domain = args.domain
self.cname_flag = args.cname
if not (self.target_domain):
print('usage: brutedns.py -h')
sys.exit(1)
self.check_env()
self.level = args.level
self.sub_dict = args.sub_file
self.speed = args.speed
self.default_dns = True if args.default_dns is "y" else False
self.next_sub_dict = args.next_sub_file
self.other_result = args.other_file
self.timeout = 10
self.resolver = dns.resolver.Resolver(configure=self.default_dns)
self.resolver.lifetime = self.timeout
self.resolver.timeout = self.timeout
self.found_count = 0
self.next_found_count = 0
self.cmdline = ""
self.queues = LifoQueue()
self.queue_sub = Queue()
self.cdn_set = set()
self.cname_set = set()
self.white_filter_subdomain = set()
self.cname_block_dict = dict()
self.ip_block_dict = dict()
self.ip_all_dict = dict()
self.ip_flag_dict = dict()
self.active_ip_dict = dict()
self.ip_count_dict = dict()
self.black_ip = set()
self.set_next_sub = self.load_next_sub_dict()
self.set_cdn = self.load_cdn()
self.load_sub_dict_to_queue()
self.extract_next_sub_log()
self.segment_num = self.judge_speed(self.speed)
if not self.default_dns:
self.nameservers = self.load_nameservers()
self.check_nameservers()
示例25
def simple_queue_test(self, q):
if q.qsize():
raise RuntimeError("Call this function with an empty queue")
self.assertTrue(q.empty())
self.assertFalse(q.full())
# I guess we better check things actually queue correctly a little :)
q.put(111)
q.put(333)
q.put(222)
target_order = dict(Queue = [111, 333, 222],
LifoQueue = [222, 333, 111],
PriorityQueue = [111, 222, 333])
actual_order = [q.get(), q.get(), q.get()]
self.assertEqual(actual_order, target_order[q.__class__.__name__],
"Didn't seem to queue the correct data!")
for i in range(QUEUE_SIZE-1):
q.put(i)
self.assertTrue(q.qsize(), "Queue should not be empty")
self.assertTrue(not qfull(q), "Queue should not be full")
last = 2 * QUEUE_SIZE
full = 3 * 2 * QUEUE_SIZE
q.put(last)
self.assertTrue(qfull(q), "Queue should be full")
self.assertFalse(q.empty())
self.assertTrue(q.full())
try:
q.put(full, block=0)
self.fail("Didn't appear to block with a full queue")
except queue.Full:
pass
try:
q.put(full, timeout=0.01)
self.fail("Didn't appear to time-out with a full queue")
except queue.Full:
pass
# Test a blocking put
self.do_blocking_test(q.put, (full,), q.get, ())
self.do_blocking_test(q.put, (full, True, 10), q.get, ())
# Empty it
for i in range(QUEUE_SIZE):
q.get()
self.assertTrue(not q.qsize(), "Queue should be empty")
try:
q.get(block=0)
self.fail("Didn't appear to block with an empty queue")
except queue.Empty:
pass
try:
q.get(timeout=0.01)
self.fail("Didn't appear to time-out with an empty queue")
except queue.Empty:
pass
# Test a blocking get
self.do_blocking_test(q.get, (), q.put, ('empty',))
self.do_blocking_test(q.get, (True, 10), q.put, ('empty',))
示例26
def simple_queue_test(self, q):
if q.qsize():
raise RuntimeError("Call this function with an empty queue")
self.assertTrue(q.empty())
self.assertFalse(q.full())
# I guess we better check things actually queue correctly a little :)
q.put(111)
q.put(333)
q.put(222)
target_order = dict(Queue = [111, 333, 222],
LifoQueue = [222, 333, 111],
PriorityQueue = [111, 222, 333])
actual_order = [q.get(), q.get(), q.get()]
self.assertEqual(actual_order, target_order[q.__class__.__name__],
"Didn't seem to queue the correct data!")
for i in range(QUEUE_SIZE-1):
q.put(i)
self.assertTrue(q.qsize(), "Queue should not be empty")
self.assertTrue(not qfull(q), "Queue should not be full")
last = 2 * QUEUE_SIZE
full = 3 * 2 * QUEUE_SIZE
q.put(last)
self.assertTrue(qfull(q), "Queue should be full")
self.assertFalse(q.empty())
self.assertTrue(q.full())
try:
q.put(full, block=0)
self.fail("Didn't appear to block with a full queue")
except queue.Full:
pass
try:
q.put(full, timeout=0.01)
self.fail("Didn't appear to time-out with a full queue")
except queue.Full:
pass
# Test a blocking put
self.do_blocking_test(q.put, (full,), q.get, ())
self.do_blocking_test(q.put, (full, True, 10), q.get, ())
# Empty it
for i in range(QUEUE_SIZE):
q.get()
self.assertTrue(not q.qsize(), "Queue should be empty")
try:
q.get(block=0)
self.fail("Didn't appear to block with an empty queue")
except queue.Empty:
pass
try:
q.get(timeout=0.01)
self.fail("Didn't appear to time-out with an empty queue")
except queue.Empty:
pass
# Test a blocking get
self.do_blocking_test(q.get, (), q.put, ('empty',))
self.do_blocking_test(q.get, (True, 10), q.put, ('empty',))