def argParse(): if len(argv) == 1: printHelp('Debe proporcionar los argumentos necesarios.') else: if '-h' in argv: printHelp() rutaProcesar = argv[argv.index('-i') + 1] if '-i' in argv else './' if not (isfile(rutaProcesar) or isdir(rutaProcesar)): printHelp('No se encontró el directorio o archivo ingresado.') outputDirectory = argv[argv.index('-o') + 1] if '-o' in argv else rutaProcesar if rutaProcesar != './' else './' if not isdir(outputDirectory): printHelp('No se encontró el directorio de salida "{}"'.format(outputDirectory)) try: TV = float(argv[argv.index('-tv') + 1]) if '-tv' in argv else 1.0 except ValueError: printHelp('TV debe ser un número (flotante o entero)') try: TI = float(argv[argv.index('-ti') + 1]) if '-ti' in argv else 1.0 except ValueError: printHelp('TI debe ser un número (flotante o entero)') for arg in argv: if arg.startswith('-v'): verboseLevel = arg.count('v') break else: verboseLevel = 0 return {'rutaProcesar': rutaProcesar.replace('\\','/'), 'outputDirectory': outputDirectory.replace('\\','/'), 'TV': TV, 'TI': TI, 'verboseLevel': verboseLevel}
def getBasePort(): ''' Returns the "ACS Base Port". This is just an integer ranging from 0-10. Tries to determine the value in the following ways: 1. Searches the command-line for --baseport option 2. Searches the command-line for the -b option 3. Looks for the ACS_INSTANCE environment variable 4. Defaults to 0. Parameters: None Return: base port number Raises: Nothing ''' #look for --baseport in the command-line try: base_port = int(argv[ argv.index("--baseport") + 1 ]) return base_port except: pass #look for -b in the command-line try: base_port = int(argv[ argv.index("-b") + 1 ]) return base_port except: pass try: return int(environ['ACS_INSTANCE']) except KeyError, excp: return int(0)
def main(): # Project文件夹路径 if argv.count('-d') == 0: print("Error:Project文件夹路径必填,格式:“-d D:\F28_Dual_DVP”。") exit() else: project_directory = argv[argv.index('-d') + 1] for i in range(argv.index('-d') + 2, len(argv)): if not argv[i].startswith('-'): project_directory += (' ' + argv[i]) else: break if project_directory[:2] == '.\\': project_directory = getcwd() + project_directory[1:] # Excel文件路径 if argv.count('-f') == 0: print("Error:Excel文件路径必填,格式:“-f D:\Example_v2.0.xlsx”。") exit() else: excel_dir = argv[argv.index('-f') + 1] for i in range(argv.index('-f') + 2, len(argv)): if not argv[i].startswith('-'): excel_dir += (' ' + argv[i]) else: break # 生成文件 generate_project(excel_dir, project_directory)
def check_help_option(): try: argv.index(ProgramArguments.help_arg) print_help() exit(0) except ValueError as HelpOptionNotUsed: pass
def __load_cmd_line_args(self): """ :return: """ required_fields = self.my_config['config'][self.default_conf]['required_fields'] resp = {} for f in required_fields: resp[f]='' if len(cmd_args) > len(required_fields)*2: for field in required_fields: arg = '--{arg_type}'.format(arg_type=field) if arg in cmd_args: if path.exists(cmd_args[cmd_args.index(arg)+1]): resp[field] = cmd_args[cmd_args.index(arg)+1] else: print self.error_codes.errors_list[4]['msg'] exit(self.error_codes.errors_list[4]['exit_code']) else: print self.error_codes.errors_list[3]['msg'] exit(self.error_codes.errors_list[3]['exit_code']) return resp['input'], resp['output'] else: print self.error_codes.errors_list[2]['msg'] exit(self.error_codes.errors_list[2]['exit_code'])
def main(): user,recAmt,library,libraryFile = configParse() if library == None: if user == None: user = input('Enter discogs username:'******'d like to clean this up """ validArgs = ['-r','-h','-update'] if len(argv) > 1: if '-r' in argv: if argv.index('-r') + 1 < len(argv): try: int(argv[argv.index('-r') + 1]) recAmt = int(argv[argv.index('-r') + 1]) except (TypeError,ValueError): print('Incorrect formatting for "-r" argument. We need an integer after it. Defaulting to 1') help() recAmt = 1 else: print("Incorrect formatting for "-r" argument. We need a number after it.") recAmt = 1 help() if '-h' in argv: help() if '-update' in argv: print('Updating...') library = popLibrary(user) libraryDump(library,libraryFile) print('Done.') if '-r' not in argv and '-update' not in argv and '-gtk' not in argv: # some argument was given but not valid help() if '-update' not in argv and '-h' not in argv: if library == None: library = popLibrary(user) libraryDump(library,libraryFile) listenList = genSuggest(recAmt,library,list(library)) if '-gtk' in argv: mainGtk(user,library) else: mainCli(listenList) else: listenList = genSuggest(recAmt,library,list(library)) if '-gtk' in argv: mainGtk(user,library) else: mainCli(listenList)
def get_parameter(): print("length:{}, content:{}".format(len(argv), argv)) file_path = argv[argv.index('--file_path') + 1] if "--outpath" not in argv: outpath = None else: outpath = argv[argv.index('--outpath') + 1] return file_path, outpath
def main(): value = {} count = {} numberOfPlays = int(argv[argv.index("-numberOfPlays")+1]) discount = float(argv[argv.index("-discount")+1]) for i in range(numberOfPlays): cards = makeCardDeck() generatePlay(cards,value,count,discount)
def check_args(self): if "--all" in argv[1:]: self.dl_all() if "--name" in argv[1:]: repname = argv[argv.index("--name") + 1] self.dl_rep(repname) if "-n" in argv[1:]: repname = argv[argv.index("-n") + 1] self.dl_rep(repname)
def prepare_arguments(): global CAIDS_FILTER, DIR_TPL, DIR_PNG, DIR_OSCAMCFG if len(sys_argv) <= 2 or ('-a' in sys_argv and '-c' not in sys_argv): show_man_page() return False if '-a' not in sys_argv: if '-o' in sys_argv: DIR_OSCAMCFG = sys_argv[sys_argv.index('-o') + 1] else: folder_list = [ '/etc/tuxbox/config', '/etc/tuxbox/oscam', '/etc/tuxbox/config/oscam', '/usr/keys/oscam', '/usr/local/etc' ] DIR_OSCAMCFG = [ d for d in folder_list if os_path.isfile(d + '/oscam.server') ] if DIR_OSCAMCFG: DIR_OSCAMCFG = DIR_OSCAMCFG[0] print('Oscam configuration directory found: %s' % DIR_OSCAMCFG) else: show_man_page() print( 'ERROR ! The Oscam configration folder was not found ! Please use the "-o" argument.' ) return False if '-1' in sys_argv and not os_path.isfile(DIR_OSCAMCFG + '/oscam.srvid'): print('ERROR ! The oscam.srvid file does not exist !') return False if '-2' in sys_argv and not os_path.isfile(DIR_OSCAMCFG + '/oscam.srvid2'): print('ERROR ! The oscam.srvid2 file does not exist !') return False if '-c' in sys_argv: clist = sys_argv[sys_argv.index('-c') + 1].upper().split(',') CAIDS_FILTER = [s.rjust(4, '0') for s in clist] print('User-selected CAIDs that will be considered: %s' % ', '.join(CAIDS_FILTER)) else: CAIDS_FILTER = [] print( 'User-selected CAIDs: <empty/blank> (all found CAIDs will be included !)' ) DIR_TPL = sys_argv[-1] DIR_PNG = sys_argv[-2] if not (os_path.isdir(DIR_TPL) and os_path.isdir(DIR_PNG)): print('ERROR ! TPL or PNG directory does not exist !') return False return True
def create_processes(n=20): try: x = int(.8 * n) y = n - x argv.index("-PART2") starts = exp_rand(x) p = [Process(pid, 0, randrange(500, 4001), randrange(0, 5)) for pid in range(y)] p.extend([Process(pid+y, starts[pid], randrange(500,4001), randrange(0,5)) for pid in range(x)]) except: p = [Process(pid, 0, randrange(500, 4001), randrange(0, 5)) for pid in range(n)] return p
def get_outputs(argv): if '-o' in argv: flag_pos = argv.index('-o') elif '--outputs' in argv: flag_pos = argv.index('--outputs') else: raise ValueError("no outputs provided") end = flag_pos + 1 while end < len(argv) and not argv[end].startswith('-'): end += 1 assert end != flag_pos + 1, "no outputs provided." return argv[flag_pos + 1 : end]
def get_dmu(argv): if '-d' in argv: flag_pos = argv.index('-d') assert flag_pos + 1 < len(argv) and not argv[flag_pos + 1].startswith('-'), "no 'dmu' column specified." dmu = argv[flag_pos + 1] elif '--dmu' in argv: flag_pos = argv.index('--dmu') assert flag_pos + 1 < len(argv) and not argv[flag_pos + 1].startswith('-'), "no 'dmu' column specified." dmu = argv[flag_pos + 1] else: dmu = 'dmu' return dmu
def get_destination(argv, stem, name): if '-w' in argv: flag_pos = argv.index('-w') assert flag_pos + 1 < len(argv) and not argv[flag_pos + 1].startswith('-'), "no destination specified." destination, _name = get_stem_name(argv[flag_pos + 1]) elif '--destination' in argv: flag_pos = argv.index('--destination') assert flag_pos + 1 < len(argv) and not argv[flag_pos + 1].startswith('-'), "no destination specified." destination, _name = get_stem_name(argv[flag_pos + 1]) else: destination = stem return destination, name if _name is None else _name
def main(): '''Main method. Put in method so can be exported.''' i = Interpreter() #TODO cleaner argument parsing if "-c" in argv and len(argv) > argv.index("-c") + 1: exprs = argv[argv.index("-c") + 1] for expr in exprs.split(";"): interpret(i, expr) else: # just a bit of main loop stuff cli = CalcInterpreterCLI(i) cli.cmdloop()
def get_parameter(): print ("length:{}, content:{}".format(len(argv),argv)) file_path = argv[argv.index('--file_path')+1] if "--quantile" not in argv: quantile = 0.5 else: quantile = float("%.1f"%float(argv[argv.index('--quantile')+1])) if "--outpath" not in argv: outpath = None else: outpath = argv[argv.index('--outpath')+1] return file_path, quantile, outpath
def get_parameter(): print("length:{}, content:{}".format(len(argv), argv)) file_path = argv[argv.index('--file_path') + 1] if "--confidence" not in argv: confidence = 0.95 else: confidence = float("%.2f" % float(argv[argv.index('--confidence') + 1])) if "--outpath" not in argv: outpath = None else: outpath = argv[argv.index('--outpath') + 1] return file_path, confidence, outpath
def rdarg(argv,key,conv=None,default=None,single=0): val = default if key in argv: if not single: val=argv[argv.index(key)+1] del argv[argv.index(key):argv.index(key)+2] if conv: val=map(conv,[val])[0] else: del argv[argv.index(key):argv.index(key)+1] val = 1 if default == 1: val=0 else: if conv and val: val=apply(conv,(val,)) return argv,val
def main(): if "-u" not in argv or "-p" not in argv: exit("usage: python main.py -u <username> -p <password>") username = argv[argv.index("-u") + 1] password = argv[argv.index("-p") + 1] rss = RSS() article = rss.read_latest_article_from_rss() content = '\n'.join([article.title, article.link]) t = Twitter() t.login(username, password) t.postTweet(content)
def testCmd(argv) : global HELP try: # ---------- do you need some help ? argv.index("-h") HELP = 1 printUsage(argv[0], 0) except: try: argv.index("--help") HELP= 1 printUsage(argv[0], 0) except: HELP = 0 return
def server_setup(): host = '127.0.0.1' port = 3500 if '-p' in argv: port = int(argv[argv.index('-p') + 1]) elif '--port' in argv: port = int(argv[argv.index('--port') + 1]) if '--host' in argv: host = argv[argv.index('--host') + 1] print(f'[*] Listening on {host}:{port}') run_server(host, port)
def main(): debug = False if 'debug' in argv or '--debug' in argv: debug = True if 'pinyin' in argv: py = sinopy.pinyin(argv[argv.index('pinyin') + 1]) print(py) if 'profile' in argv: if '--cldf' in argv: wl = Wordlist.from_cldf(argv[argv.index('profile') + 1], col='language_id', row='parameter_id') wl.add_entries('doculect', 'language_name', lambda x: x) else: wl = Wordlist(argv[argv.index('profile') + 1]) column = 'ipa' language = None filename = 'orthography.tsv' if '--column' in argv: column = argv[argv.index('--column') + 1] if '--language' in argv: language = argv[argv.index('--language') + 1] if '-l' in argv: language = argv[argv.index('-l') + 1] if '-o' in argv: filename = argv[argv.index('-o') + 1] if '--filename' in argv: filename = argv[argv.index('--filename') + 1] segments.write_structure_profile(wl, column=column, filename=filename, debug=debug, language=language)
def main(): tl = TodoList() if "--list" in argv: for number, task in enumerate(tl): print(number, task) exit() if "--add" in argv: tl.add(" ".join(argv[argv.index("--add") + 1:])) exit() if "--remove" in argv: tl.remove(argv[argv.index("--remove") + 1]) exit()
def run(self): """ Metodo run del thread, viene richiamato tramite start(). Viene eseguito un loop che cerca a intervalli di 30 secondi nuovi hosts sulla rete e per ogni host che trova inizializza un thread che ne raccoglie le informazioni. I vari thread vengono raccolti all'interno di una lista. L'indirizzo della rete viene preso dalla linea di comando o se non fornito si cerca di indovinarlo a partire dall'ip della macchina (assumendo che la netmask sia 255.255.255.0 come spesso si verifica). """ self.known_hosts = [] if '-n' in argv: network_address = argv[argv.index('-n') + 1] elif '--network' in argv: network_address = argv[argv.index('--network') + 1] else: network_address = get_network_address() if not network_address: print("Cannot find network address... program will continue without network scanning!\n" + "If this trouble persist, try providing the network address in the launch command!\n" + "Press CTRL-C to terminate!") exit() while(True): hosts = host_discovery(network_address) for host in hosts: if not (host in self.known_hosts): self.known_hosts.append(host) print("Starting thread for host %s" % host) thread = Host(host) self.threads.append(thread) thread.start() for thread in self.threads: if not thread.is_alive: self.known_hosts.remove(thread.info['ip']) sleep(30)
def main(): if '-o' in argv[1:]: ver = get_closest_version(argv[argv.index('-o') + 1]) else: ver = get_latest_version() if '-g' in argv[1:]: gui() return elif '-h' in argv[1:]: usage() return elif '-r' in argv[1:]: revert() return elif '-b' in argv[1:]: backup(ver) return print('Latest Version: ', ver) if '-v' in argv[1:]: return del_current(False) download_chromium(ver) unzip()
def main(argv=None): """Print to stdout the project home path found with find_project_dir.find_project_dir(`project_homes`, `verbose`) """ from sys import stdout, stderr # stderr.write(repr(argv) + '\n') project_homes = None # ['~/src', '~/flint-projects', '~/bin', '~/projects', '~/sublime-projects', '~'] proj_subdirs = None # TODO: Use getopt to process project_homes, verbose, and project_name keyword options/args verbose = False for verbosity in ('verbose', '-v'): if verbosity in argv: del(argv[argv.index(verbosity)]) verbose = True if argv and len(argv) >= 2: project_name = argv[1] found_path = find_project_dir(project_name=project_name, project_homes=project_homes, proj_subdirs=proj_subdirs, verbose=verbose) # stderr.write(found_path + '\n') if found_path: stdout.write(found_path) # Don't attempt to os.chdir here, because subprocesses aren't allowed to affect the parent env else: stderr.write('Unable to find a valid virtualenvwrapper path in $VENVWRAP_PROJECT_HOMES=%s\n that contains the project name %s\n and also contains a subdir among $VIRTUALENVWRAPPER_PROJECT_HOMES_CONTAIN=%s.\n' % (repr(project_homes), repr(environ.get('VIRTUAL_ENV', '')), repr(proj_subdirs)))
def check_input(self, argument): if argument in argv: next_element = argv[argv.index(argument) + 1] if '-' in next_element: print('\n Error: no user-defined argument for {}. \n'.format( argument)) exit()
def getBotFile(self): DEFAULT_BOT_FILE = "bots/TheDistractingCicada.bot" if "--" in argv: botfile = argv[argv.index("--") + 1:].pop(0) else: botfile = DEFAULT_BOT_FILE return botfile
def __init__(self): if ".py" in argv[0]: self.name = f"python {argv[0]}" else: self.name = argv[0] self.french = 0 if "-mfr" in argv: argv.pop(argv.index("-mfr")) self.french = 1 if len(argv) == 2 and "adv" in argv: self.exam_type = "adv" elif len(argv) == 2 and "basic" in argv: self.exam_type = "basic" else: print(f"\nUsage: {self.name} 'basic' or 'adv'") print("Mode Français: Ajouter '-mfr' au fin\n") exit(1) if self.exam_type == "adv": self.question_total = 50 else: self.question_total = 100 self.pwd = os.path.dirname(__file__) self.file_name = f"amat_{self.exam_type}_quest" self.file_path = os.path.join(self.pwd, self.file_name) self.log_path = os.path.join(self.pwd, self.file_name[:-6] + "_EXAM") self.url = f"https://apc-cap.ic.gc.ca/datafiles/{self.file_name}.zip" self.score = 0
def main(): if '-h' in args or '--h' in args or '--help' in args: print 'Usage is as follows: ./makefile -if infile -of outfile -s stepsize -t runtime_in_seconds -org organism_name' print 'Good default values are -s 500 and -t 120 -org scenedesmus_dimorphus' sys.exit() vals = [args[args.index(flag) + 1] for flag in ['-if', '-of', '-s', '-t', '-org']] infile = vals[0] outfile = vals[1] step = int(vals[2]) runtime = int(vals[3]) organism = vals[4].replace('_', ' ') if infile[-5:] == 'fasta': seq_dict = parse_fasta(infile) pickle.dump(seq_dict, open(infile[:-5]+'seq_dict', 'w')) else: seq_dict = pickle.load(open(infile, 'r')) #offset for chunks of sequences to blast o = 0 start = time.time() seq_dict_keys = seq_dict.keys(); n = len(seq_dict_keys) descs = [] #logic that queries as many queries possible in time given, and if we run out of queries before allotted time, end querying while time.time()-start < runtime and o+step < n: sample_seqs = [(k, seq_dict[k]) for k in seq_dict_keys[o:o+step]] descs += get_descriptions(sample_seqs, organism) o += step print 'Time Elapsed:', int(time.time()-start), 'seconds' pickle.dump(descs, open(outfile, 'w'))
def main(): '''main method''' targets = argv[argv.index("-target") + 1][1:-1].split( ',') #read targets from input regression, advice = False, False if "-reg" in argv: regression = True if "-expAdvice" in argv: advice = True for target in targets: data = Utils.readTrainingData(target, regression, advice) #read training data numberOfTrees = 10 #number of trees for boosting trees = [] #initialize place holder for trees for i in range(numberOfTrees): #learn each tree and update gradient print('=' * 20, "learning tree", str(i), '=' * 20) node.setMaxDepth(2) node.learnTree(data) #learn RRT trees.append(node.learnedDecisionTree) Boosting.updateGradients(data, trees) for tree in trees: print('=' * 30, "tree", str(trees.index(tree)), '=' * 30) for clause in tree: print(clause) testData = Utils.readTestData(target, regression) #read testing data Boosting.performInference(testData, trees) #get probability of test examples
def run(self): otpNames = listdir(self.openPath) # collation folder path if argv.count('-c') == 0: collationFolder = self.openPath + '_collation' else: collationFolder = argv[argv.index('-c') + 1] MkDir(collationFolder) otpFolders = [] for otpName in otpNames: if isdir(join(self.openPath, otpName)): otpFolders.append(join(self.openPath, otpName)) # classify raw files according to the image type in the file name pattern = '(\S+)_(\S+)-(\S+)_(\d+)_(\S+)_(\d+)x(\d+).raw' for i in range(len(otpFolders)): # get files under the folder fileList = GetFileList(otpFolders[i], '.raw') for file in fileList: fileName = basename(file) res = match(pattern, fileName) form = res[5] targetFolder = join(collationFolder, form) MkDir(targetFolder) copy(file, targetFolder) self.currentCount += 1 if self.currentCount != barCount: self._signal.emit(str(self.currentCount * 100 // barCount)) self._signal.emit(str(100))
def client_setup(): host = '' port = 0 if '--host' in argv: host = argv[argv.index('--host') + 1] else: exit() if '-p' in argv: port = int(argv[argv.index('-p') + 1]) elif '--port' in argv: port = int(argv[argv.index('--port') + 1]) else: exit() client(host, port)
def hfst_specific_option(option): if option in argv: index = argv.index(option) argv.pop(index) return True else: return False
def parseArguments(self): pattern = r"-{1,2}" class Arguments: pass result = Arguments() for arg in self.args: name = sub(pattern, lambda m: "", arg.name) if arg.name in argv: i = argv.index(arg.name) try: value = arg.valueType(argv[i+1]) except IndexError: raise MissingArgumentException("Missing required argument: {0}" .format(arg.name)) except ValueError: raise IllegalValueException("Argument {0}: expected value of type {1}" .format(arg.name, arg.valueType)) if (arg.choices is not None and value not in arg.choices): raise IllegalValueException("{0} is not a valid value for argument {1}" .format(value, arg.name)) result.__setattr__(name, value) elif arg.default is not None: result.__setattr__(name, arg.default) else: raise MissingArgumentException("Missing required argument: {0}" .format(arg.name)) return result
def args_check(args_keys): """Check if command-line arguments are not empty.""" args_values = [arg for arg in argv if argv.index(arg) % 2 == 0] for arg in args_values: if arg in args_keys: return True return False
def path_for_name(name: str, look_in_package=True) -> Path: """ Get a path input using a flag when the program is run. If no such argument is given default to the directory above the june with the name of the flag appended. e.g. --data indicates where the data folder is and defaults to june/../data Parameters ---------- name A string such as "data" which corresponds to the flag --data Returns ------- A path """ flag = f"--{name}" try: path = Path(argv[argv.index(flag) + 1]) if not path.exists(): raise FileNotFoundError(f"No such folder {path}") except (IndexError, ValueError): path = find_default(name, look_in_package=look_in_package) logger.warning(f"No {flag} argument given - defaulting to:\n{path}") return path
def getCalcArgs(): from sys import argv # get cmdline args in a dict config = {} # ex: -bg black -fg red for arg in argv[1:]: # font not yet supported if arg in ['-bg', '-fg']: # -bg red' -> {'bg':'red'} try: config[arg[1:]] = argv[argv.index(arg) + 1] except: pass return config
def main(): # excluding this programs name (argv[0]) and all arguments up to and # and excluding the first "--" are c files to include try: c_code_files = argv[1:argv.index("--")] except ValueError: # there might be no "--" c_code_files = argv[1:] if len(c_code_files) == 0: raise Exception("You must provide at least one C source file") state = State() state.autoSetupSystemMacros() state.autoSetupGlobalIncludeWrappers() interpreter = Interpreter() interpreter.register(state) for cfile in c_code_files: state = parse(cfile, state) main_func = interpreter.getFunc("main") if len(main_func.C_argTypes) == 0: return_code = interpreter.runFunc("main", return_as_ctype=False) else: # if the main() function doesn't have zero arguments, it # should have the standard two, (int argc0, char **argv0) assert(len(main_func.C_argTypes) == 2) # first c file is program name and first argument arguments_to_c_prog = [c_code_files[0]] try: # append everything after the "--" as c program arguments arguments_to_c_prog += argv[argv.index("--")+1:] except: ValueError # return_as_ctype=False as we're expecting a simple int or None for void return_code = interpreter.runFunc( "main", len(arguments_to_c_prog), arguments_to_c_prog, return_as_ctype=False) if isinstance(return_code, int): exit(return_code)
def get_short_param(self, short_param=None, single_param=True, is_mark=False): """Get the target according to the short require :param short_param (string) well, actually this most functions like the `get_full_param`, but I prefer to make a difference this param is more likely to be `-b` or `-l`, in this case, this method support a kind match like when give `-nutpl` and `-l` is a mark (is_mark=True) `-l` will be regard as True :param single_param (bool) whether or not continues to see the following as the param example will be seen at `get_full_param` but in short term :param is_mark (bool) whether the param head used ad a mark only example will be seen at `get_full_param` but in short term """ if is_mark: if short_param in self.args: return True if short_param.startswith(self.prefix_short) and self.args: from re import compile regs = compile('(?<={})\w'.format(self.prefix_short)) target = regs.findall(short_param)[0] for param in self.args: if param.startswith(self.prefix_short) and \ not param.startswith(self.prefix) and \ target in param: return True if short_param not in argv: return False last = argv[argv.index(short_param):] if len(last) > 1: if single_param: return argv[argv.index(short_param) + 1] result = '' for single in argv[argv.index(short_param) + 1:]: if not single.startswith(self.prefix) and not single.startswith(self.prefix_short): result += single + ' ' else: break return result.strip() return False
def main(): compout = subprocess.PIPE if "--run" not in argv else subprocess.STDERR retcode = subprocess.call(" ".join(CXX, FLAGS, OPTIM).split(), stdout=compout) if retcode == 0: print("### DONE COMPILING\n") if "--run" in argv: retcode = subprocess.call(["./bin/main"] + argv[argv.index("--run"):], stdout=subprocess.PIPE) print("### DONE RUNNING\n") return retcode else: print("### FAILED COMPILING\n") return retcode
def get_data(key,data_type,default=None): if key not in argv: if default == None: return data_type() else: return default key_in = argv.index(key) if data_type==str: output = argv[key_in+1] elif data_type==list: output = [] for i in range(key_in+1,len(argv)): if argv[i][0]=='-': break else: output.append(argv[i]) return output
def main(): """ run the actual LocalBox Server. Initialises the symlink cache, starts a HTTPServer and serves requests forever, unless '--test-single-call' has been specified as command line argument """ symlinkcache = SymlinkCache() try: position = argv.index("--clear-user") user = argv[position + 1] user_folder = join( config.get('filesystem', 'bindpoint'), user) getLogger('api').info( "Deleting info for user " + user, extra={'ip': 'cli', 'user': user}) for sqlstring in 'delete from users where name = ?', 'delete from keys where user = ?', 'delete from invitations where sender = ?', 'delete from invitations where receiver = ?', 'delete from shares where user = ?': database_execute(sqlstring, (user,)) for symlinkdest in symlinkcache: if symlinkdest.startswith(user_folder): symlinks = symlinkcache.get(symlinkdest) for symlink in symlinks: remove(symlink) rmtree(user_folder) return except (ValueError, IndexError): port = int(config.get('httpd', 'port', 443)) insecure_mode = config.getboolean('httpd', 'insecure-http', default=False) server_address = ('', port) httpd = HTTPServer(server_address, LocalBoxHTTPRequestHandler) if insecure_mode: getLogger(__name__).warn('Running Insecure HTTP') getLogger(__name__).warn('Therefore, SSL has not been enabled.') getLogger(__name__).warn('WARNING: Therefore, THIS SERVER IS NOT SECURE!!!') if "--test-single-call" not in argv: HALTER("Press a key to continue.") else: certfile, keyfile = get_ssl_cert() httpd.socket = wrap_socket(httpd.socket, server_side=True, certfile=certfile, keyfile=keyfile) getLogger().info("Server ready", extra={'user': None, 'ip': None, 'path': None}) if "--test-single-call" in argv: httpd.handle_request() else: httpd.serve_forever()
def main(): # Arguments: # -sf - pickled seq_dict file # -df - pickled descriptor file # -info - what type of info you want, options include: # -orthotable # -exontable # -general # -of - outfile to write the info to, if supplied with 'stdout' it will print to screen # -t - integer argument specifying top hits to write, if -1 will write all hits in unsorted order if '-h' in args or '--h' in args or '--help' in args: print 'Usage is as follows: ./display.py -sf seq_dict_file -df descriptor_file -info info_type -of outfile -t top_hits' sys.exit() vals = [args[args.index(flag) + 1] for flag in ['-sf', '-df', '-info', '-of', '-t']] info = vals[2] outfile = vals[3] top_hits = int(vals[4]) seq_dict = pickle.load(open(vals[0], 'r')) descs = pickle.load(open(vals[1], 'r')) if top_hits != -1: descs = sorted(descs, key= lambda x: x[3], reverse=True) descs = descs[:top_hits] print_str = '' if info == 'orthotable': for desc in descs: print_str += orthotable_row(desc) elif info == 'exontable': for desc in descs: print_str += exontable_row(desc) elif info == 'general': for desc in descs: print_str += general_row(desc) if outfile == 'stdout': print print_str else: open(outfile, 'w').write(print_str)
def environ(self): from sys import argv # disable cache by specifying --nocache on the command line! # usefull to configure default settings for wine apps if '--nocache' in argv: self['NOCACHE']='1' del argv[argv.index('--nocache')] # this is a NVidia var. It disables VBLANK, which # seems to make opengl apps more stable under wine. self['__GL_SYNC_TO_VBLANK'] = '0' # we need to set this to force wine to use our wine instead # of system wine, if it needs to spaw another process. self['WINELOADER'] = self.path('bin/wine') # check if wacon is attached if wacom(): # if not, disables wintab32, so wine won't show up # the annoying wintab warning dialog! self['WINEDLLOVERRIDES'] = 'wintab32=n'
def main(): from domainmodeller import settings # Parse command line arguments from sys import argv verbose = '-v' in argv if verbose: argv.remove('-v') log_level = logging.DEBUG if '-vv' in argv else logging.INFO if log_level==logging.DEBUG: argv.remove('-vv') if '-D' in argv: loc = argv.index('-D') del argv[loc] database = argv[loc] del argv[loc] else: database = settings.DATABASE from domainmodeller.storage import Storage storage = Storage.init_storage(database, **settings.BACKEND) run(storage, argv[1:], log_console=verbose, log_level=log_level)
print '*'*80 print '* Executing wallet-fragmenting script. Split your Armory wallet ' print '* into N pieces, requiring any M to recover the wallet.' print '*'*80 print '' try: from subprocess import Popen, PIPE proc = Popen('git rev-parse HEAD', shell=True, stdout=PIPE) commitHash = proc.stdout.read().strip() print 'Found hash of current git commit:', commitHash except: commitHash = None if '--testnet' in argv: i = argv.index('--testnet') del argv[i] if len(argv)<2: print '' print 'USAGE: %s file.wallet [M] [N] ' % argv[0] print '' print 'Will produce N files, of which any subset of M of them is ' print 'sufficient to reproduce your wallet.' print '' exit(0) wltfile,M,N = argv[1:] try: M = int(M) N = int(N)
def get_arg(option): return argv[argv.index(option)+1]
-d <device> - Specify path to serial device, if not, default one is: /dev/ttyUSB0 if device == 'nodev' no serial IO will be perf. chart - generate charts (unless "nodb" specified) vartext - generate plain text output from actual values varjs - generate javascript file with variables For more features,visit github and place feature request""") if "help" in argv: print_help() exit(0) dry= "dry" in argv or "dryrun" in argv if "-d" in argv: ttyS_device=argv[argv.index("-d")+1]#next argument after -d is device itself... GENchart= "chart" in argv GENtext= "vartext" in argv GENjs= "varjs" in argv debug= "debug" in argv insane= "insane" in argv dbaccess ="nodb" not in argv #we won't need data from DB, do not access it at all... if dry and not GENchart: nodb=True if debug: print("DEBUG mode enabled!! warn: high verbosity ;-)")
print '\nTrained neural net:\n', nn data = multi_forward_prop(nn, sigmoid, resolution)[1] pyplot.clf() pc = pyplot.pcolor(data) pyplot.colorbar(pc) pyplot.show() if __name__ == "__main__": train = "diagonal" net = "medium" resolution = 1 if '-data' in argv: train = argv[argv.index('-data') + 1] else: print 'defaulting to diagonal training dataset' if '-net' in argv: net = argv[argv.index('-net') + 1] else: print 'defaulting to medium net' if '-resolution' in argv: resolution = argv[argv.index('-resolution') + 1] else: print 'defaulting to resolution of 1' start_training(train, net, resolution)
def arg_parser(): """ Parses the arguments and calls the help() function if any problem is found """ global PRINT_PIXIE global PRINT_REAVER global USE_PIXIEWPS global AIRODUMP_TIME global REAVER_TIME global CHANNEL global PROMPT_APS global OUTPUT_FILE global OUTPUT global GET_PASSWORD global FOREVER global OVERRIDE global BLACKLIST global RSSI global MAX_APS global USE_MODES H = ['-h','--help'] flags = ['-p','-P','-f','-q','-F','-A'] binary_flags = ['-a','-t','-c','-o','-s','-m','-M', '--max-aps','--rssi','--airodump-time','--time','--channel','--output','--mode'] for arg in argv[1:]: if arg in H: help() exit() elif argv[argv.index(arg)-1] in binary_flags: continue elif arg == '-m' or arg == '--mode': USE_MODES = True mode = argv[argv.index(arg)+1] if mode == 'WALK': USE_PIXIEWPS = True AIRODUMP_TIME = 4 REAVER_TIME = 8 GET_PASSWORD = True FOREVER = True MAX_APS = 2 elif mode == 'DRIVE': USE_PIXIEWPS = True REAVER_TIME = 10 FOREVER = True MAX_APS = 1 elif mode == 'STATIC': USE_PIXIEWPS = True AIRODUMP_TIME = 5 REAVER_TIME = 10 GET_PASSWORD = True PROMPT_APS = True OVERRIDE = False else: print ALERT + "Do you even mode bro?" print " Check available modes in the help." help() elif arg == '-M' or arg == '--max-aps': try: MAX_APS == int(argv[argv.index(arg)+1]) except ValueError: help() elif arg == '-s' or arg == '--rssi': try: RSSI = int(argv[argv.index(arg)+1]) if RSSI < -100 or RSSI > 0: help() except ValueError: help() elif arg == '-q' or arg == '--quiet': PRINT_PIXIE = False PRINT_REAVER = False elif arg == '-p' or arg == '--use-pixie': USE_PIXIEWPS = True elif arg == '-a' or arg == '--airodump-time': try: AIRODUMP_TIME = int(argv[argv.index(arg)+1]) if REAVER_TIME <= 0: help() except ValueError: help() elif arg == '-t' or arg == '--time': try: REAVER_TIME = int(argv[argv.index(arg)+1]) if REAVER_TIME <= 0: help() except ValueError: help() elif arg == '-c' or arg == '--channel': try: CHANNEL = int(argv[argv.index(arg)+1]) if CHANNEL <= 0 or CHANNEL >= 15: help() except ValueError: help() elif arg == '-P' or arg == '--prompt': PROMPT_APS = True elif arg == '-o' or arg == '--output': OUTPUT = True try: m = argv[argv.index(arg)+1] if m not in flags: if m not in binary_flags: OUTPUT_FILE = m except IndexError: pass elif arg == '-f' or arg == '--pass': GET_PASSWORD = True elif arg == '-F' or arg == '--forever': FOREVER = True elif arg == '-A' or arg == '--again': OVERRIDE = False BLACKLIST = False else: help() if CHANNEL != '': AIRODUMP_TIME = 1
parser.add_argument('-verbose', help='how verbose? ', type=int, default=1) parser.add_argument('-tag', help='give a regexp pattern that has to match the tag', default=None ) parser.add_argument('-random_picks', type=float, help='pick X percent of the decoys randomly', default=None ) args = parser.parse_known_args()[0] from sys import argv,exit from os import popen, system from os.path import basename import string import subprocess REVERSE='' NSTRUCT=100000000 if args.tag: TAG_GREP=' egrep "%s" |'%args.tag iarg=argv.index('-tag') del argv[iarg+1] del argv[iarg] else: TAG_GREP='' if not args.formula: try: NSTRUCT = int(argv[-1]) del(argv[-1]) except: pass scorecol_defined = 0 try: SCORECOL = int(argv[-1])
from sys import argv, stdin, stderr incorrectArguments = False saveLocation = None if len(argv) > 1 and argv[1] not in ('-l', '-s'): incorrectArguments = True elif len(argv) > 1 and len(argv) < 3: incorrectArguments = True elif len(argv) > 3 and (len(argv) != 5 or argv[3] not in ('-l', '-s')): incorrectArguments = True elif '-l' not in argv: model = Model(list(stdin)) else: path = argv[argv.index('-l') + 1] try: model = Model.load(path) except IOError as ex: print "Unable to load model from the given path.", ex print incorrectArguments = True if not incorrectArguments: if '-s' in argv: path = argv[argv.index('-s') + 1] model.save(path) for name, layout in Layouts.layouts.items(): print name, model(layout)
from time import time import random from os import system from sys import argv # system('clear') print '' system('date') print '' if len(argv) == 1: print '''-l <spatie> [lengte] voor aantal regels\n -o voor openen in texteditor\n''' else: if '-l' in argv: l = int(argv[argv.index('-l') + 1]) bytes = 1.5*l**2 if bytes >= 10**9: print 'Grootte: {0:.1f} GB.'.format(bytes/10**9) elif bytes >= 10**6: print 'Grootte: {0:.1f} MB.'.format(bytes/10**6) elif bytes >= 10**3: print 'Grootte: {0:.1f} KB.'.format(bytes/10**3) elif bytes >= 0: print 'Grootte: {0:.1f} B.'.format(bytes) tic = time() filename = 'trigen2_{0}.txt'.format(l) f = open('/Users/Toine/Desktop/{0}'.format(filename), 'w')
return default # Default values eye_point = Point(0.0, 0.0, -14.0) min_x = -10.0 max_x = 10.0 min_y = -7.5 max_y = 7.5 width = 512 height = 384 light = Light(Point(-100.0, 100.0, -100.0), Color(1.5, 1.5, 1.5)) color = Color(1.0, 1.0, 1.0) if '-eye' in argv: i = argv.index('-eye') x = 0.0 y = 0.0 z = -14.0 try: x = float_default(argv[i + 1], 0.0) y = float_default(argv[i + 2], 0.0) z = float_default(argv[i + 3], -14.0) except: # Index out of bounds pass eye_point = Point(x, y, z)
dot_string += "\t"+node_styles[ns]+"\n" for node in nodes: if ns in nodes[node]: dot_string += "\t\t"+node+"\n" for es in edge_styles: dot_string += "\t"+edge_styles[es]+"\n" for edge in edges: if es in edges[edge]: dot_string += "\t\t"+edge[0]+" -> "+edge[1]+"[label=\""+es+"\"]\n" dot_string +="}" dot_file = open(output_file, "w") dot_file.write(dot_string) dot_file.close() return 0 if __name__=='__main__': output_file = "out.dot" # Parse command line arguments if "-o" in argv: output_file = argv[argv.index("-o")+1] if "-f" not in argv: dl_out = stdin.readline() else: dl_file = open(argv[argv.index("-f")+1], "r") dl_out = dl_file.read() dl_file.close() generateDot(dl_out, output_file)