def test_ge(self): eventObj2 = Event(eventTime=5) self.assertTrue(eventObj2 >= self.eventObj, "The value should be equal") eventObj2 = Event(eventTime=10) self.assertTrue(eventObj2 >= self.eventObj, "The value should be greater")
def testIterator(self): eventLines = [ "time;type;task;text", "2000-01-02 03:04;in;Work;", "3000-02-03 04:05;out;Holiday;" ] lineIter = iter(eventLines) reader = ExportReader(lineIter) self.assertEqual( Event(datetime=datetime(year=2000, month=1, day=2, hour=3, minute=4), eventType=EventType.IN, task=Task.WORK), next(reader)) self.assertEqual( Event(datetime=datetime(year=3000, month=2, day=3, hour=4, minute=5), eventType=EventType.OUT, task=Task.HOLIDAY), next(reader)) with self.assertRaises(StopIteration): next(reader)
def run(self): running = True while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False if pg.key.get_pressed()[pg.K_RIGHT] and self._map.is_valid(self._pacman.get_pos()): self._pacman.move_right() if pg.key.get_pressed()[pg.K_UP] and self._map.is_valid(self._pacman.get_pos()): self._pacman.move_up() if pg.key.get_pressed()[pg.K_DOWN] and self._map.is_valid(self._pacman.get_pos()): self._pacman.move_down() if pg.key.get_pressed()[pg.K_LEFT] and self._map.is_valid(self._pacman.get_pos()): self._pacman.move_left() Event( "pacman got a bonus", self._pacman.get_pos() == self._bonus.get_pos(), ) Event("pacman moved", self._pacman.get_pos()) self._blinky.move() self.draw() self._clock.tick(self.FPS) pg.quit()
def __init__(self, app): self.game_started = False self.game_over = False self.app = app self.current_level = 0 self.game_objects = GameObjects() self.scene = Scene(self, self.game_objects, self.app.window.UI) self.event = Event(self, self.game_objects)
def test_updateState_No_Processors(self): mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 123 self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 123, "The current time should be updated to SIMULATION_INITIAL_TIME + 123" )
def test_updateState_Not_First_Shift(self): param = Parameters() param.num_processors = 2 self.coreObj = Core(param) for mock_processor in self.coreObj.processors: mock_processor.isIdle = MagicMock(return_value=False) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 1 * 3600 + 1 self.coreObj.updateState(mock_event) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 5 * 3600 + 1 self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 5 * 3600 + 1, "The current time should be updated to SIMULATION_INITIAL_TIME + 5*3600 + 1" ) self.assertEqual( self.coreObj.serviceProcessors, (5 * 3600 + 1) * 2, "The service processors time should be (5*3600 + 1) * 2 (2 service processors)" ) self.assertEqual(self.coreObj.idleProcessors, 0, "The idle time should be 0")
def parse(self, eventString: str) -> Event: # Example event string: "2020-01-06 08:18;in;Default;" strings = self._splitString(eventString) dateTime = self._parseDate(strings[self._indexDatetime]) eventType = EventType.parse(strings[self._indexEventType]) task = Task.parse(strings[self._indexTask]) return Event(datetime=dateTime, eventType=eventType, task=task)
def consume_data(): consumer = Consumer() consumer.start() while True: event_json = consumer.get_event_from_consumer() event = Event(event_json) statistics_manager.add_to_statistics(event)
def startSimulation(self): """Implemented by all modules""" startEvent = Event(self, Constants.START_SIMULATION, self.currentTime, self.currentTime) self.logEvent(startEvent) for source in self.sources: source.startSimulation()
def post(self): event = self.get_argument("event", "") event = json.loads(event) target = Host(self.request.remote_ip, self.request.remote_ip) try: reader = geoip2.database.Reader("GeoLite2-City.mmdb") response = reader.city(self.request.remote_ip) country = response.country.name subdivision = response.subdivisions.most_specific.name city = response.city.name lat = response.location.latitude lon = response.location.longitude target = Host(self.request.remote_ip, self.request.remote_ip, country, subdivision, city, lon, lat) except AddressNotFoundError: target = Host(self.request.remote_ip, self.request.remote_ip, "", "", "", -77.63, 43.09) print("No location data for %s." % self.request.remote_ip) if event.get("longitude", 0) == 0 and event.get("latitude", 0) == 0: del event["longitude"] del event["latitude"] attacker = Host(event.get("ip", "IP Missing"), event.get("hostname", "Hostname Missing"), event.get("country", ""), event.get("subdivision", ""), event.get("city", ""), event.get("longitude", random.randrange(-100, 100)), event.get("latitude", random.randrange(-100, 100))) attempt = Event(event["username"], event["password"], event["clientVersion"], target, attacker) print(event) COORDINATOR.accept(attempt)
def test_getCurrentShift(self): source_obj = Source(self.coreObj) self.coreObj.sources.append(source_obj) self.coreObj.output_file = open('./TEST.txt', "w+") self.coreObj.executeEvent(Event(eventName=Constants.START_SIMULATION)) self.coreObj.output_file.close() self.assertEquals(self.coreObj.getCurrentShift(), Constants.ENTREGA, "The first shift should be of type ENTREGA")
def test_executeEvent_None_output(self): source = Source(self.coreObj) self.assertEqual(self.coreObj.entitiesSystem, 0, "The system should not have any entity") event = Event(eventName=Constants.NEXT_ARRIVAL) source.executeEvent(event) self.assertEqual(self.coreObj.entitiesSystem, 1, "The system should have one entity")
def decode(lst): """ Decode serialized data """ event_list = lst events = list() events = [ Event(event['event_title'], event['description']) for event in event_list ] return events
def test_executeEvent_Not_NEXT_ARRIVAL(self): source = Source(self.coreObj) source.addOutput(Queue(1)) self.assertEqual(self.coreObj.entitiesSystem, 0, "The system should not have any entity") event = Event(eventName=Constants.END_SERVICE) source.executeEvent(event) self.assertEqual(self.coreObj.entitiesSystem, 0, "The system should not have any entity")
def endSimulation(self): """Implemented by all modules""" endEvent = Event( self, # eventCreator Constants.END_SIMULATION, # eventName self.currentTime, # eventScheduled self.currentTime # eventTime ) self.logEvent(endEvent) self.updateState(endEvent)
def scheduleEndService(self): operationType = self.hostedEntity.getOperationType() rand = Random() serviceIncrement = rand.processorIncrement(operationType) endServiceEvent = Event( self, # eventCreator Constants.END_SERVICE, # eventName self.core.currentTime, # eventScheduled self.core.currentTime + serviceIncrement # eventTime ) return endServiceEvent
def scheduleNextArrival(self): shift = self.core.getCurrentShift() rand = Random() arrivalIncrement = rand.sourceIncrement(shift) arrivalEvent = Event( self, # eventCreator Constants.NEXT_ARRIVAL, # eventName self.core.currentTime, # eventSheduled self.core.currentTime + arrivalIncrement # eventTime ) return arrivalEvent
def main(): e = Event() while True: print("Please select events from below options") print("addUser userName role") print("addTopic userName topicName") print("removeTopic userName topicName") print("viewTopics userName") print("subscribeTopic userName topicName") print("postEvent messageBody", end='\n') option = input().split() if len(option): if option[0].lower() == 'adduser': print(e.addUser(option[1], option[2])) elif option[0].lower() == 'addtopic': print(e.addTopics(option[1], option[2])) elif option[0].lower() == 'removetopics': print(e.removeTopic(option[1], option[2]))
def test_executeEvent_OtherEvent(self): source_obj = Source(self.coreObj) self.coreObj.output_file = open('./TEST.txt', "w+") self.coreObj.sources.append(source_obj) self.coreObj.executeEvent(Event(eventName=Constants.END_SIMULATION)) self.coreObj.output_file.close() self.assertEquals( self.coreObj.eventsList.qsize(), 0, "The length should be 0 because the simulation did not start") obj = self.coreObj.eventsList self.assertIsNotNone("The object is not none", obj) with open('./TEST.txt', "r") as read: self.assertEquals(len(read.read()), 0, "The file should be empty")
def testParse(self): header = "time;type;task;text" event = "2000-01-02 03:04;in;Work;" eventParser = EventParser(header) actualEvent = eventParser.parse(event) expectedDate = datetime(year=2000, month=1, day=2, hour=3, minute=4) expectedType = EventType.IN expectedTask = Task.WORK expectedEvent = Event(datetime=expectedDate, eventType=expectedType, task=expectedTask) self.assertEqual(actualEvent, expectedEvent)
def test_updateState_With_2Idle_Processors(self): param = Parameters() param.num_processors = 2 self.coreObj = Core(param) for mock_processor in self.coreObj.processors: mock_processor.isIdle = MagicMock(return_value=True) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 123 self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 123, "The current time should be updated to SIMULATION_INITIAL_TIME + 123" ) self.assertEqual( self.coreObj.idleProcessors, 123 * 2, "The idle time should be 123 * 2 (2 idle processors)") self.assertEqual(self.coreObj.serviceProcessors, 0, "The service processors time should be 0")
def test_executeEvent_Start_Simulation(self): source_obj = Source(self.coreObj) self.coreObj.output_file = open('./TEST.txt', "w+") self.coreObj.sources.append(source_obj) self.coreObj.executeEvent(Event(eventName=Constants.START_SIMULATION)) self.coreObj.output_file.close() self.assertEquals( self.coreObj.eventsList.qsize(), 2, "The length should be two: start simulation event + first event from source" ) obj = self.coreObj.eventsList self.assertIsNotNone("The object is not none", obj) with open('./TEST.txt', "r") as read: self.assertNotEquals(len(read.read()), 0, "The file should not be empty")
def extractEvent(stockName, saxSeries, MODE_changeOnly=False): eventSeries = [] _len = len(saxSeries) for i in range(1, _len): diff = saxSeries[i] - saxSeries[i - 1] if diff < 0: direction = 'down' elif diff > 0: direction = 'up' else: if MODE_changeOnly: continue else: direction = 'same' event = Event(stockName, i, direction, diff) eventSeries.append(event) return eventSeries
def create_event(self, title, description): """ Method create_event creates event and adds it to the list. Args: title(str): Title of event. description(str): Description of event. Raises: Exception: if event with given title already exist. Examples: >>> model.create_event("New event", "Do smth.") >>> model._show_list(model.event_list) [Title: 'New event', Description: 'Do smth.': '] >>> model.create_event("New event", "Do smth else.") Traceback (most recent call last): Exception: [ERROR]::The event already exists. """ if self._is_title_exists(title): raise Exception("[ERROR]::The event already exists.") self.__events_list.append(Event(title, description))
def test_run(self): mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventName = MagicMock(return_value="Test") mock_event.eventScheduled = MagicMock( return_value=Constants.SIMULATION_INITIAL_TIME) mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 123 # eventsList is a Priority Queue self.coreObj.logEvent = MagicMock() self.coreObj.eventsList.put(mock_event) self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 123, "The current time should be updated to SIMULATION_INITIAL_TIME + 123" )
def download_data(self): events = self.get_todays_events() event_details = [] for eventType in events['events']: for e in events['events'][eventType]: event = Event(e) event_details.append( self.get_event_details( event, self.sport_configs[eventType]['details'])) selections_list = [ selection for event in event_details for selection in event['selections'] ] event_details_response_list = [ resp for event in event_details for resp in event['response'] ] return { "selections": selections_list, "events_response": events['events'], "event_details_response": event_details_response_list }
def setUp(self): self.eventObj = Event(eventTime=5)
def test_gt(self): eventObj2 = Event(eventTime=10) self.assertTrue(eventObj2 > self.eventObj, "The value should be greater")
def detect(self, original_image, min_score: float, max_overlap: float, max_objects: int, elementsConfiguration: str, app) -> Image: # Transforms needed for SSD300 (we are using torchvision to apply image tranformation) -> https://pytorch.org/docs/stable/torchvision/transforms.html resize = transforms.Resize((300, 300)) to_tensor = transforms.ToTensor() normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) # We use the standard transformation for RGB images - More info can be found here https://discuss.pytorch.org/t/understanding-transform-normalize/21730/22 image = normalize(to_tensor(resize(original_image))) image = image.to(self.device) predicted_locs, predicted_scores = self.model( image.unsqueeze(0) ) # Unsqueeze -> Returns a new tensor with a dimension of size one inserted at the specified position. # Run the detection over locations det_boxes, det_labels, det_scores = self.model.detect_objects( predicted_locs, predicted_scores, min_score=min_score, max_overlap=max_overlap, top_k=max_objects) det_boxes = det_boxes[0].to('cpu') det_labels = det_labels[0].to('cpu').tolist() # returns list of ints det_scores = det_scores[0].to('cpu') # Transform back to original image dimensions original_dims = torch.FloatTensor([ original_image.width, original_image.height, original_image.width, original_image.height ]).unsqueeze(0) det_boxes = det_boxes * original_dims annotated_image = original_image if det_labels == [0]: return original_image currentDetectedClasses = [] for labelId, box, score in zip(det_labels, det_boxes.tolist(), det_scores): predictedClass = self.evaluateElementsConfiguration( prediction=self.classes.getClassByPredictedId(labelId), elementsDict=elementsConfiguration) currentDetectedClasses.append(predictedClass) if (not predictedClass): return original_image boxLimits = box score = round(score.item(), 4) ElementDrawer.drawRectangule(annotated_image, boxLimits, predictedClass.color) text = predictedClass.label.upper() + " " + "{:.0%}".format(score) ElementDrawer.drawTextBox(annotated_image, text, "calibri.ttf", boxLimits, predictedClass.color) Event.processAndPersistEvent(self.detectedClassesPrevious, currentDetectedClasses, datetime.timestamp(datetime.now()), app) soundAlarmOn = app.config['soundAlarm'] if self.shouldThrowAlarm(currentDetectedClasses): for client in app.config["clients"]: app.config["socketIo"].emit( 'alarm', {'isAudioAlarmEnable': soundAlarmOn}, room=client) self.detectedClassesPrevious = currentDetectedClasses return annotated_image
def setUp(self): event = Event('Very important meeting', 'Meeting at 3:00 UTC') self.data = [event] self.output = None