def __init__(self, *fargs, **args): Backend.__init__(self, *fargs, **args) if "log_path" in args: if "debug" in args: self.debug = args["debug"] else: self.debug = True else: self.debug = False if self.debug: self.setup_logfile("dbpedia", args["log_path"]) if "backend" in args: self.set_backend(args["backend"]) else: self.set_backend(self.default_backend) if len(fargs) > 1: if type(fargs[0]) == str: self.request = fargs else: print('fixme', fargs) sys.exit() else: self.request = fargs if type(self.request) == tuple: self.request = self.request[0]
class TranslateBot(JabberBot): """My Translator Bot""" def __init__(self, username, password, res=None, debug=False): self.backend = Backend() JabberBot.__init__(self, username, password, res, debug) @botcmd def bot_time(self, mess, args): """Displays current server time""" return str(datetime.datetime.now()) @botcmd def version(self, mess, args): """print current version of module""" return self.backend.version(mess, args) @botcmd(hidden=True) def reload(self, mess, args): """DEBUG: reload module""" import backend reload(backend) self.backend = backend.Backend() return "module reloaded." @botcmd def translate(self, mess, args): """translate: TODO add help""" return self.backend.translate(mess, args) @botcmd(hidden=True, default=True) def trans(self, mess, args): return self.backend.translate(mess, args)
def events_vimeo_analytics(): # # we should be aware that engineering events get submitted through various # means (incl scripts), so if category is not set, but expected FX is, we # count those as engineering backend = Backend() events = [] query = { "query_string": { "fields": ["category"], "query": "*" } } for event in backend.get_events_raw(query): desc = event['desc'].replace("\n", ' ').replace("\r", ' ').strip() tags = '-'.join(event['tags']) expected_effect = event.get('expected_effect', '') if type(expected_effect) is list: expected_effect = '-'.join(expected_effect) known_effect = event.get('known_effect', '') event = [event['id'], event['date'], desc, tags, event['category'], expected_effect, known_effect] events.append(event) return events
def sch(request, pi_id): print("In sched") sch_id = request.POST['sch_id'] print repr(request.POST) action = request.POST['action'] schedule = Schedule.objects.get(pk=sch_id) print "Before action '%s'" % action be = Backend() print "Backend stat size: %s" % len(be.schedDict) if action == "stop": status = Const.STATUS_STOPPED # cancel currently running schedule and start new schedule_current = Schedule.objects.filter(Q(status=Const.STATUS_RUNNING) | Q(status=Const.STATUS_PLANNED)) if len(schedule_current) > 0: print "Got running schedule '%s'" % schedule_current[0] schedule_current[0].status = Const.STATUS_STOPPED schedule_current[0].save() print "Forcing stop scheduler" be.stop_schedule(schedule_current[0]) elif action == "start": status = Const.STATUS_RUNNING be.exec_schedule(schedule) print "Status switched to: %s" % status % ", action: %s" % action schedule.status = status schedule.save() print("Saved") message = "Schedule(" + sch_id + ") is %s" % ( "started" if status == Const.STATUS_RUNNING else "stopped") print("Message:" + message) return HttpResponse(message)
def main(): import argparse parser = argparse.ArgumentParser(description='set password for AppleID. CAUTION: Use AppleIDs with payment credentials at you own risk!!! EVERY purchase will be done if possible!!! The password will be stored UNENCRYPTED!!!') parser.add_argument('-b','--backend', required=True, help='the backend url') parser.add_argument('-a','--appleId', required=True, help='the AppleId') parser.add_argument('-p','--password', required=True, help='the password') args = parser.parse_args() logger.debug(args) backend = Backend(args.backend) accounts = backend.get_accounts() passwordUpdated = False for accId, acc in accounts.items(): if 'appleId' in acc and acc['appleId'] == args.appleId: logger.debug(str(acc)) acc['password'] = args.password passwordUpdated = backend.post_account(acc) break if passwordUpdated: print "password updated for AppleId '%s'" % args.appleId else: print "unable to update password for AppleId '%s'" % args.appleId
def autoupdate(): """ Autoupdate data layer about new models in engines. """ scoped_session(Backend.instance().get_sessionmaker) Backend.instance().get_base().metadata.create_all( Backend.instance().get_engine())
class Store(LineReceiver): def __init__(self, db): # each TCP request handler gets its own sqlite cursor # this should be sufficient for proper concurrent behavior, # but if anyone can confirm this, that would be appreciated self.backend = Backend(db, exists=True) # support both \n and (default) \r\n delimiters # http://stackoverflow.com/questions/5087559/twisted-server-nc-client self.delimiter = "\n" def lineReceived(self, line): # line: <timestamp> <some> <tags=here> -- description text of the event goes here event = line.rstrip("\r").split(" -- ", 1) event[0] = event[0].split(' ', 1) timestamp = int(event[0][0]) tags = event[0][1].split(' ') desc = event[1] try: event = Event(timestamp=timestamp, desc=desc, tags=tags) print "line:", line self.backend.add_event(event) except sqlite3.OperationalError, e: sys.stderr.write("sqlite error, aborting. : %s" % e) sys.exit(2) except Exception, e: sys.stderr.write("bad line: %s --> error: %s\n" % (line, e))
class StoreFactory(Factory): def __init__(self, db): self.db = db self.backend = Backend(db) try: self.backend.assure_db() except sqlite3.OperationalError, e: sys.stderr.write("sqlite error, aborting. : %s" % e) sys.exit(2)
def stop_schedule(request, pi_id): be = Backend() messsage = {"Error"} try: sch_id = request.POST['sch_id'] # # schedule = change_schedule_status(sch_id, STATUS_STOPPED) schedule = get_object_or_404(Schedule, id=sch_id) be.stop_schedule(schedule) messsage = {Const.STATUS_STOPPED} except Schedule.DoesNotExist: raise Http404 return HttpResponse(messsage)
def __init__(self, engine_config): Backend.__init__(self, engine_config) try: self.con = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpass, db=dbname, charset='utf8') self.logger.info("Connected to MySQL db %s:%s." % (dbhost, dbname)) self.cur = self.con.cursor() except Exception as e: raise BackendError("Error connecting to MySQL db %s:%s: %s" % (dbhost, dbname, e))
def add_product_get(**kwargs): backend = Backend() return page(config, backend, state, body=template( 'tpl/events_add', tags=backend.get_tags(), extra_attributes=extra_attributes['product'], event_type='product', helptext=helptext['product'], recommended_tags=[], handler='vimeo_product', **kwargs), page='add_product', **kwargs)
def func_authenticate(self, _chan, *args, **kw): backend = Backend() if not backend.authenticate(username=kw['username'], auth_tokens=kw, ip_addr=kw['ip_addr']): return False else: if not self.namespaces.has_key(_chan): self.namespaces[_chan] = {} if not self.backend.has_key(_chan): self.backend[_chan] = backend self.namespaces[_chan]['client'] = backend.get_client_tags() return True
def add_analytics_get(**kwargs): backend = Backend() return page(config, backend, state, body=template( 'tpl/events_add', tags=backend.get_tags(), extra_attributes=extra_attributes['analytics'], event_type='analytics', helptext=helptext['analytics'], recommended_tags=[], handler='vimeo_analytics', timestamp_feeder=True, **kwargs), page='add_analytics', **kwargs)
def backend(self): '''Return D-BUS backend client interface. This gets initialized lazily. Set self.search_only to True to suppress a full system hardware detection, especially if you use only search_driver() to find a remote driver for a selected, already detected device. ''' if self._dbus_iface is None: try: if self.argv_options.no_dbus: self._dbus_iface = Backend() else: self._dbus_iface = Backend.create_dbus_client() except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name in ( 'org.freedesktop.DBus.Error.FileNotFound', 'org.freedesktop.DBus.Error.NoServer'): if self.have_ui: self.error_message(self._('Cannot connect to D-BUS,'+\ ' please use the --no-dbus option as root to'+\ ' use jockey without it.'), str(e)) else: self.error_msg(str(e)) sys.exit(1) else: raise self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) else: # handle backend timeouts try: self._dbus_iface.handler_info(' ') except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name == \ 'org.freedesktop.DBus.Error.ServiceUnknown': self._dbus_iface = Backend.create_dbus_client() self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) return self._dbus_iface
def backup_az(az_domain, backup_az_domain, ceph_host, backup_ceph_host): # get ceph conf and keyring LOG.info("connect to ceph: host=%s" % ceph_host) ceph = Ceph(ceph_host=ceph_host, ceph_user=CEPH_USER, ceph_key_file=CEPH_KEYPAIR) LOG.info("get %s from %s" % (CEPH_CONF, ceph_host)) ceph.get_file(LOCAL_CEPH_PATH+"/"+CEPH_CONF, REMOTE_CEPH_PATH+"/"+CEPH_CONF) LOG.info("get %s from %s" % (CEPH_KEYRING, ceph_host)) ceph.get_file(LOCAL_CEPH_PATH+"/"+CEPH_KEYRING, REMOTE_CEPH_PATH+"/"+CEPH_KEYRING) ceph.close() # get backup ceph conf and keyring LOG.info("connect to backup_ceph: host=%s" % backup_ceph_host) backup_ceph = Ceph(ceph_host=backup_ceph_host, ceph_user=CEPH_USER, ceph_key_file=CEPH_KEYPAIR) LOG.info("get %s from %s" % (CEPH_BACKUP_CONF, backup_ceph_host)) backup_ceph.get_file(LOCAL_CEPH_PATH+"/"+CEPH_BACKUP_CONF, REMOTE_CEPH_PATH+"/"+CEPH_BACKUP_CONF) LOG.info("get %s from %s" % (CEPH_BACKUP_KEYRING, backup_ceph_host)) backup_ceph.get_file(LOCAL_CEPH_PATH+"/"+CEPH_BACKUP_KEYRING, REMOTE_CEPH_PATH+"/"+CEPH_BACKUP_KEYRING) backup_ceph.close() backend = Backend() # update volume_backend_name volume_backend_name = CEPH_VOLUME_PREFIX+":"+az_domain+":"+backup_az_domain LOG.info("ceph storage backend update: volume_backend_name = %s" % volume_backend_name) backend.update_ceph_param("volume_backend_name", volume_backend_name) # update iscsi_server_ip LOG.info("ceph storage backend update:iscsi_server_ip=%s" % ceph_host) backend.update_ceph_param("iscsi_server_ip", ceph_host) # backend.commit() ''' update_params = {} volume_backend_name = CEPH_VOLUME_PREFIX+":"+az_domain+":"+backup_az_domain update_params["volume_backend_name"] = volume_backend_name update_params["iscsi_server_ip"] = ceph_host backend.update_ceph_params(update_params) ''' # set volume_type key # volume_type=VOLUME_TYPE_PREFIX+"@"+az_domain shell_file = CURRENT_PATH+"/script/volume_backend_name.sh" # os.system("/bin/bash " + shell_file + " " + volume_type + " " + volume_backend_name) os.system("/bin/bash " + shell_file + " " + az_domain + " " + backup_az_domain) # restart Service restart_component("cinder", "cinder-volume") restart_component("cinder", "cinder-backup")
def start_schedule(request, pi_id): be = Backend() messsage = {"Error"} try: sch_id = request.POST['sch_id'] # schedule = change_schedule_status(sch_id, STATUS_PLANNED) schedule = get_object_or_404(Schedule, id=sch_id) # Defense against idiot - do not allow to plan schedule multiple times if now, so process only active schedules if schedule.status is not Const.STATUS_RUNNING or schedule.status is not Const.STATUS_PLANNED: be.exec_schedule(schedule) messsage = {Const.STATUS_PLANNED} else: messsage = {"Nothing"} except Schedule.DoesNotExist: raise Http404 return HttpResponse(messsage)
def do_action(request, pi_id): try: act_id = request.POST['action_id'] except Exception: logger.error("Can't find action ID in request", ) pass print "act_id:%s" % act_id try: actObj = get_object_or_404(Action, id=act_id) be = Backend() logger.info("Action: '%s'", actObj.name) be.exec_action(actObj) except Action.DoesNotExist: raise Http404 logger.info("%s is executed", actObj.name) msg = "ok" return StreamingHttpResponse( msg)
def init(self): """ Override parent to do explicit setting of the date format. (Oracle specific) """ # Set date format self.setDateFormat("YYYY-MM-DD HH24:MI:SS") return Backend.init(self)
def __init__(self, db): # each TCP request handler gets its own sqlite cursor # this should be sufficient for proper concurrent behavior, # but if anyone can confirm this, that would be appreciated self.backend = Backend(db, exists=True) # support both \n and (default) \r\n delimiters # http://stackoverflow.com/questions/5087559/twisted-server-nc-client self.delimiter = "\n"
class Worker(Process): def __init__(self, backendUrl): super(Worker, self).__init__() self.name = socket.gethostname() self.backend = Backend(backendUrl) worker = self.backend.worker_for_name(self.name) if '_id' in worker: self.workerId = worker['_id'] self.backend.workerId = self.workerId else: raise Exception('Worker has no id!!!!') self._stop = Event() def stop(self): self._stop.set() def stopped(self): return self._stop.is_set() def run(self): deviceLoops = {} while not self.stopped(): devices = iDevice.devices() currDeviceUDIDs = [] # search for new devices for device in devices: currDeviceUDIDs.append(device.udid) if device.udid not in deviceLoops: dLoop = DeviceLoop(device, self.backend) dLoop.start() deviceLoops[device.udid] = dLoop logger.info('Started device loop for %s', device.udid) # cleanup finished processes for udid in deviceLoops.keys(): if udid not in currDeviceUDIDs: dLoop = deviceLoops[udid] if dLoop.is_alive(): dLoop.stop() logger.info('Waiting for DeviceLoop to stop... (%s)', udid) dLoop.join(10) if dLoop.is_alive(): logger.info('... loop has not yet stopped. Terminating the loop now. (%s)', udid) dLoop.terminate() deviceLoops.pop(udid) logger.info('Device loop finished: %s', udid) time.sleep(5) logger.info('runloop is shutting down. Stoping all client processes gracefully') for udid, process in deviceLoops: logger.info('joining device loop for device %s', udid) process.join() logger.info('Worker has finished working...')
def __init__(self, backendUrl): super(Worker, self).__init__() self.name = socket.gethostname() self.backend = Backend(backendUrl) worker = self.backend.worker_for_name(self.name) if '_id' in worker: self.workerId = worker['_id'] self.backend.workerId = self.workerId else: raise Exception('Worker has no id!!!!') self._stop = Event()
def __init__(self, host): Backend.__init__(self, host) ThreadMessaging(self) self.LINUXMIN = 5.0 # GB, guessed min. space requirement for Linux # The following flag declarations serve two purposes: # 1) Show which flags are available # 2) Show the defaults ('on' is capitalized) # Flags used to affect partition formatting (fs-type dependent usage): # ext3/4::: i:directory indexing, f: full journal self.FORMATFLAGS = "If" # Flags used to set mount options in /etc/fstab: # a: noatime, m: noauto self.MOUNTFLAGS = "Am" # Default file-system for automatic partitioning self.DEFAULTFS = "ext3" # Available file-systems for formatting self.filesystems = ['ext3', 'ext4', 'reiserfs', 'ext2', 'jfs', 'xfs'] # List of mount-point suggestions self.mountpoints = ['---', '/', '/home', '/boot', '/var', '/opt', '/usr'] # By default use UUID for partitions, and for swap (if # there is one). A problem with using UUID for swaps is that the # partition might get reformatted by another installation, # which would probably change the UUID! self.use_uuid = True self.use_uuid_swap = True # Create a directory for temporary files shutil.rmtree("/tmp/larchin", True) os.mkdir("/tmp/larchin") # For inter-thread communication of errors, etc. self.error = None self.interrupt = None
def __init__(self, parent=None): """Creates a new instance of MainWindow. @param parent Qt parent. """ super(MainWindow, self).__init__(parent) self.setupUi(self) self._backend = Backend() self._setupforumstable() self._setupthreadstable() self._setuppoststabwidget() self._setuparchivetab() self._openthreads = {} self._masterobserver = BackendObserver(self._backend, self) self._resumeobservedthreads() self.buttonManualArchive.clicked.connect(self._archivethreadmanually)
class UIDClientHandler(threading.Thread): def __init__(self, clientsocket): super(UIDClientHandler, self).__init__() self.clientsocket = clientsocket self.ass = Backend() def generate_response(self, request): """ Use the servers stored data to respond to a client Returns the appropriate response """ global uids resp = {} liked = request["liked"] disliked = request["disliked"] images = self.ass.get_recommendations(liked, disliked) print "REC: {}".format(images) resp["type"] = "OK" resp["recommendations"] = images # resp["type"] = "ERROR" # resp["body"] = "Exception while handling request" return resp def run(self): """ Client handling Thread """ print "Connected to {}".format(self.clientsocket.getpeername()) while True: try: reqstr = self.clientsocket.recvln() if not reqstr: return req = json.loads(base64.b64decode(reqstr)) print "REQ: {}".format(req) resp = self.generate_response(req) print "RESP: {}".format(resp) respstr = base64.b64encode(json.dumps(resp)) self.clientsocket.sendln(respstr) except socket.error: return
class MainWindow: def __init__(self, root): self.root = root self.backend = Backend() self.btn_select = tk.Button(self.root, text='Click to Select File', command=self.open_dialog) self.btn_run = tk.Button(self.root, text='Run', command=self.run) self.btn_location = tk.Button(self.root, text='Save Location', command=self.save_location) self.text_entry = tk.Entry(self.root) self.submit_keyword = tk.Button(self.root, text='Submit', command=self.add_keyword) def grid(self): self.btn_select.grid(row=0, column=0, sticky=tk.EW) self.btn_run.grid(row=0, column=2) self.text_entry.grid(row=1, column=0) self.submit_keyword.grid(row=1, column=1, sticky=tk.W) self.btn_location.grid(row=0, column=1) def open_dialog(self): self.backend.select_target_file(fd.askopenfilename()) def save_location(self): self.backend.set_save_folder(fd.askdirectory()) def add_keyword(self): my_string = self.text_entry.get() my_list = my_string.split(", ") self.backend.add_keywords(my_list) def run(self): threading.Thread(target=self.backend.run).start() gc.collect()
def GetPoint(self, address, API_KEY): dict_point = Backend().exec(address, API_KEY) point_loud = dict_point.get('住宅安寧') point_traffic = dict_point.get('交通安全') point_hygiene = dict_point.get('衛生') point_residence = dict_point.get('住宅安全') if point_residence == True: str_residence = "是" else: str_residence = "否" # 跨class取值:self.controller.get_page('ResultPage'),放到另一頁ResultPage # 這些按紐隨address變動,按下Enter後,才會在ResultPage建立有分數的按鈕。 button_index_loud = tk.Button(self.controller.get_page('Resultpage'), text=("%s" % point_loud), bg = '#112F41', fg = '#ED553B', font= ('Noto Sans CJK TC Bold', 40), width = 5, command=Hit_loud) button_index_loud.place(x = 630, y = 165, anchor = 'center') button_index_traffic = tk.Button(self.controller.get_page('Resultpage'), text=("%s" % point_traffic), bg = '#112F41', fg = '#ED553B', font= ('Noto Sans CJK TC Bold', 40), width = 5, command=Hit_traffic) button_index_traffic.place(x = 850, y = 165, anchor = 'center') button_index_hygiene = tk.Button(self.controller.get_page('Resultpage'), text=("%s" % point_hygiene), bg = '#112F41', fg = '#ED553B', font= ('Noto Sans CJK TC Bold', 40), width = 5, command=Hit_hygiene) button_index_hygiene.place(x = 630, y = 340, anchor = 'center') button_index_residence = tk.Button(self.controller.get_page('Resultpage'), text=("%s" % str_residence), bg = '#112F41', fg = '#ED553B', font= ('Noto Sans CJK TC Bold', 40), width = 5, command=Hit_residence) button_index_residence.place(x = 850, y = 340, anchor = 'center')
""" Created on Thu Feb 27 15:27:00 2020 @author: Dhritiman Mukherjee """ from tkinter import * from backend import Backend import requests from tkinter import ttk from functools import partial from tkcalendar import DateEntry b = Backend() flag1 = 1 class Users: #User calss for login and register new user def __init__(self): #initializing the GUI wih Login Page self.root = Tk() self.root.title("User Login") self.root.minsize(400, 500) self.root.configure(background="#166353") self.loginPage() self.root.mainloop() def loginPage(self): #login Page starts self.clear() label1 = Label(self.root, text="Login Page",
def on_start(self): self.backend = Backend()
class AbstractUI(dbus.service.Object): '''Abstract user interface. This encapsulates the entire program logic and all strings, but does not implement any concrete user interface. ''' def __init__(self): '''Initialize system. This parses command line arguments, detects available hardware, and already installed drivers and handlers. ''' gettext.install('jockey', unicode=True) (self.argv_options, self.argv_args) = self.parse_argv() fix_stdouterr() if not OSLib.inst: OSLib.inst = OSLib(client_only=not self.argv_options.no_dbus, target_kernel=self.argv_options.kernel) if self.argv_options.check: time.sleep(self.argv_options.check) self.init_strings() self._dbus_iface = None self.dbus_server_main_loop = None self.have_ui = False self.search_only = False self.current_search = (None, None) # query, result # make Control-C work properly signal.signal(signal.SIGINT, signal.SIG_DFL) def backend(self): '''Return D-BUS backend client interface. This gets initialized lazily. Set self.search_only to True to suppress a full system hardware detection, especially if you use only search_driver() to find a remote driver for a selected, already detected device. ''' if self._dbus_iface is None: try: if self.argv_options.no_dbus: self._dbus_iface = Backend() else: self._dbus_iface = Backend.create_dbus_client() except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name in ( 'org.freedesktop.DBus.Error.FileNotFound', 'org.freedesktop.DBus.Error.NoServer'): if self.have_ui: self.error_message(self._('Cannot connect to D-BUS,'+\ ' please use the --no-dbus option as root to'+\ ' use jockey without it.'), str(e)) else: self.error_msg(str(e)) sys.exit(1) else: raise self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) else: # handle backend timeouts try: self._dbus_iface.handler_info(' ') except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name == \ 'org.freedesktop.DBus.Error.ServiceUnknown': self._dbus_iface = Backend.create_dbus_client() self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) return self._dbus_iface def _(self, str, convert_keybindings=False): '''Keyboard accelerator aware gettext() wrapper. This optionally converts keyboard accelerators to the appropriate format for the frontend. All strings in the source code should use the '_' prefix for key accelerators (like in GTK). For inserting a real '_', use '__'. ''' result = _(str) if convert_keybindings: result = self.convert_keybindings(result) return result def init_strings(self): '''Initialize all static strings which are used in UI implementations.''' self.string_handler = self._('Component') self.string_button_enable = self._('_Enable', True) self.string_button_disable = self._('_Disable', True) self.string_enabled = self._('Enabled') self.string_disabled = self._('Disabled') self.string_status = self._('Status') self.string_restart = self._('Needs computer restart') self.string_in_use = self._('In use') self.string_not_in_use = self._('Not in use') self.string_license_label = self._('License:') self.string_details = self._('details') # this is used in the GUI and in --list output to denote free/restricted drivers self.string_free = self._('Free') # this is used in the GUI and in --list output to denote free/restricted drivers self.string_restricted = self._('Proprietary') self.string_download_progress_title = self._('Download in progress') self.string_unknown_driver = self._('Unknown driver') self.string_unprivileged = self._( 'You are not authorized to perform this action.') # %s is the name of the operating system self.string_support_certified = self._( 'Tested by the %s developers') % OSLib.inst.os_vendor # %s is the name of the operating system self.string_support_uncertified = self._( 'Not tested by the %s developers') % OSLib.inst.os_vendor # this is used when one version of a driver is recommended over others self.string_recommended = self._('Recommended') self.string_license_dialog_title = self._( 'License Text for Device Driver') self.string_install_drivers = self._('Install Drivers') def main_window_title(self): '''Return an appropriate translated window title. This might depend on the mode the program is called (e. g. showing only free drivers, only restricted ones, etc.). ''' if self.argv_options.mode == 'nonfree': return self._('Restricted Additional Drivers') else: return self._('Additional Drivers') def main_window_text(self): '''Return a tuple (heading, subtext) of main window texts. This changes depending on whether restricted or free drivers are used/available, or if a search is currently running. Thus the UI should update it whenever it changes a handler. ''' if self.current_search[0]: return (self._('Driver search results'), self.hwid_to_display_string(self.current_search[0])) proprietary_in_use = False proprietary_available = False for h_id in self.backend().available(self.argv_options.mode): info = self.backend().handler_info(h_id) #print 'main_window_text: info for', h_id, info if not bool(info['free']): proprietary_available = True if bool(info['used']): proprietary_in_use = True break if proprietary_in_use: heading = self._('Proprietary drivers are being used to make ' 'this computer work properly.') else: heading = self._( 'No proprietary drivers are in use on this system.') if proprietary_available: subtext = self._( # %(os)s stands for the OS name. Prefix it or suffix it, # but do not replace it. 'Proprietary drivers do not have public source code that %(os)s ' 'developers are free to modify. Security updates and corrections ' 'depend solely on the responsiveness of the manufacturer. ' '%(os)s cannot fix or improve these drivers.') % { 'os': OSLib.inst.os_vendor } else: subtext = '' return (heading, subtext) def get_handler_category(self, handler_id): '''Return string for handler category.''' if handler_id.startswith('xorg:'): return self._('Graphics driver') elif handler_id.startswith('firmware:'): return self._('Firmware') else: return self._('Device driver') def get_ui_driver_name(self, handler_info): '''Return handler name, as it should be presented in the UI. This cares about translation, as well as tagging recommended drivers. ''' result = handler_info['name'] result = self._(result) if 'version' in handler_info: result += ' (%s)' % (self._('version %s') % handler_info['version']) if bool(handler_info['recommended']): result += ' [%s]' % self.string_recommended return result # TODO: this desperately needs test cases def get_ui_driver_info(self, handler_id): '''Get strings and icon types for displaying driver information. If handler_id is None, this returns empty strings, suitable for displaying if no driver is selected, and "None" for the bool values, (UIs should disable the corresponding UI element then). This returns a mapping with the following keys: name (string), description (string), certified (bool, for icon), certification_label (label string), free (bool, for icon), license_label (Free/Proprietary, label string), license_text (string, might be empty), enabled (bool, for icon), used (bool), needs_reboot(bool), status_label (label string), button_toggle_label (string)''' if not handler_id: return { 'name': '', 'description': '', 'free': None, 'enabled': None, 'used': None, 'license_text': '', 'status_label': '', 'license_label': '', 'certified': None, 'certification_label': '', 'button_toggle_label': None, } info = self.backend().handler_info(handler_id) result = { 'name': self.get_ui_driver_name(info), 'description': self._get_description_rationale_text(info), 'free': bool(info['free']), 'enabled': bool(info['enabled']), 'used': bool(info['used']), 'needs_reboot': False, 'license_text': info.get('license', '') } if result['free']: result['license_label'] = self.string_free else: result['license_label'] = self.string_restricted # TODO: support distro certification of third party drivers if 'repository' not in info: result['certified'] = True result['certification_label'] = self.string_support_certified else: result['certified'] = False result['certification_label'] = self.string_support_uncertified if result['enabled']: if 'package' in info: result['button_toggle_label'] = self._('_Remove', True) else: result['button_toggle_label'] = self._('_Deactivate', True) if result['used']: result['status_label'] = self._( 'This driver is activated and currently in use.') else: if bool(info['changed']): result['needs_reboot'] = True result['status_label'] = self._( 'You need to restart the computer to activate this driver.' ) else: result['status_label'] = self._( 'This driver is activated but not currently in use.') else: result['button_toggle_label'] = self._('_Activate', True) if result['used']: if bool(info['changed']): result['needs_reboot'] = True result['status_label'] = self._( 'This driver was just disabled, but is still in use.') else: result['status_label'] = self._( 'A different version of this driver is in use.') else: result['status_label'] = self._( 'This driver is not activated.') return result def parse_argv(self): '''Parse command line arguments, and return (options, args) pair.''' # --check can have an optional numeric argument which sleeps for the # given number of seconds; this is mostly useful for the XDG autostart # .desktop file, to not do expensive operations right at session start def check_option_callback(option, opt_str, value, parser): if len(parser.rargs) > 0 and parser.rargs[0].isdigit(): setattr(parser.values, 'check', int(parser.rargs.pop(0))) else: setattr(parser.values, 'check', 0) parser = optparse.OptionParser() parser.set_defaults(check=None) parser.add_option( '-c', '--check', action='callback', callback=check_option_callback, help=self._( 'Check for newly used or usable drivers and notify the user.')) parser.add_option( '-u', '--update-db', action='store_true', dest='update_db', default=False, help=self. _('Query driver databases for newly available or updated drivers.' )) parser.add_option( '-l', '--list', action='store_true', dest='list', default=False, help=self._('List available drivers and their status.')) parser.add_option( '-a', '--auto-install', action='store_true', dest='auto_install', default=False, help=self._('Enable drivers that can be automatically installed.')) parser.add_option( '--hardware-ids', action='store_true', dest='list_hwids', default=False, help=self._('List hardware identifiers from this system.')) parser.add_option('-e', '--enable', type='string', dest='enable', default=None, metavar='DRIVER', help=self._('Enable a driver')) parser.add_option('-d', '--disable', type='string', dest='disable', default=None, metavar='DRIVER', help=self._('Disable a driver')) parser.add_option( '--confirm', action='store_true', dest='confirm', default=False, help=self._('Ask for confirmation for --enable/--disable')) parser.add_option( '-C', '--check-composite', action='store_true', dest='check_composite', default=False, help=self. _('Check if there is a graphics driver available that supports composite and offer to enable it' )) parser.add_option( '-m', '--mode', type='choice', dest='mode', default='any', choices=['free', 'nonfree', 'any'], metavar='free|nonfree|any', help=self._('Only manage free/nonfree drivers. By default, all' ' available drivers with any license are presented.')) parser.add_option('--dbus-server', action='store_true', dest='dbus_server', default=False, help=self._('Run as session D-BUS server.')) parser.add_option( '--no-dbus', action='store_true', default=False, help=self. _('Do not use D-BUS for communicating with the backend. Needs root privileges.' )) parser.add_option( '-k', '--kernel', type='string', help= _('Use a different target kernel version than the currently running one. This is only relevant with --no-dbus.' )) #parser.add_option ('--debug', action='store_true', # dest='debug', default=False, # help=self._('Enable debugging messages.')) (opts, args) = parser.parse_args() return (opts, args) def run(self): '''Evaluate command line arguments and do the appropriate action. If no argument was specified, this starts the interactive UI. This returns the exit code of the program. ''' # first, modes without GUI if self.argv_options.update_db: self.backend().update_driverdb() return 0 elif self.argv_options.list: self.list() return 0 elif self.argv_options.list_hwids: self.list_hwids() return 0 elif self.argv_options.dbus_server: self.dbus_server() return 0 elif self.argv_options.check is not None: if self.check(): return 0 else: return 1 # all other modes involve the GUI, so load it self.ui_init() self.have_ui = True if self.argv_options.enable: if self.set_handler_enable(self.argv_options.enable, 'enable', self.argv_options.confirm, False): return 0 else: return 1 elif self.argv_options.disable: if self.set_handler_enable(self.argv_options.disable, 'disable', self.argv_options.confirm, False): return 0 else: return 1 elif self.argv_options.check_composite: if self.check_composite(): return 0 else: return 1 elif self.argv_options.auto_install: ret = 0 for h_id in self.backend().available(self.argv_options.mode): i = self.backend().handler_info(h_id) if bool(i['auto_install']) and not bool(i['enabled']): if not self.set_handler_enable(i['id'], 'enable', self.argv_options.confirm, False): ret = 1 return ret # start the UI self.ui_show_main() res = self.ui_main_loop() self.backend().shutdown() return res def list(self): '''Print a list of available handlers and their status to stdout.''' for h_id in self.backend().available(self.argv_options.mode): i = self.backend().handler_info(h_id) print '%s - %s (%s, %s, %s)%s' % ( h_id, self._(i['name']), bool(i['free']) and self.string_free or self.string_restricted, bool(i['enabled']) and self.string_enabled or self.string_disabled, bool(i['used']) and self.string_in_use or self.string_not_in_use, bool(i['auto_install']) and ' [auto-install]' or '') def list_hwids(self): '''Print a list of available handlers and their status to stdout.''' for h_id in self.backend().get_hardware(): print h_id def check(self): '''Notify the user about newly used or available drivers since last check(). Return True if any new driver is available which is not yet enabled. ''' # if the user is running Jockey with package installation or another # long-running task in parallel, the automatic --check invocation will # time out on this. try: convert_dbus_exceptions(self.backend) except Exception as e: print >> sys.stderr, 'Cannot connect to backend, is it busy?\n', e return False try: (new_used, new_avail) = convert_dbus_exceptions( self.backend().new_used_available, self.argv_options.mode) except PermissionDeniedByPolicy: self.error_msg(self.string_unprivileged) return False # any new restricted drivers? also throw out the non-announced ones restricted_available = False for h_id in set(new_avail): # create copy info = self.backend().handler_info(h_id) if not bool(info['announce']): new_avail.remove(h_id) continue if not bool(info['free']): restricted_available = True break # throw out newly used free drivers; no need for education here for h_id in new_used + []: # create copy for iteration if bool(self.backend().handler_info(h_id)['free']): new_used.remove(h_id) notified = False # launch notifications if anything remains if new_avail or new_used: # defer UI initialization until here, since --check should not # spawn a progress dialog for searching drivers self.ui_init() self.have_ui = True if new_avail: if restricted_available: self.ui_notification( self._('Restricted drivers available'), self._( 'In order to use your hardware more efficiently, you' ' can enable drivers which are not free software.')) else: self.ui_notification( self._('New drivers available'), self._('There are new or updated drivers available for ' 'your hardware.')) notified = True elif new_used: self.ui_notification( self._('New restricted drivers in use'), # %(os)s stands for the OS name. Prefix it or suffix it, # but do not replace it. self. _('In order for this computer to function properly, %(os)s is ' 'using driver software that cannot be supported by %(os)s.' ) % {'os': OSLib.inst.os_vendor}) notified = True if notified: # we need to stay in the main loop so that the tray icon stays # around self.ui_main_loop() self.backend().shutdown() return len(new_avail) > 0 def check_composite(self): '''Check for a composite-enabling X.org driver. If one is available and not installed, offer to install it and return True if installation succeeded. Otherwise return False. ''' h_id = self.backend().check_composite() if h_id: self.set_handler_enable(h_id, 'enable', self.argv_options.confirm) return bool(self.backend().handler_info(h_id)['enabled']) self.error_msg( self. _('There is no available graphics driver for your system which supports the composite extension, or the current one already supports it.' )) return False def _install_progress_handler(self, phase, cur, total): if not self._install_progress_shown: self.ui_progress_start( self._('Additional Drivers'), self._('Downloading and installing driver...'), total) self._install_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def _remove_progress_handler(self, cur, total): if not self._install_progress_shown: self.ui_progress_start(self._('Additional Drivers'), self._('Removing driver...'), total) self._install_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def _repository_progress_handler(self, cur, total): if not self._repository_progress_shown: self.ui_progress_start( self._('Additional Drivers'), self._('Downloading and updating package indexes...'), total) self._repository_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def set_handler_enable(self, handler_id, action, confirm, gui=True): '''Enable, disable, or toggle a handler. action can be 'enable', 'disable', or 'toggle'. If confirm is True, this first presents a confirmation dialog. Then a progress dialog is presented for installation/removal of the handler. If gui is True, error messags and install progress will be shown in the GUI, otherwise just printed to stderr (CLI mode). Return True if anything was changed and thus the UI needs to be refreshed. ''' try: i = convert_dbus_exceptions(self.backend().handler_info, handler_id) except UnknownHandlerException: self.error_msg('%s: %s' % (self.string_unknown_driver, handler_id)) self.error_msg(self._('Use --list to see available drivers')) return False # determine new status if action == 'enable': enable = True elif action == 'disable': enable = False elif action == 'toggle': enable = not bool(i['enabled']) else: raise ValueError( 'invalid action %s; allowed are enable, disable, toggle') # check if we can change at all if 'can_change' in i: msg = i['can_change'] if gui: self.error_message(self._('Cannot change driver'), self._(msg)) else: self.error_msg(self._(msg)) return False # actually something to change? if enable == bool(i['enabled']): return False if confirm: # construct and ask confirmation question if enable: title = self._('Enable driver?') action = self.string_button_enable else: title = self._('Disable driver?') action = self.string_button_disable n = i['name'] # self._(i['name']) is misinterpreted by xgettext if not self.confirm_action(title, self._(n), self._get_description_rationale_text(i), action): return False # go try: if gui: try: self._install_progress_shown = False convert_dbus_exceptions( dbus_sync_call_signal_wrapper, self.backend(), 'set_enabled', { 'install_progress': self._install_progress_handler, 'remove_progress': self._remove_progress_handler }, handler_id, enable) finally: if self._install_progress_shown: self.ui_progress_finish() else: convert_dbus_exceptions(dbus_sync_call_signal_wrapper, self.backend(), 'set_enabled', {}, handler_id, enable) except PermissionDeniedByPolicy: self.error_message('', self.string_unprivileged) return False except BackendCrashError: self._dbus_iface = None self.error_message( '', '%s\n\n https://launchpad.net/jockey/+filebug\n\n%s' % (self. _('Sorry, the Jockey backend crashed. Please file a bug at:'), self._('Trying to recover by restarting backend.'))) return False except SystemError as e: self.error_message('', str(e).strip().splitlines()[-1]) return False newstate = bool(self.backend().handler_info(handler_id)['enabled']) if enable and not newstate: self.error_message( '', '%s\n\n%s: /var/log/jockey.log' % (self._('Sorry, installation of this driver failed.'), self._('Please have a look at the log file for details'))) return i['enabled'] != newstate def _get_description_rationale_text(self, h_info): d = h_info.get('description', '') r = h_info.get('rationale', '') # opportunistic translation (shipped example drivers have translations) if d: d = self._(d) if r: r = self._(r) if d and r: return d.strip() + '\n\n' + r elif d: return d elif r: return r else: return '' def download_url(self, url, filename=None, data=None): '''Download an URL into a local file, and display a progress dialog. If filename is not given, a temporary file will be created. Additional POST data can be submitted for HTTP requests in the data argument (see urllib2.urlopen). Return (filename, headers) tuple, or (None, headers) if the user cancelled the download. ''' block_size = 8192 current_size = 0 try: f = urllib2.urlopen(url) except Exception as e: self.error_message(self._('Download error'), str(e)) return (None, None) headers = f.info() if 'Content-Length' in headers: total_size = int(headers['Content-Length']) else: total_size = -1 self.ui_progress_start(self.string_download_progress_title, url, total_size) if filename: tfp = open(filename, 'wb') result_filename = filename else: (fd, result_filename) = tempfile.mkstemp() tfp = os.fdopen(fd, 'wb') try: while current_size < total_size: block = f.read(block_size) tfp.write(block) current_size += len(block) # if True, user canceled download if self.ui_progress_update(current_size, total_size): # if we created a temporary file, clean it up if not filename: os.unlink(result_filename) result_filename = None break finally: tfp.close() f.close() self.ui_progress_finish() return (result_filename, headers) @classmethod def error_msg(klass, msg): '''Print msg to stderr, and intercept IOErrors.''' try: print >> sys.stderr, msg except IOError: pass def _call_progress_dialog(self, message, fn, *args, **kwargs): '''Call fn(*args, **kwargs) while showing a progress dialog.''' if self.argv_options.no_dbus: try: del kwargs['timeout'] except KeyError: pass if not self.have_ui: return fn(*args, **kwargs) progress_shown = False t_fn = threading.Thread(None, fn, 'thread_call_progress_dialog', args, kwargs) t_fn.start() while True: t_fn.join(0.2) if not t_fn.isAlive(): break if not progress_shown: progress_shown = True self.ui_progress_start(self._('Additional Drivers'), message, -1) if self.ui_progress_update(-1, -1): sys.exit(1) # cancel self.ui_idle() if progress_shown: self.ui_progress_finish() self.ui_idle() def get_displayed_handlers(self): '''Return the list of displayed handler IDs. This can either be a list of drivers which match your system, or which match a search_driver() invocation. ''' if self.current_search[0]: return self.current_search[1] else: return self.backend().available(self.argv_options.mode) def hwid_to_display_string(self, hwid): '''Convert a type:value hardware ID string to a human friendly text.''' try: (type, value) = hwid.split(':', 1) except ValueError: return hwid if type == 'printer_deviceid': try: import cupshelpers except ImportError: return hwid info = cupshelpers.parseDeviceID(value) return info['MFG'] + ' ' + info['MDL'] return hwid def _check_repositories(self): '''Check if we have package repositories, and if not, offer to update.''' if self._dbus_iface.has_repositories(): return if self.have_ui: success = False try: self._repository_progress_shown = False success = convert_dbus_exceptions( dbus_sync_call_signal_wrapper, self._dbus_iface, 'update_repository_indexes', { 'repository_update_progress': self._repository_progress_handler }) finally: if self._repository_progress_shown: self.ui_progress_finish() # check success if not success: self.error_message( '', self. _('Downloading package indexes failed, please check your network status. ' 'Most drivers will not be available.')) else: # This happens when running in --check mode. We do not particularly # care about success here. convert_dbus_exceptions(self._dbus_iface.update_repository_indexes) # # Session D-BUS server methods # DBUS_INTERFACE_NAME = 'com.ubuntu.DeviceDriver' def dbus_server(self): '''Run session D-BUS server backend.''' dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() dbus_name = dbus.service.BusName(DBUS_BUS_NAME, bus) dbus.service.Object.__init__(self, bus, '/GUI') from gi.repository import GLib self.dbus_server_main_loop = GLib.MainLoop() self.dbus_server_main_loop.run() @classmethod def get_dbus_client(klass): '''Return a dbus.Interface object for the server.''' obj = dbus.SessionBus().get_object(DBUS_BUS_NAME, '/GUI') return dbus.Interface(obj, AbstractUI.DBUS_INTERFACE_NAME) @dbus.service.method(DBUS_INTERFACE_NAME, in_signature='s', out_signature='bas', sender_keyword='sender', connection_keyword='conn') def search_driver(self, hwid, sender=None, conn=None): '''Search configured driver DBs for a particular hardware component. The hardware component is described as HardwareID type and value, separated by a colon. E. g. "modalias:pci:12345" or "printer_deviceid:MFG:FooTech;MDL:X-12;CMD:GDI". This searches the enabled driver databases for a matching driver. If it finds one, it offers it to the user. This returns a pair (success, files); where 'success' is True if a driver was found, acknowledged by the user, and installed, otherwise False; "files" is the list of files shipped by the newly installed packages (useful for e. g. printer drivers to get a list of PPDs to check). ''' self.ui_init() # we want to show progress self.have_ui = True self.search_only = False # Note: This could be set to True if we know that we only look for # remote drivers. E. g. if you don't support local printer driver # handlers, you could do: #if hwid.startswith('printer_deviceid:'): # self.search_only = True b = self.backend() def _srch(): # TODO: this is a hack: when calling through D-BUS, specify a # timeout, when calling a local object, the timeout parameter does # not exist if hasattr(b, '_locations'): drivers = self._dbus_iface.search_driver(hwid, timeout=600) else: drivers = b.search_driver(hwid) self.current_search = (hwid, drivers) self._call_progress_dialog( self._('Searching driver for %s...') % self.hwid_to_display_string(hwid), _srch) result = False files = [] if self.current_search[1]: self.ui_show_main() self.ui_main_loop() for d in self.current_search[1]: info = self.backend().handler_info(d) if bool(info['enabled']) and bool(info['changed']): result = True if 'package' in info: files += self.backend().handler_files(d) # we are D-BUS activated, so let's free resources early if self.dbus_server_main_loop: self.dbus_server_main_loop.quit() # in case we do another operation after that, we need to reinitialize # the backend if self.search_only: self.search_only = False self._dbus_iface = None return (result, files) # # The following methods must be implemented in subclasses # def convert_keybindings(self, str): '''Convert keyboard accelerators to the particular UI's format. The abstract UI and drivers use the '_' prefix to mark a keyboard accelerator. A double underscore ('__') is converted to a real '_'.''' raise NotImplementedError('subclasses need to implement this') def ui_init(self): '''Initialize UI. This should load the GUI components, such as GtkBuilder files, but not show the main window yet; that is done by ui_show_main(). ''' raise NotImplementedError('subclasses need to implement this') def ui_show_main(self): '''Show main window. This should set up presentation of handlers and show the main window. This must be called after ui_init(). ''' raise NotImplementedError('subclasses need to implement this') def ui_main_loop(self): '''Main loop for the user interface. This should return if the user wants to quit the program, and return the exit code. ''' raise NotImplementedError('subclasses need to implement this') def error_message(self, title, text): '''Present an error message box.''' raise NotImplementedError('subclasses need to implement this') def confirm_action(self, title, text, subtext=None, action=None): '''Present a confirmation dialog. If action is given, it is used as button label instead of the default 'OK'. Return True if the user confirms, False otherwise. ''' raise NotImplementedError('subclasses need to implement this') def ui_notification(self, title, text): '''Present a notification popup. This should preferably create a tray icon. Clicking on the tray icon or notification should run the GUI. This method will attempt to instantiate an appindicator to return to both the GTK and KDE children. If whatever reason it fails (missing python-appindicator) then it should behave as it did before. ''' try: indicator = AppIndicator.Indicator.new( 'jockey', 'jockey', AppIndicator.IndicatorCategory.HARDWARE) indicator.set_icon_full('jockey', self._('Restricted drivers available')) except Exception as e: raise NotImplementedError('appindicator support not available: %s' \ '\nsubclasses need to implement this' % str(e)) indicator.set_status(AppIndicator.IndicatorStatus.ATTENTION) return indicator def ui_idle(self): '''Process pending UI events and return. This is called while waiting for external processes such as package installers. ''' raise NotImplementedError('subclasses need to implement this') def ui_progress_start(self, title, description, total): '''Create a progress dialog.''' raise NotImplementedError('subclasses need to implement this') def ui_progress_update(self, current, total): '''Update status of current progress dialog. current/total specify the number of steps done and total steps to do, or -1 if it cannot be determined. In this case the dialog should display an indeterminated progress bar (bouncing back and forth). This should return True to cancel, and False otherwise. ''' raise NotImplementedError('subclasses need to implement this') def ui_progress_finish(self): '''Close the current progress dialog.''' raise NotImplementedError('subclasses need to implement this')
from flask import Flask, redirect, json, jsonify, session from flask_restful import Resource, Api from backend import Backend import os, requests app = Flask(__name__) # generating a secret key, needed for the sessions app.secret_key = os.urandom(24) api = Api(app) backend_instance = Backend() # LDD ------------------------------------------------------------------------------------------------ class Create_database(Resource): def get(self, db_name): return backend_instance.create_database(db_name) class Create_table(Resource): def get(self, table_data): return backend_instance.create_table(table_data) class Drop_database(Resource): def get(self, db_name): return backend_instance.drop_database(db_name) class Drop_table(Resource):
class HealthPlugin(CategoryPlugin): text = 'Monitoramento' icon = '/dl/health/icon.png' folder = 'top' def on_init(self): self.backend = Backend(self.app) self.mon = ComponentManager.get().find('health-monitor') def on_session_start(self): self._settings = False self._configuring = None def get_counter(self): lst = ComponentManager.get().find('health-monitor').get() return len(filter(lambda x:x!='good', lst.values())) or None def get_ui(self): ui = self.app.inflate('health:main') ostat = 'good' stat = { 'good': 'info', 'susp': 'warn', 'dang': 'err' } text = { 'good': 'BOM', 'susp': 'ATENÇÃO', 'dang': 'PERIGO' } for m in sorted(self.mon.get(), key=lambda x:x.name): st = self.mon.get()[m] if st == 'susp' and ostat == 'good': ostat = st if st == 'dang': ostat = st ui.append('list', UI.DTR( UI.StatusCell(status=stat[st], text=text[st]), UI.DTD( UI.Label(text=m.name, bold=True), UI.Label(text=m.text), ), UI.Label( text=getattr(trans, 'trans_%s'%m.transform)(m.format_value()) ), UI.DTD( UI.TipIcon( icon='/dl/core/ui/stock/edit.png', id='config/%s/%s'%(m.plugin_id,m.variant), text='Configurar', ), ), )) if self._settings: ui.append('main', self.get_ui_settings()) if self._configuring: ui.append('main', getattr(self, 'get_ui_cfg_%s'%self._configuring.type)(self._configuring)) return ui def get_ui_settings(self): ui = self.app.inflate('health:settings') for m in self.backend.list_meters(): for v in self.backend.list_variated(m): ui.append('list', UI.DTR( UI.DTD( UI.Label(text=v.name, bold=True), UI.Label(text=v.text), ), UI.DTD( UI.TipIcon( icon='/dl/core/ui/stock/edit.png', id='config/%s/%s'%(m.plugin_id,v.variant), text='Configure', ), UI.TipIcon( icon='/dl/core/ui/stock/delete.png', id='disable/%s/%s'%(m.plugin_id,v.variant), text='Disable', ) if self.backend.has_cfg(m.plugin_id,v.variant) else None, ), )) return ui @event('button/click') def on_click(self, event, params, vars=None): if params[0] == 'btnRefresh': self.mon.refresh() if params[0] == 'btnSettings': self._settings = True if params[0] == 'config': self._configuring = self.backend.get_meter(*params[1:]) if params[0] == 'disable': self.backend.del_cfg(*params[1:]) self.mon.refresh() @event('dialog/submit') def on_submit(self, event, params, vars=None): if params[0] == 'dlgSettings': self._settings = False if params[0] == 'dlgConfigure': if vars.getvalue('action', None) == 'OK': try: getattr(self, 'apply_cfg_%s'%(self._configuring.type))(self._configuring, vars) except: self.app.log.error('Invalid meter configuration') self.mon.refresh() self._configuring = None def get_ui_cfg_binary(self, cls): ui = self.app.inflate('health:cfg-binary') t = self.backend.get_cfg(cls.plugin_id, cls.variant).setdefault('good_state', True) ui.find('r-true').set('checked', t) ui.find('r-false').set('checked', not t) return ui def get_ui_cfg_decimal(self, cls): ui = self.app.inflate('health:cfg-decimal') c = self.backend.get_cfg(cls.plugin_id, cls.variant) ui.find('limit_susp').set('value', str(c.setdefault('limit_susp', 33.0))) ui.find('limit_dang').set('value', str(c.setdefault('limit_dang', 66.0))) return ui def get_ui_cfg_linear(self, cls): ui = self.app.inflate('health:cfg-linear') c = self.backend.get_cfg(cls.plugin_id, cls.variant) ui.find('limit_susp').set('value', str(c.setdefault('limit_susp', 33.0))) ui.find('limit_dang').set('value', str(c.setdefault('limit_dang', 66.0))) ui.find('max').set('text', 'Min: %.2f, max: %.2f'%(cls.get_min(), cls.get_max())) return ui def apply_cfg_binary(self, cls, vars): self.backend.set_cfg(cls.plugin_id, cls.variant, {'good_state': eval(vars.getvalue('val', 'True'))}) def apply_cfg_decimal(self, cls, vars): self.backend.set_cfg(cls.plugin_id, cls.variant, { 'limit_susp': float(vars.getvalue('lim_susp', True)), 'limit_dang': float(vars.getvalue('lim_dang', True)), }) apply_cfg_linear = apply_cfg_decimal
def init(self): """ Avoid the Oracle specific stuff here in parent method. """ return Backend.init(self)
import sys sys.path.append('../2.1') sys.path.append('../Deliverables/2/2.1') from backend_driver import json_parse_stdin from backend import Backend import json # parse the stdin to json objects objs = json_parse_stdin() # for each series of 10, call the sort function output = [] backend_obj = Backend() for i in range(0, len(objs), 10): obj_slice = objs[i:i + 10] if len(obj_slice) == 10: ret = json.dumps(backend_obj.sort(objs[i:i + 10])) output.append(ret) print("[{}]".format(",".join(output)))
y = 5 for i in range(size): dic["y"].append(y) y += random.randint(-3, 3) return dic def randomColor(size): output = [] for i in range(size): output.append(QColor(random.randint(0, 16777215))) return output if __name__ == '__main__': app = QApplication(sys.argv) backend = Backend() main = MainWindow( backend.connect, backend.disconnect, backend.setCurrentTime, backend.setZoom, backend.eraseBeforeCut, backend.cancelLastCut, backend.addCut, backend.sendOrder, backend.updateSubscriptions) backend.setGraphicalInterface(main.toolBar, main.consolePanel, main.graphPanel) backend.startBackgroundTask() # main.consolePanel.setText( # """424242_info_loli is here ! # 424252_info_loli is not here ! # 424262_info_loli is there ! # 424272_error_This is normal ! # 424282_info_loli is very long like this line, which is especially long ! # 624272_order_Order launched # 624273_answer_Answer of the order ! # """) # d = {
class TuringChat(): def __init__(self, uiPrintMessage, sendQuit=None): self.settings = Settings(self.printMessage) self.turing = Backend() self.client = None self.server = None self.uiPrintMessage = uiPrintMessage self.sendQuit = sendQuit self.connexion = None self.server = Server(self.turing, self.printMessage, self.writeMessages) self.client = Client(self.turing, self.printMessage, self.writeMessages) self.username = self.settings.getSetting("username") self.otherUsername = None self.trustManager = TrustManager(self.printMessage) self.msgBuffer = [] self.fileList = [] self.translate = Translate(self.printMessage, self.settings.getSetting("language")) setObject(self.translate) def printMessage(self, text, message=False, username=None): if username: self.otherUsername = username return self.printMessage( self.translate.tr("username.other.changed") + username) if message and not self.trustManager.connexionTrusted(): self.msgBuffer.append((text, message, username)) else: self.uiPrintMessage(text, message, username) if self.trustManager.connexionTrusted(): for element in self.msgBuffer: self.uiPrintMessage(element[0], element[1], element[2]) self.msgBuffer = [] def writeMessages(self, connexion, fingerprint=None): self.connexion = connexion if self.connexion: self.connexion.setTuringChat(self) if fingerprint: self.trustManager.setCurrentFingerprint(fingerprint) if self.username and self.connexion: self.connexion.send( self.turing.createMessage("username", self.username)) def startServer(self): self.stopConnexions() self.server.listen() self.server.start() def stopServer(self): if self.server.listening() or self.server.isStopped(): if not self.server.isStopped(): self.server.stop() self.server.join() self.server = Server(self.turing, self.printMessage, self.writeMessages) def startClient(self, addr="127.0.0.1"): self.stopConnexions() self.client.connect(addr) def stopClient(self): if self.client.connected(): self.client.close() def stopConnexions(self): self.stopClient() self.stopServer() def setUsername(self, username): self.username = username self.settings.setSetting("username", username) if self.connexion: self.connexion.send(self.turing.createMessage( "username", username)) self.printMessage(self.translate.tr("username.changed") + username) def connect(self, host="127.0.0.1"): if host == "last": host = self.settings.getSetting("lastHost") self.settings.setSetting("lastHost", host) self.startClient(host) def sendMessage(self, message): if not self.connexion: self.printMessage(self.translate.tr("error.not.connected")) return if not self.trustManager.connexionTrusted(): self.printMessage(self.translate.tr("error.connexion.not.trusted")) return self.printMessage(self.translate.tr("user.you") + message) self.connexion.send(self.turing.createMessage("message", message)) def quit(self): self.stopClient() self.stopServer() if self.sendQuit: self.sendQuit() return "quit" def setLanguage(self, language): self.translate.setLanguage(language) self.settings.setSetting("language", language) self.printMessage(self.translate.tr("language.set")) def parseCommand(self, command): parsing.listen.setParseAction(self.startServer) parsing.connect.setParseAction(lambda arg: self.connect(arg[1])) parsing.quit.setParseAction(self.quit) parsing.help.setParseAction( lambda: self.printMessage(self.translate.tr("command.help.text"))) parsing.nick.setParseAction(lambda arg: self.setUsername(arg[1])) parsing.trust.setParseAction( lambda arg: self.trustManager.setTrust(arg[1])) parsing.fingerprint.setParseAction( lambda: self.printMessage(self.turing.getMyFingerprint())) parsing.language.setParseAction(lambda arg: self.setLanguage(arg[1])) parsing.file.setParseAction(lambda arg: self.saveFile(arg[2]) if arg[ 1] == "download" else arg[1] == "upload" and self.sendFile(arg[2])) try: result = parsing.commands.parseString(command, True) if result[1] == "quit": return "quit" except pyparsing.ParseException: self.sendMessage(command) def addFile(self, file): self.fileList.append(file) def saveFile(self, fileId): fileId = int(fileId) if fileId < len(self.fileList): fileContent = self.fileList[fileId] with open("file-" + str(fileId), "wb") as f: f.write(fileContent) self.printMessage(self.translate.tr("file.saved")) else: self.printMessage(self.translate.tr("error.file.notfound")) def sendFile(self, filename): if os.path.isfile(filename): with open(filename, "rb") as f: data = f.read() self.connexion.send(self.turing.createMessage("file", data)) self.printMessage(self.translate.tr("file.sent")) else: self.printMessage(self.translate.tr("error.file.notfound"))
def __init__(self): Backend.__init__(self, rhnSQL)
def __init__(self, rng_seed=None, default_dtype=theano.config.floatX): Backend.__init__(self, rng_seed=rng_seed, default_dtype=default_dtype)
parser = argparse.ArgumentParser( description= 'Search for apps within the given folder and add it to the backend.') parser.add_argument('-a', '--app-folder', default='~/Music/iTunes/iTunes Media/Mobile Applications/', help='The folder containing the apps to import.') parser.add_argument('-b', '--backend', required=True, help='the backend url.') args = parser.parse_args() logging.debug(args) # setup backend = Backend(args.backend) path = os.path.expanduser(unicode(args.app_folder)) if not os.path.exists(path): logging.error('Path not found: %s', path) sys.exit(1) for filename in os.listdir(path): logging.info('processing %s', filename) filepath = "%s/%s" % (path, filename) if not zipfile.is_zipfile(filepath): logging.warning('%s is not a zipfile! - skipping', filename) continue appData = {'type': 'AppStoreApp'} with zipfile.ZipFile(filepath, 'r') as appachive:
import traceback from alerting import Db, rule_from_form # contains all errors as key:(title,msg) items. # will be used throughout the runtime to track all encountered errors errors = {} # will contain the latest data last_update = None config = make_config(config) logger = make_logger('app', config) logger.debug('app starting') backend = Backend(config, logger) s_metrics = structured_metrics.StructuredMetrics(config, logger) graphs_manager = Graphs() graphs_manager.load_plugins() graphs_all = graphs_manager.list_graphs() bottle.TEMPLATE_PATH.insert(0, os.path.dirname(__file__)) @route('<path:re:/assets/.*>') @route('<path:re:/timeserieswidget/.*(js|css)>') @route('<path:re:/timeserieswidget/timezone-js/src/.*js>') @route('<path:re:/timeserieswidget/tz/.*>') @route('<path:re:/DataTables/media/js/.*js>') @route('<path:re:/DataTablesPlugins/integration/bootstrap/.*(js|css)>') def static(path):
class AbstractUI(dbus.service.Object): '''Abstract user interface. This encapsulates the entire program logic and all strings, but does not implement any concrete user interface. ''' def __init__(self): '''Initialize system. This parses command line arguments, detects available hardware, and already installed drivers and handlers. ''' gettext.install('jockey', unicode=True) (self.argv_options, self.argv_args) = self.parse_argv() fix_stdouterr() if not OSLib.inst: OSLib.inst = OSLib(client_only=not self.argv_options.no_dbus, target_kernel=self.argv_options.kernel) if self.argv_options.check: time.sleep(self.argv_options.check) self.init_strings() self._dbus_iface = None self.dbus_server_main_loop = None self.have_ui = False self.search_only = False self.current_search = (None, None) # query, result # make Control-C work properly signal.signal(signal.SIGINT, signal.SIG_DFL) def backend(self): '''Return D-BUS backend client interface. This gets initialized lazily. Set self.search_only to True to suppress a full system hardware detection, especially if you use only search_driver() to find a remote driver for a selected, already detected device. ''' if self._dbus_iface is None: try: if self.argv_options.no_dbus: self._dbus_iface = Backend() else: self._dbus_iface = Backend.create_dbus_client() except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name in ( 'org.freedesktop.DBus.Error.FileNotFound', 'org.freedesktop.DBus.Error.NoServer'): if self.have_ui: self.error_message(self._('Cannot connect to D-BUS,'+\ ' please use the --no-dbus option as root to'+\ ' use jockey without it.'), str(e)) else: self.error_msg(str(e)) sys.exit(1) else: raise self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) else: # handle backend timeouts try: self._dbus_iface.handler_info(' ') except Exception as e: if hasattr(e, '_dbus_error_name') and e._dbus_error_name == \ 'org.freedesktop.DBus.Error.ServiceUnknown': self._dbus_iface = Backend.create_dbus_client() self._check_repositories() self._call_progress_dialog( self._('Searching for available drivers...'), self.search_only and self._dbus_iface.db_init or self._dbus_iface.detect, timeout=600) return self._dbus_iface def _(self, str, convert_keybindings=False): '''Keyboard accelerator aware gettext() wrapper. This optionally converts keyboard accelerators to the appropriate format for the frontend. All strings in the source code should use the '_' prefix for key accelerators (like in GTK). For inserting a real '_', use '__'. ''' result = _(str) if convert_keybindings: result = self.convert_keybindings(result) return result def init_strings(self): '''Initialize all static strings which are used in UI implementations.''' self.string_handler = self._('Component') self.string_button_enable = self._('_Enable', True) self.string_button_disable = self._('_Disable', True) self.string_enabled = self._('Enabled') self.string_disabled = self._('Disabled') self.string_status = self._('Status') self.string_restart = self._('Needs computer restart') self.string_in_use = self._('In use') self.string_not_in_use = self._('Not in use') self.string_license_label = self._('License:') self.string_details = self._('details') # this is used in the GUI and in --list output to denote free/restricted drivers self.string_free = self._('Free') # this is used in the GUI and in --list output to denote free/restricted drivers self.string_restricted = self._('Proprietary') self.string_download_progress_title = self._('Download in progress') self.string_unknown_driver = self._('Unknown driver') self.string_unprivileged = self._('You are not authorized to perform this action.') # %s is the name of the operating system self.string_support_certified = self._('Tested by the %s developers') % OSLib.inst.os_vendor # %s is the name of the operating system self.string_support_uncertified = self._('Not tested by the %s developers') % OSLib.inst.os_vendor # this is used when one version of a driver is recommended over others self.string_recommended = self._('Recommended') self.string_license_dialog_title = self._('License Text for Device Driver') self.string_install_drivers = self._('Install Drivers') def main_window_title(self): '''Return an appropriate translated window title. This might depend on the mode the program is called (e. g. showing only free drivers, only restricted ones, etc.). ''' if self.argv_options.mode == 'nonfree': return self._('Restricted Additional Drivers') else: return self._('Additional Drivers') def main_window_text(self): '''Return a tuple (heading, subtext) of main window texts. This changes depending on whether restricted or free drivers are used/available, or if a search is currently running. Thus the UI should update it whenever it changes a handler. ''' if self.current_search[0]: return (self._('Driver search results'), self.hwid_to_display_string(self.current_search[0])) proprietary_in_use = False proprietary_available = False for h_id in self.backend().available(self.argv_options.mode): info = self.backend().handler_info(h_id) #print 'main_window_text: info for', h_id, info if not bool(info['free']): proprietary_available = True if bool(info['used']): proprietary_in_use = True break if proprietary_in_use: heading = self._('Proprietary drivers are being used to make ' 'this computer work properly.') else: heading = self._('No proprietary drivers are in use on this system.') if proprietary_available: subtext = self._( # %(os)s stands for the OS name. Prefix it or suffix it, # but do not replace it. 'Proprietary drivers do not have public source code that %(os)s ' 'developers are free to modify. Security updates and corrections ' 'depend solely on the responsiveness of the manufacturer. ' '%(os)s cannot fix or improve these drivers.') % {'os': OSLib.inst.os_vendor} else: subtext = '' return (heading, subtext) def get_handler_category(self, handler_id): '''Return string for handler category.''' if handler_id.startswith('xorg:'): return self._('Graphics driver') elif handler_id.startswith('firmware:'): return self._('Firmware') else: return self._('Device driver') def get_ui_driver_name(self, handler_info): '''Return handler name, as it should be presented in the UI. This cares about translation, as well as tagging recommended drivers. ''' result = handler_info['name'] result = self._(result) if 'version' in handler_info: result += ' (%s)' % (self._('version %s') % handler_info['version']) if bool(handler_info['recommended']): result += ' [%s]' % self.string_recommended return result # TODO: this desperately needs test cases def get_ui_driver_info(self, handler_id): '''Get strings and icon types for displaying driver information. If handler_id is None, this returns empty strings, suitable for displaying if no driver is selected, and "None" for the bool values, (UIs should disable the corresponding UI element then). This returns a mapping with the following keys: name (string), description (string), certified (bool, for icon), certification_label (label string), free (bool, for icon), license_label (Free/Proprietary, label string), license_text (string, might be empty), enabled (bool, for icon), used (bool), needs_reboot(bool), status_label (label string), button_toggle_label (string)''' if not handler_id: return { 'name': '', 'description': '', 'free': None, 'enabled': None, 'used': None, 'license_text': '', 'status_label': '', 'license_label': '', 'certified': None, 'certification_label': '', 'button_toggle_label': None, } info = self.backend().handler_info(handler_id) result = { 'name': self.get_ui_driver_name(info), 'description': self._get_description_rationale_text(info), 'free': bool(info['free']), 'enabled': bool(info['enabled']), 'used': bool(info['used']), 'needs_reboot': False, 'license_text': info.get('license', '') } if result['free']: result['license_label'] = self.string_free else: result['license_label'] = self.string_restricted # TODO: support distro certification of third party drivers if 'repository' not in info: result['certified'] = True result['certification_label'] = self.string_support_certified else: result['certified'] = False result['certification_label'] = self.string_support_uncertified if result['enabled']: if 'package' in info: result['button_toggle_label'] = self._('_Remove', True) else: result['button_toggle_label'] = self._('_Deactivate', True) if result['used']: result['status_label'] = self._('This driver is activated and currently in use.') else: if bool(info['changed']): result['needs_reboot'] = True result['status_label'] = self._('You need to restart the computer to activate this driver.') else: result['status_label'] = self._('This driver is activated but not currently in use.') else: result['button_toggle_label'] = self._('_Activate', True) if result['used']: if bool(info['changed']): result['needs_reboot'] = True result['status_label'] = self._('This driver was just disabled, but is still in use.') else: result['status_label'] = self._('A different version of this driver is in use.') else: result['status_label'] = self._('This driver is not activated.') return result def parse_argv(self): '''Parse command line arguments, and return (options, args) pair.''' # --check can have an optional numeric argument which sleeps for the # given number of seconds; this is mostly useful for the XDG autostart # .desktop file, to not do expensive operations right at session start def check_option_callback(option, opt_str, value, parser): if len(parser.rargs) > 0 and parser.rargs[0].isdigit(): setattr(parser.values, 'check', int(parser.rargs.pop(0))) else: setattr(parser.values, 'check', 0) parser = optparse.OptionParser() parser.set_defaults(check=None) parser.add_option ('-c', '--check', action='callback', callback=check_option_callback, help=self._('Check for newly used or usable drivers and notify the user.')) parser.add_option ('-u', '--update-db', action='store_true', dest='update_db', default=False, help=self._('Query driver databases for newly available or updated drivers.')) parser.add_option ('-l', '--list', action='store_true', dest='list', default=False, help=self._('List available drivers and their status.')) parser.add_option ('-a', '--auto-install', action='store_true', dest='auto_install', default=False, help=self._('Enable drivers that can be automatically installed.')) parser.add_option ('--hardware-ids', action='store_true', dest='list_hwids', default=False, help=self._('List hardware identifiers from this system.')) parser.add_option ('-e', '--enable', type='string', dest='enable', default=None, metavar='DRIVER', help=self._('Enable a driver')) parser.add_option ('-d', '--disable', type='string', dest='disable', default=None, metavar='DRIVER', help=self._('Disable a driver')) parser.add_option ('--confirm', action='store_true', dest='confirm', default=False, help=self._('Ask for confirmation for --enable/--disable')) parser.add_option ('-C', '--check-composite', action='store_true', dest='check_composite', default=False, help=self._('Check if there is a graphics driver available that supports composite and offer to enable it')) parser.add_option ('-m', '--mode', type='choice', dest='mode', default='any', choices=['free', 'nonfree', 'any'], metavar='free|nonfree|any', help=self._('Only manage free/nonfree drivers. By default, all' ' available drivers with any license are presented.')) parser.add_option ('--dbus-server', action='store_true', dest='dbus_server', default=False, help=self._('Run as session D-BUS server.')) parser.add_option ('--no-dbus', action='store_true', default=False, help=self._('Do not use D-BUS for communicating with the backend. Needs root privileges.')) parser.add_option ('-k', '--kernel', type='string', help=_('Use a different target kernel version than the currently running one. This is only relevant with --no-dbus.')) #parser.add_option ('--debug', action='store_true', # dest='debug', default=False, # help=self._('Enable debugging messages.')) (opts, args) = parser.parse_args() return (opts, args) def run(self): '''Evaluate command line arguments and do the appropriate action. If no argument was specified, this starts the interactive UI. This returns the exit code of the program. ''' # first, modes without GUI if self.argv_options.update_db: self.backend().update_driverdb() return 0 elif self.argv_options.list: self.list() return 0 elif self.argv_options.list_hwids: self.list_hwids() return 0 elif self.argv_options.dbus_server: self.dbus_server() return 0 elif self.argv_options.check is not None: if self.check(): return 0 else: return 1 # all other modes involve the GUI, so load it self.ui_init() self.have_ui = True if self.argv_options.enable: if self.set_handler_enable(self.argv_options.enable, 'enable', self.argv_options.confirm, False): return 0 else: return 1 elif self.argv_options.disable: if self.set_handler_enable(self.argv_options.disable, 'disable', self.argv_options.confirm, False): return 0 else: return 1 elif self.argv_options.check_composite: if self.check_composite(): return 0 else: return 1 elif self.argv_options.auto_install: ret = 0 for h_id in self.backend().available(self.argv_options.mode): i = self.backend().handler_info(h_id) if bool(i['auto_install']) and not bool(i['enabled']): if not self.set_handler_enable(i['id'], 'enable', self.argv_options.confirm, False): ret = 1 return ret # start the UI self.ui_show_main() res = self.ui_main_loop() self.backend().shutdown() return res def list(self): '''Print a list of available handlers and their status to stdout.''' for h_id in self.backend().available(self.argv_options.mode): i = self.backend().handler_info(h_id) print '%s - %s (%s, %s, %s)%s' % ( h_id, self._(i['name']), bool(i['free']) and self.string_free or self.string_restricted, bool(i['enabled']) and self.string_enabled or self.string_disabled, bool(i['used']) and self.string_in_use or self.string_not_in_use, bool(i['auto_install']) and ' [auto-install]' or '') def list_hwids(self): '''Print a list of available handlers and their status to stdout.''' for h_id in self.backend().get_hardware(): print h_id def check(self): '''Notify the user about newly used or available drivers since last check(). Return True if any new driver is available which is not yet enabled. ''' # if the user is running Jockey with package installation or another # long-running task in parallel, the automatic --check invocation will # time out on this. try: convert_dbus_exceptions(self.backend) except Exception as e: print >> sys.stderr, 'Cannot connect to backend, is it busy?\n', e return False try: (new_used, new_avail) = convert_dbus_exceptions( self.backend().new_used_available, self.argv_options.mode) except PermissionDeniedByPolicy: self.error_msg(self.string_unprivileged) return False # any new restricted drivers? also throw out the non-announced ones restricted_available = False for h_id in set(new_avail): # create copy info = self.backend().handler_info(h_id) if not bool(info['announce']): new_avail.remove(h_id) continue if not bool(info['free']): restricted_available = True break # throw out newly used free drivers; no need for education here for h_id in new_used + []: # create copy for iteration if bool(self.backend().handler_info(h_id)['free']): new_used.remove(h_id) notified = False # launch notifications if anything remains if new_avail or new_used: # defer UI initialization until here, since --check should not # spawn a progress dialog for searching drivers self.ui_init() self.have_ui = True if new_avail: if restricted_available: self.ui_notification(self._('Restricted drivers available'), self._('In order to use your hardware more efficiently, you' ' can enable drivers which are not free software.')) else: self.ui_notification(self._('New drivers available'), self._('There are new or updated drivers available for ' 'your hardware.')) notified = True elif new_used: self.ui_notification(self._('New restricted drivers in use'), # %(os)s stands for the OS name. Prefix it or suffix it, # but do not replace it. self._('In order for this computer to function properly, %(os)s is ' 'using driver software that cannot be supported by %(os)s.') % {'os': OSLib.inst.os_vendor}) notified = True if notified: # we need to stay in the main loop so that the tray icon stays # around self.ui_main_loop() self.backend().shutdown() return len(new_avail) > 0 def check_composite(self): '''Check for a composite-enabling X.org driver. If one is available and not installed, offer to install it and return True if installation succeeded. Otherwise return False. ''' h_id = self.backend().check_composite() if h_id: self.set_handler_enable(h_id, 'enable', self.argv_options.confirm) return bool(self.backend().handler_info(h_id)['enabled']) self.error_msg(self._('There is no available graphics driver for your system which supports the composite extension, or the current one already supports it.')) return False def _install_progress_handler(self, phase, cur, total): if not self._install_progress_shown: self.ui_progress_start(self._('Additional Drivers'), self._('Downloading and installing driver...'), total) self._install_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def _remove_progress_handler(self, cur, total): if not self._install_progress_shown: self.ui_progress_start(self._('Additional Drivers'), self._('Removing driver...'), total) self._install_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def _repository_progress_handler(self, cur, total): if not self._repository_progress_shown: self.ui_progress_start(self._('Additional Drivers'), self._('Downloading and updating package indexes...'), total) self._repository_progress_shown = True self.ui_progress_update(cur, total) self.ui_idle() def set_handler_enable(self, handler_id, action, confirm, gui=True): '''Enable, disable, or toggle a handler. action can be 'enable', 'disable', or 'toggle'. If confirm is True, this first presents a confirmation dialog. Then a progress dialog is presented for installation/removal of the handler. If gui is True, error messags and install progress will be shown in the GUI, otherwise just printed to stderr (CLI mode). Return True if anything was changed and thus the UI needs to be refreshed. ''' try: i = convert_dbus_exceptions(self.backend().handler_info, handler_id) except UnknownHandlerException: self.error_msg('%s: %s' % (self.string_unknown_driver, handler_id)) self.error_msg(self._('Use --list to see available drivers')) return False # determine new status if action == 'enable': enable = True elif action == 'disable': enable = False elif action == 'toggle': enable = not bool(i['enabled']) else: raise ValueError('invalid action %s; allowed are enable, disable, toggle') # check if we can change at all if 'can_change' in i: msg = i['can_change'] if gui: self.error_message(self._('Cannot change driver'), self._(msg)) else: self.error_msg(self._(msg)) return False # actually something to change? if enable == bool(i['enabled']): return False if confirm: # construct and ask confirmation question if enable: title = self._('Enable driver?') action = self.string_button_enable else: title = self._('Disable driver?') action = self.string_button_disable n = i['name'] # self._(i['name']) is misinterpreted by xgettext if not self.confirm_action(title, self._(n), self._get_description_rationale_text(i), action): return False # go try: if gui: try: self._install_progress_shown = False convert_dbus_exceptions(dbus_sync_call_signal_wrapper, self.backend(), 'set_enabled', {'install_progress': self._install_progress_handler, 'remove_progress': self._remove_progress_handler}, handler_id, enable) finally: if self._install_progress_shown: self.ui_progress_finish() else: convert_dbus_exceptions(dbus_sync_call_signal_wrapper, self.backend(), 'set_enabled', {}, handler_id, enable) except PermissionDeniedByPolicy: self.error_message('', self.string_unprivileged) return False except BackendCrashError: self._dbus_iface = None self.error_message('', '%s\n\n https://launchpad.net/jockey/+filebug\n\n%s' % ( self._('Sorry, the Jockey backend crashed. Please file a bug at:'), self._('Trying to recover by restarting backend.'))) return False except SystemError as e: self.error_message('', str(e).strip().splitlines()[-1]) return False newstate = bool(self.backend().handler_info(handler_id)['enabled']) if enable and not newstate: self.error_message('', '%s\n\n%s: /var/log/jockey.log' % ( self._('Sorry, installation of this driver failed.'), self._('Please have a look at the log file for details'))) return i['enabled'] != newstate def _get_description_rationale_text(self, h_info): d = h_info.get('description', '') r = h_info.get('rationale', '') # opportunistic translation (shipped example drivers have translations) if d: d = self._(d) if r: r = self._(r) if d and r: return d.strip() + '\n\n' + r elif d: return d elif r: return r else: return '' def download_url(self, url, filename=None, data=None): '''Download an URL into a local file, and display a progress dialog. If filename is not given, a temporary file will be created. Additional POST data can be submitted for HTTP requests in the data argument (see urllib2.urlopen). Return (filename, headers) tuple, or (None, headers) if the user cancelled the download. ''' block_size = 8192 current_size = 0 try: f = urllib2.urlopen(url) except Exception as e: self.error_message(self._('Download error'), str(e)) return (None, None) headers = f.info() if 'Content-Length' in headers: total_size = int(headers['Content-Length']) else: total_size = -1 self.ui_progress_start(self.string_download_progress_title, url, total_size) if filename: tfp = open(filename, 'wb') result_filename = filename else: (fd, result_filename) = tempfile.mkstemp() tfp = os.fdopen(fd, 'wb') try: while current_size < total_size: block = f.read(block_size) tfp.write (block) current_size += len(block) # if True, user canceled download if self.ui_progress_update(current_size, total_size): # if we created a temporary file, clean it up if not filename: os.unlink(result_filename) result_filename = None break finally: tfp.close() f.close() self.ui_progress_finish() return (result_filename, headers) @classmethod def error_msg(klass, msg): '''Print msg to stderr, and intercept IOErrors.''' try: print >> sys.stderr, msg except IOError: pass def _call_progress_dialog(self, message, fn, *args, **kwargs): '''Call fn(*args, **kwargs) while showing a progress dialog.''' if self.argv_options.no_dbus: try: del kwargs['timeout'] except KeyError: pass if not self.have_ui: return fn(*args, **kwargs) progress_shown = False t_fn = threading.Thread(None, fn, 'thread_call_progress_dialog', args, kwargs) t_fn.start() while True: t_fn.join(0.2) if not t_fn.isAlive(): break if not progress_shown: progress_shown = True self.ui_progress_start(self._('Additional Drivers'), message, -1) if self.ui_progress_update(-1, -1): sys.exit(1) # cancel self.ui_idle() if progress_shown: self.ui_progress_finish() self.ui_idle() def get_displayed_handlers(self): '''Return the list of displayed handler IDs. This can either be a list of drivers which match your system, or which match a search_driver() invocation. ''' if self.current_search[0]: return self.current_search[1] else: return self.backend().available(self.argv_options.mode) def hwid_to_display_string(self, hwid): '''Convert a type:value hardware ID string to a human friendly text.''' try: (type, value) = hwid.split(':', 1) except ValueError: return hwid if type == 'printer_deviceid': try: import cupshelpers except ImportError: return hwid info = cupshelpers.parseDeviceID(value) return info['MFG'] + ' ' + info['MDL'] return hwid def _check_repositories(self): '''Check if we have package repositories, and if not, offer to update.''' if self._dbus_iface.has_repositories(): return if self.have_ui: success = False try: self._repository_progress_shown = False success = convert_dbus_exceptions(dbus_sync_call_signal_wrapper, self._dbus_iface, 'update_repository_indexes', {'repository_update_progress': self._repository_progress_handler}) finally: if self._repository_progress_shown: self.ui_progress_finish() # check success if not success: self.error_message('', self._( 'Downloading package indexes failed, please check your network status. ' 'Most drivers will not be available.')) else: # This happens when running in --check mode. We do not particularly # care about success here. convert_dbus_exceptions(self._dbus_iface.update_repository_indexes) # # Session D-BUS server methods # DBUS_INTERFACE_NAME = 'com.ubuntu.DeviceDriver' def dbus_server(self): '''Run session D-BUS server backend.''' dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() dbus_name = dbus.service.BusName(DBUS_BUS_NAME, bus) dbus.service.Object.__init__(self, bus, '/GUI') from gi.repository import GLib self.dbus_server_main_loop = GLib.MainLoop() self.dbus_server_main_loop.run() @classmethod def get_dbus_client(klass): '''Return a dbus.Interface object for the server.''' obj = dbus.SessionBus().get_object(DBUS_BUS_NAME, '/GUI') return dbus.Interface(obj, AbstractUI.DBUS_INTERFACE_NAME) @dbus.service.method(DBUS_INTERFACE_NAME, in_signature='s', out_signature='bas', sender_keyword='sender', connection_keyword='conn') def search_driver(self, hwid, sender=None, conn=None): '''Search configured driver DBs for a particular hardware component. The hardware component is described as HardwareID type and value, separated by a colon. E. g. "modalias:pci:12345" or "printer_deviceid:MFG:FooTech;MDL:X-12;CMD:GDI". This searches the enabled driver databases for a matching driver. If it finds one, it offers it to the user. This returns a pair (success, files); where 'success' is True if a driver was found, acknowledged by the user, and installed, otherwise False; "files" is the list of files shipped by the newly installed packages (useful for e. g. printer drivers to get a list of PPDs to check). ''' self.ui_init() # we want to show progress self.have_ui = True self.search_only = False # Note: This could be set to True if we know that we only look for # remote drivers. E. g. if you don't support local printer driver # handlers, you could do: #if hwid.startswith('printer_deviceid:'): # self.search_only = True b = self.backend() def _srch(): # TODO: this is a hack: when calling through D-BUS, specify a # timeout, when calling a local object, the timeout parameter does # not exist if hasattr(b, '_locations'): drivers = self._dbus_iface.search_driver(hwid, timeout=600) else: drivers = b.search_driver(hwid) self.current_search = (hwid, drivers) self._call_progress_dialog(self._( 'Searching driver for %s...') % self.hwid_to_display_string(hwid), _srch) result = False files = [] if self.current_search[1]: self.ui_show_main() self.ui_main_loop() for d in self.current_search[1]: info = self.backend().handler_info(d) if bool(info['enabled']) and bool(info['changed']): result = True if 'package' in info: files += self.backend().handler_files(d) # we are D-BUS activated, so let's free resources early if self.dbus_server_main_loop: self.dbus_server_main_loop.quit() # in case we do another operation after that, we need to reinitialize # the backend if self.search_only: self.search_only = False self._dbus_iface = None return (result, files) # # The following methods must be implemented in subclasses # def convert_keybindings(self, str): '''Convert keyboard accelerators to the particular UI's format. The abstract UI and drivers use the '_' prefix to mark a keyboard accelerator. A double underscore ('__') is converted to a real '_'.''' raise NotImplementedError('subclasses need to implement this') def ui_init(self): '''Initialize UI. This should load the GUI components, such as GtkBuilder files, but not show the main window yet; that is done by ui_show_main(). ''' raise NotImplementedError('subclasses need to implement this') def ui_show_main(self): '''Show main window. This should set up presentation of handlers and show the main window. This must be called after ui_init(). ''' raise NotImplementedError('subclasses need to implement this') def ui_main_loop(self): '''Main loop for the user interface. This should return if the user wants to quit the program, and return the exit code. ''' raise NotImplementedError('subclasses need to implement this') def error_message(self, title, text): '''Present an error message box.''' raise NotImplementedError('subclasses need to implement this') def confirm_action(self, title, text, subtext=None, action=None): '''Present a confirmation dialog. If action is given, it is used as button label instead of the default 'OK'. Return True if the user confirms, False otherwise. ''' raise NotImplementedError('subclasses need to implement this') def ui_notification(self, title, text): '''Present a notification popup. This should preferably create a tray icon. Clicking on the tray icon or notification should run the GUI. This method will attempt to instantiate an appindicator to return to both the GTK and KDE children. If whatever reason it fails (missing python-appindicator) then it should behave as it did before. ''' try: indicator = AppIndicator.Indicator.new('jockey', 'jockey', AppIndicator.IndicatorCategory.HARDWARE) indicator.set_icon_full('jockey', self._('Restricted drivers available')) except Exception as e: raise NotImplementedError('appindicator support not available: %s' \ '\nsubclasses need to implement this' % str(e)) indicator.set_status(AppIndicator.IndicatorStatus.ATTENTION) return indicator def ui_idle(self): '''Process pending UI events and return. This is called while waiting for external processes such as package installers. ''' raise NotImplementedError('subclasses need to implement this') def ui_progress_start(self, title, description, total): '''Create a progress dialog.''' raise NotImplementedError('subclasses need to implement this') def ui_progress_update(self, current, total): '''Update status of current progress dialog. current/total specify the number of steps done and total steps to do, or -1 if it cannot be determined. In this case the dialog should display an indeterminated progress bar (bouncing back and forth). This should return True to cancel, and False otherwise. ''' raise NotImplementedError('subclasses need to implement this') def ui_progress_finish(self): '''Close the current progress dialog.''' raise NotImplementedError('subclasses need to implement this')
def __init__(self, src=None, alg_name='multi_tri', multi_pipe=None, serial_pipe=None, repeat_log=False): self.PACKET_PROCESSORS = { "Range Packet": self.process_range, "Stats Packet": self.process_stats } # Communication with engineering display self.multi_pipe = multi_pipe self.kill = False self.log_file_name = None self.repeat_log = repeat_log # Load from file if specified, otherwise serial if src: self.src_input = src self.src = open(src) self.log_file = None self.playback_pipe = serial_pipe else: self.repeat_log = False try: self.src = serial.Serial(config.SERIAL_PORT, config.SERIAL_BAUD) self.log_file_name = "log-{}.log".format( datetime.now().strftime("%Y%m%d-%H%M%S")) self.log_file = open(self.log_file_name, 'w') # Thread for piping stdin to the serial port (for manually typing commands) serial_sender = SerialSender(output_pipe=self.src, multi_pipe=serial_pipe) self.playback_pipe = None serial_sender.start() except serial.serialutil.SerialException as e: self.kill = True print(e) if self.multi_pipe is not None: self.multi_pipe.send({'cmd': 'error', 'type': 'no_serial'}) return # Load algorithm alg_module = importlib.import_module('algorithms.' + alg_name + '.' + alg_name) self.algorithm = getattr(alg_module, alg_name) # Connect to backend self.backend = Backend(Main.ANCHORED_BASE, Main.CALCULATED_BASE) if self.multi_pipe: for node_id, node in Main.r_nodes.items(): node.set_pipe(self.multi_pipe) self.name_arr = [] self.history = {} for key, value in Main.r_nodes.items(): val = int(key) for i in range(val + 1, len(Main.r_nodes)): self.name_arr.append(f"{val}-{i}") for name in self.name_arr: if Main.AUTO_SETUP_BASE is True and name == Main.auto_base_meas_key: self.history[name] = MeasHistory(name, max_meas=100, min_vals=5) else: self.history[name] = MeasHistory(name) self.node_list = Main.r_nodes
def __init__(self, backend_config): Backend.__init__(self, backend_config) self.logger = None self.slurm_driver = """
cv2.imshow("Preview", frame) cv2.waitKey(1) return (student_name, student_id) # cv2.imshow("retarget", retarget_img) text_location = cv2.boundingRect(big_contour)[0:2] reading_aid_msg = f"Bring Card Closer ... {round(frame_occupation_percentage / frame_occupation_threshold, 2) * 100}%" if frame_occupation_percentage >= frame_occupation_threshold: reading_aid_msg = "Keep Still ..." cv2.drawContours(frame, [box], 0, (0, 255, 0), 3) cv2.putText(frame, reading_aid_msg, (text_location[0], text_location[1]), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 0), 1, cv2.LINE_AA) else: cv2.drawContours(frame, [box], 0, (0, 0, 255), 3) cv2.putText(frame, reading_aid_msg, (text_location[0], text_location[1]), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 255), 1, cv2.LINE_AA) cv2.putText(frame, "Face Student ID Towards The Camera.", (10, 50), cv2.FONT_HERSHEY_PLAIN, 1.2, (255, 0, 0), 1, cv2.LINE_AA) cv2.imshow("Preview", frame) cv2.waitKey(1) server = Backend(get_card_info)
class Ui_MainWindow(object): def setupUi(self, MainWindow): self.BE = Backend() MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/logo/Logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_3 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.label_9 = QtGui.QLabel(self.centralwidget) self.label_9.setObjectName(_fromUtf8("label_9")) self.verticalLayout.addWidget(self.label_9) self.horizontalLayout_5 = QtGui.QHBoxLayout() self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.label = QtGui.QLabel(self.centralwidget) self.label.setObjectName(_fromUtf8("label")) self.horizontalLayout.addWidget(self.label) self.label_2 = QtGui.QLabel(self.centralwidget) self.label_2.setObjectName(_fromUtf8("label_2")) self.horizontalLayout.addWidget(self.label_2) self.horizontalLayout_5.addLayout(self.horizontalLayout) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.label_7 = QtGui.QLabel(self.centralwidget) self.label_7.setObjectName(_fromUtf8("label_7")) self.horizontalLayout_4.addWidget(self.label_7) self.label_8 = QtGui.QLabel(self.centralwidget) self.label_8.setObjectName(_fromUtf8("label_8")) self.horizontalLayout_4.addWidget(self.label_8) self.horizontalLayout_5.addLayout(self.horizontalLayout_4) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout_2.addWidget(self.label_3) self.label_4 = QtGui.QLabel(self.centralwidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.horizontalLayout_2.addWidget(self.label_4) self.horizontalLayout_5.addLayout(self.horizontalLayout_2) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.label_5 = QtGui.QLabel(self.centralwidget) self.label_5.setObjectName(_fromUtf8("label_5")) self.horizontalLayout_3.addWidget(self.label_5) self.label_6 = QtGui.QLabel(self.centralwidget) self.label_6.setObjectName(_fromUtf8("label_6")) self.horizontalLayout_3.addWidget(self.label_6) self.horizontalLayout_5.addLayout(self.horizontalLayout_3) self.verticalLayout.addLayout(self.horizontalLayout_5) self.gridLayout_3.addLayout(self.verticalLayout, 0, 0, 1, 2) self.horizontalLayout_6 = QtGui.QHBoxLayout() self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.label_10 = QtGui.QLabel(self.centralwidget) self.label_10.setObjectName(_fromUtf8("label_10")) self.horizontalLayout_6.addWidget(self.label_10) self.label_11 = QtGui.QLabel(self.centralwidget) self.label_11.setObjectName(_fromUtf8("label_11")) self.horizontalLayout_6.addWidget(self.label_11) self.gridLayout_3.addLayout(self.horizontalLayout_6, 1, 0, 1, 1) self.horizontalLayout_7 = QtGui.QHBoxLayout() self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.label_12 = QtGui.QLabel(self.centralwidget) self.label_12.setObjectName(_fromUtf8("label_12")) self.horizontalLayout_7.addWidget(self.label_12) self.label_13 = QtGui.QLabel(self.centralwidget) self.label_13.setObjectName(_fromUtf8("label_13")) self.horizontalLayout_7.addWidget(self.label_13) self.gridLayout_3.addLayout(self.horizontalLayout_7, 1, 1, 1, 1) self.horizontalLayout_11 = QtGui.QHBoxLayout() self.horizontalLayout_11.setObjectName( _fromUtf8("horizontalLayout_11")) self.frame = QtGui.QFrame(self.centralwidget) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setObjectName(_fromUtf8("frame")) self.gridLayout = QtGui.QGridLayout(self.frame) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.horizontalLayout_8 = QtGui.QHBoxLayout() self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.radioButton = QtGui.QRadioButton(self.frame) self.radioButton.setObjectName(_fromUtf8("radioButton")) self.horizontalLayout_8.addWidget(self.radioButton) self.radioButton_2 = QtGui.QRadioButton(self.frame) self.radioButton_2.setObjectName(_fromUtf8("radioButton_2")) self.horizontalLayout_8.addWidget(self.radioButton_2) self.radioButton_3 = QtGui.QRadioButton(self.frame) self.radioButton_3.setObjectName(_fromUtf8("radioButton_3")) self.horizontalLayout_8.addWidget(self.radioButton_3) self.radioButton_4 = QtGui.QRadioButton(self.frame) self.radioButton_4.setObjectName(_fromUtf8("radioButton_4")) self.radioButton.setChecked(True) self.horizontalLayout_8.addWidget(self.radioButton_4) self.verticalLayout_2.addLayout(self.horizontalLayout_8) self.listView = QtGui.QListView(self.frame) self.listView.setObjectName(_fromUtf8("listView")) self.verticalLayout_2.addWidget(self.listView) self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1) self.horizontalLayout_11.addWidget(self.frame) self.label_16 = QtGui.QLabel(self.centralwidget) self.label_16.setObjectName(_fromUtf8("label_16")) self.horizontalLayout_11.addWidget(self.label_16) self.frame_2 = QtGui.QFrame(self.centralwidget) self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtGui.QFrame.Raised) self.frame_2.setObjectName(_fromUtf8("frame_2")) self.gridLayout_2 = QtGui.QGridLayout(self.frame_2) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.horizontalLayout_10 = QtGui.QHBoxLayout() self.horizontalLayout_10.setObjectName( _fromUtf8("horizontalLayout_10")) self.label_14 = QtGui.QLabel(self.frame_2) self.label_14.setObjectName(_fromUtf8("label_14")) self.horizontalLayout_10.addWidget(self.label_14) self.label_15 = QtGui.QLabel(self.frame_2) self.label_15.setObjectName(_fromUtf8("label_15")) self.horizontalLayout_10.addWidget(self.label_15) self.verticalLayout_3.addLayout(self.horizontalLayout_10) self.horizontalLayout_9 = QtGui.QHBoxLayout() self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9")) spacerItem = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Minimum) self.horizontalLayout_9.addItem(spacerItem) self.listView_2 = QtGui.QListView(self.frame_2) self.listView_2.setObjectName(_fromUtf8("listView_2")) self.horizontalLayout_9.addWidget(self.listView_2) self.verticalLayout_3.addLayout(self.horizontalLayout_9) self.gridLayout_2.addLayout(self.verticalLayout_3, 0, 0, 1, 1) self.horizontalLayout_11.addWidget(self.frame_2) self.gridLayout_3.addLayout(self.horizontalLayout_11, 2, 0, 1, 2) self.label.raise_() self.label_2.raise_() self.label_3.raise_() self.label_4.raise_() self.label_5.raise_() self.label_6.raise_() self.label_7.raise_() self.label_8.raise_() self.label_9.raise_() self.label_10.raise_() self.label_11.raise_() self.label_12.raise_() self.label_13.raise_() self.label_10.raise_() self.totalPoints = 1000 self.frame.raise_() self.frame_2.raise_() self.label_16.raise_() MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.formation = [] self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuManage_Teams = QtGui.QMenu(self.menubar) self.menuManage_Teams.setObjectName(_fromUtf8("menuManage_Teams")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.actionNEW_TEam = QtGui.QAction(MainWindow) self.actionNEW_TEam.setObjectName(_fromUtf8("actionNEW_TEam")) self.actionOPEN_Team = QtGui.QAction(MainWindow) self.actionOPEN_Team.setObjectName(_fromUtf8("actionOPEN_Team")) self.actionSAVE_Team = QtGui.QAction(MainWindow) self.actionSAVE_Team.setObjectName(_fromUtf8("actionSAVE_Team")) self.actionEVALUATE_Team = QtGui.QAction(MainWindow) self.actionEVALUATE_Team.setObjectName( _fromUtf8("actionEVALUATE_Team")) self.menuManage_Teams.addAction(self.actionNEW_TEam) self.menuManage_Teams.addAction(self.actionOPEN_Team) self.menuManage_Teams.addAction(self.actionSAVE_Team) self.menuManage_Teams.addAction(self.actionEVALUATE_Team) self.menubar.addAction(self.menuManage_Teams.menuAction()) self.selectedPlayers = [] self.pointList = {} self.selectedPlayerModel = QtGui.QStandardItemModel() self.PlayerModel = QtGui.QStandardItemModel() self.listView_2.setModel(self.selectedPlayerModel) self.listView.setModel(self.PlayerModel) self.retranslateUi(MainWindow) self.radioButton.clicked.connect(self.BATClicked) self.radioButton_2.clicked.connect(self.BOWClicked) self.radioButton_3.clicked.connect(self.ARClicked) self.radioButton_4.clicked.connect(self.WKClicked) self.listView.doubleClicked.connect(self.selectPlayer) self.listView_2.doubleClicked.connect(self.removePlayer) self.actionNEW_TEam.activated.connect(self.newTeamActivated) self.actionOPEN_Team.activated.connect(self.openDialog) self.actionSAVE_Team.activated.connect(self.save) self.actionEVALUATE_Team.activated.connect(self.evaluate) QtCore.QMetaObject.connectSlotsByName(MainWindow) def openDialog(self): d = OpenDialog() d.exec_() tn = d.getTeamName() if not tn or len(tn) == 0: return self.load(tn) def load(self, teamName): d = {} data = self.BE.getData(teamName) d['PLAYERS'] = data['PLAYERS'] d['NAME'] = teamName self.totalPoints = 1000 self.pointList = {} for i in data['SELECTED_PLAYERS']: try: d[i['ctg']] += 1 except KeyError: d[i['ctg']] = 1 self.pointList[i['player']] = i['scored'] self.totalPoints -= int(i['scored']) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) self.newTeamActivated(d) self.selectedPlayers = data['SELECTED_PLAYERS'] self.selectedPlayerModel = QtGui.QStandardItemModel() for i in self.selectedPlayers: self.selectedPlayerModel.appendRow( QtGui.QStandardItem(str(i['player']))) self.listView_2.setModel(self.selectedPlayerModel) def evaluate(self): d = LaunchEval() d.exec_() def WKClicked(self): if 'WK' not in self.players: return self.PlayerModel = QtGui.QStandardItemModel() for i in self.players['WK']: item = QtGui.QStandardItem(i) self.PlayerModel.appendRow(item) self.listView.setModel(self.PlayerModel) self.cv = 'WK' def ARClicked(self): if 'AR' not in self.players: return self.PlayerModel = QtGui.QStandardItemModel() for i in self.players['AR']: item = QtGui.QStandardItem(i) self.PlayerModel.appendRow(item) self.listView.setModel(self.PlayerModel) self.cv = 'AR' def save(self): ht = {'AR': False, 'WK': False, 'BAT': False, 'BWL': False} if len(self.selectedPlayers) < 11: return Notify("Warning", "You need to have a team of atleast 11 players", QtGui.QMessageBox.Critical) for i in self.selectedPlayers: ht[i['ctg']] = True final = True for i in ht: final = final and ht[i] if not final: return Notify( "Warning", "You need to have atleast one player from each group", QtGui.QMessageBox.Critical) d = SaveDialog() d.exec_() text = d.getName() if len(text) == 0: return pl = [] if text: for i in self.selectedPlayers: pl.append(i['player']) rc = self.BE.saveTeam(text, pl) if rc: Notify("Error", "Error Saving!", QtGui.QMessageBox.Critical) else: Notify("Saved", "Saved!", QtGui.QMessageBox.Information) self.label_15.setText(text) def BOWClicked(self): if 'BWL' not in self.players: return self.PlayerModel = QtGui.QStandardItemModel() for i in self.players['BWL']: item = QtGui.QStandardItem(i) self.PlayerModel.appendRow(item) self.listView.setModel(self.PlayerModel) self.cv = 'BOW' def BATClicked(self): self.PlayerModel = QtGui.QStandardItemModel() if 'BAT' not in self.players: return for i in self.players['BAT']: item = QtGui.QStandardItem(i) self.PlayerModel.appendRow(item) self.listView.setModel(self.PlayerModel) self.cv = 'BAT' def removePlayer(self, index): if len(self.selectedPlayers) > 0: index = index.row() ctg = self.selectedPlayers[index]['ctg'] for i in self.selectedPlayerModel.findItems( self.selectedPlayers[index]['player']): self.selectedPlayerModel.removeRow(i.row()) if ctg == 'AR': txt = int(self.label_6.text()) self.label_6.setText(str(txt - 1)) if ctg == 'WK': txt = int(self.label_8.text()) self.label_8.setText(str(txt - 1)) if ctg == 'BAT': txt = int(self.label_2.text()) self.label_2.setText(str(txt - 1)) if ctg == 'BWL': txt = int(self.label_4.text()) self.label_4.setText(str(txt - 1)) player = self.selectedPlayers.pop(index)['player'] self.players[ctg].append(player) self.totalPoints += int(self.pointList[player]) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) eval("self." + self.cv + "Clicked()") def selectPlayer(self, index): index = index.row() ctg = 'BWL' if self.cv == 'BOW' else self.cv c = 0 txt = self.players[ctg][index] for i in self.selectedPlayers: if i['ctg'] == ctg: c += 1 currentPlayer = '' if ctg == 'AR': self.label_6.setText(str(c + 1)) self.selectedPlayerModel.appendRow(QtGui.QStandardItem(txt)) currentPlayer = self.players[ctg].pop(index) self.selectedPlayers.append({'player': currentPlayer, 'ctg': ctg}) self.totalPoints -= int(self.pointList[currentPlayer]) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) eval("self." + self.cv + "Clicked()") return elif ctg == 'WK': if c < 1: currentPlayer = self.players[ctg].pop(index) self.selectedPlayers.append({ 'player': currentPlayer, 'ctg': ctg }) self.totalPoints -= int(self.pointList[currentPlayer]) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) self.label_8.setText(str(c + 1)) self.selectedPlayerModel.appendRow(QtGui.QStandardItem(txt)) eval("self." + self.cv + "Clicked()") return elif ctg == 'BAT': currentPlayer = self.players[ctg].pop(index) self.selectedPlayers.append({'player': currentPlayer, 'ctg': ctg}) self.totalPoints -= int(self.pointList[currentPlayer]) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) self.label_2.setText(str(c + 1)) self.selectedPlayerModel.appendRow(QtGui.QStandardItem(txt)) eval("self." + self.cv + "Clicked()") return elif ctg == 'BWL': if c < 3: currentPlayer = self.players[ctg].pop(index) self.selectedPlayers.append({ 'player': currentPlayer, 'ctg': ctg }) self.totalPoints -= int(self.pointList[currentPlayer]) self.label_11.setText(str(self.totalPoints)) self.label_13.setText(str(1000 - self.totalPoints)) self.label_4.setText(str(c + 1)) self.selectedPlayerModel.appendRow(QtGui.QStandardItem(txt)) eval("self." + self.cv + "Clicked()") return Notify( "Warning", "You can't select more than " + self.translate(c) + " " + self.decode(ctg), QtGui.QMessageBox.Critical) def translate(self, c): if c == 1: return "one" if c == 2: return "two" if c == 3: return "three" if c == 4: return "four" def decode(self, ctg): if ctg == 'AR': return "All Rounders" if ctg == 'WK': return "Wicket Keeper" if ctg == "BWL": return "Bowlers" if ctg == "BAT": return "Batsmen" def newTeamActivated(self, team=None): self.players = {} if not team: players = self.BE.newTeam() else: self.players['BWL'] = [] self.players['BAT'] = [] self.players['WK'] = [] self.players['AR'] = [] players = team['PLAYERS'] if not team: self.label_2.setText("0") self.label_4.setText("0") self.label_6.setText("0") self.label_8.setText("0") self.label_11.setText("1000") self.label_13.setText("0") self.label_15.setText("*Untitled") else: self.label_2.setText("0" if 'BAT' not in team.keys() else str(team['BAT'])) self.label_4.setText("0" if 'BWL' not in team.keys() else str(team['BWL'])) self.label_6.setText("0" if 'AR' not in team.keys() else str(team['AR'])) self.label_8.setText("0" if 'WKT' not in team.keys() else str(team['WKT'])) self.label_15.setText(team['NAME']) for p in players: item = QtGui.QStandardItem(p['player']) self.pointList[p['player']] = int(p['scored']) try: self.players[p['ctg']].append(p['player']) except: self.players[p['ctg']] = [p['player']] self.BATClicked() self.selectedPlayerModel = QtGui.QStandardItemModel() self.listView_2.setModel(self.selectedPlayerModel) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Cricket", None)) self.label_9.setText(_translate("MainWindow", "Your Selections", None)) self.label.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Batsman (BAT)</span></p></body></html>", None)) self.label_2.setText(_translate("MainWindow", "##", None)) self.label_7.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Wicket-Keeper (WK)</span></p></body></html>", None)) self.label_8.setText(_translate("MainWindow", "##", None)) self.label_3.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Bowler (BOW)</span></p></body></html>", None)) self.label_4.setText(_translate("MainWindow", "##", None)) self.label_5.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Allrounders (AR)</span></p></body></html>", None)) self.label_6.setText(_translate("MainWindow", "##", None)) self.label_10.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Points Available</span></p></body></html>", None)) self.label_11.setText(_translate("MainWindow", "####", None)) self.label_12.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Points Used</span></p></body></html>", None)) self.label_13.setText(_translate("MainWindow", "####", None)) self.radioButton.setText(_translate("MainWindow", "BAT", None)) self.radioButton_2.setText(_translate("MainWindow", "BOW", None)) self.radioButton_3.setText(_translate("MainWindow", "AR", None)) self.radioButton_4.setText(_translate("MainWindow", "WK", None)) self.label_16.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-size:28pt;\">></span></p></body></html>", None)) self.label_14.setText( _translate( "MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">Team Name</span></p></body></html>", None)) self.label_15.setText(_translate("MainWindow", "Displayed Here", None)) self.menuManage_Teams.setTitle( _translate("MainWindow", "Manage Teams", None)) self.actionNEW_TEam.setText(_translate("MainWindow", "NEW Team", None)) self.actionNEW_TEam.setToolTip( _translate("MainWindow", "Create New Team", None)) self.actionOPEN_Team.setText( _translate("MainWindow", "OPEN Team", None)) self.actionOPEN_Team.setToolTip( _translate("MainWindow", "Open an Existing Team", None)) self.actionSAVE_Team.setText( _translate("MainWindow", "SAVE Team", None)) self.actionSAVE_Team.setToolTip( _translate("MainWindow", "Save your Team", None)) self.actionEVALUATE_Team.setText( _translate("MainWindow", "EVALUATE Team", None)) self.actionEVALUATE_Team.setToolTip( _translate("MainWindow", "Evaluate Team Performance", None))
class Main: def __init__(self, src=None, alg_name='multi_tri', multi_pipe=None, serial_pipe=None, repeat_log=False): self.PACKET_PROCESSORS = { "Range Packet": self.process_range, "Stats Packet": self.process_stats } # Communication with engineering display self.multi_pipe = multi_pipe self.kill = False self.log_file_name = None self.repeat_log = repeat_log # Load from file if specified, otherwise serial if src: self.src_input = src self.src = open(src) self.log_file = None self.playback_pipe = serial_pipe else: self.repeat_log = False try: self.src = serial.Serial(config.SERIAL_PORT, config.SERIAL_BAUD) self.log_file_name = "log-{}.log".format( datetime.now().strftime("%Y%m%d-%H%M%S")) self.log_file = open(self.log_file_name, 'w') # Thread for piping stdin to the serial port (for manually typing commands) serial_sender = SerialSender(output_pipe=self.src, multi_pipe=serial_pipe) self.playback_pipe = None serial_sender.start() except serial.serialutil.SerialException as e: self.kill = True print(e) if self.multi_pipe is not None: self.multi_pipe.send({'cmd': 'error', 'type': 'no_serial'}) return # Load algorithm alg_module = importlib.import_module('algorithms.' + alg_name + '.' + alg_name) self.algorithm = getattr(alg_module, alg_name) # Connect to backend self.backend = Backend(Main.ANCHORED_BASE, Main.CALCULATED_BASE) if self.multi_pipe: for node_id, node in Main.r_nodes.items(): node.set_pipe(self.multi_pipe) self.name_arr = [] self.history = {} for key, value in Main.r_nodes.items(): val = int(key) for i in range(val + 1, len(Main.r_nodes)): self.name_arr.append(f"{val}-{i}") for name in self.name_arr: if Main.AUTO_SETUP_BASE is True and name == Main.auto_base_meas_key: self.history[name] = MeasHistory(name, max_meas=100, min_vals=5) else: self.history[name] = MeasHistory(name) self.node_list = Main.r_nodes def run(self): if self.kill: return self.multi_pipe.send("Hey, @realMainThread here. I’m alive." ) if self.multi_pipe else None # Clear out the backend of stale data self.backend.clear_nodes() line_ctr = 0 packet_ctr = 0 start_time = time.time() paused = True do = True self.pause_time = 0 while do or self.repeat_log is True: self.src.readline() # discard first (possibly incomplete) line for line in self.src: if self.playback_pipe is not None: while do or paused is True: do = False msg = None if paused: msg = self.playback_pipe.recv() elif self.playback_pipe.poll(): msg = self.playback_pipe.recv() if msg is not None and type( msg) == dict and "cmd" in msg: if msg['cmd'] == "play": paused = False elif msg['cmd'] == "pause": paused = True elif msg['cmd'] == "set_speed" and 'speed' in msg: if float(msg['speed']) == 0: self.pause_time = 0 else: self.pause_time = 1 / float(msg['speed']) do = True try: # Try to decode 'bytes' from serial line = line.decode("utf-8") except AttributeError: # Probably already a 'str' from file pass # Write log, flush to make sure we got it down if self.log_file: self.log_file.write(line) self.log_file.flush() tmp = line.strip().split("|") line_ctr += 1 # Make sure we have a valid packet if len(tmp) != 2: continue # Check packet type packet_type = tmp[0].strip() if packet_type not in self.PACKET_PROCESSORS.keys(): continue packet_ctr += 1 # Clean up packet contents packet_contents = tmp[1].strip().split(',') for i in range(len(packet_contents)): packet_contents[i] = packet_contents[i].strip().split( ":")[1] # Pass to packet processor for processing self.PACKET_PROCESSORS[packet_type](packet_contents) if self.repeat_log: self.multi_pipe.send({ 'cmd': 'clear_connection_list', 'args': {} }) self.src = open(self.src_input) else: do = False print() print("Processed {} lines ({} packets) in {} secs".format( line_ctr, packet_ctr, time.time() - start_time)) print("Total non-base node resolutions: {}".format(Main.resolved_ctr)) self.multi_pipe.send( "@realMainThread signing off. Peace.") if self.multi_pipe else None ##################### # Packet processors # ##################### AUTO_SETUP_BASE = config.AUTO_SETUP_BASE MANUAL_BASE_DIST = config.MANUAL_BASE_DIST ANCHORED_BASE = None CALCULATED_BASE = None r_nodes = {} for node_id, details in config.NODES.items(): if 'name' not in details: print( 'INVALID NODE SETUP: All nodes require the "name" attribute in config.py.' ) exit() continue if 'is_base' in details and details['is_base'] is True: r_nodes[node_id] = Node(node_id, details['name'], is_base=True) if 'base_type' in details: if details['base_type'] == 'anchored': if ANCHORED_BASE is None: ANCHORED_BASE = node_id else: print( 'INVALID NODE SETUP: Only one node may have the "anchored" attribute.' ) exit() elif details['base_type'] == 'calculated': if CALCULATED_BASE is None: CALCULATED_BASE = node_id else: print( 'INVALID NODE SETUP: Only one node may have the "calculated" attribute.' ) exit() else: r_nodes[node_id] = Node(node_id, details['name']) if ANCHORED_BASE is None or CALCULATED_BASE is None: print( 'INVALID NODE SETUP: Two base stations must be specified, and each needs to be "calculated" or "anchored" in type.' ) exit() config.ANCHORED_BASE = ANCHORED_BASE config.CALCULATED_BASE = CALCULATED_BASE r_current_cycle = None r_cycle_offset = None r_cycle_data = [] r_cycle_history = [] auto_base_meas_key = ANCHORED_BASE + "-" + CALCULATED_BASE if int(ANCHORED_BASE) > int(CALCULATED_BASE): auto_base_meas_key = CALCULATED_BASE + "-" + ANCHORED_BASE if AUTO_SETUP_BASE is False: r_nodes[CALCULATED_BASE].set_real_x_pos(MANUAL_BASE_DIST) else: r_nodes[CALCULATED_BASE].force_set_resolved(False) resolved_ctr = 0 def algorithm_callback(self, nodes, _t, _n): # self.backend.clear_nodes() for node_id, node in nodes.items(): self.backend.update_node(node) if not node.is_base and node.is_resolved(): Main.resolved_ctr += 1 @staticmethod def get_key_from_nodes(node_id_1, node_id_2): n1 = int(node_id_1) n2 = int(node_id_2) if n1 > n2: return str(n2) + "-" + str(n1) else: return str(n1) + "-" + str(n2) def process_range(self, packet): p_cycle, p_from, p_to, p_seq, p_hops, p_range = packet p_cycle = int(p_cycle) p_range = int(p_range) # START code to discard initial cycle if not Main.r_current_cycle: Main.r_current_cycle = p_cycle if p_cycle == Main.r_current_cycle: return if not Main.r_cycle_offset: Main.r_current_cycle = 0 Main.r_cycle_offset = 0 # END code to discard initial cycle if p_cycle != Main.r_current_cycle + Main.r_cycle_offset: # Pop old cycle data out of the history, and # insert the latest data at the front. while len(Main.r_cycle_history) >= config.MAX_HISTORY: Main.r_cycle_history.pop() Main.r_cycle_history.insert(0, Main.r_cycle_data) if self.multi_pipe is None: self.algorithm(Main.r_nodes, Main.ANCHORED_BASE, Main.CALCULATED_BASE)._process( self.algorithm_callback) else: self.multi_pipe.send({"cmd": "frame_start", "args": None}) self.algorithm(Main.r_nodes, Main.ANCHORED_BASE, Main.CALCULATED_BASE)._process( self.algorithm_callback, multi_pipe=self.multi_pipe) self.multi_pipe.send({"cmd": "frame_end", "args": None}) # Keep track of cycle count in a way that's not affected by system reboots Main.r_current_cycle += 1 Main.r_cycle_offset = p_cycle - Main.r_current_cycle Main.r_cycle_data = [] for node_id, node in Main.r_nodes.items(): node.start_new_cycle() # node.show() for name in self.name_arr: # self.history[name].new_cycle() meas = self.history[name] n1 = meas.get_node_1() n2 = meas.get_node_2() avg = meas.get_avg() std = meas.get_std_deviation() meas.new_cycle() if avg != 0: Main.r_nodes[n1].add_measurement(Main.r_nodes[n2], avg, std=std) Main.r_nodes[n2].add_measurement(Main.r_nodes[n1], avg, std=std) if Main.AUTO_SETUP_BASE and name == Main.auto_base_meas_key and avg != 0: Main.r_nodes[Main.CALCULATED_BASE].set_real_x_pos(avg) if self.pause_time > 0: time.sleep(self.pause_time) key = self.get_key_from_nodes(p_from, p_to) if self.multi_pipe is not None: self.multi_pipe.send({ "cmd": "report_communication", "args": { "key": key } }) self.history[key].add_measurement(p_range) Main.r_cycle_data.append([p_from, p_to, p_range, p_hops, p_seq]) def process_stats(self, packet): p_cycle, p_from, p_seq, p_hops, p_batt, p_temp, p_heading = packet p_heading = float(p_heading) p_temp = float(p_temp) p_batt = volts_to_percentage(float(p_batt)) self.backend.update_node_telemetry(Main.r_nodes[p_from], p_temp, p_batt, p_heading, "TELEMETRY") if self.multi_pipe is not None: self.multi_pipe.send({ 'cmd': 'status_update', 'args': { 'node_id': p_from, 'bat': p_batt, 'temp': p_temp, 'heading': p_heading } })
def on_init(self): self.backend = Backend(self.app) self.mon = ComponentManager.get().find('health-monitor')
def setupUi(self, MainWindow): self.BE = Backend() MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/logo/Logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_3 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.label_9 = QtGui.QLabel(self.centralwidget) self.label_9.setObjectName(_fromUtf8("label_9")) self.verticalLayout.addWidget(self.label_9) self.horizontalLayout_5 = QtGui.QHBoxLayout() self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.label = QtGui.QLabel(self.centralwidget) self.label.setObjectName(_fromUtf8("label")) self.horizontalLayout.addWidget(self.label) self.label_2 = QtGui.QLabel(self.centralwidget) self.label_2.setObjectName(_fromUtf8("label_2")) self.horizontalLayout.addWidget(self.label_2) self.horizontalLayout_5.addLayout(self.horizontalLayout) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.label_7 = QtGui.QLabel(self.centralwidget) self.label_7.setObjectName(_fromUtf8("label_7")) self.horizontalLayout_4.addWidget(self.label_7) self.label_8 = QtGui.QLabel(self.centralwidget) self.label_8.setObjectName(_fromUtf8("label_8")) self.horizontalLayout_4.addWidget(self.label_8) self.horizontalLayout_5.addLayout(self.horizontalLayout_4) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout_2.addWidget(self.label_3) self.label_4 = QtGui.QLabel(self.centralwidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.horizontalLayout_2.addWidget(self.label_4) self.horizontalLayout_5.addLayout(self.horizontalLayout_2) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.label_5 = QtGui.QLabel(self.centralwidget) self.label_5.setObjectName(_fromUtf8("label_5")) self.horizontalLayout_3.addWidget(self.label_5) self.label_6 = QtGui.QLabel(self.centralwidget) self.label_6.setObjectName(_fromUtf8("label_6")) self.horizontalLayout_3.addWidget(self.label_6) self.horizontalLayout_5.addLayout(self.horizontalLayout_3) self.verticalLayout.addLayout(self.horizontalLayout_5) self.gridLayout_3.addLayout(self.verticalLayout, 0, 0, 1, 2) self.horizontalLayout_6 = QtGui.QHBoxLayout() self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.label_10 = QtGui.QLabel(self.centralwidget) self.label_10.setObjectName(_fromUtf8("label_10")) self.horizontalLayout_6.addWidget(self.label_10) self.label_11 = QtGui.QLabel(self.centralwidget) self.label_11.setObjectName(_fromUtf8("label_11")) self.horizontalLayout_6.addWidget(self.label_11) self.gridLayout_3.addLayout(self.horizontalLayout_6, 1, 0, 1, 1) self.horizontalLayout_7 = QtGui.QHBoxLayout() self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.label_12 = QtGui.QLabel(self.centralwidget) self.label_12.setObjectName(_fromUtf8("label_12")) self.horizontalLayout_7.addWidget(self.label_12) self.label_13 = QtGui.QLabel(self.centralwidget) self.label_13.setObjectName(_fromUtf8("label_13")) self.horizontalLayout_7.addWidget(self.label_13) self.gridLayout_3.addLayout(self.horizontalLayout_7, 1, 1, 1, 1) self.horizontalLayout_11 = QtGui.QHBoxLayout() self.horizontalLayout_11.setObjectName( _fromUtf8("horizontalLayout_11")) self.frame = QtGui.QFrame(self.centralwidget) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setObjectName(_fromUtf8("frame")) self.gridLayout = QtGui.QGridLayout(self.frame) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.horizontalLayout_8 = QtGui.QHBoxLayout() self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.radioButton = QtGui.QRadioButton(self.frame) self.radioButton.setObjectName(_fromUtf8("radioButton")) self.horizontalLayout_8.addWidget(self.radioButton) self.radioButton_2 = QtGui.QRadioButton(self.frame) self.radioButton_2.setObjectName(_fromUtf8("radioButton_2")) self.horizontalLayout_8.addWidget(self.radioButton_2) self.radioButton_3 = QtGui.QRadioButton(self.frame) self.radioButton_3.setObjectName(_fromUtf8("radioButton_3")) self.horizontalLayout_8.addWidget(self.radioButton_3) self.radioButton_4 = QtGui.QRadioButton(self.frame) self.radioButton_4.setObjectName(_fromUtf8("radioButton_4")) self.radioButton.setChecked(True) self.horizontalLayout_8.addWidget(self.radioButton_4) self.verticalLayout_2.addLayout(self.horizontalLayout_8) self.listView = QtGui.QListView(self.frame) self.listView.setObjectName(_fromUtf8("listView")) self.verticalLayout_2.addWidget(self.listView) self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1) self.horizontalLayout_11.addWidget(self.frame) self.label_16 = QtGui.QLabel(self.centralwidget) self.label_16.setObjectName(_fromUtf8("label_16")) self.horizontalLayout_11.addWidget(self.label_16) self.frame_2 = QtGui.QFrame(self.centralwidget) self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtGui.QFrame.Raised) self.frame_2.setObjectName(_fromUtf8("frame_2")) self.gridLayout_2 = QtGui.QGridLayout(self.frame_2) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.horizontalLayout_10 = QtGui.QHBoxLayout() self.horizontalLayout_10.setObjectName( _fromUtf8("horizontalLayout_10")) self.label_14 = QtGui.QLabel(self.frame_2) self.label_14.setObjectName(_fromUtf8("label_14")) self.horizontalLayout_10.addWidget(self.label_14) self.label_15 = QtGui.QLabel(self.frame_2) self.label_15.setObjectName(_fromUtf8("label_15")) self.horizontalLayout_10.addWidget(self.label_15) self.verticalLayout_3.addLayout(self.horizontalLayout_10) self.horizontalLayout_9 = QtGui.QHBoxLayout() self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9")) spacerItem = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Minimum) self.horizontalLayout_9.addItem(spacerItem) self.listView_2 = QtGui.QListView(self.frame_2) self.listView_2.setObjectName(_fromUtf8("listView_2")) self.horizontalLayout_9.addWidget(self.listView_2) self.verticalLayout_3.addLayout(self.horizontalLayout_9) self.gridLayout_2.addLayout(self.verticalLayout_3, 0, 0, 1, 1) self.horizontalLayout_11.addWidget(self.frame_2) self.gridLayout_3.addLayout(self.horizontalLayout_11, 2, 0, 1, 2) self.label.raise_() self.label_2.raise_() self.label_3.raise_() self.label_4.raise_() self.label_5.raise_() self.label_6.raise_() self.label_7.raise_() self.label_8.raise_() self.label_9.raise_() self.label_10.raise_() self.label_11.raise_() self.label_12.raise_() self.label_13.raise_() self.label_10.raise_() self.totalPoints = 1000 self.frame.raise_() self.frame_2.raise_() self.label_16.raise_() MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.formation = [] self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuManage_Teams = QtGui.QMenu(self.menubar) self.menuManage_Teams.setObjectName(_fromUtf8("menuManage_Teams")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.actionNEW_TEam = QtGui.QAction(MainWindow) self.actionNEW_TEam.setObjectName(_fromUtf8("actionNEW_TEam")) self.actionOPEN_Team = QtGui.QAction(MainWindow) self.actionOPEN_Team.setObjectName(_fromUtf8("actionOPEN_Team")) self.actionSAVE_Team = QtGui.QAction(MainWindow) self.actionSAVE_Team.setObjectName(_fromUtf8("actionSAVE_Team")) self.actionEVALUATE_Team = QtGui.QAction(MainWindow) self.actionEVALUATE_Team.setObjectName( _fromUtf8("actionEVALUATE_Team")) self.menuManage_Teams.addAction(self.actionNEW_TEam) self.menuManage_Teams.addAction(self.actionOPEN_Team) self.menuManage_Teams.addAction(self.actionSAVE_Team) self.menuManage_Teams.addAction(self.actionEVALUATE_Team) self.menubar.addAction(self.menuManage_Teams.menuAction()) self.selectedPlayers = [] self.pointList = {} self.selectedPlayerModel = QtGui.QStandardItemModel() self.PlayerModel = QtGui.QStandardItemModel() self.listView_2.setModel(self.selectedPlayerModel) self.listView.setModel(self.PlayerModel) self.retranslateUi(MainWindow) self.radioButton.clicked.connect(self.BATClicked) self.radioButton_2.clicked.connect(self.BOWClicked) self.radioButton_3.clicked.connect(self.ARClicked) self.radioButton_4.clicked.connect(self.WKClicked) self.listView.doubleClicked.connect(self.selectPlayer) self.listView_2.doubleClicked.connect(self.removePlayer) self.actionNEW_TEam.activated.connect(self.newTeamActivated) self.actionOPEN_Team.activated.connect(self.openDialog) self.actionSAVE_Team.activated.connect(self.save) self.actionEVALUATE_Team.activated.connect(self.evaluate) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def main(): # Run pre-install tasks, if available. if os.path.isdir('exec.d'): dirnames = os.listdir('exec.d') dirnames.sort() for module in dirnames: filename = os.path.join('exec.d', module, 'charm-pre-install') try: run(filename) except OSError, e: # If the exec.d file does not exist or is not runnable or # is not a directory, assume we can recover. Log the problem # and proceed. Note that Juju Core has a special need of # errno.ENOTDIR because it apparently adds a ".empty" file in # empty charm directories, so trying to run # ./exec.d/.empty/charm-pre-install will trigger that error. if e.errno in (errno.ENOENT, errno.EACCES, errno.ENOTDIR): log('{}: {}'.format(e.strerror, filename)) else: raise config = get_config() backend = Backend(config) backend.install() # Store current configuration. config_json.set(config) if __name__ == '__main__': with log_hook(): main()
os.chdir(os.path.dirname(__file__)) logger = logging.getLogger('update_metrics') logger.setLevel(logging.DEBUG) chandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') chandler.setFormatter(formatter) logger.addHandler(chandler) if config.log_file: fhandler = logging.FileHandler(config.log_file) fhandler.setFormatter(formatter) logger.addHandler(fhandler) try: backend = Backend(config, logger) s_metrics = structured_metrics.StructuredMetrics(config, logger) errors = s_metrics.load_plugins() if len(errors) > 0: logger.warn('errors encountered while loading plugins:') for e in errors: print '\t%s' % e logger.info("fetching/saving metrics from graphite...") backend.download_metrics_json() logger.info("generating structured metrics data...") backend.update_data(s_metrics) logger.info("success!") except Exception, e: logger.error("sorry, something went wrong: %s", e) from traceback import print_exc print_exc()
def events_table_vimeo_analytics(**kwargs): return page_light(config, Backend(), {}, body=template('plugins/vimeo_analytics_table', events=events_vimeo_analytics()), **kwargs)
def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.backend = Backend() self.initialize_keyboard() """---------------------A: this section of code controls the appearance of the main window-------------------""" self.cols = 3 self.rows = 2 self.padding = 20 self.spacing = 10 Window.size = (980, 700) self.control_down = False def window_color_updater(instance, value): self.rect.pos = instance.pos self.rect.size = instance.size self.rect2.pos = 20, instance.size[1] - self.rect2.texture.size[ 1] - 10 with self.canvas.before: Color(1, 1, 1, 0.2) self.rect = Rectangle(pos=self.pos, size=(200, 200)) lable_texture = self.map_title() self.rect2 = Rectangle(size=lable_texture.size, texture=lable_texture) self.bind(size=window_color_updater, pos=window_color_updater) """------------B: This section of code creates the tileset control menue and active tile display------------""" def handle_tileset_select(instance): target_tileset = self.backend.working_dir + "img_store/tilesets/" + instance.text + ".png" if target_tileset != self.backend.active_tile_set_file: self.backend.active_tile_set_file = target_tileset self.backend.update_active_tileset() self.redraw_tileset() if self.backend.check_active_layer_type(): self.backend.layerlist.new_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 self.populate_layer_list(layer_list) self.backend.draw_map() self.redraw_active_tile() current_set.text = self.backend.active_tile_set_file.split( '/')[-1] tileset_dropdown.dismiss() else: tileset_dropdown.dismiss() def open_tile_set_dropdown(instance): tileset_dropdown.open(instance) tileset_menue = GridLayout(size_hint=(None, None), size=(300, 100), spacing=20, pos_hint=(None, 1), cols=3) tileset_select_shell = FloatLayout(size=(175, 100), size_hint=(None, None)) tileset_dropdown = DropDown() available_sets = os.listdir(self.backend.working_dir + 'img_store/tilesets') for i in available_sets: set_name = i[:len(i) - 4] set_btn = Button(text=set_name, size_hint_y=None, height=44) set_btn.bind(on_press=handle_tileset_select) tileset_dropdown.add_widget(set_btn) tileset_dropdown_btn = Button(text="Select", size=(175, 27), size_hint=(None, None), pos_hint={ 'x': 0, 'y': .2 }) tileset_dropdown_btn.bind(on_release=open_tile_set_dropdown) current_set = Label( text=self.backend.active_tile_set_file.split('/')[-1], size=(175, 25), size_hint=(None, None), pos_hint={ 'x': 0, 'y': .5 }) tileset_select_shell.add_widget(current_set) tileset_select_shell.add_widget(tileset_dropdown_btn) tileset_menue.add_widget(tileset_select_shell) tileset_menue.add_widget(Label(text="Active\nTile:", font_size='18sp')) active_tile_display = KvyImage() active_tile_display.texture = self.get_texture( self.backend.get_active_tile_image()) tileset_menue.add_widget(active_tile_display) self.add_widget(tileset_menue) """-------------C: This section of code creates the map space control buttons and drawing tools--------------""" map_control = GridLayout(cols=5, size=(100, 100), size_hint=(1, None), padding=20, spacing=5, rows=2) def alter_map(instance): if instance.text == "Resize": self.popup_constructor_size("Resize Map").open() else: self.popup_constructor_size( "New Map: !!UNSAVED PROGRESS WILL BE LOST!!").open() def save_load_export(instance): if instance.text == "Save": self.popup_constructor_file("Save Map") if instance.text == "Load": self.popup_constructor_file("Load Map") if instance.text == "Export": self.popup_constructor_file("Export Map") resize_map_btn = Button(text="Resize") new_map_btn = Button(text="New") save_btn = Button(text="Save") load_btn = Button(text="Load") export_btn = Button(text="Export") resize_map_btn.bind(on_press=alter_map) new_map_btn.bind(on_press=alter_map) for button in [save_btn, load_btn, export_btn]: button.bind(on_press=save_load_export) for button in [ new_map_btn, resize_map_btn, save_btn, load_btn, export_btn ]: map_control.add_widget(button) def tool_logic(instance): if instance.text == "Grid": self.backend.grid_toggle = 1 if self.backend.grid_toggle == 0 else 0 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.grid_toggle: tool_buttons[0].background_color = (0.5, 0.5, 0.5, 1.0) else: tool_buttons[0].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "Fill": self.backend.fill_toggle = 1 if self.backend.fill_toggle == 0 else 0 self.backend.square_toggle = 0 self.redraw_map() if self.backend.fill_toggle: tool_buttons[1].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[2].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[1].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "Sqr": self.backend.square_toggle = 1 if self.backend.square_toggle == 0 else 0 self.backend.fill_toggle = 0 if self.backend.square_toggle: tool_buttons[2].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[1].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[2].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "2x": self.backend.zoom_mod = 2 if self.backend.zoom_mod != 2 else 1 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.zoom_mod == 2: tool_buttons[3].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[4].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[3].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == ".5x": self.backend.zoom_mod = 0.5 if self.backend.zoom_mod != 0.5 else 1 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.zoom_mod == 0.5: tool_buttons[4].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[3].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[4].background_color = (1.0, 1.0, 1.0, 1.0) elif instance.text == "Img": self.popup_constructor_file('Import Image') tool_buttons = [] for tool in [ 'Grid', 'Fill', 'Sqr', '2x', '.5x', 'Img', ]: tool_btn = Button(text=tool) tool_btn.bind(on_press=tool_logic) tool_buttons.append(tool_btn) for i in range(0, 6, 2): button_shell = GridLayout(cols=2, spacing=5) button_shell.add_widget(tool_buttons[i]) button_shell.add_widget(tool_buttons[i + 1]) map_control.add_widget(button_shell) self.add_widget(map_control) """-------------------------D: This section of code creates an important spacer label------------------------""" self.add_widget( Label(text="\n\n\n\n[b]Layer Menue[/b]", markup=True, text_size=(200, 100), font_size='20dp', size_hint=(None, None), size=(200, 100), pos_hint=(1, 0))) """---------------E: This section of code creates the scrollable viewers for the map and tileset-------------""" map_scroller = self.get_map_scroller() tile_scroller = self.get_tileset_scroller() tileset = TilesetView(backend=self.backend, size_hint=(None, None)) map_image = MapView(backend=self.backend, size_hint=(None, None)) map_scroller.add_widget(map_image) tile_scroller.add_widget(tileset) self.add_widget(tile_scroller) self.add_widget(map_scroller) tileset.texture = self.get_texture(self.backend.active_tile_set) map_image.texture = self.get_texture(self.backend.draw_map()) tileset.size = tileset.texture.size map_image.size = map_image.texture.size cursor_size = (self.backend.layerlist.get_grid_res(), self.backend.layerlist.get_grid_res()) cursor_size = tuple(val * self.backend.zoom_mod for val in cursor_size) map_cursor = Button(text="", size=cursor_size) tile_cursor = Button(text="", size=cursor_size) map_image.add_widget(map_cursor) tileset.add_widget(tile_cursor) def cursor_polling(instance, pos): res = self.backend.layerlist.get_grid_res() if map_scroller.collide_point(*pos): res = self.backend.layerlist.get_grid_res( ) * self.backend.zoom_mod pos = map_scroller.to_local(*pos) if map_image.collide_point(*pos): tile_cursor.background_color = [0, 0, 0, 0] map_cursor.background_color = [0, 0, 1, 0.3] map_cursor.size = tuple( val * self.backend.zoom_mod for val in self.backend.active_tile_image.size) if self.backend.check_active_layer_type(): pos = (pos[0] // res) * res, (pos[1] // res) * res - ( map_cursor.size[1] - res) else: pos = pos[0] - map_cursor.size[1] / 2, pos[1] - \ map_cursor.size[1] / 2 map_cursor.pos = pos else: map_cursor.background_color = [0, 0, 0, 0] elif tile_scroller.collide_point(*pos): pos = tile_scroller.to_local(*pos) if tileset.collide_point(*pos): tile_cursor.background_color = [0, 1, 0, 0.5] map_cursor.background_color = [0, 0, 0, 0] tile_cursor.size = cursor_size pos = (pos[0] // res) * res, (pos[1] // res) * res tile_cursor.pos = pos else: tile_cursor.background_color = [0, 0, 0, 0] Window.bind(mouse_pos=cursor_polling) """-------------------------F: This section of code creates the layer control panel--------------------------""" layer_control_shell = GridLayout(rows=2, size_hint=(None, 1), size=(200, 200)) layer_control_panel = GridLayout(rows=3, cols=3, size_hint=(None, None), size=(200, 40), pos=self.size, pos_hint=(None, None)) layer_list = GridLayout(rows=1, cols=1, size=(200, 1), size_hint=(None, 1)) def modify_layer_list(instance): """ This method handles button presses on the layer control buttons. :param instance: :return: """ if instance.text == "New": self.backend.layerlist.new_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 elif instance.text == "Delete": self.backend.layerlist.del_layer(self.backend.active_layer) self.backend.active_layer += -1 if self.backend.active_layer < 1: if len(self.backend.layerlist.stack) <= 1: self.backend.layerlist.new_layer( self.backend.active_tile_set_file) self.backend.active_layer += 1 else: self.backend.active_layer = 1 self.backend.active_tile_set_file = self.backend.layerlist.get_layer( self.backend.active_layer).tileset self.backend.update_active_tileset() self.redraw_active_tile() self.redraw_tileset() elif instance.text == "Up": if self.backend.active_layer > 1: self.backend.layerlist.move_up(self.backend.active_layer) self.backend.active_layer += -1 elif instance.text == "Down": if self.backend.active_layer < len( self.backend.layerlist.stack) - 1: self.backend.layerlist.move_down(self.backend.active_layer) self.backend.active_layer += 1 elif instance.text == "Rename": self.popup_constructor_rename().open() else: self.backend.layerlist.add_image_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 self.populate_layer_list(layer_list) self.redraw_map() new_layer_btn = Button(text="New") del_layer_btn = Button(text="Delete") new_layer_btn.bind(on_press=modify_layer_list) del_layer_btn.bind(on_press=modify_layer_list) up_btn = Button(text="Up") down_btn = Button(text="Down") rename_btn = Button(text="Rename") freedraw_btn = Button(text="Unsnap") for button in [ rename_btn, new_layer_btn, up_btn, freedraw_btn, del_layer_btn, down_btn ]: button.bind(on_press=modify_layer_list) layer_control_panel.add_widget(button) layer_control_shell.add_widget(layer_control_panel) self.populate_layer_list(layer_list) layer_control_shell.add_widget(layer_list) self.add_widget(layer_control_shell)
class MainScreen(GridLayout): """ This class describes the main GUI window """ def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.backend = Backend() self.initialize_keyboard() """---------------------A: this section of code controls the appearance of the main window-------------------""" self.cols = 3 self.rows = 2 self.padding = 20 self.spacing = 10 Window.size = (980, 700) self.control_down = False def window_color_updater(instance, value): self.rect.pos = instance.pos self.rect.size = instance.size self.rect2.pos = 20, instance.size[1] - self.rect2.texture.size[ 1] - 10 with self.canvas.before: Color(1, 1, 1, 0.2) self.rect = Rectangle(pos=self.pos, size=(200, 200)) lable_texture = self.map_title() self.rect2 = Rectangle(size=lable_texture.size, texture=lable_texture) self.bind(size=window_color_updater, pos=window_color_updater) """------------B: This section of code creates the tileset control menue and active tile display------------""" def handle_tileset_select(instance): target_tileset = self.backend.working_dir + "img_store/tilesets/" + instance.text + ".png" if target_tileset != self.backend.active_tile_set_file: self.backend.active_tile_set_file = target_tileset self.backend.update_active_tileset() self.redraw_tileset() if self.backend.check_active_layer_type(): self.backend.layerlist.new_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 self.populate_layer_list(layer_list) self.backend.draw_map() self.redraw_active_tile() current_set.text = self.backend.active_tile_set_file.split( '/')[-1] tileset_dropdown.dismiss() else: tileset_dropdown.dismiss() def open_tile_set_dropdown(instance): tileset_dropdown.open(instance) tileset_menue = GridLayout(size_hint=(None, None), size=(300, 100), spacing=20, pos_hint=(None, 1), cols=3) tileset_select_shell = FloatLayout(size=(175, 100), size_hint=(None, None)) tileset_dropdown = DropDown() available_sets = os.listdir(self.backend.working_dir + 'img_store/tilesets') for i in available_sets: set_name = i[:len(i) - 4] set_btn = Button(text=set_name, size_hint_y=None, height=44) set_btn.bind(on_press=handle_tileset_select) tileset_dropdown.add_widget(set_btn) tileset_dropdown_btn = Button(text="Select", size=(175, 27), size_hint=(None, None), pos_hint={ 'x': 0, 'y': .2 }) tileset_dropdown_btn.bind(on_release=open_tile_set_dropdown) current_set = Label( text=self.backend.active_tile_set_file.split('/')[-1], size=(175, 25), size_hint=(None, None), pos_hint={ 'x': 0, 'y': .5 }) tileset_select_shell.add_widget(current_set) tileset_select_shell.add_widget(tileset_dropdown_btn) tileset_menue.add_widget(tileset_select_shell) tileset_menue.add_widget(Label(text="Active\nTile:", font_size='18sp')) active_tile_display = KvyImage() active_tile_display.texture = self.get_texture( self.backend.get_active_tile_image()) tileset_menue.add_widget(active_tile_display) self.add_widget(tileset_menue) """-------------C: This section of code creates the map space control buttons and drawing tools--------------""" map_control = GridLayout(cols=5, size=(100, 100), size_hint=(1, None), padding=20, spacing=5, rows=2) def alter_map(instance): if instance.text == "Resize": self.popup_constructor_size("Resize Map").open() else: self.popup_constructor_size( "New Map: !!UNSAVED PROGRESS WILL BE LOST!!").open() def save_load_export(instance): if instance.text == "Save": self.popup_constructor_file("Save Map") if instance.text == "Load": self.popup_constructor_file("Load Map") if instance.text == "Export": self.popup_constructor_file("Export Map") resize_map_btn = Button(text="Resize") new_map_btn = Button(text="New") save_btn = Button(text="Save") load_btn = Button(text="Load") export_btn = Button(text="Export") resize_map_btn.bind(on_press=alter_map) new_map_btn.bind(on_press=alter_map) for button in [save_btn, load_btn, export_btn]: button.bind(on_press=save_load_export) for button in [ new_map_btn, resize_map_btn, save_btn, load_btn, export_btn ]: map_control.add_widget(button) def tool_logic(instance): if instance.text == "Grid": self.backend.grid_toggle = 1 if self.backend.grid_toggle == 0 else 0 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.grid_toggle: tool_buttons[0].background_color = (0.5, 0.5, 0.5, 1.0) else: tool_buttons[0].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "Fill": self.backend.fill_toggle = 1 if self.backend.fill_toggle == 0 else 0 self.backend.square_toggle = 0 self.redraw_map() if self.backend.fill_toggle: tool_buttons[1].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[2].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[1].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "Sqr": self.backend.square_toggle = 1 if self.backend.square_toggle == 0 else 0 self.backend.fill_toggle = 0 if self.backend.square_toggle: tool_buttons[2].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[1].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[2].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == "2x": self.backend.zoom_mod = 2 if self.backend.zoom_mod != 2 else 1 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.zoom_mod == 2: tool_buttons[3].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[4].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[3].background_color = (1.0, 1.0, 1.0, 1.0) if instance.text == ".5x": self.backend.zoom_mod = 0.5 if self.backend.zoom_mod != 0.5 else 1 self.backend.undo_tracker += -1 self.backend.undo_array = self.backend.undo_array[0:-1] self.redraw_map() if self.backend.zoom_mod == 0.5: tool_buttons[4].background_color = (0.5, 0.5, 0.5, 1.0) tool_buttons[3].background_color = (1.0, 1.0, 1.0, 1.0) else: tool_buttons[4].background_color = (1.0, 1.0, 1.0, 1.0) elif instance.text == "Img": self.popup_constructor_file('Import Image') tool_buttons = [] for tool in [ 'Grid', 'Fill', 'Sqr', '2x', '.5x', 'Img', ]: tool_btn = Button(text=tool) tool_btn.bind(on_press=tool_logic) tool_buttons.append(tool_btn) for i in range(0, 6, 2): button_shell = GridLayout(cols=2, spacing=5) button_shell.add_widget(tool_buttons[i]) button_shell.add_widget(tool_buttons[i + 1]) map_control.add_widget(button_shell) self.add_widget(map_control) """-------------------------D: This section of code creates an important spacer label------------------------""" self.add_widget( Label(text="\n\n\n\n[b]Layer Menue[/b]", markup=True, text_size=(200, 100), font_size='20dp', size_hint=(None, None), size=(200, 100), pos_hint=(1, 0))) """---------------E: This section of code creates the scrollable viewers for the map and tileset-------------""" map_scroller = self.get_map_scroller() tile_scroller = self.get_tileset_scroller() tileset = TilesetView(backend=self.backend, size_hint=(None, None)) map_image = MapView(backend=self.backend, size_hint=(None, None)) map_scroller.add_widget(map_image) tile_scroller.add_widget(tileset) self.add_widget(tile_scroller) self.add_widget(map_scroller) tileset.texture = self.get_texture(self.backend.active_tile_set) map_image.texture = self.get_texture(self.backend.draw_map()) tileset.size = tileset.texture.size map_image.size = map_image.texture.size cursor_size = (self.backend.layerlist.get_grid_res(), self.backend.layerlist.get_grid_res()) cursor_size = tuple(val * self.backend.zoom_mod for val in cursor_size) map_cursor = Button(text="", size=cursor_size) tile_cursor = Button(text="", size=cursor_size) map_image.add_widget(map_cursor) tileset.add_widget(tile_cursor) def cursor_polling(instance, pos): res = self.backend.layerlist.get_grid_res() if map_scroller.collide_point(*pos): res = self.backend.layerlist.get_grid_res( ) * self.backend.zoom_mod pos = map_scroller.to_local(*pos) if map_image.collide_point(*pos): tile_cursor.background_color = [0, 0, 0, 0] map_cursor.background_color = [0, 0, 1, 0.3] map_cursor.size = tuple( val * self.backend.zoom_mod for val in self.backend.active_tile_image.size) if self.backend.check_active_layer_type(): pos = (pos[0] // res) * res, (pos[1] // res) * res - ( map_cursor.size[1] - res) else: pos = pos[0] - map_cursor.size[1] / 2, pos[1] - \ map_cursor.size[1] / 2 map_cursor.pos = pos else: map_cursor.background_color = [0, 0, 0, 0] elif tile_scroller.collide_point(*pos): pos = tile_scroller.to_local(*pos) if tileset.collide_point(*pos): tile_cursor.background_color = [0, 1, 0, 0.5] map_cursor.background_color = [0, 0, 0, 0] tile_cursor.size = cursor_size pos = (pos[0] // res) * res, (pos[1] // res) * res tile_cursor.pos = pos else: tile_cursor.background_color = [0, 0, 0, 0] Window.bind(mouse_pos=cursor_polling) """-------------------------F: This section of code creates the layer control panel--------------------------""" layer_control_shell = GridLayout(rows=2, size_hint=(None, 1), size=(200, 200)) layer_control_panel = GridLayout(rows=3, cols=3, size_hint=(None, None), size=(200, 40), pos=self.size, pos_hint=(None, None)) layer_list = GridLayout(rows=1, cols=1, size=(200, 1), size_hint=(None, 1)) def modify_layer_list(instance): """ This method handles button presses on the layer control buttons. :param instance: :return: """ if instance.text == "New": self.backend.layerlist.new_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 elif instance.text == "Delete": self.backend.layerlist.del_layer(self.backend.active_layer) self.backend.active_layer += -1 if self.backend.active_layer < 1: if len(self.backend.layerlist.stack) <= 1: self.backend.layerlist.new_layer( self.backend.active_tile_set_file) self.backend.active_layer += 1 else: self.backend.active_layer = 1 self.backend.active_tile_set_file = self.backend.layerlist.get_layer( self.backend.active_layer).tileset self.backend.update_active_tileset() self.redraw_active_tile() self.redraw_tileset() elif instance.text == "Up": if self.backend.active_layer > 1: self.backend.layerlist.move_up(self.backend.active_layer) self.backend.active_layer += -1 elif instance.text == "Down": if self.backend.active_layer < len( self.backend.layerlist.stack) - 1: self.backend.layerlist.move_down(self.backend.active_layer) self.backend.active_layer += 1 elif instance.text == "Rename": self.popup_constructor_rename().open() else: self.backend.layerlist.add_image_layer( self.backend.active_tile_set_file, position=self.backend.active_layer + 1) self.backend.active_layer += 1 self.populate_layer_list(layer_list) self.redraw_map() new_layer_btn = Button(text="New") del_layer_btn = Button(text="Delete") new_layer_btn.bind(on_press=modify_layer_list) del_layer_btn.bind(on_press=modify_layer_list) up_btn = Button(text="Up") down_btn = Button(text="Down") rename_btn = Button(text="Rename") freedraw_btn = Button(text="Unsnap") for button in [ rename_btn, new_layer_btn, up_btn, freedraw_btn, del_layer_btn, down_btn ]: button.bind(on_press=modify_layer_list) layer_control_panel.add_widget(button) layer_control_shell.add_widget(layer_control_panel) self.populate_layer_list(layer_list) layer_control_shell.add_widget(layer_list) self.add_widget(layer_control_shell) def populate_layer_list(self, widget): """ This layer populates the list of displayed layers, highlighting the active layer in white :param widget: :return: """ def set_active_layer(instance): words = instance.text.split(" ") self.backend.active_layer = int(words[-1]) self.populate_layer_list(widget) self.backend.active_tile_set_file = self.backend.layerlist.get_layer( self.backend.active_layer).tileset self.backend.update_active_tileset() self.redraw_active_tile() self.redraw_tileset() self.children[len(self.children) - 1].children[2].children[1]. \ text = text = self.backend.active_tile_set_file.split('/')[-1] widget.clear_widgets() for i, layer in enumerate(self.backend.layerlist.stack[1:]): widget.rows += 1 layer_button = Button(text=f"{layer.name} at position {i + 1}") layer_button.bind(on_press=set_active_layer) if not isinstance(layer, Layer): layer_button.color = [0.5, 0.5, 1, 1] if i + 1 == self.backend.active_layer: layer_button.background_normal = "" if not isinstance(layer, Layer): layer_button.color = [0, 0.4, 0.9, 1] else: layer_button.color = (0, 0, 0, 1) widget.add_widget(layer_button) def redraw_active_tile(self): self.children[5].children[0].texture = self.get_texture( self.backend.get_active_tile_image()) self.children[5].children[0].size = self.children[5].children[ 0].texture.size def popup_constructor_rename(self): """ this method creates a pop-up dialogue to rename a layer :return: """ def resolve(instance): """ This method resolves the rename popup :param instance: :return: """ new_name = instance.text if new_name.isalnum(): self.backend.layerlist.set_name(new_name, self.backend.active_layer) self.populate_layer_list(self.children[0].children[0]) pop.dismiss() self.initialize_keyboard() name_input = TextInput(text="Layername") name_input.multiline = False name_input.bind(on_text_validate=resolve) pop = Popup(title="Rename Layer:", content=name_input, size_hint=(None, None), size=(500, 100), auto_dismiss=True) return pop def popup_constructor_file(self, title): """ generalized popup constructor for save/load/export and import image commands :param title: :return: """ changed_dir = True #set this to false when testing in IDE file_browser = FileChooserIconView() file_browser_text = TextInput(text="File.txt", multiline=False, size=(345, 30), size_hint=(None, None)) file_browser.add_widget(file_browser_text) file_browser.path = self.backend.working_dir + 'Saved maps' file_browser_cancel_btn = Button(text="Cancel", size=(60, 30), size_hint=(None, None), pos=(415, 0)) file_browser_confirm_btn = Button(text="blank", size=(60, 30), size_hint=(None, None), pos=(350, 0)) if title == "Save Map": file_browser_text.text = file_browser.path + "/Untitled.text" file_browser_confirm_btn.text = "Save" elif title == "Load Map": file_browser_text.text = file_browser.path + "/Untitled.text" file_browser_confirm_btn.text = "Load" elif title == "Import Image": file_browser_text.text = file_browser.path + "/Untitled.png" file_browser_confirm_btn.text = "Import" else: file_browser_text.text = file_browser.path + "/Untitled.png" file_browser_confirm_btn.text = "Export" file_browser.add_widget(file_browser_cancel_btn) file_browser.add_widget(file_browser_confirm_btn) def resolve_dialogue(instance): try: if title == "Save Map": if file_browser_text.text.split("\\")[-1] in [i.split("\\")[-1] for i in file_browser.files] or \ file_browser_text.text.split("/")[-1] in [i.split("\\")[-1] for i in file_browser.files]: def overwrite_resolve(instance): self.backend.save_to_file(file_browser_text.text) self.backend.working_file = file_browser_text.text self.backend.last_save = datetime.now() self.update_map_title() pop2.dismiss() pop.dismiss() self.initialize_keyboard() overwrite_okay.bind(on_press=overwrite_resolve) nonlocal overwrite_msg overwrite_msg = Label( text= f"The file: \n{file_browser_text.text}\nwill be Overwritten" ) pop2.open() else: self.backend.save_to_file(file_browser_text.text) self.backend.working_file = file_browser_text.text self.backend.last_save = datetime.now() self.update_map_title() pop.dismiss() self.initialize_keyboard() elif title == "Load Map": self.backend.load_from_file(file_browser_text.text) self.redraw_map() self.redraw_tileset() self.redraw_active_tile() self.populate_layer_list(self.children[0].children[0]) self.backend.working_file = file_browser_text.text self.backend.last_save = datetime.now() self.update_map_title() pop.dismiss() self.initialize_keyboard() elif title == "Export Map": if file_browser_text.text.split("\\")[-1] in [i.split("\\")[-1] for i in file_browser.files] or \ file_browser_text.text.split("/")[-1] in [i.split("\\")[-1] for i in file_browser.files]: def overwrite_resolve(instance): self.backend.export(file_browser_text.text) pop2.dismiss() pop.dismiss() self.initialize_keyboard() overwrite_okay.bind(on_press=overwrite_resolve) overwrite_msg.text = f"!WARNING!: The file: \n{file_browser_text.text}\nwill be Overwritten" pop2.open() else: self.backend.export(file_browser_text.text) pop.dismiss() self.initialize_keyboard() elif title == "Import Image": self.backend.import_img(file_browser_text.text) self.populate_layer_list(self.children[0].children[0]) self.redraw_map() pop.dismiss() self.initialize_keyboard() except Exception as e: error = Popup(title=" An error Occured:", content=(Label(text=e.__str__())), size_hint=(None, None), size=(400, 200), auto_dismiss=True) error.open() def filecancel(instance): pop.dismiss() self.initialize_keyboard() def update_file_text(instance, path): nonlocal changed_dir changed_dir = True if title == "Save Map" or title == "Load Map": file_browser_text.text = file_browser.path + "/Untitled.text" else: file_browser_text.text = file_browser.path + "/Untitled.png" def update_file_text_select(instance, selection, touch): path = "" for i in selection: path = i file_browser_text.text = path if changed_dir == False: segments = path.split("\\") del segments[5] clean_path = "\\".join(segments) file_browser_text.text = clean_path file_browser.bind(on_submit=update_file_text_select, path=update_file_text) file_browser_cancel_btn.bind(on_press=filecancel) file_browser_confirm_btn.bind(on_press=resolve_dialogue) pop = Popup(title=title, content=file_browser, size_hint=(None, None), size=(500, 500), auto_dismiss=True) pop.open() overwrite = GridLayout(rows=2) overwrite_msg = Label( text= f"!WARNING!: The file: \n{file_browser_text.text}\nwill be Overwritten" ) overwrite_buttons = GridLayout(cols=2, size_hint=(1, None), size=(100, 40)) overwrite_okay = Button(text="Overwrite", size_hint=(1, None), size=(100, 40)) overwrite_cancel = Button(text="Cancel", size_hint=(1, None), size=(100, 40)) overwrite_buttons.add_widget(overwrite_okay) overwrite_buttons.add_widget(overwrite_cancel) overwrite.add_widget(overwrite_msg) overwrite.add_widget(overwrite_buttons) overwrite_cancel.bind(on_press=lambda instance: pop2.dismiss()) pop2 = Popup(title="Confirm File Overwrite", content=overwrite, size_hint=(None, None), size=(500, 300), auto_dismiss=True) def popup_constructor_size(self, title): """ This popup creates a generic pop up with two text field inputs, used for height and width to update the size of the map, or create a new map of the specified size. :param title: :return: """ grid_res = self.backend.layerlist.get_grid_res() self.map_width = self.backend.layerlist.get_size()[0] self.map_height = self.backend.layerlist.get_size()[1] def cancel_dialogue(instance): pop.dismiss() self.initialize_keyboard() def resolve_dialogue(instance): self.map_height = 1 if self.map_height < 2 else self.map_height self.map_width = 1 if self.map_height < 2 else self.map_width if title == "New Map: !!UNSAVED PROGRESS WILL BE LOST!!": self.backend.create_drawspace(1, 1) self.backend.layerlist.resize( (self.map_width, self.map_height)) self.redraw_map() self.populate_layer_list(self.children[0].children[0]) self.backend.working_file = "" self.backend.last_save = "" self.update_map_title() pop.dismiss() self.initialize_keyboard() else: self.backend.layerlist.resize( (self.map_width, self.map_height)) self.redraw_map() pop.dismiss() Window.size = Window.size[0] - 1, Window.size[1] - 1 self.initialize_keyboard() def store_width(instance, value): if instance.text != "": self.map_width = int(instance.text) def store_height(instance, value): if instance.text != "": self.map_height = int(instance.text) input_shell = GridLayout(rows=3, cols=2) input1 = TextInput(multiline=False, text=str(int(self.map_width))) input1.bind(text=store_width) input2 = TextInput(multiline=False, text=str(int(self.map_height))) input2.bind(text=store_height) input_shell.add_widget(Label(text="Grid Width")) input_shell.add_widget(Label(text="Grid Height")) input_shell.add_widget(input1) input_shell.add_widget(input2) okay_btn = Button(text="Okay") cancel_btn = Button(text="Cancel") okay_btn.bind(on_press=resolve_dialogue) cancel_btn.bind(on_press=cancel_dialogue) input_shell.add_widget(cancel_btn) input_shell.add_widget(okay_btn) pop = Popup(title=title, content=input_shell, size_hint=(None, None), size=(400, 200), auto_dismiss=True) return pop def redraw_map(self, target=None): """ Simple method that redraws the full map and displays it on the gui. :return: """ self.children[1].children[0].texture = self.get_texture( self.backend.draw_map(target)) self.children[1].children[0].size = self.children[1].children[ 0].texture.size def redraw_tileset(self): """ Simple method that redraws the tileset and displays it on the gui :return: """ self.children[len(self.children) - 1].children[2].children[1].text = \ self.backend.active_tile_set_file.split('/')[-1] self.children[2].children[0].texture = self.get_texture( self.backend.active_tile_set) self.children[2].children[0].size = self.children[2].children[ 0].texture.size def get_map_scroller(self): """ returns a scroll view object for viewing the map or drawspace :return: """ returnable = ScrollView(size_hint=(1, 1), scroll_type=['bars'], bar_width=16) return returnable def get_tileset_scroller(self): """ returns a scroll view object for viewing the tilset :return: """ returnable = ScrollView(size_hint=(None, 1), size=(300, 300), scroll_type=['bars'], bar_width=16) return returnable def get_texture(self, image): """ This method accepts a PIL image object and returns a kivy texture created from the image :param image: :return: """ num_array = numpy.array(image) texture = Texture.create(size=image.size) texture.blit_buffer(num_array.tobytes(), bufferfmt="ubyte", colorfmt="rgba") texture.flip_vertical() return texture def run_undo(self): if self.backend.undo(): self.children[1].children[0].texture = self.get_texture( self.backend.draw_map(not_undoing=False)) self.children[1].children[0].size = self.children[1].children[ 0].texture.size self.backend.active_tile_set_file = self.backend.layerlist.get_layer( self.backend.active_layer).tileset self.backend.update_active_tileset() self.redraw_active_tile() self.redraw_tileset() self.populate_layer_list(self.children[0].children[0]) def run_redo(self): if self.backend.redo(): self.children[1].children[0].texture = self.get_texture( self.backend.draw_map(not_undoing=False)) self.children[1].children[0].size = self.children[1].children[ 0].texture.size self.backend.active_tile_set_file = self.backend.layerlist.get_layer( self.backend.active_layer).tileset self.backend.update_active_tileset() self.redraw_active_tile() self.redraw_tileset() self.populate_layer_list(self.children[0].children[0]) def map_title(self): if self.backend.working_file: # map_name = self.backend.working_file[0:-5] # map_name_clean = "" # for i in range(len(map_name) - 1, 0, -1): # char = map_name[i] # if char.isalnum(): # map_name_clean += char # else: # break # map_name_clean = map_name_clean[::-1] map_name = self.backend.working_file.replace("\\", "/") map_name_clean = map_name.split("/")[-1][0:-5] title_string = map_name_clean + ", Last Saved: " + self.backend.last_save.strftime( "%Y-%m-%d %H:%M:%S") else: title_string = "Unsaved" title_label = CoreLabel(text=title_string, font_size=20) title_label.refresh() return title_label.texture def update_map_title(self): text = self.map_title() self.rect2.texture = text self.rect2.size = text.size def no_dialogue_save(self): try: self.backend.save_to_file(self.backend.working_file) self.backend.last_save = datetime.now() self.update_map_title() print('Saved') except: print('failed to save') def initialize_keyboard(self): def _keyboard_closed(): self._keyboard.unbind(on_key_down=on_keyboard_down) self._keyboard.unbind(on_key_up=on_keyboard_up) self._keyboard = None def on_keyboard_down(self, key, scancode, codepoint): if key == (305, 'lctrl'): self.control_down = True return True def on_keyboard_up(self, key): if key == (305, 'lctrl'): self.control_down = False if key == (122, 'z') and self.control_down: self.target.run_undo() elif key == (121, 'y') and self.control_down: self.target.run_redo() elif key == (115, 's') and self.control_down: self.target.no_dialogue_save() return True self._keyboard = Window.request_keyboard(_keyboard_closed, self) self._keyboard.bind(on_key_up=on_keyboard_up) self._keyboard.bind(on_key_down=on_keyboard_down)
title='404 page not found', msg='The requested page was not found'), **kwargs) def p(**kwargs): return page(config, backend, state, **kwargs) app_dir = os.path.dirname(__file__) if app_dir: os.chdir(app_dir) import config config = Config(config) backend = Backend(config) state = {} (state, errors) = load_plugins(config.plugins, config) if errors: for e in errors: sys.stderr.write(str(e)) sys.exit(2) session_opts = { 'session.type': 'file', 'session.cookie_expires': 300, 'session.data_dir': './session_data', 'session.auto': True } app = SessionMiddleware(app(), session_opts) debug(True) #run(app=app, reloader=True, host=config.listen_host, port=config.listen_port)
version = "N/A" except subprocess.CalledProcessError: version = "N/A" print(version) load_dotenv() app = Flask(__name__) app.secret_key = os.getenv("FLASK_SECRET_KEY") # subtitle for template sub = "{} | {}-{}".format(os.getenv("WOWGUILD"), os.getenv("WOWREALM"), os.getenv("WOWREGION")) backend = Backend() @app.route('/') def index(): """ Responds to route '/'. Gets data required for index page from backend.getView(), backend.getLogs(), calculates time from last update of roster and returns flask.render_template('index.html') with required data. """ sidebar = backend.getSideBar() sidebar[1] = {"version": version} roster = backend.getView()
def handle_text(message): message.text = message.text.lower() # creating google sheets session sh = SheetHandler() ch = ConnectSheet() # writing to log current_time = datetime.datetime.now() now = current_time.strftime("%H:%M:%S") chat_id = str(message.chat.id) if chat_id == '388953283': chat_id = 'me' with open('log.txt', 'a') as log: log.write('Used. Time: ' + now + '. By: ' + chat_id + '\n') fooStr = """ 1. maintain 2. 1 3. test 4. del - deletes 2 worksheet in Botsheet 4.1 copy - copies worksheet from Spreadsheet to Botsheet 5. reset - deletes 2 worksheet in Botsheet and creates new instead 6. week - today's week 7. heroku - heroku link 8. clear log 9. print log """ helpStr = """ Он не показывает 4 пары по нечётным неделям: три матана в четверг и одно программирование в пятницу За всё вините апи гугла!1 0. хелп/help - помощь 1. ссылку - ссылка на расписание 2. пара - текущая пара [не работает] 3. след пара - следующая пара [не работает] 4. пары - все пары на сегодня 5. пары завтра - все пары на завтра 6. пн/вт/ср/чт/пт - какие пары на этой неделе 7. пн2/вт2/ср2/чт2/пт2 - какие пары будут на следующей неделе 8. черта 9. foo - для разрабов foohelp """ maintainStr = """ 1. Follow the link https://docs.google.com/spreadsheets/d/1sN4war5N8FGEkomKv0Vo-lwLmREsEmXt/edit#gid=112716612 2. Copy the "1 курс" worksheet over to "Botsheet" """ if message.text == 'heroku': bot.send_message( message.chat.id, 'https://dashboard.heroku.com/apps/guarded-retreat-31483/logs') if message.text == 'clear log': with open('log.txt', 'w') as log: log.write('') bot.send_message(message.chat.id, 'log cleared') if message.text == 'print log': with open('log.txt', 'r') as log: text = log.read() try: bot.send_message(message.chat.id, text) except: bot.send_message( message.chat.id, 'A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: message is too long\n\ntry: clear log' ) if message.text == 'foohelp': bot.send_message(message.chat.id, fooStr) if message.text == 'foo': bot.send_message( message.chat.id, 'https://cdn.fishki.net/upload/post/2018/02/18/2515915/8-1.jpg') if message.text in ['help', 'хелп', 'помоги', '/help']: bot.send_message(message.chat.id, helpStr, reply_markup=keyboardMain()) if message.text == 'maintain': bot.send_message(message.chat.id, maintainStr) if message.text in ['ссылку', 'ссылка', 'ссыль', 'сс']: bot.send_message( message.chat.id, "https://docs.google.com/spreadsheets/d/1sN4war5N8FGEkomKv0Vo-lwLmREsEmXt/edit#gid=112716612", reply_markup=keyboardMain()) if message.text == '1': bot.send_message(message.chat.id, "2") if message.text == 'week': bot.send_message(message.chat.id, str(datetime.date.today().isocalendar()[1])) if message.text == 'test': text = ch.readCol()['values'] bot.send_message(message.chat.id, text[0][1]) bot.send_message(message.chat.id, text[1][1]) bot.send_message(message.chat.id, text[19][1]) if message.text == 'del': call = sh.deleteWorksheet() if call == True: bot.send_message(message.chat.id, "deleted") else: bot.send_message(message.chat.id, "no del") if message.text == 'copy': sh.copySheet() bot.send_message(message.chat.id, "copied") if message.text == 'reset': sh.deleteWorksheet() sh.copySheet() bot.send_message(message.chat.id, "reset") if message.text in ['пары', 'пары сёдня']: bc = Backend() bot.send_message(message.chat.id, bc.AllForToday()) if message.text == 'пары завтра': bc = Backend() bot.send_message(message.chat.id, bc.tomorrowClasses()) if message.text == 'черта': week = datetime.date.today().isocalendar()[1] if week % 2 == 0: bot.send_message(message.chat.id, "сёдня смотрим над чертой") if week % 2 == 1: bot.send_message(message.chat.id, "сёдня смотрим под чертой") # week days if message.text == 'пн': bc = Backend() bot.send_message(message.chat.id, bc.byDay(0)) if message.text == 'вт': bc = Backend() bot.send_message(message.chat.id, bc.byDay(1)) if message.text == 'ср': bc = Backend() bot.send_message(message.chat.id, bc.byDay(2)) if message.text == 'чт': bc = Backend() bot.send_message(message.chat.id, bc.byDay(3)) if message.text == 'пт': bc = Backend() bot.send_message(message.chat.id, bc.byDay(4)) # next week if message.text == 'пн2': bc = Backend() bot.send_message(message.chat.id, bc.byDayNext(0)) if message.text == 'вт2': bc = Backend() bot.send_message(message.chat.id, bc.byDayNext(1)) if message.text == 'ср2': bc = Backend() bot.send_message(message.chat.id, bc.byDayNext(2)) if message.text == 'чт2': bc = Backend() bot.send_message(message.chat.id, bc.byDayNext(3)) if message.text == 'пт2': bc = Backend() bot.send_message(message.chat.id, bc.byDayNext(4)) if message.text == "расписание-на-эту-неделю": bot.send_message(message.chat.id, 'Выбери день', reply_markup=keyboardThisWeek()) if message.text == "расписание-на-следующую-неделю": bot.send_message(message.chat.id, 'Выбери день', reply_markup=keyboardNextWeek()) if message.text == "назад": bot.send_message(message.chat.id, 'Ок', reply_markup=keyboardMain())
def init(self): """ Avoid the Oracle specific stuff here in parent method. """ self.setSessionTimeZoneToLocalTimeZone() return Backend.init(self)
def work(socket_instance): backend_instance = Backend() connection, address = socket_instance.accept() while True: client_request = connection.recv(1024) client_request = client_request.decode() if client_request != "": print("client sent : " + client_request) json_response = backend_instance.dispatcher(client_request) nature = json_response['nature'] del (json_response['nature']) if nature == 'error': response = json_response['error_msg'] #HANDLING AUTHENTICATION if nature == 'authentication': login = json_response['login'] password = json_response['password'] response = backend_instance.authenticate(login, password) # HANDLING ROUTES TO LDD if (nature == 'create_database'): response = backend_instance.create_database( json_response['database_name']) if (nature == 'create_table'): response = backend_instance.create_table( json.dumps(json_response)) if (nature == 'create_user'): response = backend_instance.create_user( json.dumps(json_response)) if (nature == 'drop_database'): response = backend_instance.drop_database( json_response['database_name']) if (nature == 'drop_table'): response = backend_instance.drop_table( json_response['table_name']) if (nature == 'use'): response = backend_instance.use(json_response['database_name']) #HANDLING ROUTES TO LMD if (nature == 'insert'): response = backend_instance.insert(json.dumps(json_response)) if (nature == 'update'): response = backend_instance.update(json.dumps(json_response)) if (nature == 'delete'): response = backend_instance.delete(json.dumps(json_response)) # HANDLING ROUTES TO LED if (nature == 'select'): response = backend_instance.select(json.dumps(json_response)) connection.send(response.encode())