def __init__(self, btcTrader, apiName, authId, authPass): Engine.__init__(self, apiName, btcTrader, 1) # refresh rate of 1 second. In the futur with the websockets we will probably put 0 and use some kind of select self.req = self.CreateRequester(authId, authPass) self.depth = {} self.clock = Clock() self.first = 1 self.account = Account()
class FullscreenWindow: def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background='black') self.bottomFrame = Frame(self.tk, background='black') self.topFrame.pack(side=TOP, fill=BOTH, expand=YES) self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) self.tk.bind("<Escape>", self.end_fullscreen) # weather self.weather = Weather(self.topFrame) self.weather.place(x=0, y=5, anchor=NW, width=700, height=400) # Date self.date = Date(self.topFrame) self.date.place(x=1015, y=10, anchor=NE, width=350, height=90) # Day self.day = Day(self.topFrame) self.day.place(x=860, y=10, anchor=NE, width=300, height=90) # clock self.clock = Clock(self.topFrame) self.clock.place(x=940, y=60, anchor=NE, width=250, height=90) #Seconds self.sec = Sec(self.topFrame) self.sec.place(x=1015, y=60, anchor=NE, width=80, height=85) # news self.news = News(self.bottomFrame) self.news.pack(side=LEFT, anchor=S, padx=0, pady=10) # Facial rec #self.FacialRecognition = News(self.bottomFrame) #self.FacialRecognition.pack(side=LEFT, anchor=N, padx=100, pady=60) # calender self.calender = Calendar(self.topFrame) self.calender.place(x=1015, y=150, width=250, anchor=NE) # calender Time self.calenderTime = CalendarTime(self.topFrame) self.calenderTime.place(x=850, y=172, width=250, anchor=NE) #Traffic self.traffic = Traffic(self.topFrame) #Launch self.launch = Launch(self.topFrame) #crypto name self.crypto = Crypto(self.topFrame) self.crypto.pack(side=TOP, anchor=NE) #Crypto Time self.cryptoPrice = CryptoPrice(self.topFrame) self.cryptoPrice.pack(side=TOP, anchor=NE) #camera s = FacialRec() def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.tk.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.tk.attributes("-fullscreen", False) return "break"
def on_init(self): pygame.init() self._clock = Clock(pygame.font) self._opening.initTitle(pygame.font) self._display_surf = pygame.display.set_mode(Helpers.GAME_SIZE, pygame.HWSURFACE | pygame.DOUBLEBUF) self._running = True pygame.display.set_caption(Helpers.GAME_TITLE)
class FullscreenWindow: def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background='black') self.bottomFrame = Frame(self.tk, background='black') self.topFrame.pack(side=LEFT, fill=BOTH, expand=YES) self.bottomFrame.pack(side=RIGHT, fill=BOTH, expand=YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) self.tk.bind("<Escape>", self.end_fullscreen) # clock self.clock = Clock(self.topFrame) self.clock.pack(side=TOP, anchor=NW, padx=100, pady=60) # weather self.weather = Weather(self.topFrame, self.clock.day_of_week1) self.weather.pack(side=TOP, anchor=NW, padx=100, pady=(60, 0)) # news self.news = News(self.bottomFrame) self.news.pack(side=RIGHT, anchor=N, padx=100, pady=(80, 0)) # calender - removing for now # self.calender = Calendar(self.bottomFrame) # self.calender.pack(side = RIGHT, anchor=S, padx=100, pady=60) def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.tk.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.tk.attributes("-fullscreen", False) return "break"
def start_execution(options): f = open(options.file, 'r') content = f.read() read_content = ReadContents() instructions = Instructions() #print "Id 2 :", id(instructions) registers = Registers() memory = Memory() read_content.read_iregisters(content) read_content.read_fpregisters(content) read_content.read_memory(content) read_content.get_instructions(content) #instructions, registers, memory = read_content.return_attrs() instructions = read_content.return_attrs() #print "registers: ", id(registers), " Inst : ", id(instructions.registers), id(memory), id(instructions.memory) #print instructions.get_instructions(), '\n', registers.r['R2'], '\n', memory.location, '\n', registers.f instructions.build_instruction_objects() #print instructions.instructions_object_list #print "In main file : ", id(memory), id(registers), id(instructions) clock = Clock(instructions) #clock.print_object_ids() #print clock.start_clock() #print clock.clock clock.next_instruction() #print "log : ", Registers.f['F4']['contents'] writer = Writer(clock.clock_execution_dict, Registers.f, len(instructions.instructions_object_list)) writer.write_to_file() writer.write_to_file_registers()
def __init__(self, robot_name, v, beta, phi): """ var state = (xcur, ycur, thetacur) :param robot_name: :param v: :param beta: :param phi: """ file_name = "data_{}.txt".format(robot_name) self.file = open(file_name, 'w') sub_topic = "/{}/north_star".format(robot_name) pub_topic = "/{}/cmd_vel".format(robot_name) self.sub_pose = rospy.Subscriber(sub_topic, NorthStarReadings, self.control_callback) self.pub_vels = rospy.Publisher(pub_topic, Twist, queue_size=10) # Trajectory setup. self.line_law = LineControlLaw(v, beta, phi) self.clock = Clock() self.state = (0, 0, 0) self.turn = "ON" self.old_cur_pose = None
def __init__(self, c, is_last_level=False, time_this=False, start_time=time.time()): self.time_this = time_this self.start_time = start_time self.jump_sound = None self.is_last_level = is_last_level self.SPEED_OF_LIGHT = c # 80 -> 8 -> 5.5 pygame.init() pygame.font.init() pygame.display.set_caption("Relativity Man") self.screen = pygame.display.set_mode( (self.WINDOW_WIDTH, self.WINDOW_HEIGHT), pygame.FULLSCREEN) self.player = Player(150, Game.GROUND - 300) thickness = 25 self.platforms = ( Platform(self.GROUND - 100, 100, 1600, 2 * thickness), Platform(self.GROUND - 200, 200, 200, thickness), Platform(self.GROUND - 500, 500, 200, thickness), Platform(self.GROUND - 400, 300, 200, thickness), Platform(self.GROUND - 300, 700, 200, thickness), ) self.clock_rel = Clock(50, 100, 200, 100, self.SPEED_OF_LIGHT) self.clock = Clock(160, 100, 200, 100, self.SPEED_OF_LIGHT) self.keys = {} # Automatically initialized in handle user input. self.ball = Ball(50, 50, 0)
def tick(self): """ advance the clock by one second """ previous_hour = self._hours Clock.tick(self) if (self._hours < previous_hour): self.advance()
def readClock(): print("playing clock...") clock = Clock() clockDict = clock.getClockCodes() clockMediaPlayer = clock.getClockMediaPlayer(soundApp.data, soundApp.songsFolder) soundApp.songsArray.append(clockMediaPlayer) clockMediaPlayer.playSound() return emptyResponse()
def onBeforeConnectCallback(self, **kwargs): try: self.socket.connect((self.host, self.port)) self.connected = True self.Clock = Clock() kwargs["callback"](True, None) except Exception as e: kwargs["callback"](False, e)
def setUp(self): self._clock = Clock() self.locale_id = 1000 self.book_stat = BookStat() self.sut_smithy_weapon = SmithWeapon() self.sut_smithy_armor = SmithArmor() self.sut_brains = Brains() self.sut_faction = Faction( experience=0, name='Red', faction_id='1000', clock=self._clock, smithy_weapon=self.sut_smithy_weapon, smithy_armor=self.sut_smithy_armor, brains=self.sut_brains, ) self.sut2_faction = Faction( experience=0, name='blue', faction_id='1001', clock=self._clock, smithy_weapon=self.sut_smithy_weapon, smithy_armor=self.sut_smithy_armor, brains=self.sut_brains, ) self.sut = self.sut_faction.create_vpc(name='sut') self.sut2 = self.sut2_faction.create_vpc(name='sut2') arena = HexMap() arena.arena_ground = 'plains' arena.arena_height = 10 arena.create_arena(radius=5) self.sut_dm = DungeonMaster( clock=Clock(), dungeon=arena, locale_id=self.locale_id, ) self.sut_dm.add_char( member=self.sut, faction=self.sut_faction, edge='sw', ) self.sut_dm.add_char( member=self.sut2, faction=self.sut2_faction, edge='se', ) weapon_smith = SmithWeapon() new_weapon = weapon_smith.create() self.sut.rack_weapon.give_weapon(new_weapon)
def __init__(self, parent): EnablePanel.__init__(self, parent) self.box = wx.StaticBox(self, label=u'Available Events') boxSizer = wx.StaticBoxSizer(self.box, wx.HORIZONTAL) self.SetBackgroundColour(wx.WHITE) self.events = [] self.event = None self.activeBar = EnableBar(self) self.activeBar.SetToolTip( wx.ToolTip(u'\n'.join([ u'Click on an available Event in the table.', u'Then press Select.', ]))) self.selectButton = MakeRoundButton(self, 'Select', isSelect) self.headerNames = ['Event', 'Bib', 'Name', 'Team', 'In', 'Out'] self.grid = ReorderableGrid(self, style=wx.BORDER_SUNKEN) self.grid.CreateGrid(0, len(self.headerNames)) self.grid.EnableReorderRows(False) self.grid.SetRowLabelSize(40) self.grid.SetSelectionMode(gridlib.Grid.SelectRows) font = GetFont() self.grid.SetLabelFont(font) for col in six.moves.range(self.grid.GetNumberCols()): self.grid.SetColLabelValue(col, self.headerNames[col]) attr = gridlib.GridCellAttr() attr.SetFont(font) attr.SetRenderer(GridCellMultiLineStringRenderer()) attr.SetReadOnly(True) if self.headerNames[col] == 'Bib': attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_TOP) self.grid.SetColAttr(col, attr) self.clock = Clock(self, size=(128, 128)) self.clock.SetBackgroundColour(wx.WHITE) boxSizer.Add(self.activeBar, 0, flag=wx.ALL | wx.EXPAND, border=4) vs = wx.BoxSizer(wx.VERTICAL) vs.AddSpacer( int(self.grid.GetColLabelSize() + FontSize * 1.15 - RoundButtonSize / 2)) vs.Add(self.selectButton, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=4) boxSizer.Add(vs, 0, flag=wx.ALL, border=4) boxSizer.Add(self.grid, 1, flag=wx.ALL | wx.EXPAND, border=4) boxSizer.Add(self.clock, 0, flag=wx.ALL, border=4) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(boxSizer, 1, flag=wx.EXPAND) self.SetSizer(sizer)
def start (self): try: self.server = socket.socket(); self.server.bind((self.host, self.port)); self.server.listen(self.maxConnections); self.Clock = Clock(); self.onStartCallback(True, None); except Exception as e: self.onStartCallback(False, e);
def setUp(self): self._clock = Clock() self.sut_name = 'sut' self.sut_smithy_weapon = SmithWeapon() self.sut_smithy_armor = SmithArmor() self.sut = Faction( experience=0, name=self.sut_name, faction_id=0, clock=self._clock, smithy_weapon=self.sut_smithy_weapon, smithy_armor=self.sut_smithy_armor, )
def __init__(self, robot_name, v, A): file_name = "data_{}.txt".format(robot_name) self.file = open(file_name, 'w') sub_topic = "/{}/north_star".format(robot_name) pub_topic = "/{}/cmd_vel".format(robot_name) self.sub_pose = rospy.Subscriber(sub_topic, NorthStarReadings, self.control_callback) self.pub_vels = rospy.Publisher(pub_topic, Twist, queue_size=10) # Trajectory setup. self.sin_law = SinControlLaw(v, A) self.clock = Clock() self.state = (0, 0, 0)
def __init__(self, robot_name, goal): file_name = "data_{}.txt".format(robot_name) self.file = open(file_name, 'w') sub_topic = "/{}/north_star".format(robot_name) pub_topic = "/{}/cmd_vel".format(robot_name) srv_topic = "/{}/gotogoal".format(robot_name) self.sub_pose = rospy.Subscriber(sub_topic, NorthStarReadings, self.point_callback) self.pub_vels = rospy.Publisher(pub_topic, Twist, queue_size=10) self.go_to_goal = rospy.Service(srv_topic, GoToGoal, self.go_to_goal_handler) self.goal = goal self.clock = Clock() self.work()
def parse_line(line): line = line.split(',') emotion = '' sex = '' time, *another = line clock = Clock(time) if int(another[0]) == -1: left_panel = another[0:1] another = another[1:] else: left_panel = another[:4] another = another[4:] if int(another[0]) == -1: right_panel = another[0:1] another = another[1:] else: right_panel = another[:4] another = another[4:] left_panel, right_panel = list(map(int, left_panel)), list(map(int, right_panel)) if left_panel[0] != -1 or right_panel[0] != -1: sex = another[0] another = another[1:] if another: emotion = another[0] return clock, left_panel, right_panel, sex, emotion
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("Self Spy") self.spy = 0 self.setWindowFlag(Qt.WindowTitleHint) self.resize(1000, 900) self.setStyleSheet("background-color: #F0DFF7;") self.highGroundLayout = QHBoxLayout() self.clock = Clock() self.focusChart = PieChart() self.highGroundLayout.addWidget(self.clock) self.highGroundLayout.addWidget(self.focusChart) self.focusLayout = Focus(self.focusName, self.focusTime) self.activeLayout = Active(self.activeName, self.activeTime) self.middleLayout = QHBoxLayout() self.middleLayout.addLayout(self.focusLayout) self.middleLayout.addLayout(self.activeLayout) self.layout.addLayout(self.highGroundLayout) self.layout.addLayout(self.middleLayout) widget = QWidget() widget.setLayout(self.layout) self.setCentralWidget(widget)
def new_project(self, video_file, eye_movement_file, trialid_target, categorise_frames=False, categorising_eye_is_left=None): """Creates a new project. Categorisation of frames or fixations is indicated by the 'categorise_frames' flag. """ self.categorise_frames = categorise_frames self.categorising_eye_is_left = categorising_eye_is_left self.video_reader = VideoReader(video_file) self.eye_movement = EyeMovement(eye_movement_file, trialid_target) self.clock = Clock(self.video_reader.frame_count, self.video_reader.fps) self.clock.register(self._clock_tick) if self.categorise_frames: objects = {} for frame in xrange(int(self.video_reader.frame_count)): objects[(frame, frame)] = str(frame) else: objects = self.eye_movement.fixations(self.categorising_eye_is_left) self.category_container = CategoryContainer(objects) if categorising_eye_is_left == True: self.show_eyes = [True, False, False] elif categorising_eye_is_left == False: self.show_eyes = [False, True, False] else: self.show_eyes = [False, False, True] # seek to zero so we'll have a picture after loading the videeo file self.produceCurrentImage()
def __init__(self, cpu, mmu, hard_disk, scheduling_policy=RoundRobin(3)): self.pids = 0 # Queues self.ready_queue = queue.Queue() # Hardware self.hard_disk = hard_disk self.mmu = mmu # Interruption Manager self.interruption_manager = InterruptionManager(self) # Scheduling self.short_term_scheduler = ShortTermScheduler(self.ready_queue, scheduling_policy) self.long_term_scheduler = LongTermScheduler(self.ready_queue) # Cpu self.cpu = cpu self.cpu.set_scheduler(self.short_term_scheduler) self.cpu.set_mmu(self.mmu) self.cpu.set_interruption_manager(self.interruption_manager) # IO self.console = Console() self.io = IODevice(self.interruption_manager) self.clock = Clock("Cpu - IntManager clock", [self.cpu, self.interruption_manager])
def __init__(self): Game = self pygame.init() self.__previousState = GameState() Config.Init() Display.Init() self.__screen = Display.GetDisplay() Display.SetCaption(Config.Get("GameSettings")["Caption"]) self.Clock = Clock().SetTick(int(Config.Get("GameSettings")["Fps"])) self.__gameObjects = []
def __init__(self, team1, team2, halfsecs, ticktime): # Start in the first half self.half = 1 self.ticks_left = halfsecs / ticktime # Create the teams from the rosters self.hometeam = team1 self.awayteam = team2 self.clock = Clock(halfsecs, ticktime) #self.field = Field("sss","ddd") self.down = 1 self.to_go = 10 self.yardline = 20 self.ball_in_play = False self.gameover = False self.ball = Ball()
class Controller: k = 0.5 k2 = 2 def __init__(self, robot_name, goal): file_name = "data_{}.txt".format(robot_name) self.file = open(file_name, 'w') sub_topic = "/{}/north_star".format(robot_name) pub_topic = "/{}/cmd_vel".format(robot_name) srv_topic = "/{}/gotogoal".format(robot_name) self.sub_pose = rospy.Subscriber(sub_topic, NorthStarReadings, self.point_callback) self.pub_vels = rospy.Publisher(pub_topic, Twist, queue_size=10) self.go_to_goal = rospy.Service(srv_topic, GoToGoal, self.go_to_goal_handler) self.goal = goal self.clock = Clock() self.work() def __del__(self): self.file.close() def go_to_goal_handler(self, req): self.goal.x = req.point.x self.goal.y = req.point.y print("New goal is [{}, {}]".format(self.goal.x, self.goal.y)) def point_callback(self, cur_pose): t, dt = self.clock.getTandDT() q = cur_pose.pose.orientation eu = euler_from_quaternion((q.x, q.y, q.z, q.w)) lock.acquire() e_x = self.goal.x - cur_pose.pose.position.x e_y = self.goal.y - cur_pose.pose.position.y e_theta = 0 - eu[2] # self.goal.z - eu[2] lock.release() e = sqrt(e_x ** 2 + e_y ** 2) # euclid error # self.file.write("{} {} {} {}\n".format(t, cur_pose.pose.position.x, cur_pose.pose.position.y, e)) velocity = Twist() if abs(e) > 0.05: # velocity.linear.x = self.k * e_y # velocity.linear.y = -self.k * e_x velocity.linear.x = self.k * e_x velocity.linear.y = self.k * e_y velocity.angular.z = 4 * e_theta self.pub_vels.publish(velocity) def work(self): rate = rospy.Rate(100) while not rospy.is_shutdown(): rate.sleep()
def on_event(self, event): print("Event: ", event.type) if not self._opening.isAlive() and event.type == pygame.KEYDOWN: if event.key == K_SPACE: self._paused = not self._paused if event.key == K_r: self.__init__() self._clock = Clock(pygame.font) self._display_surf = pygame.display.set_mode(Helpers.GAME_SIZE, pygame.HWSURFACE | pygame.DOUBLEBUF) if event.type == pygame.QUIT: self._running = False if event.type == pygame.MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() self._opening.startGame(mouse)
class Market(Engine): def __init__(self, btcTrader, apiName, authId, authPass): Engine.__init__(self, apiName, btcTrader, 1) # refresh rate of 1 second. In the futur with the websockets we will probably put 0 and use some kind of select self.req = self.CreateRequester(authId, authPass) self.depth = {} self.clock = Clock() self.first = 1 self.account = Account() def CreateRequester(self, authId, authPass): if (self.engineName == "mtgox"): return MtGoxRequester(authId, authPass) elif (self.engineName == "bitcoin-central"): return BitcoinCentralRequester(authId, authPass) raise Exception("Unknown Market.") def GetDescription(self): desc = Engine.GetDescription(self) desc.extend(self.account.GetDescription()) return desc # Refresh personal informations, # those informations are not supposed to change if the bot does not perform any action def Refresh(self): self.account = self.req.GetAccount() self.PushMsg("account updated.") # Update informations from the market def Update(self): self.req.UpdateDepth(self.depth) self.PushMsg("Depth updated.") def Initialize(self): self.Refresh() # for now we only update the market infos every 60 seconds def Execute(self, elapsedTime): if self.clock.ElapsedTime() > 60 or self.first == 1: self.first = 0 self.Update() self.clock.Reset() def CleanUp(self): i = 0 # do nothing
def __init__(self, port): Thread.__init__(self) ip = socket.gethostbyname(socket.gethostname()) self.server = SimpleThreadedXMLRPCServer((ip, port), allow_none=True) self.server.register_introspection_functions() self.server.register_multicall_functions() self.server.register_instance(Api(self), allow_dotted_names=True) self.ctr = 0 self.addr = ip + ":" + str(port) self.net_members = [self.addr] self.string_queue = deque() self.status = False self.master_string = "" self.master_address = "" self.is_interested_in_master_string = False self.is_victory_broadcasted = False self.clock = Clock(self.addr) self.wordListToCheck = [] print("Serv created")
def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background='black') self.bottomFrame = Frame(self.tk, background='black') self.topFrame.pack(side=LEFT, fill=BOTH, expand=YES) self.bottomFrame.pack(side=RIGHT, fill=BOTH, expand=YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) self.tk.bind("<Escape>", self.end_fullscreen) # clock self.clock = Clock(self.topFrame) self.clock.pack(side=TOP, anchor=NW, padx=100, pady=60) # weather self.weather = Weather(self.topFrame, self.clock.day_of_week1) self.weather.pack(side=TOP, anchor=NW, padx=100, pady=(60, 0)) # news self.news = News(self.bottomFrame) self.news.pack(side=RIGHT, anchor=N, padx=100, pady=(80, 0))
def __init__(self): """ Erstellt eine Instanz des Hubs. Stellt die VR-Zeit initial auf reale/n Wochentag und Uhrzeit. """ now = datetime.today() self.clock = Clock(now.weekday(), now.hour, now.minute, now.second) self.mainDoor = None self.rooms = [] self.clocks = [] self.doors = [] self.lamps = [] self.radiators = [] self.sensors = [] self.bordcomputers = [] self.accessGroups = {} self.persons = {} self.presentIds = [] self.presenceLog = []
def __init__(self): self.sta_if = WLAN(STA_IF) self.settings = Settings(state=b"%s" % State.CLOCK).load() self.credentials = Credentials().load() self.tags = Tags().load() self.wifi = WifiManager(b"%s-%s" % (PUBLIC_NAME, self.settings.net_id)) self.mdns = mDnsServer(PUBLIC_NAME.lower(), self.settings.net_id) self.mqtt = MqttManager(self.mdns, BROKER_NAME, self.settings.net_id, MQTT_TOPIC_NAME) routes = { b"/": b"./index.html", b"/index.html": b"./index.html", b"/scripts.js": b"./scripts.js", b"/style.css": b"./style.css", b"/favicon.ico": self.favicon, b"/connect": self.connect, b"/action/color": self.set_color, b"/action/clock/display": self.display_clock, b"/action/brightness": self.set_brightness, b"/action/scoreboard/display": self.display_scoreboard, b"/action/scoreboard/green/more": self.scoreboard_green_more, b"/action/scoreboard/green/less": self.scoreboard_green_less, b"/action/scoreboard/red/more": self.scoreboard_red_more, b"/action/scoreboard/red/less": self.scoreboard_red_less, b"/action/scoreboard/reset": self.scoreboard_reset, b"/settings/values": self.settings_values, b"/settings/net-id": self.settings_net_id, b"/settings/ssids": self.get_ssids, } self.http = HttpServer(routes) print("> HTTP server up and running") self.clock = Clock(self.settings.color) self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) self.loop.create_task(self.check_mqtt()) self.loop.create_task(self.send_state()) self.loop.run_forever() self.loop.close()
def __init__(self): super(PiPyDesktop, self).__init__() grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(Clock(), 1, 0) grid.addWidget(Weather(), 1, 1) self.setLayout(grid) self.setWindowTitle('PiPyDesktop') self.setStyleSheet("background-color:black;") self.setCursor(QtCore.Qt.BlankCursor)
def parse_line(line): line = line.split(',') time, *another = line clock = Clock(time) nums = list(map(int, another[:-1])) rect = Rect(*nums) label = another[-1] return clock, rect, label
def __init__(self, window_size: Size, window_title: str, stage_size: Size, stage_colors: Tuple[Color, Color], clock_font: Font, clock_font_color: Color, text_box_font: Font): Rectangle.set_window(window_size, window_title) self.__width = stage_size.width self.__height = stage_size.height self.__stage_color = stage_colors[0] self.__walls_color = stage_colors[1] self.__window_width = Constants.WINDOW_WIDTH self.__window_height = Constants.WINDOW_HEIGHT self.__wall_width = (self.__window_width - self.__width) / 2 self.__wall_height = (self.__window_height - self.__height) / 2 self.__walls, self.__stage = self.__initialize_stage() self.__text_boxes = self.__initialize_text_boxes(text_box_font) clock_pos = Point(self.__width + self.__wall_width + 1, self.__height + self.__wall_height) self.__clock = Clock(clock_pos, self.__stage_color, self.__walls_color, clock_font, clock_font_color)
def __init__(self, mode, num_agents,sites,name, id): self.mode = mode#the type of simulation. Deterministic mode == agents that have constant page and home times. Variable == agents that have page and home times that change self.num_agents = num_agents self.rando = Random() self.curr_agents_surfing = []#list of agents who are currently surfing the web self.all_agents = []#list of all agents who have finished surfing the web and agents who are currently surfing the web self.threads = []#Each agent surfing has a thread self.agents_finished_surfing = 0 self.sites = sites#List of homepages available to visit self.name = name#the name of the overseer self.id = id#the id number for the overseer. Overseer 4 should have id = 4 self.clock = Clock()
def __init__(self, parent=None): super(PreludeTimer, self).__init__(parent) self.title = 'SafetyPlay - Prelude Timer' self.settings = load() self.setupUi() self.clock = Clock() self.save_timer = SaveCloser() self.resizer = Resizer() self.font_color_picker = ColorChooser() self.font_color_picker.setCurrentColor(self.settings['f_color']) self.bg_color_picker = ColorChooser() self.bg_color_picker.setCurrentColor(self.settings['bg_color']) self.setupActions()
def load_project(self, saved_filepath, overwrite_video_filepath=None): sc = SaveController() sc.loadFromFile(saved_filepath) controller_state = sc.getSavedState('controller') self.show_eyes = controller_state['show_eyes'] self.categorise_frames = controller_state['categorise_frames'] self.eye_movement = EyeMovement(saved_state=sc.getSavedState('eye_movement')) if overwrite_video_filepath is None: self.video_reader = VideoReader(saved_state=sc.getSavedState('video_reader')) else: self.video_reader = VideoReader(overwrite_video_filepath) self.clock = Clock(saved_state=sc.getSavedState('clock')) self.clock.register(self._clock_tick) self.category_container = CategoryContainer(saved_state=sc.getSavedState('category_container')) self.produceCurrentImage()
def __init__(self, day,month,year,hours=0, minutes=0,seconds=0): Calendar.__init__(self, day, month, year) Clock.__init__(self, hours, minutes, seconds)
from Clock import Clock clock = Clock(12, 22, 40) print(str(clock)) print(clock.__str__()) clock2 = Clock(60, 70, 80)
#!/usr/bin/env python # timer.py - Clock Exceptions from ClockException import * from Clock import Clock try: c1 = Clock(12, 33) print "%d:%d" %(c1.getHour(), c1.getMinute()) c2 = Clock (12, 73) # raises exception except ClockException as ex: print "%s: %s" %(ex.__class__.__name__, ex.response()) ################################################# # # $ timer.py # 12:33 # MinuteException: minute 73 not between 0 and 59 #
class Controller(Saveable): """This class connects all the in- and output classes together and provides a clean interface for the connection to the gui. This means that a lot of the methods are like proxies, eg. `isClockRunning()` uses the instance of the Clock class to run the corresponding method in Clock. For information about those methods, please see the documentation of the class they are defined in. The images for the cursors which indicate the state of each eye are retreived from the config file. """ def __init__(self, video_str, current_frame): self.video_reader = None self.eye_movement = None self.clock = None self.cursors = [] self.category_container = None self.categorise_frames = False self.video_image = None self.show_eyes = [False, False, False] # [left_eye, right_eye, mean_eye] self.categorising_eye_is_left = None # True -> left, False -> right, None -> mean self.video_str = video_str self.current_frame = current_frame """contains the current image of the overlayed video. shared memory, so no latent ipc is needed""" self.config = Config() self.cursors = {None:None, 'fixated_left':self.config.get('cursors','fixated_left'), 'saccade_left':self.config.get('cursors','saccade_left'), 'blink_left':self.config.get('cursors','blink_left'), 'fixated_right':self.config.get('cursors','fixated_right'), 'saccade_right':self.config.get('cursors','saccade_right'), 'blink_right':self.config.get('cursors','blink_right'), 'fixated_mean':self.config.get('cursors','fixated_mean'), 'saccade_mean':self.config.get('cursors','saccade_mean'), 'blink_mean':self.config.get('cursors','blink_mean'), } # ----- CLOCK STUFF ---- def _clock_tick(self, frame): self.produceCurrentImage() # ------ STATUS STUFF --- def isClockRunning(self): return self.clock.running def categorisationEye(self): if self.categorising_eye_is_left == True: return 'left' elif self.categorising_eye_is_left == False: return 'right' else: return 'mean' def categorisationObjects(self): if self.categorise_frames == False: return 'fixations' else: return 'frames' def leftEyeStatus(self, show): self.show_eyes[0] = bool(show) # reproduce the current image to show or exclude this eye self.produceCurrentImage() def rightEyeStatus(self, show): self.show_eyes[1] = bool(show) # reproduce the current image to show or exclude this eye self.produceCurrentImage() def meanEyeStatus(self, show): self.show_eyes[2] = bool(show) # reproduce the current image to show or exclude this eye self.produceCurrentImage() def getEyeStatus(self): return self.show_eyes def ready(self): """You should always make sure this class is ready before using it's functions. If `ready()` returns true, this means every data needed is available""" return bool(self.video_reader) and \ bool(self.eye_movement) and \ bool(self.clock) and \ bool(self.cursors) and \ bool(self.category_container) def getMaxFramesOfEyeMovement(self): return self.eye_movement.maxFrames() def plausibleCheck(self): percent = float(self.getMaxFramesOfEyeMovement()) / float(self.getVideoFrameCount()) if abs(percent - 1) * 100 > self.config.get('general', 'plausible_edf_video_frame_diff_percent'): return False else: return True # ----------- LOAD/SAVE/NEW PROJECT ---- def new_project(self, video_file, eye_movement_file, trialid_target, categorise_frames=False, categorising_eye_is_left=None): """Creates a new project. Categorisation of frames or fixations is indicated by the 'categorise_frames' flag. """ self.categorise_frames = categorise_frames self.categorising_eye_is_left = categorising_eye_is_left self.video_reader = VideoReader(video_file) self.eye_movement = EyeMovement(eye_movement_file, trialid_target) self.clock = Clock(self.video_reader.frame_count, self.video_reader.fps) self.clock.register(self._clock_tick) if self.categorise_frames: objects = {} for frame in xrange(int(self.video_reader.frame_count)): objects[(frame, frame)] = str(frame) else: objects = self.eye_movement.fixations(self.categorising_eye_is_left) self.category_container = CategoryContainer(objects) if categorising_eye_is_left == True: self.show_eyes = [True, False, False] elif categorising_eye_is_left == False: self.show_eyes = [False, True, False] else: self.show_eyes = [False, False, True] # seek to zero so we'll have a picture after loading the videeo file self.produceCurrentImage() def save_project(self, saved_filepath): sc = SaveController() sc.addSaveable('eye_movement', self.eye_movement) sc.addSaveable('category_container', self.category_container) sc.addSaveable('video_reader', self.video_reader) sc.addSaveable('clock', self.clock) sc.addSaveable('controller', self) sc.saveToFile(saved_filepath) def load_project(self, saved_filepath, overwrite_video_filepath=None): sc = SaveController() sc.loadFromFile(saved_filepath) controller_state = sc.getSavedState('controller') self.show_eyes = controller_state['show_eyes'] self.categorise_frames = controller_state['categorise_frames'] self.eye_movement = EyeMovement(saved_state=sc.getSavedState('eye_movement')) if overwrite_video_filepath is None: self.video_reader = VideoReader(saved_state=sc.getSavedState('video_reader')) else: self.video_reader = VideoReader(overwrite_video_filepath) self.clock = Clock(saved_state=sc.getSavedState('clock')) self.clock.register(self._clock_tick) self.category_container = CategoryContainer(saved_state=sc.getSavedState('category_container')) self.produceCurrentImage() def getState(self): """Returns the state of the selected eye(s) and if frames or fixations are being categorised.""" return {'show_eyes':self.show_eyes, 'categorise_frames':self.categorise_frames} # ----------- CATEGORISATION STUFF ---- def categorise(self, shortcut): try: return self.category_container.categorise(self.clock.frame, shortcut) except CategoryContainerError: raise return False def deleteCategorisation(self, frame): self.category_container.deleteCategorisation(frame) def getCategorisations(self): return self.category_container.dictOfCategorisations() def getCategorisationsOrder(self): return self.category_container.start_end_frames def exportCategorisations(self, filepath): self.category_container.export(filepath) def getCategories(self): return self.category_container.categories def editCategory(self, old_shortcut, new_shortcut, category_name): self.category_container.editCategory(old_shortcut, new_shortcut, category_name) def getCategoryContainer(self): return self.category_container def importCategories(self, filepath): self.category_container.importCategories(filepath) def getCategoryOfFrame(self, frame): return self.category_container.getCategoryOfFrame(frame) # ----------- IMAGE PROCESSING ---- def overlayedFrame(self, frame, left, right, mean): """This method produces the overlay of eyemovement data on the current frame. It uses the video_reader to grab the frame and then uses `_addCursorToImage()` to draw the overlay.""" # retrieve original image from video file image = self.video_reader.frame(frame) # add cursors as neede if left and not self.eye_movement.statusLeftEyeAt(frame) is None: self._addCursorToImage(image, self.cursors[self.eye_movement.statusLeftEyeAt(frame)+'_left'], self.eye_movement.leftLookAt(frame)) if right and not self.eye_movement.statusRightEyeAt(frame) is None: self._addCursorToImage(image, self.cursors[self.eye_movement.statusRightEyeAt(frame)+'_right'], self.eye_movement.rightLookAt(frame)) if mean and not self.eye_movement.meanStatusAt(frame) is None: self._addCursorToImage(image, self.cursors[self.eye_movement.meanStatusAt(frame)+'_mean'], self.eye_movement.meanLookAt(frame)) return image def _addCursorToImage(self, image, cursor, position): """This helper method draws the overlay of the cursor image onto the video image, by using functions of opencv. In order for the overlay to be drawn correctly, it has to be put in a mask (cursorMask).""" # in case that we don't have information about the position or cursor end now if position is None or cursor is None: return cursor_left_upper_corner = (int(position[0]-cursor.width/2), int(position[1]-cursor.height/2)) cursor_right_lower_corner = (cursor_left_upper_corner[0]+cursor.width, cursor_left_upper_corner[1]+cursor.height) cursorROI = [0, 0, cursor.width, cursor.height] imageROI = [cursor_left_upper_corner[0], cursor_left_upper_corner[1], cursor.width, cursor.height] if cursor_right_lower_corner[0] <= 0 or cursor_right_lower_corner[1] < 0 or \ cursor_left_upper_corner[0] > image.width or cursor_left_upper_corner[1] > image.height: #print "cursor is out of image" # cursor out of image return if cursor_left_upper_corner[0] < 0: #print "left upper edge of cursor is left of image border" cursorROI[0] = - cursor_left_upper_corner[0] cursorROI[2] -= cursorROI[0] imageROI[0] = 0 if cursor_left_upper_corner[1] < 0: #print "left upper edge of cursor is above image border" cursorROI[1] = - cursor_left_upper_corner[1] cursorROI[3] -= cursorROI[1] imageROI[1] = 0 if cursor_right_lower_corner[0] > image.width: #print "right lower edge of cursor is right of image" cursorROI[2] = cursor.width - (cursor_right_lower_corner[0] - image.width) if cursorROI[2] == 0: return # width of cursor would be zero if cursor_right_lower_corner[1] > image.height: #print "right lower edge of cursor is below image" cursorROI[3] = cursor.height - (cursor_right_lower_corner[1] - image.height) if cursorROI[3] == 0: return # height of cursor would be zero imageROI[2] = cursorROI[2] imageROI[3] = cursorROI[3] cv.SetImageROI(cursor, tuple(cursorROI)) cursorMask = cv.CreateImage((cursorROI[2], cursorROI[3]), cv.IPL_DEPTH_8U, 1) for row in xrange(cursorROI[3]): for col in xrange(cursorROI[2]): if cursor[row, col] != (0,0,0): cursorMask[row,col] = 1 else: cursorMask[row,col] = 0 cv.SetImageROI(image, tuple(imageROI)) cv.SubS(image, cv.Scalar(101, 101, 101), image, cursorMask) cv.Add(image, cursor, image) cv.ResetImageROI(image) def produceCurrentImage(self): """This method populates the video widget of the gui with the current video image. For more information, please look at the documentation of the Clock class.""" frame = self.clock.frame fr = self.overlayedFrame(frame, self.show_eyes[0], self.show_eyes[1], self.show_eyes[2]) return_frame = cv.CreateImage((self.video_reader.width, self.video_reader.height), cv.IPL_DEPTH_8U, 3) cv.Copy(fr, return_frame) cv.CvtColor(return_frame, return_frame, cv.CV_BGR2RGB) self.video_image = return_frame self.current_frame.value = frame self.video_str.value = return_frame.tostring() def exportVideo(self, output_file): """ Exports the overlayed video to a new video file by using the VideoWriter. """ frame_size = (self.getVideoWidth(), self.getVideoHeight()) vidfps = self.video_reader.fps codec = self.config.get('general', 'video_export_codec') video_writer = VideoWriter(output_file, frame_size, vidfps, codec) # you have to be sure _clock_tick is called before this function # otherwise video offset of one frame self.pause() self.seek(0) for frame in xrange(self.video_reader.frame_count): self.seek(frame) video_writer.addFrame(self.video_image) video_writer.releaseWriter() # ----------- PLAYBACK CONTROLL ---- def play(self): if not self.clock.running: self.clock.run() def pause(self): if self.clock.running: self.clock.stop() def seek(self, frame): try: self.clock.seek(frame) except ClockError: # seeked to a frame out of video pass def nextFrame(self): """Jump one frame ahead.""" self.seek(self.clock.frame + 1) def prevFrame(self): """Jump back one frame.""" self.seek(self.clock.frame - 1) def jumpToNextUncategorisedObject(self): """Jump to the next frame or fixation (depending on what the user entered in the project wizard) that is not categorised yet.""" frame = self.category_container.nextNotCategorisedIndex(self.clock.frame) self.seek(frame) def nextFixation(self): '''Jump to the next fixation.''' frame = self.eye_movement.nextFixationFrame(self.clock.frame, self.categorising_eye_is_left) self.seek(frame) def prevFixation(self): '''Jump to the previous fixation.''' frame = self.eye_movement.prevFixationFrame(self.clock.frame, self.categorising_eye_is_left) self.seek(frame) def slowerPlayback(self): self.clock.setMultiplicator(self.clock.multiplicator * 0.9) def fasterPlayback(self): self.clock.setMultiplicator(self.clock.multiplicator * 1.1) def setPlaybackSpeed(self, speed): self.clock.setMultiplicator(speed) # --------------- VIDEO INFORMATION ----- def getVideoStrLength(self): return len(self.video_reader.frame(0).tostring()) def getVideoHeight(self): return self.video_reader.height def getVideoWidth(self): return self.video_reader.width def getVideoFrameCount(self): return self.video_reader.frame_count def getVideoFrameRate(self): return self.video_reader.fps
def run_simulation(self): clock = Clock() # Read the file. self.parse_file() # Set the processing times. self.set_processing_times() self.theater.add_lines() # Jumps the simulation forward to when customers first arrive. clock.time = self.customer_arrival_time[0] print "Time %d - Simulation has started" % clock.time for q in range(len(self.theater.ticket_window_list)): self.idle_time.append(clock.time) # While the program hasn't reached the end (simulation time)... while clock.time != self.length_of_simulation + 1: # Loop through the windows for n in range(len(self.theater.ticket_window_list)): # Set the processing time for each window to a local variable. original_process_time = self.processing_time_for_window[n] - 1 # Check for the number of lines; 1 vs. n lines if self.number_of_ticket_lines == 1: y = 0 else: y = n # ISSUE: # Customer gets added to the wrong window. # This is a problem with matching index and windows inside move_customer() I think. # If we expect arrivals and the customer(s) haven't been added to the window yet (double-counting). if clock.time == self.customer_arrival_time[0] and self.customer_has_arrived_in_line is False: # Move the customers to the appropriate lines self.theater.delegate_line(self.number_of_customers[0]) self.customer_has_arrived_in_line = True # For every customer, print how many have been added. for q in range(self.number_of_customers[0]): print "Time %d - Customer entered line %d" % \ (clock.time, self.theater.ticket_line_list[y].line_number) # If there is no one at the window and we can add customers to the line (length >=1), # move the customer from the line to the window. # 1) if self.theater.ticket_window_list[n].customer_occupied_window is False: self.theater.move_customer() print "Time %d - Customer exited line %d" % \ (clock.time, self.theater.ticket_line_list[y].line_number) print "Time %d - Customer entered window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) self.theater.ticket_window_list[n].process_time -= 1 # Given that we add customers to the line, we already prove that len >= 1; # If there is someone at the window, check to see if they're done. If # they're not done, decrement the processing time for that window. # 2) elif self.theater.ticket_window_list[n].customer_occupied_window is True and \ self.theater.ticket_window_list[n].process_time != 0: self.theater.ticket_window_list[n].process_time -= 1 # Given that we add customers to the line, we already prove that len >= 1 # If there is someone at the window, check to see if they're done. If # they are done, remove them from the window and add someone from line to window. # Reset the processing time for that window and decrement it, since one second has passed. # 3) elif self.theater.ticket_window_list[n].customer_occupied_window is True and \ self.theater.ticket_window_list[n].process_time == 0: self.theater.move_customer() print "Time %d - Customer left window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) print "Time %d - Customer exited line %d" % \ (clock.time, self.theater.ticket_line_list[y].line_number) print "Time %d - Customer entered window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) self.theater.ticket_window_list[n].process_time = original_process_time self.theater.ticket_window_list[n].process_time -= 1 # 4) else: self.idle_time[n] += 1 else: # 1) if self.theater.ticket_window_list[n].customer_occupied_window is False and \ len(self.theater.ticket_line_list[y]) >= 1: self.theater.move_customer() print "Time %d - Customer exited line %d" % \ (clock.time, self.theater.ticket_line_list[y].line_number) print "Time %d - Customer entered window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) self.theater.ticket_window_list[n].process_time -= 1 # 2) elif self.theater.ticket_window_list[n].customer_occupied_window is True and \ self.theater.ticket_window_list[n].process_time != 0: self.theater.ticket_window_list[n].process_time -= 1 # 3) elif self.theater.ticket_window_list[n].customer_occupied_window is True and \ self.theater.ticket_window_list[n].process_time == 0 and \ len(self.theater.ticket_line_list[y]) >= 1: self.theater.move_customer() print "Time %d - Customer left window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) print "Time %d - Customer exited line %d" % \ (clock.time, self.theater.ticket_line_list[y].line_number) print "Time %d - Customer entered window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) self.theater.ticket_window_list[n].process_time = original_process_time # 4) elif self.theater.ticket_window_list[n].customer_occupied_window is True and \ self.theater.ticket_window_list[n].process_time == 0 and \ len(self.theater.ticket_line_list[y]) == 0: self.theater.move_customer() print "Time %d - Customer left window %d" % \ (clock.time, self.theater.ticket_window_list[n].window_number) self.idle_time[n] += 1 # 5) else: self.idle_time[n] += 1 if len(self.theater.ticket_line_list[y]) >= 1 and clock.time == self.length_of_simulation: self.length_of_lines_at_the_end += len(self.theater.ticket_line_list[y]) else: pass self.customer_has_arrived_in_line = False # This is a way to control iterations such that we get rid of a list element # once an arrival time happens. if clock.time == self.customer_arrival_time[0] and len(self.customer_arrival_time) >= 2: self.customer_arrival_time.pop(0) self.number_of_customers.pop(0) else: pass # Increment the time after we check all the windows. clock.time += 1
class PreludeTimer(QtGui.QWidget): request_length = QtCore.Signal() prelude_exit = QtCore.Signal() def __init__(self, parent=None): super(PreludeTimer, self).__init__(parent) self.title = 'SafetyPlay - Prelude Timer' self.settings = load() self.setupUi() self.clock = Clock() self.save_timer = SaveCloser() self.resizer = Resizer() self.font_color_picker = ColorChooser() self.font_color_picker.setCurrentColor(self.settings['f_color']) self.bg_color_picker = ColorChooser() self.bg_color_picker.setCurrentColor(self.settings['bg_color']) self.setupActions() def time_changed(self): h = self.start_time_editor.time().hour() m = self.start_time_editor.time().minute() s = self.start_time_editor.time().second() save(gotime=[h, m, s]) self.settings['gotime'] = [h, m, s] self.clock.settings['gotime'] = [h, m, s] self.clock.advance_timer() self.resizer.start() def set_to_current_time(self): h = int(time.strftime('%H')) m = int(time.strftime('%M')) s = int(time.strftime('%S')) self.start_time_editor.setTime(QtCore.QTime(h, m, s)) def change_time(self, seconds): h = self.start_time_editor.time().hour() m = self.start_time_editor.time().minute() s = self.start_time_editor.time().second() new_s = abs(seconds) ha = new_s // 3600 ma = int((new_s % 3600)/60) sa = int((new_s % 3600) % 60) if seconds < 0: ha = ha * -1 ma = ma * -1 sa = sa * -1 if s + sa < 60 and s + sa > -1: s = s + sa elif s + sa > 59: s = s + sa - 60 ma += 1 elif s + sa < 0: s = s + sa + 60 ma -= 1 if m + ma < 60 and m + ma > -1: m = m + ma elif m + ma > 59: m = m + ma - 60 ha += 1 elif m + ma < 0: m = m + ma + 60 ha -= 1 if h + ha < 24 and h + ha > -1: h = h + ha elif h + ha == 24: h = h + ha - 24 elif h + ha < 0: h = h + ha + 24 self.start_time_editor.setTime(QtCore.QTime(h, m, s)) def change_font_style(self): save(font=self.font_style_combobox.currentText()) self.settings['font'] = self.font_style_combobox.currentText() self.clock.label.setFont(QtGui.QFont( self.settings['font'], int(self.settings['f_size']))) self.resizer.start() def change_font_size(self): save(f_size=self.font_size_combobox.currentText()) self.settings['f_size'] = self.font_size_combobox.currentText() self.clock.label.setFont(QtGui.QFont( self.settings['font'], int(self.settings['f_size']))) self.resizer.start() def preview_font_color(self, color): color = color.name() self.font_color_button.setStyleSheet("background-color:" + color) self.clock.label.setStyleSheet("color:" + color) def change_font_color(self, color): color = color.name() self.font_color_button.setStyleSheet("background-color:" + color) self.clock.label.setStyleSheet("color:" + color) self.settings['f_color'] = color save(f_color=color) def check_font_color(self): color = self.font_color_picker.currentColor().name() if not color == self.settings['f_color']: self.font_color_button.setStyleSheet( "background-color:" + self.settings['f_color']) self.clock.label.setStyleSheet( "color:" + self.settings['f_color']) def preview_bg_color(self, color): color = color.name() self.bg_color_button.setStyleSheet("background-color:" + color) self.clock.setStyleSheet("background-color:" + color) def change_bg_color(self, color): color = color.name() self.bg_color_button.setStyleSheet("background-color:" + color) self.clock.setStyleSheet("background-color:" + color) self.settings['bg_color'] = color save(bg_color=color) def check_bg_color(self): color = self.bg_color_picker.currentColor().name() if not color == self.settings['bg_color']: self.bg_color_button.setStyleSheet( "background-color:" + self.settings['bg_color']) self.clock.setStyleSheet( "background-color:" + self.settings['bg_color']) def browse_to_presenter(self): userhome = os.path.expanduser('~') file, _ = QtGui.QFileDialog.getOpenFileName( self, 'Open file', userhome, "*.exe") if file != '': file = file.replace('/', '\\') self.settings['presenter'] = file self.presenter_line_edit.setText(file) save(presenter=file) def browse_to_presentation(self): userhome = os.path.expanduser('~') file, _ = QtGui.QFileDialog.getOpenFileName( self, 'Open file', userhome, "") if file != '': file = file.replace('/', '\\') self.settings['presentation'] = file self.presentation_line_edit.setText(file) save(presentation=file) def moveEvent(self, event): self.save_timer.start() def save_stuff(self): pos = [self.x(), self.y()] resto = self.audio_restore_slider.value() save(prelude_pos = pos, restore_volume=resto) def closeEvent(self, event): self.clock.close() self.prelude_exit.emit() self.save_timer.terminate() self.resizer.terminate() def setupActions(self): self.save_timer.time_up.connect(self.save_stuff) self.start_time_editor.timeChanged.connect(self.time_changed) self.current_time_button.clicked.connect(self.set_to_current_time) self.playlist_end_button.clicked.connect(self.request_length.emit) self.plus_minute_button.clicked.connect(lambda: self.change_time(60)) self.minus_minute_button.clicked.connect(lambda: self.change_time(-60)) self.font_style_combobox.currentIndexChanged.connect( self.change_font_style) self.font_color_button.clicked.connect(self.font_color_picker.open) self.font_color_picker.currentColorChanged.connect( self.preview_font_color) self.font_color_picker.colorSelected.connect(self.change_font_color) self.font_color_picker.close_signal.connect(self.check_font_color) self.font_size_combobox.currentIndexChanged.connect( self.change_font_size) self.bg_color_button.clicked.connect(self.bg_color_picker.open) self.bg_color_picker.currentColorChanged.connect(self.preview_bg_color) self.bg_color_picker.colorSelected.connect(self.change_bg_color) self.bg_color_picker.close_signal.connect(self.check_bg_color) self.fade_audio_checkbox.clicked.connect( lambda: save(fade_audio=self.fade_audio_checkbox.isChecked())) self.audio_restore_slider.valueChanged.connect(self.save_timer.start) self.jump_to_next_checkbox.clicked.connect( lambda: save(jump_end=self.jump_to_next_checkbox.isChecked())) self.jump_to_next_checkbox.clicked.connect( lambda: save(pause_end=self.pause_playback_checkbox.isChecked())) self.press_f5_checkbox.clicked.connect( lambda: save(press_f5=self.press_f5_checkbox.isChecked())) self.kill_video_checkbox.clicked.connect( lambda: save(kill_video=self.kill_video_checkbox.isChecked())) self.presentation_checkbox.clicked.connect( lambda: save(start_presentation=self.presentation_checkbox.isChecked())) self.presenter_button.clicked.connect(self.browse_to_presenter) self.presentation_button.clicked.connect(self.browse_to_presentation) self.start_timer_button.clicked.connect(lambda: self.clock.show()) self.end_timer_button.clicked.connect(lambda: self.clock.hide()) self.resizer.time_up.connect(lambda: self.clock.resize(0, 0)) self.presenter_line_edit.textChanged.connect( lambda: save(presenter=self.presenter_line_edit.displayText())) self.presentation_line_edit.textChanged.connect( lambda: save(presentation=self.presentation_line_edit.displayText())) def setupUi(self): self.setWindowTitle(self.title) self.setWindowIcon(SafetyPlayIcon()) self.setFixedSize(0, 0) self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint) pos = self.settings['prelude_pos'] self.move(pos[0], pos[1]) self.VL = QtGui.QVBoxLayout(self) self.HL_1 = QtGui.QHBoxLayout() self.start_time_label = QtGui.QLabel() self.start_time_label.setText('Presentation Start Time: ') self.start_time_label.setMaximumSize(QtCore.QSize(150, 16777215)) self.HL_1.addWidget(self.start_time_label) self.start_time_editor = QtGui.QTimeEdit() g = self.settings['gotime'] self.start_time_editor.setTime(QtCore.QTime(g[0], g[1], g[2])) self.HL_1.addWidget(self.start_time_editor) self.VL.addLayout(self.HL_1) self.HL_2 = QtGui.QHBoxLayout() self.current_time_button = QtGui.QPushButton() self.current_time_button.setText('Current Time') self.HL_2.addWidget(self.current_time_button) self.playlist_end_button = QtGui.QPushButton() self.playlist_end_button.setText('Current Media End Time') self.HL_2.addWidget(self.playlist_end_button) self.VL.addLayout(self.HL_2) self.HL_3 = QtGui.QHBoxLayout() self.plus_minute_button = QtGui.QPushButton() self.plus_minute_button.setText('+1 Minute') self.HL_3.addWidget(self.plus_minute_button) self.minus_minute_button = QtGui.QPushButton() self.minus_minute_button.setText('-1 Minute') self.HL_3.addWidget(self.minus_minute_button) self.VL.addLayout(self.HL_3) self.line_1 = QtGui.QFrame() self.line_1.setFrameShape(QtGui.QFrame.HLine) self.line_1.setFrameShadow(QtGui.QFrame.Sunken) self.VL.addWidget(self.line_1) self.HL_4 = QtGui.QHBoxLayout() self.font_style_label = QtGui.QLabel() self.font_style_label.setText('Clock Font:') self.font_style_label.setMaximumSize(QtCore.QSize(70, 16777215)) self.HL_4.addWidget(self.font_style_label) self.font_style_combobox = QtGui.QFontComboBox() self.font_style_combobox.setCurrentFont( QtGui.QFont(self.settings['font'])) self.HL_4.addWidget(self.font_style_combobox) self.VL.addLayout(self.HL_4) self.HL_5 = QtGui.QHBoxLayout() self.font_size_label = QtGui.QLabel() self.font_size_label.setText('Font Size:') self.font_size_label.setMaximumSize(QtCore.QSize(70, 16777215)) self.HL_5.addWidget(self.font_size_label) self.font_size_combobox = QtGui.QComboBox() self.font_size_combobox.setMaximumSize(QtCore.QSize(50, 16777215)) self.font_sizes = ["20", "24", "28", "30", "34", "38", "40", "44", "48", "52", "56", "60", "64", "68", "72"] self.font_size_combobox.insertItems(0, self.font_sizes) self.font_size_combobox.setCurrentIndex( self.font_sizes.index(self.settings['f_size'])) self.HL_5.addWidget(self.font_size_combobox) self.font_size_color_line = QtGui.QFrame() self.font_size_color_line.setFrameShape(QtGui.QFrame.VLine) self.font_size_color_line.setFrameShadow(QtGui.QFrame.Sunken) self.HL_5.addWidget(self.font_size_color_line) self.font_color_label = QtGui.QLabel() self.font_color_label.setText('Font Color:') self.font_color_label.setMaximumSize(QtCore.QSize(70, 16777215)) self.HL_5.addWidget(self.font_color_label) self.font_color_button = QtGui.QToolButton() self.font_color_button.setMinimumSize(QtCore.QSize(25, 25)) self.font_color_button.setMaximumSize(QtCore.QSize(25, 25)) self.font_color_button.setText("") self.font_color_button.setStyleSheet( ''.join(["background-color:", self.settings['f_color']])) self.HL_5.addWidget(self.font_color_button) self.font_color_bg_color_line = QtGui.QFrame() self.font_color_bg_color_line.setFrameShape(QtGui.QFrame.VLine) self.font_color_bg_color_line.setFrameShadow(QtGui.QFrame.Sunken) self.HL_5.addWidget(self.font_color_bg_color_line) self.bg_color_label = QtGui.QLabel() self.bg_color_label.setText('Bg Color:') self.bg_color_label.setMaximumSize(QtCore.QSize(60, 16777215)) self.HL_5.addWidget(self.bg_color_label) self.bg_color_button = QtGui.QToolButton() self.bg_color_button.setMinimumSize(QtCore.QSize(25, 25)) self.bg_color_button.setMaximumSize(QtCore.QSize(25, 25)) self.bg_color_button.setText("") self.bg_color_button.setStyleSheet( ''.join(["background-color:", self.settings['bg_color']])) self.HL_5.addWidget(self.bg_color_button) self.VL.addLayout(self.HL_5) self.line_2 = QtGui.QFrame() self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.VL.addWidget(self.line_2) self.on_timer_end_label = QtGui.QLabel() self.on_timer_end_label.setText('On Timer End:') self.VL.addWidget(self.on_timer_end_label) self.HL_7 = QtGui.QHBoxLayout() self.fade_audio_checkbox = QtGui.QCheckBox() self.fade_audio_checkbox.setText('Fade Audio') self.fade_audio_checkbox.setChecked(self.settings['fade_audio']) self.HL_7.addWidget(self.fade_audio_checkbox) self.audio_restore_label = QtGui.QLabel() self.audio_restore_label.setText('Restore Audio:') self.HL_7.addWidget(self.audio_restore_label) self.audio_restore_slider = QtGui.QSlider() self.audio_restore_slider.setMaximum(100) self.audio_restore_slider.setSliderPosition( self.settings['restore_volume']) self.audio_restore_slider.setOrientation(QtCore.Qt.Horizontal) self.HL_7.addWidget(self.audio_restore_slider) self.VL.addLayout(self.HL_7) self.pause_playback_checkbox = QtGui.QCheckBox() self.pause_playback_checkbox.setText('Pause Playback') self.pause_playback_checkbox.setChecked(self.settings['pause_end']) self.VL.addWidget(self.pause_playback_checkbox) self.jump_to_next_checkbox = QtGui.QCheckBox() self.jump_to_next_checkbox.setText('Jump to next item in playlist') self.jump_to_next_checkbox.setChecked(self.settings['jump_end']) self.VL.addWidget(self.jump_to_next_checkbox) self.press_f5_checkbox = QtGui.QCheckBox() self.press_f5_checkbox.setText('Press F5') self.press_f5_checkbox.setChecked(self.settings['press_f5']) self.VL.addWidget(self.press_f5_checkbox) self.kill_video_checkbox = QtGui.QCheckBox() self.kill_video_checkbox.setText('Close Video Window') self.kill_video_checkbox.setChecked(self.settings['kill_video']) self.VL.addWidget(self.kill_video_checkbox) self.presentation_checkbox = QtGui.QCheckBox() self.presentation_checkbox.setText( 'Open Presentation (5 seconds early)') self.presentation_checkbox.setChecked( self.settings['start_presentation']) self.VL.addWidget(self.presentation_checkbox) self.HL_8 = QtGui.QHBoxLayout() self.presenter_label = QtGui.QLabel() self.presenter_label.setText('Software Path:') self.presenter_label.setMaximumSize(QtCore.QSize(85, 16777215)) self.presenter_label.setAlignment(QtCore.Qt.AlignCenter) self.HL_8.addWidget(self.presenter_label) self.presenter_button = QtGui.QPushButton() self.presenter_button.setText('Browse') self.HL_8.addWidget(self.presenter_button) self.presenter_line_edit = QtGui.QLineEdit() self.presenter_line_edit.setReadOnly(True) self.presenter_line_edit.setText(self.settings['presenter']) self.HL_8.addWidget(self.presenter_line_edit) self.VL.addLayout(self.HL_8) self.HL_9 = QtGui.QHBoxLayout() self.presentation_label = QtGui.QLabel() self.presentation_label.setText('File Path:') self.presentation_label.setMinimumSize(QtCore.QSize(85, 16777215)) self.presentation_label.setAlignment(QtCore.Qt.AlignCenter) self.HL_9.addWidget(self.presentation_label) self.presentation_button = QtGui.QPushButton() self.presentation_button.setText('Browse') self.HL_9.addWidget(self.presentation_button) self.presentation_line_edit = QtGui.QLineEdit() self.presentation_line_edit.setReadOnly(True) self.presentation_line_edit.setText(self.settings['presentation']) self.HL_9.addWidget(self.presentation_line_edit) self.VL.addLayout(self.HL_9) self.HL_10 = QtGui.QHBoxLayout() self.start_timer_button = QtGui.QPushButton() self.start_timer_button.setText('Start Timer') self.HL_10.addWidget(self.start_timer_button) self.end_timer_button = QtGui.QPushButton() self.end_timer_button.setText('End Timer') self.HL_10.addWidget(self.end_timer_button) self.VL.addLayout(self.HL_10)
class Overseer(object): sim_time = 120#Default simulation time mode = "Deterministic"#Default mode def __init__(self, mode, num_agents,sites,name, id): self.mode = mode#the type of simulation. Deterministic mode == agents that have constant page and home times. Variable == agents that have page and home times that change self.num_agents = num_agents self.rando = Random() self.curr_agents_surfing = []#list of agents who are currently surfing the web self.all_agents = []#list of all agents who have finished surfing the web and agents who are currently surfing the web self.threads = []#Each agent surfing has a thread self.agents_finished_surfing = 0 self.sites = sites#List of homepages available to visit self.name = name#the name of the overseer self.id = id#the id number for the overseer. Overseer 4 should have id = 4 self.clock = Clock() #This method will spawn an agent. #Each agent is unique and will surf the web def spawn_agent(self): lifespan = (self.rando.randint(60,400))#lifespan of the agent, agent stops surfing once lifespan is reached(60,400) pagetime = (self.rando.randint(10,40))#Time spent on a page within a website, i.e youtube.com/watch...(10,40) hometime = (self.rando.randint(60,180))#Time spent on a website from the list of sites, i.e youtube.com(60,180) name = str(self.name) + " Agent " + str(len(self.all_agents)+1)#name = Overseer x: Agent y new_agent = Agent(self.clock.get_time_passed(), self.sites,(pagetime),(hometime), name, (lifespan),self.clock) print("") print("Created an agent") new_agent.print_params() print("") new_thread = surfThread(new_agent,Overseer.sim_time, self.mode, self.clock) new_thread.start()#Agent begins surfing the web self.threads.append(new_thread) self.curr_agents_surfing.append(new_agent) self.all_agents.append(new_agent) def run_overseer(self): #Spawns the number of agents this overseer is responsible for self.clock.start() for i in range(0,(self.num_agents)): self.spawn_agent() #Makes sure the desired number of agents are surfing #Will keep checking until simulation ends while(self.clock.get_time_passed() < Overseer.sim_time): self.maintain_agents() print("") #Spawns a new agent when another agent reaches the end of its lifespan #This keeps the desired number of agents surfing for this overseer def maintain_agents(self): for agent in self.curr_agents_surfing: if agent.surfing == False and self.clock.get_time_passed() < Overseer.sim_time:#Checks the clock to make sure an agent isnt spawned after the simulation is supposed to end self.agents_finished_surfing+=1 self.curr_agents_surfing.remove(agent) self.spawn_agent()
def main( ): global mapa, block_list, all_sprites_list#, xMapa, yMapa, yMapaDim, xMapaDim global DICC_IMAGENES, JUGADOR_IMAGEN, ventana #block_list = pygame.sprite.Group() all_sprites_list = pygame.sprite.Group() ventana = pygame.display.set_mode( ( ANCHO, ALTO ) ) pygame.display.set_caption( "Juego" ) FPSreloj = pygame.time.Clock( ) jugador = Jugador( TILE_ANCHO, TILE_ALTO ) jugador.setPosicionInicial( 360, 425) y = int( ANCHO / TILE_ANCHO ) x = int ( ALTO / TILE_ALTO ) #------------------------ # Diccionario de imagenes #------------------------ DICC_IMAGENES = { 'mesa' : pygame.image.load( 'mesa.png' ), 'jugador' : pygame.image.load( 'jugador.png' ), 'pisoSombra' : pygame.image.load( 'piso4.png' ), 'pisoNormal' : pygame.image.load( 'pisoNormal.png' ), 'companiero1' : pygame.image.load( 'companiero1.png' ), 'malo': pygame.image.load('malo.png') } #------------------------------------- # Diccionario de las imagenes del mapa #------------------------------------- hud = None malo1 = None malo2 = None malo3 = None companiero1 = None companiero2 = None companiero3 = None mundoReal = None mapaLogico = None listaMapa = None preguntas = Preguntas( ) #all_sprites_list.add(jugador) #se usará una vez que tengamos más personajes moverSeCompaniero1 = None moverSeCompaniero2 = None moverSeCompaniero3 = None ir_a = None incremento = None direccion = None SPEED = 0.1 #SPEED_MALO = 0.08 moverJugadorA = None gameover = False jugarDenuevo = True #para la demostracion quedarSe = False respuesta = None muestraPregunta = True modoPregunta = False esMalo = False pausarJuego = False clock = None while True: if pausarJuego: pausarJuego = captureEvent() continue FPSreloj.tick( FPS ) if jugarDenuevo: #ESTO NO ME GUSTA malo1 = Malo("malo.png", (6, 2), TILE_ANCHO, TILE_ALTO) malo2 = Malo("malo.png", (1, 0), TILE_ANCHO, TILE_ALTO) malo3 = Malo("malo.png", (0, 12), TILE_ANCHO, TILE_ALTO) jugador.setPosicionInicial( 360, 425) mundoReal = MundoReal( TILE_ANCHO, TILE_ALTO, ANCHO, ALTO ) mapaLogico = ElMapa( x, y, jugador.rect.y / TILE_ALTO, jugador.rect.x / TILE_ANCHO) listaMapa = mapaLogico.leerMapa( 'mapa.txt' ) mundoReal.dibujarMundoReal( listaMapa, ventana, DICC_IMAGENES ) companiero1 = Companiero( 2, 8, TILE_ANCHO, TILE_ALTO ) companiero2 = Companiero( 2, 2, TILE_ANCHO, TILE_ALTO ) companiero3 = Companiero( 4, 5, TILE_ANCHO, TILE_ALTO ) hud = Hud( ) clock = Clock() moverSeCompaniero1 = False moverSeCompaniero2 = False moverSeCompaniero3 = False quedarSe = False ir_a = None incremento = None direccion = None moverJugadorA = None gameover = False jugarDenuevo = True respuesta = None muestraPregunta = True modoPregunta = False esMalo = False jugarDenuevo = False #print "aaaaaaa" if not( modoPregunta ): mundoReal.dibujarMundoReal( listaMapa, ventana, DICC_IMAGENES ) jugador.draw( ventana ) companiero1.draw( ventana ) companiero2.draw( ventana ) companiero3.draw( ventana ) malo1.draw( ventana ) malo2.draw( ventana ) malo3.draw( ventana ) hud.draw( ventana, esMalo ) if gameover: jugarDenuevo = jugador.gameOver( ventana ) if jugarDenuevo: gameover = False esMalo = False clock.mainClock( ventana, gameover ) pygame.display.flip() if gameover: #solo reinicia el bucle continue if quedarSe: quedarSe = quedarSeGetEvent() if respuesta: pygame.time.wait( 2000 ) respuesta = None #print "bbbbbb" if ir_a and quedarSe == False: if jugador.moverSe( incremento, ir_a, mapaLogico ): actualizaElIndiceDelJugador( mapaLogico, direccion ) ir_a = None incremento = None direccion = None #if not( moverSeCompaniero1 ): #print companiero1.getPosY( ) tupla = companiero1.debeInteractuar( mapaLogico, jugador, listaMapa,TILE_ANCHO, TILE_ALTO ) if tupla: modoPregunta = tupla[ 1 ] moverSeCompaniero1 = tupla[ 0 ] if modoPregunta: muestraPregunta = True #print "modoPregunta: %d" % modoPregunta if not( modoPregunta ): tupla = companiero2.debeInteractuar( mapaLogico, jugador, listaMapa,TILE_ANCHO, TILE_ALTO ) if tupla: modoPregunta = tupla[ 1 ] moverSeCompaniero2 = tupla[ 0 ] muestraPregunta = True if not( modoPregunta ): #print "companiero3" tupla = companiero3.debeInteractuar( mapaLogico, jugador, listaMapa,TILE_ANCHO, TILE_ALTO ) if tupla: modoPregunta = tupla[ 1 ] moverSeCompaniero3 = tupla[ 0 ] muestraPregunta = True #continue if malo1.maloMain( jugador.posObjMatriz, mapaLogico, listaMapa, modoPregunta, TILE_ANCHO, TILE_ALTO, ir_a): gameover = True elif malo2.maloMain( jugador.posObjMatriz, mapaLogico, listaMapa, modoPregunta, TILE_ANCHO, TILE_ALTO, ir_a): gameover = True elif malo3.maloMain( jugador.posObjMatriz, mapaLogico, listaMapa, modoPregunta, TILE_ANCHO, TILE_ALTO, ir_a): gameover = True if ir_a: continue #print "cccccccc1" if modoPregunta: if muestraPregunta: pygame.time.wait( 1000 ) preguntas.dibujarPregunta( ventana ) muestraPregunta = False respuesta = preguntas.elegirOpcion( preguntas ) if respuesta: modoPregunta = False if respuesta == '4': esMalo = True continue #print "cccccccc2" if moverSeCompaniero1: tupla = companiero1.interactuando( modoPregunta, listaMapa ) modoPregunta = tupla[ 1 ] moverSeCompaniero1 = tupla[ 0 ] continue elif moverSeCompaniero2: tupla = companiero2.interactuando( modoPregunta, listaMapa ) modoPregunta = tupla[ 1 ] moverSeCompaniero2 = tupla[ 0 ] continue elif moverSeCompaniero3: #print "cccccccc3" tupla = companiero3.interactuando( modoPregunta, listaMapa ) modoPregunta = tupla[ 1 ] moverSeCompaniero3 = tupla[ 0 ] print moverSeCompaniero3 continue #print "dddddd" #blocks_hit_list = pygame.sprite.spsritecollide(jugador, block_list, True) #all_sprites_list.draw(ventana) #se usará una vez que tengamos más personajes #if moverJugadorA == None: #con esto se evita que e mueva en otra direccion durante el movimiento for event in pygame.event.get( ): # event handling loop. Captura eventos del teclado una vez que se haya #presionado una tecla if event.type == QUIT: pygame.quit sys.exit( 0 ) elif event.type == KEYDOWN: if event.key == K_RIGHT: moverJugadorA = "DERECHA" elif event.key == K_LEFT: moverJugadorA = "IZQUIERDA" elif event.key == K_DOWN: moverJugadorA = "ABAJO" elif event.key == K_UP: moverJugadorA = "ARRIBA" elif event.key == K_SPACE: pausarJuego = True elif event.key == K_q: if quedarSe == False: quedarSe = True else: quedarSe = False pygame.time.wait(5000) #print "eeeeee" if moverJugadorA != None: puedeMoverse = mapaLogico.estaLibre( moverJugadorA, mapaLogico ) if puedeMoverse: #esMalo = True ir_a = jugador.getPosicionsObjetivo( moverJugadorA, mapaLogico ) pos_actual = jugador.posicionActual( mapaLogico.getXDelJugador( ) , mapaLogico.getYDelJugador( ) ) incremento = ( ( ( ir_a[ 0 ] - pos_actual[ 0 ] ) * SPEED ), ( ( ir_a[ 1 ] - pos_actual[ 1 ] ) * SPEED ) ) direccion = moverJugadorA #moverJugadorA = None return 0
def tick(self): previous_hour = self.hours Clock.tick(self) if self._hours < previous_hour: self.advance()
def __init__(self, day, month, year, hour, minute, second): Clock.__init__(self, hour, minute, second) Calendar.__init__(self, day, monts, year)
def __str__(self): return Calendar.__str__(self) + ", " + Clock.__str__(self)
class Serv(Thread): def __init__(self, port): Thread.__init__(self) ip = socket.gethostbyname(socket.gethostname()) self.server = SimpleThreadedXMLRPCServer((ip, port), allow_none=True) self.server.register_introspection_functions() self.server.register_multicall_functions() self.server.register_instance(Api(self), allow_dotted_names=True) self.ctr = 0 self.addr = ip + ":" + str(port) self.net_members = [self.addr] self.string_queue = deque() self.status = False self.master_string = "" self.master_address = "" self.is_interested_in_master_string = False self.is_victory_broadcasted = False self.clock = Clock(self.addr) self.wordListToCheck = [] print("Serv created") def run(self): self.server.serve_forever() print("Serv started") def incr(self): self.ctr += 1 print(self.ctr) def get_clock(self): return self.clock def leave(self): self.net_members.remove(self.addr) self.set_status(False) for node in self.net_members: get_node_by_addr(node).deleteNode(self.addr) if(self.master_address == self.addr and len(self.net_members) > 1): get_node_by_addr(self.net_members[0]).runBully() for node in self.net_members: get_node_by_addr(node).setVictoryBroadcasted(False) self.net_members = [self.addr] self.master_address = "" self.masterString = "" self.is_victory_broadcasted = False; def join_net(self, addr): if addr.startswith("127.0.0.1") or addr.startswith("localhost"): asp = addr.split(":") ip = socket.gethostbyname(socket.gethostname()) addr = ip + ":" + asp[1] destApi = get_node_by_addr(addr) for node in destApi.getNetworkMembers(): if node not in self.net_members: self.net_members.append(node) for node in self.net_members: if self.addr != node: get_node_by_addr(node).appendNode(self.addr) if destApi.getMasterAddress() == "": self.run_bully() for node in self.net_members: get_node_by_addr(node).setVictoryBroadcasted(False) else: self.master_address = destApi.getMasterAddress() def set_status(self, st): self.status = st def get_status(self): return self.status def get_net_members(self): return self.net_members def set_net_members(self, members): self.net_members = members def append_node(self, addr): self.status = True if addr not in self.net_members: print("Adding node " + addr) self.net_members.append(addr) def delete_node(self, address): if address in self.net_members: self.net_members.remove(address) if len(self.net_members) == 1: self.status = False def get_master_string(self): if self.master_address == self.addr: return self.master_string else: return get_node_by_addr(self.master_address).getMasterString() def get_master_address(self): return self.master_address def have_fun(self, isAgrawala): self.wordListToCheck = [] print("Having fun") master = get_node_by_addr(self.master_address) stTime = time.time() while (time.time() - stTime) < 20: time.sleep(random.randint(1,20)) w = get_random_word() self.wordListToCheck.append(w) if not isAgrawala: print("Sent request for access critical section") master.appendMasterStringRequest(self.addr) print("Entering critical section") ms = master.getMasterString() print("Got master string " + ms) master.setMasterString(ms+w) print("Appending word " + w) master.appendMasterStringRelease(self.addr) print("Left critical section") else: self.agrawala_append_string_request(w) def adventure_time(self, isAgrawala): print("Adventure time!") self.check_master_avaliability() threads = [] for node in self.net_members: a = get_node_by_addr(node) t = threading.Thread(target=a.haveFun, args=(isAgrawala,)) threads.append(t) t.start() for t in threads: t.join() for node in self.net_members: a = get_node_by_addr(node) a.checkAppend() def checkAppend(self): ms = self.get_master_string() print("Node: " + self.addr + ", master string: " + ms); failedWords = [] for word in self.wordListToCheck: if word not in ms: failedWords.append(word) if len(failedWords) == 0: print("All the appended words are in the master string: " + ','.join(self.wordListToCheck)) else: print("The following words were not appended into master string " + ','.join(failedWords)) def run_bully(self): electionSleepTime = 1 isThereAnybodyHere = False threads = [] for node in self.net_members: if node > self.addr: try: a = get_node_by_addr(node) t1 = threading.Thread(target=a.runBully) t1.start() threads.append(t1) isThereAnybodyHere = True except ValueError as e: print(e) for t in threads: t.join() if isThereAnybodyHere: time.sleep(electionSleepTime) if not self.is_victory_broadcasted: self.run_bully() else: for node in self.net_members: get_node_by_addr(node).setVictoryBroadcasted(True) self.set_master(self.addr) def election_broadcast(self, source_addr): print("Broadcasting elections") threading.Thread(target=self.run_bully).start() return True def set_victory_broadcasted(self, status): print("broadcasting victory") self.is_victory_broadcasted = status def agrawala_append_string_request(self, word): self.clock.tick() threads = [] for node in self.net_members: if not self.addr == node: a = get_node_by_addr(node) self.clock.tick() cl = self.clock.get_val() t = threading.Thread(target=a.agrawalaAppendHandle, args=(cl,)) threads.append(t) t.start() for t in threads: t.join() print("Node is in critical section") self.clock.tick() master = get_node_by_addr(self.master_address) print("Want to append word " + word) self.clock.tick() ms = master.getMasterString() print("Got master string:" + ms) self.clock.tick() master.setMasterString(ms+word) self.clock.tick() self.is_interested_in_master_string = False print("Left critical section") self.clock.tick() def agrawala_append_handler(self, timestamp): self.clock.tick() if self.clock.get_val().get("val") < timestamp.get("val"): self.clock.set_clock(timestamp.get("val") + 1) else: self.clock.tick() while self.is_interested_in_master_string and self.clock.compareTo(timestamp) < 0: time.sleep(1) self.clock.tick() def append_master_string_request(self, source_addr): self.string_queue.appendleft(source_addr) while self.string_queue[-1] != source_addr: time.sleep(1) def set_master_string(self, s): self.master_string = s def append_master_string(self, s): self.master_string += s def set_master_addr(self, addr): self.master_address = addr def set_master(self, newIp): print("New master elected with addr " + newIp) #get old params oldString = "" try: oldMaster = get_node_by_addr(self.master_address) oldString = oldMaster.getMasterString() oldMaster.setMasterString("") except: pass #find new master newMaster = get_node_by_addr(newIp) newMaster.setMasterString(oldString) #set master ip for others for node in self.net_members: get_node_by_addr(node).setMasterAddress(newIp) #TODO may be it is worth setting isVictoryBroadcasted to false here and in Java def get_addr(self): return self.addr def check_master_avaliability(self): #checking if master is alive try: get_node_by_addr(self.master_address).getStatus() except: self.net_members.remove(self.master_address) for node in self.net_members: get_node_by_addr(node).deleteNode(self.master_address) self.run_bully() def get_word_list_to_check(self): return self.wordListToCheck def apppend_master_string_release(self, sourceAddr): if self.string_queue[-1] == sourceAddr: #todo check popping queue self.string_queue.pop()
class Kernel: def __init__(self, cpu, mmu, hard_disk, scheduling_policy=RoundRobin(3)): self.pids = 0 # Queues self.ready_queue = queue.Queue() # Hardware self.hard_disk = hard_disk self.mmu = mmu # Interruption Manager self.interruption_manager = InterruptionManager(self) # Scheduling self.short_term_scheduler = ShortTermScheduler(self.ready_queue, scheduling_policy) self.long_term_scheduler = LongTermScheduler(self.ready_queue) # Cpu self.cpu = cpu self.cpu.set_scheduler(self.short_term_scheduler) self.cpu.set_mmu(self.mmu) self.cpu.set_interruption_manager(self.interruption_manager) # IO self.console = Console() self.io = IODevice(self.interruption_manager) self.clock = Clock("Cpu - IntManager clock", [self.cpu, self.interruption_manager]) #=============== #=== Methods === #=============== def save_program(self, program): self.hard_disk.save_program(program) def run(self, programs_name): # get program program = self.hard_disk.get_program(programs_name) # create the new pcb with the current id new_pcb = self.create_pcb_of(program) # add the new process to the new process list self.long_term_scheduler.add_new_process(new_pcb) # NewPcb Interruption self.interruption_manager.dispatch(NewPcb()) def create_pcb_of(self, a_program): # load the program in memory program_counter = self.mmu.load(a_program, self.pids) # create the new Pcb with the current id new_pcb = Pcb(self.pids, program_counter, a_program.length()) self.raise_pid() return new_pcb def raise_pid(self): self.pids += 1 def start(self): self.clock.start() self.io.start() def stop(self): self.clock.stop() self.io.clock.stop()
def post(self, user, text): self.storage.add(Message(user, text, Clock.now()))
def __format_message(self, m): return m.text + " (" + self.formatter.Format(Clock.now() - m.createdOn) + " ago)"
def typo_test(): clock = Clock() test_agent = Agent(clock.get_time_passed(),["http://www.youtube.com","http://www.cnn.com","http://www.yahoo.com"],10,25,"Test Agent",65) mistake = test_agent.make_typo_mistake() print(mistake)