def handle_controls(player): while player.state != 'stopped': a = getch() if ord(a) == 3 or a == 'q': quit(player) elif a == 'f': if len(player.stream_chunks) != 0: player.stream_chunks.insert(0, 'forward') elif a == 'b': if len(player.stream_chunks) != 0: player.stream_chunks = [player.stream_chunks[0]] + ['backward'] elif a == '>': if player.current_song == len(player.playlist) - 1: pass else: player.stream_chunks = [] player.stream_chunks.append('reset_time') player.stream_chunks.append('next') elif a == '<': if player.current_song == 0: pass else: player.stream_chunks = [] player.stream_chunks.append('reset_time') player.stream_chunks.append('previous')
def list(config, app_id, id, type): """List available application policies. Examples: List all group policies that belong to application 50: $ jaguar policy list 50 --type group List instance policy 101 that belongs to application 50: $ jaguar policy list 50 --type instance --id 101 """ try: url = config.server_url + '/v1/applications/' \ + str(app_id) + '/policies/' if type: url += type + '/' if id > 0: url += str(id) rest = Rest(url, {'username': config.user}) display(rest.get()) except RestError as error: quit(error.message)
def execute(self): attempts = 0 # for SSL Errors, allow 5 attempts. For other exceptions, no additional attempts. while attempts < self.MAX_ATTEMPTS: try: utils.d_print(self.debug_level + 3, "GET", "URL=", self.get_url, "PARAMS=", self.get_params, "HEADER=", self.get_header) r = requests.get(self.get_url, params=self.get_params, headers=self.get_header) utils.d_print(self.debug_level + 3, "GET_RETURN", "r.encoding=", r.encoding, "r.status_code=", r.status_code) # we don't need to be in the loop. we had a success. break except requests.exceptions.SSLError: exceptionInfo = sys.exc_info() utils.d_print(2, "#### SSL Error Exception Occurred", exceptionInfo) attempts += 1 if attempts >= self.MAX_ATTEMPTS: utils.d_print( 1, "SSL Exception occured more than 5 times during a single request!. Quitting." ) utils.quit("EXIT.") else: exceptionInfo = sys.exc_info() print("Exception Occurred:", exceptionInfo) utils.quit('!') utils.d_print(self.debug_level + 3, "ATTEMPTS: ", attempts) return r
def list(config, app_id, id, type): """List available application policies. Examples: List all group policies that belong to application 50: $ jaguar policy list 50 --type group List instance policy 101 that belongs to application 50: $ jaguar policy list 50 --type instance --id 101 """ try: url = config.server['url'] + '/v1/applications/' \ + str(app_id) + '/policies/' if type: url += type + '/' if id > 0: url += str(id) rest = Rest(url, {'username':config.user}) display(rest.get()) except RestError as error: quit(error.message)
def __generate_xml(self): self.xml_string = self.PAYLOAD_HEADER self.xml_string += '<payloadMessage>' self.__add_attribute('payloadID', self.p_id) cc = CommonCoversions() self.__add_attribute('payloadTime', cc.time_in_iso_format(self.p_time)) self.__add_attribute('payloadContentType', self.p_content_type) self.__add_attribute('payloadTypeURI', self.p_uri) # put in the attach info if self.p_attach_type == 'E': print(self.p_attach) utils.d_pprint(0, "Payload Attach", self.p_attach) self.xml_string += '<eventIDList>' x = self.p_attach.split(',') for event_id in x: self.__add_attribute('eventID', event_id) self.xml_string += '</eventIDList>' else: utils.quit("not yet implemented") self.xml_string += '<payload>' current_payload = json.loads(self.p_pyld) title_payload = {"key":"title", "value":self.p_title,"type":"string"} current_payload.append(title_payload) final_payload_str = json.dumps(current_payload) self.xml_string += final_payload_str self.xml_string += '</payload>' self.xml_string += self.PAYLOAD_FOOTER return self.xml_string
def main(): utils.cl_news_headline() service = raw_input() print '\n' if service == 'cnn': cache['cnn'] = cnn.cl_news_util([service, '-h'], cache['cnn']) elif service == 'hn': cache['hn'] = hackernews.cl_news_util([service, '-h'], cache['hn']) elif service == 'ap': cache['ap'] = ap.cl_news_util([service, '-h'], cache['ap']) elif service == 'gu': cache['gu'] = guardian.cl_news_util([service, '-h'], cache['gu']) elif service == 'aljaz': cache['aljaz'] = aljaz.cl_news_util([service, '-h'], cache['aljaz']) elif service == 'nyt': cache['nyt'] = nyt.cl_news_util([service, '-h'], cache['nyt']) elif service == 'wp': cache['wp'] = wp.cl_news_util([service, '-h'], cache['wp']) elif service == 'quit': utils.quit() else: print '\nCommand not recognized.\n' main() pick_article(service)
def pick_article(service): utils.command_prompt() command = raw_input() if command == 'quit': utils.quit() elif command == 'main': main() try: int(command) except: pick_article(service) if service == 'cnn': cnn.cl_news_util(['cnn', '-r', command], cache['cnn']) elif service == 'hn': # Hacker News is the only read action that opens the page hackernews.cl_news_util(['hn', '-o', command], cache['hn']) elif service == 'ap': ap.cl_news_util(['ap', '-r', command], cache['ap']) elif service == 'gu': guardian.cl_news_util(['gu', '-r', command], cache['gu']) elif service == 'aljaz': aljaz.cl_news_util(['aljaz', '-r', command], cache['aljaz']) elif service == 'nyt': nyt.cl_news_util(['nyt', '-r', command], cache['nyt']) read_more(service)
def read_more(service): utils.read_more(service) command = raw_input() if command == 'main': main() elif command == 'quit': utils.quit() if command == 'y': print '\n' # read more from cnn if service == 'cnn': cnn.cl_news_util(['cnn', '-h'], cache['cnn']) # read more from hackernews elif service == 'hn': hackernews.cl_news_util(['hn', '-h'], cache['hn']) # read more from ap elif service == 'ap': ap.cl_news_util(['ap', '-h'], cache['ap']) # read more from the guradian elif service == 'gu': guardian.cl_news_util(['gu', '-h'], cache['gu']) # read more from al jazeera elif service == 'aljaz': aljaz.cl_news_util(['aljaz', '-h'], cache['aljaz']) # read more from nyt elif service == 'nyt': nyt.cl_news_util(['nyt', '-h'], cache['nyt']) pick_article(service) else: print '\nCommand not recognized.\n' read_more(service)
def input(self): for event in pygame.event.get(): if event.type == QUIT: utils.quit() elif event.type == KEYDOWN: if event.key == K_F1: self.manager.setScene(PlayScene())
def time_in_iso_format(self, given_time): # '2020-01-15:23:10' to '2013-06-08T14:58:56.591Z' x = given_time.split(':') if len(x) != 3: utils.d_print(0, "Input Time: ", given_time) utils.quit("Time not in required format! Format: YYYY-MM-DD:HH:MM") iso_time = x[0] + 'T' + x[1] + ':' + x[2] + ':00.000Z' return iso_time
def signIn(browser, login, password): browser.get('https://is.cuni.cz/studium/') browser.find_element_by_id('login').send_keys(login) browser.find_element_by_id('heslo').send_keys(password) browser.find_element_by_name('all').click() if 'login.php' in browser.current_url: browser.quit() quit(1, 'Incorrect login or password supplied.')
def unregister(config, id): """Unregister an application.""" try: url = config.server_url + '/v1/applications/' + str(id) headers = {'username': config.user} rest = Rest(url, headers) display(rest.delete()) except RestError as error: quit(error.message)
def parse_args_and_setup(): # parse and print arguments utils.parse_arguments() if utils.global_args.mode == 'stats': utils.quit('stats mode not supported in data_analytics program; only output mode supported') if utils.global_args.mode == 'input': utils.quit('input mode not supported in data_analytics program; only output mode supported') return
def delete(config, app_id, type, id): """Delete an application policy. """ try: url = config.server_url + '/v1/applications/' + str(app_id) \ + '/policies/' + type + '/' + str(id) headers = {'username': config.user, 'Content-Type': 'application/json'} rest = Rest(url, headers) display(rest.delete()) except RestError as error: quit(error.message)
def delete(config, app_id, type, id): """Delete an application policy. """ try: url = config.server['url'] + '/v1/applications/' + str(app_id) \ + '/policies/' + type + '/' + str(id) headers = {'username':config.user, 'Content-Type':'application/json'} rest = Rest(url, headers) display(rest.delete()) except RestError as error: quit(error.message)
def __init__(self, string_type, name_or_id_string): if string_type.upper() == 'NAME': self.name = name_or_id_string self.__get_id_from_name() elif string_type.upper() == 'ID': self.id = name_or_id_string utils.quit("ID to Name translation not yet implemented.") else: utils.quit("Unknown string type. Has to be 'Name' or 'Id'") return
def validate_inbound_data_rules(self): if self.env == "prod": # you can NEVER push an XML to prod. utils.d_print(1, "env can never be prod") utils.quit("Tried to push to PROD !") return False if self.env == "sandbox": return False return True
def __generate_epc_serial(self, gtin_str, serial): try: return_str = '' if 'urn:ibm:ift:' in gtin_str: # we have an IFT id prefix_itemref = gtin_str.split(':class:')[1] return_str = 'urn:ibm:ift:product:serial:obj:' + prefix_itemref + '.' + str(serial) else: utils.quit("GS1 Serials not yet implemented.") return return_str except: utils.print_exception(1)
def get_func_exprs(): """ Prompt for a list of functions the user wants to see graphed. As mentioned previously, anything entered remains for the duration of the program, so you can graph something, change the settings, and return to find your functions still there. """ def change_colors(item): # index new color item_index = button_entries.index(item) COL_POS_LIST[item_index] += 1 # reset index if gone too far if COL_POS_LIST[item_index] >= len(COLOR_LIST): COL_POS_LIST[item_index] = 0 # create new Button image col = item.image.copy() col.fill(COLOR_LIST[COL_POS_LIST[item_index]]) # update Button item.set_new_image(col) item.color = COLOR_LIST[COL_POS_LIST[item_index]] box = gui.Container() box.add(gui.Button(10, 10, utils.load_image("cube.bmp", True), "Back")) box.add( gui.Button(constants.SCR_WIDTH - 70, 10, utils.load_image("cube.bmp", False), "Graph!")) box.add(text_entries) box.add(button_entries) while True: if pygame.event.peek(QUIT): utils.quit() box.update(*pygame.event.get()) for item in box: if isinstance(item, gui.Button) and item.clicked: item.clicked = False if item.text == "Back": return elif item.text == "": change_colors(item) elif item.text == "Graph!": exprs = [(x.expr_text, y.color) for x, y in zip(text_entries, button_entries) if x.expr_text] draw_graph(exprs) blit_background() box.draw(SCREEN) pygame.display.update()
def get_func_exprs(): """ Prompt for a list of functions the user wants to see graphed. As mentioned previously, anything entered remains for the duration of the program, so you can graph something, change the settings, and return to find your functions still there. """ def change_colors(item): # index new color item_index = button_entries.index(item) COL_POS_LIST[item_index] += 1 # reset index if gone too far if COL_POS_LIST[item_index] >= len(COLOR_LIST): COL_POS_LIST[item_index] = 0 # create new Button image col = item.image.copy() col.fill(COLOR_LIST[COL_POS_LIST[item_index]]) # update Button item.set_new_image(col) item.color = COLOR_LIST[COL_POS_LIST[item_index]] box = gui.Container() box.add( gui.Button(10, 10, utils.load_image("cube.bmp", True), "Back")) box.add( gui.Button(constants.SCR_WIDTH - 70, 10, utils.load_image("cube.bmp", False), "Graph!")) box.add(text_entries) box.add(button_entries) while True: if pygame.event.peek(QUIT): utils.quit() box.update(*pygame.event.get()) for item in box: if isinstance(item, gui.Button) and item.clicked: item.clicked = False if item.text == "Back": return elif item.text == "": change_colors(item) elif item.text == "Graph!": exprs = [(x.expr_text, y.color) for x, y in zip(text_entries, button_entries) if x.expr_text] draw_graph(exprs) blit_background() box.draw(SCREEN) pygame.display.update()
def __generate_agg_xml(self): try: self.xml_string += "<AggregationEvent>" self.__add_attribute('eventTime', self.__generate_time_in_iso_format(self.event_params[self.EV_TIME])) self.__add_attribute('eventTimeZoneOffset', self.EV_DEFAULT_TIME_ZONE) self.xml_string += "<baseExtension>" self.__add_attribute('eventID', self.event_params[self.EV_ID]) self.xml_string += "</baseExtension>" self.xml_string += self.__generate_bizloc(self.event_params[self.EV_BIZLOC]) # output is a pallet id etc., the parent # for now, only Logistic Units are supported as parents; infact, only 1 logistic unit. x = json.loads(self.event_params[self.EV_OUTPUT]) lu_details = x[0] self.__add_attribute('parentID', self.__generate_lu(lu_details)) if self.event_params[self.EV_INPUT_TYPE] == 'E': self.__generate_epc_list('childEPCs', self.event_params[self.EV_INPUT]) elif self.event_params[self.EV_INPUT_TYPE] == 'Q': self.__add_attribute('childEPCs', '') else: utils.quit('Unknown Input Type ' + self.event_params[self.EV_INPUT_TYPE]) self.__add_attribute('action', 'ADD') self.xml_string += self.__generate_bizstep(self.event_params[self.EV_BIZSTEP]) self.xml_string += '<extension>' # generate the inputs, the children if self.event_params[self.EV_INPUT_TYPE] == 'Q': self.__generate_quantity_list('childQuantityList', self.event_params[self.EV_INPUT]) self.xml_string += self.__generate_src_dest('source', self.event_params[self.EV_SRC]) self.xml_string += self.__generate_src_dest('destination', self.event_params[self.EV_DEST]) self.xml_string += '</extension>' # add biz txn documents here self.xml_string += self.__generate_biztxn_list(self.event_params[self.EV_BIZ_TXN_TYPE_LIST]) self.xml_string += '</AggregationEvent>' utils.d_print(2, "## Aggregation: ", self.xml_string) except: utils.print_exception(1) return
def register(config, name, provider, enable): """Register an application for monitor and evaluation.""" try: url = config.server_url + '/v1/applications' headers = {'username': config.user, 'Content-Type': 'application/json'} data = json.dumps({ 'name': name, 'provider': provider, 'enabled': enable }) rest = Rest(url, headers, data) display(rest.post()) except RestError as error: quit(error.message)
def __generate_lu(self, lu_details): try: utils.d_print(7, "LU Gen", lu_details) return_str = '' if 'lu' in lu_details: lud = lu_details['lu'] if 'urn:ibm:ift:' in lud: return_str = lud else: utils.quit("GS1 LUs not yet implemented.") else: utils.d_print(7, "LU Generation: ", lu_details) utils.quit("'lu' key not present.") return return_str except: utils.print_exception(1)
def start(config, daemon): """Start Jaguar service. Examples: $ jaguar service start $ jaguar service --daemon start """ # Make sure java is available if not environ.get(JAGUAR_HOME): raise click.UsageError('JAGUAR_HOME envrionment variable is not set.') dir_must_exist(environ.get(JAGUAR_HOME)) execute_envsh(config.conf) if environ["JAVA_HOME"] is not None and environ["JAVA_HOME"]: prg = join(environ["JAVA_HOME"], "bin", "java") else: prg = which("java") if prg is None: quit("Cannot locate java.") # Jaguar conf properties = join(config.conf, JAGUAR_PROPERTIES) args = JAGUAR_CONF_ARGS.format(properties).split() # Jaguar log logback = join(config.conf, JAGUAR_LOGBACK) args.extend(JAGUAR_LOG_ARGS.format(logback).split()) # Jaguar port args.extend(JAGUAR_PORT_ARGS.format(config.server['port']).split()) # Jaguar classpath classpath = join(environ.get(JAGUAR_HOME), 'lib', '*') jvm_opts_list = DEFAULT_JVM_OPTS.split() # Shall we daemonize? if daemon: daemonize() environ['LOG_APPENDER'] = 'FILE' else: environ['LOG_APPENDER'] = 'STDOUT' commandline = [prg] commandline.extend(jvm_opts_list) commandline.append("-classpath") commandline.append(classpath) commandline.append(JAGUAR_CLASSNAME) commandline.extend(args) return run(commandline)
def __generate_obs_xml(self): try: self.xml_string += "<ObjectEvent>" self.__add_attribute('eventTime', self.__generate_time_in_iso_format(self.event_params[self.EV_TIME])) self.__add_attribute('eventTimeZoneOffset', self.EV_DEFAULT_TIME_ZONE) self.xml_string += "<baseExtension>" self.__add_attribute('eventID', self.event_params[self.EV_ID]) self.xml_string += "</baseExtension>" self.xml_string += self.__generate_bizloc(self.event_params[self.EV_BIZLOC]) self.xml_string += self.__generate_bizstep(self.event_params[self.EV_BIZSTEP]) self.__add_attribute('action', 'OBSERVE') if self.event_params[self.EV_INPUT_TYPE] == 'E': self.__generate_epc_list('epcList', self.event_params[self.EV_INPUT]) elif self.event_params[self.EV_INPUT_TYPE] == 'Q': self.__add_attribute('epcList', '') else: utils.quit('Unknown Input Type ' + self.event_params[self.EV_INPUT_TYPE]) self.xml_string += '<extension>' # input for observation if self.event_params[self.EV_INPUT_TYPE] == 'Q': self.__generate_quantity_list('quantityList', self.event_params[self.EV_INPUT]) elif self.event_params[self.EV_INPUT_TYPE] != 'E': utils.quit('Unknown Input Type ' + self.event_params[self.EV_INPUT_TYPE]) self.xml_string += self.__generate_src_dest('source', self.event_params[self.EV_SRC]) self.xml_string += self.__generate_src_dest('destination', self.event_params[self.EV_DEST]) self.xml_string += '</extension>' # add biz txn documents here self.xml_string += self.__generate_biztxn_list(self.event_params[self.EV_BIZ_TXN_TYPE_LIST]) self.xml_string += '</ObjectEvent>' utils.d_print(2, "## Observation: ", self.xml_string) except: utils.print_exception(1) return
def openBrowser(args): if args.webdriver is not None: if 'chromedriver' in args.webdriver: try: browser = webdriver.Chrome(args.webdriver) return browser except WebDriverException: quit(3, '-p value does not point to valid chromedriver, try downloading chromedriver again.') elif 'geckodriver' in args.webdriver: try: browser = webdriver.Firefox(args.webdriver) return browser except WebDriverException: quit(3, '-p value does not point to valid geckodriver, try downloading geckodriver again.') elif 'operadriver' in args.webdriver: try: browser = webdriver.Opera(args.webdriver) return browser except WebDriverException: quit(3, '-p value does not point to valid operadriver, try downloading operadriver again.') else: quit(3, 'Invalid -p value. It should contain chromedriver, geckodriver or operadriver.') else: try: browser = webdriver.Chrome() return browser except WebDriverException: pass try: browser = webdriver.Firefox() except WebDriverException: pass try: browser = webdriver.Opera() except WebDriverException: quit(4, """Error: No webdriver found. 1. Download chromedriver, geckodriver or operadriver according to your browser preferences. 2. Place it into a folder containing this script. 3. Start main.py again.""")
def __generate_xfm_xml(self): try: self.xml_string += "<extension> <TransformationEvent>" self.__add_attribute('eventTime', self.__generate_time_in_iso_format(self.event_params[self.EV_TIME])) self.__add_attribute('eventTimeZoneOffset', self.EV_DEFAULT_TIME_ZONE) self.xml_string += "<baseExtension>" self.__add_attribute('eventID', self.event_params[self.EV_ID]) self.xml_string += "</baseExtension>" self.xml_string += self.__generate_bizloc(self.event_params[self.EV_BIZLOC]) self.xml_string += self.__generate_bizstep(self.event_params[self.EV_BIZSTEP]) # input for transformation if self.event_params[self.EV_INPUT_TYPE] == 'Q': self.__generate_quantity_list('inputQuantityList', self.event_params[self.EV_INPUT]) elif self.event_params[self.EV_INPUT_TYPE] == 'E': self.__generate_epc_list('inputEPCList', self.event_params[self.EV_INPUT]) else: utils.quit('Unknown Input Type ' + self.event_params[self.EV_INPUT_TYPE]) # output for transformation if self.event_params[self.EV_OUTPUT_TYPE] == 'Q': self.__generate_quantity_list('outputQuantityList', self.event_params[self.EV_OUTPUT]) elif self.event_params[self.EV_OUTPUT_TYPE] == 'E': self.__generate_epc_list('outputEPCList', self.event_params[self.EV_OUTPUT]) else: utils.quit('Unknown Output Type ' + self.event_params[self.EV_OUTPUT_TYPE]) self.xml_string += "<extension>" self.xml_string += self.__generate_src_dest('source', self.event_params[self.EV_SRC]) self.xml_string += self.__generate_src_dest('destination', self.event_params[self.EV_DEST]) self.xml_string += "</extension>" # add biz txn documents here self.xml_string += self.__generate_biztxn_list(self.event_params[self.EV_BIZ_TXN_TYPE_LIST]) self.xml_string += "</TransformationEvent></extension> " utils.d_print(2, "## Transformation: ", self.xml_string) except: utils.print_exception(1) return
def update(config, id, enable): """Update an application""" try: url = config.server_url + '/v1/applications/' + str(id) headers = {'username': config.user, 'Content-Type': 'application/json'} rest = Rest(url, headers) # check if the application exists response = rest.get() if response.status_code != requests.codes.ok: quit('Error: Application ' + str(id) + ' does not exist.') result = response.json() # update the field result['enabled'] = enable # post the data back data = json.dumps(result) rest = Rest(url, headers, data) display(rest.put()) except RestError as error: quit(error.message)
def __get_id_from_name(self): # set up the API for correct org set_up = False for organization in utils.global_args.myorgs['orgs']: org_name = str(organization['name']) if self.name.upper() in org_name.upper(): if organization['env'] == utils.global_args.env: utils.d_print(5, "Org: ", organization) self.properties = organization self.id = organization['orgid'] set_up = True break if set_up == False: print (organization) utils.d_print(0, "Organization [", utils.global_args.client, "] not found in the myorgs.json file.") utils.quit("") return self.id
def cli(self): prompt = ''' +===========================+ | [0]查成绩 | | [1]个人信息 | | [2]选修课 | | [3]登录其他账号 | | [4]清除历史记录 | | [5]安全退出 | +===========================+ >>> ''' self.usrname = rinput('学号: ') self.usrpswd = rinput('密码: 00000000\b\b\b\b\b\b\b\b') status = self.login() if status['status']: choice = True choice_dict = { '0': self.get_score, '1': self.get_info, '2': self.elective, '3': self.cli, '4': clear, '5': quit } while choice is True: usr_choice = rinput('\r' + prompt).strip()[0] os.system('clear') if usr_choice in choice_dict: choice_dict.get(usr_choice)() choice = usr_choice not in "35" else: print('Input incorrect..again!') else: print(status['info']) cho = rinput('Any key to continue, [q] to quit.') if cho == 'q': quit() else: self.cli()
def run(self): self.show_menu() for event in pygame.event.get(): utils.common_events(event) if event.type == pygame.MOUSEMOTION: mouseover = False for element in Menu.main_menu + Menu.game_menu + Menu.results_menu: if element[1].collidepoint(event.pos): pygame.mouse.set_cursor(*pygame.cursors.diamond) mouseover = True if not mouseover: pygame.mouse.set_cursor(*pygame.cursors.arrow) if event.type == pygame.MOUSEBUTTONDOWN: if self.current_menu == Menu.main_menu: if Menu.play_choice_rect.collidepoint(event.pos): self.current_menu = Menu.game_menu self.show_menu() elif Menu.rules_choice_rect.collidepoint(event.pos): webbrowser.open( "https://en.wikipedia.org/wiki/Rules_of_Go") elif Menu.quit_choice_rect.collidepoint(event.pos): utils.quit() elif self.current_menu == Menu.game_menu: if Menu.nine_by_nine_goban_choice_rect.collidepoint( event.pos): return constants.GameChoice.NINE_BY_NINE_GOBAN elif Menu.thirteen_by_thirteen_goban_choice_rect.collidepoint( event.pos): return constants.GameChoice.THIRTEEN_BY_THIRTEEN_GOBAN elif Menu.nineteen_by_nineteen_goban_choice_rect.collidepoint( event.pos): return constants.GameChoice.NINETEEN_BY_NINETEEN_GOBAN elif Menu.return_choice_rect.collidepoint(event.pos): self.current_menu = Menu.main_menu self.show_menu() elif self.current_menu == Menu.results_menu: if Menu.return_choice_rect.collidepoint(event.pos): self.current_menu = Menu.main_menu self.show_menu() elif Menu.quit_choice_rect.collidepoint(event.pos): utils.quit() pygame.display.flip()
def cli(self): prompt = ''' +===========================+ | [0]查成绩 | | [1]个人信息 | | [2]选修课 | | [3]登录其他账号 | | [4]清除历史记录 | | [5]安全退出 | +===========================+ >>> ''' self.usrname = rinput('学号: ') self.usrpswd = rinput('密码: 00000000\b\b\b\b\b\b\b\b') status = self.login() if status['status']: choice = True choice_dict = { '0': self.get_score, '1': self.get_info, '2': self.elective, '3': self.cli, '4': clear, '5': quit } while choice is True: usr_choice = rinput('\r'+prompt).strip()[0] os.system('clear') if usr_choice in choice_dict: choice_dict.get(usr_choice)() choice = usr_choice not in "35" else: print('Input incorrect..again!') else: print(status['info']) cho = rinput('Any key to continue, [q] to quit.') if cho == 'q': quit() else: self.cli()
def __generate_com_xml(self): try: self.xml_string += "<ObjectEvent>" # convert time to required string and add self.__add_attribute('eventTime', self.__generate_time_in_iso_format(self.event_params[self.EV_TIME])) self.__add_attribute('eventTimeZoneOffset', self.EV_DEFAULT_TIME_ZONE) self.xml_string += "<baseExtension>" self.__add_attribute('eventID', self.event_params[self.EV_ID]) self.xml_string += "</baseExtension>" self.__add_attribute('action', 'ADD') self.xml_string += self.__generate_bizstep(self.event_params[self.EV_BIZSTEP]) self.xml_string += self.__generate_bizloc(self.event_params[self.EV_BIZLOC]) if self.event_params[self.EV_OUTPUT_TYPE] == 'Q': self.__add_attribute('epcList', '') else: utils.quit("Add EPCs in Commission event to handle type 'E'") self.xml_string += "<extension>" if self.event_params[self.EV_OUTPUT_TYPE] == 'Q': self.__generate_quantity_list('quantityList', self.event_params[self.EV_OUTPUT]) # add source and desination lists here self.xml_string += self.__generate_src_dest('source', self.event_params[self.EV_SRC]) self.xml_string += self.__generate_src_dest('destination', self.event_params[self.EV_DEST]) self.xml_string += "</extension>" # add biz txn documents here self.xml_string += self.__generate_biztxn_list(self.event_params[self.EV_BIZ_TXN_TYPE_LIST]) self.xml_string += "</ObjectEvent>" utils.d_print(2, "## Commission: ", self.xml_string) except: utils.print_exception(1) return
def list(config, id): """List registered applications. Examples: $ jaguar application list $ jaguar application list --id 50 """ try: if id > 0: url = config.server_url + '/v1/applications/' + str(id) else: url = config.server_url + '/v1/applications' headers = {'username': config.user} rest = Rest(url, headers) display(rest.get()) except RestError as error: quit(error.message)
def update(config, app_id, type, id, file): """Update an application policy. """ try: data = '' while True: chunk = file.read(1024) if not chunk: break data += chunk if not is_json(data): raise click.BadParameter('The policy file ' + file.name \ + ' is not a valid json file.') url = config.server['url'] + '/v1/applications/' + str(app_id) \ + '/policies/' + type + '/' + str(id) headers = {'username':config.user, 'Content-Type':'application/json'} rest = Rest(url, headers, data) display(rest.put()) except RestError as error: quit(error.message)
def update(config, app_id, type, id, file): """Update an application policy. """ try: data = '' while True: chunk = file.read(1024) if not chunk: break data += chunk if not is_json(data): raise click.BadParameter('The policy file ' + file.name \ + ' is not a valid json file.') url = config.server_url + '/v1/applications/' + str(app_id) \ + '/policies/' + type + '/' + str(id) headers = {'username': config.user, 'Content-Type': 'application/json'} rest = Rest(url, headers, data) display(rest.put()) except RestError as error: quit(error.message)
def menu(): box = gui.Container() box.add( gui.Button(100, 50, utils.load_image("sphere.bmp", True), "Graph", 30, colors.white, get_func_exprs)) box.add( gui.Button(300, 200, utils.load_image("sphere.bmp", True), "Settings", 30, colors.white, settings)) box.add( gui.Button(500, 350, utils.load_image("sphere.bmp", True), "Help", 30, colors.white, xhelp)) while True: if pygame.event.peek(QUIT): utils.quit() events = pygame.event.get() box.update(*events) blit_background() box.draw(SCREEN) pygame.display.update()
def main(): current_dir = os.path.dirname(os.path.abspath(__file__)) default_conf_file = os.path.join(current_dir, 'config.json') theme_file = os.path.join(current_dir, 'themes', 'dracula.json') obj = load_config(default_conf_file) config.update(obj) theme = load_config(theme_file) config.update({'THEME': theme}) users.authenticate_user() while True: try: promt = color(config['THEME']['PROMT'])(config['PROMT_MSG']) data = input(promt).strip() except EOFError: print() continue except KeyboardInterrupt: sys.exit(yellow('\nGoodbye, see you. :)')) except Exception: continue if data == 'q': utils.quit(yellow('Bye, see you. :)'), EXIT_SUCCESS) try: args = data.split() cmd = args[0] COMMANDS[cmd](*args[1:]) except (KeyError, ValueError): print(red('Command `{}` not found!'.format(data))) except (IndexError, KeyboardInterrupt): pass except TypeError: print(red('Sorry, I can\'t understand.')) except NotImplementedError: utils.perr(red('command hasn\'t implemented yet!')) except Exception as err: utils.perr(red(err))
def settings(): """ Options for graphing. New settings are only saved after you press Accept. This way, we can also have a Cancel button (that discards all changes made). """ def save(): # the file is assumed to be small enough to # fit in memory all at once (which it should) with utils.load_tfile("settings.txt", "rU") as f: stuff = f.read() # read old data and modify our new copy new_lines = [] for line in stuff.split("\n"): l = line.split() if l[0] == "GRID_ON": l[1] = str(int(grid_setting)) elif l[0] == "AXES_ON": l[1] = str(int(axis_setting)) elif l[0] == "GRAPH_ANIM": l[1] = str(int(graph_anim_setting)) elif l[0].startswith("x") or l[0].startswith("y"): for t_entry in xy_t_entries: if t_entry.text.startswith(l[0]): l[1] = t_entry.expr_text GRAPH[l[0]] = float(l[1]) break new_lines.append(" ".join(l)) GRAPH["x_dist"] = GRAPH["x_right"] - GRAPH["x_left"] GRAPH["y_dist"] = GRAPH["y_bottom"] - GRAPH["y_top"] # now overwrite the old file with our new copy with utils.load_tfile("settings.txt", "w") as f: f.write("\n".join(new_lines)) box = gui.Container() box.add( gui.Button(10, 10, utils.load_image("cube.bmp", True), "Cancel")) box.add( gui.Button(constants.SCR_WIDTH - 70, 10, utils.load_image("cube.bmp", True), "Accept")) xy_settings = [] with utils.load_tfile("settings.txt", "rU") as f: for line in f: l = line.rstrip("\n") if l.startswith("GRID_ON"): grid_setting = bool(int(l.split()[1])) elif l.startswith("AXES_ON"): axis_setting = bool(int(l.split()[1])) elif l.startswith("GRAPH_ANIM"): graph_anim_setting = bool(int(l.split()[1])) elif l.startswith("x") or l.startswith("y"): xy_settings.append(l) # grid box.add( gui.Label(10, 120, "Grid:")) grid_button = \ gui.Button(70, 100, utils.load_image("cube.bmp", True), "On" if grid_setting else "Off") box.add(grid_button) # axes box.add( gui.Label(210, 120, "Axes:")) axis_button = \ gui.Button(270, 100, utils.load_image("cube.bmp", True), "On" if axis_setting else "Off") box.add(axis_button) # graph animation box.add( gui.Label(410, 120, "Graph animation: ")) graph_anim_button = \ gui.Button(570, 100, utils.load_image("cube.bmp", True), "On" if graph_anim_setting else "Off") box.add(graph_anim_button) # x/y settings y = 200 xy_t_entries = [] for item in xy_settings: t_entry = \ gui.TextEntry(10, y, item.split()[0] + ": ", 30, colors.white, 300) box.add(t_entry) t_entry.text += item.split()[1] t_entry.expr_text = item.split()[1] xy_t_entries.append(t_entry) y += 50 while True: if pygame.event.peek(QUIT): utils.quit() box.update(*pygame.event.get()) for item in box: if isinstance(item, gui.Button) and item.clicked: item.clicked = False if item is grid_button: grid_setting = not grid_setting item.text = "On" if grid_setting else "Off" elif item is axis_button: axis_setting = not axis_setting item.text = "On" if axis_setting else "Off" elif item is graph_anim_button: graph_anim_setting = not graph_anim_setting item.text = "On" if graph_anim_setting else "Off" elif item.text == "Cancel": # changes are merely discarded return elif item.text == "Accept": save() return blit_background() box.draw(SCREEN) pygame.display.update()
def draw_graph(exprs): """ Draw all functions in |exprs|: each element should supply a tuple (or any iterable thing), first element being the expression to be eval'd(), second element being a color. """ utils.cls(SCREEN) draw_grid = False draw_axes = False with utils.load_tfile("settings.txt", "rU") as f: for line in f: l = line.rstrip("\n").split() if l[0] == "GRID_ON" and l[1] == "1": draw_grid = True elif l[0] == "AXES_ON" and l[1] == "1": draw_axes = True elif l[0] == "GRAPH_ANIM": GRAPH["GRAPH_ANIM"] = bool(int(l[1])) if draw_grid: draw_funcs.draw_grid(GRAPH, SCREEN, colors.white) if draw_axes: draw_funcs.draw_axes(GRAPH, SCREEN, colors.silver) pygame.display.update() for expr, col in exprs: # automatically add in multiplication signs a = re.findall(r"[0-9]+x", expr) for pattern in a: expr = expr.replace(pattern, "".join(pattern.split("x") + ["*x"])) # change ^ to ** expr = expr.replace("^", "**") draw_funcs.draw_function( GRAPH, SCREEN, expr, col) pygame.event.clear() # save a copy of the current screen for performance reasons # (extremely slow to constantly replot functions) graphed_surface = SCREEN.copy() box = gui.Container() pos_label = gui.Label(0, 0, "(0, 0)", 20, colors.lime) pos_label_pos = (0, 0) while True: if pygame.event.peek(QUIT): utils.quit() events = pygame.event.get() for event in events: if event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == KEYUP and event.key == K_BACKQUOTE: import time t = time.strftime("%b%d %I_%M_%S") del time pygame.image.save(graphed_surface, "graph_%s.bmp" % (t)) elif event.type == MOUSEMOTION: pos_label_pos = event.pos elif event.type == MOUSEBUTTONDOWN and event.button == 1: if pos_label in box: box.remove(pos_label) else: box.add(pos_label) box.update(*events) pos_label.x, pos_label.y = pos_label_pos pos_label.text = "(%.3f, %.3f)" % ( draw_funcs.to_graph(GRAPH, *pos_label_pos)) utils.cls(SCREEN) SCREEN.blit(graphed_surface, (0, 0)) box.draw(SCREEN) pygame.display.update()
def xhelp(): """ Show help. Prefixed with an "x" to avoid confusion with builtin. """ def load(): """load help text files""" for i in range(5): parts.append([]) with utils.load_tfile("help%d.txt" % (i + 1), "rU") as f: for line in f: parts[i].append(line.rstrip("\n")) def update(): """update with new text""" help_labels.empty() y = 100 help_labels.add(gui.Label(100, 10, parts[current_part][0], 30)) for t in parts[current_part][2:]: help_labels.add(gui.Label(10, y, t, 20)) y += 20 box = gui.Container() help_labels = gui.Container() box.add( gui.Button(10, 10, utils.load_image("cube.bmp", True), "Back")) box.add( gui.Button(constants.SCR_WIDTH - 70, 10, utils.load_image("cube.bmp", True), "Next")) parts = [] current_part = 0 load() update() while True: if pygame.event.peek(QUIT): utils.quit() events = pygame.event.get() box.update(*events) help_labels.update(*events) for item in box: if isinstance(item, gui.Button) and item.clicked: item.clicked = False if item.text == "Back": current_part -= 1 if current_part < 0: return update() elif item.text == "Next": current_part += 1 if current_part >= len(parts): return update() blit_background() box.draw(SCREEN) help_labels.draw(SCREEN) pygame.display.update()