本文整理汇总了Python中queue.PriorityQueue.empty方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.empty方法的具体用法?Python PriorityQueue.empty怎么用?Python PriorityQueue.empty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类queue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TicketSystem
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
class TicketSystem(object):
def __init__(self, seconds_between_requests):
self.seconds_between_requests = seconds_between_requests
self.queue = PriorityQueue()
self.lock = Lock()
def get_ticket(self, priority):
with self.lock:
if self.queue.empty():
self.start_thread()
event = Event()
# the tiebreaker makes sure the __lt__ operator on event is never
# called by PriorityQueue, since it doesn't have one.
tiebreaker = id(event)
self.queue.put((priority + time.time(), tiebreaker, event))
event.wait()
def start_thread(self):
self.thread = Thread(target=self.run, args=())
self.thread.start()
def run(self):
while True:
time.sleep(self.seconds_between_requests)
with self.lock:
(timeout, tiebreaker, event) = self.queue.get(True)
if timeout <= time.time():
event.set()
else:
self.queue.put((timeout, tiebreaker, event))
if self.queue.empty():
return
示例2: HeapMultiSet
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
class HeapMultiSet(object):
def __init__(self, prioritizer):
self.prioritizer = prioritizer
self.heap = PriorityQueue()
self.counts = {}
self.length = 0
def offer(self, value):
# Add the value to the heap if it does not exist yet.
if (value not in self.counts or self.counts[value] <= 0):
# Calculate a priority for the value
priority = self.prioritizer(value)
self.heap.put((priority, value))
# Track the count of the value
self.counts[value] = 0
self.counts[value] += 1
# Update the size of the heap
self.length += 1
def peek(self):
if (self.heap.empty()):
return None
(priority, value) = self.heap.queue[0]
return value
def remove(self, value):
if (not self.contains(value)):
return False
if (self.counts[value] > 0):
self.length -= 1
self.counts[value] = self.counts[value] - 1
self.fix_top()
return True
def pop(self):
if (self.heap.empty()):
return None
value = self.peek()
if (self.counts[value] > 0):
self.counts[value] -= 1
self.length -= 1
self.fix_top()
return value
def fix_top(self):
while (not self.heap.empty()):
(priority, value) = self.heap.queue[0]
if (self.counts[value] > 0):
break
self.heap.get()
def contains(self, value):
return value in self.counts and self.counts[value] > 0
def __len__(self):
return self.length
示例3: main
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def main():
global CREATURE_COUNT
if process_targeting_form():
c0 = []
c1 = PriorityQueue()
result_out('[+]\tLoading DB...')
#load in creatures from DB
lc = load_DB()
loaded_creatures = lc.split('\n')
#finish loading
result_out('[+]\tSuccess')
result_out('[+]\tCreating initial batch of creatures...')
cl = create_creatures(CREATURE_COUNT, GENOME_LENGTH, tools)
generation = 0
for i in cl:
c1.put((100, i))
for i in loaded_creatures:
c1.put((50, Creature(0, i)))
for ii in range(0, GENE_POOL_INFLUENCE-1):
c1.put((50, Creature(0, mutate(i))))
result_out('[+]\tSuccess')
result_out('[+]\tPre-breeding in loaded creatures with the population for great success')
while not c1.empty():
c = c1.get()[1]
c0.append(c)
c1 = breed_it(c0)
c1 = c0
result_out('[+]\tSuccess')
exploit_found = 0
while exploit_found == 0 and c1.qsize() > 0::
generation += 1
CREATURE_COUNT = c1.qsize()
result_out('[>]\tRunning with creature_count %d,\tgeneration %d' % (CREATURE_COUNT, generation))
c2 = PriorityQueue(0)
cached_c = 0
total_c = 0
while not c1.empty():
c = c1.get()[1]
total_c += 1
if c.modified == 0:
cached_c += 1
if fitnessfunction(c) == 1:
exploit_found = 1
break
c2.put((c.score, c))
result_out('[i]\tEfficiency %s, cached[%d], total[%d]' % (str((total_c-cached_c) * 1.0 / total_c),cached_c,total_c))
c3 = cull_it(c2)
c4 = []
while not c3.empty():
c = c3.get()[1]
c4.append(c)
c1 = breed_it(c4)
if exploit_found > 0:
result_out('[i]\tExploit found in %d seconds with %d requests' % (abs(int(start_time - time.time())), REQ_TOTAL))
else:
result_out('No exploits found')
示例4: getREF
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def getREF(self):
#used to make sure that each each vector in priority queue is a unique instance
#Using a tuple to make priorities in the queue b/c there are too
#many ways to naturally sort vectors and subclassing seemed like overkill
#First tiebreaker is the pivot location
#Next tiebreaker is "qId" which is basically the order it entered the queue
def nextQId():
nextQId.id = nextQId.id+1
return nextQId.id
nextQId.id = 0
#These methods have to do with the PriorityQueue
#The first converts the vector to a tuple so that the priority queue can sort by the pivot
#The second converts from this tuple back to vector form
def qForm(vec):
if vec.firstNonZeroLoc() is not None:
return (vec.firstNonZeroLoc(),nextQId(),vec)
else:
return vec.getDimension()+1,nextQId(),vec
def vecForm(tup):
return tup[2]
q = PriorityQueue()
for row in self.rows:
q.put_nowait(qForm(row))
finishedVecs = []
while not q.empty():
topVec = vecForm(q.get_nowait())
if q.empty(): #top Vec was the last one
finishedVecs.append(topVec)
break
#can't use zero vector to subtract stuff out
#Additionally, this means all remaining vectors are zero vectors
elif topVec.firstNonZeroLoc() is None:
finishedVecs.append(topVec)
else:
nextVec = vecForm(q.get_nowait())
#While there are vectors w/ same pivot, subtract them
while nextVec is not None and nextVec.firstNonZeroLoc() == topVec.firstNonZeroLoc():
subNextVec = nextVec - topVec*(nextVec.firstNonZeroVal()//topVec.firstNonZeroVal())
q.put_nowait(qForm(subNextVec))
nextVec = vecForm(q.get_nowait()) #Have to put in queue to make sure we don't skip any w/ same pivot
if nextVec is not None: #got out of loop b/c pivot position didn't math. There is probably a cleaner way to do this
q.put_nowait(qForm(nextVec))
finishedVecs.append(topVec)#topVec is now the only one w/ that pivot
return Matrix(finishedVecs)
示例5: heuristic_map_constructor
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def heuristic_map_constructor(goal, cost_map, resolution=0.2):
"""construct heuristic query map
goal - State, has x,y attributes
return type : matrix has same size as cost_map
"""
if type(goal)==list or type(goal)==tuple:
g_i, g_j = floor(goal[1]/resolution), floor(goal[0]/resolution)
else:
g_i, g_j = floor(goal.y/resolution), floor(goal.x/resolution)
goal_grid = Grid(g_i, g_j, cost_map[g_i, g_j])
grid_dict = {(goal_grid.i, goal_grid.j):goal_grid}
pq = PriorityQueue()
pq.put(goal_grid)
heuristic_map = np.inf*np.ones(cost_map.shape)
while not pq.empty():
current = pq.get()
successors = current.successors(grid_dict)
for successor in successors:
successor.extend = True
cost = current.cost + resolution*(abs(current.i-successor.i)+abs(current.j-successor.j)) + cost_map[successor.i, successor.j]
if successor.cost > cost:
successor.cost = cost
heuristic_map[successor.i, successor.j] = cost
pq.put(successor)
return heuristic_map
示例6: bestFirstSearch
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def bestFirstSearch(self, startNode, goalNode, heuristic):
bestFitstQueue = PriorityQueue(0)
visitedNode = {}
parent = {}
utility = Utility()
goalNodeStateDict = utility.getGoalNodeStateDict(goalNode)
bestFitstQueue.put((1, startNode))
while not(bestFitstQueue.empty()):
poppedTuple = bestFitstQueue.get()
self.nodesVisited+=1
popped = poppedTuple[1]
if (popped == goalNode):
# print popped==goalNode
return self.backtrack(popped)
else:
visitedNode[popped.stringRep]=popped
if self.maxDepth < popped.level:
self.maxDepth = popped.level
popped.expand()
for child in popped.children:
if child.stringRep not in visitedNode:
heuristicOfChild = utility.getHeuristic(child, goalNode, heuristic, goalNodeStateDict)
bestFitstQueue.put((heuristicOfChild, child))
self.maxQueueSize +=1
示例7: run_test_2
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def run_test_2():
pq = PriorityQueue()
pq.put(Point2D(2,2))
pq.put(Point2D(-2, -2))
pq.put(Point2D(2,-10))
while( not pq.empty() ):
print(str(pq.get()), end= ' ')
示例8: JobQueue
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
class JobQueue(object):
def __init__(self):
self.queue = PriorityQueue()
self.last_enqueued = None
self.logger = logging.getLogger(self.__class__.__name__)
def put(self, job, next_t=0):
self.logger.debug("Putting a {} with t={}".format(job.__class__.__name__, next_t))
re_enqueued_last = self.last_enqueued == job
self.queue.put((next_t, job))
self.last_enqueued = job
return re_enqueued_last
def tick(self):
now = time.time()
self.logger.debug("Ticking jobs with t={}".format(now))
while not self.queue.empty():
t, j = self.queue.queue[0]
self.logger.debug("Peeked a {} with t={}".format(j.__class__.__name__, t))
if t < now:
self.queue.get()
self.logger.debug("About time! running")
j.run()
self.put(j, now + j.INTERVAL)
continue
self.logger.debug("Next task isn't due yet. Finished!")
break
示例9: find_path
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def find_path(self, start, end):
start = start # .upper()
# end = list(set([x.upper() for x in end])) # list comprehension, convert tuple to list. Booyeah.
end = end # [x.upper() for x in end]
while (start in end):
end.remove(start)
if (not start in self.graph.keys()) or (not set(end) <= set(self.graph.keys())) or (start == end):
return []
self.__reset_visited__()
from queue import PriorityQueue
pq = PriorityQueue()
self.__assign__(pq, [[start, 0]], self.__get_adjacent__(start))
while not pq.empty():
shortest = pq.get()
if (shortest.head() in end):
end.remove(shortest.head())
self.__reset_visited__()
pq = PriorityQueue()
'''print(shortest.head())
print(shortest.path())
print(end)'''
self.__assign__(pq, shortest.path(), [])
if not end:
return shortest.path()
self.__assign__(pq, shortest.path(), self.__get_adjacent__(shortest.head()))
'''print("second")'''
return []
示例10: get_discrete_voronoi_diagram
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def get_discrete_voronoi_diagram(image, list_of_generators):
"""
Given an image and a list of generating points, return the discrete voronoi diagram. The DVD is represented
by a matrix of numbers, with each number being a different color(section) of the DVD
:param image: The image being stippled
:param list_of_generators: A list of generating points
:return: The discrete voronoi diagram
"""
width, length = image.size
discrete_voronoi_diagram = [[-1 for x in range(width)] for y in range(length)]
queue = PriorityQueue()
for i in range(len(list_of_generators)):
if 0 <= list_of_generators[i][0] <= width and 0 <= list_of_generators[i][1] <= length:
queue.put((0, list_of_generators[i], i))
while not queue.empty():
triple = queue.get()
point_coordinate = triple[1]
x_coor = point_coordinate[0]
y_coor = point_coordinate[1]
i = triple[2]
if discrete_voronoi_diagram[y_coor][x_coor] == -1:
discrete_voronoi_diagram[y_coor][x_coor] = i
neighboring_points = [(x_coor, y_coor+1), (x_coor+1, y_coor), (x_coor, y_coor-1), (x_coor-1, y_coor)]
for item in neighboring_points:
if 0 <= item[0] < width and 0 <= item[1] < length:
if discrete_voronoi_diagram[item[1]][item[0]] == -1:
distance = math.sqrt((item[0] - list_of_generators[i][0])**2 +
(item[1] - list_of_generators[i][1])**2)
queue.put((distance, item, i))
return discrete_voronoi_diagram
示例11: _test_loaded_in_correct_order
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def _test_loaded_in_correct_order(
self, enrichment_manager: EnrichmentManager, enrichment_loaders: Iterable[EnrichmentLoader]
):
"""
Tests that the given enrichment manager applies enrichments defined be the given loaders in the correct order.
:param enrichment_manager: enrichment manager
:param enrichment_loaders: enrichment loaders
"""
logging.root.setLevel(logging.CRITICAL)
cookie = Cookie("the_identifier")
enrichment_loaders_priority_queue = PriorityQueue()
for enrichment_loader in enrichment_loaders:
if enrichment_loader.can_enrich(cookie):
enrichment_loaders_priority_queue.put(enrichment_loader)
enrichment = enrichment_manager.next_enrichment(cookie)
while enrichment is not None:
expected_enrichment_loader = enrichment_loaders_priority_queue.get() # type: EnrichmentLoader
expected_enrichment = expected_enrichment_loader.load_enrichment(cookie)
self.assertEqual(enrichment, expected_enrichment)
cookie.enrich(enrichment)
expected_enrichment_loader.can_enrich = MagicMock(return_value=False)
enrichment = enrichment_manager.next_enrichment(cookie)
self.assertTrue(enrichment_loaders_priority_queue.empty())
示例12: giveConclusion
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def giveConclusion():
foodmap = mapFood()
print("Foodmap =", foodmap)
heatmap = mapHeat()
foodheat = {}
foods = PriorityQueue()
for (food, distance) in foodmap:
foodheat[food] = heatmap[food[1]][food[0]]
if foodheat[food] < calculateLimit(heatmap):
foods.put((distance, food))
if not foods.empty():
good_food = foods.get()[1]
head = snakes[speler_nummer].head
path = givePath(head, good_food)
direction = giveDirection(path[0], path[1])
else:
minimum = wall_value
direction = -1
head = snakes[speler_nummer].head
backuplist = []
for coordinate in neighbours(head):
if heatmap[coordinate[1]][coordinate[0]] < minimum:
direction = giveDirection(head, coordinate)
minimum = heatmap[coordinate[1]][coordinate[0]]
elif level[coordinate[1]][coordinate[0]] in ['.','x']:
backuplist.append(coordinate)
if direction == -1:
if len(backuplist)!= 0:
direction = giveDirection(head,backuplist[0])
else:
print("Goodbye, cruel world!")
direction = 'r'
return direction
示例13: Astar
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def Astar(start, goal, cost_map, heuristic_map, vehicle, cursor, motion_primitives):
"""
Open Aera Motion Planning, Static Environment
"""
pq = PriorityQueue()
pq.put(start)
node_dict = {start.index:start, goal.index:goal}
edge_dict = {}
# graph = {} # {(state1, state2):trajectory}
times = 0
while times<200 and not goal.reach and not pq.empty():
times += 1
current = pq.get()
current.extend = True
State.RushTowardGoal(current=current, goal=goal, cursor=cursor, edge_dict=edge_dict, pq=pq, cost_map=cost_map, vehicle=vehicle)
# if traj_g is not None:
# edge_dict[(current, goal)] = traj_g
# pq.put(goal)
State.ControlSet(current=current,motion_primitives=motion_primitives, pq=pq, node_dict=node_dict, edge_dict=edge_dict, cost_map=cost_map, heuristic_map=heuristic_map,vehicle=vehicle, goal=goal)
# control_set = State.ControlSet(current=current,motion_primitives=motion_primitives, cost_map=cost_map, heuristic_map=heuristic_map,vehicle=vehicle)
# for (successor, traj) in control_set:
# edge_dict[(current, successor)] = traj
# pq.put(successor)
if goal.reach:
return True, node_dict, edge_dict
else:
return False, node_dict, edge_dict
示例14: find_path
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
def find_path(self, graph, start_id, end_id, heuristic=euclidean):
if heuristic is None:
raise ValueError
# (priority, data)
flood = PriorityQueue()
flood.put((0, start_id))
visited = {}
visited_cost = {}
visited[start_id] = None
visited_cost[start_id] = 0
while not flood.empty():
current = flood.get()[1]
if current == end_id:
break
for n in graph.get_neighbours(current):
updated_cost = visited_cost[current] + graph.get_cost(current, n)
if n not in visited_cost or updated_cost < visited_cost[n]:
visited_cost[n] = updated_cost
nx, ny = n
ex, ey = end_id
priority = updated_cost + heuristic(ex, ey, nx, ny)
flood.put((priority, n))
visited[n] = current
return visited, visited_cost
示例15: MultiThreadedWeatherDatabase
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import empty [as 别名]
class MultiThreadedWeatherDatabase(Thread):
def __init__(self, file):
super(MultiThreadedWeatherDatabase, self).__init__()
self.file = file
self.queue = PriorityQueue()
self.event = Event()
self.create_tables = False
if not os.path.isfile(file):
self.create_tables = True
self.start() # Threading module start
def run(self):
super(MultiThreadedWeatherDatabase, self).run()
db = sqlite3.connect(self.file)
cursor = db.cursor()
if self.create_tables:
self.create_all_tables()
while True:
if self.queue.empty():
sleep(0.1) # So the thread doesnt use all of the processor
continue
job, sql, arg, result = self.queue.get_nowait()
if sql == '__close__':
break
if arg is None:
arg = ''
cursor.execute(sql, arg)
db.commit()
if result:
for rec in cursor:
result.put(rec)
result.put('__last__')
db.close()
self.event.set()
def execute(self, sql, args=None, res=None, priority=2):
self.queue.put_nowait((priority, sql, args, res))
def select(self, sql, args=None, priority=2):
res = Queue()
self.execute(sql, args, res, priority)
while True:
rec = res.get()
if rec == '__last__':
break
yield rec
def close(self):
self.execute('__close__')
def create_all_tables(self):
command1 = '''CREATE TABLE location (location_id INTEGER PRIMARY KEY , town TEXT, country TEXT, lat REAL, lon REAL, dateadded INTEGER, timezone INTEGER)'''
self.execute(command1)
command2 = '''CREATE TABLE "forecast" (forecast_id INTEGER PRIMARY KEY, location_id INTEGER, time INTEGER, temp REAL, pressure INTEGER, humidity INTEGER, clouds INTEGER, windspeed REAL, winddirection INTEGER, symbol INTEGER, FOREIGN KEY (location_id) REFERENCES location (location_id) DEFERRABLE INITIALLY DEFERRED)'''
self.execute(command2)
def remove_old_forecasts(self):
command = '''DELETE FROM forecast WHERE forecast.time < STRFTIME('%s', 'now')'''
self.execute(command)