def sort(columniter): with status('Determining sort order'): info = datasets.source.columns if sum(info[column].type not in nononehandling_types for column in options.sort_columns): # At least one sort column can have unsortable values first = True iters = [] for column in options.sort_columns: it = columniter(column, status_reporting=first) first = False if info[column].type not in nononehandling_types: it = filter_unsortable(column, it) iters.append(it) if len(iters) == 1: # Special case to not make tuples when there is only one column. lst = list(iters[0]) else: lst = list(izip(*iters)) else: columns = options.sort_columns if len(columns) == 1: # Special case to not make tuples when there is only one column. columns = columns[0] lst = list(columniter(columns)) reverse = (options.sort_order == 'descending') with status('Creating sort list'): return sorted(range(len(lst)), key=lst.__getitem__, reverse=reverse)
def main(): numero = inicio() hp_enemy = dificultad(numero) print("******") hp = 100 turno = True print("Tu batalla inicia") while hp_enemy > 0 and hp > 0: ataqueenemigo = atack.atack_enemy(numero) print(f"El ataque de tu enemigo fue de { ataqueenemigo }") hp = hp - ataqueenemigo if hp > 0: if turno == True: status.status(hp, hp_enemy) print( "Te toca atacar\n Elige un ataque\n El ataque fuerte baja entre 20 y 65\n el ataque normalbaja entre 10 y 30 de vida\ para el ataque fuerte [1] y para el ataquee normal [1]" ) mi_ataque = int(input("=>")) elataque = atack.atk(mi_ataque) mi_dano = elataque[0] turno = elataque[1] print(f"Tu ataque fue de {mi_dano}") hp_enemy = hp_enemy - mi_dano if hp_enemy <= 0: print("Derribaste al enemigo, ganaste!!") else: status.status(hp, hp_enemy) pass else: turno = True else: print("Has muerto!!!, Perdiste") sys.exit()
def main(): args = sys.argv[1:] if len(args) < 1: logging.warning('Usage: python <filename> <function> <parameters..>') elif args[0] == 'init': init() elif args[0] == 'add': data_to_copy_path = args[1] add(data_to_copy_path) elif args[0] == 'commit': message = args[1] commit(message) elif args[0] == 'status': status() elif args[0] == 'checkout': commit_id = args[1] checkout(commit_id) elif args[0] == 'graph': graph() elif args[0] == 'branch': branch_name = args[1] branch(branch_name) elif args[0] == 'merge': branch_name = args[1] merge()
def processMissedRecords(): """get records that were missed because of server errors""" allrecids = glob.iglob(data_dir + '*afnmap') | Map(lambda f: open(f) | pCut(1)) | pFlatten | pSet missedids = allrecids - scrapedrecids for id in missedids: processRecord(id) time.sleep(_opts.waittime) status.status('missed ids', total=len(missedids))
def init_ui(self): # Sending mainWindow obj to initialize components # No need to store the objs because they're just init helper # Use parent-child relationship to access between classes self.menu = menu.menu(self) tool.tool(self) status.status(self) self.central = central.central(self)
def readChromosome(filename, chr_id, persons): with open(filename) as infile: for person in persons: txtdata = infile.readline() infile.readline() #ignore every alternate row person.chromosomes[chr_id] = Chromosome(person, chr_id, txtdata) status.status(total=len(persons)) assert infile.read() == ''
def processMissedRecords(): """get records that were missed because of server errors""" allrecids = glob.iglob(data_dir + '*afnmap') | Map( lambda f: open(f) | pCut(1)) | pFlatten | pSet missedids = allrecids - scrapedrecids for id in missedids: processRecord(id) time.sleep(_opts.waittime) status.status('missed ids', total=len(missedids))
def main(args): """ select appropriate response """ if args.status == True: status.status() elif args.write == True: write.write() else: parser.print_help()
def makeTree(size=100000, generations=10): nodes=[[Node(None, None) for spam in xrange(size)]] for i in xrange(size): nodes[0][i].location = i nodes[0][i].generation = 0 for gen in xrange(1,generations): newgen = newGen(nodes[-1],size) postProcessLocation(newgen) nodes.append(newgen) status.status(total=generations-1) return nodes
def statusmenu(db,user): import status while(True): user = db.member.find_one({'_id': user['_id']}) print('-'*49) print('1) Modify my name') print('2) Update my profile') print('3) Show my followings') print('4) Show my followers') print('5) Config my block list') print('q) Back to my status') print('-' * 49) n=input('Enter:') if n=='q':return status.status(n,db,user)
def build(method, options={}, datasets={}, jobids={}, name=None, caption=None): """Just like urd.build, but for making subjobs""" global _a assert g.running != 'analysis', "Analysis is not allowed to make subjobs" assert g.subjob_cookie, "Can't build subjobs: out of cookies" if not _a: from automata_common import Automata _a = Automata(g.daemon_url, subjob_cookie=g.subjob_cookie) _a.update_method_deps() _a.record[None] = _a.jobs = jobs def run(): return _a.call_method(method, options={method: options}, datasets={method: datasets}, jobids={method: jobids}, record_as=name, caption=caption) if name or caption: msg = 'Building subjob %s' % (name or method, ) if caption: msg += ' "%s"' % (caption, ) with status(msg): jid = run() else: jid = run() for d in _a.job_retur.jobs.values(): if d.link not in _record: _record[d.link] = bool(d.make) return jid
def pickle_load(filename='result', jobid='', sliceno=None, verbose=False, default=None, encoding='bytes'): filename = full_filename(filename, '.pickle', sliceno, jobid) if not filename and default is not None: return default if verbose: print('Pickle load "%s" ... ' % (filename, ), end='') t0 = time.time() try: with status('Loading ' + filename): with open(filename, 'rb') as fh: if PY3: ret = pickle.load(fh, encoding=encoding) else: ret = pickle.load(fh) except IOError: if default is not None: return default raise if verbose: print('done (%f seconds).' % (time.time() - t0, )) return ret
def __enter__(self): self._status = status('Saving ' + self.filename) self._status.__enter__() # stupid python3 feels that w and x are exclusive, while python2 requires both. fh = open(self.tmp_filename, 'xb' if PY3 else 'wbx') self.close = fh.close return fh
def effective_total(session, entries): if status(session) == "finished_provisional": # 1. total (league endpoint)!== total (entry endpoint): obsolete # 2. total (league endpoint)!== total (old + live) # => total (league) !== total (old live) # for entry in entries: return
def launchGame(params): app_id = int(params.get('id')) username = urllib.unquote_plus(params.get('username')) hostname = urllib.unquote_plus(params.get('hostname')) start = [] with Service() as service: app = service.update_app((hostname, username), app_id) if app["state"] == 4 or app["state"] == 8 or app["state"] == 16 or app["state"] == 64 or app["state"] == 8196: result = service.start_game((hostname, username), app_id) if result[0] != eresult.k_EResultOK: dialog = xbmcgui.Dialog() ok = dialog.ok(utils.translation(32012), utils.translation(32013) + "(Code: "+str(result[0])+")." + utils.translation(32014)) else: player = xbmc.Player() if player.isPlaying(): player.pause() dialog = xbmcgui.DialogProgress() dialog.update(0, utils.translation(32043), "", "") service.launch_client(result[1], result[2], result[3], app_id, (hostname, username)) dialog.close() elif app["state"] == -1 or app["state"] == 1: if xbmcgui.Dialog().yesno(utils.translation(32015), utils.translation(32016)): result = service.start_game((hostname, username), app_id) if result[0] == -1: #steam seems to use only positiv values, this is a little hacky. (TODO we should refactor this result to a dictionary) dialog = xbmcgui.Dialog() ok = dialog.ok(utils.translation(32012), utils.translation(32017)) elif result[0] == 3: #no idea, how that number comes for that case dialog = xbmcgui.Dialog() ok = dialog.ok(utils.translation(32018), utils.translation(32019)) else: if result[0] != eresult.k_EResultBusy: print "Unknown Result: "+str(result[0]) #TODO find a way to collect those (is informing the user to aggresive?) start.append(status.status(service, params)) else: print "Interesting state: "+str(app["state"]) #TODO find a way to collect those (is informing the user to aggresive?) start.append(status.status(service, params)) if len(start) > 0: if start[0] == "start": launchGame(params) if start[0] == "list": import listGames listGames.listGames(params)
def synthesis(params): if not options.sliced: filename = '%d.gz' if options.filename.lower().endswith('.gz') else '%d.csv' with open(options.filename, "wb") as outfh: for sliceno in range(params.slices): with status("Assembling %s (%d/%d)" % (options.filename, sliceno, params.slices)): with open(filename % sliceno, "rb") as infh: copyfileobj(infh, outfh) unlink(filename % sliceno)
def dispatch(messageJson=None): """ dispatch is the microservice dispatcher for IndigoGirls, a 2048-like game. It routes requests for game state transformations to the appropriate functions :param messageJson: JSON string that describes the state of the game needed for the requested transformation :return: A JSON string that describes the state of the game after the requested transformation has taken place. """ def buildErrorString(diagnostic=None): """ returns a dictionary containing the specified key and accompanying diagnostic information :param diagnostic: A string that describes the error :return: A dictionary that contains the specified error key having a value that consists of the specfied error string followed by a free-form diagnostic message """ ERROR_PROPERTY = u'gameStatus' ERROR_PREFIX = u'error: ' return {ERROR_PROPERTY: ERROR_PREFIX + diagnostic} #Validate JSONness of input be converting the string to an equivalent dictionary try: messageDictionary = json.loads(messageJson) except: resultDictionary = json.dumps( buildErrorString('input JSON string is invalid')) return resultDictionary #Validate presence of dispatching code if (u"op" not in messageDictionary): resultDictionary = json.dumps(buildErrorString('op is missing')) return resultDictionary #Perform the game transformation as directed by the value of the "op" key # input to each function: a dictionary containing the name-value pairs of the input JSON string # output of each function: a dictionary containing name-value pairs to be encoded as a JSON string if (messageDictionary[u"op"] == u"initializeGame"): resultDictionary = initializeGame( messageDictionary) #<---------- Added my implementation elif (messageDictionary[u"op"] == u"swipe"): resultDictionary = swipe(messageDictionary) elif (messageDictionary[u"op"] == u"recommend"): resultDictionary = recommend(messageDictionary) elif (messageDictionary[u"op"] == u"status"): resultDictionary = status(messageDictionary) elif (messageDictionary[u"op"] == u"predict"): resultDictionary = predict(messageDictionary) else: resultDictionary = buildErrorString('op is invalid') #Covert the dictionary back to a string in JSON format resultJson = json.dumps(resultDictionary) return resultJson
def fill_config_file_values(template_paths): log('Compiling configuration templates') env, cfg = load_env() for template_path in template_paths: with status(template_path): with open(template_path) as f: data = f.read() data_compiled = re.sub('\$\$\{\{([a-zA-Z_]+)?\}\}', '{\\1}', data.replace('{', '{{').replace('}', '}}')) with open(os.path.splitext(template_path)[0], 'w') as f: f.write(data_compiled.format(**cfg['ports']))
def main(): global _opts _opts, args = utils.EasyParser("waittime=1.0: missed").parse_args() if _opts.missed: processMissedRecords() for familyid in scrapequeue: themap = makeMap(familyid) time.sleep(_opts.waittime) if themap is None: themap = {} for recid in themap.itervalues(): if recid in scrapedrecids: continue processRecord(recid) time.sleep(_opts.waittime) status.status(total=len(scrapequeue)) qout.close() scrout.close()
def state(): data = status() # print data #Debug if data['vlc']: if data['type'] == 'video': return [True, 'Watching', parse_path(data['path'])] elif data['type'] == 'audio': return [True, 'Listening to', parse_path(data['path'])] else: return [True, 'your are not playing anything on VLC', ''] else: return [False, 'VLC is not running', '']
def main(): global _opts _opts, args = utils.EasyParser("waittime=1.0: missed").parse_args() if _opts.missed: processMissedRecords() for familyid in scrapequeue: themap = makeMap(familyid) time.sleep(_opts.waittime) if themap is None: themap = {} for recid in themap.itervalues(): if recid in scrapedrecids: continue processRecord(recid) time.sleep(_opts.waittime) status.status(total=len(scrapequeue)) qout.close() scrout.close()
def analysis(sliceno, params, prepare_res): dw, ds_list, sort_idx = prepare_res if options.sort_across_slices: columniter = partial(Dataset.iterate_list, None, datasets=ds_list) sort_idx = sort_idx[sliceno] else: columniter = partial(Dataset.iterate_list, sliceno, datasets=ds_list) sort_idx = sort(columniter) for ix, column in enumerate(datasets.source.columns, 1): colstat = '%r (%d/%d)' % ( column, ix, len(datasets.source.columns), ) with status('Reading ' + colstat): lst = list(columniter(column)) with status('Writing ' + colstat): w = dw.writers[column].write for idx in sort_idx: w(lst[idx]) # Delete the list before making a new one, so we use less memory. del lst
def test200_010_AcceptanceTest2(self): messageDictionary = { "tile": 200000, "board": { "columnCount": 4, "rowCount": 4, "grid": [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] } } resultDictionary = status.status(messageDictionary) result = resultDictionary["gameStatus"] expected = "error: invalid tile value" self.assertEquals(expected, result)
def test300_010_AcceptanceTest3(self): messageDictionary = { "tile": 512, "board": { "columnCount": 4, "rowCount": 4, "grid": [1, 0, 3, 1, 5, 6, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8] } } resultDictionary = status.status(messageDictionary) result = resultDictionary["gameStatus"] expected = "underway" self.assertEquals(expected, result)
def test100_010_AcceptanceTest1(self): messageDictionary = { "tile": 2, "board": { "columnCount": 4, "rowCount": 4, "grid": [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] } } resultDictionary = status.status(messageDictionary) result = resultDictionary["gameStatus"] expected = "win" self.assertEquals(expected, result)
def main(): """ handle main """ argument = take_argument() if argument.command == 'init': init() elif argument.command == 'add': handle_add(argument.file) elif argument.command == 'status': status() elif argument.command == 'commit': commits(argument.m) elif argument.command == 'log': log() elif argument.command == 'rm': rm(argument.file[0]) elif argument.command == 'ls-files': ls_files() elif argument.command == 'config': set_path(__file__) write_file('.lgit/config', argument.author + '\n', 'w')
def fill_config_file_values(template_paths): log('Compiling configuration templates') env, cfg = load_env() for template_path in template_paths: with status(template_path): with open(template_path) as f: data = f.read() template = jinja2.Template(data) rendered = template.render(cfg) with open(os.path.splitext(template_path)[0], 'w') as f: f.write(rendered)
def fill_config_file_values(template_paths): log('Compiling configuration templates') env, cfg = load_env() for template_path in template_paths: with status(template_path): tpath, tfile = os.path.split(template_path) env = jinja2.Environment(loader=jinja2.FileSystemLoader(tpath), ) env.filters['md5sum'] = md5sum template = env.get_template(tfile) rendered = template.render(cfg) with open(os.path.splitext(template_path)[0], 'w') as f: f.write(rendered) f.write('\n')
def main(argv): if not os.path.isdir(CONFIG_DIRECTORY): print("Creating directory for first time use...\n") os.mkdir(CONFIG_DIRECTORY) os.mkdir(CONFIG_DIRECTORY + "\\configs") os.mkdir(CONFIG_DIRECTORY + "\\seasions") parser = argparse.ArgumentParser(prog="cfun") parser.add_argument("command", help="your command") parser.add_argument("-f", "--file", help="location of your file", default="main.cpp") parser.add_argument("-pr", "--problem", help="problem you want to submit", default=os.path.basename(os.getcwd())) parser.add_argument("-u", "--user", help="Username", default=None) args = parser.parse_args() if args.command == "login": login.login_set() elif args.command == "submit": submit.submit(args.file, args.problem, False) elif args.command == "status": status.status(args.user)
def fill_config_file_values(template_paths): log("Compiling configuration templates") env, cfg = load_env() for template_path in template_paths: with status(template_path): tpath, tfile = os.path.split(template_path) jenv = jinja2.Environment( loader=jinja2.FileSystemLoader(tpath), ) jenv.filters.update(custom_filters) template = jenv.get_template(tfile) cfg['env'] = env rendered = template.render(cfg) with open(os.path.splitext(template_path)[0], "w") as f: f.write(rendered) f.write("\n")
def commands() -> None: """Redirects all the commands that require a wit path.""" wit_path = _search_parent_dir(".wit") _set_logger(os.path.join(wit_path, '.wit')) if sys.argv[1] == 'add': add(sys.argv[2], wit_path) elif sys.argv[1] == 'commit': print(commit(sys.argv[2], wit_path)) elif sys.argv[1] == 'status': print(status(wit_path)) elif sys.argv[1] == 'checkout': checkout(sys.argv[2], wit_path) elif sys.argv[1] == 'graph': graph(wit_path) elif sys.argv[1] == 'branch': branch(sys.argv[2], wit_path) elif sys.argv[1] == 'merge': merge(sys.argv[2], wit_path) else: logging.error( MethodNotFoundError(f'unrecognized method: "{sys.argv[1]}".'))
def _search(self): searchPath = [] judgePath = [] mySet = set([]) myStack = [] isMax = True self._root = status.status(status=self._current) myStack.append(self._root) while len(myStack) > 0: cur = myStack.pop() (complete, message) = cur.isCompleteAndMessage() if complete == True: continue if cur.getLevel() > self.depth: continue if cur not in mySet: searchPath.append(cur) sta = cur.getStatus() sons = self.createSons(sta, max=cur.getMax()) for i in sons: cur.addSonFromArray(i) sons = set(cur.getSons()) cur.setSons(sons) for i in sons: myStack.append(i) self._searchPath = searchPath self._priority = self._root.getPriority() self._bestPath = self._root.getBestPath()
def test_db(database): test_cmd = f"psql {flags} -c 'SELECT 0;' {database}" p = run(test_cmd) try: with status('Testing database connection'): if not p.returncode == 0: raise RuntimeError() except: print( textwrap.dedent(f''' !!! Error accessing database: The most common cause of database connection errors is a misconfigured `pg_hba.conf`. We tried to connect to the database with the following parameters: database: {db} username: {user} host: {host} port: {port} The postgres client exited with the following error message: {'-' * 78} {p.stderr.decode('utf-8').strip()} {'-' * 78} Please modify your `pg_hba.conf`, and use the following command to check your connection: {test_cmd} ''')) sys.exit(1)
def choices(): from globals import current_status_message loop = True while loop: cprint ("You Can Do following Things\n" \ "What do you want to do? \n " \ "1. Add a status update \n " \ "2. Add a friend \n " \ "3. Send a secret message \n " \ "4. Read a secret message \n " \ "5. Read Chats from a user \n " \ "6. Close Application \n", "cyan") try: choice = int(raw_input()) if choice == 1: current_status_message = status(current_status_message) elif choice == 2: total = add_friend() c = "Total Friend's = " + str(total) cprint(c, "magenta") elif choice == 3: send_message() elif choice == 4: read_message() elif choice == 5: read_chat() elif choice == 6: cprint("Thank You\nGood Bye!!!!!!!!!!!!!!", "red") exit() else: cprint("Wrong Choice", "red", attrs=["bold"]) loop = False except ValueError: cprint("Choose from the above please", "green", attrs=["bold"])
def readData(): gedfiles = os.popen('ls data | grep family') | pStrip | pList for filename in gedfiles: map(processBlock, parseGED('data/' + filename)) status.status(total=len(gedfiles))
os.mkdir(os.path.join(serverdir, "data")) conf = zoocfg(searchList=[{'sid' : sid, 'servername' : options.servers[sid - 1], 'clientPort' : options.clientports[sid - 1], 'weights' : options.weights, 'groups' : options.groups, 'serverlist' : serverlist, 'maxClientCnxns' : options.maxclientcnxns, 'electionAlg' : options.electionalg}]) writefile(os.path.join(serverdir, "zoo.cfg"), str(conf)) writefile(os.path.join(serverdir, "data", "myid"), str(sid)) writescript("start.sh", str(start(searchList=[{'serverlist' : serverlist}]))) writescript("stop.sh", str(stop(searchList=[{'serverlist' : serverlist}]))) writescript("status.sh", str(status(searchList=[{'serverlist' : serverlist}]))) writescript("cli.sh", str(cli())) for f in glob.glob(os.path.join(args[0], 'lib', '*.jar')): shutil.copy(f, args[1]) for f in glob.glob(os.path.join(args[0], 'src', 'java', 'lib', '*.jar')): shutil.copy(f, args[1]) for f in glob.glob(os.path.join(args[0], 'build', 'lib', '*.jar')): shutil.copy(f, args[1]) for f in glob.glob(os.path.join(args[0], '*.jar')): shutil.copy(f, args[1]) for f in glob.glob(os.path.join(args[0], 'build', '*.jar')): shutil.copy(f, args[1]) shutil.copyfile(os.path.join(args[0], "conf", "log4j.properties"), os.path.join(args[1], "log4j.properties"))