def main(): try: patient = connect.get_current('Patient') case = connect.get_current('Case') examination = connect.get_current("Examination") patient_db = connect.get_current('PatientDB') plan = connect.get_current('Plan') beamset = connect.get_current('BeamSet') except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) UserInterface.WarningBox(message) UserInterface.WarningBox( 'This script requires a patient, case, and beamset to be loaded') sys.exit( 'This script requires a patient, case, and beamset to be loaded') # Capture the current list of ROI's to avoid saving over them in the future targets = so.find_targets(case) for t in targets: patient.Set2DvisualizationForRoi(RoiName=t, Mode='filled') max_dose = find_max_dose_in_plan(examination=examination, case=case, plan=plan) try: ref_dose = beamset.Prescription.PrimaryDosePrescription.DoseValue except AttributeError: ref_dose = max_dose logging.info( 'Neither prescription nor max dose are defined in the plan. Setting to default max_dose' ) isodose_reconfig(case=case, ref_dose=ref_dose, max_dose=max_dose)
def main(): # UW Inputs # If machines names change they need to be modified here: institution_inputs_machine_name = ['TrueBeamSTx', 'TrueBeam'] institution_inputs_sites = ['Liver', 'Lung', 'Breast'] institution_inputs_motion = ['MIBH', 'MEBH', 'Free-Breathing'] status = UserInterface.ScriptStatus(steps=[ 'SimFiducials point declaration', 'Enter Plan Parameters', 'Make plan for dry run', 'Confirm iso placement' ], docstring=__doc__, help=__help__) try: patient = connect.get_current('Patient') case = connect.get_current("Case") examination = connect.get_current("Examination") patient_db = connect.get_current('PatientDB') except: UserInterface.WarningBox( 'This script requires a patient, case, and exam to be loaded') sys.exit('This script requires a patient, case, and exam to be loaded') # Capture the current list of ROI's to avoid saving over them in the future rois = case.PatientModel.StructureSets[examination.Name].RoiGeometries # Capture the current list of POI's to avoid a crash pois = case.PatientModel.PointsOfInterest # Find all targets plan_targets = [] for r in case.PatientModel.RegionsOfInterest: if r.OrganData.OrganType == 'Target': plan_targets.append(r.Name)
def train(model, optimizer, epoch, train_loader, scheduler=None, c_confines=None): model.train() if c_confines is not None: c_step_size = (c_confines[1] / c_confines[0])**(1.0 / C_STEPS_AMOUNT) when_to_step = math.floor(len(train_loader) / C_STEPS_AMOUNT) for corrEpoch in range(0, epoch): model.quantization_layer.c = c_confines[0] if scheduler is not None: scheduler.step() for batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data.float()), Variable(target.float()) optimizer.zero_grad() output = model(data) loss = criterion(output.view(-1, 1), target.view(-1, 1)) loss.backward() optimizer.step() if c_confines is not None and batch_idx % when_to_step == 0: if model.quantization_layer.c * c_step_size < c_confines[1]: model.quantization_layer.c *= c_step_size if batch_idx % 10 == 0: Ui.train_iteration(model, corrEpoch, epoch, batch_idx, data, train_loader, loss, c_confines)
def main(): print('Starting FDSystem') # Database credentials. LOCAL_DATABASE_NAME = 'CSC-450_FDS' LOCAL_DATABASE_PASSWORD = '******' database = Templates.TemplateDatabase(LOCAL_DATABASE_NAME, LOCAL_DATABASE_PASSWORD) database.connect() templates = {'edge': {}, 'foreground': {}} template_characteristics = templates.keys() template_types = ['upright', 'falling', 'sitting', 'lying'] for template_characteristic in template_characteristics: for template_type in template_types: templates[template_characteristic][template_type] = [] if database.connected(): templates = database.load_templates(templates) else: templates = Templates.loadTemplatesLocally() edge_classifier = HumanStateClassifier.KNeighborsClassifier( templates['edge'], k=20) foreground_classifier = HumanStateClassifier.KNeighborsClassifier( templates["foreground"], k=20) UserInterface.systemUserInterface( templates, database, edgeClassifier=edge_classifier, foregroundClassifier=foreground_classifier)
def main(): season = UI.UserSeason() week = UI.UserWeek() TMTNumber = UI.UserTMTNumber() #season = 1 #week = 7 #TMTNumber = 7 UpdateNewPlayerMains(season, week, TMTNumber) UpdateTags(season, week)
def main(): season = UI.UserSeason() week = UI.UserWeek() slug = UI.UserSlug() #season = 1 #week = 8 #slug = 'training-mode-tournaments-8' ids = getIDs(slug) outputPlayers(ids, season, week)
def main(): UI.PrintRankWelcomeMessage() choice = UI.rankChoice() season = UI.UserSeason() week = UI.UserWeek() #choice = 2 #season = 1 #week = 3 CreateDirectories(season) # Input files WSL = f'Data/Season{season}/WeeklyLadderBracket/S{season}W{week}WeeklyScoresLadder.csv' WSB = f'Data/Season{season}/WeeklyLadderBracket/S{season}W{week}WeeklyScoresBracket.csv' # It combines the results of Ladders and Bracket WeeklyResults = f'Data/Season{season}/Debug/S{season}W{week}WeeklyResults.csv' oldFeatures = f'Data/Season{season}/Records/S{season}W{week - 1}Features.csv' Features = f'Data/Season{season}/Records/S{season}W{week}Features.csv' oldPlacements = f'Data/Season{season}/Records/S{season}W{week - 1}Placements.csv' Placements = f'Data/Season{season}/Records/S{season}W{week}Placements.csv' # Points for that week's ladder WeeklyRankLadder = f'Data/Season{season}/Debug/S{season}W{week}WeeklyRankLadder.csv' WeeklyRank = f'Data/Season{season}/Debug/S{season}W{week}WeeklyRank.csv' oldRankRecords = f'Data/Season{season}/Records/S{season}W{week - 1}RankRecords.csv' RankRecords = f'Data/Season{season}/Records/S{season}W{week}RankRecords.csv' oldPastPoints = f'Data/Season{season}/Records/S{season}W{week - 1}PastPoints.csv' PastPoints = f'Data/Season{season}/Records/S{season}W{week}PastPoints.csv' # These three will go on the website WebWLR = f'Data/Season{season}/Website/S{season}W{week}WebsiteWeeklyLadderRank.csv' # Ladders and Bracket Ranks WebWR = f'Data/Season{season}/Website/S{season}W{week}WebsiteWeeklyRank.csv' # Rank for the entire season WebTR = f'Data/Season{season}/Website/S{season}W{week}WebsiteTotalRanks.csv' if choice == 1: RankLadder(WSL, WeeklyRankLadder) WebsiteWeeklyRank(WeeklyRankLadder, WebWLR) else: CreateWeeklyResults(WSL, WSB, WeeklyResults, week) UpdateTiers(WeeklyResults, oldFeatures, Features, week) UpdatePlacements(WeeklyResults, oldPlacements, Placements, week) RankWeekly(WeeklyResults, WeeklyRank) RankSeason(Features, Placements, week) ChangeRank(Features, oldRankRecords, week, RankRecords) UpdatePoints(Features, oldPastPoints, PastPoints, week) WebsiteWeeklyRank(WeeklyRank, WebWR) WebsiteTotalRank(Features, RankRecords, Placements, WebTR)
def main(): # Start Comminucation Communication.init() # Pause (2 Seconds) # time.sleep(2) # Start User Interface UserInterface.startDisplay()
def main(): # Get current patient, case, and exam try: patient = connect.get_current('Patient') case = connect.get_current('Case') exam = connect.get_current('Examination') patient.Save() except Exception: UserInterface.WarningBox('This script requires a patient to be loaded') sys.exit('This script requires a patient to be loaded') # Start timer tic = time.time() # Start script status status = UserInterface.ScriptStatus(steps=['Enter plan information for TPO', 'Clean up structure list', 'Approve structures', 'Initialize plan and beamsets', 'Set clinical goals', 'Add planning goals', 'Generate TPO'], docstring=__doc__, help=__help__) # Display input dialog box for TPO status.next_step(text='In order to approve the plan and create a TPO, please fill out the displayed form ' + 'with information about the plan. Once completed, click Continue.') tpo = UserInterface.TpoDialog(patient=patient, title='TPO Dialog', match=0.6, rx=3, priority=priority) tpo.load_protocols(os.path.join(os.path.dirname(__file__), protocol_folder, institution_folder)) response = tpo.show(case=case, exam=exam) if response == {}: status.finish('Script cancelled, inputs were not supplied') sys.exit('Script cancelled') # Re-name/organize structures based on TPO form status.next_step(text='The structures are now being renamed and organized based on your input...') changes = 0 for roi in case.PatientModel.RegionsOfInterest: approved = False for a in case.PatientModel.StructureSets[exam.Name].ApprovedStructureSets: try: if a.ApprovedRoiStructures[roi.Name].OfRoi.RoiNumber > 0 and a.Review.ApprovalStatus == 'Approved': approved = True logging.debug('Structure {} was approved by {} and therefore will not be modified'. format(roi.Name, a.Review.ReviewerName)) break except Exception: logging.debug('Structure {} is not list approved by {}'.format(roi.Name, a.Review.ReviewerName))
def main(): season = UI.UserSeason() week = UI.UserWeek() #season = 1 #week = 8 credentials = getClient() updateWeeklyFiles(credentials, season, week) time.sleep(50) updateRanks(credentials, season, week) time.sleep(50) updatePoints(credentials, season, week)
def test_passing_gradient(model): model.eval() test_loss = 0 for batch_idx, (data, target) in enumerate(testLoader): data, target = Variable(data.float()), Variable(target.float()) output = model(data) # sum up batch loss test_loss += criterion(output.view(-1, 1), target.view(-1, 1)) Ui.test_iteration(model.modelname, batch_idx, data, testLoader) test_loss /= (len(testLoader.dataset) / BATCH_SIZE) return test_loss.detach().numpy()
def main(): UI.PrintArmadaNumberWelcomeMessage() choice = UI.ArmadaGeneralOption() season = UI.UserSeason() week = UI.UserWeek() #choice = 2 #season = 1 #week = 6 CreateDirectories(season) if choice == 1: # Collect Player Set from Smash.gg slug = UI.UserSlug() #slug = 'training-mode-tournaments-6' info = CTData.get_event_info(slug) CombineSetData(info, season, week) SetDataWithSmashTag(season, week) elif choice == 2: # Find Armada Number SmashTag, SmasherID = findBestRankedPlayer(season, week) Armada = UI.findArmada(SmashTag, SmasherID) ArmadaSolver(Armada, season, week) else: # Collect Player Sets and Find Armada Number slug = UI.UserSlug() info = CTData.get_event_info(slug) CombineSetData(info, season, week) SetDataWithSmashTag(season, week) SmashTag, SmasherID = findBestRankedPlayer(season, week) Armada = UI.findArmada(SmashTag, SmasherID) ArmadaSolver(Armada, season, week)
def main(): # Get current patient, case, and machine DB machine_db = connect.get_current('MachineDB') try: patient = connect.get_current('Patient') case = connect.get_current('Case') patient.Save() except Exception: UserInterface.WarningBox('This script requires a patient to be loaded') sys.exit('This script requires a patient to be loaded') # Start script status status = UserInterface.ScriptStatus(steps=[ 'Verify CT density table and external are set', 'Enter script runtime options' ], docstring=__doc__, help=__help__) # Confirm a CT density table, boxes, and external contour was set status.next_step( text= 'Prior to execution, the script will make sure that a CT density table, External, ' + 'and Box_1/Box_2 contours are set for the current plan. Also, at least one contour must be ' + 'overridden to water.') time.sleep(1) examination = connect.get_current('Examination') if examination.EquipmentInfo.ImagingSystemReference is None: connect.await_user_input( 'The CT imaging system is not set. Set it now, then continue the script.' ) patient.Save() else: patient.Save() external = False bounds = [-30, 30, 0, 40, -30, 30] for r in case.PatientModel.RegionsOfInterest: if r.Type == 'External': external = True b = case.PatientModel.StructureSets[ examination.Name].RoiGeometries[r.Name].GetBoundingBox() bounds = [b[0].x, b[1].x, b[0].y, b[1].y, b[0].z, b[1].z]
def main(): import connect import UserInterface import sys plan = connect.get_current("Plan") beam_set = connect.get_current( "BeamSet") # for the currently selected beam set QA_Plan_Name = beam_set.DicomPlanLabel + "QA" try: patient = connect.get_current('Patient') case = connect.get_current('Case') exam = connect.get_current('Examination') plan = connect.get_current('Plan') beamset = connect.get_current("BeamSet") except Exception: UserInterface.WarningBox( 'This script requires a Beam Set to be loaded') sys.exit('This script requires a Beam Set to be loaded') # Click magic ui = connect.get_current('ui') ui.TitleBar.MenuItem['QA Preparation'].Button_QA_Preparation.Click() try: beamset.CreateQAPlan(PhantomName="50cm Cube_2", PhantomId="50cm Cube", QAPlanName=QA_Plan_Name, IsoCenter={ 'x': 0, 'y': -30, 'z': 25 }, DoseGrid={ 'x': 0.25, 'y': 0.25, 'z': 0.25 }, GantryAngle=0, CollimatorAngle=None, CouchAngle=0, ComputeDoseWhenPlanIsCreated=True, NumberOfMonteCarloHistories=500000) except Exception: UserInterface.WarningBox('QA Plan failed to create') sys.exit('QA Plan failed to create')
def main(): """ Function will take the optional input of the protocol file name :return: """ filename = None status = UserInterface.ScriptStatus(steps=[ 'Finding correct protocol', 'Matching Structure List', 'Getting target Doses', 'Adding Goals' ], docstring=__doc__, help=__help__) protocol_folder = r'../protocols' institution_folder = r'UW' path_protocols = os.path.join(os.path.dirname(__file__), protocol_folder, institution_folder) # Get current patient, case, exam, and plan # note that the interpreter handles a missing plan as an Exception try: patient = connect.get_current("Patient") except SystemError: raise IOError("No Patient loaded. Load patient case and plan.") try: case = connect.get_current("Case")
def main(): #url = input("Enter the url of blog: ") app = UI.App() url = str(app.returnURL()) print("URL = " + str(url) + "\n------") posts = ws.scrapeBlog(url) print("Scrapingok \n------") for post in posts: print("into the loop") filename = ws.scrapePost(post) #path = input("Enter the name of the file: ") #The League of Extraordinary Gentlemen – Akaash Preetham text = dr.readDoc(filename) #text = input("Enter text here at main: ") #sortedWords = wc.countWords(text) #for word in sortedWords: # print(str(word[0]) + '-' + str(word[1])) #wordcount = wc.countWords(text) #dv.visualizeData(wordcount) dv.visualizeData(text, filename)
def init_ui(self): """ Main application setup :return: """ self.master.title() self.pack(fill=BOTH, expand=1) self.user_interface = UserInterface(self.root)
def init(data): data.background = Background(data) data.userInterface = UserInterface(data) data.userAircraft = UserAircraft(data) data.userLaserCollection = UserLaserCollection(50, data) data.specialEffectCollection = SpecialEffectCollection(150, data) data.enemyShipCollection = EnemyShipCollection(30, data) data.enemyLaserCollection = EnemyLaserCollection(100, data)
def test_collectSpeed(self): legalSpeed = '4' legalAnswer = 4.0 illegalSpeed = 'u45' interface = UserInterface.UserInterface() with mock.patch("builtins.input", return_value=legalSpeed): interface.collectSpeed() self.assertEqual(interface.infoPacket.getSpeed(), legalAnswer) with mock.patch("builtins.input", return_value=illegalSpeed): self.assertRaises(SystemExit, interface.collectSpeed)
def test_collectDuration(self): legalDuration = '11' legalAnswer = 11 illegalDuration = 'uwu' interface = UserInterface.UserInterface() with mock.patch("builtins.input", return_value=legalDuration): interface.collectDuration() self.assertEqual(interface.infoPacket.getDuration(), legalAnswer) with mock.patch("builtins.input", return_value=illegalDuration): self.assertRaises(SystemExit, interface.collectDuration)
def test_collectStartPoint(self): legalPoint = '6 4' legalAnswer = (6, 4) illegalPoint = '64' interface = UserInterface.UserInterface() with mock.patch("builtins.input", return_value=legalPoint): interface.collectStartPoint() self.assertEqual(interface.infoPacket.getStartPoint(), legalAnswer) with mock.patch("builtins.input", return_value=illegalPoint): self.assertRaises(SystemExit, interface.collectStartPoint)
def test_collectMovePattern(self): legalOption = '1' legalAnswer = MovePattern.ZOOM illegalOption = '8' interface = UserInterface.UserInterface() with mock.patch("builtins.input", return_value=legalOption): interface.collectMovePattern() self.assertEqual(interface.infoPacket.getMovePattern(), legalAnswer) with mock.patch("builtins.input", return_value=illegalOption): self.assertRaises(SystemExit, interface.collectMovePattern)
def test_simple_interface(check_list=True): if check_list: inputs = ['1', '2', '3', '4'] color_inputs = ['Red', 'Blue', 'Green', 'Yellow'] quest_inputs = [ 'To buy an argument.', 'To find the Holy Grail.', 'To beat Confucious in a foot race.' ] name_inputs = [ 'Arthur', 'Tarquin Fin-tim-lin-bin-whin-bim-lim-bus-stop-Ftang-Ftang-Ole-Biscuitbarrel' ] sample_dialog = UserInterface.InputDialog( title='Sample Interface', inputs={ inputs[0]: 'What is your favorite color?', inputs[1]: 'What is your quest?', inputs[2]: 'What is your Name?', inputs[3]: 'What Is the Airspeed Velocity of an Unladen Swallow?' }, datatype={ inputs[0]: 'check', inputs[1]: 'combo', inputs[2]: 'combo' }, initial={color_inputs[0]: '40'}, options={ inputs[0]: color_inputs, inputs[1]: quest_inputs, inputs[2]: name_inputs }, required=[inputs[0], inputs[1]]) options_response = sample_dialog.show() if options_response == {}: sys.exit('Selection of planning structure options was cancelled') message = '' for k, v in sample_dialog.values.iteritems(): message += k + ' : ' + str(v) + '\n' UserInterface.MessageBox(message)
def initializeCharactersAndObjects(self): self.boss = None # Initialize characters self.myCharacter = characters( "Player", self.gameAssets.allGameImages.allCharacterAnimations["Player"], 60, 100, self) self.allEntities[self.myCharacter.name] = self.myCharacter # Initialize camera self.camera = Camera.camera(self, 0, 0) self.myCharacter.initCamera(self.camera) ## Initialize Objects # fill platforms according to map for x in range(len(self.map)): for y in range(len(self.map)): if self.map[x][y] == 1: self.platforms.append( platforms(50, 50, self.gameAssets.allGameImages.platform1, (50 * x, 50 * y), self)) # Initialize Boss self.boss = boss( "Hydra", 1000, self.gameAssets.allGameImages.allCharacterAnimations["Hydra"], 750, 750, self) self.allEntities[self.boss.name] = self.boss # Initialize UI self.userInterface = UserInterface.userInterface(self) self.playerHealthBar = UserInterface.playerHealthBar( 0, 10, 300, 40, self.allEntities["Player"], self.gameAssets.allGameImages.playerHealthBar) self.blackBorder = pygame.transform.scale( self.gameAssets.allGameImages.blackBorder, [self.wndWidth, 100]) self.gameAssets.allGameImages.gameOverScreen = pygame.transform.scale( self.gameAssets.allGameImages.gameOverScreen, [self.wndWidth, self.wndHeight]) self.gameAssets.allGameImages.gameWinScreen = pygame.transform.scale( self.gameAssets.allGameImages.gameWinScreen, [self.wndWidth, self.wndHeight])
def train(model, optimizer, epoch, train_loader, scheduler=None, c_confines=None): model.train() if c_confines is not None: c_step_size = (c_confines[1] / c_confines[0])**(1.0 / C_STEPS_AMOUNT) when_to_step = math.floor(len(train_loader) / C_STEPS_AMOUNT) else: # Set default values so the variables will always be defined c_step_size = 1 when_to_step = 1 for corrEpoch in range(0, epoch): # model.quantization_layer.c = c_confines[0] if scheduler is not None: scheduler.step() for batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data.float()), Variable(target.float()) optimizer.zero_grad() output = model(data) loss = criterion(output.view(-1, 1), target.view(-1, 1)) loss.backward() optimizer.step() if c_confines is not None and batch_idx % when_to_step == 0 \ and model.quantizationLayerIndex: if model.quantization_layer.c * c_step_size < c_confines[1]: model.quantization_layer.c *= c_step_size if batch_idx % 10 == 0: Ui.train_iteration(model, corrEpoch, epoch, batch_idx, data, train_loader, loss, c_confines) epoch_loss_log.log(epoch=corrEpoch + 1, loss=test_soft_to_hard_quantization(model))
def test_soft_to_hard_quantization(model): if model.quantizationLayerIndex: a, b, c, q = SoftToHardQuantization.get_parameters(model) log.log(a=a, b=b, c=c) test_loss = 0 for batch_idx, (data, target) in enumerate(testLoader): output, target = Variable(data.float()), Variable(target.float()) # DEBUGGING VARIABLE target_numpy = target.detach().numpy() for layerIndex, layer in enumerate(model.layers): if layerIndex is model.quantizationLayerIndex: output_numpy = np.copy(output.detach().numpy()) # DEBUGGING VARIABLE quantization_in = output_numpy for ii in range(0, output_numpy.shape[0]): for jj in range(0, output_numpy.shape[1]): output[ii, jj], kk = SoftToHardQuantization.quantize( output_numpy[ii, jj], a, b, q) # DEBUGGING VARIABLE quantization_out = output.detach().numpy() else: output = layer(output) # DEBUGGING VARIABLE net_out = output.detach().numpy() # sum up batch loss test_loss += criterion(output.view(-1, 1), target.view(-1, 1)) Ui.test_iteration(model.modelname, batch_idx, data, testLoader) test_loss /= (len(testLoader.dataset) / BATCH_SIZE) return test_loss.detach().numpy()
def main(): global Mission global hero global current_room global plot while True: Setting.draw_room() UI.describe_setting() #------------------------------------------------- # give options for current room # this will be a dict -- each item will be: # key : name of object # value : object room_options = {} for character in current_room.contents: # name of character / item name = character['name'] room_options[name] = character target = UI.prompt_options(room_options) #------------------------------------------------- # CONFLICT # instantiate a conflict between hero and target conflict = Conflict.conflict(hero, target) conflict.main() #------------------------------------------------- # check all plot conditions if plot.check_win_conditions(): plot.victory() exit() if plot.check_lose_conditions(): plot.failure() exit()
def main(): # Get current patient, case, and machine DB machine_db = connect.get_current('MachineDB') try: patient = connect.get_current('Patient') case = connect.get_current('Case') except Exception: UserInterface.WarningBox('This script requires a patient to be loaded') sys.exit('This script requires a patient to be loaded') # Start script status status = UserInterface.ScriptStatus(steps=['Verify CT density table and external are set', 'Select folder to import DICOM RT plans from', 'Select folder to export calculated dose to', 'Choose import overrides and calculation options', 'Import, re-calculate, and export plans'], docstring=__doc__, help=__help__) # Confirm a CT density table and external contour was set status.next_step(text='Prior to execution, the script will make sure that a CT density table and External ' + 'contour are set for the current plan. These are required for dose calculation.') examination = connect.get_current('Examination') if examination.EquipmentInfo.ImagingSystemReference is None: connect.await_user_input('The CT imaging system is not set. Set it now, then continue the script.') patient.Save() else: patient.Save() external = False for r in case.PatientModel.RegionsOfInterest: if r.Type == 'External': external = True
def main(): app = QApplication(sys.argv) path=sys.path[0] os.chdir(path)#get the current directory #initialize the objects login_win = login.Login_Dialog() error_win = ip.Error_Dialog() userinterface_win = ui.Userinterface_Dialog() goodslist_win = gl.GoodsList_Dialog() customerlist_win = gl.CustomerList_Dialog() myshop_win = ms.MyShop_Dialog() admininterface_win = ai.Admininterface_Dialog() admin_customerlist_win = ag.Admin_CustomerList_Dialog() admin_goodslist_win = ag.Admin_GoodsList_Dialog() newuser_win = nu.NewUser_Dialog() #connect the signal #user part login_win.login_fail.connect(error_win.show_myself)#操作失败时显示提示窗口 login_win.login_succeed_user.connect(userinterface_win.receive_user_argument)#用户登陆成功,打开用户界面 userinterface_win.this_hide.connect(login_win.show_myself)#退出用户界面时返回登陆界面 userinterface_win.shop_chose.connect(goodslist_win.receive_info)#用户选择商店后打开该商店窗口 goodslist_win.cus_list.connect(customerlist_win.reveice_data)#用户查看当前店内顾客时打开顾客列表 goodslist_win.exit_shop.connect(userinterface_win.user_leave_shop)#用户退出商店时发送退出信号 userinterface_win.myshop.connect(myshop_win.get_owner)#用户进入 我的商店 时打开自己商店的界面 myshop_win.act_fail.connect(error_win.show_myself)#用户创建新商品失败时显示提示窗口 userinterface_win.act_fail.connect(error_win.show_myself)#用户充值失败时显示提示窗口 goodslist_win.act_fail.connect(error_win.show_myself)#余额不足时显示提示窗口 goodslist_win.remain_update.connect(userinterface_win.get_remaining)#买东西后提醒更新余额窗口 #admin part login_win.login_succeed_admin.connect(admininterface_win.receive_admin_argument)#管理员登陆成功,打开管理员界面 admininterface_win.this_hide.connect(login_win.show_myself)#退出管理员界面时返回登录界面 admininterface_win.act_fail.connect(error_win.show_myself)#操作失败时显示提示窗口 admininterface_win.shop_chose.connect(admin_goodslist_win.receive_info)#管理员选择商店后打开该商店窗口 admin_goodslist_win.cus_list.connect(admin_customerlist_win.reveice_data)#管理员查看当前店内顾客时打开顾客列表 admininterface_win.new_user.connect(newuser_win.show_win)#点击创建用户按钮,打开窗口 newuser_win.act_fail.connect(error_win.show_myself)#操作失败时显示提示窗口 login_win.show() sys.exit(app.exec_())
def recieveThread(s): while True: message = s.recv(500).decode("utf8") if message == 'a': ui.btn1["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'b': ui.btn2["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'c': ui.btn3["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'd': ui.btn4["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'e': ui.btn5["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'f': ui.btn6["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'g': ui.btn7["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'h': ui.btn8["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'i': ui.btn9["text"] = "O" ui.lbl2['text'] = "player O is waiting for you" if message == 'r': ui.restart() if message == 'w': mb.showinfo(windowshow, "Other side wins") ui.restart() if message == 'go': mb.showinfo(windowshow, "Game Over") ui.restart() ui.send("r")
import sys sys.settrace import os os.environ['LD_LIBRARY_PATH'] = "/soft/users/home/u5682/nfs/todo_GATE/CLHEP/lib:/soft/users/home/u5682/nfs/todo_GATE/root/lib:/opt/gw/lib:/opt/d-cache/dcap/lib:/opt/d-cache/dcap/lib64:/opt/glite/lib:/opt/glite/lib64:/opt/globus/lib:/opt/lcg/lib:/opt/lcg/lib64:/opt/classads/lib64/:/opt/c-ares/lib" if __name__ == '__main__': print("WELLCOME TO MONTERA 2.0") print("---") print ("date:" + str(datetime.now())) print("") if len(sys.argv) != 2: UserInterface.printUsageInstructions() print("Exiting...") sys.exit(1) requirementsFile=sys.argv[1] print("Starting connection with database") metadata = MetaData() myDBDesign = DBDesign() hostDB = myDBDesign.HostDBDesign(metadata) pilotDB = myDBDesign.PilotDBDesign(metadata)
def newExecution(self, requirementsFile): print("") print("Starting the execution of a new Montera template") print("") print("") print("Cleaning the DB from past executions") self.purgeDB() print("Database cleaned") print("") print("Reading application requirements") self.myApplication = UserInterface.readRequirements(requirementsFile) base.Session.add(self.myApplication.profile) base.Session.add(self.myApplication) base.Session.commit() # TODO: esto es un añapa, pero el base.Session.commit jode este puntero self.myApplication.profile.application = self.myApplication print("application requirements read an stored") print("") print("name: " + self.myApplication.name) print("desired samples: " + str(self.myApplication.desiredSamples)) # base.tmpExecutionFolder += str(self.myApplication.id) + "/" try: os.makedirs(base.tmpExecutionFolder) print("Creating temporary folder for application results, " + base.tmpExecutionFolder) except: print("Temporary folder for the application already exists, ok") print("") print("Checking if a profiling of the application is neccesary") if self.myApplication.profile.numProfilings == 0: print("it is necessary. Starting app profile!") self.profileApplication() try: base.Session.commit() except: base.Session.rollback() print("Lost connection with database, not storing anything!") print("Application profiling finished") else: print("Application profiling loaded from past executions, profiling is not needed") print("Constant effort, sample effort:") print( str(self.myApplication.profile.constantEffort) + " whetstones, " + str(self.myApplication.profile.sampleEffort) + " whetstones/sample" ) print("") print("Loading scheduling algorithm") self.mySchedulingAlgorithm = InformationManager.loadSchedulingAlgorithm(self.myApplication.schedulingAlgorithm) if self.mySchedulingAlgorithm != None: print("Scheduling Algorithm loaded") else: print("Could not find an appropriate scheduling algorithm") sys.exit(1)
def run(self): self.log("[INFO]: run IA"); UserInterface.run(self)
def init(self): self.log("[INFO]: init IA"); UserInterface.init(self)
import sys from requests import HTTPError import UploadFile import UserInterface if __name__ == '__main__': try: class_id = UserInterface.get_course() assign_id = UserInterface.get_assignment(class_id) file_name = UserInterface.get_file() UploadFile.upload_file(class_id, assign_id, file_name) except HTTPError: print("Canvas returned an error. Please try again later.", file=sys.stderr) sys.exit() print("\nAssignment submitted.")