class BadLinks: def __init__(self, rsrc): self.__rsrc = rsrc.encode('utf-8') self.__queue = MyQueue() self.__queue.push(Link(self.__rsrc)) self._handleResource() def _handleResource(self): while (not (self.__queue.isEnd())): currentURL = self.__queue.pop() if (self.__rsrc in currentURL.getByteRef()): links = currentURL.getAllLinks() for i in links: self.__queue.push(Link(i)) def __getRefWithStatus(self, link): s = str(link.getUtfRef()) + ' - status: ' s = s + str(link.getStatusCode()) + '\n' return s def printLinks(self): goodLinks = open('good_links.txt', 'w') badLinks = open('bad_links.txt', 'w') self.__queue.reset() while (not (self.__queue.isEnd())): currentURL = self.__queue.pop() if (currentURL.isWorking()): goodLinks.write(self.__getRefWithStatus(currentURL)) else: badLinks.write(self.__getRefWithStatus(currentURL)) badLinks.close() goodLinks.close()
def testConstructor(self): q = MyQueue() self.assertEqual(1, q._parallelism) self.assertRaises(Exception, MyQueue, 0) self.assertEqual(0, q.size()) self.assertFalse(q.isRunning()) self.assertEqual(0, q.inFlight())
def testStartErrorHandling(self): q = MyQueue() q.addTask(waitOneSecond) q.addTask(raiseException) q.addTask(waitOneSecond) q.start()
def testStartMultipleStart(self): q = MyQueue() q.addTask(waitOneSecond) startTime = datetime.now() q.start() q.start() # should only take one second, aka the loaded task should not be run twice self.sleepCountAssert(startTime, q, 1)
def __init__(self, config, context): self._input_queue = None self._name = config.get('name') self._params = config.get('params') self._output_queue = MyQueue(config, context) self._output_queue2 = MyQueue(config, context) self._context = context self._threads_alloc = multiprocessing.Value('i', 0) self._threads_occup = multiprocessing.Value('i', 0) self._thread_alloc_lock = multiprocessing.Lock() self.index = 0 self._is_last = False self._max_parallel = multiprocessing.cpu_count() self.should_display = True self._cache_config = None
def __init__(self, display): super(Opponent, self).__init__(display) self.__display = display self.__brain = MyQueue() # a list that tracks the balls position on different frames. Used for simulating delayed reaction time self.__reaction_time = 5 # reaction time of AI in frames self.__difficulties = (self.__ai_easy, self.__ai_normal, self.__ai_hard) self.__current_difficulty = 0 #0 for easy, 1 for normal, 2 for hard self.__winfo = pygame.display.Info() self.set_position(15, 200) #move the ai paddle to the left side of the screen
def test_poll(self): q = MyQueue() q.add(1) q.add(2) q.add(3) self.assertTrue(q.poll() == 1) self.assertTrue(q.poll() == 2) self.assertTrue(q.size() == 1)
def test_peek(self): q = MyQueue() q.add(1) q.add(2) q.add(3) self.assertTrue(q.peek() == 1) self.assertTrue(q.peek() == 1) self.assertTrue(q.size() == 3)
def testStartMultipleProcesses(self): # test that we can run 3 seconds of tests with 2 procs in about 2 seconds. startTime = datetime.now() q = MyQueue(2) q.addTask(waitOneSecond) q.addTask(waitOneSecond) q.addTask(waitOneSecond) q.start() self.sleepCountAssert(startTime, q, 2)
def levelByLevel(self, aFile): ''' Print the nodes of the BTree level-by-level on aFile. ''' aFile.write('A level-by-level listing of the nodes:\n') node_cache = MyQueue() node_cache.enqueue(self.rootNode) while not node_cache.isEmpty(): cur_node = node_cache.dequeue() aFile.write(str(cur_node)) for child_idx in cur_node.child: if child_idx is not None: node_cache.enqueue(self.readFrom(child_idx))
def testStartSimple(self): # should be able to run 2 tasks serially in about 2 seconds startTime = datetime.now() q = MyQueue() q.addTask(waitOneSecond) q.addTask(waitOneSecond) q.addCallback(callbackFunc) q.start() self.sleepCountAssert(startTime, q, 2) # callback function creates this file. testing for a file existence is an easy way of passing info between multithreaded tasks self.assertTrue(os.path.isfile("callback.txt")) os.system("rm callback.txt")
def search(board): start = time() nodes_generated = 0 nodes_repeated = 0 if board.is_win(): end = time() print_results(board, 1, 0, 0, 1, end - start) return board node = deepcopy(board) nodes_generated += 1 frontier = MyQueue() frontier.push(node) explored = set() keepLooking = True while keepLooking: if frontier.isEmpty(): print "Solution not found" return else: currNode = frontier.pop() moves = currNode.moves_available() currNode.fboxes = frozenset(currNode.boxes) explored.add(currNode) for m in moves: child = deepcopy(currNode) nodes_generated += 1 child.move(m) if child not in explored: if child.is_win(): end = time() print_results(child, nodes_generated, nodes_repeated, len(frontier), len(explored), end - start) return child frontier.push(child) else: nodes_repeated += 1
if option == "1" or option == "2" or option == "3" or option == "4": break print("Wrong INPUT, try again...") # Simulation SIMULATION = 'simulation00' + option checkInDuration = s[SIMULATION]['checkInDuration'] # Average Rates coachAvgSvcRate = s[SIMULATION]['coach']['serviceRate'] coachAvgArrivalRate = s[SIMULATION]['coach']['arrivalRate'] fcAvgSvcRate = s[SIMULATION]['firstClass']['serviceRate'] fcAvgArrivalRate = s[SIMULATION]['firstClass']['arrivalRate'] # Start Queues coachQueue = MyQueue() firstClassQueue = MyQueue() # Start Service Stations coachSvcStation001 = ServiceStation() coachSvcStation002 = ServiceStation() coachSvcStation003 = ServiceStation() firstClassSvcStation001 = ServiceStation() firstClassSvcStation002 = ServiceStation() # Stats MISC coachQueueSTATS = { 'duration': 0.0, 'maxSize': 0, 'maxWait': 0, 'nPass': 0 } firstQueueSTATS = { 'duration': 0.0, 'maxSize': 0, 'maxWait': 0, 'nPass': 0 } # Stats Service Stations busyStation = {
def __init__(self, rsrc): self.__rsrc = rsrc.encode('utf-8') self.__queue = MyQueue() self.__queue.push(Link(self.__rsrc)) self._handleResource()
def _load_remotes(self, remotes_config): for remote in remotes_config: name = remote['name'] self._context.remotes[name] = MyQueue()
def main(): import queue from myqueue import MyQueue from mystack import MyStack # built function q = queue.Queue(maxsize=20) q.put(1) q.put(2) q.put(3) print(q.get()) s = queue.LifoQueue(maxsize=10) s.put(1) s.put(2) s.put(3) print(s.get()) # my own func arr1 = MyStack() arr1.add(1) arr1.add(2) arr1.add(3) arr1.add(4) arr1.get() arr1.remove() arr1.remove() arr1.get() arr2 = MyQueue() arr2.add(1) arr2.add(2) arr2.add(3) arr2.add(4) arr2.get() arr2.remove() arr2.remove() arr2.get()
def testStartMoreProcsThanTasks(self): q = MyQueue(2) q.addTask(waitOneSecond) q.start()
def testStartComplex(self): q = MyQueue() q.addTask(waitOneSecond) q.addTask(waitFiveSeconds) q.addTask(waitOneSecond) self.assertEqual(3, q.size()) self.assertFalse(q.isRunning()) self.assertEqual(0, q.inFlight()) q.start() time.sleep(0.5) self.assertTrue(q.isRunning()) self.assertEqual(1, q.inFlight()) self.assertEqual(2, q.size()) time.sleep(1) self.assertEqual(1, q.inFlight()) self.assertEqual(1, q.size()) self.assertTrue(q.isRunning()) time.sleep(5) self.assertEqual(1, q.inFlight()) self.assertEqual(0, q.size()) self.assertTrue(q.isRunning()) time.sleep(1) self.assertEqual(0, q.inFlight()) self.assertEqual(0, q.size()) self.assertFalse(q.isRunning())
def test_add(self): q = MyQueue() self.assertTrue(q.size() == 0) q.add(1) self.assertTrue(q.size() == 1) q.add(2) self.assertTrue(q.size() == 2) q.add(3) self.assertTrue(q.size() == 3)
def testStartMultipleUse(self): q = MyQueue() q.addTask(waitOneSecond) q.start() while q.isRunning(): time.sleep(0.1) self.assertEqual(0, q.size()) self.assertEqual(0, q.inFlight()) self.assertFalse(q.isRunning()) q.addTask(waitOneSecond) startTime = datetime.now() q.start() # it should take about 1 second to run the second task again self.sleepCountAssert(startTime, q, 1)
from myqueue import MyQueue app = Flask(__name__) app.config['DEBUG'] = True app.config['ENV'] = 'development' app.config['SQLALCHEMY_DATABASE_ URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) CORS(app) Migrate(app, db) manager = Manager(app) manager.add_command("db", MigrateCommand) my_queue = MyQueue() @app.route('/') def main(): return render_template('index.html') @app.route('/all') def index(): users = my_queue.get_queue() return jsonify(users), 200 @app.route('/new', methods=['POST']) def create(): if not request.is_json: return jsonify({"error": "Request must be JSON"}), 400
class Opponent(Paddle): def __init__(self, display): super(Opponent, self).__init__(display) self.__display = display self.__brain = MyQueue() # a list that tracks the balls position on different frames. Used for simulating delayed reaction time self.__reaction_time = 5 # reaction time of AI in frames self.__difficulties = (self.__ai_easy, self.__ai_normal, self.__ai_hard) self.__current_difficulty = 0 #0 for easy, 1 for normal, 2 for hard self.__winfo = pygame.display.Info() self.set_position(15, 200) #move the ai paddle to the left side of the screen def set_difficulty(self, new_difficulty): # new_difficulty must be an int between 0-2. 0 for easy, 1 for normal, 2 for hard self.__current_difficulty = new_difficulty # the ai methods of the opponent. different thinking process for each difficulty def __ai_base(self, ball, reaction_time): self.__reaction_time = reaction_time while(self.__brain.size()>self.__reaction_time): self.__brain.dequeue() self.__brain.enqueue(ball.get_position()) #add the position of the ball to the brain delay queue # only check the ball position and move to it if the ball is on screen if ball.is_in_play(): if self.__brain.size()>self.__reaction_time: ball_position = self.__brain.dequeue() #get the position of the ball from reaction_time frames ago, in a (x, y) tuple paddle_rect = self.get_rect() paddle_speed = self.get_speed() # move the ai paddle towards the balls y position, making sure they dont move off the screen if paddle_rect[1]+paddle_rect[3]//2 < ball_position[1] - paddle_speed and \ paddle_rect[1]+paddle_rect[3]<self.__winfo.current_h: self.move_down() elif paddle_rect[1]+paddle_rect[3]//2 > ball_position[1] + paddle_speed and \ paddle_rect[1]>0: self.move_up() def __ai_easy(self, ball): #same as ai_normal but with a slower reaction time self.__ai_base(ball, 14) def __ai_normal(self, ball): self.__ai_base(ball, 8) def __ai_hard(self, ball): #same as ai_normal but with a faster reaction time, and moves to the middle after returning a shot. self.__reaction_time = 3 while(self.__brain.size()>self.__reaction_time): self.__brain.dequeue() self.__brain.enqueue(ball.get_position()) if ball.is_in_play(): if self.__brain.size()>self.__reaction_time: paddle_rect = self.get_rect() paddle_speed = self.get_speed() ball_position = self.__brain.dequeue() #get the position of the ball from reaction_time frames ago, in a (x, y) tuple ball_direction = ball.get_direction() # if the ball is moving away from the ai, move towards the middle of the screen if math.cos(ball_direction)>0: #assumes ai is on the left if paddle_rect[1]+paddle_rect[3]//2<self.__winfo.current_h//2-paddle_speed: self.move_down() elif paddle_rect[1]+paddle_rect[3]//2>self.__winfo.current_h//2+paddle_speed: self.move_up() # otherwise move the ai paddle towards the balls y position, making sure they dont move off the screen else: if paddle_rect[1]+paddle_rect[3]//2 < ball_position[1] - paddle_speed and \ paddle_rect[1]+paddle_rect[3]<self.__winfo.current_h: self.move_down() elif paddle_rect[1]+paddle_rect[3]//2 > ball_position[1] + paddle_speed and \ paddle_rect[1]>0: self.move_up() def update(self, events, objects): for object in objects: if isinstance(object, Ball): #call the ai method for the opponent. Moves the paddle based on the ball and its own positions' self.__difficulties[self.__current_difficulty](object) #update the paddle super(Opponent, self).update()