def __init__(self, real_time=False): Manager.__init__(self) self.real_time = real_time self.balance = 1.0 if self.real_time: self.balance = self.GetBTCBalance() self.open_orders = []
class App(object): def __init__(self, filename): self.manager = Manager() self.canvas = Manager.canvas self.root = Manager.root self.filename = filename self.canvas.pack() self.do() self.move_one() self.animate = None def do(self): global stage stage = Environment() #filepath = str(os.getcwd())+ '/' + self.filename filepath = self.filename try: execfile(filepath, globals()) except IOError: print "There is no file named "+filepath+". Please try again!" except SyntaxError: print filepath+" is not a codesters Python file. Please try again!" def move_one(self): self.manager.run() self.animate = Manager.root.after(5, self.move_one)
def main(): """ Creates the GUI and runs a GUI event thread until it is shut down. """ Manager.setup() exit_code = Manager.execute() sys.exit(exit_code)
def __new__(cls, name, bases, attrs): new_class = SchemaBase.__new__(cls, name, bases, attrs) if 'objects' not in attrs: objects = Manager() objects.contribute_to_class(new_class, 'objects') parents = [b for b in bases if isinstance(b, DocumentBase)] module = new_class.__module__ if not new_class._meta.virtual: new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.virtual) or (ObjectDoesNotExist,), module)) new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.virtual) or (MultipleObjectsReturned,), module)) if parents and new_class._meta.proxy: new_class._meta.module_name = parents[0]._meta.module_name #ensure index on natural key hash if not new_class._meta.virtual and not new_class._meta.proxy: #TODO these fields should be definable at the document level from fields import CharField, DictField new_class.add_to_class('@natural_key_hash', CharField(editable=False, null=False)) new_class.add_to_class('@natural_key', DictField(editable=False, null=False)) register_documents(new_class._meta.app_label, new_class) new_class.objects.index('@natural_key_hash__exact').commit() return new_class
def test_passive(): def on_device_found(adapter, address, values): print "on device found" print "adapter", adapter print "address", address print "values", values def on_device_created(adapter, dev_path): print "on device created" print "adapter" ,adapter print "dev_path", dev_path from manager import Manager from adapter import Adapter manager = Manager() adapter = Adapter(manager.get_default_adapter()) adapter.set_powered(True) adapter.set_discoverable(True) adapter.set_pairable(True) # print "adapter properties:\n %s" % adapter.get_properties() adapter.connect("device-found", on_device_found) adapter.connect("device-created", on_device_created) mainloop = gobject.MainLoop() mainloop.run()
def __new__(cls, name, bases, attrs): new_class = SchemaBase.__new__(cls, name, bases, attrs) if 'objects' not in attrs: objects = Manager() objects.contribute_to_class(new_class, 'objects') if not new_class._meta.virtual and not new_class._meta.proxy: _register_document(new_class) parents = [b for b in bases if isinstance(b, DocumentBase)] module = new_class.__module__ if not new_class._meta.virtual: new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.virtual) or (ObjectDoesNotExist,), module)) new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.virtual) or (MultipleObjectsReturned,), module)) if parents and new_class._meta.proxy: new_class._meta.module_name = parents[0]._meta.module_name return new_class
def main(logfilepath): term = Terminal() mngr = Manager(term, num_divisions=1, logfilepath=logfilepath) cursor, scrn = mngr.get_focus_cursor_and_screen() with term.hidden_cursor(), \ term.raw(), \ term.location(), \ term.fullscreen(), \ term.keypad(): inp = None while True: inp = term.inkey(timeout=0.2) if inp != u'': signal = mngr.handle_input(inp) if signal == -1: # got exit signal break mngr.draw() if mngr.logger != None: mngr.logger.write_to_file()
def __init__(self): Manager.__init__( self, 'prediction') self.high = [] self.low = [] self.priority = 0 self.modTime = None self.revision = 0
def main(): pygame.init() pygame.mixer.music.load("rematch.mp3") pygame.mixer.music.play(-1) screen = pygame.display.set_mode((1024, 1024)) clock = pygame.time.Clock() game_manager = Manager() b = True while b: screen.blit(title,(0,0)) pygame.display.flip() for e in pygame.event.get(): pass keys = pygame.key.get_pressed() if keys[K_SPACE]: break while True: clock.tick(30) for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): pygame.quit() return keys = pygame.key.get_pressed() game_manager.update(keys) game_manager.draw(screen) pygame.display.flip()
def __init__(self, app_state): # create "managers" which will help a dev find things inside lists logger.info("Converting app state to analyzed app.") self.models = Manager(Model) self.pages = Manager(Page) self.routes = Manager(Route) logger.debug("Adding user fields to the analyzed app.") base_user = { "name": "User" } if app_state['users']['local']: self.local_login = True base_user['fields'] = app_state['users']['fields'] assert len([ f for f in base_user['fields'] if f['name'].lower() in ['username', 'email', 'First Name', 'Last Name']]) == 0, "Plz get rid of username field from user fields." base_user['fields'].append(simplejson.loads(r"""{"name": "username","required": true,"type": "text"}""")) # adds username base_user['fields'].append(simplejson.loads(r"""{"name": "email","required": true,"type": "text"}""")) base_user['fields'].append(simplejson.loads(r"""{"name": "First Name","required": true,"type": "text"}""")) base_user['fields'].append(simplejson.loads(r"""{"name": "Last Name","required": true,"type": "text"}""")) m = Model.create_user(base_user) self.models.add(m) if app_state['users']['facebook']: self.facebook_login = True logger.debug("Adding entities to the analyzed app.") for ent in app_state['entities']: m = Model.create(ent) self.models.add(m) logger.debug("Initing entities.") self.init_models() # create pages from app_state pages logger.debug("Adding pages to the analyzed app.") for p in app_state['pages']: page = Page(p) self.pages.add(page) logger.debug("Adding route for a page.") u = p['url'] r = Route(u, page) self.routes.add(r) # this shouldn't be here, but who cares if page.navbar_brandname is None: logger.debug("Navbar set to app name.") page.navbar_brandname = app_state['name'] # (ensures all navbar brandnames are strings) logger.debug("Resolving internal links in navbar.") for p in self.pages.each(): p.resolve_navbar_pages(self) logger.debug("Resolving the models in URLs.") self.link_models_to_routes() logger.debug("Resolving the routes and pages.") self.link_routes_and_pages() logger.debug("Resolving links in nodes.") self.fill_in_hrefs() logger.debug("Resolving forms: entity, required fields, goto page.") self.init_forms() logger.debug("Resolving entities in the lists and tables.") self.init_queries(app_state)
def minister(): parser = get_parser() options, args = parser.parse_args() if len(args) != 1: parser.print_usage() sys.exit(0) # Address ip, _, port = options.socket.partition(':') if port: port = int(port) address = (ip, port) # User if options.user: address = Manager.listen(address) set_process_owner(options.user) # Path path = args[0] if not os.path.exists(path): os.makedirs(path) # Handle Daemon Stoppping pidfile = os.path.join(path, 'minister.pid') if options.stop: if daemon.stop(pidfile): print "Minister stopped." sys.exit(0) else: sys.exit(1) elif options.restart: if daemon.stop(pidfile): print "Minister stopped." # Config config = get_config( os.path.join(path, 'config.json') ) config['path'] = path if options.debug: config['debug'] = True # Logging setup_logger( echo = options.verbose, path = os.path.join(path, 'logs/minister.log') ) # Daemon Start if options.start or options.restart: print "Minister daemon starting..." daemon.start(pidfile) # Start 'er up. manager = Manager(**config) atexit.register(manager.close) manager.serve(address)
def __init__(self, transport): """ Call superclass initializer to initialize the environment variables which are used by both clients and servers. Then initialize the environment variable which is used bo just clients. This is TOR_PT_CLIENT_TRANSPORTS. """ Manager.__init__(self) os.environ['TOR_PT_CLIENT_TRANSPORTS'] = transport
def run(): print "Hermes version 0.0.1" print "Starting Hermes Manager..." # Create a Manager m = Manager() m.run() # Demo: starts an ERPProductCustomer # from ERP.erpcustomer import * app.run()
def getMaterialIndexByPart(self, element, partIndex): """ Returns the material index either for building walls or for buildings roofs Args: element: OSM element (building=* or building:part=*) partIndex (int): Equal to either <roofIndex> or <wallIndex> """ # material name is just the related color (either a hex or a CSS color) name = Manager.normalizeColor(element.tags.get(tags[partIndex])) if name is None: # <name> is invalid as a color name if self.outline is element: # Building oultine is rendererd if there are no parts or # if the outline has <building:part=yes> # take the name for the related default color name = defaultColorNames[partIndex] # check if Blender material has been already created materialIndex = self.getMaterialIndexByName(name) if materialIndex is None: # the related Blender material hasn't been created yet, so create it materialIndex = self.createDiffuseMaterial(name, defaultColors[partIndex]) if self.parts: # If there are parts, store <materialIndex>, # since it's set for a building part, if it doesn't have an OSM tag for color self.defaultMaterialIndices[partIndex] = materialIndex else: # this a building part (building:part=yes), not the building outline # check if the material index for the default color has been set before if self.defaultMaterialIndices[partIndex] is None: # The material index for the default color hasn't been set before # Get the material index for the default color, # i.e. the material index for <self.outline> materialIndex = self.getMaterialIndexByPart(self.outline, partIndex) else: # The material index for the default color has been set before, so use it, # i.e. use the color for <self.outline> materialIndex = self.defaultMaterialIndices[partIndex] else: # check if the related Blender material has been already created materialIndex = self.getMaterialIndexByName(name) if materialIndex is None: # The related Blender material hasn't been already created, # so create it materialIndex = self.createDiffuseMaterial(name, Manager.getColor(name)) # If <element is self.outline> and there are parts, store <materialIndex>, # since it's set for a building part, if it doesn't have an OSM tag for color if element is self.outline and self.parts: self.defaultMaterialIndices[partIndex] = materialIndex return materialIndex
def main(host, db_type, port, file_name, mysql_host, mysql_port, db, user, password, target_url, interval, log_level): set_logger(getattr(logging, log_level)) proxy_list = load_file(file_name) if db_type == "sqlite": queue = SqliteQueue() else: queue = MysqlQueue(mysql_host, mysql_port, db, user, password) checker = ProxyCheck(proxy_list, queue, target_url) relay_handler = HttpRelayHandler(queue, (host, port)) scheldurer = Manager(checker, queue, relay_handler, interval) scheldurer.run()
def __init__(self, context, depth_generator): Manager.__init__(self) self.depth_generator = depth_generator self.user_generator = UserGenerator() self.user_generator.create(context) self.user_generator.register_user_cb(self.new_user, self.lost_user) self.skel_cap = self.user_generator.skeleton_cap self.skel_cap.set_profile(SKEL_PROFILE_ALL)
def walk(self, managername=None, **kwargs): """ Walk a package tree and execute callbacks along the way. This is a bit like iteration but can't match the iterator protocol due to the varying argument lists given to each type of callback. The available callbacks are: * `before(manager):` Executed before a manager's dependencies are enumerated. * `package(manager, package, versions):` Executed when a package is enumerated. * `after(manager):` Executed after a manager's dependencies are enumerated. """ # Walking begins with the system package managers, `apt` and `yum`. if managername is None: self.walk('apt', **kwargs) self.walk('yum', **kwargs) return # Get the full manager from its name. Watch out for KeyError (by # using dict.get instead of dict.__get__), which means the manager # isn't part of this blueprint. manager = Manager(managername, self.packages.get(managername, {})) # Give the manager a chance to setup for its dependencies. callable = getattr(kwargs.get('before', None), '__call__', None) if callable: callable(manager) # Each package gets its chance to take action. Note which packages # are themselves managers so they may be visited recursively later. managers = [] callable = getattr(kwargs.get('package', None), '__call__', None) for package, versions in sorted(manager.iteritems()): if callable: for version in versions: callable(manager, package, version) if managername != package and package in self.packages: managers.append(package) # Give the manager a change to cleanup after itself. callable = getattr(kwargs.get('after', None), '__call__', None) if callable: callable(manager) # Now recurse into each manager that was just installed. Recursing # here is safer because there may be secondary dependencies that are # not expressed in the hierarchy (for example the `mysql2` gem # depends on `libmysqlclient-dev` in addition to its manager). for managername in managers: self.walk(managername, **kwargs)
def tear_down_enviroment(self): print 'Tearing down test enviroment' conn = Manager.get_connection() if getattr(self, 'orig_conn', None): conn.close() cursor = self.orig_conn.cursor() else: cursor = conn.cursor() cursor.execute("DROP DATABASE %s" % self.DBNAME) cursor.close() self.orig_conn.commit() Manager.set_connection(self.orig_conn)
def cli(ctx, **args): ''' A tool which will take a guess what the NYTimes will write about something in the future ''' # manually add it since always invoked from setup.py ctx.obj = args if (ctx.invoked_subcommand is None): manager = Manager(ctx) found_articles = manager.perform_search(args['subject'], args['training_size']) manager.analyze_results(found_articles) guess = manager.predict_result(args['date'])
def test_service(): '''should had paired first''' def device_discover_services(device): # discovery services services = device.discover_services() import re for key in services.keys(): p = re.compile(">.*?<") xml = p.sub("><", services[key].replace("\n", "")) print "[ 0x%5x ]" % (key) print xml print def device_get_services(device): # get services from device_service import DeviceService from utils import bluetooth_uuid_to_string for serv in device.get_services(): service = DeviceService(serv) uuid = service.get_uuid() print "uuid:%s" % uuid print bluetooth_uuid_to_string(uuid) def device_get_uuids(device): from utils import bluetooth_uuid_to_string for uuid in device.get_uuids(): print uuid print bluetooth_uuid_to_string(uuid) from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) device = Device(adapter.get_devices()[0]) if adapter.get_devices(): device = Device(adapter.get_devices()[0]) else: print "after paired, should exists devices" print "device_get_services" device_get_services(device) print "device_discover_services" device_discover_services(device) print "device_get_uuids" device_get_uuids(device) mainloop = gobject.MainLoop() mainloop.run()
def __init__(self, transport): """ Call superclass initializer to initialize the environment variables which are used by both clients and servers. Then initialize the environment variables which are used bo just servers. These are TOR_PT_EXTENDED_SERVER_PORT, TOR_PT_ORPORT, TOR_PT_SERVER_BINDADDR, and TOR_PT_SERVER_TRANSPORTS. """ Manager.__init__(self) os.environ['TOR_PT_EXTENDED_SERVER_PORT'] = '127.0.0.1:22211' os.environ['TOR_PT_ORPORT'] = '127.0.0.1:43210' os.environ['TOR_PT_SERVER_BINDADDR'] = transport \ + '-127.0.0.1:46466' os.environ['TOR_PT_SERVER_TRANSPORTS'] = transport
def main(): parser = argparse.ArgumentParser() parser.add_argument("--do_test", help="Only test", action='store_true') args = parser.parse_args() print_newsnet_title() graph = bootstrap() manager = Manager(graph) if args.do_test: manager.test() else: manager.shell()
def start_mav_connection(request): try: #try to connect to drone via mavlink ready = Manager.get_instance().start_mav() #return true if mavlink connection is ready if ready: string = "connected" #starting continuous method for get data thread.start_new_thread(Manager.get_instance().run_mav, ()) else: string = "unable to connect" except: string = "error on server" return HttpResponse(string, content_type="text/plain")
def __main__(self, running, socket=None): if socket is not None: manager = Manager() bridge = Bridge(manager, socket=socket) self.register(manager) manager.start() try: self.run() finally: if socket is not None: while bridge or manager: pass manager.stop() bridge.stop()
def waiting_login_in(self, s): if len(s) > 2 and s[0] == 'login': if SuperManager.login_in(s[1], s[2]): self.username = '******' + s[1]+ ')' self.manager = SuperManager(self.conn) self.state = 1 elif Manager.login_in(s[1], s[2], self.conn): self.username = '******' + s[1]+ ')' self.manager = Manager(self.conn, s[1]) self.state = 1 else: print 'Warning[1]:Wrong username or password!' else: print 'Warning[0]:Please login in!'
def start(self): self.log("Starting app. Initializing storage") storage_configs = self.config.get_storages() storage_list = {} for storage_name in storage_configs: storage = storage_configs[storage_name] storage_list[storage_name] = storages.builder.build(storage) manager = Manager(self.config.dir, self.config.get_domains(), storage_list) self.log("Starting manager service") manager.start() self.log("Starting API service") api_service = api.service.Service(manager, self.config.port, self.config.ssl) api_service.start()
class ExternalToolsPlugin(cedit.Plugin): WINDOW_DATA_KEY = "ExternalToolsPluginWindowData" def __init__(self): super(ExternalToolsPlugin, self).__init__() self._manager = None self._manager_default_size = None ToolLibrary().set_locations(os.path.join(self.get_data_dir(), 'tools')) def activate(self, window): helper = ExternalToolsWindowHelper(self, window) window.set_data(self.WINDOW_DATA_KEY, helper) def deactivate(self, window): window.get_data(self.WINDOW_DATA_KEY).deactivate() window.set_data(self.WINDOW_DATA_KEY, None) def update_ui(self, window): window.get_data(self.WINDOW_DATA_KEY).update_ui() def create_configure_dialog(self): return self.open_dialog() def open_dialog(self): if not self._manager: self._manager = Manager(self.get_data_dir()) if self._manager_default_size: self._manager.dialog.set_default_size(*self._manager_default_size) self._manager.dialog.connect('destroy', self.on_manager_destroy) window = cedit.app_get_default().get_active_window() self._manager.run(window) return self._manager.dialog def update_manager(self, tool): if not self._manager: return self._manager.tool_changed(tool, True) def on_manager_destroy(self, dialog): self._manager_default_size = [dialog.allocation.width, dialog.allocation.height] self._manager = None
def main(): # TODO(sedivy): Store user_id in a config file user_id = '11124246152' playlist_id = '3dDVf6yzpX5IQK2R7GtYcq' playlist = Manager.load_playlist(user_id=user_id, playlist_id=playlist_id) parser = argparse.ArgumentParser(description='Spotify command line') parser.add_argument('command', metavar='command', nargs='+', help='Command') args = parser.parse_args() command = args.command[0] arguments = ' '.join(args.command[1:]) spotify = Spotify() if command == 'list': playlist.print_songs() elif command == 'play': spotify.play_song_from_playlist(playlist.find(arguments), playlist) elif command == 'pause': spotify.pause() elif command == 'start': spotify.start() elif command == 'toggle': spotify.toggle() elif command == 'next_track': spotify.next_track() elif command == 'previous_track': spotify.previous_track() elif command == 'play_song': spotify.play_song(arguments) else: print('Undefined command "{}"'.format(command))
def test_rm_feed(self): """ Tests rm_feed. Add a feed to the collector. Add a feed to the indexer. Get the first item: 1- Check if the webpage url exists in the indexer. Remove the feed with the query 2- Check if the same query retrieves no result. """ name, url, tag, _ = Manager.get_feeds_info()[0] self.co.add_feed(name, url, tag) self.indexer.add_feed(name) _, item = self.co.get_items(name).next() field = "webpage_url" keyword = item.webpage_url query = self.indexer._Indexer__query(field, keyword) with self.indexer.ix.searcher() as s: self.assertEquals(len(s.search(query)), 1) # 1 self.indexer.rm_feed(field, keyword, print_search=False) with self.indexer.ix.searcher() as s: self.assertEquals(len(s.search(query)), 0) # 2
def test_hypervisorCheckIn(self, server): options = MagicMock() server.return_value.registration.new_system_user_pass.return_value = { 'system_id': '123' } config = Config('test', 'libvirt', sat_server='localhost') manager = Manager.fromOptions(self.logger, options, config) options.env = "ENV" options.owner = "OWNER" manager.hypervisorCheckIn(self.host_guest_report, options) manager.server.registration.virt_notify.assert_called_with(ANY, [ [0, "exists", "system", {"identity": "host", "uuid": "0000000000000000"}], [0, "crawl_began", "system", {}], [0, "exists", "domain", { "memory_size": 0, "name": "VM 9c927368-e888-43b4-9cdb-91b10431b258 from libvirt hypervisor ad58b739-5288-4cbc-a984-bd771612d670", "state": "running", "uuid": "9c927368e88843b49cdb91b10431b258", "vcpus": 1, "virt_type": "fully_virtualized" }], [0, "exists", "domain", { "memory_size": 0, "name": "VM d5ffceb5-f79d-41be-a4c1-204f836e144a from libvirt hypervisor ad58b739-5288-4cbc-a984-bd771612d670", "state": "shutoff", "uuid": "d5ffceb5f79d41bea4c1204f836e144a", "vcpus": 1, "virt_type": "fully_virtualized" }], [0, "crawl_ended", "system", {}] ])
# -*- coding: utf-8 -*- import requests from database import Data from template import Interface import tables import windows from manager import Manager display = Interface(windows.window_dict) database = Data(tables.TABLES, windows.window_dict) manager = Manager(tables.TABLES, windows.window_dict) if __name__ == '__main__': manager.main()
class Controller: def __init__(self, players, manager, timeout, max_steps): self.players = [] self.manager = Manager(players, manager["image"]) self.state = "INITIALIZING" self.max_steps = max_steps for player in players: self.players.append(Player(player, timeout)) self.state = "READY" def start(self): self.state = "RUNNING" game_state = self.manager.get_state() current_player = self.players[0] num_steps = 0 while num_steps < self.max_steps: # can remove time.sleep(0.1) num_steps += 1 last_action = current_player.action(game_state) verdict = self.manager.action(current_player.to_dict(), last_action) print(f"---------STEP {num_steps}---------") print(f"Current player: {current_player.name}") print(f" Action: {last_action}") print(f" Verdict: {verdict}") print("---") if "error" in verdict: self.manager.invalid(current_player.to_dict()) # TODO: check if its okay to be wrong before quitting current_player.quit() # TODO: have a mech for deciding next player # ig manager should give it to me current_player = None elif "winner" in verdict: # TODO: check if winner can be deduced self.reset() break else: next_id = verdict["next"] next_player = list( filter(lambda x: x.id == next_id, self.players)) if len(next_player) == 0: print(f"Got unknown player id: {next_id}") sys.exit(1) current_player = next_player[0] game_state = verdict["state"] self.state = "READY" def reset(self): try: self.manager.quit() except Exception: pass for i in range(len(self.players)): try: self.players[i].quit() except Exception: pass
def get(self, ingredients): # Return value rv = [] rv = manager.ReceipSearch(ingredients) return json.dumps(rv) if __name__ == '__main__': # Init flask app = Flask(__name__) api = Api(app) PORT = 8081 # Create new db manager manager = Manager(settings.host, settings.username, settings.passwd, settings.database, settings.charset) # Routes configuration api.add_resource(Ingredients, '/ingredients/') api.add_resource(Receips, '/receips/') api.add_resource(IstantReceipSearch, '/istantReceipSerch/') api.add_resource(StandardReceipSearch, '/standardReceipSerch/') try: # Connect to DB manager.connect() # Start API app.run(host='localhost', port=PORT) finally: manager.close()
def application(global_config, **local_config): """Method to load all configuration of cloudooo and start the application. To start the application a number of params are required: Keyword arguments: debug_mode -- Mode as the application prints the messages. e.g debug_mode=logging.DEBUG working_path -- Full path to create the environment of the processes. e.g working_path='/var/run/cloudooo' application_hostname -- Sets the host to Openoffice. office_binary_path -- Folder where soffice.bin is installed. e.g office_binary_path='/opt/libreoffice/program' uno_path -- Folder where UNO library is installed. e.g uno_path='/opt/libreoffice/basis-link/program/' """ prefix = 'env-' environment_dict = {} for parameter_name, value in local_config.iteritems(): if parameter_name.startswith(prefix): value = value or '' variable_name = parameter_name[len(prefix):] if variable_name == 'PATH': # merge only for PATH current_value = environ.get(variable_name, '') if current_value: value = '%s:%s' % (value, current_value) environment_dict[variable_name] = value local_config["env"] = environment_dict gc.enable() debug_mode = util.convertStringToBool(local_config.get('debug_mode')) util.configureLogger(debug_mode=debug_mode) # path of directory to run cloudooo working_path = local_config.get('working_path') if not path.exists(working_path): mkdir(working_path) # directory to create temporary files cloudooo_path_tmp_dir = path.join(working_path, 'tmp') if not path.exists(cloudooo_path_tmp_dir): mkdir(cloudooo_path_tmp_dir) util.loadMimetypeList() mimetype_registry = local_config.get("mimetype_registry", "") local_config["mimetype_registry"] = handler_mapping_list = \ filter(None, mimetype_registry.split("\n")) ooo_disable_filter_list = [] for filter_name in local_config.get("ooo_disable_filter_list", "").split("\n"): filter_name = filter_name.strip() if filter_name and not filter_name in ooo_disable_filter_list: ooo_disable_filter_list.append(filter_name) local_config["ooo_disable_filter_list"] = ooo_disable_filter_list ooo_disable_filter_name_list = [] for filter_name in local_config.get("ooo_disable_filter_name_list", "").split("\n"): filter_name = filter_name.strip() if filter_name and not filter_name in ooo_disable_filter_name_list: ooo_disable_filter_name_list.append(filter_name) local_config["ooo_disable_filter_name_list"] = ooo_disable_filter_name_list handler_dict = {} for line in handler_mapping_list: input_mimetype, output_mimetype, handler = line.strip().split() if handler not in handler_dict: import_path = "cloudooo.handler.%s.handler" % handler # Import Errors are not catched, check your configuration file module = __import__(import_path, globals(), locals(), ['']) # Call the bootstraping method getattr(module, 'bootstrapHandler', lambda x: None)(local_config) handler_dict[handler] = module.Handler local_config['handler_dict'] = handler_dict from manager import Manager cloudooo_manager = Manager(cloudooo_path_tmp_dir, **local_config) return WSGIXMLRPCApplication(instance=cloudooo_manager)
def main(): Manager().run()
from application import app, db from manager import Manager import os manager = Manager() @manager.command def initialize(): """Initialize the SQLite3 database.""" db.create_all() os.system("export FLASK_APP=application.py") os.system("flask db init") @manager.command def migration(): """Migrate domain object changes to SQLite3 database.""" os.system(f"flask db migrate") os.system("flask db upgrade")
def __init__(self, *args, **kwargs): super(PyPgCursor, self).__init__(*args, **kwargs) self._logger = Manager.get_logger()
from person import Person from manager import Manager bob = Person('Bob Smith', 42, 30000, 'software') sue = Person('Sue Jones', 45, 40000, 'hardware') tom = Manager('Tom', 50, 30000) # база данных db = {} db['bob'] = bob db['sue'] = sue db['tom'] = tom if __name__ == '__main__': """если запускается, как сценарий""" for key in db: print(key, '=>\n ', db[key])
def test_found_pair(): '''test_found_pair''' def on_device_found(adapter, address, values): print "address of found device \n %s " % address if address not in adapter.get_address_records(): print "values of found device \n %s " % values print "now create device" return adapter.create_device(address) else: # print "device already exists" if adapter.get_discovering(): print "stop discovery" adapter.stop_discovery() pass def on_device_created(adapter, dev_path): print "path of created device \n %s" % dev_path device = Device(dev_path) pair(device) def pair(device): from agent import Agent path = "/org/bluez/agent" agent = Agent(path) agent.set_exit_on_release(False) device.set_trusted(True) if not device.get_paired(): print "create paired device" adapter.create_paired_device(device.get_address(), path, "DisplayYesNo", create_paired_reply, create_paired_error) def create_paired_reply(device): print "succeed paired device (%s)" % (device) def create_paired_error(error): print "paired device failed: %s" % (error) from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) adapter.set_powered(True) adapter.set_discoverable(True) adapter.set_pairable(True) # print "adapter properties:\n %s" % adapter.get_properties() adapter.connect("device-found", on_device_found) adapter.connect("device-created", on_device_created) for dev in adapter.get_devices(): print "DEBUG", dev adapter.remove_device(dev) else: pass print "begin discovery \n" adapter.start_discovery() mainloop = gobject.MainLoop() mainloop.run()
from employee import Employee from manager import Manager employeeList = [] employeeList.append(Employee("Adam", "Bobs", 1111, 60000)) employeeList.append(Employee("Carly", "Davis", 2222, 70000)) employeeList.append(Employee("Daniel", "Evans", 3333, 80000)) employeeList.append( Manager("Fredrick", "Gall", 4444, 90000, "Project Manager", 10000)) employeeList.append( Manager("Harriot", "Truman", 5555, 100000, "Division Head", 20000)) print("Original Employees:") for employee in employeeList: print(employee) # Oh boy, everyone is getting rich today! for employee in employeeList: employee.giveRaise(.2) print("\nAfter raise of 20% for everyone:") for employee in employeeList: print(employee) """ Program Output Original Employees: Adam Bobs, ssn: 1111, salary: 60000 Carly Davis, ssn: 2222, salary: 70000 Daniel Evans, ssn: 3333, salary: 80000 Fredrick Gall, ssn: 4444, salary: 90000, title: Project Manager, bonus: 10000 Harriot Truman, ssn: 5555, salary: 100000, title: Division Head, bonus: 20000 After raise of 20% for everyone: Adam Bobs, ssn: 1111, salary: 72000.0 Carly Davis, ssn: 2222, salary: 84000.0
def __init__(self, *args, **kwargs): super(TestManager, self).__init__(*args, **kwargs) self.manager = Manager.from_file(DB_CONFIG_PATH)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- @Name: make_db_classes.py @Desc: @Author: [email protected] @Create: 2020.05.07 9:04 ------------------------------------------------------------------------------- @Change: 2020.05.07 ------------------------------------------------------------------------------- """ import shelve from person import Person from manager import Manager bob = Person('Bob Smith', 42, 30000, 'Software') sue = Person('Sue Jones', 45, 40000, 'Hardware') tom = Manager('Tom Doe', 50, 50000) db = shelve.open('class-shelve') db['bob'] = bob db['sue'] = sue db['tom'] = tom db.close()
from department import Department as D from manager import Manager from emp import Employee from devdesigner import Developer, Designer from myError import SalaryGivingError from myError import WrongEmployeeRoleError tom1 = Manager('Tom Jones', 100000, 10, None) tom2 = Manager('Tom Sellek', 150000, 20, None) angelina = Manager('Angelina Jolie', 150000, 20, None) deptom1 = D('Office', 100000, 10, None) #Adding Managers deptom1.add_manager(tom1) deptom1.add_manager(tom2) deptom1.add_manager(angelina) #Adding guys john = Designer('John Sno', 100000, 1, 'Tom Jones', 0.99) jack = Developer('Jack Black', 100000, 2, 'Tom Jones') joe = Developer('Joe Moe', 100000, 5, 'Tom Sellek') jane = Developer('Jane Cane', 100000, 10, 'Tom Sellek') #deptom1.add_Team(john) # print(deptom1.team_of_managers[0].name) print('Managers:') deptom1.show_Team_M() #print(john) try: tom1.add_Team(john) tom1.add_Team(jack)
from client import ClientConnectionPool from protogen.company_pb2_grpc import CompanyServerStub from manager import Manager pool = ClientConnectionPool(stub_cls=CompanyServerStub) manager = Manager(config="config.yaml") print(manager.methods) print(manager.pools) from google.protobuf.empty_pb2 import Empty for i in range(10): r = manager.GetAllCompany(Empty()) # print(r)
from person import Person from manager import Manager bob = Person(name='Bob Smith', age=42, pay=10000) sue = Person(name='Sue jones', age=45, pay=20000) tom = Manager(name='Tom Doe', age=55, pay=30000) db = [bob, sue, tom] for obj in db: obj.giveRaise(0.10) for obj in db: print(obj.lastname(), '=>', obj.pay)
def getMaterialIndexByPart(self, element, partIndex): """ Returns the material index either for building walls or for buildings roof Args: element: OSM element (building=* or building:part=*) partIndex (int): Equal to either <roofIndex> or <wallIndex> """ # material name is just the related color (either a hex or a CSS color) name = Manager.normalizeColor(element.tags.get(tags[partIndex])) if name is None: # <name> is invalid as a color name if self.outline is element: # Building oultine is rendererd if there are no parts or # if the outline has <building:part=yes> # take the name for the related default color name = defaultColorNames[partIndex] # check if Blender material has been already created materialIndex = self.getMaterialIndexByName(name) if materialIndex is None: # the related Blender material hasn't been created yet, so create it materialIndex = self.getMaterialIndex( createDiffuseMaterial(name, defaultColors[partIndex])) if self.parts: # If there are parts, store <materialIndex>, # since it's set for a building part, if it doesn't have an OSM tag for color self.defaultMaterialIndices[partIndex] = materialIndex else: # this a building part (building:part=yes), not the building outline # check if the material index for the default color has been set before if self.defaultMaterialIndices[partIndex] is None: # The material index hasn't been set before if self.defaultMaterials[partIndex] is None: # A Blender material also hasn't been set before # Get the material index for the default color, # i.e. the material index for <self.outline> materialIndex = self.getMaterialIndexByPart( self.outline, partIndex) else: # A Blender material also has been set before # Append the Blender material to the related Blender object and # get its material index materialIndex = self.getMaterialIndex( self.defaultMaterials[partIndex]) # Store the material index, so we won't need to check # defaultMaterials for the next building part self.defaultMaterialIndices[partIndex] = materialIndex else: # The material index for the default color has been set before, so use it, # i.e. use the color for <self.outline> materialIndex = self.defaultMaterialIndices[partIndex] else: # check if the related Blender material has been already created materialIndex = self.getMaterialIndexByName(name) if materialIndex is None: # The related Blender material hasn't been already created, # so create it materialIndex = self.getMaterialIndex( createDiffuseMaterial(name, Manager.getColor(name))) # If <element is self.outline> and there are parts, store <materialIndex>, # since it's set for a building part, if it doesn't have an OSM tag for color if element is self.outline and self.parts: self.defaultMaterialIndices[partIndex] = materialIndex return materialIndex
def test_phone(): '''must had paired first, use xiaomi for test''' def get_device_supported_services(device): services = [] from utils import bluetooth_uuid_to_string for uuid in device.get_uuids(): if bluetooth_uuid_to_string(uuid) != None: services.append(bluetooth_uuid_to_string(uuid)) else: continue return services def send_file(device, files): ###please see the example in obex_agent.py pass def browse_device(device): ###please see the example in utils.py pass ### test phone audio def connect_phone_audio(device): from device import AudioSource from device import Control ###AudioSource if "AudioSource" not in get_device_supported_services(device): print "device not support AudioSource" return audiosource = AudioSource(device.object_path) ###when connect, voice switch from phone to my'pc if audiosource.get_state() == "disconnected": audiosource.connect() ###Control if "A/V_RemoteControlTarget" not in get_device_supported_services( device): print "device not support A/V control" return control = Control(device.object_path) if not control.get_connected(): return for i in range(10): control.volume_up() ###HandsFreeGateway from device import HandsfreeGateway from handsfree_agent import HandsfreeAgent if not "HandsfreeAudioGateway" in get_device_supported_services( device): print "device not support handsfree gateway" return hfg = HandsfreeGateway(device.object_path) HandsfreeAgent("/org/bluez/HandsfreeAgent") hfg.register_agent("/org/bluez/HandsfreeAgent") if hfg.get_state() == "disconnected": hfg.connect() def connect_phone_network(adapter, device): '''for my phone, it's nap''' from device import Network from adapter import NetworkServer if "NAP" not in get_device_supported_services(device): print "device not support NAP" return network = Network(device.object_path) server = NetworkServer(adapter.object_path) server.register("nap", "wlan0") network.connect("nap") def connect_phone_serial(adapter, device): pass from manager import Manager from adapter import Adapter from device import Device manager = Manager() adapter = Adapter(manager.get_default_adapter()) if adapter.get_devices(): device = Device(adapter.get_devices()[0]) else: print "after paired, should exists devices" send_file(device, ["/home/zhaixiang/debug"]) #connect_phone_audio(device) # connect_phone_network(adapter, device) mainloop = gobject.MainLoop() mainloop.run()
from manager import Manager import os import csv from src.tools.video import RipVideo, RenderVideo from src.tools.pre_processing_tools import YoloTools from src.tools.meta import log as log from src.tools.meta import config as config from src.tools.event_measure import Draw, Extract from src.obj_tracking.segmentation import Motion, IsolateObjects environment = config.get('GLOB', 'environment') log.info('Running in {} mode'.format(environment)) manager = Manager() @manager.command def run_tests(): """Run the unit tests""" log.debug('Running Tests') os.system('nose2') @manager.command def run_draw_annotations(video, em_file=None): """Draw all of event measure annotations""" ann = Draw(video=video, em_file=em_file) ann.draw_annotations()
def show_forgetting(): # Seed Random Processes print("Current Device ID:", torch.cuda.current_device()) print("Current Device: Address", torch.cuda.device(torch.cuda.current_device())) print("Current Device: Name", torch.cuda.get_device_name(torch.cuda.current_device())) print("Device Count:", torch.cuda.device_count()) print("Cuda Available: ", torch.cuda.is_available()) seed = 123 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # torch.backends.cudnn.deterministic = True # fix the GPU to deterministic mode torch.backends.cudnn.benchmark = False torch.manual_seed(seed) # CPU seed if device == torch.device("cuda:0"): print("Cuda Seeding..") torch.cuda.manual_seed_all(seed) # GPU seed random.seed(seed) # python seed for image transformation np.random.seed(seed) args = parser.parse_args() if not os.path.exists(args.save_path): print(f"Making path: {args.save_path}") os.mkdir(args.save_path) num_classes = args.num_classes num_tasks = args.num_tasks total_classes = num_classes * num_tasks prev_dl = None with open(args.outfile, 'w') as file: for k, v in args.__dict__.items(): print(f"{k},{v}", file=file, flush=True) print("Known,Task,Test Acc,Test Loss,Train Acc,Train Loss,Epoch", file=file) manager = Manager(args, device) # Show forgetting by not using distilation loss manager.use_soft_labels = False prev_dls = {} for task_id in range(1, num_tasks + 1): # Load Datasets curr_task = CIFAR100[task_id] print(f'Task: {curr_task} ({task_id})') train_loader, test_loader = CIFAR_SuperClass_loader( curr_task, args.batch_size) dl = {"train": train_loader, "test": test_loader} # Expand FC and train net train_acc, train_loss, epoch = manager.train(dl, curr_task) manager.seen_classes = manager.n_classes print("%d, " % manager.seen_classes, file=file, end="") print("model classes : %d, " % manager.seen_classes) # Evaluate on test test_acc, test_loss = manager.evaluate_per_task( test_loader, task_id) print( f"{curr_task}, {test_acc}, {test_loss}, {train_acc}, {train_loss}, {epoch}", file=file) # # # Evaluate on previous task # if len(prev_dls) != 0: # print("Evaluating on previous tasks") # for task, data in prev_dls.items(): # print(f"Task: {task}") # print(f"Previous Loss: {data['loss']}, Acc: {data['acc']}") # manager.evaluate(data['dl']) # Save Best model # save_path = args.save_path + f"{curr_task}_{test_acc}_{test_loss}" save_path = args.save_path + f"{curr_task}" save_model(manager.model, args, test_acc, test_loss, train_acc, train_loss, save_path, task_id, epoch) prev_dls[curr_task] = { "dl": dl['test'], "acc": test_acc, "loss": test_loss } if math.isnan(train_loss): print("Loss is NaN!", file=file) sys.exit(0) # Now load last saved and eval on all tasks json_file = args.outfile.replace(".csv", ".txt") with open(json_file, 'w') as f: f.write(json.dumps(manager.track_predictions)) f.close() evaluate_past_tasks(file, args, device)
parser = argparse.ArgumentParser() parser.add_argument('-n','--node', type=int, default = 20, help='Number of nodes to create on the screen. \n Maximum of 25') parser.add_argument('-b','--block', type=int, default = 6, help='Number of blocks to create on the screen. \n Maximum of 10') args = parser.parse_args() #Initializing pygame screen pygame.init() width,height = 1280,640 screen = pygame.display.set_mode((width,height)) screen_colour = (255,255,255) #White clock = pygame.time.Clock() clock.tick(60) #FPS terminate = False manager = Manager(args.node,args.block) manager.populateBlocks() #manager.testing() #manager.populateNode() while(not terminate): for event in pygame.event.get(): if event.type == pygame.QUIT: terminate = True #Fill screen with colour #Make sure blip is after this screen.fill(screen_colour) for i in range(len(manager.blocks)): pygame.draw.rect(screen, (125, 125, 125), manager.blocks[i].rect)
f = Employee('Минько', 30, 2019) print(f) print(f.experience()) print(f.days_of_work(), end='\n\n') g = Employee('Парапланов', 18, datetime.date(2010, 5, 8)) print(g) print(g.experience()) print(g.days_of_work(), end='\n\n') c = Director('Енотаевская', 60, 2010) print(c) print(c.experience()) print(c.days_of_work(), end='\n\n') d = Manager('Эйнштейн', 30, 2005) print(d) print(d.experience()) print(d.days_of_work(), end='\n\n') who = input( 'Кого вы хотите создать? (человек/работник/директор/менеджер) ').strip() if who == 'человек': surname = input('Введите фамилию: ') age = int(input('Введите возраст: ')) e = Person(surname, age) print(e, end='\n\n') elif who == 'работник': surname = input('Введите фамилию: ') age = int(input('Введите возраст: ')) year = int(input('Введите год поступления на работу: '))
def test_merge_namespace(self): new_manager = Manager() new_manager.add_command(Command(name='new_command')) manager.merge(new_manager, namespace='new_namespace') self.assertIn('new_namespace.new_command', manager.commands)
def sync_ports(self): """sslibev should only be managed by this single thread, then right ports and passwords can be ensured. If you use other tools like UDP debugger to change the port number, ssman will reset it according to database. But if you kill the process manually, if will not be corrected as sslibev cannot detect that. Direct manually password change wont be corrected. """ logger.debug('sync ports...') ports_to_add = dict() ports_to_update = dict() ports_to_remove = list() # get real working ports old_ports_list = Manager.get_working_ports() temp_dict = self._ports_working.copy() for p in temp_dict: if p not in old_ports_list: del self._ports_working[p] for p in old_ports_list: if p not in self._ports_working: self._ports_working.update({p: None}) ports_enabled = db.get_enabled_ports() for p in ports_enabled: if p in self._ports_working: if self._ports_working[p] != ports_enabled[p]: ports_to_update.update({p: ports_enabled[p]}) else: ports_to_add.update({p: ports_enabled[p]}) for p in self._ports_working: if p not in ports_enabled: ports_to_remove.append(p) if ports_to_remove: logger.info('Sync: Will Remove P%s' % ports_to_remove) ports_failed = Manager.remove_ports(ports_to_remove) if ports_failed is None: # better than try logger.info('Sync: Ports Removed') for p in ports_to_remove: del self._ports_working[p] else: for p in ports_to_remove: if p not in ports_failed: del self._ports_working[p] if ports_to_update: logger.info('Sync: Will Update P%s' % list(ports_to_update)) ports_failed = Manager.update_ports( ports_to_update) # subset of ports_to_update # then handle _ports_working: self._ports_working.update(ports_to_update) if ports_failed is None: logger.info('Sync: Ports Updated') else: for p in ports_failed: del self._ports_working[p] if ports_to_add: logger.info('Sync: Will Add P%s' % list(ports_to_add)) ports_failed = Manager.add_ports( ports_to_add) # subset of ports_to_add # then handle _ports_working: self._ports_working.update(ports_to_add) if ports_failed is not None: for p in ports_failed: del self._ports_working[p] else: logger.info('Sync: Ports Added') del ports_to_add, ports_to_remove, ports_to_update, ports_enabled, old_ports_list
class AutoBouquetsMaker(Screen): skin = """ <screen position="c-300,e-80" size="600,70" flags="wfNoBorder" > <widget name="background" position="0,0" size="600,70" zPosition="-1" /> <widget name="action" halign="center" valign="center" position="65,10" size="520,20" font="Regular;18" backgroundColor="#11404040" transparent="1" /> <widget name="status" halign="center" valign="center" position="65,35" size="520,20" font="Regular;18" backgroundColor="#11000000" transparent="1" /> <widget name="progress" position="65,55" size="520,5" borderWidth="1" backgroundColor="#11000000"/> </screen>""" LOCK_TIMEOUT_FIXED = 100 # 100ms for tick - 10 sec LOCK_TIMEOUT_ROTOR = 1200 # 100ms for tick - 120 sec ABM_BOUQUET_PREFIX = "userbouquet.abm." def __init__(self, session, args=0): self.printconfig() self.session = session Screen.__init__(self, session) Screen.setTitle(self, _("AutoBouquetsMaker")) self.frontend = None self.rawchannel = None self.postScanService = None self.providers = Manager().getProviders() self["actions"] = ActionMap(["OkCancelActions", "ColorActions"], { "cancel": self.keyCancel, "red": self.keyCancel, }, -2) self["background"] = Pixmap() self["action"] = Label(_("Starting scanner")) self["status"] = Label("") self["progress"] = ProgressBar() self["progress_text"] = Progress() self["tuner_text"] = Label("") self["Frontend"] = FrontendStatus( frontend_source=lambda: self.frontend, update_interval=100) # dependent providers self.dependents = {} for provider_key in self.providers: if len(self.providers[provider_key] ["dependent"]) > 0 and self.providers[provider_key][ "dependent"] in self.providers: if self.providers[provider_key][ "dependent"] not in self.dependents: self.dependents[self.providers[provider_key] ["dependent"]] = [] self.dependents[self.providers[provider_key] ["dependent"]].append(provider_key) # get ABM config string including dependents self.abm_settings_str = self.getABMsettings() self.actionsList = [] self.onFirstExecBegin.append(self.firstExec) def firstExec(self, postScanService=None): from Screens.Standby import inStandby if not inStandby: try: png = resolveFilename(SCOPE_ACTIVE_SKIN, "autobouquetsmaker/background.png") except: png = None if not png or not fileExists(png): png = "%s/../images/background.png" % os.path.dirname( sys.modules[__name__].__file__) self["background"].instance.setPixmapFromFile(png) if len(self.abm_settings_str) > 0: if not inStandby: self["action"].setText(_('Loading bouquets...')) self["status"].setText(_("Services: 0 video - 0 radio")) self.timer = eTimer() self.timer.callback.append(self.go) self.timer.start(100, 1) else: self.showError(_('Please first setup, in configuration')) def showError(self, message): from Screens.Standby import inStandby self.releaseFrontend() self.restartService() if not inStandby: question = self.session.open(MessageBox, message, MessageBox.TYPE_ERROR) question.setTitle(_("AutoBouquetsMaker")) self.close() def keyCancel(self): self.releaseFrontend() self.restartService() self.close() def go(self): from Screens.Standby import inStandby self.manager = Manager() self.manager.setPath("/etc/enigma2") self.manager.setAddPrefix(config.autobouquetsmaker.addprefix.value) self.selectedProviders = {} self.actionsList = [] providers_tmp = self.abm_settings_str.split("|") for provider_tmp in providers_tmp: provider_config = ProviderConfig(provider_tmp) if provider_config.isValid() and Providers().providerFileExists( provider_config.getProvider()): self.actionsList.append(provider_config.getProvider()) self.selectedProviders[ provider_config.getProvider()] = provider_config if config.autobouquetsmaker.keepallbouquets.getValue(): bouquets = Manager().getBouquetsList() bouquets_tv = [] bouquets_radio = [] for bouquet in bouquets["tv"]: if bouquet["filename"][:len(self.ABM_BOUQUET_PREFIX )] == self.ABM_BOUQUET_PREFIX: continue if len(bouquet["filename"]) > 0: bouquets_tv.append(bouquet["filename"]) for bouquet in bouquets["radio"]: if bouquet["filename"][:len(self.ABM_BOUQUET_PREFIX )] == self.ABM_BOUQUET_PREFIX: continue if len(bouquet["filename"]) > 0: bouquets_radio.append(bouquet["filename"]) self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio) else: bouquets = config.autobouquetsmaker.keepbouquets.value.split("|") bouquets_tv = [] bouquets_radio = [] for bouquet in bouquets: if bouquet.endswith(".tv"): bouquets_tv.append(bouquet) elif bouquet.endswith(".radio"): bouquets_radio.append(bouquet) self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio) bouquetsToHide = {} bouquets = config.autobouquetsmaker.hidesections.value.split("|") for bouquet in bouquets: tmp = bouquet.split(":") if len(tmp) != 2: continue if tmp[0].strip() not in bouquetsToHide: bouquetsToHide[tmp[0].strip()] = [] bouquetsToHide[tmp[0].strip()].append(int(tmp[1].strip())) self.manager.setBouquetsToHide(bouquetsToHide) self.manager.load() self.progresscount = (len(self.actionsList) * 2) + 3 self.progresscurrent = 1 if not inStandby: self["progress_text"].range = self.progresscount self["progress_text"].value = self.progresscurrent self["progress"].setRange((0, self.progresscount)) self["progress"].setValue(self.progresscurrent) self.timer = eTimer() self.timer.callback.append(self.doActions) self.timer.start(100, 1) def doActions(self): from Screens.Standby import inStandby if len(self.actionsList) == 0: self.progresscurrent += 1 self["actions"].setEnabled( False ) # disable action map here so we can't abort half way through writing result to settings files if not inStandby: self["progress_text"].value = self.progresscurrent self["progress"].setValue(self.progresscurrent) self["action"].setText(_('Bouquets generation...')) self["status"].setText( _("Services: %d video - %d radio") % (self.manager.getServiceVideoRead(), self.manager.getServiceAudioRead())) self["tuner_text"].setText("") self.timer = eTimer() self.timer.callback.append(self.doBuildIndex) self.timer.start(100, 1) return self.currentAction = self.actionsList[0] del (self.actionsList[0]) self.progresscurrent += 1 if not inStandby: self["progress_text"].value = self.progresscurrent self["progress"].setValue(self.progresscurrent) self["action"].setText( _("Tuning %s...") % str(self.providers[self.currentAction]["name"])) self["status"].setText( _("Services: %d video - %d radio") % (self.manager.getServiceVideoRead(), self.manager.getServiceAudioRead())) self["tuner_text"].setText("") self.timer = eTimer() self.timer.callback.append(self.doTune) self.timer.start(100, 1) def doTune(self): print >> log, "[ABM-main][doTune] searching for tuner for %s" % self.providers[ self.currentAction]["name"] from Screens.Standby import inStandby if self.providers[self.currentAction]["streamtype"] == "dvbs": transponder = self.providers[self.currentAction]["transponder"] else: bouquet_key = None providers_tmp = self.abm_settings_str.split("|") for provider_tmp in providers_tmp: provider_config = ProviderConfig(provider_tmp) provider_key = provider_config.getProvider() if self.currentAction != provider_key: continue bouquet_key = provider_config.getArea() if not bouquet_key: print >> log, "[ABM-main][doTune] No area found" self.showError(_('No area found')) return transponder = self.providers[ self.currentAction]["bouquets"][bouquet_key] self.transponder = transponder nimList = [] tunerSelectionAlgorithm = "UNKNOWN" # for debug for nim in nimmanager.nim_slots: if self.providers[self.currentAction][ "streamtype"] == "dvbs" and nim.isCompatible("DVB-S"): try: if nim.isFBCLink(): continue # do not load FBC links, only root tuners except: pass try: # OpenPLi Hot Switch compatible image if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \ {"dvbs": "DVB-S", "dvbc": "DVB-C", "dvbt": "DVB-T"}.get(self.providers[self.currentAction]["streamtype"], "UNKNOWN") in [x[:5] for x in nim.getTunerTypesEnabled()]: if self.validNIM(nim.slot): nimList.append(nim.slot) tunerSelectionAlgorithm = "OpenPLi Hot Switch compatible" except AttributeError: try: if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \ ((self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S")) or \ (self.providers[self.currentAction]["streamtype"] == "dvbc" and (nim.isCompatible("DVB-C") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-C")))) or \ (self.providers[self.currentAction]["streamtype"] == "dvbt" and (nim.isCompatible("DVB-T") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-T"))))): if self.validNIM(nim.slot): nimList.append(nim.slot) tunerSelectionAlgorithm = "Conventional" except AttributeError: # OpenATV > 5.3 if (self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.canBeCompatible("DVB-S") and nim.config_mode_dvbs not in ("loopthrough", "satposdepends", "nothing")) or \ (self.providers[self.currentAction]["streamtype"] == "dvbc" and nim.canBeCompatible("DVB-C") and nim.config_mode_dvbc != "nothing") or \ (self.providers[self.currentAction]["streamtype"] == "dvbt" and nim.canBeCompatible("DVB-T") and nim.config_mode_dvbt != "nothing"): if self.validNIM(nim.slot): nimList.append(nim.slot) tunerSelectionAlgorithm = "OpenATV > 5.3" print >> log, "[ABM-main][doTune] tuner selection algorithm '%s'" % tunerSelectionAlgorithm if len(nimList) == 0: print >> log, "[ABM-main][doTune] No NIMs found" self.showError( _('No NIMs found for ') + self.providers[self.currentAction]["name"]) return resmanager = eDVBResourceManager.getInstance() if not resmanager: print >> log, "[ABM-main][doTune] Cannot retrieve Resource Manager instance" self.showError(_('Cannot retrieve Resource Manager instance')) return if self.providers[self.currentAction][ "streamtype"] == "dvbs": # If we have a choice of dishes sort the nimList so "fixed" dishes have a higher priority than "motorised". nimList = [ slot for slot in nimList if not self.isRotorSat(slot, transponder["orbital_position"]) ] + [ slot for slot in nimList if self.isRotorSat(slot, transponder["orbital_position"]) ] # stop pip if running if self.session.pipshown: self.session.pipshown = False del self.session.pip print >> log, "[ABM-main][doTune] Stopping PIP." # find currently playing nim currentlyPlayingNIM = None currentService = self.session and self.session.nav.getCurrentService() frontendInfo = currentService and currentService.frontendInfo() frontendData = frontendInfo and frontendInfo.getAll(True) if frontendData is not None: currentlyPlayingNIM = frontendData.get("tuner_number", None) # stop currently playing service if it is using a tuner in ("loopthrough", "satposdepends"), as running in this configuration will prevent getting rawchannel on the root tuner. if self.providers[self.currentAction][ "streamtype"] == "dvbs" and currentlyPlayingNIM is not None and nimmanager.nim_slots[ currentlyPlayingNIM].isCompatible("DVB-S"): try: nimConfigMode = nimmanager.nim_slots[ currentlyPlayingNIM].config_mode except AttributeError: # OpenATV > 5.3 nimConfigMode = nimmanager.nim_slots[ currentlyPlayingNIM].config_mode_dvbs if nimConfigMode in ("loopthrough", "satposdepends"): self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference( ) self.session.nav.stopService() currentlyPlayingNIM = None print >> log, "[ABM-main][doTune] The active service was using a %s tuner, so had to be stopped (slot id %s)." % ( nimConfigMode, currentlyPlayingNIM) del frontendInfo del currentService self.releaseFrontend() for current_slotid in nimList: self.rawchannel = resmanager.allocateRawChannel(current_slotid) if self.rawchannel: print >> log, "[ABM-main][doTune] Tuner %s selected%s" % ( chr(ord('A') + current_slotid), (" for orbital position %d" % transponder["orbital_position"] if "orbital_position" in transponder else "")) break if not self.rawchannel: # if we are here the only possible option is to close the active service if currentlyPlayingNIM in nimList: print >> log, "[ABM-main][doTune] Tuner %s has been selected but it's busy. Stopping currently playing service." % chr( ord('A') + currentlyPlayingNIM) self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference( ) self.session.nav.stopService() self.rawchannel = resmanager.allocateRawChannel( currentlyPlayingNIM) if self.rawchannel: print >> log, "[ABM-main][doTune] The active service was stopped, and tuner %s is now free to use." % chr( ord('A') + currentlyPlayingNIM) current_slotid = currentlyPlayingNIM if not self.rawchannel: if self.session.nav.RecordTimer.isRecording(): print >> log, "[ABM-main][doTune] Cannot free NIM because a recording is in progress" self.showError( _('Cannot free NIM because a recording is in progress') ) return else: print >> log, "[ABM-main][doTune] Cannot get the NIM" self.showError(_('Cannot get the NIM')) return # set extended timeout for rotors self.motorised = False if self.providers[self.currentAction][ "streamtype"] == "dvbs" and self.isRotorSat( current_slotid, transponder["orbital_position"]): self.motorised = True self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_ROTOR print >> log, "[ABM-main][doTune] Motorised dish. Will wait up to %i seconds for tuner lock." % ( self.LOCK_TIMEOUT / 10) else: self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_FIXED print >> log, "[ABM-main][doTune] Fixed dish. Will wait up to %i seconds for tuner lock." % ( self.LOCK_TIMEOUT / 10) if not inStandby: self["tuner_text"].setText(chr(ord('A') + current_slotid)) self.frontend = self.rawchannel.getFrontend() if not self.frontend: print >> log, "[ABM-main][doTune] Cannot get frontend" self.showError(_('Cannot get frontend')) return demuxer_id = self.rawchannel.reserveDemux() if demuxer_id < 0: print >> log, "[ABM-main][doTune] Cannot allocate the demuxer." self.showError(_('Cannot allocate the demuxer.')) return if self.providers[self.currentAction]["streamtype"] == "dvbs": params = eDVBFrontendParametersSatellite() params.frequency = transponder["frequency"] params.symbol_rate = transponder["symbol_rate"] params.polarisation = transponder["polarization"] params.fec = transponder["fec_inner"] params.inversion = transponder["inversion"] params.orbital_position = transponder["orbital_position"] params.system = transponder["system"] params.modulation = transponder["modulation"] params.rolloff = transponder["roll_off"] params.pilot = transponder["pilot"] if hasattr(eDVBFrontendParametersSatellite, "No_Stream_Id_Filter"): params.is_id = eDVBFrontendParametersSatellite.No_Stream_Id_Filter if hasattr(eDVBFrontendParametersSatellite, "PLS_Gold"): params.pls_mode = eDVBFrontendParametersSatellite.PLS_Gold if hasattr(eDVBFrontendParametersSatellite, "PLS_Default_Gold_Code"): params.pls_code = eDVBFrontendParametersSatellite.PLS_Default_Gold_Code if hasattr(eDVBFrontendParametersSatellite, "No_T2MI_PLP_Id"): params.t2mi_plp_id = eDVBFrontendParametersSatellite.No_T2MI_PLP_Id if hasattr(eDVBFrontendParametersSatellite, "T2MI_Default_Pid"): params.t2mi_pid = eDVBFrontendParametersSatellite.T2MI_Default_Pid params_fe = eDVBFrontendParameters() params_fe.setDVBS(params, False) elif self.providers[self.currentAction]["streamtype"] == "dvbt": params = eDVBFrontendParametersTerrestrial() params.frequency = transponder["frequency"] params.bandwidth = transponder["bandwidth"] params.code_rate_hp = transponder["code_rate_hp"] params.code_rate_lp = transponder["code_rate_lp"] params.inversion = transponder["inversion"] params.system = transponder["system"] params.modulation = transponder["modulation"] params.transmission_mode = transponder["transmission_mode"] params.guard_interval = transponder["guard_interval"] params.hierarchy = transponder["hierarchy"] params_fe = eDVBFrontendParameters() params_fe.setDVBT(params) elif self.providers[self.currentAction]["streamtype"] == "dvbc": params = eDVBFrontendParametersCable() params.frequency = transponder["frequency"] params.symbol_rate = transponder["symbol_rate"] params.fec_inner = transponder["fec_inner"] params.inversion = transponder["inversion"] params.modulation = transponder["modulation"] params_fe = eDVBFrontendParameters() params_fe.setDVBC(params) try: self.rawchannel.requestTsidOnid() except (TypeError): # for compatibility with some third party images self.rawchannel.requestTsidOnid(self.gotTsidOnid) self.frontend.tune(params_fe) self.manager.setAdapter(0) # FIX: use the correct device self.manager.setDemuxer(demuxer_id) self.manager.setFrontend(current_slotid) self.current_slotid = current_slotid self.lockcounter = 0 self.locktimer = eTimer() self.locktimer.callback.append(self.checkTunerLock) self.locktimer.start(100, 1) def checkTunerLock(self): from Screens.Standby import inStandby dict = {} self.frontend.getFrontendStatus(dict) if dict["tuner_state"] == "TUNING": print >> log, "[ABM-main][checkTunerLock] TUNING" elif dict["tuner_state"] == "LOCKED": print >> log, "[ABM-main][checkTunerLock] ACQUIRING TSID/ONID" self.progresscurrent += 1 if not inStandby: self["progress_text"].value = self.progresscurrent self["progress"].setValue(self.progresscurrent) self["action"].setText( _("Reading %s...") % str(self.providers[self.currentAction]["name"])) self["status"].setText( _("Services: %d video - %d radio") % (self.manager.getServiceVideoRead(), self.manager.getServiceAudioRead())) self.timer = eTimer() self.timer.callback.append(self.doScan) self.timer.start(100, 1) return elif dict["tuner_state"] == "LOSTLOCK": print >> log, "[ABM-main][checkTunerLock] LOSTLOCK" elif dict["tuner_state"] == "FAILED": print >> log, "[ABM-main][checkTunerLock] TUNING FAILED FATAL" self.showError( _('Tuning failed!\n\nProvider: %s\nTuner: %s\nFrequency: %d MHz\n\nPlease check affected tuner for:\n\nTuner configuration errors,\nSignal cabling issues,\nAny other reception issues.' ) % (str(self.providers[self.currentAction]["name"]), chr(ord('A') + self.current_slotid), self.transponder["frequency"] / 1000)) return self.lockcounter += 1 if self.lockcounter > self.LOCK_TIMEOUT: print >> log, "[AutoBouquetsMaker] Timeout for tuner lock, " self.showError( _('Tuning lock timed out!\n\nProvider: %s\nTuner: %s\nFrequency: %d MHz\n\nPlease check affected tuner for:\n\nTuner configuration errors,\nSignal cabling issues,\nAny other reception issues.' ) % (str(self.providers[self.currentAction]["name"]), chr(ord('A') + self.current_slotid), self.transponder["frequency"] / 1000)) return self.locktimer.start(100, 1) # for compatibility with some third party images def gotTsidOnid(self, tsid, onid): print >> log, "[ABM-main][gotTsidOnid] tsid, onid:", tsid, onid INTERNAL_PID_STATUS_NOOP = 0 INTERNAL_PID_STATUS_WAITING = 1 INTERNAL_PID_STATUS_SUCCESSFUL = 2 INTERNAL_PID_STATUS_FAILED = 3 if tsid is not None and onid is not None: self.pidStatus = INTERNAL_PID_STATUS_SUCCESSFUL self.tsid = tsid self.onid = onid else: self.pidStatus = INTERNAL_PID_STATUS_FAILED self.tsid = -1 self.onid = -1 self.timer.start(100, True) def doScan(self): if not self.manager.read(self.selectedProviders[self.currentAction], self.providers, self.motorised): print >> log, "[ABM-main][doScan] Cannot read data" self.showError(_('Cannot read data')) return self.doActions() def doBuildIndex(self): self.manager.save(self.providers, self.dependents) self.scanComplete() def scanComplete(self): from Screens.Standby import inStandby self.releaseFrontend() self.restartService() eDVBDB.getInstance().reloadServicelist() eDVBDB.getInstance().reloadBouquets() self.progresscurrent += 1 if not inStandby: self["progress_text"].value = self.progresscurrent self["progress"].setValue(self.progresscurrent) self["action"].setText(_('Done')) self["status"].setText( _("Services: %d video - %d radio") % (self.manager.getServiceVideoRead(), self.manager.getServiceAudioRead())) self.timer = eTimer() self.timer.callback.append(self.close) self.timer.start(2000, 1) def releaseFrontend(self): if hasattr(self, 'frontend'): del self.frontend if hasattr(self, 'rawchannel'): del self.rawchannel self.frontend = None self.rawchannel = None def restartService(self): if self.postScanService: self.session.nav.playService(self.postScanService) self.postScanService = None def isRotorSat(self, slot, orb_pos): rotorSatsForNim = nimmanager.getRotorSatListForNim(slot) if len(rotorSatsForNim) > 0: for sat in rotorSatsForNim: if sat[0] == orb_pos: return True return False def validNIM(self, slot): return self.providers[ self.currentAction]["streamtype"] != "dvbs" or self.providers[ self.currentAction]["transponder"]["orbital_position"] in [ sat[0] for sat in nimmanager.getSatListForNim(slot) ] def printconfig(self): print >> log, "[ABM-config] level: ", config.autobouquetsmaker.level.value print >> log, "[ABM-config] providers: ", config.autobouquetsmaker.providers.value if config.autobouquetsmaker.bouquetsorder.value: print >> log, "[ABM-config] bouquetsorder: ", config.autobouquetsmaker.bouquetsorder.value if config.autobouquetsmaker.keepallbouquets.value: print >> log, "[ABM-config] keepbouquets: All" else: print >> log, "[ABM-config] keepbouquets: ", config.autobouquetsmaker.keepbouquets.value if config.autobouquetsmaker.hidesections.value: print >> log, "[ABM-config] hidesections: ", config.autobouquetsmaker.hidesections.value print >> log, "[ABM-config] add provider prefix: ", config.autobouquetsmaker.addprefix.value print >> log, "[ABM-config] show in extensions menu: ", config.autobouquetsmaker.extensions.value print >> log, "[ABM-config] placement: ", config.autobouquetsmaker.placement.value print >> log, "[ABM-config] skip services on non-configured satellites: ", config.autobouquetsmaker.skipservices.value print >> log, "[ABM-config] show non-indexed: ", config.autobouquetsmaker.showextraservices.value if config.autobouquetsmaker.FTA_only.value: print >> log, "[ABM-config] FTA_only: ", config.autobouquetsmaker.FTA_only.value print >> log, "[ABM-config] schedule: ", config.autobouquetsmaker.schedule.value if config.autobouquetsmaker.schedule.value: print >> log, "[ABM-config] schedule time: ", config.autobouquetsmaker.scheduletime.value print >> log, "[ABM-config] schedule days: ", [ ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")[i] for i in range(7) if config.autobouquetsmaker.days[i].value ] def getABMsettings(self): providers_extra = [] providers_tmp = config.autobouquetsmaker.providers.value.split("|") for provider_str in providers_tmp: provider = provider_str.split(":", 1)[0] if provider in self.dependents: for descendent in self.dependents[provider]: providers_extra.append('|' + descendent + ':' + provider_str.split(":", 1)[1]) return config.autobouquetsmaker.providers.value + ''.join( providers_extra) def about(self): self.session.open( MessageBox, "AutoBouquetsMaker\nVersion date - 21/10/2012\n\nCoded by:\n\nSkaman and AndyBlac", MessageBox.TYPE_INFO) def help(self): self.session.open(MessageBox, "AutoBouquetsMaker\nto be coded.", MessageBox.TYPE_INFO) def cancel(self): self.close(None)
from manager import Manager if __name__ == "__main__": m = Manager() m.get_depmap_info() m.write_config(m.cfig_path, m.parser) m.download_defaults() m.write_config(m.cfig_path, m.parser) m.depmap_autoformat() m.write_config(m.cfig_path, m.parser)
def go(self): from Screens.Standby import inStandby self.manager = Manager() self.manager.setPath("/etc/enigma2") self.manager.setAddPrefix(config.autobouquetsmaker.addprefix.value) self.selectedProviders = {} self.actionsList = [] providers_tmp = self.abm_settings_str.split("|") for provider_tmp in providers_tmp: provider_config = ProviderConfig(provider_tmp) if provider_config.isValid() and Providers().providerFileExists( provider_config.getProvider()): self.actionsList.append(provider_config.getProvider()) self.selectedProviders[ provider_config.getProvider()] = provider_config if config.autobouquetsmaker.keepallbouquets.getValue(): bouquets = Manager().getBouquetsList() bouquets_tv = [] bouquets_radio = [] for bouquet in bouquets["tv"]: if bouquet["filename"][:len(self.ABM_BOUQUET_PREFIX )] == self.ABM_BOUQUET_PREFIX: continue if len(bouquet["filename"]) > 0: bouquets_tv.append(bouquet["filename"]) for bouquet in bouquets["radio"]: if bouquet["filename"][:len(self.ABM_BOUQUET_PREFIX )] == self.ABM_BOUQUET_PREFIX: continue if len(bouquet["filename"]) > 0: bouquets_radio.append(bouquet["filename"]) self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio) else: bouquets = config.autobouquetsmaker.keepbouquets.value.split("|") bouquets_tv = [] bouquets_radio = [] for bouquet in bouquets: if bouquet.endswith(".tv"): bouquets_tv.append(bouquet) elif bouquet.endswith(".radio"): bouquets_radio.append(bouquet) self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio) bouquetsToHide = {} bouquets = config.autobouquetsmaker.hidesections.value.split("|") for bouquet in bouquets: tmp = bouquet.split(":") if len(tmp) != 2: continue if tmp[0].strip() not in bouquetsToHide: bouquetsToHide[tmp[0].strip()] = [] bouquetsToHide[tmp[0].strip()].append(int(tmp[1].strip())) self.manager.setBouquetsToHide(bouquetsToHide) self.manager.load() self.progresscount = (len(self.actionsList) * 2) + 3 self.progresscurrent = 1 if not inStandby: self["progress_text"].range = self.progresscount self["progress_text"].value = self.progresscurrent self["progress"].setRange((0, self.progresscount)) self["progress"].setValue(self.progresscurrent) self.timer = eTimer() self.timer.callback.append(self.doActions) self.timer.start(100, 1)
def checkTemperature(): manager = Manager() temp = manager.readTemperature() print("Temperature: " + str(temp) + "C") notifyTemperatureToServer(temp)
import shelve __author__ = 'Naveen' from person import Person from manager import Manager bob = Person('Bob Smith', 42, 30000, 'Software') sue = Person('Sue Jones', 45, 40000, 'Hardware') tom = Manager('Tom Due', 50, 50000) db = shelve.open('class-shelve') db['bob'] = bob db['sue'] = sue db['tom'] = tom db.close()
def __init__(self, context): self.manager = Manager() self.rpcapi = rpcapi.API(context=context) self.scheduler_client = scheduler_client.SchedulerClient() super(API, self).__init__()
import shelve from person import Person from manager import Manager # 实例化 bob = Person('bob smith', 42, 30000, 'software') sue = Person('sue jones', 42, 40000, 'hardware') tom = Manager('tom doe', 50, 50000) # 数据持久化 db = shelve.open('class.shelve') db['bob'] = bob db['sue'] = sue db['tom'] = tom db.close()