def __init__(self): rospy.init_node('STATE') self.is_sitl = rospy.get_param('~is_sitl', False) self.is_airsim = rospy.get_param('~is_airsim', False) self.observer = Observer(self.is_sitl, self.is_airsim) self.rate = 1.0 self.pub_diag = rospy.Publisher('/system_diagnostics', Diagnostics, queue_size=1) self.srv_cmd_state = rospy.Service('set_mode', SetMode, self.set_mode_callback) rospy.wait_for_service('/MOVE/clear_costmaps') self.clear_costmaps_srv = rospy.ServiceProxy('/MOVE/clear_costmaps', Empty) rospy.loginfo('Starting state observer...') self.diag = Diagnostics()
def runBenchmark(outdir, experiment): Aim.sepservers0 = ['euler10', 'euler11'] Aim.sepservers1 = [] srvObserver = Observer('AIM server started') storageClients = [] ## start storages storageClients = startStorage() print "Storage started" # Populate outfile = "{}/{}_population.db".format(outdir, sqliteOut(False)) aimObserver = Observer("AIM") aimClients = startAimServers([aimObserver]) #aimObserver.waitFor(len(Aim.sepservers0) + len(Aim.sepservers1) + len(Aim.rtaservers0) + len(Aim.rtaservers1)) time.sleep(2) populationClient = startSepClient(True, outfile) populationClient.join() experiment() for aimClient in aimClients: aimClient.kill() aimClient.join() for client in storageClients: client.kill() for client in storageClients: client.join()
def mainProgram(self): """ In this function things are hardcoded a bit.Also dogtail modules are imported inside. """ #####types##### # observer : object of class Observer # children_of_gnometerm : list of objects of class Accessibility.Accessible *i think # index_of_frame : integer # frameName : string from observer import Observer from dogtail.procedural import FocusApplication, click, keyCombo, type import dogtail.rawinput observer = Observer() observer.openWindowFromMenu(['Applications', 'Accessories', 'Terminal']) if(not observer.isFocussed('gnome-terminal')): raise Error("Could not focus gnome-termnal") children_of_gnometerm = FocusApplication.node.children index_of_frame = len(children_of_gnometerm)-1 #index of last created frame frameName = children_of_gnometerm[index_of_frame].name if(not observer.frameFocussed(frameName)): raise Error("Could not focus frame " + frameName) type("sudo apt-get install ")
class Screen: def __init__(self, settings_tuple): """ Initialize simulation area. """ self.screen_len_new = DISPLAY self.screen = pg.display.set_mode(DISPLAY, pg.RESIZABLE) pg.display.set_caption("Fire in tunnel") self.bg = pg.Surface(DISPLAY) self.bg.fill(c.BLUE) self.observer = Observer(0, 2) self.tunnel = Tunnel(settings_tuple) self.camera = Camera(camera_configure, settings_tuple[1] + 60, WIN_HEIGHT) self.settings_tuple = settings_tuple def draw_on_screen(self, r, left, right): self.screen.blit(self.bg, (0, 0)) self.camera.update(self.observer, self.screen_len_new) self.tunnel.blit_tunnel(r, self.screen, self.camera) #self.tunnel.blit_smoke(self.screen, self.camera) self.observer.update(left, right, self.screen_len_new, self.settings_tuple[1], self.settings_tuple[6])
def __init__(self, view: Window, model: MainModel): Observer.__init__(self) self.model = model self.view = view self.view.attach(self) self.model.attach(self)
def __init__(self): # Create Home as an Observer object Observer.__init__(self) # Create Home as an Observable object Observable.__init__(self) # Monsters/NPCs within the house self.monsters = [] # Populates the homes with random monsters for i in range(randint(0, 10)): randNum = randint(1, 5) if (randNum == 1): currMonster = Persons() elif (randNum == 2): currMonster = Zombies() elif (randNum == 3): currMonster = Ghouls() elif (randNum == 4): currMonster = Vampires() elif (randNum == 5): currMonster = Werewolves() # Has house observe each monster currMonster.add_observer(self) self.monsters.append(currMonster)
def __init__(self): """ constructor for neighborhood inititates observer and calls house grid generation method """ Observer.__init__(self) self.makeHouseGrid()
def run_simulation(P=0, Q=0, lying_function=lie_on_every_packet, length_of_path=5, total_ticks=50): client_to_server_path = Path(length_of_path, "Client", "Server") server_to_client_path = Path(length_of_path, "Server", "Client") client = Client(0, P, lying_function) server = Server(0, Q, lying_function) observer = Observer() current_tick = 1 while (current_tick <= total_ticks): # add_packet_to_path() pops off the bit that has # reached the end of the path bit_reaching_server = client_to_server_path.add(client.cur_spin) bit_reaching_client = server_to_client_path.add(server.cur_spin) # update value of spin bit for client and server # this will be set next tick client.cur_spin = bit_reaching_client server.cur_spin = bit_reaching_server print("Tick:"), print(current_tick) client_to_server_path.pretty_print() server_to_client_path.pretty_print(True) # measurements are sampled from midpoint of path observer.add_measurement(client_to_server_path) current_tick += 1 print("Final RTT is %.2f") % observer.measure_rtt()
class Environment(): """Representation of the environment in which the system and the observer will perform """ def __init__(self, system, store, limit_time=40000, verbose=False): self.__time = 0 self.__limit_time = limit_time self.__system = system self.__store = store self.__observer = Observer() @classmethod def create(cls, system, store, limit_time=40000): return cls(system, store, limit_time=limit_time) def start(self): while self.__limit_time > self.__time and self.__system.get_state( ) != SystemState.COMPLETED: full_agents = self.__system.step() if len(full_agents) > 0: self.__observer.collect_metrics( self.__time, full_agents, self.__store.distribution, self.__system.get_agents_count(), self.__system.get_full_agents_count()) self.__time += 1 if self.__limit_time == self.__time: print("LIMIT REACHED in case {} {}".format( self.__system.get_agents_count(), 2)) print("Simulation ended")
def __init__(self, model): tk.Tk.__init__(self) Subject.__init__(self) # VIEW OBSERVES THE MODEL FOR STATE CHANGES Observer.__init__(self) self.model = model self.model.attach(self) for x in self.model.layout_algos: print(x, self.model.layout_algos[x]) for x in self.model.algos: print(x, self.model.algos[x]) self.info_menu = None self.geometry("1920x1080") # Init. canvas self.tabs = {} self.nb = ttk.Notebook(self, name="nb") self.index = 0 self.nb.grid(column=0, row=0, sticky=tk.N) self.bind("<Control-t>", self.open_new_graph) self.bind("<Control-w>", self.delete_tab) self.bind("<Control-s>", self.do_algo) self.bind("<Control-r>", self.zoom_out) self.bind("<Control-f>", self.zoom_in)
def __init__(self, system, store, limit_time=40000, verbose=False): self.__time = 0 self.__limit_time = limit_time self.__system = system self.__store = store self.__observer = Observer()
def update(self): Observer.update_ball_is_moving(self._ball_info) Observer.update_role_is_exist(self._roledecision._rolestocker._role_is_exist) self._roledecision.set_disappeared([i.disappeared for i in self._robot_info['our']]) if tool.is_in_defense_area(self._ball_info.pose, 'our') is False \ and Observer.ball_is_moving() is False: # ボールが自チームディフェンスエリア外にあり # ボールが動いていないとき、アタッカーの交代を考える self._roledecision.check_ball_dist([i.pose for i in self._robot_info['our']], self._ball_info) self._roledecision.event_observer() defense_num = self._roledecision._rolestocker._defense_num self._obstacle_avoidance.update_obstacles(self._ball_info, self._robot_info) for our_info in self._robot_info['our']: robot_id = our_info.robot_id target = ControlTarget() # ロールの更新 self._robot_node[robot_id]._my_role = self._roledecision._rolestocker._my_role[robot_id] if our_info.disappeared: # ロボットが消えていたら停止 target = self._robot_node[robot_id].get_sleep() else: # ロボットの状態を更新 self._robot_node[robot_id].set_state( our_info.pose, our_info.velocity) # 目標位置を生成 target = self._robot_node[robot_id].get_action( self._decoded_referee, self._obstacle_avoidance, self._ball_info, self._robot_info, defense_num) self._pubs_control_target[robot_id].publish(target)
def __init__(self, conf_args): super(BasicGenerator, self).__init__(conf_args) self._prg = None self._observer = Observer() self._solve_opts = [ "-t {0}".format(self._args.threads), "--project", # "--opt-mode=optN", "-n {0}".format(self._args.num) ] if self._args.random: self._solve_opts.extend([ '--rand-freq={}'.format(self._args.rand_freq), '--sign-def={}'.format(self._args.sign_def), '--seed={}'.format(self._args.seed) ]) if self._args.solve_opts: self._solve_opts.extend(self._args.solve_opts) self._inits = None self._object_counters = {} self._instance_count = 0 self._instances = [] self.dest_dirs = [] if self._args.cluster_x is None: self._cluster_x = int((self._args.grid_x - 2 + 0.5) / 2) else: self._cluster_x = self._args.cluster_x if self._args.cluster_y is None: self._cluster_y = int((self._args.grid_y - 4 + 0.5) / 2) else: self._cluster_y = self._args.cluster_y
def __call__(self, obs: Observer): msg = None # loop until the ode object halts while self._ode.status == "running": # if the stepper has no remaining work, leave loop if self._stepper.emit_done(): msg = "complete (stepper reports no longer changing)" break # reset timer and take timestep _xtime0 = default_timer() msg = self._ode.step() self._tot_steptime += (default_timer() - _xtime0) self._avg_steptime = (self._tot_steptime / float(self._steps + 1)) if np.any(np.isnan(self._ode.y)): obs(self._steps, force_screen=True) raise ValueError("NAN detected, leaving") obs(self._steps) self._steps = self._steps + 1 print( f"ODE loop exist\n\tstep msg=\'{msg}\'\n\tstatus=\'{self._ode.status}\'\n" ) obs.dump(self._steps)
def _penalty_shoot(my_pose, ball_info, control_target, kick_enable, target_pose, kick_power=1.0): # PK用のシュートアクション # kick_enable is Falseで、ボールの近くまで移動する # kick_enable is True で、シュートする KICK_POWER = kick_power SHOOT_TARGET = target_pose DRIBBLE_POWER = 0.5 angle_ball_to_target = tool.get_angle(ball_info.pose, SHOOT_TARGET) trans = tool.Trans(ball_info.pose, angle_ball_to_target) tr_my_pose = trans.transform(my_pose) random_num = Observer.random_zero_one() if random_num == 0: target_goal_side = Field.goal_pose('their', 'upper') else: target_goal_side = Field.goal_pose('their', 'lower') angle_to_target_side = tool.get_angle(my_pose, target_goal_side) # ロボットがボールの裏側に回ったらcan_kick is True can_kick = False if tr_my_pose.x > -0.2 and math.fabs(tr_my_pose.y) < 0.05: can_kick = True avoid_ball = True # ボールを回避する new_goal_pose = Pose2D() if can_kick and kick_enable: # ボールをける avoid_ball = False # ボールの前方に移動する new_position = trans.inverted_transform(Pose2D(0, 0, 0)) new_goal_pose = new_position new_goal_pose.theta = angle_to_target_side # ドリブルとキックをオン control_target.dribble_power = DRIBBLE_POWER control_target.kick_power = KICK_POWER else: Observer.update_random_zero_one() # ボールの裏に移動する new_position = trans.inverted_transform(Pose2D(-0.1, 0, 0)) new_goal_pose = new_position new_goal_pose.theta = angle_ball_to_target # ドリブルとキックをオフ control_target.kick_power = 0.0 control_target.dribble_power = 0.0 # パスを追加 control_target.path = [] control_target.path.append(new_goal_pose) return control_target, avoid_ball
def __init__(self, model, view): """Inits the class with the view and model.""" Observer.__init__(self, view) self.model = model self.view = view self.update()
def __init__(self, parent, bg="white", width=600, height=300): Observer.__init__(self) self.canvas = tk.Canvas(parent, bg=bg, width=width, height=height) self.a, self.f, self.p = 10.0, 2.0, 0.0 self.signal = [] self.width, self.height = width, height self.units = 1 self.canvas.bind("<Configure>", self.resize)
def __init__(self, parent, width=600, height=600, from_=1, to=10): Observer.__init__(self) self.frame = tk.LabelFrame(parent, text="Generator ", borderwidth=5, padx=20, pady=20) # self.menu = Menubar(parent) self.notes = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ] self.octave = tk.IntVar() self.octave.set(4) # Note selection self.noteList = tk.Listbox(self.frame, height=15, bd=4, selectborderwidth=1) for note in self.notes: self.noteList.insert("end", note) # Octave selection self.octaveScale = tk.Scale(self.frame, variable=self.octave, label="Octave", orient="vertical", length=350, from_=from_, to=to, tickinterval=1) # Generate Button self.generateButton = tk.Button(self.frame, text="Generate") # Play Button self.playButton = tk.Button(self.frame, text="Play note", bg="light sky blue") self.playChordButton = tk.Button(self.frame, text="Play chord", bg="light sky blue") # Chords prepate self.addToChord = tk.Button(self.frame, text="Add to chord => ") self.chordPrepareListbox = tk.Listbox(self.frame, height=5, bd=4, selectborderwidth=1) # Generate chord self.generateChord = tk.Button(self.frame, text="Generate chord") # Chords selection self.chordsSelection = tk.Listbox(self.frame, height=15, bd=4, selectborderwidth=1)
def mainProgram(self): """ In this function things are hardcoded a bit.Also dogtail modules are imported inside. """ from observer import Observer observer = Observer() observer.openWindowFromMenu(['System', 'Administration', 'Software Sources']) time.sleep(4)
def __init__(self, **kwargs): self.blinker = False self.ob = Observer() self.group_list = self.ob.get_observing_group_list() self.created_group_id_list = [] self.lamp_list = [""] * self.show_num self.set_lamp_list() super(MainPanel, self).__init__(**kwargs) Clock.schedule_interval(self.observing, 15) Clock.schedule_interval(self.set_blinker, 0.5)
def __init__(self,parent,subject,bg="white"): print("View : __init__") Observer.__init__(self) self.subject=subject self.parent=parent self.signal_id=None self.canvas=Canvas(parent,bg=bg) self.canvas.bind("<Configure>", self.resize) self.width=int(self.canvas.cget("width")) self.height=int(self.canvas.cget("height"))
class Agent: def __init__(self, player, names): self.player = player self.name = names[player] self.observer = Observer(names) self.cards = [] def __str__(self): return self.name def start_game(self): self.observer.start_game() def start_round(self, card): self.observer.start_round(self.player, card) self.cards = [card] def report_draw(self, card): self.observer.report_draw(self.player, card) self.cards.append(card) def end_round(self, cards, winner): self.observer.end_round(cards, winner) def end_game(self, winner): pass def report_play(self, *k, **kw): self.observer.report_play(*k, **kw) player = kw['player'] card = kw['card'] target = kw.get('target', None) discard = kw.get('discard', None) new_card = kw.get('new_card', None) other_card = kw.get('other_card', None) loser = kw.get('loser', None) if self.player == player: self.cards.remove(card) if target is not None and not self.observer.players[target].handmaiden: if card == Cards.BARON and self.player == loser: self.cards.remove(discard) elif card == Cards.PRINCE and self.player == target: self.cards.remove(discard) self.cards.append(new_card) elif card == Cards.KING and self.player in (player, target): del self.cards[0] self.cards.append(other_card) def _get_required_play(self): if Cards.COUNTESS in self.cards: if Cards.PRINCE in self.cards or Cards.KING in self.cards: return {'card': Cards.COUNTESS} return None
class Main: def __init__(self): logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(threadName)s\t%(levelname)-8s\t%(message)s') signal.signal(signal.SIGINT, self.exit) signal.signal(signal.SIGTERM, self.exit) self.is_restarted = False self.config = self.load_config() host = self.config['host'] stream_token = self.config['stream_token'] stream_config = self.config['stream_config'] self.previous_status = "" logging.info('### PICAM-STREAM ###') logging.info('streaming to \'{}\''.format(host)) self.s = Streamer(host, stream_token, stream_config) self.o = Observer(host, self.observer_event_handler) def load_config(self, config_path='./config.json'): with open(config_path, 'r') as f: config = json.load(f) return config def observer_event_handler(self, status): if self.previous_status != status: # status has changed logging.debug('observer reported status \'{}\''.format(status)) self.previous_status = status if status in ['disconnected', 'stopped', 'error']: if not self.is_restarted: logging.warning('(re)starting stream ...'.format(status)) self.s.restart_stream() self.is_restarted = True else: self.is_restarted = False def start(self): self.o.start() def exit(self, signum, frame): logging.debug('SIGTERM was sent, exiting') self.o.stop() self.s.stop_stream() logging.info('bye!')
def conduct_game(self): logger.info("The players in the game are " + str(self.player_names)) self.start_game() logger.info("Initial moves have finished.") self.perform_game() logger.info("The game has now finished.") obs = Observer() obs.observe_game_state(self.game_state) referee_game_management.end_game(self)
def enable_bot_and_player(_game): player = Player(settings.PLAYER_SKINS[0], 175, 100, 290, "Player") bot = Bot(settings.BOT_SKINS[0], 75, 200, 300, 290, "Bot") obs_player = Observer(player, [wall]) obs_bot = Observer(bot, [wall]) player.obs = obs_player bot.set_target(wall) bot.obs = obs_bot _game.player = player _game.add_object(bot)
def check_new_event(self, planet_list): """Watch periodically for any new incoming fleet""" fleet_observer = Observer(planet_list, self.navigate) while True: try: self.mutex.acquire() self.is_event_over = fleet_observer.check_new_event() except Exception: print("ERROR check_new_event") finally: self.mutex.release() time.sleep(self.DELAY)
def main(): observer = Observer() fuzzifier = Fuzzifier(observer) inferrer = Inferrer(fuzzifier) defuzzifier = Defuzzifier(inferrer) observer.observe() fuzzifier.fuzzify() inferrer.infer() defuzzifier.defuzzify() print("Time should be {0} minutes".format(defuzzifier.crisp_time()))
class OberverTestCase(TestCase): def setUp(self): self.my_observer = Observer() def test_register(self): test_graph = GraphDataPatientNumber() self.my_observer.register(test_graph) actual = self.my_observer.subscribers.pop() self.assertEqual(test_graph, actual) def test_unregister(self): test_graph = GraphDataPatientNumber() self.assertTrue(self.my_observer.register(test_graph))
def __init__(self): self.ob = Observer() self.timer = RepeatedTimer(7200, self.ob.ob_all) self.cmd_list = { "help": self._help, "status": self._status, "list": self._list, "delete": self._delete, "admin-status": self._admin_status, "admin-list": self._admin_list, "admin-run": self._admin_run } self.ob.init_checker()
def __init__(self, system, agent, limit_time=40000, verbose=False): """Environment constructor Args: system (System): Systems that will be perform in the environment agent (Agent): Agent which will solve the problem limit_time (int, optional): Simulation limit time. Defaults to 40000. verbose (bool, optional): Verbose mode. Defaults to False. """ self.__time = 0 self.__limit_time = limit_time self.__system = system self.__agent = agent self.__observer = Observer()
def __init__(self): Observer.__init__(self) self.__observers = [] # keys are properties names, values are pairs (bool, methods) # inside the observer. bool is True for custom observing # methods, False otherwise self.__value_notifications = {} self.__instance_notif_before = {} self.__instance_notif_after = {} self.__signal_notif = {} for key in self.get_properties(): self.register_property(key) return
def __init__(self, goghdoc, drawable): self.x_visible, self.y_visible, self.w_visible, self.h_visible = 0, 0, 0, 0 self.viewpixbuf = None self.goghdoc = goghdoc self.drawable = drawable self.zoom_factor = 1.0 self.size_observer = Observer() self.image_observer = Observer() self.goghdoc.size_observer.add_callback(self.on_resize) self.goghdoc.pixbuf_observer.add_callback(self.refresh_area) self.gc = self.drawable.new_gc() self.top_level_gc = self.drawable.new_gc(function=gtk.gdk.INVERT) self.show_cursor = False self.xcur, self.ycur, self.brush_min_width, self.brush_max_width = 0, 0, 0, 0 self.xcur_old, self.ycur_old = None, None
def __init__(self, logger, spectrumId, dic, udic, pdata, dataSource, reference): Observer.__init__(self, logger) self.logger = logger self.id = spectrumId self.dic = dic self.udic = udic self.pdata = pdata self.mpdata = np.array(map(lambda x: -x, pdata)) self.dataSource = dataSource reference.addObserver(lambda n: referenceObserver(self, n)) self.sources = dict() self.sources['peaks'] = ColumnDataSource(data=dict(x=[], y=[]))
def __init__(self, logger, spectrumId, pdata, dataSource, reference): Observer.__init__(self, logger) self.logger = logger self.id = spectrumId self.pdata = pdata self.dataSource = dataSource reference.addObserver(lambda n: referenceObserver(self, n)) self.sources = dict() self.sources['integration'] = ColumnDataSource( data=dict(x=[], y=[], width=[], height=[])) self.initIntegral = None
def __init__(self, agents): """ This class is used to setup, run and log the results of an experiment. """ Observer.__init__(self) for ag in agents: for topic in ["motor", "presence", "td_error", "activation", "weights", "reward", "aud_act", "amp"]: ag.subscribe(topic, self) self.ags = agents self.n_ag = len(agents) self.log = [defaultdict(list) for _ in range(self.n_ag)] self.eval_at = [] self._running = threading.Event()
def mainProgram(self): """ In this function things are hardcoded a bit.Also dogtail modules are imported inside. """ ####types#### # observer : object of class Observer # children_of_firefox : list of objects of class Accessibility.Accessible # prefWindowNum,newWindowNum : integer # frameName = string from observer import Observer from dogtail.procedural import FocusApplication, click import dogtail.rawinput observer = Observer() observer.openWindowFromMenu(['Applications', 'Ubuntu Software Center']) if(not observer.isFocussed('software-center')): #if i can somehow avoid such statements i can make this code more general i think raise Error("Could not focus Ubuntu Software Center")
def mainProgram(self): """ In this function things are hardcoded a bit.Also dogtail modules are imported inside. """ from observer import Observer import dogtail.rawinput observer = Observer() observer.openWindowFromMenu(['System', 'Administration', 'Synaptic Package Manager']) #frameName = 'Synaptic Package Manager' #if(not observer.frameFocussed(frameName,1)): # raise Error("Could not focus frame " + frameName) """I am debating which to include.The above three lines or the next few lines. The above two lines will definitely raise an error and end while with the below few lines i can even type some name in many cases""" time.sleep(4) dogtail.rawinput.typeText('vim')
def __init__(self): Observer.__init__(self) self.__observers = [] # keys are properties names, values are pairs (method, # kwargs|None) inside the observer. kwargs is the keyword # argument possibly specified when explicitly defining the # notification method in observers, and it is used to build # the NTInfo instance passed down when the notification method # is invoked. If kwargs is None (special case), the # notification method is "old style" (property_<name>_...) and # won't be receiving the property name. self.__value_notifications = {} self.__instance_notif_before = {} self.__instance_notif_after = {} self.__signal_notif = {} for key in self.get_properties(): self.register_property(key) return
def __init__(self): self.brush_types = {'pen': BrushType.Pen, 'eraser': BrushType.Eraser, 'smudge': BrushType.Smudge }#, 'bucket': BrushType.Bucket} self.brush_type_names = inverse_dictionary(self.brush_types) self.init_brush_list() self.current_pen_data = self.default_pen_data self.current_eraser_data = self.default_eraser_data self.active_brush_data = self.current_pen_data self.init_brush_menu() self.select_menu_item_for_active_brush_data() self.eraser_mode = False self.brush_selection_observer = Observer()
def mainProgram(self): """ In this function things are hardcoded a bit.Also dogtail modules are imported inside. """ ####types#### # observer : object of class Observer # children_of_firefox : list of objects of class Accessibility.Accessible # prefWindowNum,newWindowNum : integer # frameName = string from observer import Observer from dogtail.procedural import FocusApplication, click import dogtail.rawinput observer = Observer() observer.openWindowFromMenu(['Applications', 'Internet', 'Firefox Web Browser']) if(not observer.isFocussed('Firefox')): #if i can somehow avoid such statements i can make this code more general i think raise Error("Could not focus Firefox") children_of_firefox = FocusApplication.node.children newWindowNum = len(children_of_firefox) - 1 frameName = children_of_firefox[newWindowNum].name if(not observer.frameFocussed(frameName)): raise Error("Could not focus frame " + frameName) click('Edit', roleName='menu') click('Preferences', roleName='menu item') time.sleep(2) children_of_firefox = FocusApplication.node.children prefWindowNum = len(children_of_firefox) - 1 if(prefWindowNum <= newWindowNum ): raise Error("Preference window did not open.Please make sure nothing interferes with the focussing of the created window.") prefWindow = children_of_firefox[prefWindowNum].name if(not(prefWindow == "Firefox Preferences")): #double-check.Can also be removed to make the code more general raise Error("Preference Window did not open") if(not observer.frameFocussed(prefWindow)): raise Error("Could not focus frame " + prefWindow) click('Advanced') time.sleep(1) click('Network') time.sleep(1) scroll_pane = children_of_firefox[prefWindowNum].children panel = scroll_pane[7].children #scroll_pane[7] is Advanced options scroll_pane2 = panel[0].children panel2 = scroll_pane2[2].children next_child = panel2[0].children #panel2 is Connection option in Network option in Advanced options settings = next_child[2] x,y = settings.position dogtail.rawinput.click(x, y, 1) children_of_firefox = FocusApplication.node.children cntnsWindowNum = len(children_of_firefox) - 1 cnctn_sttngs_win = children_of_firefox[cntnsWindowNum].name if(not observer.frameFocussed(cnctn_sttngs_win)): raise Error("Could not focus frame " + cnctn_sttngs_win)
class CommandStack: def __init__(self, goghdoc): self.packed_command_list = [] self.current_index = -1; self.goghdoc = goghdoc self.observer = Observer() self.changes_since_save = 0 def add(self, command): if(command.is_trivial()): return del self.packed_command_list[self.current_index+1:] self.packed_command_list.append(self.pack_command(command)) self.current_index+=1 self.changes_since_save+=1 command.execute() if len(self.packed_command_list)>max_stack_len: self.current_index -= len(self.packed_command_list)-max_stack_len del self.packed_command_list[:-max_stack_len] self.observer.notify_all() def undo(self): if self.current_index<0: return command = self.unpack_command(self.packed_command_list[self.current_index]) command.undo() self.current_index-=1 self.changes_since_save-=1 self.observer.notify_all() def redo(self): if self.current_index+1>=len(self.packed_command_list): return command = self.unpack_command(self.packed_command_list[self.current_index+1]) command.redo() self.current_index+=1 self.changes_since_save+=1 self.observer.notify_all() def pack_command(self, command): return zlib.compress(pickle.dumps(command, 2)) def unpack_command(self, packed_command): command = pickle.loads(zlib.decompress(packed_command)) command.goghdoc = self.goghdoc return command def clear(self): self.packed_command_list = [] self.current_index = -1;
from observer import Observer from graphvizmanager import renderGraphViz from config import config APP = ArgumentParser() APP.add_argument("--list", default=False, action="store_true") APP.add_argument("--debug", default=False, action="store_true") ARGS = APP.parse_args() if config["DEBUG"] or ARGS.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig() WINLOGGER = Observer() if ARGS.list: print WINLOGGER.top() WINLOGGER.stop() sys.exit() SINCE = time() CMD = "" try: while CMD not in [":q", ":quit", "exit", "q", "quit"]: if CMD == "": pass elif CMD == "du": print subprocess.check_output(["du", "-h", config["DATABASE"]]) elif CMD == "feh":
def __init__(self, player, names): self.player = player self.name = names[player] self.observer = Observer(names) self.cards = []
def __init__(self, model, spurious=False): Observer.__init__(self, model, spurious) self.view = None self.__adapters = [] return
class GoghView: def __init__(self, goghdoc, drawable): self.x_visible, self.y_visible, self.w_visible, self.h_visible = 0, 0, 0, 0 self.viewpixbuf = None self.goghdoc = goghdoc self.drawable = drawable self.zoom_factor = 1.0 self.size_observer = Observer() self.image_observer = Observer() self.goghdoc.size_observer.add_callback(self.on_resize) self.goghdoc.pixbuf_observer.add_callback(self.refresh_area) self.gc = self.drawable.new_gc() self.top_level_gc = self.drawable.new_gc(function=gtk.gdk.INVERT) self.show_cursor = False self.xcur, self.ycur, self.brush_min_width, self.brush_max_width = 0, 0, 0, 0 self.xcur_old, self.ycur_old = None, None def get_size(self): return int(ceil(self.goghdoc.width*self.zoom_factor)), int(ceil(self.goghdoc.height*self.zoom_factor)) def zoom_in(self): self.set_zoom(self.zoom_factor*1.5) def zoom_out(self): self.set_zoom(self.zoom_factor/1.5) def zoom_normal(self): self.set_zoom(1.0) def set_zoom(self, zoom_factor): self.zoom_factor = zoom_factor if abs(self.zoom_factor-round(self.zoom_factor))<0.01: self.zoom_factor = round(self.zoom_factor) self.size_observer.notify_all() def scale_with_clipping(self, x, y, w, h): if x<0 : w,x = w-x, 0 if x+w>self.viewpixbuf.get_width() : w = self.viewpixbuf.get_width()-x if y<0 : h, y = h-y, 0 if y+h>self.viewpixbuf.get_height() : h = self.viewpixbuf.get_height()-y if w<=0 or h<=0 : return self.goghdoc.composite.scale(self.viewpixbuf, x, y, w, h, -self.x_visible, -self.y_visible, self.zoom_factor, self.zoom_factor, gtk.gdk.INTERP_TILES) def update_view_pixbuf(self, x, y, w, h): xv, yv, wv, hv = self.to_view_rect(x, y, w, h) self.scale_with_clipping(xv-self.x_visible, yv-self.y_visible, wv, hv) def reset_view_pixbuf(self): if self.viewpixbuf : if (self.viewpixbuf.get_width(), self.viewpixbuf.get_height()) != (self.w_visible +1, self.h_visible+1): del self.viewpixbuf self.viewpixbuf = create_pixbuf(self.w_visible +1, self.h_visible+1) else : self.viewpixbuf = create_pixbuf(self.w_visible +1, self.h_visible+1) self.scale_with_clipping(0, 0, self.w_visible +1, self.h_visible+1) def refresh_area(self, area_rect=None): if not area_rect: self.image_observer.notify_all(gtk.gdk.Rectangle(0, 0, self.w_visible, self.h_visible), False) return xv, yv, wv, hv = self.to_view_rect(area_rect.x, area_rect.y, area_rect.width, area_rect.height) self.scale_with_clipping(xv-self.x_visible, yv-self.y_visible, wv, hv) self.image_observer.notify_all(gtk.gdk.Rectangle(xv, yv, wv, hv), False) def on_resize(self): self.reset_view_pixbuf() self.size_observer.notify_all() def to_model(self, x, y): return x/self.zoom_factor, y/self.zoom_factor def to_view(self, x, y): return x*self.zoom_factor, y*self.zoom_factor def redraw_image_fragment_for_model_coord(self, x, y, w, h): xv, yv, wv, hv = self.to_view_rect(x, y, w, h) if self.zoom_factor==1: self.draw_pixbuf_with_clipping(self.goghdoc.composite, xv, yv, xv, yv, wv, hv) else: xv, yv, wv, hv = xv-1, yv-1, wv+2, hv+2 self.draw_pixbuf_with_clipping(self.viewpixbuf, xv-self.x_visible, yv-self.y_visible, xv, yv, wv, hv) self.draw_top_level_items(xv, yv, wv, hv) def draw_pixbuf_with_clipping(self, pixbuf, src_x, src_y, dest_x, dest_y, w, h): w_ofs, h_ofs = min(src_x, 0), min(src_y, 0) w_cutoff, h_cutoff = max(src_x+w-pixbuf.get_width(), 0), max(src_y+h-pixbuf.get_height(), 0) if w<=w_ofs+w_cutoff or h<=h_ofs+h_cutoff: return self.drawable.draw_pixbuf(self.gc, pixbuf, src_x-w_ofs, src_y-h_ofs, dest_x-w_ofs, dest_y-h_ofs, w-w_ofs-w_cutoff, h-h_ofs-h_cutoff) def redraw_image_for_cursor(self): max_size = max(self.brush_min_width, self.brush_max_width)+1 d = max_size//2 model_rect = None if self.xcur_old is not None and self.ycur_old is not None: model_rect = rect_union(model_rect, rect_from_float_list([self.xcur_old-d, self.ycur_old-d-1, max_size+2, max_size+2])) if self.show_cursor: model_rect = rect_union(model_rect, rect_from_float_list([self.xcur-d-1, self.ycur-d-1, max_size+2, max_size+2])) if model_rect: model_rect = model_rect.intersect(gtk.gdk.Rectangle(0, 0, self.goghdoc.width, self.goghdoc.height)) self.redraw_image_fragment_for_model_coord(model_rect.x, model_rect.y, model_rect.width, model_rect.height) self.xcur_old, self.ycur_old = self.xcur, self.ycur def draw_top_level_items(self, xv, yv, wv, hv): self.top_level_gc.set_clip_rectangle(gtk.gdk.Rectangle(xv, yv, wv, hv)) if self.show_cursor: xc, yc = [int(round(t)) for t in self.to_view(self.xcur, self.ycur)] w1, w2 = [int(ceil(w*self.zoom_factor)) | 1 for w in (self.brush_min_width, self.brush_max_width)] self.drawable.draw_arc(self.top_level_gc, False, xc-w1//2, yc-w1//2, w1, w1, 0, 360*64) if w1 != w2: self.drawable.draw_arc(self.top_level_gc, False, xc-w2//2, yc-w2//2, w2, w2, 0, 360*64) def to_view_rect(self, x, y, w, h): xv1, yv1 = [int(floor(t)) for t in self.to_view(x, y)] xv2, yv2 = [int(ceil(t)) for t in self.to_view(x+w, y+h)] return xv1, yv1, xv2-xv1, yv2-yv1 def reposition(self, x, y, w, h): if (self.x_visible, self.y_visible, self.w_visible, self.h_visible) == (x, y, w, h): return self.x_visible, self.y_visible, self.w_visible, self.h_visible = [int(k) for k in (x, y, w, h)] def redraw_image(self): self.reset_view_pixbuf() self.drawable.draw_pixbuf(self.drawable.new_gc(), self.viewpixbuf, 0, 0, self.x_visible, self.y_visible, -1, -1) self.draw_top_level_items(self.x_visible, self.y_visible, self.w_visible, self.h_visible) def set_cursor(self, x, y, brush_data): self.xcur, self.ycur, self.brush_min_width, self.brush_max_width = x, y, brush_data.min_width, brush_data.max_width self.show_cursor = True def set_no_cursor(self): self.show_cursor = False
def __init__(self, goghdoc): self.packed_command_list = [] self.current_index = -1; self.goghdoc = goghdoc self.observer = Observer() self.changes_since_save = 0
def main(): observer = Observer(settings) observer.watch()
class BrushManager: def __init__(self): self.brush_types = {'pen': BrushType.Pen, 'eraser': BrushType.Eraser, 'smudge': BrushType.Smudge }#, 'bucket': BrushType.Bucket} self.brush_type_names = inverse_dictionary(self.brush_types) self.init_brush_list() self.current_pen_data = self.default_pen_data self.current_eraser_data = self.default_eraser_data self.active_brush_data = self.current_pen_data self.init_brush_menu() self.select_menu_item_for_active_brush_data() self.eraser_mode = False self.brush_selection_observer = Observer() def construct_brush_from_node(self, brush_node): brush = BrushData(brush_node.getAttribute("name")) for child_node in brush_node.childNodes: if child_node.localName=='width': brush.min_width = int(child_node.getAttribute("min")) brush.max_width = int(child_node.getAttribute("max")) if child_node.localName=='opacity': brush.min_opacity = float(child_node.getAttribute("min")) brush.max_opacity = float(child_node.getAttribute("max")) if child_node.localName=='step': brush.step = int(child_node.getAttribute("value")) if child_node.localName=='smudge-amount': brush.smudge_amount = float(child_node.getAttribute("value")) if child_node.localName=='type': brush.brush_type = self.brush_types[child_node.childNodes[0].nodeValue.strip()] if child_node.localName=='default-eraser': self.default_eraser_data = brush if child_node.localName=='default-pen': self.default_pen_data = brush brush.populate_originals() return brush def construct_node_from_brush(self, brush, xmldoc): brush_node = xmldoc.createElement('brush') brush_node.setAttribute('name', brush.name) brush_node.appendChild(xmldoc.createElement('width')) brush_node.lastChild.setAttribute('min', str(int(brush.min_width))) brush_node.lastChild.setAttribute('max', str(int(brush.max_width))) if (brush.min_opacity!=0 or brush.max_opacity!=1) and brush.brush_type != BrushType.Smudge: brush_node.appendChild(xmldoc.createElement('opacity')) brush_node.lastChild.setAttribute('min', str(brush.min_opacity)) brush_node.lastChild.setAttribute('max', str(brush.max_opacity)) if brush.step != 1: brush_node.appendChild(xmldoc.createElement('step')) brush_node.lastChild.setAttribute('value', str(int(brush.step))) if brush.brush_type == BrushType.Smudge: brush_node.appendChild(xmldoc.createElement('smudge-amount')) brush_node.lastChild.setAttribute('value', str(brush.smudge_amount)) brush_node.appendChild(xmldoc.createElement('type')) brush_node.lastChild.appendChild(xmldoc.createTextNode(self.brush_type_names[brush.brush_type])) if self.default_pen_data == brush : brush_node.appendChild(xmldoc.createElement('default-pen')) if self.default_eraser_data == brush : brush_node.appendChild(xmldoc.createElement('default-eraser')) return brush_node def init_brush_list(self): original_doc, custom_doc = load_original_brush_list_xmldoc(), load_custom_brush_list_xmldoc() self.brush_groups = [] self.load_brushes_from_document(original_doc, True) if custom_doc: self.load_brushes_from_document(custom_doc, False) def load_brushes_from_document(self, doc, is_original): for group_node in doc.getElementsByTagName("brushgroup"): group_name = group_node.getAttribute("name") group = find_item(self.brush_groups, lambda g : g.name == group_name) if not group: group = BrushGroup(group_node.getAttribute("name")) self.brush_groups.append(group) for brush_node in group_node.getElementsByTagName("brush"): brush = self.construct_brush_from_node(brush_node) brush.is_original = is_original group.brushes.append(brush) def save_brush_list(self): doc = xml.dom.minidom.Document() root_node = doc.createElement('brushes') doc.appendChild(root_node) for group in self.brush_groups: group_node = doc.createElement('brushgroup') group_node.setAttribute('name', group.name) for brush in group.brushes: if not brush.is_original: brush_node = self.construct_node_from_brush(brush, doc) group_node.appendChild(brush_node) root_node.appendChild(group_node) save_brush_list_xmldoc(doc) def init_brush_menu(self): self.brush_menu = gtk.Menu() self.brush_menu.connect("selection-done", self.selection_done) self.items_for_brushes = {} self.menu_item_group = None for brush_group in self.brush_groups: for brush_data in brush_group.brushes: item = gtk.RadioMenuItem(self.menu_item_group, brush_data.name) self.items_for_brushes[brush_data] = item if not self.menu_item_group: self.menu_item_group = item self.brush_menu.append(item) self.brush_menu.append(gtk.SeparatorMenuItem()) self.brush_menu.show_all() def selection_done(self, widget, data=None): for brush_data, item in self.items_for_brushes.iteritems(): if item.get_active(): self.active_brush_data = brush_data self.brush_selection_observer.notify_all() self.assign_current_brushes() self.select_menu_item_for_active_brush_data() return def select_eraser(self): self.eraser_mode = True if self.active_brush_data!=self.current_eraser_data : self.current_pen_data = self.active_brush_data self.active_brush_data = self.current_eraser_data self.brush_selection_observer.notify_all() self.select_menu_item_for_active_brush_data() def unselect_eraser(self): self.eraser_mode = False if self.active_brush_data!=self.current_pen_data : self.current_eraser_data = self.active_brush_data self.active_brush_data = self.current_pen_data self.brush_selection_observer.notify_all() self.select_menu_item_for_active_brush_data() def select_menu_item_for_active_brush_data(self): item = self.items_for_brushes[self.active_brush_data] self.brush_menu.select_item(item) item.set_active(True) def assign_current_brushes(self): if self.eraser_mode : self.current_eraser_data = self.active_brush_data else : self.current_pen_data = self.active_brush_data def on_brush_name_changed(self, brush_data) : self.items_for_brushes[brush_data].child.set_text(brush_data.name) def group_for_brush(self, brush_data): return find_item(self.brush_groups, lambda g : brush_data in g.brushes) def add_brush(self, brush_group, brush_data): brush_group.brushes.append(brush_data) new_item = gtk.RadioMenuItem(self.menu_item_group, brush_data.name) self.items_for_brushes[brush_data] = new_item self.brush_menu.append(new_item) self.brush_menu.show_all() def remove_brush(self, brush_data): brush_group = self.group_for_brush(brush_data) brush_group.brushes.remove(brush_data) self.brush_menu.remove(self.items_for_brushes[brush_data]) del self.items_for_brushes[brush_data] self.brush_menu.show_all() def select_brush(self, brush_data): if self.active_brush_data!=brush_data : self.active_brush_data = brush_data self.brush_selection_observer.notify_all() self.assign_current_brushes() self.select_menu_item_for_active_brush_data()
def signal_handler(signal, frame): print ("Closing all threads...") for t in threads: if t.isAlive(): t.stop() '''for t in threads: if t.isAlive(): t.join()''' print ("Finished.") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) queue_ = Queue(100) obs = Observer(queue_) temp_sensor = TemperatureSensor("temp", queue_, sleeptime, pin = 0) flame_sensor = FlameSensor("flame", queue_, sleeptime, pin = 27) #rotary_sensor = RotarySensor(thread_id="rotary", queue_, sleeptime) buzzer = ActorBuzzer(15) def tempAlarm(*args, **kwargs): print ("HIGH TEMPERATURE: %s" % str(kwargs["value"])) buzzer.buzz() obs.addSensor("temp", temperature_threshold, operator.ge, tempAlarm) def flameAlarm(*args, **kwargs): print ("ON FIRE!!!") buzzer.buzz()