def main(): setting = Setting() setting.parser() poly = Polynome(*setting.tab, setting.verbose, setting.graph) poly.process() poly.final() exit(0)
def __init__(self, parent=None): # 主窗口界面 super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setFixedSize(800, 600) self.difficulty = 3 # 难度 self.setWindowTitle('小学算术题 难度:%d' % self.difficulty) self.setWindowIcon(QIcon('res/image/windowIcon.jpg')) self.ui.pauseBtn.setIcon(QIcon('res/image/pause.png')) # 设置窗口界面 self.setting = Setting() self.setting._close_signal.connect(self.on_setting_closed) # 音效加载 self.playlist = QMediaPlaylist() self.playlist.addMedia(QMediaContent(QUrl('res/audio/correct.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/wrong.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/complete.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/timeOver.mp3'))) self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.play() # 定义变量 self.answer = 0 self.total = 0 self.correct = 0 self.accuracy = 0. self.overtime = 0 self.tmpOutput = [] # 保存路径 self.fpath = 'history.txt' # 定时器初始化 self.timeLimit = 30 self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.currentTime = self.timeLimit self.ui.timeLabel.setText(str(self.currentTime)) self.pause = False # 错题模式初始化 self.mistakeBatchSize = 5 self.mistakeMode = False self.exitingMistakeMode = False self.ui.tipLabel.clear() self.ui.remainingLabel.clear() self.questionQueue = [] # 第一次开始运行 self.refreshQuestion() self.refreshBoard() # 计时器开始计时 self.timer.start(1000)
def tof_counter(update: Update, _: CallbackContext) -> None: """Echo the user message.""" # update.message.reply_text(update.message.text) num = update.message.text.count('تف تو قبر امیر') chat_id = update.message.chat['id'] data = [] try: with open('data.txt', 'r') as file: for line in file: col = line.split() if col[0] == str(chat_id): col[1] = str(int(col[1]) + num) data.append(col) except FileNotFoundError: print("File not accessible") flag = False for row in data: if row[0] == str(chat_id): flag = True if flag is False: data.append([str(chat_id), str(num)]) with open('data.txt', 'w') as file: for row in data: for col in row: file.write(col + ' ') file.write('\n') Setting.inc_cnt(num)
def __init__(self, controller=PresenterFromViewInterface()): self.controller = controller print('PyQt version: '+QtCore.qVersion()) Setting.desktop = QApplication.desktop().screenGeometry() if Setting.view_debug: print('Running view on display: ', Setting.desktop) self.thumb_view = QTThumbViewer(view_manager=self) self.picture_view = PictureView(view_manager=self) self.video_view = VideoView(view_manager=self) self.tool_box = ToolBox(view_manager=self) self.config_dialog = None self.playlist = QTPlaylistView(Qt_WindowFlags_flags=QtCore.Qt.Tool | QtCore.Qt.WindowStaysOnTopHint, view_manager=self, player=self.video_view.video_player) self.thumb_view.setGeometry(Setting.thumb_view_geometry()) self.picture_view.setGeometry(Setting.full_view_geometry()) self.video_view.setGeometry(Setting.full_view_geometry()) self.tool_box.setGeometry(Setting.tool_box_geometry()) self.playlist.setGeometry(Setting.playlist_geometry()) self.picture_view.hide() self.video_view.hide() self.playlist.hide() self.add_keyboard_shortcut(self.thumb_view, 'Ctrl+`', self.controller.panic) # self.add_keyboard_shortcut(self.video_view,'Space',lambda: (self.video_view.video_player.little_forvard(30))) self.thumb_view.show()
def got_setting(self, result, error): if error: logging.error('got_setting error: %s %s', error, result) self.send_error(204) return user_setting = result and Setting(result) or Setting.default() if 'width' not in user_setting: user_setting = Setting.default() if self.cache: raw = user_setting.get(str(self.pid), None) if raw: self.set_header("Content-Type", "image/png") self.set_header("Content-Length", len(raw)) self.finish(raw) return try: self.u = arch.user.User.get(self.uid) except Exception, e: logging.error('userbase error: %d %s', self.uid, e) self.send_error(204) return
def generate_ssl_host_csr(settings: Setting, destdir: pathlib.Path): for group_name in settings.get_group_names(): for hostname in settings.get_hostnames_in_group(group_name): role_name = settings.get_role_of(hostname) if role_name == 'master': generate_ssl_kubernetes_master_csr(settings, destdir.joinpath(hostname), hostname) elif role_name == 'worker': generate_ssl_kubernetes_worker_csr(settings, destdir.joinpath(hostname), hostname)
def get_settings(game): settings = Group() scr = game.scr dic = game.current_settings settings.append( Setting(scr, "Show FPS Counter", [True, False], dic['Show FPS Counter'], 0, 150)) settings.append( Setting(scr, "Cap FPS To 60", [True, False], dic['Cap FPS To 60'], 0, 250)) return settings
def aline_invasion_game_handle(): #创建默认设置对象(获取默认设置参数) settings = Setting() screen_size = settings.get_screen_size() #初始化pygame模块、创建一个屏幕对象、设置标题栏标题 pygame.init() screen = pygame.display.set_mode(screen_size) pygame.display.set_caption("疯狂外星人") #初始化游戏状态 status = GameStats(settings) game.game_init_deal(status, settings) new_ship = game.create_new_ship(screen, settings) #创建PLAY按钮 button_attr = settings.button button_attr["text_msg"] = "PLAY" play_bubtton = Button(screen, button_attr) #STOP提示栏 button_attr["text_msg"] = "STOP" stop_bubtton = Button(screen, button_attr) #计分板 score = ScoreBoard(screen, settings, status) #游戏主循环 while True: #屏幕背景色颜色绘制 screen_attr = settings.screen.copy() surface_screen_color_draw(screen, screen_attr["color"]) #处理pygame系统事件 game.event_traverl_deal(settings, \ screen, new_ship, play_bubtton, status) #暂停(提示,按钮不可按) if status.game_stop: stop_bubtton.__draw__() score_board_draw(score) pygame.display.flip() continue if not status.game_over: #处理外星人、子弹、飞船在屏幕中的位置以及相关逻辑 game.update_game_status(screen, settings, new_ship, status) #游戏结束则绘制按钮并处理一些统计信息等数据 game.game_over_check(status, new_ship, play_bubtton, settings) #绘制最新屏幕(刷新) score_board_draw(score) pygame.display.flip()
class LevelOne(Level): def __init__(self): super().__init__() self.unit_current_count = 6 self.unit_exist_count = 0 self.setting = Setting() def load(self, config): super().load(config) rect = self.screen.get_rect() self.ship.set_poisition({ 'centerx': rect.centerx, 'bottom': rect.bottom }) self.ship.set_boundary({'left': 0, 'right': rect.right}) for unit_type, unit_count in self.unit_type_list.items(): self._create_unit(unit_type, self.unit_current_count) self.unit_exist_count += self.unit_current_count b = BulletDouble(self.setting.bulletSetting()) b1 = BulletNormal(self.setting.bulletSetting()) self.ship.add_bullet(b) self.ship.add_bullet(b1) def run(self): if len(self.unit_list) <= 0: self.end() if len(self.unit_list) < self.unit_current_count: for unit_type, unit_count in self.unit_type_list.items(): if self.unit_exist_count < unit_count: self._create_unit(unit_type, 1) self.unit_exist_count += 1 super().run() def is_end(self): if len(self.unit_list) <= 0: return True return False def end(self): print('win') self.unit_list.empty() # 生成单元 def _create_unit(self, unit_type, count): sapcing = 30 tmp = 0 x = 0 while count > tmp: alien = Unit.create_unit(unit_type) alien.rect.x += x x = alien.rect.x + alien.width + sapcing tmp += 1 self.unit_list.add(alien)
def __init__(self): self.setting = Setting() self.cli1_dir = os.path.join(os.getcwd(), 'cli1') self.cli2_dir = os.path.join(os.getcwd(), 'cli2') self.worktree1 = os.path.join(os.getcwd(), 'worktree1') self.worktree2 = os.path.join(os.getcwd(), 'worktree2') self.enc_repo = False try: self.enc_repo = bool(os.environ['ENCRYPTED_REPO']) except Exception: pass self.repo_id = None
def __init__(self): pygame.init() self.setting1 = Setting() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.screen_rect = self.screen.get_rect() pygame.display.set_caption('Alien Invasion') self.stats = Gamestats(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'PLAY') self.sb = Scoreboard(self)
def test(): from setting import Setting qeOut = QEOutput(Setting('config.ini'), 'pw') print qeOut.listParsers() qeOut.parse() print qeOut.properties() qeOut.parse(['total energy', 'stress']) print qeOut.properties() print qeOut.property('total energy') print qeOut.property('stress') qeOut = QEOutput(Setting('config.ini'), 'matdyn') print qeOut.listParsers() qeOut.parse() print qeOut.properties()
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.labels[0].setText(_translate("MainWindow", "게시판 URL")) self.labels[1].setText(_translate("MainWindow", "다운로드 폴더 경로")) self.labels[2].setText(_translate("MainWindow", "저장 폴더 경로")) self.labels[3].setText(_translate("MainWindow", "Chrome Driver 경로")) self.checkBox.setText(_translate("MainWindow", "개념글")) self.radioButton.setText(_translate("MainWindow", "존재 파일 건너뛰기")) self.group1Box.setTitle(_translate("MainWindow", "번호 지정 받기")) self.group1Box.pushButton.setText(_translate("MainWindow", "시작")) self.group1Box.labels[0].setText(_translate("MainWindow", "시작 번호")) self.group1Box.labels[1].setText(_translate("MainWindow", "끝 번호")) self.group2Box.setTitle(_translate("MainWindow", "선택 지정 모드")) self.group2Box.pushButton.setText(_translate("MainWindow", "시작")) setting = Setting(initSetting=True) self.textEdits[0].setText(setting.postListUrl) self.textEdits[1].setText(setting.downloadDirPath) self.textEdits[2].setText(setting.saveDirPath) self.textEdits[3].setText(setting.chromeDriverPath) self.checkBox.setChecked(setting.recommend) self.radioButton.setChecked(setting.passExistFile) self.group1Box.pushButton.clicked.connect(self.startSelectRangeMode)
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Setting() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() #开始游戏主循环 while True: #监控键盘和鼠标事件 gf.check_events(ai_settings, screen, ship, bullets) ship.update() if ship.bullet_on: # 创建一个子弹,并将其加入编组bullet中 new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) bullets.update() # 删除已经消失的子弹 for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) print(len(bullets)) # 每次循环时都重绘整个屏幕 gf.update_screen(ai_settings, screen, ship, bullets)
def run_game(): # 初始化游戏,并创建一个屏幕对象 pygame.init() ai_settings = Setting() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, aliens) # 设置背景色 bg_color = (230, 230, 230) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, aliens, bullets)
def run_game(): #initial game and make a screen target pygame.init() setting = Setting() screen = pygame.display.set_mode((setting.screen_width, setting.screen_height)) ship = Ship(setting, screen) bullets = Group() aliens = Group() gf.creat_fleet(setting, screen, aliens) pygame.display.set_caption(setting.caption) #begin main loop while True: #watch keyboard and mouse gf.check_events(ship, bullets, setting, screen) ship.update_position() bullets.update() aliens.update() #delete bullet outside of the screen for bullet in bullets.copy(): if bullet.rect.bottom < 0: bullets.remove(bullet) #move aliens gf.get_fleet_direction(aliens, setting) #kill aliens gf.kill(aliens, bullets) #refresh screen gf.update_screen(screen, setting, ship, bullets, aliens)
def main(): pygame.init() al_setting = Setting() bullets = Group() aliens = Group() stats = GameStats(al_setting) # 设置屏幕 screen = pygame.display.set_mode((al_setting.screen_width, al_setting.screen_height)) pygame.display.set_caption(al_setting.game_title) play_button = Button(al_setting, screen, 'Start') score_board = ScoreBoard(al_setting, screen, stats) # 创建飞船 ship = Ship(screen, al_setting) # 创建外星人 gf.create_aliens(al_setting, screen, aliens, ship.rect.height) # 开启游戏主循环 while True: # stats.game_active # 处理事件 event.check_event(al_setting, screen, ship, bullets, play_button, stats, aliens, score_board) if stats.game_active: # 更新位置 ship.update() gf.update_bullets(al_setting, screen, ship, bullets, aliens, score_board, stats) gf.update_aliens(al_setting, screen, ship, bullets, aliens, stats, score_board) #score_board.pre_score() # 绘制 gf.update_screen(al_setting, screen, ship, bullets, aliens, play_button, stats, score_board)
def main(argv=None): if argv is None: argv = sys.argv pygame.init() st = Setting() screen: pygame.Surface = pygame.display.set_mode(st.SCREEN_SIZE) print(type(screen)) pygame.display.set_caption('Tik Tak V3') clock = pygame.time.Clock() sprites = pygame.sprite.Group() number = 0 for row in range(st.BLOKS): for column in range(st.BLOKS): number += 1 w = column * st.SIZE_BLOKS + (column + 1) * st.MARGIN h = row * st.SIZE_BLOKS + (row + 1) * st.MARGIN cell = Cell(w, h, number, st) sprites.add(cell) font_game = pygame.font.Font(None, 24) text_user = font_game.render('Ваши-Крестики, ПК-Нолики', 1, st.RED) first_step = random.randint(0, 1) font_game = pygame.font.Font(None, 24) if first_step == 0: text_step = font_game.render('Первый ходит ПК', 1, st.RED) else: text_step = font_game.render('Первый ход за Вами', 1, st.RED) running = True # Цикл игры while running: # Держим цикл на правильной скорости clock.tick(st.FPS) # Ввод процесса (события) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: sprite: Cell for sprite in sprites: if sprite.mouse_click(pygame.mouse.get_pos()): sprite.cell_change(st) print(sprite.number) # Обновление sprites.update() # Рендеринг screen.fill(st.BLACK) sprites.draw(screen) screen.blit(text_user, (10, st.WIDTH)) screen.blit(text_step, (10, st.WIDTH + 20)) # После отрисовки всего, переворачиваем экран pygame.display.flip() pygame.quit()
def run_game(): # 初始化屏幕对象 pygame.init() alien_setting = Setting() screen = pygame.display.set_mode((alien_setting.screen_width,\ alien_setting.screen_height)) # 屏幕 ship = Ship(alien_setting, screen) # 子弹集合 bullets = Group() # 外星人集合, aliens = Group() # 描述状态 stats = GameStats(alien_setting) # 创建一群外星 gf.create_feet(alien_setting, screen, ship, aliens) sb = Scoreboard(alien_setting, screen, stats) start_button = Button(alien_setting, screen, "Start") pygame.display.set_caption('王尼玛大作战') # 游戏标题 while True: # 监听鼠标键盘事件 gf.check_events(alien_setting, stats, sb, start_button, screen, ship, bullets, aliens) # 时刻刷新王尼玛的位置 if stats.game_active: ship.update() gf.update_bullet(alien_setting, screen, stats, sb, aliens, bullets, ship) gf.update_aliens(alien_setting, stats, sb, screen, ship, aliens, bullets) # 最近绘制的图像屏幕可见 gf.update_screen(alien_setting, screen, stats, sb, ship, aliens, bullets, start_button)
def run_game(): pygame.init() setting = Setting() screen = pygame.display.set_mode( (setting.screen_width, setting.screen_height)) ship = Ship(setting, screen) alien = Alien(setting, screen) bullets = Group() aliens = Group() gf.create_fleet(setting, screen, ship, aliens) pygame.display.set_caption('Alien_Invantion') stats = GameStats(setting) sb = Scoreboard(setting, screen, stats) play_button = Button(setting, screen, "Play") while True: gf.check_event(setting, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() bullets.update() gf.update_bullets(setting, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(setting, stats, screen, sb, ship, aliens, bullets) gf.update_screen(setting, screen, stats, sb, ship, bullets, aliens, play_button)
def run_game(): pygame.init() ai_setting = Setting() screen = pygame.display.set_mode( (ai_setting.screen_width, ai_setting.screen_height)) pygame.display.set_caption("外星人大战") ship = Ship(ai_setting, screen) # 创建存储子弹的编组 bullets = Group() #创建一个外星人 aliens = Group() gameState = GameState(ai_setting) sb = ScoreBoard(ai_setting, screen, gameState) play_button = Button(ai_setting, screen, 'Play') gf.create_fleet(ai_setting, screen, ship, aliens) while True: gf.check_events(ai_setting, gameState, aliens, screen, ship, bullets, play_button, sb) if gameState.game_active: ship.update() gf.update_bullets(ai_setting, screen, gameState, sb, ship, aliens, bullets) gf.update_aliens(ai_setting, gameState, sb, screen, ship, aliens, bullets) gf.update_screen(ai_setting, gameState, screen, ship, aliens, bullets, play_button, sb)
def __init__(self, arg): # setting self.name_map = arg.name_map self.opt = Setting() # pygame pygame.init() self.screen = pygame.display.set_mode(self.opt.WINDOW_SIZE) pygame.display.set_caption(self.opt.TITLE % self.name_map) self.clock = pygame.time.Clock() self.set_grill_surface() # data self.path = os.path.dirname(__file__) self.path_img = os.path.join(self.path, "..", "src", "img") file = self.name_map + self.opt.LUA_FORMAT self.path_maps = os.path.join(self.path, "..", "src", "maps", file) self.create = not os.path.exists(self.path_maps) # objects self.builder = Builder(self) self.converter = Converter(self) self.images = Images(self) self.map = Map(self) self.selector = Selector(self) self.toolbar = Toolbar(self) # loop self.saved = True self.loop() pygame.quit()
def run_game(): gn_settings = Setting() print('Let\'s begin the game!') #开始游戏主循环 while gn_settings.begin: f.guess(gn_settings.num) f.go_on_game()
def run_game(): #初始化 pygame.init() ai_setting = Setting() screen = pygame.display.set_mode( (ai_setting.screen_width, ai_setting.screen_hight)) #创建窗口 ship = Ship(ai_setting, screen) #实例化飞船 stats = Gamestats(ai_setting) #统计信息 sb = Scoreboard(ai_setting, screen, stats) #scoreboard记分牌 bullets = Group() #创建子弹的一个列表 aliens = Group() #同上 gf.create_fleet(ai_setting, screen, ship, aliens) play_button = Button(ai_setting, screen, "Play") # 检测操作->game_function while True: gf.check_event(ai_setting, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_setting, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_setting, screen, stats, sb, ship, aliens, bullets) gf.upgrade_screen(ai_setting, screen, stats, sb, ship, aliens, bullets, play_button) #更新屏幕函数
def run_game(): pygame.init() ai_settings = Setting() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") play_button = Button(ai_settings, screen, "Play") stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) ship = Ship(ai_settings, screen) aliens = Group() bullets = Group() gf.create_fleet(ai_settings, screen, aliens, ship) while True: gf.check_events(ai_settings, screen, ship, bullets, stats, play_button, aliens, sb) if stats.game_active: ship.update() gf.update_bullets(ai_settings, ship, screen, bullets, aliens, stats, sb) gf.update_aliens(ai_settings, aliens, ship, stats, screen, bullets, sb) gf.update_screen(ai_settings, screen, ship, bullets, aliens, play_button, stats, sb)
def getTreeWidgetItemFromGraphSetting(self, graphSetting = Setting().getInitSettings()["graphSet"]["graphSet1"]["graphs"]["graph1"]): item = QTreeWidgetItem([""]) item.setText(0, graphSetting["title"]) item.setText(1, graphSetting["backgroundColor"]) item.setText(2, str(graphSetting["position"])) item.setText(3, str(graphSetting["span"])) item.setText(4, str(graphSetting["size"])) item.setText(5, str(graphSetting["plots"])) item.setText(6, str(graphSetting["range"])) item.setText(7, str(graphSetting["tick"])) item.setText(8, graphSetting["xAxisTitle"]) item.setText(9, graphSetting["xAxisTitleColor"]) item.setText(10, graphSetting["y1AxisTitle"]) item.setText(11, graphSetting["y1AxisTitleColor"]) item.setText(12, graphSetting["y2AxisTitle"]) item.setText(13, graphSetting["y2AxisTitleColor"]) item.setText(14, graphSetting["y3AxisTitle"]) item.setText(15, graphSetting["y3AxisTitleColor"]) item.setText(16, str(graphSetting["yAxisNum"])) item.setText(17, str(graphSetting["position"]["c"]) + "-" + str(graphSetting["position"]["r"]) + " (" + str(graphSetting["span"]["c"]) + "-" + str(graphSetting["span"]["r"]) + ")") item.setText(18, str(graphSetting["size"]["h"]) + "*" + str(graphSetting["size"]["w"])) item.setText(19, str(len(graphSetting["plots"].keys()))) return item
def select_setting_file(self): """ 选择配置文件 :return: """ setting_file = QFileDialog.getOpenFileName(self, "选择配置文件", filter="JSON Files(*.json)") self.setting = Setting(setting_file[0])
def run_game(): #初始化游戏并创建一个屏幕对象 pygame.init() setting = Setting() screen = pygame.display.set_mode((setting.screen_width,setting.screen_height)) pygame.display.set_caption('扫雷') #加载图片资源 flags = [setting.flag0_image, setting.flag1_image, setting.flag2_image] nums = [setting.num_0_image, setting.num_1_image, setting.num_2_image, setting.num_3_image, setting.num_4_image, setting.num_5_image, setting.num_6_image, setting.num_7_image, setting.num_8_image] bomb_image = setting.bomb0_image #创建统计信息和计分牌 stats = GameStats(setting) sb = Scoreboard(setting, screen, stats) #创建重玩的按键图片 reset_button = Button(setting, screen) #创建cubes编组 cubes = Group() gf.create_cubes(setting, screen, cubes) #创建bombs编制 bombs = Group() gf.create_bombs(setting, screen, bombs) #开始游戏的主循环 while True: gf.check_event(setting, screen, bombs, cubes, flags, nums, stats, bomb_image, reset_button) gf.update_screen(setting, screen, cubes, bombs, stats,reset_button,sb) gf.check_win(setting, screen, cubes, bombs, stats,reset_button)
def run_game(): pygame.init() ai_setting = Setting() screen = pygame.display.set_mode( (ai_setting.screen_width, ai_setting.screen_height)) pygame.display.set_caption('MO') ship = Ship(screen, ai_setting) bullets = Group() aliens = Group() gf.create_aliens(ai_setting, screen, aliens, ship) stats = GameStats(ai_setting) score = Scoreboard(ai_setting, screen, stats) play_button = Button(ai_setting, screen, 'PLAY') while True: gf.check_event(ai_setting, screen, ship, bullets, stats, play_button, score) if stats.game_active: ship.update() gf.update_bullets(ai_setting, screen, ship, aliens, bullets, stats, score) gf.update_aliens(ai_setting, screen, ship, aliens, bullets, stats, score) gf.update_screen(ai_setting, screen, ship, aliens, bullets, stats, play_button, score)
def __init__(self, parent=None, record=None, favorites=None): QDialog.__init__(self, parent) self.favorites = favorites self.record = record self.ui = Ui_EditDialog() self.ui.setupUi(self) self.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.WindowStaysOnTopHint) self.setGeometry(Setting.fav_change_dialog_geometry()) if record.is_thumb(): self.ui.input_type.setText('Thumbnail page') elif record.is_pix(): self.ui.input_type.setText('Pictures page') elif record.is_video(): self.ui.input_type.setText('Video page') else: self.ui.input_type.setText('Unknown page') if record.name != '': self.ui.input_name.setText(self.record.name) else: self.ui.input_name.setText(self.record.url.get()) self.ui.input_url.setText(self.record.url.get()) self.ui.combo_category.addItems(self.favorites.get_categories()) self.ui.combo_category.setCurrentText(record.category) self.ui.check_delete.stateChanged.connect(self.check_state_changed)
def run_game(): pygame.init() ai_setting = Setting() screen = pygame.display.set_mode(( ai_setting.screen_width, ai_setting.screen_height )) pygame.display.set_caption("Alien Invasion") #创建一个用于储存游戏统计信息的实例 stats = GameStats(ai_setting) #创建一艘飞船 一个子弹编组和一个外星人编组 ship = Ship(ai_setting, screen) bullets = Group() aliens = Group() #创建外星人群 gf.create_fleet(ai_setting, screen, ship, aliens) while True: gf.check_events(ai_setting, screen, ship, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_setting, screen, ship, aliens, bullets) gf.update_aliens(ai_setting, stats, screen, ship, aliens, bullets) gf.update_screen(ai_setting, screen, ship, aliens, bullets)
def _call(self, method, url, params, file, completed_data, failed_data): completed_id = self.connect('transfer-completed', self._completed_cb, completed_data) failed_id = self.connect('transfer-failed', self._failed_cb, failed_data) self.request(method, Setting.get_url(url), params, file) self.disconnect(completed_id) self.disconnect(failed_id)
class Issue(object): ISSUE_URL = 'issues/%s.json?include=attachments' def __init__(self, issue): self._issue = str(issue) self._setting = Setting() def get_attachments(self, chunk): url = self._get_issue_url() issue_metadata = json.loads(self._request(url)) attachments = sorted(issue_metadata['issue']['attachments'], key=lambda a: a['created_on']) attachments.reverse() # make sure it has exactly what we asked for issue_path = self._get_issue_path() if os.path.exists(issue_path): shutil.rmtree(issue_path) os.makedirs(issue_path) for attachment in attachments[:chunk]: path = os.path.join(issue_path, attachment['filename']) with file(path, 'w') as dump: dump.write(self._request(attachment['content_url'])) print 'Dumped %s from %s' % (path, attachment['content_url']) def _request(self, url): headers = {'X-Redmine-API-Key': self._setting.get_key()} req = urllib2.Request(url, None, headers) try: response = urllib2.urlopen(req) except urllib2.HTTPError as err: raise LookupError('Could not retrieve %s (%s)' % (url, str(err))) else: return response.read() def _get_issue_url(self): return urlparse.urljoin(self._setting.get_host(), self.ISSUE_URL % self._issue) def _get_issue_path(self): return os.path.join(self._setting.get_path(), self._issue)
def __init__(self, superuser=None, computer=None, user=None, code=None, branch=None, id_local_process='unused', type_list=[None], case_list=[[None]], configuration_list=[None], flow_process_list=[None], element_type_list=[[None]], operation_type=None, operation=None, test_mode='0', db_user='******', db_password='******', db_host='localhost', db_schema='testing_environment'): """ These parameters can be preselected: belong to (test) Subject: :param superuser: has accounts on separate computer :param computer: :param user: :param code: belongs to source code tree :param branch: belongs to source code tree belong to (test) Item: :param type_list: belongs to example tree :param case_list: belongs to example tree :param configuration_list: belongs to example tree :param flow_process_list: :param element_type_list: :param operation_type: one-character string [b: building,s: simulating,p: plotting] :param operation: one-character string - meaning depends on operation_type :param test_mode: Parameters to access database: :param db_user: :param db_password: :param db_host: :param db_schema: """ self.__flow_process_name_list = flow_process_list self.__element_type_name_list = element_type_list db_inst = Database(db_user, db_password, db_host, db_schema) self.__subject_inst = Subject(superuser, computer, user, code, branch, id_local_process) self.__setting_inst = Setting(type_list, case_list, configuration_list, operation_type, operation, test_mode, db_inst) if location == 'local': self.__subject_inst.print_selected_variables() self.__setting_inst.print_selected_variables() print('\n-----------------------------------------------------------------')
def __init__(self, filename = None, configString = None, cleanOutDir = False): # parallelization parameters # Default values, see explanations below: #self.name = 'Launcher' self._isSerial = True self._mergedTask = False configDic = { 'useTorque' : 'False', 'paraTorqueParams': '-l nodes=1:ppn=1', 'serialTorqueParams': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '', 'serialPrefix': '', 'serialPostfix': '', 'paraRemoteShell': '', 'outdir': None } if filename == None and configString == None: filename = 'config.ini' self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) self.cleanOutDir = cleanOutDir if self.setting.get('useTorque') == 'True': self.setting.set('useTorque', True) else: self.setting.set('useTorque', False) if self.setting.get('useTorque'): if self.isSerial(): self._torque = QETorque(self.setting.get('serialTorqueParams')) else: self._torque = QETorque(self.setting.get('paraTorqueParams'))
def __init__(self, filename = None, configString = None, cleanOutDir = None): # parallelization parameters # Default values, see explanations below: #self.name = 'Launcher' configDic = { 'useTorque' : 'False', 'torqueResourceList': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '' } self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) self.cleanOutDir = cleanOutDir if self.setting.useTorque == 'True': self.setting.useTorque = True else: self.setting.useTorque = False if self.setting.useTorque: self._torque = QETorque(self.setting.torqueResourceList)
def readSetting(self, filename = None, configString = None, \ sectionName = None): """ Initializes setting class """ configDic = { 'useTorque' : 'False', 'paraTorqueParams': '-l nodes=1:ppn=1', 'serialTorqueParams': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '', 'serialPrefix': '', 'serialPostfix': '', 'paraRemoteShell': '', 'outdir': None } # if filename == None and configString == None: # configString = '' # filename = 'config.ini' if filename == None and configString == None: self.setting = Setting(configString = "") else: self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) if self.setting.get('useTorque') == 'True': self.setting.set('useTorque', True) else: self.setting.set('useTorque', False) if self.setting.get('useTorque'): if self.isSerial(): self._torque = QETorque(self.setting.get('serialTorqueParams')) else: self._torque = QETorque(self.setting.get('paraTorqueParams')) # ********************************************************************** # Task subclass specific part: if hasattr(self, '_type'): defaultModName = 'QESInput' modname = self._inputConstructor #Input = __import__("qeparser." + modname.lower(), globals(), \ # locals(), [modname], -1) mod_cmd = "from qeparser.%s import %s as Input"%(modname.lower(), modname) exec(mod_cmd) from qeparser.qeoutput import QEOutput if sectionName == None: name = self.name() else: name = sectionName self.setting.section(name, self._configDic) # add pointer to setting for input filenames synchronization #self.input._setting = self.setting self.output = QEOutput(self.setting, type = self._type) args = { 'setting': self.setting, } if modname == defaultModName: args['type'] = self._type if filename != None or configString != None: self.input = Input(**args) self.syncSetting() else: # add parse: args['parse'] = False self.input = Input( **args)
class QETask(object): """ Base abstract class for 'TaskNameTask' family of classes. It also provides the interface to launch tasks All user defined tasks should be derived from this class setting -- provides access to parallel environment and QE input/output files """ def __init__(self, filename = None, configString = None, cleanOutDir = False): # parallelization parameters # Default values, see explanations below: #self.name = 'Launcher' self._isSerial = True self._mergedTask = False self.cleanOutDir = cleanOutDir QETask.readSetting(self, filename, configString) def readSetting(self, filename = None, configString = None, \ sectionName = None): """ Initializes setting class """ configDic = { 'useTorque' : 'False', 'paraTorqueParams': '-l nodes=1:ppn=1', 'serialTorqueParams': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '', 'serialPrefix': '', 'serialPostfix': '', 'paraRemoteShell': '', 'outdir': None } # if filename == None and configString == None: # configString = '' # filename = 'config.ini' if filename == None and configString == None: self.setting = Setting(configString = "") else: self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) if self.setting.get('useTorque') == 'True': self.setting.set('useTorque', True) else: self.setting.set('useTorque', False) if self.setting.get('useTorque'): if self.isSerial(): self._torque = QETorque(self.setting.get('serialTorqueParams')) else: self._torque = QETorque(self.setting.get('paraTorqueParams')) # ********************************************************************** # Task subclass specific part: if hasattr(self, '_type'): defaultModName = 'QESInput' modname = self._inputConstructor #Input = __import__("qeparser." + modname.lower(), globals(), \ # locals(), [modname], -1) mod_cmd = "from qeparser.%s import %s as Input"%(modname.lower(), modname) exec(mod_cmd) from qeparser.qeoutput import QEOutput if sectionName == None: name = self.name() else: name = sectionName self.setting.section(name, self._configDic) # add pointer to setting for input filenames synchronization #self.input._setting = self.setting self.output = QEOutput(self.setting, type = self._type) args = { 'setting': self.setting, } if modname == defaultModName: args['type'] = self._type if filename != None or configString != None: self.input = Input(**args) self.syncSetting() else: # add parse: args['parse'] = False self.input = Input( **args) def name(self): return 'Launcher' def parse(self): self.syncSetting() def syncSetting(self): """ Will syncronise QE input file with class Setting for given task (QE input files may contain multiple input/ouput file names definitions which can be overriden in this method) """ pass def cleanOutputDir(self, cleanOutDir = None): """ Cleans the output directory (directory, where large files, used for calculation are stored, can be for example 'temp/' or 'scratch/') """ # import shutil if cleanOutDir == None: cleanOutDir = self.cleanOutDir # if cleanOutDir == None: # raise Exception('outDir can not be cleaned, since it was not defined') if cleanOutDir: outDir = self.setting.get('outdir') os.system(self.setting.paraRemoteShell + ' rm -r -f ' + outDir) os.system(self.setting.paraRemoteShell + ' mkdir ' + outDir) # if self.setting.useTorque: # # else: # shutil.rmtree(cleanOutDir) # os.mkdir(cleanOutDir) # def cmdLine(self): # """ # returns command string of a given task # """ # return self._cmdStr def launch(self, cleanOutDir = False): """ Parses input. Launches task. Parses output. """ # if cleanOutDir == None: # cleanOutDir = self.cleanOutDir # if cleanOutDir != None: # self.cleanOutputDir(cleanOutDir) #self.input.parse() self.syncSetting() # sync setting with QE input file self.input.save() self.cleanOutputDir(cleanOutDir) self._run() self.output.parse(parserList = 'all') def setSerial(self): #self._serialThroughMPI = serialThroughMPI self._isSerial = True def setParallel(self): self._isSerial = False def isSerial(self): if self._isSerial: return True else: return False def getPrefix(self) : if self.isSerial(): # if self._isSerialThroughMPI(): # return '' # else: return self.setting.get('serialPrefix') else: return self.setting.get('paraPrefix') def getPostfix(self): if self.isSerial(): return self.setting.get('serialPostfix') else: return self.setting.get('paraPostfix') def isMerged(self): return self._mergedTask def _initCmdLineParams(self): self._inp = '-inp' self._devnul = '< /dev/null' if self.isSerial(): self._inp = '<' self._devnul = '' # def _isSerialThroughMPI(self): # if self.isSerial(): # if self._serialThroughMPI: # return True # else: # return False def _check(self, x): """ Will check the exit status of the program to be executed """ signal = x & 0xFF exitcode = (x >> 8) & 0xFF if exitcode != 0: raise Exception("Task " + self.name() + " crashed: check your \ settings!\n" + "Command string: " + self.cmdLine()) def _run(self): if os.path.exists('CRASH'): os.remove('CRASH') outdir = self.setting.get('outdir') if outdir != None: os.system(self.setting.paraRemoteShell + ' mkdir -p ' + outdir) if self.setting.get('useTorque'): if self.isSerial(): if self.setting.get('serialPrefix') == '': self._check(os.system(self.cmdLine())) else: self._torque.serial(self.cmdLine(), torqueParams = self.setting.serialTorqueParams) else: self._torque.serial(self.cmdLine(), torqueParams = self.setting.paraTorqueParams) else: self._check(os.system(self.cmdLine())) # if self.setting.paraPrefix != '' and self.setting.paraPrefix in self.cmdLine(): # if self.setting.useTorque: # self._torque.serial(self.cmdLine()) # else: # self._check(os.system(self.cmdLine())) # else: # self._check(os.system(self.cmdLine())) if os.path.exists('CRASH'): raise Exception("Task " + self.name() + " crashed: 'CRASH' file was discovered") def _getCmdLine(self, executable, input, output): self._initCmdLineParams() return self.getPrefix() + ' ' + executable + " " + self.getPostfix() + \ ' ' + self._inp + ' ' + self.setting.get(input) + ' > ' + \ self.setting.get(output) + self._devnul def _setSetiingInputOutput(self, configDic, filename = None, configString = None, sectionName = None): """ Helper method for readSetting() """ if sectionName == None: name = self.name() else: name = sectionName self.setting.section(name, configDic) self.input = PWInput( self.setting.pwInput ) #self.setting.get('pwInput') ) # add pointer to setting for input filenames synchronization self.input._setting = self.setting self.output = QEOutput(self.setting, type='pw') if filename != None or configString != None: self.syncSetting()
def _url(self, url): return Setting.get_url(url)
class Mainboard: def __init__(self): """ """ self._modules = [] self._size = None self._screen = None self._isDisplayOn = True # Загружаем настройки из конфиг файла self._config = Setting() self._config.load(FILE_SETTING) self._managerList = { "Time": BlockTime(logger, self._config), "Alarm": BlockAlarm(logger, self._config), "Voice": BlockVoice(logger, self._config), "YandexNews": BlockYandexNews(logger, self._config), "OpenWeatherMap": BlockOpenWeatherMap(logger, self._config), "WunderGround": BlockWunderGround(logger, self._config), "Calendar": BlockCalendar(logger, self._config), "Swap": BlockSwap(logger, self._config), "Watcher": BlockWatcher(logger, self._config), "MT8057": BlockMT8057(logger, self._config), "YandexWeather": BlockYandexWeather(logger, self._config), "IR": BlockIR(logger, self._config), } for name in self._config._blockList: if name in self._managerList: self._modules.append(self._managerList[name]) print(name) # Based on "Python GUI in Linux frame buffer" # http://www.karoltomala.com/blog/?p=679 # Check which frame buffer drivers are available # Start with fbcon since directfb hangs with composite output drivers = ["x11", "windib"] found = False for driver in drivers: # Make sure that SDL_VIDEODRIVER is set if not os.getenv("SDL_VIDEODRIVER"): os.putenv("SDL_VIDEODRIVER", driver) try: pygame.display.init() except pygame.error: print("Driver: {0} failed.".format(driver)) continue found = True break if not found: raise Exception("No suitable video driver found!") ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi self._size = (pygame.display.Info().current_w, pygame.display.Info().current_h) self._screen = pygame.display.set_mode(self._size, pygame.FULLSCREEN | pygame.HWSURFACE) else: self._size = (1824, 984) self._screen = pygame.display.set_mode(self._size) ########################################################################### print("Framebuffer size: {0}".format(self._size)) # Инициализируем шрифты pygame.font.init() # Инициализируем музыкальный модуль pygame.mixer.init() pygame.mixer.music.set_volume(0.0) # Выключаем курсор pygame.mouse.set_visible(False) for module in self._modules: module.init(self._managerList) pygame.time.set_timer(BLOCK_SECOND_UPDATE_EVENT, 1000) pygame.time.set_timer(BLOCK_MINUTE_UPDATE_EVENT, 60000) def __del__(self): """Destructor to make sure pygame shuts down, etc.""" # pygame.mixer.quit() # pygame.display.quit() def setDisplayTimerOn(self): """Таймер для отключения дисплея""" (start, backgroundColor, foregroundColor, idleTime) = self._config.get_curret_setting() pygame.time.set_timer(IDLE_EVENT, 0) pygame.time.set_timer(IDLE_EVENT, idleTime * 60000) def setDisplayTimerOff(self): """Таймер для отключения дисплея""" pygame.time.set_timer(IDLE_EVENT, 0) def displayOff(self): if (not self._isDisplayOn): return self._isDisplayOn = False ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi # https://news.screenly.io/how-to-automatically-turn-off-and-on-your-monitor-from-your-raspberry-pi-5f259f40cae5, # https://elinux.org/RPI_vcgencmd_usage subprocess.Popen("vcgencmd display_power 0 > /dev/null 2>&1", shell=True).wait() GPIO.output(LED_PIN, 0) else: pass ########################################################################### self.setDisplayTimerOff() def displayOn(self): self.setDisplayTimerOn() if (self._isDisplayOn): return self._isDisplayOn = True ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi # https://news.screenly.io/how-to-automatically-turn-off-and-on-your-monitor-from-your-raspberry-pi-5f259f40cae5, # https://elinux.org/RPI_vcgencmd_usage subprocess.Popen("vcgencmd display_power 1 > /dev/null 2>&1", shell=True).wait() GPIO.output(LED_PIN, 1) else: pass ########################################################################### for module in self._modules: module.updateInfo(self._isDisplayOn) def proccedEvent(self, events): for event in events: if (event.type == pygame.locals.QUIT): return 0 if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): return 0 if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_r): ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi subprocess.Popen("sudo reboot", shell=True) else: pass ########################################################################### return 0 if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_h): ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi subprocess.Popen("sudo shutdown -h now", shell=True) else: pass ########################################################################### return 0 if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_o): self.displayOff() if (event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_p): self.displayOn() if event.type == IDLE_EVENT: self.displayOff() for module in self._modules: module.proccedEvent(event, self._isDisplayOn) return 1 def loop(self): clock = pygame.time.Clock() while (self.proccedEvent(pygame.event.get())): if self._isDisplayOn: (start, backgroundColor, foregroundColor, idleTime) = self._config.get_curret_setting() self._screen.fill(backgroundColor) time = datetime.datetime.now() for module in self._modules: module.updateDisplay( self._isDisplayOn, self._screen, self._size, foregroundColor, backgroundColor, time) else: self._screen.fill((0, 0, 0)) pygame.display.update() # pygame.time.delay(WAIT_TIME) clock.tick(FPS) for module in self._modules: module.done() pygame.quit()
def _hook_header(self, params=None): return ['X-Sugar-Buddy: %s' % Setting.get_buddy_credential()]
class TestUtil(): def __init__(self): self.setting = Setting() self.cli1_dir = os.path.join(os.getcwd(), 'cli1') self.cli2_dir = os.path.join(os.getcwd(), 'cli2') self.worktree1 = os.path.join(os.getcwd(), 'worktree1') self.worktree2 = os.path.join(os.getcwd(), 'worktree2') self.enc_repo = False try: self.enc_repo = bool(os.environ['ENCRYPTED_REPO']) except Exception: pass self.repo_id = None @staticmethod def clean_sync_data(conf): try: os.remove(os.path.join(conf, 'ccnet.sock')) os.remove(os.path.join(conf, 'seafile.ini')) shutil.rmtree(os.path.join(conf, 'logs')) shutil.rmtree(os.path.join(conf, 'misc')) shutil.rmtree(os.path.join(conf, 'seafile')) shutil.rmtree(os.path.join(conf, 'seafile-data')) except Exception: pass def init_conf(self): self.setting.parse_config() if not os.path.exists(self.cli1_dir) or not os.path.exists(self.cli2_dir): raise Exception('ccnet conf dir is missing') if os.name != 'nt': TestUtil.clean_sync_data(self.cli1_dir) TestUtil.clean_sync_data(self.cli2_dir) if os.path.exists(self.worktree1): shutil.rmtree(self.worktree1) if os.path.exists(self.worktree2): shutil.rmtree(self.worktree2) os.mkdir(self.worktree1) os.mkdir(self.worktree2) seaf_op.seaf_init(self.cli1_dir) seaf_op.seaf_init(self.cli2_dir) def start_daemon(self): seaf_op.seaf_start_all(self.cli1_dir) seaf_op.seaf_start_all(self.cli2_dir) def create_repo(self): self.repo_id = seaf_op.seaf_create(self.cli1_dir, self.setting.server_url, self.setting.user, self.setting.password, self.enc_repo) def sync_cli1(self): seaf_op.seaf_sync(self.cli1_dir, self.setting.server_url, self.repo_id, self.worktree1, self.setting.user, self.setting.password) def sync_cli2(self): seaf_op.seaf_sync(self.cli2_dir, self.setting.server_url, self.repo_id, self.worktree2, self.setting.user, self.setting.password) def sync_repo(self): self.sync_cli1() self.sync_cli2() def desync_cli1(self): seaf_op.seaf_desync(self.cli1_dir, self.worktree1) def desync_cli2(self): seaf_op.seaf_desync(self.cli2_dir, self.worktree2) def desync_repo(self): self.desync_cli1() self.desync_cli2() # delete test repo seaf_op.seaf_delete(self.cli1_dir, self.setting.server_url, self.setting.user, self.setting.password, self.repo_id) def stop_daemon(self): seaf_op.seaf_stop(self.cli1_dir) seaf_op.seaf_stop(self.cli2_dir) def clean(self): try: if os.name != 'nt': TestUtil.clean_sync_data(self.cli1_dir) TestUtil.clean_sync_data(self.cli2_dir) shutil.rmtree(self.worktree1) shutil.rmtree(self.worktree2) except Exception: pass def wait_sync(self): max_retry = 12 cur_retry = 0 while cur_retry < max_retry: time.sleep(5) cur_retry += 1 repo1 = seaf_op.seaf_get_repo(self.cli1_dir, self.repo_id) if repo1 is None: continue repo2 = seaf_op.seaf_get_repo(self.cli2_dir, self.repo_id) if repo2 is None: continue if repo1.head_cmmt_id == repo2.head_cmmt_id: break @staticmethod def verify_by_rsync(dir1, dir2): ret = call_process(['rsync', '-acrin', dir1, dir2]) if ret: for d in ret.split('\n'): # omit empty str if not d: continue # omit directory has almost same result except st_mod items = d.split(' ') dattr = items[0] name = items[1] # Output format difference between rsync versions: # rsync 3.1.1 : '.d..t.......' # rsync 3.0.9 : '.d..t......' # On Windows, file timestamp may have 1 second difference # between two clients after sync. That's caused by the # precision lose when converting Windows timestamp to # Unix timestamp. So we don't check timestamp difference # for files either. if not all([c in ('f', 'd', 't', '.') for c in dattr]): assert False, 'Sync with two client have different result: %s %s' % (dattr, name) def verify_result(self, callable=None): self.wait_sync() if callable: callable(self.worktree1, self.worktree2) else: dir1 = './worktree1/' dir2 = './worktree2/' TestUtil.verify_by_rsync(dir1, dir2) TestUtil.verify_by_rsync(dir2, dir1) # worktree: 1(worktree1), 2(worktree2) def mkdir(self, worktree, path): if worktree == 1: os.makedirs(os.path.join(self.worktree1, path)) elif worktree == 2: os.makedirs(os.path.join(self.worktree2, path)) def rmdir(self, worktree, path): if worktree == 1: shutil.rmtree(os.path.join(self.worktree1, path)) elif worktree == 2: shutil.rmtree(os.path.join(self.worktree2, path)) def mkfile(self, worktree, fpath, con=''): if worktree == 1: pdir = self.worktree1 elif worktree == 2: pdir = self.worktree2 else: return abs_path = os.path.join(pdir, fpath) dirname = os.path.dirname(abs_path) if not os.path.exists(dirname): os.makedirs(dirname) with open(abs_path, 'w') as fd: fd.write(con) def rmfile(self, worktree, fpath): if worktree == 1: os.remove(os.path.join(self.worktree1, fpath)) elif worktree == 2: os.remove(os.path.join(self.worktree2, fpath)) def modfile(self, worktree, fpath, con=''): if worktree == 1: pdir = self.worktree1 elif worktree == 2: pdir = self.worktree2 else: return abs_path = os.path.join(pdir, fpath) with open(abs_path, 'a') as fd: fd.write(con) def move(self, worktree, org_path, dest_path): if worktree == 1: shutil.move(os.path.join(self.worktree1, org_path), os.path.join(self.worktree1, dest_path)) elif worktree == 2: shutil.move(os.path.join(self.worktree2, org_path), os.path.join(self.worktree2, dest_path)) def batchmove(self, worktree, regex, dest_path): if worktree == 1: pdir = self.worktree1 elif worktree == 2: pdir = self.worktree2 else: return files = glob.glob(os.path.join(pdir, regex)) dest = os.path.join(pdir, dest_path) for f in files: shutil.move(f, dest) def copy(self, worktree, org_path, dest_path): if worktree == 1: shutil.copytree(os.path.join(self.worktree1, org_path), os.path.join(self.worktree1, dest_path)) elif worktree == 2: shutil.copytree(os.path.join(self.worktree2, org_path), os.path.join(self.worktree2, dest_path)) def touch(self, worktree, path, time=None): if worktree == 1: os.utime(os.path.join(self.worktree1, path), time) if worktree == 2: os.utime(os.path.join(self.worktree2, path), time) def getpath(self, worktree, path): if worktree == 1: return os.path.join(self.worktree1, path) elif worktree == 2: return os.path.join(self.worktree2, path) raise Exception('Invalid worktree')
class QETask(object): """ Base abstract class for 'TaskNameTask' family of classes. It also provides the interface to loumch tasks All user defined tasks should be derived from this class setting -- provides access to parallel environment and QE input/output files """ def __init__(self, filename = None, configString = None, cleanOutDir = False): # parallelization parameters # Default values, see explanations below: #self.name = 'Launcher' self._isSerial = True configDic = { 'useTorque' : 'False', 'paraTorqueParams': '-l nodes=1:ppn=1', 'serialTorqueParams': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '', 'serialPrefix': '', 'serialPostfix': '', 'paraRemoteShell': '', 'outdir': None } if filename == None and configString == None: filename = 'config.ini' self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) self.cleanOutDir = cleanOutDir if self.setting.get('useTorque') == 'True': self.setting.set('useTorque', True) else: self.setting.set('useTorque', False) if self.setting.get('useTorque'): if self.isSerial(): self._torque = QETorque(self.setting.get('serialTorqueParams')) else: self._torque = QETorque(self.setting.get('paraTorqueParams')) def name(self): return 'Launcher' def _check(self, x): """ Will check the exit status of the program to be executed """ signal = x & 0xFF exitcode = (x >> 8) & 0xFF if exitcode != 0: raise Exception("Task " + self.name() + " crashed: check your settings" + "Command string:" + self.cmdLine()) def _run(self): if os.path.exists('CRASH'): os.remove('CRASH') outdir = self.setting.get('outdir') if outdir != None: os.system(self.setting.paraRemoteShell + ' mkdir -p ' + outdir) if self.setting.get('useTorque'): if self.isSerial(): if self.setting.get('serialPrefix') == '': self._check(os.system(self.cmdLine())) else: self._torque.serial(self.cmdLine(), torqueParams = self.setting.serialTorqueParams) else: self._torque.serial(self.cmdLine(), torqueParams = self.setting.paraTorqueParams) else: self._check(os.system(self.cmdLine())) # if self.setting.paraPrefix != '' and self.setting.paraPrefix in self.cmdLine(): # if self.setting.useTorque: # self._torque.serial(self.cmdLine()) # else: # self._check(os.system(self.cmdLine())) # else: # self._check(os.system(self.cmdLine())) if os.path.exists('CRASH'): raise Exception("Task " + self.name() + " crashed: 'CRASH' file was discovered") def syncSetting(self): """ Will syncronise QE input file with class Setting for given task (QE input files may contain multiple input/ouput file names definitions which can be overriden in this method) """ pass def cleanOutputDir(self, cleanOutDir = None): """ Cleans the output directory (directory, where large files, used for calculation are stored, can be for example 'temp/' or 'scratch/') """ # import shutil if cleanOutDir == None: cleanOutDir = self.cleanOutDir # if cleanOutDir == None: # raise Exception('outDir can not be cleaned, since it was not defined') if cleanOutDir: outDir = self.setting.get('outdir') os.system(self.setting.paraRemoteShell + ' rm -r -f ' + outDir) os.system(self.setting.paraRemoteShell + ' mkdir ' + outDir) # if self.setting.useTorque: # # else: # shutil.rmtree(cleanOutDir) # os.mkdir(cleanOutDir) # def cmdLine(self): # """ # returns command string of a given task # """ # return self._cmdStr def launch(self, cleanOutDir = False): """ Parses input. Launches task. Parses output. """ # if cleanOutDir == None: # cleanOutDir = self.cleanOutDir # if cleanOutDir != None: # self.cleanOutputDir(cleanOutDir) self.input.parse() self.syncSetting() # sync setting with QE input file self.input.save() self.cleanOutputDir(cleanOutDir) self._run() self.output.parse(parserList = 'all') def setSerial(self): #self._serialThroughMPI = serialThroughMPI self._isSerial = True def setParallel(self): self._isSerial = False def isSerial(self): if self._isSerial: return True else: return False def getPrefix(self) : if self.isSerial(): # if self._isSerialThroughMPI(): # return '' # else: return self.setting.get('serialPrefix') else: return self.setting.get('paraPrefix') def getPostfix(self): if self.isSerial(): return self.setting.get('serialPostfix') else: return self.setting.get('paraPostfix') def _initCmdLineParams(self): self._inp = '-inp' self._devnul = '< /dev/null' if self.isSerial(): self._inp = '<' self._devnul = '' # def _isSerialThroughMPI(self): # if self.isSerial(): # if self._serialThroughMPI: # return True # else: # return False def _getCmdLine(self, executable, input, output): self._initCmdLineParams() return self.getPrefix() + ' ' + executable + " " + self.getPostfix() + \ ' ' + self._inp + ' ' + self.setting.get(input) + ' > ' + \ self.setting.get(output) + self._devnul
def __init__(self, fname=None): Setting.__init__(self, fname)
class QETask(object): """ Base abstract class for 'TaskNameTask' family of classes. It also provides the interface to loumch tasks All user defined tasks should be derived from this class setting -- provides access to parallel environment and QE input/output files """ def __init__(self, filename = None, configString = None, cleanOutDir = None): # parallelization parameters # Default values, see explanations below: #self.name = 'Launcher' configDic = { 'useTorque' : 'False', 'torqueResourceList': '-l nodes=1:ppn=1', 'paraPrefix': '', 'paraPostfix': '' } self.setting = Setting(filename, configString) self.setting.section(QETask.name(self), configDic) self.cleanOutDir = cleanOutDir if self.setting.useTorque == 'True': self.setting.useTorque = True else: self.setting.useTorque = False if self.setting.useTorque: self._torque = QETorque(self.setting.torqueResourceList) def name(self): return 'Launcher' def _check(self, x): """ Will check the exit status of the program to be executed """ signal = x & 0xFF exitcode = (x >> 8) & 0xFF if exitcode != 0: raise Exception("Task " + self.name() + " crashed: check your settings" + "Command string:" + self.cmdLine()) def _run(self): if os.path.exists('CRASH'): os.remove('CRASH') if self.setting.paraPrefix != '' and self.setting.paraPrefix in self.cmdLine(): if self.setting.useTorque: self._torque.serial(self.cmdLine()) else: self._check(os.system(self.cmdLine())) else: self._check(os.system(self.cmdLine())) if os.path.exists('CRASH'): raise Exception("Task " + self.name() + " crashed: 'CRASH' file was discovered") def _syncSetting(self): """ Will syncronise QE input file with class Setting for given task (QE input files may contain multiple input/ouput file names definitions which can be overriden in this method) """ pass def cleanOutputDir(self, cleanOutDir = None): """ Cleans the output directory (directory, where large files, used for calculation are stored, can be for example 'temp/' or 'scratch/') """ import shutil if cleanOutDir == None: cleanOutDir = self.cleanOutDir if cleanOutDir == None: raise Exception('outDir can not be cleaned, since it was not defined') if self.setting.useTorque: os.system('bpsh -a rm -r -f ' + cleanOutDir) os.system('bpsh -a mkdir ' + cleanOutDir) else: shutil.rmtree(cleanOutDir) os.mkdir(cleanOutDir) # def cmdLine(self): # """ # returns command string of a given task # """ # return self._cmdStr def launch(self, cleanOutDir = None): """ Parses input. Launches task. Parses output. """ if cleanOutDir == None: cleanOutDir = self.cleanOutDir if cleanOutDir != None: self.cleanOutputDir(cleanOutDir) self.input.parse() self._syncSetting() # sync setting with QE input file self.input.save() self._run() self.output.parse(parserList = 'all')
def __init__(self, fname=None): Setting.__init__(self,fname) if self.useTorque: self.torque = qetorque.QETorque(self.configFileName)
class Environment: """ main object of icbc: hosts instance of classes subject, setting """ def __init__(self, superuser=None, computer=None, user=None, code=None, branch=None, id_local_process='unused', type_list=[None], case_list=[[None]], configuration_list=[None], flow_process_list=[None], element_type_list=[[None]], operation_type=None, operation=None, test_mode='0', db_user='******', db_password='******', db_host='localhost', db_schema='testing_environment'): """ These parameters can be preselected: belong to (test) Subject: :param superuser: has accounts on separate computer :param computer: :param user: :param code: belongs to source code tree :param branch: belongs to source code tree belong to (test) Item: :param type_list: belongs to example tree :param case_list: belongs to example tree :param configuration_list: belongs to example tree :param flow_process_list: :param element_type_list: :param operation_type: one-character string [b: building,s: simulating,p: plotting] :param operation: one-character string - meaning depends on operation_type :param test_mode: Parameters to access database: :param db_user: :param db_password: :param db_host: :param db_schema: """ self.__flow_process_name_list = flow_process_list self.__element_type_name_list = element_type_list db_inst = Database(db_user, db_password, db_host, db_schema) self.__subject_inst = Subject(superuser, computer, user, code, branch, id_local_process) self.__setting_inst = Setting(type_list, case_list, configuration_list, operation_type, operation, test_mode, db_inst) if location == 'local': self.__subject_inst.print_selected_variables() self.__setting_inst.print_selected_variables() print('\n-----------------------------------------------------------------') def __del__(self): del self.__subject_inst del self.__setting_inst def run(self): """ main function of icbc: 1. connect to and disconnect from data base if on local computer 2. call select functions 3. call loop if selects successful :return: 0 """ if location == 'local': self.__setting_inst.connect_to_db() operation_inst = self.select() # rerun if reselect chosen if operation_inst == 1: self.run() # rerun self.loop(operation_inst) del operation_inst if location == 'local': self.__setting_inst.disconnect_from_db() # to reconnect each run in case of table update if self.__setting_inst.test_mode == '0': # control with shell self.run() return 0 def select(self): """ select 1. select operation type and operation 2. do configurations which are independent of test item 3. select test items :return: (Operation(Building, Simulating, or Plotting)) operation instance; 1 if operation reselect or exception """ self.__subject_inst.select(self.__setting_inst) selected_operation_type = self.__setting_inst.select_operation_type() operation_inst = self.select_operation(selected_operation_type) if operation_inst == 1: return 1 if operation_inst.selected_operation == 's': # reselect self.__setting_inst.reselect(self.__subject_inst) # decide what to reselect return 1 self.configure(operation_inst) self.__setting_inst.select_items_to_test(selected_operation_type, operation_inst.selected_operation, self.__subject_inst.computer) if self.__setting_inst.operation == 'reselect': self.__setting_inst.operation = None self.run() # now reselection is finished, rerun to select next operation return operation_inst def select_operation(self, operation_type): """ 1. generate operation instance, 2. call select_operation where operation is chosen :param operation_type: one-character string [b: building,s: simulating,p: plotting] :return: operation instance Building, Simulating, Plotting; 1 if error """ if operation_type == 'b': # building operation_inst = Building(self.__subject_inst) elif operation_type == 's': # simulating operation_inst = Simulating(self.__subject_inst) elif operation_type == 'p': # plotting operation_inst = Plotting(self.__subject_inst) else: message(mode='ERROR', not_supported=operation_type) return 1 operation_inst.select_operation(self.__setting_inst.operation) return operation_inst def configure(self, operation_inst): """ 0. call function to set flags for file uploads 1. if operation is to compare results with references, clear log file with names of deviating files from previous runs 2. check if list entries for test items exit :param operation_inst: (class Building, Simulating, Plotting (Operation)) :return: 0 if success; 1 if lists for item not complete """ operation_inst.set_upload_file_flags() if operation_inst.selected_operation_type == 's' and operation_inst.selected_operation == 'o': # the selected operation is to compare results with references files = glob(adapt_path('{}references\\deviatingFiles*'.format(self.__subject_inst.directory))) for file in files: remove_file(file, False) #clear_file(adapt_path('{}references\\deviatingFiles_{}.log'.format( # self._subject_inst.directory, self._item.configuration))) def loop(self, operation_inst): """ loop over type, case, and configuration lists :param operation_inst: (class Building, Simulating, Plotting (Operation)) :return: """ type_list_counter = 0 for item_type in self.__setting_inst.item_constituents.type_list: for item_case in self.__setting_inst.item_constituents.case_list[type_list_counter]: self.set_inner_loop_elements(item_case) for item_configuration in self.__setting_inst.item_constituents.configuration_list: if self.item_is_to_test(item_case): self.loop_inner(operation_inst, item_type, item_case, item_configuration) if len(self.__setting_inst.item_constituents.case_list) > 1: type_list_counter += 1 def set_inner_loop_elements(self, item_case): """ set lists with process name and element type :param item_case: (string) :return: """ if item_case is None: self.__flow_process_name_list = [None] self.__element_type_name_list = [[None]] else: if location == 'local': self.__flow_process_name_list = self.__setting_inst.query_flow_process_name_list(item_case) self.__element_type_name_list = self.__setting_inst.query_element_type_name_list( item_case, self.__flow_process_name_list) def item_is_to_test(self, item_case): """ check test_mode, state, used for simulation, plotting operation type (case item exists) (all items (i.e. configurations) involved in building operation type) :param item_case: (string or None) :return: (bool )False: not involved, True: involved or ERROR """ execute_flag = True if location == 'local' and item_case: if self.__setting_inst.test_mode == '0': # no test mode - select everything by typing on console # and than the items in the loop (in environment run) is involved pass elif self.__setting_inst.test_mode == '1': # via browser execute_flag = self.__setting_inst.query_column_entry_for_name('cases', item_case, 'state') elif self.__setting_inst.test_mode == '2': # via CI tool if not self.__setting_inst.query_column_entry_for_name('cases', item_case, 'active'): execute_flag = False else: message(mode='ERROR', not_supported=self.__setting_inst.test_mode) # returns '1' return execute_flag # remote always '1' def loop_inner(self, operation_inst, item_type, item_case, item_configuration): """ 1. generate (and delete) item instance 2. call write files (for numerics, processing) 3. call operation run function :param operation_inst: (class Building, Simulating, or Plotting) :param item_type: (string) :param item_case: (string) :param item_configuration: (string) :return: """ for index, flow_process_name in enumerate(self.__flow_process_name_list): for element_type_name in self.__element_type_name_list[index]: # take all for remote, building or plotting if location == 'remote' or operation_inst.selected_operation_type == 'b' or \ operation_inst.selected_operation_type == 'p' or\ (str2bool(self.__setting_inst.query_column_entry_for_name( 'flow_processes', flow_process_name, 'active')) and str2bool(self.__setting_inst.query_column_entry_for_name( 'element_types', element_type_name, 'active'))): item_inst = self.generate_item_instance( operation_inst, item_type, item_case, item_configuration, flow_process_name, element_type_name) operation_inst.set_numerics_and_processing_data(item_type, item_case, item_configuration, flow_process_name, element_type_name, self.__setting_inst, self.__subject_inst.location) operation_inst.run(item_inst) del item_inst def generate_item_instance( self, operation_inst, item_type, item_case, item_configuration, flow_process, element_type): """ generate Build, Sim or Plot according to chosen operation :param operation_inst: :param item_type: :param item_case: :param item_configuration: :param flow_process: :param element_type :return: child of Item instance (Build, Sim, Plot) """ if operation_inst.selected_operation_type == 'b': # building return Build(self.__subject_inst, item_configuration) elif operation_inst.selected_operation_type == 's': # simulating return Sim(self.__subject_inst, item_type, item_case, item_configuration, flow_process, element_type) elif operation_inst.selected_operation_type == 'p': # plotting return Plot(self.__subject_inst, item_type, item_case, item_configuration, flow_process, element_type) else: message(mode='ERROR', not_supported=operation_inst.selected_operation_type) return 1 # check this
def __init__(self): """ """ self._modules = [] self._size = None self._screen = None self._isDisplayOn = True # Загружаем настройки из конфиг файла self._config = Setting() self._config.load(FILE_SETTING) self._managerList = { "Time": BlockTime(logger, self._config), "Alarm": BlockAlarm(logger, self._config), "Voice": BlockVoice(logger, self._config), "YandexNews": BlockYandexNews(logger, self._config), "OpenWeatherMap": BlockOpenWeatherMap(logger, self._config), "WunderGround": BlockWunderGround(logger, self._config), "Calendar": BlockCalendar(logger, self._config), "Swap": BlockSwap(logger, self._config), "Watcher": BlockWatcher(logger, self._config), "MT8057": BlockMT8057(logger, self._config), "YandexWeather": BlockYandexWeather(logger, self._config), "IR": BlockIR(logger, self._config), } for name in self._config._blockList: if name in self._managerList: self._modules.append(self._managerList[name]) print(name) # Based on "Python GUI in Linux frame buffer" # http://www.karoltomala.com/blog/?p=679 # Check which frame buffer drivers are available # Start with fbcon since directfb hangs with composite output drivers = ["x11", "windib"] found = False for driver in drivers: # Make sure that SDL_VIDEODRIVER is set if not os.getenv("SDL_VIDEODRIVER"): os.putenv("SDL_VIDEODRIVER", driver) try: pygame.display.init() except pygame.error: print("Driver: {0} failed.".format(driver)) continue found = True break if not found: raise Exception("No suitable video driver found!") ########################################################################### if sys.platform == "linux": # Only for Raspberry Pi self._size = (pygame.display.Info().current_w, pygame.display.Info().current_h) self._screen = pygame.display.set_mode(self._size, pygame.FULLSCREEN | pygame.HWSURFACE) else: self._size = (1824, 984) self._screen = pygame.display.set_mode(self._size) ########################################################################### print("Framebuffer size: {0}".format(self._size)) # Инициализируем шрифты pygame.font.init() # Инициализируем музыкальный модуль pygame.mixer.init() pygame.mixer.music.set_volume(0.0) # Выключаем курсор pygame.mouse.set_visible(False) for module in self._modules: module.init(self._managerList) pygame.time.set_timer(BLOCK_SECOND_UPDATE_EVENT, 1000) pygame.time.set_timer(BLOCK_MINUTE_UPDATE_EVENT, 60000)
def __init__(self, issue): self._issue = str(issue) self._setting = Setting()
def _generate_header(self): return ['X-Sugar-Buddy: %s' % Setting.get_buddy_credential()]