def edit_dvd(db): title, identity = find_dvd(db, "edit") if title is None: return title = Console.get_string("Title", "title", title) if not title: return cursor = db.cursor() cursor.execute("SELECT dvds.year, dvds.duration, directors.name " "FROM dvds, directors " "WHERE dvds.director_id = directors.id AND " "dvds.id=:id", dict(id=identity)) year, duration, director = cursor.fetchone() director = Console.get_string("Director", "director", director) if not director: return year = Console.get_integer("Year", "year", year, 1896, datetime.date.today().year) duration = Console.get_integer("Duration (minutes)", "minutes", duration, minimum=0, maximum=60*48) director_id = get_and_set_director(db, director) cursor.execute("UPDATE dvds SET title=:title, year=:year, " "duration=:duration, director_id=:director_id " "WHERE id=:identity", locals()) db.commit()
def find_dvd(db, message): message = "(Start of) title to " + message cursor = db.cursor() while True: start = Console.get_string(message, "title") if not start: return (None, None) cursor.execute("SELECT title, id FROM dvds " "WHERE title LIKE ? ORDER BY title", (start + "%",)) records = cursor.fetchall() if len(records) == 0: print("There are no dvds starting with", start) continue elif len(records) == 1: return records[0] elif len(records) > DISPLAY_LIMIT: print("Too many dvds ({0}) start with {1}; try entering " "more of the title".format(len(records), start)) continue else: for i, record in enumerate(records): print("{0}: {1}".format(i + 1, record[0])) which = Console.get_integer("Number (or 0 to cancel)", "number", minimum=1, maximum=len(records)) return records[which - 1] if which != 0 else (None, None)
def retrieve_car_details(previous_license): license = Console.get_string("License", "license", previous_license) if not license: return previous_license, None license = license.upper() ok, *data = handle_request("GET_CAR_DETAILS", license) if not ok: print(data[0]) while True: start = Console.get_string("Start of license", "license") if not start: return previous_license, None start = start.upper() ok, *data = handle_request("GET_LICENSES_STARTING_WITH", start) if not data[0]: print("No licence starts with " + start) continue for i, license in enumerate(data[0]): print("({0}) {1}".format(i + 1, license)) answer = Console.get_integer("Enter choice (0 to cancel)", minimum=0, maximum=len(data[0])) if answer == 0: return previous_license, None license = data[0][answer - 1] ok, *data = handle_request("GET_CAR_DETAILS", license) if not ok: print(data[0]) return previous_license, None break return license, CarTuple(*data)
def __check__(self, no): if no < 0 or len(self.flist) <= no: Console.print_temp("Invalid No.") import time time.sleep(1) return False return True
def find_dvd(db, message): message = "(Start of) title to " + message while True: matches = [] start = Console.get_string(message, "title") if not start: return None for title in db: if title.lower().startswith(start.lower()): matches.append(title) if len(matches) == 0: print("There are no dvds starting with", start) continue elif len(matches) == 1: return matches[0] elif len(matches) > DISPLAY_LIMIT: print("Too many dvds start with {0}; try entering " "more of the title".format(start)) continue else: matches = sorted(matches, key=str.lower) for i, match in enumerate(matches): print("{0}: {1}".format(i + 1, match)) which = Console.get_integer("Number (or 0 to cancel)", "number", minimum=1, maximum=len(matches)) return matches[which - 1] if which != 0 else None
def remove_discrete_record(db): identity = Console.get_integer("Delete record number", "id", minimum=0) if id is None: return ans = Console.get_bool("Remove {0}?".format(identity), "no") if ans: cursor = db.cursor() cursor.execute("DELETE FROM discrete_records WHERE id=?", (identity,)) db.commit()
def add_bookmark(db): url = Console.get_string("URL", "URL") if not url: return if "://" not in url: url = "http://" + url name = Console.get_string("Name", "name") if not name: return db[name] = url db.sync()
def add_dvd(db): title = Console.get_string("Title", "title") if not title: return director = Console.get_string("Director", "director") if not director: return year = Console.get_integer("Year", "year", minimum=1896, maximum=datetime.date.today().year) duration = Console.get_integer("Duration (minutes)", "minutes", minimum=0, maximum=60*48) db[title] = (director, year, duration) db.sync()
def sendGameRequest(connection: 'connection'): s_output = connection[2] s_input = connection[1] string = 'AI_GAME' send_to_server(s_output, string) print('Client: ' + string) serverReply = receive_from_server(s_input) if serverReply == 'READY': newGame = Console.new_game_state() Console.print_board(newGame) print('Server: ' +serverReply) return newGame else: print('GameRequest: ERROR')
def edit_bookmark(db): name = find_bookmark(db, "edit") if name is None: return url = Console.get_string("URL", "URL", db[name]) if not url: return if "://" not in url: url = "http://" + url new_name = Console.get_string("Name", "name", name) db[new_name] = url if new_name != name: del db[name] db.sync()
def interfaceConsole(self): """ Some Comment """ lat = self.lat lng = self.lng zoom = self.zoom size = self.size if myFrame.infile is None: tkMessageBox.showwarning("Open file", "Please Choose A KML file to Open") infile = self.onOpen() else: infile = myFrame.infile if myFrame.outfile is None: tkMessageBox.showwarning("Write KML file", "Please Choose A KML file to write to") outfile = self.saveFileKML() else: outfile = myFrame.outfile if myFrame.outimage is None: tkMessageBox.showwarning("Write Img file", "Please Choose an image file to write to") outimage = self.saveFileImg() else: outimage = myFrame.outimage # if ' ' in infile: infile = '"'+infile+'"' # if ' ' in outimage: outimage = '"'+outimage+'"' # if ' ' in outfile: outfile = '"'+outfile+'"' sampleLine = """-wa -w {} -m {} -v -z {} -c {},{} -s {} {}""".format(outfile, outimage, repr(zoom), repr(lat), repr(lng), repr(size), infile) args = ['-wa', '-w', outfile, '-m', outimage, '-v', '-z', repr(zoom), '-c', repr(lat)+','+ repr(lng), '-s', repr(size), infile] if self.if_extract: args = ['-h'] + args # disable run button, to disallow too many running applications self.run.config(state=DISABLED) self.wd = waitDialog.WaitDialog(350, 100, myFrame.outimage) self.wd.activate() uiobserver = UiObserver(self) imobserver = WaitObserver(self.wd) urlobserver = WaitObserver(self.wd) Console.interface(args, uiobserver, imobserver, urlobserver) self.wd.end() self.log("FINISHED", "\n" + str(self.div_string[0] * ((self.div_string[1]/len(self.div_string[0]))+1))[:self.div_string[1]] + "\n\n") self.run.config(state=NORMAL)
def main(): functions = dict(a=add_dvd, e=edit_dvd, l=list_dvds, r=remove_dvd, i=import_, x=export, q=quit) filename = os.path.join(os.path.dirname(__file__), "dvds.dbm") db = None try: db = shelve.open(filename, protocol=pickle.HIGHEST_PROTOCOL) action = "" while True: print("\nDVDs ({0})".format(os.path.basename(filename))) if action != "l" and 1 <= len(db) < DISPLAY_LIMIT: list_dvds(db) else: print("{0} dvd{1}".format(len(db), Util.s(len(db)))) print() menu = ("(A)dd (E)dit (L)ist (R)emove (I)mport " "e(X)port (Q)uit" if len(db) else "(A)dd (I)mport (Q)uit") valid = frozenset("aelrixq" if len(db) else "aiq") action = Console.get_menu_choice(menu, valid, "l" if len(db) else "a", True) functions[action](db) finally: if db is not None: db.close()
def import_(db): filename = Console.get_string("Import from", "filename") if not filename: return try: tree = xml.etree.ElementTree.parse(filename) except (EnvironmentError, xml.parsers.expat.ExpatError) as err: print("ERROR:", err) return cursor = db.cursor() cursor.execute("DELETE FROM directors") cursor.execute("DELETE FROM dvds") for element in tree.findall("dvd"): get_and_set_director(db, element.get("director")) for element in tree.findall("dvd"): try: year = int(element.get("year")) duration = int(element.get("duration")) title = element.text.strip() director_id = get_director_id(db, element.get("director")) cursor.execute("INSERT INTO dvds " "(title, year, duration, director_id) " "VALUES (?, ?, ?, ?)", (title, year, duration, director_id)) except ValueError as err: db.rollback() print("ERROR:", err) break else: db.commit() count = dvd_count(db) print("Imported {0} dvd{1}".format(count, Util.s(count)))
def main(): functions = dict(a=add_dvd, e=edit_dvd, l=list_dvds, d=list_directors, r=remove_dvd, i=import_, x=export, q=quit) filename = os.path.join(os.path.dirname(__file__), "dvds.sdb") db = None try: db = connect(filename) action = "" while True: count = dvd_count(db) print("\nDVDs ({0})".format(os.path.basename(filename))) if action != "l" and 1 <= count < DISPLAY_LIMIT: list_dvds(db) else: print("{0} dvd{1}".format(count, Util.s(count))) print() menu = ("(A)dd (E)dit (L)ist (D)irectors (R)emove " "(I)mport e(X)port (Q)uit" if count else "(A)dd (I)mport (Q)uit") valid = frozenset("adelrixq" if count else "aiq") action = Console.get_menu_choice(menu, valid, "l" if count else "a", True) functions[action](db) finally: if db is not None: db.close()
def main(): functions = dict(a=add_record, l=list_records, m=list_machines, r=remove_record, i=import_, d=initialize_discrete_table, q=quit) filename = os.path.join(os.path.dirname(__file__), "records.sdb") db = None try: db = connect(filename) action = "" while True: count = record_count(db) print("\nRecords ({0})".format(os.path.basename(filename))) if action != "l" and 1 <= count < DISPLAY_LIMIT: list_records(db) else: print("{0} record{1}".format(count, Util.s(count))) print() menu = ("(A)dd (L)ist (M)achines (R)emove " "(I)mport (D)iscretize (Q)uit" if count else "(A)dd (I)mport (Q)uit") valid = frozenset("almridq" if count else "aiq") action = Console.get_menu_choice(menu, valid, "l" if count else "a", True) functions[action](db) finally: if db is not None: db.close()
def main(): functions = dict(a=all_employee, r=list_report, m=list_manager, q=quit_app) con = None try: # connect to hostName, userName, password, databaseName con = mdb.connect("localhost", "testuser", "test623", "testdb") cur = con.cursor() initDB(con, cur) print("\nManager and his/her reports:\n") all_employee(cur) action = "" while True: print() menu = " (A)llEmployee List(R)eport List(M)anager (Q)uit" action = Console.get_menu_choice(menu, "armq", "q", True) functions[action](cur) except mdb.Error as e: print("Error %d: %s", e.args[0], e.args[1]) sys.exit(1) finally: if con is not None: con.close()
def remove_bookmark(db): name = find_bookmark(db, "remove") if name is None: return ans = Console.get_bool("Remove {0}?".format(db[name]), "no") if ans: del db[name] db.sync()
def remove_dvd(db): title = find_dvd(db, "remove") if title is None: return ans = Console.get_bool("Remove {0}?".format(title), "no") if ans: del db[title] db.sync()
def delete_genre(): get_genres() index = Console.get_integer("Choice index of genre to delete", default=0) data = handle_request("DEL_GENRE", index) if not data[0]: print "ERROR:", data[1] print "Genre successfully deleted." print
def delete_dance(): get_dances() index = Console.get_integer("Choice index of dance to delete", default=0) data = handle_request("DEL_DANCE", index) if not data[0]: print "ERROR:", data[1] print "Dance successfully deleted." print
def start(): Console.show_in_box("QQ Documents Reader\n" "Create By emengjzs\n" "Use For iPhone QQ 2.2 Only\n" "DO NOT USE FOR COMERCIAL PROPOSE", True) print "QQ: " + QQ dbc = DBConnector(QQ) dbc.connect() pc = Processor(dbc) while True: order = raw_input("::") if order == "exit": dbc.disconnect() exit() else: pc.process(order)
def add_dvd(db): title = Console.get_string("Title", "title") if not title: return director = Console.get_string("Director", "director") if not director: return year = Console.get_integer("Year", "year", minimum=1896, maximum=datetime.date.today().year) duration = Console.get_integer("Duration (minutes)", "minutes", minimum=0, maximum=60*48) director_id = get_and_set_director(db, director) cursor = db.cursor() cursor.execute("INSERT INTO dvds " "(title, year, duration, director_id) " "VALUES (?, ?, ?, ?)", (title, year, duration, director_id)) db.commit()
def new_registration(previous_license): license = Console.get_string("License", "license") if not license: return previous_license license = license.upper() seats = Console.get_integer("Seats", "seats", 4, 0) if not (1 < seats < 10): return previous_license mileage = Console.get_integer("Mileage", "mileage", 0, 0) owner = Console.get_string("Owner", "owner") if not owner: return previous_license ok, *data = handle_request("NEW_REGISTRATION", license, seats, mileage, owner) if not ok: print(data[0]) else: print("Car {0} successfully registered".format(license)) return license
def remove_dvd(db): title, identity = find_dvd(db, "remove") if title is None: return ans = Console.get_bool("Remove {0}?".format(title), "no") if ans: cursor = db.cursor() cursor.execute("DELETE FROM dvds WHERE id=?", (identity,)) db.commit()
def choixParametresJeu(): """ Permet l'affichage d'un menu de départ """ print "###############################################" print "## SOKOBAN CONSOLE ##" print u"## Par Timothée C. & Jérémy G. ##" print "###############################################" print print u"Démarrer une nouvelle partie avec la touche [n]" print u"Recharger une partie existante avec la touche [e]" print u"Quitter le jeu avec la touche [q]" print u"Appuyez sur une touche pour executer une des actions listées ci-dessus" touche=Console.getkey() while touche not in(['n','e','q']): print u"Appuyez sur une touche pour executer une des actions listées ci-dessus" touche=Console.getkey() return touche
def find_bookmark(db, message): message = "Number of bookmark to " + message number = Console.get_integer(message, "number", minimum=0, maximum=len(db)) if number == 0: return None number -= 1 for i, name in enumerate(sorted(db, key=str.lower)): if i == number: return name
def retrieve_car_details(previous_license): license = Console.get_string("License", "license", previous_license) if not license: return previous_license, None license = license.upper() ok, *data = handle_request("GET_CAR_DETAILS", license) if not ok: print(data[0]) return previous_license, None return license, CarTuple(*data)
def edit_dvd(db): old_title = find_dvd(db, "edit") if old_title is None: return title = Console.get_string("Title", "title", old_title) if not title: return director, year, duration = db[old_title] director = Console.get_string("Director", "director", director) if not director: return year = Console.get_integer("Year", "year", year, 1896, datetime.date.today().year) duration = Console.get_integer("Duration (minutes)", "minutes", duration, minimum=0, maximum=60*48) db[title] = (director, year, duration) if title != old_title: del db[old_title] db.sync()
def list_dvds(db): start = "" if len(db) > DISPLAY_LIMIT: start = Console.get_string("List those starting with " "[Enter=all]", "start") print() for title in sorted(db, key=str.lower): if not start or title.lower().startswith(start.lower()): director, year, duration = db[title] print("{0} ({1}) {2} minute{3}, by {4}".format( title, year, duration, Util.s(duration), director))
def list_dvds(db): start = "" if len(db) > DISPLAY_LIMIT: start = Console.get_string("List those starting with " "[Enter=all]", "start") print() for title in sorted(db, key=str.lower): if not start or title.lower().startswith(start.lower()): director, year, duration = db[title] print("{title} ({year}) {duration} minute{0}, by " "{director}".format(Util.s(duration), **locals()))
def list_discrete_machines(db): cursor = db.cursor() cursor.execute("SELECT COUNT(*) FROM discrete_machines") count = cursor.fetchone()[0] sql = "SELECT id, name, freq, memory FROM discrete_machines" start = None if count > DISPLAY_LIMIT: start = Console.get_integer("List those starting with " "[Enter=1]", "start=1") sql += " WHERE id LIKE ?" sql += " ORDER BY id" print() if start is None: cursor.execute(sql) else: cursor.execute(sql, (start + "%",)) for discrete_fields in cursor: print("{0[0]}: {0[1]} {0[2]} {0[3]}".format(discrete_fields))
def ShowMainMenu(index=0): Console.Clear() color = Fore.WHITE welcome = f"{color}{Enum.Welcome}{color}" controls = f"{color}{Enum.Controls}{color}" strings = [] strings.append(welcome.center(50)) strings.append(controls.center(50)) strings.append("\n") for i in range(len(Enum.MenuOptions)): if i == index: color = Fore.GREEN strings.append(f"> {color}{Enum.MenuOptions[i]}{color}".center(50)) color = Fore.WHITE else: strings.append(f"{color}{Enum.MenuOptions[i]}{color}".center(50)) strings.append("") print("\n".join(strings))
def list_directors(db): cursor = db.cursor() cursor.execute("SELECT COUNT(*) FROM directors") count = cursor.fetchone()[0] sql = "SELECT name FROM directors" start = None if count > DISPLAY_LIMIT: start = Console.get_string("List those starting with " "[Enter=all]", "start") sql += " WHERE name LIKE ?" sql += " ORDER BY name" print() if start is None: cursor.execute(sql) else: cursor.execute(sql, (start + "%",)) for fields in cursor: print(fields[0])
def app(): console = Console.Console(True) appuifw.app.title = ru("CheckIP") appuifw.app.exit_key_handler = quit global body body = appuifw.app.body = console.text body.color = (255, 0, 0) body.font = "title", 22 slow_print("CheckIP by gauravssnl\n") body.font = "title", 17 body.color = (255, 0, 255) slow_print("Features :\n") body.color = (0, 0, 255) slow_print("---Check Local IP\n") slow_print("---Check Internet IP\n") appuifw.app.menu = [(ru("Check Internet IP"), internetIP), (ru("Check Local IP"), localIP), (ru("About"), about), (ru("Exit"), quit)]
def list_discrete_records(db): cursor = db.cursor() sql = ("SELECT discrete_records.id, discrete_records.input_size, discrete_records.exec_time," "discrete_machines.name, discrete_machines.freq, discrete_machines.memory FROM " "discrete_records, discrete_machines WHERE discrete_records.machine_id = discrete_machines.id") start = None if record_count(db) > DISPLAY_LIMIT: start = Console.get_integer("List those starting with " "[Enter=1]", "start=1") sql += " AND discrete_records.id LIKE ?" sql += " ORDER BY discrete_records.id" print() if start is None: cursor.execute(sql) else: cursor.execute(sql, (start + "%",)) for discrete_record in cursor: print("{0[0]}: {0[1]} {0[2]} {0[3]} {0[4]} {0[5]} ".format( discrete_record))
def list_records(db): cursor = db.cursor() sql = ("SELECT records.id, records.input_size, records.exec_time, machines.name, " "machines.freq, machines.memory FROM records, machines " "WHERE records.machine_id = machines.id") start = None if record_count(db) > DISPLAY_LIMIT: start = Console.get_integer("List those starting with " "[Enter=1]", "start=1") sql += " AND records.id LIKE ?" sql += " ORDER BY records.id" print() if start is None: cursor.execute(sql) else: cursor.execute(sql, (start + "%",)) for record in cursor: print("{0[0]}: {0[1]} {0[2]} sec on {0[3]} @{0[4]} GHz {0[5]} MB".format( record))
def main(): functions = dict(a=add_bookmark, e=edit_bookmark, l=list_bookmarks, r=remove_bookmark, q=quit) filename = os.path.join(os.path.dirname(__file__), "bookmarks.dbm") db = None try: db = shelve.open(filename, protocol=pickle.HIGHEST_PROTOCOL) action = "" while True: print("\nBookmarks ({0})".format(os.path.basename(filename))) list_bookmarks(db) print() menu = "(A)dd (E)dit (L)ist (R)emove (Q)uit" action = Console.get_menu_choice(menu, "aelrq", "l" if len(db) else "a", True) functions[action](db) finally: if db is not None: db.close()
def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.SetSize((800, 600)) self.panel_1 = wx.Panel(self, wx.ID_ANY) self.fig = Figure() Console.ax = self.fig.add_subplot(111) Console.ax.grid(True) Console.ax.set_title("Osciloscopio virtual con PIC18F2550") Console.ax.set_ylim(-1, 6) Console.ax.set_xlim(0, 100) Console.ax.set_ylabel('Voltaje [V]') Console.ax.set_xlabel('Muestras') #plt.ylim(-1,6) #plt.grid() self.Osciloscopio_Canvas = FigureCanvas(self.panel_1, wx.ID_ANY, self.fig) self.Osciloscopio_Canvas.set_window_title( "Osciloscopio virtual con PIC18F2550") self.cmb_baud = wx.ComboBox(self.panel_1, wx.ID_ANY, choices=[ "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400", "4800", "9600", "19200", "38400", "57600", "115200", "921600" ], style=wx.CB_DROPDOWN) self.cmb_port = wx.ComboBox(self.panel_1, wx.ID_ANY, choices=Console.serial_ports(), style=wx.CB_DROPDOWN) self.button_plot = wx.Button(self.panel_1, wx.ID_ANY, "Graficar") self.button_exit = wx.Button(self.panel_1, wx.ID_ANY, "Parar") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.on_button_plot, self.button_plot) self.Bind(wx.EVT_BUTTON, self.on_button_stop, self.button_exit)
def find_object_px(base_file, obj_file): """ This method will be find the height of the found object in pixels to be used essential to every distance method `return` the object height in pixels, as determined by the Image_merge module via console """ consolas = Console.Console('Output/ImF.png') consolas.do_extractremote(None) consolas.do_redhighlight(None) consolas.do_colordiff(120) consolas.do_merge(base_file) consolas.do_merge(obj_file) consolas.do_gengroups(None) consolas.do_countsortgroups(None) first = consolas.groups.first() return first.height
def __init__(self, parent): super(CInterface, self).__init__() self.m_Parent = parent self.m_CurSelectColor = 0 self.m_RowCnt = 0 self.m_ColCnt = 0 self.m_EntranceColor = 0 self.m_ExitColor = 0 self.m_BlockColor = 0 try: self.LayoutInit() self.InitGraphLayout() self.StatusBarInit() except Exception as e: Console.ConsoleFree() import traceback traceback.print_exc()
def import_xml(db): filename = Console.get_string("Import from", "filename") if not filename: return try: tree = xml.etree.ElementTree.parse(filename) except (EnvironmentError, xml.parsers.expat.ExpatError) as err: print("ERROR: ", err) return db.clear() for element in tree.findall("bookmark"): try: name = element.get('name') address = element.text db[name] = address except ValueError as err: print("ERROR: ", err) return print("Imported {0} bookmark{1}".format(len(db), Util.s(len(db)))) db.sync()
def ConnectVM(self, p_id, vm): key = vm.name try: vmtype = vms_dict[key] Type = vmtype['vmtype'] except: Type = "UNKNOWN" Logger.info("VM is a %s type", Type) if Type == 'JSP' or Type == 'UNKNOWN': dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...') thread = Console.LaunchThread(p_id, vm, Type, dlg) thread.start() if dlg.ShowModal() == wx.ID_CANCEL: thread.stop() else: thread.join() elif Type == 'RDP': RDP = RDPLoginDialog.RDPLoginDialog(vm, Type) RDP.ShowModal()
def show_zones(self, *a): """show firewall zones Produces a list of firewall zones""" self.checkFirewall() zones = self.config.Shorewall.get('zones', {}) if len(zones) < 1: print "No zones found" return else: print "| Zone Name | Policy | Log Target | Interfaces |" print "|-----------+--------+----------------+-------------------------------------|" for zone, zd in zones.items(): print "| % 9s | % 6s | % 14s | % 35s |" % ( str(zone), str(zd['policy']), str(zd['log']), str.join( ' ', [Console.renameIfaces(str(i)) for i in zd['interfaces']]).rstrip()) print "+-----------+--------+----------------+-------------------------------------+"
def reset(self): self.shakeScreen = resources.screen self.screen = self.shakeScreen.copy() resources.screen_copied = self.screen self.background = Background(self.screen) self.screenShaker = ScreenShaker() self.OPACITY = 250 self.activeRegions = {} self.allPackages = {} self.allPackageNames = [] self.allShields = [] self.messages = [] self.MAX_SHIP_HP = 100 self.shipHp = 100 self.MAX_SHIP_POWER = 1000 self.ship_power = 1000 self.ship_reload = 0 self.SHIP_MAX_PROGRESS = 2000 self.ship_progress = 0 self.night_opacity = self.OPACITY #self.cannon_accuracy = 3 self.console = Console.Console(self.screen) self.addMessage( "Once upon a time, there was a woman named Wax Chug da Gwad. She had a solar powered ship. However, she was far from home and the solar panels sucked. And tentacle monsters appeared. Help Wax Chug get home." ) resources.time = Time() self.time = resources.time #tells Time to call "toggleDay" when 6:00 happens self.time.setToggleDayListener(self, '6:00') self.day = False self.night = resources.all_sprites["night.png"] self.monsterList = MonsterList() self.initializePackages()
def config_add_zone(self, zoneName=None, policy=None, logDetails=None, *a): """config firewall add <zone name> <policy(ACCEPT|DROP)> <log|NONE> [interfaces] Adds a zone to the firewall, if you would like to specify no log specify None To specify multiple interfaces seperate with a :""" if not zoneName or not policy: print "Error: zone name and a policy are required" self.genAllDoc('config') return matchZonePolicy = self.regZonePolicy.match(str(policy)) if not matchZonePolicy: print "ERROR: Invalid policy specified should be ACCEPT or DROP" self.genAllDoc('config') return k = self.config.Shorewall # Make a zone def if there isn't one if not k.get('zones', None): k['zones'] = {} if str(logDetails).upper() == 'NONE': logDetails = None if zoneName in k.get('zones', {}): del k['zones'][zoneName] if a: ifs = Console.fixIfaces(str.join(' ', a)).split(':') else: ifs = [] zone = { 'policy': policy.upper(), 'log': logDetails or '', 'interfaces': ifs } k['zones'][zoneName] = zone self.config.Shorewall = k print "Zone has been added successfully"
def show_interface(self, *a): """show net int[erface][: interfaces] Displays information regarding a particular ip network interface (optional interface parameter list).""" # Display interfaces showifs = [str(i).lower() for i in a] r = os.popen('ip addr') current = "" ifs = {} for i in r: l = i.strip('\n').strip() if "<" in l: current = Console.renameIfaces(l.split()[1].strip(':')) ifs[current] = {'ip': [], 'ip6': [], 'up': False} if "link/" in l: try: ifs[current]['mac'] = l.split()[1] except: # No mac? ifs[current]['mac'] = None if "inet " in l: ifs[current]['ip'].append(l.split()[1]) if "inet6" in l and not "scope link" in l: # Inet6 but not link-local ifs[current]['ip6'].append(l.split()[1]) if "valid_lft" in l: ifs[current]['up'] = True for i, v in ifs.items(): if showifs: if i.lower() not in showifs: continue print "Interface: ", i print " State: ", v['up'] and "Connected" or "No Link" print " MAC : ", v['mac'] for j in v['ip']: print " IPv4 : ", j for j in v['ip6']: print " IPv6 : ", j print ""
def import_(db): filename = Console.get_string("Import from", "filename") if not filename: return try: tree = xml.etree.ElementTree.parse(filename) except (EnvironmentError, xml.parsers.expat.ExpatError) as err: print("ERROR:", err) return cursor = db.cursor() cursor.execute("DELETE FROM machines") cursor.execute("DELETE FROM records") for element in tree.findall("record"): try: machine_freq = float(element.get("machine_freq")) machine_memory = int(element.get("machine_memory")) get_and_set_machine(db, element.get("machine_name"), machine_freq, machine_memory) except ValueError as err: db.rollback() print("ERROR:", err) break for element in tree.findall("record"): try: input_size = int(element.get("input_size")) exec_time = float(element.get("exec_time")) machine_id = get_machine_id(db, element.get("machine_name")) cursor.execute( "INSERT INTO records " "(input_size, exec_time, machine_id) " "VALUES (?, ?, ?)", (input_size, exec_time, machine_id)) except ValueError as err: db.rollback() print("ERROR:", err) break else: db.commit() count = record_count(db) print("Imported {0} record{1}".format(count, Util.s(count)))
def create(self,set): def lines(slice): self.xpos = 0 draw = ImageDraw.Draw(self.img) for c in slice[0]: if c == 'A': draw.line((self.xpos,self.ypos, self.xpos+self.dim[self.type]['w']/3,self.ypos), fill=0, width=75) self.xpos += self.dim[self.type]['w']/3 self.ypos += 150 count = 0 display = Console.Progress(len(set)) for g in set: self.type = self.folders[str(len(g))] self.setup() for elem in g: lines(elem) self.img.save('img/'+self.type+'/'+str(count).rjust(5,'0')+'.png') count += 1 display.update(count,self.type)
def main(): functions = dict(p=add_bookmark, u=edit_bookmark, v=list_bookmarks, o=remove_bookmark, k=quit) filename = os.path.join(os.path.dirname(__file__), "bookmarks.dbm") db = None try: db = shelve.open(filename, protocol=pickle.HIGHEST_PROTOCOL) action = "" while True: print("\nZáložky ({0})".format(os.path.basename(filename))) list_bookmarks(db) print() menu = "(P)řidat (U)pravit (V)ypsat (O)odstranit (K)onec" action = Console.get_menu_choice(menu, "puvok", "v" if len(db) else "p", True) functions[action](db) finally: if db is not None: db.close()
def show_snat(self, *a): """ show firewall snat Displays a list of SNAT rules""" self.checkFirewall() #SNAT rules snat = self.config.Shorewall.get('snat', []) if len(snat) < 1: print "No snat rules found" return else: print " RN| Source IP | Ext Int | Internal IP | Any Interface | Use Internal |" print " |-----------------+----------+-----------------+---------------+---------------|" ruleIndex = 0 for ru in snat: rule = ru.split() #Fix interfaces rule[1] = Console.renameIfaces(rule[1]) print "% 4d| % 15s | % 8s | % 15s | % 13s | % 13s |" % ( ruleIndex, rule[0], rule[1], rule[2], rule[3], rule[4]) ruleIndex += 1 print " +-----------------+----------+-----------------+---------------+---------------+"
def __init__(self): self.mode = MODE_COMMANDS # Other is MODE_USERPLAY where you are in control of the hero if CURSES: # Initialize curses cbreak() noecho() # Initialize the Kernel Kernel() # Set's up the socket NethackSock() # Socket observers SocketLogger( ) # This should be before other stuff for easier debugging FramebufferParser() DGLParser() # Stuff Console() Cursor() Dungeon() Hero() MonsterSpoiler() ItemDB() Inventory() # AI Personality() Senses() Pathing() # Brains curBrain = TestBrain() Kernel.instance.Personality.setBrain(curBrain) # Default brain
def list_dvds(db): cursor = db.cursor() sql = ('SELECT dvds.title, dvds.year, dvds.duration, ' 'directors.name FROM dvds, directors ' 'WHERE dvds.director_id = directors.id') start = None if dvd_count(db) > DISPLAY_LIMIT: start = Console.get_string('List those starting with [Enter=all]', 'start') sql += ' AND dvds.title LIKE ?' sql += ' ORDER BY dvds.title' print() if start is None: cursor.execute(sql) else: cursor.execute(sql, (start + '%', )) print('{:<20} {:<10} {:<20} {:<20}'.format('Title', 'Year', 'Duration (minutes)', 'Director')) print('-' * 80) for record in cursor: print( f'{record[0]:<20} {record[1]:<10} {record[2]:<20} {record[3]:<20}')
def import_(db): filename = Console.get_string('Import from', 'filename') if not filename: return try: tree = xml.etree.ElementTree.parse(filename) except (EnvironmentError, xml.parsers.expat.ExpatError) as err: print('ERROR:', err) return db.clear() for element in tree.findall('dvd'): try: year = int(element.get('year')) duration = int(element.get('duration')) director = element.get('director') title = element.text.strip() db[title] = (director, year, duration) except ValueError as err: print('ERROR:', err) return print(f'Imported {len(db)} dvd{Util.s(len(db))}') db.sync()
def main(): functions = dict(a=add_bookmark, e=edit_bookmark, l=list_bookmarks, r=remove_bookmark, i=import_xml, x=export_xml, q=quit) filename = os.path.join(os.path.dirname(__file__), "bookmarks.dbm") db = None try: db = shelve.open(filename, protocol=pickle.HIGHEST_PROTOCOL) action = '' while True: print("\nBookmarks: ({0})".format(os.path.basename(filename))) if action != 'l' and 1 <= len(db) < DISPLAY_LIMIT: list_bookmarks(db) else: print("{0} bookmark{1}\n".format(len(db), Util.s(len(db)))) menu = ("(A)dd (E)dit (L)ist (R)emove (I)import" "e(X)port (Q)uit" if len(db) else "(A)dd (I)mport (Q)uit") valid = frozenset("aelirxq" if len(db) else "aiq") action = Console.get_menu_choice(menu, valid, 'l' if len(db) else 'a', True) functions[action](db) finally: if db is not None: db.close()
def OnBtnOKButton(self, event): username = self.Input_username.GetValue() password = self.Input_password.GetValue() if Setting.getPublic().lower() == "true": try: image_lists = havclient.image_list(FirstUser['firstuser']) for i in image_lists: if i.name == u'Port': image_info = havclient.data(FirstUser['firstuser'], i.id) break havclient.download_templet(image_info) Logger.info("Download status:Download hosts successful!") except: Logger.info("Download status:Download hosts unsuccessful!") else: pass if username == '' or password == '': Util.MessageBox(self, u'缺少用户名或密码!', u'错误', wx.OK | wx.ICON_ERROR) return else: Setting.setUser(username) Setting.setCipher(password) Setting.save() dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...') thread = Console.LaunchThread(self.vm.tenant_id, self.vm, self.Type, dlg) thread.start() if dlg.ShowModal() == wx.ID_CANCEL: thread.stop() else: thread.join() self.Destroy() event.Skip()
def SearchBy(selection): persons = None Console.SearchByInputInfo(selection) if selection == Enum.SearchByName: name = Console.GetPersonName(True) persons = Data.GetPersonsWith(selection, name) elif selection == Enum.SearchByCity: city = Console.GetCityName(True) persons = Data.GetPersonsWith(selection, city) elif selection == Enum.SearchByNumber: number = Console.GetPhoneNumber(True) persons = Data.GetPersonsWith(selection, number) if len(persons) > 0: for p in persons: Console.PrintPerson(p) else: Console.IsntSuchAContact(Enum.SearchOptionsClear[selection])