def test_likness(self): generic = CommonTestFunctions() category = generic.category() preference = generic.preference(category) has_likness = hasattr(preference, 'likness') self.assertTrue(has_likness) minimum = Preference.get_min_likness() maximum = Preference.get_max_likness() + 1 possible_likeness_values = range(minimum, maximum) for val in possible_likeness_values: try: preference.likness = val except Exception as e: self.fail('failed to set preference to value: ' + str(val)) else: self.assertEqual(preference.likness, val) unacceptable = [ minimum - 1, minimum - 2, minimum - 3, maximum + 1, maximum + 2, maximum + 3, 0.3, maximum - 0.3 ] for val in unacceptable: self.assertRaises(AssertionError, preference.set_likness, val)
def get_preferences_of(self, likness): assert Preference.get_min_likness( ) <= likness <= Preference.get_max_likness( ), 'likness must be between [%d, %d]. Not: %s' % ( Preference.get_min_likness(), Preference.get_max_likness(), str(likness)) assert isinstance(likness, int), 'likness must be an integer.' return list(filter(lambda x: x.likness == likness, self.preferences))
def importPreflibFile(self, fileName): """ Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are allowed, if a voter ranks only one candidate, then the voter did not prefer any candidates over another. This may lead to some discrepancies when importing and exporting a .toi preflib file or a .soi preflib file. :ivar str fileName: The name of the input file to be imported. """ # Use the functionality found in io to read the file. elecFileObj = open(fileName, 'r') self.candMap, rankMaps, wmgMapsCounts, self.numVoters = io.read_election_file( elecFileObj) elecFileObj.close() self.numCands = len(self.candMap.keys()) # Go through the rankMaps and generate a wmgMap for each vote. Use the wmgMap to create a # Preference object. self.preferences = [] for i in range(0, len(rankMaps)): wmgMap = self.genWmgMapFromRankMap(rankMaps[i]) self.preferences.append(Preference(wmgMap, wmgMapsCounts[i]))
def update_preference(): request_data = request.json user_id = get_jwt_identity() region = request_data.get('region') section = request_data.get('section') kind = request_data.get('kind') rent_price = request_data.get('rent_price') pattern = request_data.get('pattern') space = request_data.get('space') # if not user_id: # return jsonify({'error': "user_id not provided."}), 400 if not region: return jsonify({'error': "region not provided."}), 400 pref = Preference(user_id=user_id, region=region, section=section, kind=(kind if kind != None else ''), rent_price=(rent_price if rent_price != None else 0), pattern=(pattern if pattern != None else ''), space=(space if space != None else '')) try: db.update_user_preference(pref) except SqlError as error: return jsonify({'error': error.message}), 400 return jsonify({'message': "success"}), 200
def parse_preference(preference): can_work = preference.like != 0 # This way neutral is 0, likes are positive and dislikes are negative. likeness = preference.like - 3 category = CategoryAssembler.assemble(preference.category) return Preference(category, likeness, can_work)
def get_user_preference(self, user_id: str): sqlCommand = f""" SELECT region, kind, rent_price, pattern, space FROM user_preference WHERE id = %s """ try: id = (user_id,) result = self.__get_sql_result(sqlCommand, param=id) if len(result) > 0: # for element in result pres = [] for element in result: if len(element) == 5: pref = Preference( user_id=user_id, region=element['region'], kind=element['kind'], rent_price=element['rent_price'], pattern=element['pattern'], space=element['space']) pres.append(pref) else: raise TypeError return pres else: return None except connector.Error as error: print(error.msg) raise SqlError(error.msg)
def test_one_task_one_user_assign(self): start_a = datetime.datetime(2000, 1, 1, 6, 0, 0) end_a = datetime.datetime(2000, 1, 1, 22, 0, 0) availability = [Availability(Duration(start_a, end_a))] category = Category(1, 'TestCategory') preferences = [Preference(category, 0, True)] groups = [Group(1, 'Employee')] generic = CommonTestFunctions() staff_member = StaffMember(1, 'TestMember', 0, 40, 80, 10, availability, preferences, groups) start_t = datetime.datetime(2000, 1, 1, 9, 0, 0) end_t = datetime.datetime(2000, 1, 1, 16, 0, 0) task_time = Duration(start_t, end_t) location = Location(1, 'TestLocation') task = Task(1, 'TestTask', task_time, 1, groups[0], location, category) staff_members = [staff_member] roles = [] tasks = [task] settings = generic.settings(40, True) generator = ScheduleGenerator(staff_members, roles, tasks) generator.schedule(settings) self.assertTrue(staff_member.has_task(task)) self.assertFalse(generator.has_unassigned_tasks())
def get_preference(db_conn, a_id): sqlSelect = "SELECT * from Preference WHERE A_ID = '{}'".format(a_id) results = db_conn.execute(sqlSelect) preference_data = results.fetchone() print(preference_data) if preference_data == None: return False else: preference = Preference(preference_data) return preference
def genPref(ranking, num_votes): wmgMap = dict() for i in range(1,len(ranking)+1): wmgMap[i] = dict() for i in ranking: for j in ranking: if i != j: if ranking.index(i) < ranking.index(j): wmgMap[i][j] = 1 else: wmgMap[i][j] = -1 return Preference(wmgMap, num_votes)
def parse_data(filename, agents=[], alternatives=[]): """ Parses voter data from input file. """ f = open(sys.argv[1], "r") for line in f: ranking = line.rstrip().split(',') if len(ranking) > len(alternatives): alternatives = sorted(ranking) wmgMap = create_wmgMap(ranking) agents.append(Preference(wmgMap)) return agents, alternatives
def test_category(self): generic = CommonTestFunctions() acceptable = [ generic.category(id=1, name='A'), generic.category(id=2, name='B'), generic.category(id=3, name='C'), ] for category in acceptable: p = None try: p = Preference(category, 0, True) except Exception as e: self.fail('Could not create preference. More Info: ' + str(e.args)) else: self.assertEqual(p.category, category) self.assertRaises(AssertionError, Preference, None, 0, True)
def importJsonFile(self, fileName): """ Imports a json file that contains all the information of a Profile. This function will completely override all members of the current Profile object. :ivar str fileName: The name of the input file to be imported. """ infile = open(fileName) data = json.load(infile) infile.close() self.numCands = int(data["numCands"]) self.numVoters = int(data["numVoters"]) # Because the json.load function imports everything as unicode strings, we will go through # the candMap dictionary and convert all the keys to integers and convert all the values to # ascii strings. candMap = dict() for key in data["candMap"].keys(): candMap[int(key)] = data["candMap"][key].encode("ascii") self.candMap = candMap # The Preference class is also not directly JSON serializable, so we exported the # underlying dictionary for each Preference object. When we import, we will create a # Preference object from these dictionaries. self.preferences = [] for preferenceMap in data["preferences"]: count = int(preferenceMap["count"]) # Because json.load imports all the items in the wmgMap as unicode strings, we need to # convert all the keys and values into integers. preferenceWmgMap = preferenceMap["wmgMap"] wmgMap = dict() for key in preferenceWmgMap.keys(): wmgMap[int(key)] = dict() for key2 in preferenceWmgMap[key].keys(): wmgMap[int(key)][int(key2)] = int( preferenceWmgMap[key][key2]) self.preferences.append(Preference(wmgMap, count))
def get_preference_for_category(self, category): for pref in self._preferences: if pref.category == category: return pref.likness # By default no one has preferences for each task. Therefore, return preference default. return Preference.get_avg_likness()
from preference import Preference setting = { 'light': [ { "name": "SpacegrayLight", "color_scheme": "Packages/User/SublimeLinter/Mac Classic (SL).tmTheme", "theme": "Spacegray Light.sublime-theme", }, ], 'dark': [{ "name": "SpacegrayDark", "color_scheme": "Packages/User/SublimeLinter/base16-eighties.dark (SL).tmTheme", "theme": "Spacegray.sublime-theme", }] } # init sublime settings preference = Preference() # judge current time sec = datetime.datetime.now().strftime('%H') flag = 'dark' if 10 <= int(sec) <= 17 else 'light' # choose a random theme theme = setting[flag][random.randrange(len(setting[flag]))] theme.pop('name') # set theme preference.setAttr(theme) preference.save()
def show_preference(self): pref = Preference( self ) self.connect( pref , SIGNAL('accept') , self.applyPreference ) pref.show()
wmgMap2 = dict() wmgMap2[1] = dict() wmgMap2[2] = dict() wmgMap2[3] = dict() wmgMap2[1][2] = -1 wmgMap2[1][3] = 1 wmgMap2[2][1] = 1 wmgMap2[2][3] = 1 wmgMap2[3][1] = -1 wmgMap2[3][2] = -1 # We can generate Preference objects from these dictionaries, by calling the Preference constructor. # Let's say that the ranking {cand1 > cand2 > cand3} occurs only once. Then, we can call the # Preference constructor with just the dictionary as our constructor. preference1 = Preference(wmgMap1) # Let's say that the ranking {cand2 > cand1 > cand3} occurs three times. Then, we can include an # optional int argument that represents the number of times the ranking occurs. preference2 = Preference(wmgMap2, 3) # Let's put these into a list. preferences = [] preferences.append(preference1) preferences.append(preference2) # Let's set up a dictionary that associates integer representations of our candidates with their names. candMap = dict() candMap[1] = "john" candMap[2] = "jane" candMap[3] = "jill"
def main(): media_list = [] suggestions = [] preference = Preference() preference_path = Path( os.path.expandvars( r'%LOCALAPPDATA%/Temp/Random_Player_qc/preference.json')) preference = PreferenceManager.loadFrom(preference_path) print("{}".format(preference)) if preference.directory == Path(): state = State.STATE_ASK_DIRECTORY else: state = State.STATE_GENERATE_LIST while True: if state == State.STATE_ASK_DIRECTORY: is_valid, path = ask_directory("Media directory:") if is_valid: preference.directory = path state = State.STATE_ASK_MEDIA_TYPE elif state == State.STATE_ASK_MEDIA_TYPE: is_valid, media_type = ask_mediatype() if is_valid: preference.media_type = media_type state = State.STATE_GENERATE_LIST elif state == State.STATE_GENERATE_LIST: media_list = Librarian.generate_media_list( preference.directory, media_type=preference.media_type, reccurent=True) if not media_list: state = State.STATE_ASK_EMPTY else: state = State.STATE_ASK_ACTION elif state == State.STATE_ASK_EMPTY: is_valid, state = ask_empty_folder() elif state == State.STATE_ASK_ACTION: is_valid, state = ask_action() elif state == State.STATE_RANDOM_MEDIA: media = Librarian.random_media(media_list) state = State.STATE_PLAY elif state == State.STATE_GENERATE_SUGGESTION: suggestions = Librarian.random_media_list( media_list, 3) # TODO: retake can have many time the same media state = State.STATE_ASK_SUGGESTION elif state == State.STATE_ASK_SUGGESTION: is_valid, option = aks_suggestion(suggestions) if is_valid: media = suggestions[option] state = State.STATE_PLAY elif state == State.STATE_PLAY: if media: open_file(media) break else: break print("{}".format(preference.directory, preference.media_type)) PreferenceManager.saveTo(preference_path, preference)
wmgMap1[2] = dict() wmgMap1[3] = dict() wmgMap1[4] = dict() wmgMap1[1][2] = 1 wmgMap1[1][3] = 1 wmgMap1[1][4] = 1 wmgMap1[2][1] = -1 wmgMap1[2][3] = 1 wmgMap1[2][4] = 1 wmgMap1[3][1] = -1 wmgMap1[3][2] = -1 wmgMap1[3][4] = 1 wmgMap1[4][1] = -1 wmgMap1[4][2] = -1 wmgMap1[4][3] = -1 preference1 = Preference(wmgMap1, 2) #ranking 2: 3 @ b>d>c>a wmgMap2 = dict() wmgMap2[1] = dict() wmgMap2[2] = dict() wmgMap2[3] = dict() wmgMap2[4] = dict() wmgMap2[1][2] = -1 wmgMap2[1][3] = -1 wmgMap2[1][4] = -1 wmgMap2[2][1] = 1 wmgMap2[2][3] = 1 wmgMap2[2][4] = 1 wmgMap2[3][1] = 1 wmgMap2[3][2] = -1
def test_get_preference_for_category(self): generic = CommonTestFunctions() category1 = generic.category(1) category2 = generic.category(2) category3 = generic.category(3) category4 = generic.category(4) category5 = generic.category(5) category6 = generic.category(6) category7 = generic.category(7) preference1 = generic.preference(category1, -2) preference2 = generic.preference(category2, -1) preference3 = generic.preference(category3, -0) preference4 = generic.preference(category4, 1) preference5 = generic.preference(category5, 2) preference6 = generic.preference(category6, 2) preferences = [ preference1, preference2, preference3, preference4, preference5, preference6, ] staff_member = generic.staff_member(preferences=preferences) self.assertEqual(staff_member.get_preference_for_category(category1), preference1.likness) self.assertEqual(staff_member.get_preference_for_category(category2), preference2.likness) self.assertEqual(staff_member.get_preference_for_category(category3), preference3.likness) self.assertEqual(staff_member.get_preference_for_category(category4), preference4.likness) self.assertEqual(staff_member.get_preference_for_category(category5), preference5.likness) self.assertEqual(staff_member.get_preference_for_category(category6), preference6.likness) self.assertEqual(staff_member.get_preference_for_category(category7), Preference.get_avg_likness()) self.assertTrue(staff_member.has_preference_for_category(category1)) self.assertTrue(staff_member.has_preference_for_category(category2)) self.assertTrue(staff_member.has_preference_for_category(category3)) self.assertTrue(staff_member.has_preference_for_category(category4)) self.assertTrue(staff_member.has_preference_for_category(category5)) self.assertTrue(staff_member.has_preference_for_category(category6)) self.assertFalse(staff_member.has_preference_for_category(category7)) location = generic.location() task_duration = generic.duration(9, 15) group = generic.group() task1 = generic.task(group, location, category1, task_duration) task2 = generic.task(group, location, category2, task_duration) task3 = generic.task(group, location, category3, task_duration) task4 = generic.task(group, location, category4, task_duration) task5 = generic.task(group, location, category5, task_duration) task6 = generic.task(group, location, category6, task_duration) task7 = generic.task(group, location, category7, task_duration) self.assertEqual(staff_member.get_preference_for_task(task1), preference1.likness) self.assertEqual(staff_member.get_preference_for_task(task2), preference2.likness) self.assertEqual(staff_member.get_preference_for_task(task3), preference3.likness) self.assertEqual(staff_member.get_preference_for_task(task4), preference4.likness) self.assertEqual(staff_member.get_preference_for_task(task5), preference5.likness) self.assertEqual(staff_member.get_preference_for_task(task6), preference6.likness) self.assertEqual(staff_member.get_preference_for_task(task7), Preference.get_avg_likness()) self.assertTrue(staff_member.dislikes_task(task1)) self.assertFalse(staff_member.likes_task(task1)) self.assertTrue(staff_member.dislikes_task(task2)) self.assertFalse(staff_member.likes_task(task2)) self.assertFalse(staff_member.dislikes_task(task3)) self.assertFalse(staff_member.likes_task(task3)) self.assertTrue(staff_member.likes_task(task4)) self.assertFalse(staff_member.dislikes_task(task4)) self.assertTrue(staff_member.likes_task(task5)) self.assertFalse(staff_member.dislikes_task(task5)) self.assertTrue(staff_member.likes_task(task6)) self.assertFalse(staff_member.dislikes_task(task6))
def __init__(self, pt): self.pt = pt self.list_help_words = [] self.mepref = Preference(self.pt) self.build()
from preference import Preference setting = { 'light':[ { "name":"SpacegrayLight", "color_scheme": "Packages/User/SublimeLinter/Mac Classic (SL).tmTheme", "theme": "Spacegray Light.sublime-theme", }, ], 'dark':[ { "name":"SpacegrayDark", "color_scheme": "Packages/User/SublimeLinter/base16-eighties.dark (SL).tmTheme", "theme": "Spacegray.sublime-theme", } ] } # init sublime settings preference = Preference() # judge current time sec = datetime.datetime.now().strftime('%H') flag = 'dark' if 10 <= int(sec) <= 17 else 'light' # choose a random theme theme = setting[flag][random.randrange(len(setting[flag]))] theme.pop('name') # set theme preference.setAttr(theme) preference.save()
def __init__(self, parent=None): super().__init__(parent) self.icon = QIcon() self.icon.addPixmap(QPixmap("./tianhou.ico"), QIcon.Normal, QIcon.Off) self.setWindowIcon(self.icon) self.setupUi(self) """-------- System ---------""" self.local_system = platform.system() """-------- Short Cuts ---------""" self.actionSave.setShortcut(QKeySequence(QKeySequence.Save)) self.actionUndo.setShortcut(QKeySequence(QKeySequence.Undo)) self.actionRedo.setShortcut(QKeySequence(QKeySequence.Redo)) self.actionNew.setShortcut(QKeySequence(QKeySequence.New)) self.actionCopy.setShortcut(QKeySequence(QKeySequence.Copy)) self.actionPaste.setShortcut(QKeySequence(QKeySequence.Paste)) self.actionCut.setShortcut(QKeySequence(QKeySequence.Cut)) self.actionFind.setShortcut(QKeySequence(QKeySequence.Find)) self.actionSelect_All.setShortcut(QKeySequence(QKeySequence.SelectAll)) """-------- Code ---------""" self.actionAbout_us.triggered.connect(self.aboutusEvent) # 关于我们 self.actionExit.triggered.connect(self.closeEvent) # 退出 self.actionPreference.triggered.connect( self.showpreferenceEvent) # 偏好设置 """-------- File ---------""" self.actionNew.triggered.connect(self.newfileEvent) # 新建 self.actionOpen_File.triggered.connect(self.openfileEvent) # 打开文件 self.actionOpen_Folder.triggered.connect(self.openfolderEvent) # 打开文件夹 self.actionSave.triggered.connect(self.savefileEvent) # 保存文件 self.actionSave_All.triggered.connect(self.saveallEvent) # 全部保存 self.actionSave_As.triggered.connect(self.saveasEvent) # 另存为 self.actionClose.triggered.connect(self.closefileEvent) # 关闭 self.tabWidget.tabCloseRequested.connect(self.closefileEvent) # 关闭tab """-------- Edit ---------""" self.actionUndo.triggered.connect(self.text_undo) # 撤销 self.actionRedo.triggered.connect(self.text_redo) # 重做 self.actionCut.triggered.connect(self.text_cut) # 剪切 self.actionCopy.triggered.connect(self.text_copy) # 复制 self.actionPaste.triggered.connect(self.text_paste) # 粘贴 self.actionFind.triggered.connect(self.text_find) # 查找 self.win_find_is_show = False self.actionSelect_All.triggered.connect(self.text_selectAll) # 全选 """-------- Language ---------""" self.actionPlain_Text.triggered.connect(self.selectLanguage) self.actionC.triggered.connect(self.selectLanguage) self.actionMarkdown.triggered.connect(self.selectLanguage) self.actionPython.triggered.connect(self.selectLanguage) """-------- Whatever... ---------""" self.actionQR_Code.triggered.connect(self.rewardEvent) # 打赏 """-------- Status bar ---------""" self.lb_margin = QtWidgets.QLabel() self.lb_lang = QtWidgets.QLabel() self.statusbar.addWidget(self.lb_margin, 4) self.statusbar.addWidget(self.lb_lang, 1) """-------- Dir Tree ---------""" self.model = QDirModel() """ view from source""" """-------- Run Event ---------""" self.dock_win = QtWidgets.QDockWidget() self.dock_tab = QtWidgets.QTabWidget() self.dock_win.setWidget(self.dock_tab) self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_win) self.dock_tab.setTabPosition(QTabWidget.South) self.teridx = 0 self.dock_win.setFeatures(QDockWidget.DockWidgetVerticalTitleBar) self.dock_tab.setTabsClosable(True) self.dock_tab.tabCloseRequested.connect(self.run_close_event) self.run_event = False self.actionStop.setDisabled(True) """-------- Basic Configs ---------""" self.setAttribute(Qt.WA_DeleteOnClose, True) self.tabWidget.setAttribute(Qt.WA_DeleteOnClose, True) self.tabidx = 0 self.font_content = None # 字体和大小 self.interpreter = None # 解释器 self.preference = Preference(par=self) self.tab_dict = {} # 存放tab self.file_save_path = None # 保存文件的路径 self.language = 'txt' # 当前语言 """-------- Terminal ---------""" self.actionNew_Terminal.triggered.connect(self.new_terminal_event) # self.actionClose_Terminal.triggered.connect(self.close_terminal_event) """-------- Run ---------""" self.run_browser = RunBrowser(self.font_content) self.run_browser.startSignal.connect(self.run_start_event) self.run_browser.exitSignal.connect(self.run_exit_event) self.gcc = None self.actionRun.triggered.connect(self.new_run_event) self.actionStop.triggered.connect(self.stop_run) self.actionCompile.triggered.connect(self.compile_event) """--------tool------------""" self.actionWrite_Board.triggered.connect(self.OpenBoard) self.enableClickFlag = True # 改变tab enable的flag """所有语言类型为: txt -> 文本文件 md -> Markdown文件 c -> C文件 py -> Python文件 """ """-------- 初始执行的操作 ---------""" self.openIDEevent()
class Notebook(QMainWindow, Ui_CodePlus): r""" Notebook 类 """ def __init__(self, parent=None): super().__init__(parent) self.icon = QIcon() self.icon.addPixmap(QPixmap("./tianhou.ico"), QIcon.Normal, QIcon.Off) self.setWindowIcon(self.icon) self.setupUi(self) """-------- System ---------""" self.local_system = platform.system() """-------- Short Cuts ---------""" self.actionSave.setShortcut(QKeySequence(QKeySequence.Save)) self.actionUndo.setShortcut(QKeySequence(QKeySequence.Undo)) self.actionRedo.setShortcut(QKeySequence(QKeySequence.Redo)) self.actionNew.setShortcut(QKeySequence(QKeySequence.New)) self.actionCopy.setShortcut(QKeySequence(QKeySequence.Copy)) self.actionPaste.setShortcut(QKeySequence(QKeySequence.Paste)) self.actionCut.setShortcut(QKeySequence(QKeySequence.Cut)) self.actionFind.setShortcut(QKeySequence(QKeySequence.Find)) self.actionSelect_All.setShortcut(QKeySequence(QKeySequence.SelectAll)) """-------- Code ---------""" self.actionAbout_us.triggered.connect(self.aboutusEvent) # 关于我们 self.actionExit.triggered.connect(self.closeEvent) # 退出 self.actionPreference.triggered.connect( self.showpreferenceEvent) # 偏好设置 """-------- File ---------""" self.actionNew.triggered.connect(self.newfileEvent) # 新建 self.actionOpen_File.triggered.connect(self.openfileEvent) # 打开文件 self.actionOpen_Folder.triggered.connect(self.openfolderEvent) # 打开文件夹 self.actionSave.triggered.connect(self.savefileEvent) # 保存文件 self.actionSave_All.triggered.connect(self.saveallEvent) # 全部保存 self.actionSave_As.triggered.connect(self.saveasEvent) # 另存为 self.actionClose.triggered.connect(self.closefileEvent) # 关闭 self.tabWidget.tabCloseRequested.connect(self.closefileEvent) # 关闭tab """-------- Edit ---------""" self.actionUndo.triggered.connect(self.text_undo) # 撤销 self.actionRedo.triggered.connect(self.text_redo) # 重做 self.actionCut.triggered.connect(self.text_cut) # 剪切 self.actionCopy.triggered.connect(self.text_copy) # 复制 self.actionPaste.triggered.connect(self.text_paste) # 粘贴 self.actionFind.triggered.connect(self.text_find) # 查找 self.win_find_is_show = False self.actionSelect_All.triggered.connect(self.text_selectAll) # 全选 """-------- Language ---------""" self.actionPlain_Text.triggered.connect(self.selectLanguage) self.actionC.triggered.connect(self.selectLanguage) self.actionMarkdown.triggered.connect(self.selectLanguage) self.actionPython.triggered.connect(self.selectLanguage) """-------- Whatever... ---------""" self.actionQR_Code.triggered.connect(self.rewardEvent) # 打赏 """-------- Status bar ---------""" self.lb_margin = QtWidgets.QLabel() self.lb_lang = QtWidgets.QLabel() self.statusbar.addWidget(self.lb_margin, 4) self.statusbar.addWidget(self.lb_lang, 1) """-------- Dir Tree ---------""" self.model = QDirModel() """ view from source""" """-------- Run Event ---------""" self.dock_win = QtWidgets.QDockWidget() self.dock_tab = QtWidgets.QTabWidget() self.dock_win.setWidget(self.dock_tab) self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_win) self.dock_tab.setTabPosition(QTabWidget.South) self.teridx = 0 self.dock_win.setFeatures(QDockWidget.DockWidgetVerticalTitleBar) self.dock_tab.setTabsClosable(True) self.dock_tab.tabCloseRequested.connect(self.run_close_event) self.run_event = False self.actionStop.setDisabled(True) """-------- Basic Configs ---------""" self.setAttribute(Qt.WA_DeleteOnClose, True) self.tabWidget.setAttribute(Qt.WA_DeleteOnClose, True) self.tabidx = 0 self.font_content = None # 字体和大小 self.interpreter = None # 解释器 self.preference = Preference(par=self) self.tab_dict = {} # 存放tab self.file_save_path = None # 保存文件的路径 self.language = 'txt' # 当前语言 """-------- Terminal ---------""" self.actionNew_Terminal.triggered.connect(self.new_terminal_event) # self.actionClose_Terminal.triggered.connect(self.close_terminal_event) """-------- Run ---------""" self.run_browser = RunBrowser(self.font_content) self.run_browser.startSignal.connect(self.run_start_event) self.run_browser.exitSignal.connect(self.run_exit_event) self.gcc = None self.actionRun.triggered.connect(self.new_run_event) self.actionStop.triggered.connect(self.stop_run) self.actionCompile.triggered.connect(self.compile_event) """--------tool------------""" self.actionWrite_Board.triggered.connect(self.OpenBoard) self.enableClickFlag = True # 改变tab enable的flag """所有语言类型为: txt -> 文本文件 md -> Markdown文件 c -> C文件 py -> Python文件 """ """-------- 初始执行的操作 ---------""" self.openIDEevent() def OpenBoard(self): textedit = self.__get_textEditor() self.boardwindow = PaintForm(textedit) self.boardwindow.show() def openIDEevent(self): tmp_path = '.tmp' def listdir(path): for item in os.listdir(path): if not item.startswith('.') and not item.endswith('.pkl'): yield item if not os.path.exists(tmp_path) or not os.path.exists( os.path.join(tmp_path, 'mapping.pkl')): self.__create_tab() # 初始创建一个tab self.tabWidget.currentChanged.connect(self.changeTab) # 切换tab触发 else: """读取缓存的文件""" with open(os.path.join(tmp_path, 'mapping.pkl'), 'rb') as f: mapping = pickle.load(f) tmp_files = listdir(tmp_path) for i, file in enumerate(tmp_files): file_path = os.path.join(tmp_path, file) if file.startswith('*'): file = file[1:] origin_path = mapping[file] self.openfileEvent(file_path, origin_path) if i == 0: self.tabWidget.currentChanged.connect( self.changeTab) # 切换tab触发 self.lb_lang.setText(self.language) def stop_run(self): self.run_browser.process.close() def run_start_event(self): self.actionRun.setDisabled(True) self.actionStop.setDisabled(False) def run_exit_event(self): self.actionRun.setDisabled(False) self.actionStop.setDisabled(True) def new_run_event(self): if not self.run_event: pix = QPixmap('./imgs/run.jpg') icon = QIcon() icon.addPixmap(pix) self.dock_tab.addTab(self.run_browser, 'Run ') index = self.dock_tab.count() - 1 self.dock_tab.setTabIcon(index, icon) self.dock_tab.setCurrentIndex(index) self.run_event = True cur_path = self.__get_textEditor().filepath if cur_path: if os.path.splitext(cur_path)[-1] == '.py': if not self.interpreter: QMessageBox.warning( self, '提示', '未设置有效的python解释器\n' + '->\n'.join([ 'Code', 'Preference', 'Environment', 'interpreter' ])) return cmd = ' '.join([self.interpreter, cur_path]) self.run_browser.start_process(cmd) elif os.path.splitext(cur_path)[-1] == '.c': cmd = os.path.splitext(cur_path)[0] + '.exe' if os.path.exists(cmd): self.run_browser.process.start(cmd) else: compile_cmd = 'gcc ' + cur_path self.run_browser.process.start(compile_cmd) self.run_browser.process.waitForFinished() if os.path.exists(cmd): self.run_browser.process.start(cmd) def compile_event(self): if not self.run_event: pix = QPixmap('./imgs/run.jpg') icon = QIcon() icon.addPixmap(pix) self.dock_tab.addTab(self.run_browser, 'Run ') index = self.dock_tab.count() - 1 self.dock_tab.setTabIcon(index, icon) self.dock_tab.setCurrentIndex(index) self.run_event = True cur_path = self.__get_textEditor().filepath if cur_path: if os.path.splitext(cur_path)[-1] == '.c': cmd = 'gcc ' + cur_path self.run_browser.start_process(cmd) def run_close_event(self): if not self.actionRun.isEnabled(): ref = QMessageBox.information(self, '提示', '还有项目正在运行\n确定退出?', QMessageBox.Yes | QMessageBox.No) if ref == QMessageBox.Yes: self.stop_run() else: return self.run_event = False self.dock_tab.removeTab(0) def new_terminal_event(self): if self.local_system == 'Windows': os.system('start cmd') elif self.local_system == 'Linux': os.system('gnome-terminal') elif self.local_system == 'Darwin': os.system('open -a Terminal .') def close_terminal_event(self): if self.local_system == 'Darwin': import appscript appscript.app('Terminal').do_script('exit') # def new_terminal_event(self): # from threading import Thread # t = Thread(target=self.aaa) # t.start() # # self.teridx += 1 # self.temp = QTextEdit() # time.sleep(1) # calc_hwnd = win32gui.FindWindow(None, u'C:\WINDOWS\system32\cmd.exe') # print(calc_hwnd) # # self.win = QWindow.fromWinId(calc_hwnd) # # self.new_tab = self.createWindowContainer(self.win, self.temp) # self.new_tab.showMaximized() # # self.win.setKeyboardGrabEnabled(True) # # self.win.setMouseGrabEnabled(True) # 查找 def text_find(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): if not self.win_find_is_show: self.win_find_is_show = True self.find_win = Find_Win(self, textedit) self.find_win.show() def text_undo(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.undo() def text_redo(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.redo() def text_copy(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.copy() def text_paste(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.paste() def text_cut(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.cut() def text_selectAll(self): textedit = self.__get_textEditor() # if isinstance(textedit, QTextEdit): textedit.selectAll() def selectLanguage(self): r""" 选择语言 :return: """ language_support = { 'Plain Text': 'txt', 'C': 'c', 'Markdown': 'md', 'Python': 'py' } textedit = self.__get_textEditor() signal_src = self.sender().text() language = language_support[signal_src] textedit.setlanguage(language) self.language = language self.lb_lang.setText(self.language) # if self.language == 'txt': # self.actionPlain_Text.setDisabled(True) if signal_src == 'Markdown': self.markdown_handler() else: self.normalmode_handler() def changeTab(self): # super().tabWidget.changeEvent() self.language = self.cur_language() self.lb_lang.setText(self.language) cur_tabs = self.tabWidget.count() if cur_tabs == 0: self.actionCut.setDisabled(True) self.actionFind.setDisabled(True) self.actionSave.setDisabled(True) self.actionSave_All.setDisabled(True) self.actionSave_As.setDisabled(True) self.actionClose.setDisabled(True) self.actionUndo.setDisabled(True) self.actionRedo.setDisabled(True) self.actionCopy.setDisabled(True) self.actionPaste.setDisabled(True) self.actionSelect_All.setDisabled(True) self.actionC.setDisabled(True) self.actionPython.setDisabled(True) self.actionPlain_Text.setDisabled(True) self.actionMarkdown.setDisabled(True) self.actionRun.setDisabled(True) self.actionCompile.setDisabled(True) self.enableClickFlag = False else: if not self.enableClickFlag: self.enableClickFlag = True self.actionCut.setDisabled(False) self.actionFind.setDisabled(False) self.actionSave.setDisabled(False) self.actionSave_All.setDisabled(False) self.actionSave_As.setDisabled(False) self.actionClose.setDisabled(False) self.actionUndo.setDisabled(False) self.actionRedo.setDisabled(False) self.actionCopy.setDisabled(False) self.actionPaste.setDisabled(False) self.actionSelect_All.setDisabled(False) self.actionC.setDisabled(False) self.actionPython.setDisabled(False) self.actionPlain_Text.setDisabled(False) self.actionMarkdown.setDisabled(False) self.actionRun.setDisabled(False) self.actionCompile.setDisabled(False) def cur_language(self): if self.tabWidget.count() == 0: return '' language = self.__get_textEditor().language return language def __find_tab_by_index(self, index): r""" 通过currentIndex获取字典中的 :param index: CurrentIndex :return: (str, object) 当前Tab名,TabItem 对象 """ cur_tab_name = self.tabWidget.widget(index).objectName() return cur_tab_name, self.tab_dict[cur_tab_name] def __get_textEditor(self, index=None): r""" 获取当前tab的textEditor :return: (object) textEditor """ if index is None: index = self.tabWidget.currentIndex() _, tabitem = self.__find_tab_by_index(index) return tabitem.text def __get_tabitem(self, index=None): r""" 获取当前tab :return: (object) tab """ if index is None: index = self.tabWidget.currentIndex() _, tabitem = self.__find_tab_by_index(index) return tabitem def newfileEvent(self): r""" 新建文件事件函数 :return: None """ self.__create_tab() def __create_tab(self, name=None): r""" 新建tab :return: None """ self.tabidx += 1 newfile_name = f'New File {self.tabidx}' if name is None else name if name: _, language = os.path.splitext(name) language = language[1:] else: language = 'txt' new_tabname = 'tab_' + str(self.tabidx) tab_new = QWidget() tab_new.setObjectName(new_tabname) layout = QGridLayout(tab_new) layout.setObjectName(f'layout_of_{new_tabname}') # text_editor = TextEditorS(name=newfile_name, parent_tabWidget=self.tabWidget, # language=language, font_size=self.fontsize) # text_editor = Editor() text_editor = IDEeditor(name=newfile_name, parent_tabWidget=self.tabWidget, language=language, font_content=self.font_content) text_editor.newFileSignal.connect(lambda: self.model.refresh()) # text_editor.textChange.connect(self.__handle_textChange) layout.addWidget(text_editor, 0, 0, 1, 1) tabitem = TabItem(tab_new, layout, text_editor) self.tab_dict[new_tabname] = tabitem self.tabWidget.addTab(tab_new, newfile_name) # 跳转到新页面 index = self.tabWidget.count() - 1 self.tabWidget.setCurrentIndex(index) if language == 'md': self.markdown_handler() def openfileEvent(self, file_path=None, mapping=None): r""" 打开文件事件函数 :return: None """ if not file_path: file_path, _ = QFileDialog.getOpenFileName( self, 'Choose a file', '/', 'All Files (*);;' 'Text Files (*.txt);;' 'Markdown Files (*.md);;' 'C Sources (*.c);;' 'Python Scripts (*.py)') if not file_path: return # 判断文件是否可读取 if os.path.isdir(file_path): # 屏蔽文件夹 return if not os.path.splitext(file_path)[-1] in ['.py', '.c', '.txt', '.md']: QMessageBox.warning(self, u'警告', u'文件类型不支持!') return if len(file_path): _, file_fullname = os.path.split(file_path) for tabitem in self.tab_dict.values(): tmp_edititem = tabitem.text if file_fullname == tmp_edititem.objectName(): index = self.tabWidget.indexOf(tabitem.tab) self.tabWidget.setCurrentIndex(index) return self.__create_tab(name=file_fullname) index = self.tabWidget.count() - 1 textedit = self.__get_textEditor(index=index) textedit.load(file_path, mapping) def openfolderEvent(self): folder_path = QFileDialog.getExistingDirectory(self, '请选择打开的文件夹') if folder_path: self.dirtree.setModel(self.model) self.dirtree.setRootIndex(self.model.index(folder_path)) self.dirtree.setAnimated(False) self.dirtree.setIndentation(20) self.dirtree.setSortingEnabled(True) self.dirtree.doubleClicked.connect(self.__choose_file) self.dirtree.setWindowTitle("Dir View") # self.dirtree.setHeaderHidden(True) def __choose_file(self, index): file_path = self.model.filePath(index) # print(file_path) self.openfileEvent(file_path) def saveasEvent(self): r""" 另存为事件函数 :return: None """ textedit = self.__get_textEditor() status = textedit.saveas() if status: """保存成功,设置tab名""" index = self.tabWidget.currentIndex() textedit = self.__get_textEditor(index) self.language = textedit.language self.lb_lang.setText(self.language) def savefileEvent(self): r""" 保存文件事件函数 :return: """ textedit = self.__get_textEditor() text_saveas = textedit.save() if text_saveas: self.language = textedit.language self.lb_lang.setText(self.language) def saveallEvent(self): r""" 全部保存 :return: """ for tabitem in self.tab_dict.values(): textedit = tabitem.text text_saveas = textedit.save() if text_saveas: self.language = textedit.language self.lb_lang.setText(self.language) def closefileEvent(self, index): r""" 关闭文件事件函数 :return: None """ if self.tabWidget.count() == 0: self.close() return cur_tab_name, tabitem = self.__find_tab_by_index(index) textedit = tabitem.text # print(cur_tab_name) if textedit.isModified(): """已修改文件,需要保存""" ret_code = QMessageBox.information( self, '提示', '文件尚未保存,确定退出?', QMessageBox.Yes | QMessageBox.No) # ret_code: Yes -- 16384 # No -- 65536 if ret_code == QMessageBox.Yes: textedit.closeText() self.tabWidget.removeTab(index) del self.tab_dict[cur_tab_name] else: textedit.closeText() self.tabWidget.removeTab(index) del self.tab_dict[cur_tab_name] def setFontSizeEvent(self): r""" 改变所有textedit的字体大小和样式 :return: """ for tabitem in self.tab_dict.values(): textedit = tabitem.text textedit.setFontSize(self.font_content) self.run_browser.set_font(self.font_content) def rewardEvent(self): r""" 打赏事件函数 :return: """ self.qrcode_window = Reward() self.qrcode_window.show() def showpreferenceEvent(self): r""" 调出偏好设置 :return: """ self.preference.show() def aboutusEvent(self): r""" 关于我们事件函数 :return: """ QMessageBox.information( self, 'About us', 'Monkey Editor v0.1\n' u'天猴工作室出品 \n' u'制作人:吴栋、廖满文、汪潇翔、文一晴、吴雨暄、张维天') def closeEvent(self, event): r""" 关闭notebook事件函数 :param event: :return: None """ # 缓存文件的文件夹 tmp_path = '.tmp' if os.path.exists(tmp_path): # os.system(f'rm -r {tmp_path}') shutil.rmtree(tmp_path) if len(self.tab_dict): os.mkdir(tmp_path) # check_quit = True increment = 1 mapping = {} # 地址映射表 for tabitem in self.tab_dict.values(): # 缓存当前未关闭的页面 textedit = tabitem.text if textedit.filepath is None: tmp_filename = f'Plain_{increment}.' + self.language mapping[tmp_filename] = None tmp_filepath = os.path.join(tmp_path, tmp_filename) increment += 1 else: _, tmp_filename = os.path.split(textedit.filepath) mapping[tmp_filename] = textedit.filepath tmp_filepath = os.path.join(tmp_path, tmp_filename) if textedit.isModified(): # check_quit = False tmp_filepath = os.path.join(tmp_path, '*' + tmp_filename) textedit.save(tmp_filepath) # 保存mapping try: with open(os.path.join(tmp_path, 'mapping.pkl'), 'wb') as f: pickle.dump(mapping, f) except: pass # if not check_quit: # ret_code = QMessageBox.information(self, '提示', '存在文件未保存,确定退出?', # QMessageBox.Yes | QMessageBox.No) # if ret_code == QMessageBox.Yes: # self.close() # else: # event.ignore() # else: # 保存preference self.preference.close() self.close() def markdown_handler(self): index = self.tabWidget.currentIndex() _, tabitem = self.__find_tab_by_index(index) current_tab = tabitem.tab current_layout = tabitem.layout current_text = tabitem.text # content = current_text.text() # content.replace(r'\r\n', r' \n') # content = '' # for i in range(linenum - 1): # current_content = current_text.document().findBlockByLineNumber(i).text() # current_content += ' \n' # content += current_content # for i in reversed(range(current_layout.count())): # current_layout.takeAt(i).widget().deleteLater() # markdown_tab = QtWidgets.QTabWidget(current_tab) # markdown_tab.setTabPosition(3) # orin = QWidget() # md = QWidget() # orin.setObjectName("orin") # md.setObjectName("md") # layout_orin = QGridLayout(orin) # text_editor_orin = TextEditorS(name='orin', parent_tabWidget=self.tabWidget, language=language) # layout_orin.addWidget(text_editor_orin, 0, 0, 1, 1) # layout_md = QGridLayout(md) # text_editor_txt = TextEditorS(name='md_txt', parent_tabWidget=self.tabWidget, # language='txt', font_content=self.font_content) text_browser_md = TextEditorS(name='md_show', parent_tabWidget=self.tabWidget, language='md') text_browser_md.setReadOnly(True) # text_editor_txt = TextEditorS(name='md_txt', parent_tabWidget=self.tabWidget, language='txt') # text_browser_md = TextEditorS(name='md_md', parent_tabWidget=self.tabWidget, language=self.language) # layout_md.addWidget(text_editor_txt, 0, 0, 1, 1) # layout_md.addWidget(text_browser_md, 0, 1, 1, 1) # markdown_tab.addTab(orin, 'orin') # markdown_tab.addTab(md, 'md') current_layout.addWidget(text_browser_md, 0, 1, 1, 1) # current_layout.addWidget(markdown_tab, 0, 0, 1, 1) tabitem = TabItem(current_tab, current_layout, current_text, text_browser_md) now_tabname = 'tab_' + str(self.tabidx) self.tab_dict[now_tabname] = tabitem current_text.linesChanged.connect(self.show_markdown) # text_editor_txt.document().blockCountChanged.connect(self.show_markdown) # text_editor_txt.setPlainText(content) # text_editor_txt.document().blockCountChanged.connect(self.show_markdown) def normalmode_handler(self): index = self.tabWidget.currentIndex() _, tabitem = self.__find_tab_by_index(index) current_tab = tabitem.tab current_layout = tabitem.layout current_text = tabitem.text if tabitem.textview != None: current_layout.itemAt(1).widget().close() tabitem = TabItem(current_tab, current_layout, current_text) now_tabname = 'tab_' + str(self.tabidx) self.tab_dict[now_tabname] = tabitem def show_markdown(self): current_tab = self.__get_tabitem() textedit = current_tab.text textview = current_tab.textview if textview != None: content = textedit.text() content = content.replace('\r\n', ' \n') textview.document().setMarkdown(content) # linenum = textedit.document().lineCount() # content = '' # for i in range(linenum - 1): # current_content = textedit.document().findBlockByLineNumber(i).text() # current_content += ' \n' # content += current_content def windowShow(self): youWin.show() #你的主页程序
def preference(self, category, likeness=0, can_work=True): return Preference(category, likeness, can_work)
brick = self.preference.brick margin = self.preference.margin self.bricks = pygame.sprite.Group() self.wall = Wall(self) self.bullet = Bullet(self) for x in range(self.preference.army[0]): for y in range(self.preference.army[1]): b = Brick(self, x * (brick[0] + margin[0]) + margin[0], y * (brick[1] + margin[1]) + margin[1]) self.bricks.add(b) def _update(self): self.wall.update() self.bricks.update() self.bullet.update() def _flip(self): self.display.fill((255, 255, 255)) self.wall.draw() self.bullet.draw() for brick in self.bricks: brick.draw() pygame.display.flip() if __name__ == '__main__': instance = Game(Preference())