class IoDevice: def __init__(self, dType, timePerOp): self.type = dType self.timePerOp = timePerOp self.queue = Queue() self.busy = False def request(self, ioOp): # se estiver livre retorna True, se nao coloca na fila e retorna false if (self.busy != True): self.busy = True ioOp.processing = True return True else: self.queue.enqueue(ioOp) return False # retorna true se tiver pendencias na fila def release(self, ioOp): self.busy = False ioOp.processing = False ioOp.finished = True addedIo = None if len(self.queue.queue) > 0: addedIo = self.queue.dequeue() return addedIo
def createArrivalQueue(fname): q = Queue() infile = open(fname) for line in infile: time, items = line.split() q.enqueue(Customer(time,items)) infile.close() return q
def hotPotato(namelist, num): queue = Queue() for name in namelist: queue.enqueue(name) while queue.size() > 1: for i in range(num): queue.enqueue(queue.dequeue()) out = queue.dequeue() return queue.dequeue()
def __init__(self, arrivalQueue, avgTime): self.time = 0 # ticks so far in simulation self.arrivals = arrivalQueue # queue of arrival events to process self.line = Queue() # customers waiting in line self.serviceTime = 0 # time left for current customer self.totalWait = 0 # sum of wait time for all customers self.maxWait = 0 # longest wait of any customer self.customerCount = 0 # number of customers processed self.maxLength = 0 # maximum line length self.ticksPerItem = avgTime # time to process an item
def __init__(self): self.myCurrent = Stack() # my currently displayed card self.otherCurrent = Stack() # other currently displayed card self.currentState = 0 # keeps track of the state of play self.dealingPile = Stack() # queue or stack self.myPlayingPile = Stack() # queue or stack self.myStoragePile = Queue() # queue or stack self.otherPlayingPile = Stack() # queue or stack self.otherStoragePile = Queue() # queue or stack self.lootPile = Stack() # queue or stack self.war = Stack() # holds cards in a war situation
def simulation(numSeconds, pagesPerMinute): ''' numSeconds,模拟时间,我们将每次模拟视为1秒 pagesPerMinute,页面速率,以分钟计 ''' #create Printer object labPrinter = Printer(pagesPerMinute) #create task queue taskQueue = Queue() #save time that task wait waitingTimes = [] #模拟时间 for currentSecond in range(numSeconds): if newPrintTask(): #create Task object task = Task(currentSecond) #push task queue taskQueue.enqueue(task) #add task to printer if not labPrinter.busy() and not taskQueue.isEmpty(): nextTask = taskQueue.dequeue() waitingTimes.append(nextTask.waitTime(currentSecond)) labPrinter.startNext(nextTask) #printer deal task labPrinter.tick() averageWait = sum(waitingTimes) / len(waitingTimes) print('Average wait %6.2f seconds and %3d tasks remaining' % (averageWait, taskQueue.size()))
class Processor: # Atributos: queue, cpuSliceTime, roundRobin def __init__(self, sliceTime): self.sliceTime = sliceTime self.queue = Queue() self.roundRobin = RoundRobin(5) # metodos: request, release, isBusy # tenta adicionar segmento ao Round Robin, se nao conseguir coloca na queue. def request(self, segment, time): # se nao ha posicoes disponiveis if(not self.roundRobin.avaiable()): # coloca na fila self.queue.enqueue(segment) # se processador ja comecou a processar algo (tempo de inicio round robin diferente do tempo do segmento) elif(self.roundRobin.startTime != time and self.roundRobin.startTime != None): # coloca na fila self.queue.enqueue(segment) # Se passou por tudo, pode colocar no Round Robin else: self.roundRobin.add(segment) self.roundRobin.startTime = time self.roundRobin.endTime = time + self.sliceTime def run(self, segment): # se tiver no Round Robin atualiza tempo para processar isOnRoundRabin = False for seg in self.roundRobin.list: if seg.id == segment.id: isOnRoundRabin = True break if(isOnRoundRabin): segment.decreaseTime(self.sliceTime) def release(self, segment): # verificar se segmento existe self.roundRobin.list.remove(segment) self.roundRobin.avaiablePositions += 1
def bfs(g, start): start.setDisatance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == 'white': nbr.setColor('gray') nbr.setDisatance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('balck')
load_dotenv(find_dotenv()) app = Flask(__name__) app.url_map.strict_slashes = False app.config['DEBUG'] = True app.config['ENV'] = 'development' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' app.config['SQLACHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) CORS(app) Migrate(app,db) manager = Manager(app) manager.add_command("db", MigrateCommand) _queue = Queue() @app.route('/') def main(): return render_template('index.html') @app.route('/new', methods= ['POST']) def new_e(): if not request.is_json: return jsonify({"msg": "No JSON return"}), 400 name = request.json.get('name', None) phone = request.json.get('phone', None) if not name or name == '': return jsonify({"msg": "No name in request"}), 400
class CheckerSim(object): #------------------------------------------------------------ def __init__(self, arrivalQueue, avgTime): self.time = 0 # ticks so far in simulation self.arrivals = arrivalQueue # queue of arrival events to process self.line = Queue() # customers waiting in line self.serviceTime = 0 # time left for current customer self.totalWait = 0 # sum of wait time for all customers self.maxWait = 0 # longest wait of any customer self.customerCount = 0 # number of customers processed self.maxLength = 0 # maximum line length self.ticksPerItem = avgTime # time to process an item #------------------------------------------------------------ def run(self): while (self.arrivals.size() > 0 or self.line.size() > 0 or self.serviceTime > 0): self.clockTick() #------------------------------------------------------------ def averageWait(self): return float(self.totalWait) / self.customerCount #------------------------------------------------------------ def maximumWait(self): return self.maxWait #------------------------------------------------------------ def maximumLineLength(self): return self.maxLength #------------------------------------------------------------ def clockTick(self): # one tick of time elapses self.time += 1 # customer(s) arriving at current time enter the line while (self.arrivals.size() > 0 and self.arrivals.front().arrivalTime == self.time): self.line.enqueue(self.arrivals.dequeue()) self.customerCount += 1 # if line has reached a new maximum, remember that self.maxLength = max(self.maxLength, self.line.size()) # process items if self.serviceTime > 0: # a customer is currently being helped self.serviceTime -= 1 elif self.line.size() > 0: # help the next customer in line customer = self.line.dequeue() #print self.time, customer # nice tracing point # compute and update statistics on this customer self.serviceTime = customer.itemCount * self.ticksPerItem waitTime = self.time - customer.arrivalTime self.totalWait += waitTime self.maxWait = max(self.maxWait, waitTime)
def __init__(self, sliceTime): self.sliceTime = sliceTime self.queue = Queue() self.roundRobin = RoundRobin(5)
#!/usr/bin/env python # -*- coding: utf-8 -*- from myQueue import Queue s = Queue() s.enQueue(2) s.enQueue(3) s.enQueue("sxw") s.enQueue(3.14) while not s.isEmpty(): item = s.deQueue() print("length:", len(s),"value:", item.value)
def hotPotato(nameList, num=6): simQueue = Queue() for name in nameList: simQueue.enqueue(name) while simQueue.size() > 1: for i in range(num): simQueue.enqueue(simQueue.dequeue()) simQueue.dequeue() return simQueue.dequeue()
class War: def __init__(self): self.myCurrent = Stack() # my currently displayed card self.otherCurrent = Stack() # other currently displayed card self.currentState = 0 # keeps track of the state of play self.dealingPile = Stack() # queue or stack self.myPlayingPile = Stack() # queue or stack self.myStoragePile = Queue() # queue or stack self.otherPlayingPile = Stack() # queue or stack self.otherStoragePile = Queue() # queue or stack self.lootPile = Stack() # queue or stack self.war = Stack() # holds cards in a war situation def add_dealingpile(self): """Adds the shuffled decks of cards to the dealer's pile""" deck = Deck() # Gets deck from deck class in Cards.py self.dealingPile = deck.shuffle() # Shuffles deck and stores it return self.dealingPile def deal(self, wn, turt, u_turt, x_turt): """Deals out 25 cards from to each player's playing pile from shuffled dealers pile """ Display.draw_board(self, wn, turt) # initializes board Display.write_text(self, wn, turt) # initiates user and computer for i in range(1): # deals out 25 cards to player 1 my_card = self.dealingPile.pop() self.myPlayingPile.push(my_card) Display.user_playing(self, wn, turt) # draws user playing pile u_turt.clear() Display.user_card_number(self, wn, u_turt, self.myPlayingPile.size()) # prints number of cards for i in range(1): # deals out 25 cards to the computer other_card = self.dealingPile.pop() self.otherPlayingPile.push(other_card) Display.comp_playing(self, wn, turt) # draws computer playing pile x_turt.clear() Display.other_card_number(self, wn, x_turt, self.otherPlayingPile.size()) # prints the number of cards return self.otherPlayingPile, self.myPlayingPile # returns the storage for each hand def make_move(self, wn, turt): """initiates a round of play and communicates play-by-play during the round returns true when the game is still in play returns false when the game is over Communicates an appropriate message about whether the user beat the computer""" self.currentState += 1 # tells what round of play the game is in print("Round " + str(self.currentState)) mycards = self.myPlayingPile.size() othercards = self.otherPlayingPile.size() if mycards == 0: # indicates who has won print("Computer Won!") Display.win_message(self, wn, turt, 'Computer Won!') # prints computer won quit() return False elif othercards == 0: print("You Won!") Display.win_message(self, wn, turt, 'You Won!') # prints user won quit() return False else: return True def remove_my_card(self): """Precondition: myPlayingPile is not empty If it is not empty, the function removes a card from myPlayingPile, returning the stored value""" mycards = self.myPlayingPile.size() if mycards != 0: x = self.myPlayingPile.pop() # removes card from player 1 stack self.myCurrent.push(x) # puts card in the player's current card stack return self.myCurrent def remove_other_card(self): """Precondition: otherPlayingPile is not empty If it is not empty, the function removes a card from otherPlayingPile, returning the stored value""" othercards = self.otherPlayingPile.size() if othercards != 0: a = self.otherPlayingPile.pop() # removes card from computer stack self.otherCurrent.push(a) # puts card in the computer's current card stack return self.otherCurrent def display_card(self, wn, p_turt, c_turt): """Displays a card on the screen and returns the value""" a = self.otherCurrent.top() # looks at the cards in the current stack b = self.myCurrent.top() print("Computer has placed a " + str(a)) p_turt.clear() Display.play_card(self, wn, p_turt) # displays user played card Display.played_number(self, wn, p_turt, b) # displays played card number c_turt.clear() Display.play_other_card(self, wn, c_turt) # displays computer card Display.other_played_number(self, wn, c_turt, a) # displays computer card number print("You have placed a " + str(b)) # prints the cards to the screen def compare_cards(self): """Compares the cards that each player plays""" b = self.myCurrent.top() # Looks at the current cards and compares them a = self.otherCurrent.top() if b > a: return 0 elif b < a: return 1 def compare_other(self, wn, u_turt, x_turt): """Gives the cards to whichever layer had the highest played number""" b = self.myCurrent.top() a = self.otherCurrent.top() if b > a: a = self.myCurrent.pop() # removes card and places it in the lootpile self.lootPile.push(a) x = self.otherCurrent.pop() self.lootPile.push(x) while self.war.size() != 0: # removes cards inside the war stack and places it in the lootpile p = self.war.pop() self.lootPile.push(p) u_turt.clear() Display.user_card_number(self, wn, u_turt, self.myPlayingPile.size()) # displays number of cards remaining for user x_turt.clear() Display.other_card_number(self, wn, x_turt, self.otherPlayingPile.size()) print("You won the cards.") return self.lootPile elif b < a: b = self.myCurrent.pop() self.lootPile.push(b) c = self.otherCurrent.pop() # removes card and places it in the lootpile self.lootPile.push(c) while self.war.size() != 0: h = self.war.pop() self.lootPile.push(h) u_turt.clear() Display.user_card_number(self, wn, u_turt, self.myPlayingPile.size()) x_turt.clear() Display.other_card_number(self, wn, x_turt, self.otherPlayingPile.size()) # displays number of cards remaining for computer print("Computer won the cards.") return self.lootPile # returns the lootpile elif b == a: b = self.myCurrent.pop() # puts the player's current card and the computer's current card in a stack if they are the same self.war.push(b) c = self.otherCurrent.pop() self.war.push(c) while self.war.size() != 0: x = self.war.pop() self.lootPile.push(x) u_turt.clear() Display.user_card_number(self, wn, u_turt, self.myPlayingPile.size()) x_turt.clear() Display.other_card_number(self, wn, x_turt, self.otherPlayingPile.size()) return self.lootPile def move_my_loot(self, wn, t_turt, turt): """Moves everything from lootPile to myStoragePile""" while self.lootPile.size() != 0: # removes all the cards from the lootpile and puts them into the storage pile a = self.lootPile.pop() self.myStoragePile.enqueue(a) Display.user_storage(self, wn, turt) # displays user storage pile t_turt.clear() Display.user_storage_number(self, wn, t_turt, self.myStoragePile.size()) # displays number of cards in storage return self.myStoragePile def move_other_loot(self, wn, o_turt, turt): """Moves everything from lootPile to otherStoragePile""" while self.lootPile.size() != 0: # removes all the cards from the lootpile and puts them into the storage pile b = self.lootPile.pop() self.otherStoragePile.enqueue(b) Display.comp_storage(self, wn, turt) # displays computer storage pile o_turt.clear() Display.other_storage_number(self, wn, o_turt, self.otherStoragePile.size()) # displays number of cards in storage return self.otherStoragePile def move_my_storage(self, wn, u_turt, t_turt, s_turt): """Moves everything from myStoragePile to myPlayingPile""" if self.myPlayingPile.size() == 0: while self.myStoragePile.size() != 0: # removes all the cards from the storage pile and puts it into the playing hand c = self.myStoragePile.dequeue() self.myPlayingPile.push(c) if self.myStoragePile.size()== 0: return self.myPlayingPile else: u_turt.clear() Display.user_card_number(self, wn, u_turt, self.myPlayingPile.size()) # updated user card number Display.replace_card(self, wn, s_turt) # moves the storage to the playing pile t_turt.clear() Display.user_storage_number(self, wn, t_turt, self.myStoragePile.size()) # updates storage pile number s_turt.clear() return self.myPlayingPile def move_other_storage(self, wn, x_turt, o_turt, cs_turt): """Moves everything from otherStoragePile to otherPlayingPile""" if self.otherPlayingPile.size() == 0: while self.otherStoragePile.size() != 0: # removes all the cards from the storage pile and puts it into the playing hand d = self.otherStoragePile.dequeue() self.otherPlayingPile.push(d) if self.otherStoragePile.size() == 0: return self.otherPlayingPile else: x_turt.clear() Display.other_card_number(self, wn, x_turt, self.otherPlayingPile.size()) # updates computer playing pile number Display.replace_other_card(self, wn, cs_turt) # moves computer storage to playing pile o_turt.clear() Display.other_storage_number(self, wn, o_turt, self.otherStoragePile.size()) # updates computer storage pile number cs_turt.clear() return self.otherPlayingPile
def breath_first_traverse(self): temp_node = self.bList.root queue_list = Queue() queue_list.enqueue(temp_node) while not queue_list.is_empty(): if queue_list.is_empty(): return else: print(queue_list.peek()) if queue_list.peek().left != None: queue_list.enqueue(queue_list.peek().left) if queue_list.peek().right != None: queue_list.enqueue(queue_list.peek().right) queue_list.dequeue()
def __init__(self, dType, timePerOp): self.type = dType self.timePerOp = timePerOp self.queue = Queue() self.busy = False
from myQueue import Queue q = Queue() q.enqueue(4) q.enqueue('dog') q.enqueue(True) print(q.size())