def init_parser(): """ init parser debug or remote """ usage = "usage: %prog [options] arg" parser = OptionParser(usage=usage) parser.add_option("-l", "--local", dest="local", action="store_true", help="pwn for local bin", default=False) parser.add_option("-r", "--remote", dest="remote", action="store_true", help="pwn for remote bin", default=False) (options, args) = parser.parse_args() if options.remote: options.local = False options.remote = True elif options.remote: options.local = False options.remote = True else: options.local = True options.remote = False return options
def main(): parser = OptionParser('usage: %prog [options] task') parser.add_option("-f", "--config-file", dest='config_file', help="Configuration file") options, args = parser.parse_args() if not (options.config_file): parser.error("Please specify a configuration file.") logging.config.fileConfig(options.config_file) config = ConfigParser() config.read(options.config_file) session = get_session(config) today = date.today() entries = session.query(TimeEntry).filter( not_(TimeEntry.task.like('Aura %'))).filter( or_(TimeEntry.comment == None, TimeEntry.comment == '')).filter( TimeEntry.start_dt >= today).filter( TimeEntry.start_dt <= (today + timedelta(days=1))) grouped_entries = group_entries(entries) if grouped_entries: print 'Following Non-Aura entries require annotations:' print_alerts(session, grouped_entries) email_offenders(session, grouped_entries)
def main(): description = ( "This application generates .h and .ld files for symbols defined in input file. " "The input symbols file can be generated using nm utility like this: " "esp32-ulp-nm -g -f posix <elf_file> > <symbols_file>" ); parser = OptionParser(description=description) parser.add_option("-s", "--symfile", dest="symfile", help="symbols file name", metavar="SYMFILE") parser.add_option("-o", "--outputfile", dest="outputfile", help="destination .h and .ld files name prefix", metavar="OUTFILE") (options, args) = parser.parse_args() if options.symfile is None: parser.print_help() return 1 if options.outputfile is None: parser.print_help() return 1 with open(options.outputfile + ".h", 'w') as f_h, \ open(options.outputfile + ".ld", 'w') as f_ld, \ open(options.symfile) as f_sym: \ gen_ld_h_from_sym(f_sym, f_ld, f_h) return 0
def make_cli_parser(): """ Creates the command line interface parser. """ usage = "\n".join([ """\ python %prog [OPTIONS] FASTAFILE1 FASTAFILE2 ... ARGUMENTS: FASTAFILE1, FASTAFILE2, ...: paths to one or more FASTA formatted files """, __doc__ ]) cli_parser = OptionParser(usage) cli_parser.add_option( '-o', '--outfile', default=OUTFILE_NAME, help="path to output file [Default: %default]" ) cli_parser.add_option( '-b', '--barrelon', action='store_true', help="ignore possible errors in parsing" ) return cli_parser
def getOptions(): ''' Parse the command line and return a list of positional arguments and a dictionanary of keyword options. NOTE: Requirement is an inappropriate, oversimplification. Invoking argparse or optparse (deprecated with Python 2.7.0) do not produce equivalent output without substantial post processing that has not yet been created. This may explain inability to migrate use of tsApplication to tsCommandLineEnv or to tsWxMultiFrameEnv. ''' #global parser parser = OptionParser() parser.add_option("-c", "--command", action="store", dest="command", default=None, type="string", help="command [default = None]") parser.add_option("-V", "--Verbose", action="store_true", dest="verbose", default=False, help="print status messages to stdout [default = False]") (args, options) = parser.parse_args() return (args, options)
def LoadOptions(): """Load command line options.""" parser = OptionParser() parser.add_option("-g", "--game_id", dest="game_id") parser.add_option("-m", "--max_id", dest="max_id") cl_options = parser.parse_args()[0] return cl_options
def main(args=None): # parse the command line from optparse import OptionParser parser = OptionParser(description=__doc__) for key in choices: parser.add_option('--%s' % key, dest=key, action='store_true', default=False, help="display choices for %s" % key) options, args = parser.parse_args() # args are JSON blobs to override info if args: # lazy import import json for arg in args: if _os.path.exists(arg): string = file(arg).read() else: string = arg update(json.loads(string)) # print out choices if requested flag = False for key, value in options.__dict__.items(): if value is True: print '%s choices: %s' % (key, ' '.join([str(choice) for choice in choices[key]])) flag = True if flag: return # otherwise, print out all info for key, value in info.items(): print '%s: %s' % (key, value)
def parse_cmdline(argv=[]): cmdline = OptionParser() cmdline.add_option('-f', '--force-build', dest='force_build', action='store_true', default=False, help="run a build whether or not it's stale") cmdline.add_option('-n', '--no-report', dest='report', action='store_false', default=True, help="do not report build results to server") cmdline.add_option('-N', '--no-clean-temp', dest='cleanup_temp', action='store_false', default=True, help='do not clean up the temp directory') cmdline.add_option('-s', '--server-url', dest='server_url', action='store', default='default', help='set pony-build server URL for reporting results') cmdline.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='set verbose reporting') if not argv: (options, args) = cmdline.parse_args() else: (options, args) = cmdline.parse_args(argv) return options, args
def get_parameters(): global host global port global thr global item optp = OptionParser(add_help_option=False,epilog="Hammers") optp.add_option("-q","--quiet", help="set logging to ERROR",action="store_const", dest="loglevel",const=logging.ERROR, default=logging.INFO) optp.add_option("-s","--server", dest="host",help="attack to server ip -s ip") optp.add_option("-p","--port",type="int",dest="port",help="-p 80 default 80") optp.add_option("-t","--turbo",type="int",dest="turbo",help="default 135 -t 135") optp.add_option("-h","--help",dest="help",action='store_true',help="help you") opts, args = optp.parse_args() logging.basicConfig(level=opts.loglevel,format='%(levelname)-8s %(message)s') if opts.help: usage() if opts.host is not None: host = opts.host else: usage() if opts.port is None: port = 80 else: port = opts.port if opts.turbo is None: thr = 135 else: thr = opts.turbo
def generate_from_command_line_options(argv, msg_template_dict, srv_template_dict, module_template_dict = {}): from optparse import OptionParser parser = OptionParser("[options] <srv file>") parser.add_option("-p", dest='package', help="ros package the generated msg/srv files belongs to") parser.add_option("-o", dest='outdir', help="directory in which to place output files") parser.add_option("-I", dest='includepath', help="include path to search for messages", action="append") parser.add_option("-m", dest='module', help="write the module file", action='store_true', default=False) parser.add_option("-e", dest='emdir', help="directory containing template files", default=sys.path[0]) (options, argv) = parser.parse_args(argv) if( not options.package or not options.outdir or not options.emdir): parser.print_help() exit(-1) if( options.module ): generate_module(options.package, options.outdir, options.emdir, module_template_dict) else: if len(argv) > 1: generate_from_file(argv[1], options.package, options.outdir, options.emdir, options.includepath, msg_template_dict, srv_template_dict) else: parser.print_help() exit(-1)
def main(): usage = "usage: %prog [options] arg1 [arg2]" desc = """arg1: file with the output of the baseline search engine (ex: svm.test.res) arg2: predictions file from svm (ex: test/svm.pred) if arg2 is omitted only the search engine is evaluated""" parser = OptionParser(usage=usage, description=desc) parser.add_option("-t", "--threshold", dest="th", default=15, type=int, help="supply a value for computing Precision up to a given threshold " "[default: %default]", metavar="VALUE") parser.add_option("-r", "--reranking_threshold", dest="reranking_th", default=None, type=float, help="if maximum prediction score for a set of candidates is below this threshold, do not re-rank the candiate list." "[default: %default]", metavar="VALUE") parser.add_option("-f", "--format", dest="format", default="trec", help="format of the result file (trec, answerbag): [default: %default]", metavar="VALUE") parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true", help="produce verbose output [default: %default]") parser.add_option("--ignore_noanswer", dest="ignore_noanswer", default=False, action="store_true", help="ignore questions with no correct answer [default: %default]") (options, args) = parser.parse_args() if len(args) == 1: res_fname = args[0] eval_search_engine(res_fname, options.format, options.th) elif len(args) == 2: res_fname = args[0] pred_fname = args[1] eval_reranker(res_fname, pred_fname, options.format, options.th, options.verbose, options.reranking_th, options.ignore_noanswer) else: parser.print_help() sys.exit(1)
def main(): parser = OptionParser() parser.add_option("-s", "--sim_id", dest="sim_id", type="string", help="simulation id") parser.add_option("-d", "--sim_dirs", dest="sim_dirs", type="string", action="append", help="simulation directories") parser.add_option("-b", "--bam_fname", dest="bam_fname", type="string", help="name of the simulated bam file") parser.add_option("-o", "--out_dir", dest="out_dir", type="string", help="main output directory") parser.add_option("-c", "--config_template", dest="config_template", type="string", help="template file for config.txt") (options, args) = parser.parse_args() if options.sim_dirs is None and options.sim_id is None: parser.error("Specify simulation id or simulation directories") if options.sim_dirs is not None and options.sim_id is not None: parser.error("Simulation id and simulation directories are mutually exclusive options") if options.sim_dirs is not None: bam_dirs = options.sim_dirs if options.sim_id is not None: sim_dir = "/illumina/scratch/tmp/users/ccolombo/simulation/" print "Looking for simulation directories in: " + sim_dir bam_dirs = [sim_dir + dir for dir in os.listdir(sim_dir) if re.search("sim" + options.sim_id + ".*", dir)] if len(bam_dirs) == 0: print "No simulation directories found" if options.bam_fname is None: options.bam_fname = "sorted_Proteus_LP6007590_LP6007591_som_var.bam" print "Using default name for simulated bam: " + options.bam_fname if options.out_dir is None or not os.path.exists(options.out_dir): options.out_dir = "/illumina/build/CNA/CNV/haplotype_simulation/FREEC/" print "Using default output directory: " + options.out_dir if options.config_template is None or not os.path.exists(options.config_template): options.config_template = "/illumina/build/CNA/CNV/haplotype_simulation/FREEC/config_template.txt" print "Using default configuration template file: " + options.config_template run_FREEC(bam_dirs, options.out_dir, options.bam_fname, options.config_template)
def _parseArgs(): helpString = ( "This script scrubs data-path profiling info from YOMP service logs on " "the local host and emits a CSV file to STDOUT.\n" "%prog" ) parser = OptionParser(helpString) parser.add_option( "--logdir", action="store", type="str", default=logging_support.LoggingSupport.getLoggingRootDir(), dest="logDir", help=("Logging root directory path override. [default: %default]\n")) (options, posArgs) = parser.parse_args() if len(posArgs) != 0: parser.error("Expected no positional args, but got %s: %s" % ( len(posArgs), posArgs,)) if not os.path.isdir(options.logDir): parser.error("Log directory doesn't exist or is not a directory: %r" % (options.logDir,)) return { "logDir": options.logDir }
def main(argv=None): """Main entry point for the script""" ret_code = 0 if argv is None: argv = sys.argv parser = OptionParser() parser.add_option("-f", "--file", action="store", type="string", dest="filepath", default="/var/log/asterisk/refs", help="The full path to the refs file to process") (options, args) = parser.parse_args(argv) if not os.path.isfile(options.filepath): print("File not found: %s" % options.filepath, file=sys.stderr) return -1 try: process_file(options) except (KeyboardInterrupt, SystemExit, IOError): print("File processing cancelled", file=sys.stderr) return -1 return ret_code
def main(): parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="Database file to load", metavar="FILE") parser.add_option("-d", "--dest", dest="destfile", help="Database file to write to. If not supplied will use input database", metavar="FILE") parser.add_option("-n", "--name", dest="name", help="Attribute Name. If 'all' then all attributes will be changed", metavar="name") parser.add_option("-e", "--enable", dest="enabled", action="store_true", default=False, help="If set enable the meter. Otherwise disable") parser.add_option("-p", "--protocols", action="append", dest="protocols", help="Protocols to enable / disable the Attribute to. Not adding this means all") (options, args) = parser.parse_args() if options.filename is None or options.filename == "": print "ERROR: No Database file supplied\n" parser.print_help() sys.exit(1) if options.destfile is None or options.destfile == "": options.destfile = options.filename if options.name is None or options.name == "": print "ERROR: No Name\n" parser.print_help() sys.exit(1) toggle_attribute_meter(options.filename, options.destfile, options.name, options.enabled, options.protocols)
def __init__(self): self.__options = None parser = OptionParser( usage="%prog [-v] [-q] [-d] [-f] [-g] [-c config_file]", version="OSSIM (Open Source Security Information Management) " + \ "- Agent ") parser.add_option("-v", "--verbose", dest="verbose", action="count", help="verbose mode, makes lot of noise") parser.add_option("-d", "--daemon", dest="daemon", action="store_true", help="Run agent in daemon mode") parser.add_option("-f", "--force", dest="force", action="store_true", help="Force startup overriding pidfile") parser.add_option("-s", "--stats", dest="stats", type='choice', choices=['all', 'clients', 'plugins'], default=None, help="Get stats about the agent") parser.add_option("-c", "--config", dest="config_file", action="store", help="read config from FILE", metavar="FILE") (self.__options, args) = parser.parse_args() if len(args) > 1: parser.error("incorrect number of arguments") if self.__options.verbose and self.__options.daemon: parser.error("incompatible options -v -d")
def run( arguments ): '''run( arguments ) Parses and executes the given command-line `arguments`. Parameters: - arguments A list of strings representing the command-line arguments to ``restblog <command>``, e.g. ``sys.argv[2:]`` ''' # Parse usage = USAGE.strip() parser = OptionParser( usage=usage ) options = dict( interactive=False, ) parser.set_defaults( **options ) parser.add_option( '-i', '--interactive', action='store_true', help='Prompt for missing credentials when connecting to the server.' ) options, arguments = parser.parse_args( arguments ) # Validate if not arguments: raise RuntimeError, 'Required arguments are missing.' count = len( arguments ) if count != 1: raise RuntimeError, 'Unexpected arguments: %s' % ' '.join( arguments ) # Execute file_name = arguments[0] insert( file_name, options.interactive )
def main(): optparser = OptionParser() optparser.add_option( '-q', '--quiet', action='store_const', dest='verbosity', const=0, help="don't output anything to stderr") optparser.add_option( '-v', '--verbose', action='count', dest='verbosity', help="increase program verbosity") optparser.add_option( '-l', '--hostname', action='store', dest='hostname', help="hostname (or location) of this server") optparser.add_option( '-i', '--interface', action='store', dest='interface', help="interface (IP address) to bind to") optparser.add_option( '-p', '--port', action='store', dest='port', type='int', help="port number on which to listen") optparser.set_defaults(verbosity=1, hostname=None, interface='', port=8000) (options, args) = optparser.parse_args() options = vars(options) # options is not a dict!? run(**options)
def main(): url = "cmsweb.cern.ch" testbed_url = "https://cmsweb-testbed.cern.ch" # url = 'https://alan-cloud1.cern.ch' # Create option parser usage = "usage: %prog [options] [WORKFLOW]" parser = OptionParser(usage=usage) parser.add_option("-f", "--file", dest="file", default=None, help="Text file of a list of workflows") parser.add_option( "-m", "--memory", dest="memory", default=None, help="Memory to override the original request memory" ) (options, args) = parser.parse_args() wfs = None if options.file: wfs = [l.strip() for l in open(options.file) if l.strip()] elif args: wfs = args else: parser.error("Provide the Workflow Name") sys.exit(1) for wf in wfs: acdcs = makeAllACDCs(url, wf) print "created acdcs" print "\n".join(acdcs)
def parse_options(): """ Options parser. """ parser = OptionParser(option_class=eng_option, usage="%prog: [options]") parser.add_option("-s", "--servername", type="string", default="localhost", help="Server hostname") (options, args) = parser.parse_args() return options
def get_parser(): """Parse command line options and return an OptionParser object """ parser = OptionParser(version="%prog "+core.get_api_version()) parser.add_option("-d", "--debug", action="store_true", dest="debug", default=core.cfg['API_DEBUG'], help="Enable debug mode") parser.add_option("-f", "--force-node", dest="node", metavar="hostname", default=None, help="Specify the node to operate with") parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=core.cfg['QUIET'], help="Quiet mode: suppress extra outputs") parser.add_option("-n", "--no-refresh", action="store_true", dest="norefresh", default=core.cfg['NOREFRESH'], help="Don't refresh LVM metadatas (DANGEROUS)") parser.add_option("-c", "--console", action="store_true", dest="console", default=False, help="Attach console to the domain as soon as it has started.") parser.usage = "%prog <subcommand> [args] [options]\n\n" parser.usage += get_help() parser.epilog = "For more help on 'cxm' see the cxm(1) man page." return parser
def cli_main(self,argv): with self: # so the sys.path was modified appropriately # I believe there's no performance hit loading these here when # CLI--it would load everytime anyway. from StringIO import StringIO from calibre.library import db from calibre_plugins.fanficfare_plugin.fanficfare.cli import main as fff_main from calibre_plugins.fanficfare_plugin.prefs import PrefsFacade from calibre.utils.config import prefs as calibre_prefs from optparse import OptionParser parser = OptionParser('%prog --run-plugin '+self.name+' -- [options] <storyurl>') parser.add_option('--library-path', '--with-library', default=None, help=_('Path to the calibre library. Default is to use the path stored in the settings.')) # parser.add_option('--dont-notify-gui', default=False, action='store_true', # help=_('Do not notify the running calibre GUI (if any) that the database has' # ' changed. Use with care, as it can lead to database corruption!')) pargs = [x for x in argv if x.startswith('--with-library') or x.startswith('--library-path') or not x.startswith('-')] opts, args = parser.parse_args(pargs) fff_prefs = PrefsFacade(db(path=opts.library_path, read_only=True)) fff_main(argv[1:], parser=parser, passed_defaultsini=StringIO(get_resources("fanficfare/defaults.ini")), passed_personalini=StringIO(fff_prefs["personal.ini"]))
def main(): set_logger() logger = logging.getLogger('emu_con') parser = OptionParser(description="Emulador de consentrador") parser.add_option("-p", "--port", dest="port", type=int, help="Puerto a conectarse") parser.add_option("-i", "--ip", dest="ip", type=str, help="Ip del concentrador") (options, args) = parser.parse_args(sys.argv) if not options.port: print "Debe especificar el puerto, para mas informacion utilize el parametro -h" sys.exit() if not options.ip: print "Debe especificar la IP del concentrador, para más inforamción utilize el parámetro -h" sys.exit() print options sock = socket.socket() logger.info("Espera coneccion en la ip %s, puerto %d" % (options.ip, options.port)) sock.bind((options.ip, options.port)) sock.listen(1) try: sock_con,(ip_scada,port_scada) = sock.accept() logger.info("\nSe creo la coneccion con el scada en: ip=%s port=%d \n" %(ip_scada,port_scada)) except Exception, e: logger.info("\nNo se pudo conecctar.\n") print e return 0
def main(): usage = "usage: %prog [options] [broker-url]" epilog = """\ The worker needs Filetracker server configured. If no FILETRACKER_URL is present in the environment, a sensible default is generated, using the same host as the Celery broker uses, with default Filetracker port.""" parser = OptionParser(usage=usage, epilog=epilog) parser.disable_interspersed_args() os.environ.setdefault('CELERY_CONFIG_MODULE', 'sio.celery.default_config') app = Celery() cmd = WorkerCommand(app) for x in cmd.get_options(): parser.add_option(x) options, args = parser.parse_args() if len(args) > 1: parser.error("Unexpected arguments: " + ' '.join(args[1:])) if args: broker_url = args[0] os.environ['CELERY_BROKER_URL'] = args[0] if 'FILETRACKER_URL' not in os.environ: default_filetracker_host = None if 'CELERY_BROKER_URL' in os.environ: default_filetracker_host = \ _host_from_url(os.environ['CELERY_BROKER_URL']) if not default_filetracker_host: default_filetracker_host = '127.0.0.1' os.environ['FILETRACKER_URL'] = 'http://%s:%d' \ % (default_filetracker_host, DEFAULT_FILETRACKER_PORT) return cmd.run(**vars(options))
def main(): parser = OptionParser(usage="usage:%prog [options] filepath") parser.add_option("-p", "--port", action="store", type="string", default="", dest="port") (options, args) = parser.parse_args() port = options.port print port if not port: port = utils.config.get("global", "port") debug_mode = int(utils.config.get('global', 'debug')) sys.stderr.write("listen server on port %s ...\n" % port) settings = dict( debug=True if debug_mode else False, cookie_secret="e446976943b4e8442f099fed1f3fea28462d5832f483a0ed9a3d5d3859f==78d", session_secret="3cdcb1f00803b6e78ab50b466a40b9977db396840c28307f428b25e2277f1bcc", session_timeout=600, store_options={ 'redis_host': '127.0.0.1', 'redis_port': 6379, 'redis_pass': '', } ) application = HandlersApplication(handler, **settings) server = tornado.httpserver.HTTPServer(application) server.bind(port) server.start(1 if debug_mode else 15) tornado.ioloop.IOLoop.instance().start()
def make_option_parser(): usage = "%prog [options] <time-untouched> <URIs>" description = ( "Delete all files in a given URI that are older than a specified" " time.\n\nThe time parameter defines the threshold for removing" " files. If the file has not been accessed for *time*, the file is" " removed. The time argument is a number with an optional" " single-character suffix specifying the units: m for minutes, h for" " hours, d for days. If no suffix is specified, time is in hours." ) option_parser = OptionParser(usage=usage, description=description) option_parser.add_option( "-v", "--verbose", dest="verbose", default=False, action="store_true", help="Print more messages" ) option_parser.add_option( "-q", "--quiet", dest="quiet", default=False, action="store_true", help="Report only fatal errors." ) option_parser.add_option( "-c", "--conf-path", dest="conf_path", default=None, help="Path to alternate mrjob.conf file to read from" ) option_parser.add_option( "--no-conf", dest="conf_path", action="store_false", help="Don't load mrjob.conf even if it's available" ) option_parser.add_option( "-t", "--test", dest="test", default=False, action="store_true", help="Don't actually delete any files; just log that we would", ) return option_parser
def testformatter(): parser=OptionParser() parser.add_option('-c', '--color', dest='color',action='store_true') parser.add_option('-t', '--term', dest='term') opts, args = parser.parse_args() termname = opts.term if opts.color and not opts.term: termname = 'xterm-256color' #print termname bgcol = 15 fgcol = curses.COLOR_BLACK formatter = cursespygments.CursesFormatter(usebg=True, defaultbg=-2, defaultfg = -2) lexer = pygments.lexers.get_lexer_by_name('python') def texttoscreen(scr, txt): for text, attr in formatter.formatgenerator(lexer.get_tokens(txt)): scr.addstr(text, attr) #scr.addstr('\n') with safescreen(termname) as scr: formatter.makebackground(scr) for s in list(pygments.styles.get_all_styles()): formatter.style = pygments.styles.get_style_by_name(s) #formatter.setup_styles() texttoscreen(scr, s) texttoscreen(scr, 'def g(x=3+4, y = "abcd"): pass') formatter.updatewindow(scr) if scr.getch() == ord('q'): break
def parse_args(): parser = OptionParser() parser.set_usage("rhn-custom-info [options] key1 value1 key2 value2 ...") parser.add_option("-u", "--username", action="store", type="string", dest="username", help="your RHN username", metavar="RHN_LOGIN") parser.add_option("-p", "--password", action="store", type="string", dest="password", help="your RHN password", metavar="RHN_PASSWD") parser.add_option("-s", "--server-url", action="store", type="string", dest="url", help="use the rhn api at URL", metavar="URL") parser.add_option("-d", "--delete-values", action="store_true", dest="delete_values", default=0, help="delete one or multiple custom keys from the system") parser.add_option("-l", "--list-values", action="store_true", dest="list_values", default=0, help="list the custom keys and values for the system", ) return parser.parse_args()
def main(args): parser = OptionParser() parser.add_option("-p", "--port", dest="port") parser.add_option("--debug", dest="debug", default=False) (options, args) = parser.parse_args(args) app.run(debug=options.debug, host="0.0.0.0", port=int(options.port))
def __init__(self): gr.top_block.__init__(self) usage = "%prog: [options] filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-N", "--samples", type="eng_float", default=None, help="number of samples to record") (options, args) = parser.parse_args () if len(args) != 1 or options.samples is None: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl) src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl) head0 = blocks.head(gr.sizeof_float, int(options.samples)) head1 = blocks.head(gr.sizeof_float, int(options.samples)) dst = blocks.wavfile_sink(args[0], 2, int(options.sample_rate), 16) self.connect(src0, head0, (dst, 0)) self.connect(src1, head1, (dst, 1))
self.yang_file suite = unittest.TestSuite() suite.addTest(PyGenTest(profile, actual_directory, expected_directory, groupings_as_class)) return suite if __name__ == "__main__": parser = OptionParser(usage="usage: %prog [options]", version="%prog 0.3.0") parser.add_option("--profile", type=str, dest="profile", help="Take options from a profile file, any CLI targets ignored") parser.add_option("--actual-directory", type=str, dest="actual_directory", help="The actual directory where the sdk will get created.") parser.add_option("--expected-directory", type=str, dest="expected_directory", help="The expected directory whose contents will be compared to the actual directory.") parser.add_option("-v", "--verbose", action="store_true",
def create_parser(): commands = 'Commands: ' + ', '.join(COMMANDS) parser = OptionParser(prog='launcher', usage='usage: %prog [options] command', description=commands) parser.add_option('-v', '--verbose', action='store_true', default=False, help='Run verbosely') parser.add_option('--launcher-config', metavar='FILE', help='Defaults to INSTALL_PATH/bin/launcher.properties') parser.add_option('--node-config', metavar='FILE', help='Defaults to INSTALL_PATH/etc/node.properties') parser.add_option('--jvm-config', metavar='FILE', help='Defaults to INSTALL_PATH/etc/jvm.config') parser.add_option('--config', metavar='FILE', help='Defaults to INSTALL_PATH/etc/config.properties') parser.add_option('--log-levels-file', metavar='FILE', help='Defaults to INSTALL_PATH/etc/log.properties') parser.add_option('--data-dir', metavar='DIR', help='Defaults to INSTALL_PATH') parser.add_option('--pid-file', metavar='FILE', help='Defaults to DATA_DIR/var/run/launcher.pid') parser.add_option( '--launcher-log-file', metavar='FILE', help='Defaults to DATA_DIR/var/log/launcher.log (only in daemon mode)') parser.add_option( '--server-log-file', metavar='FILE', help='Defaults to DATA_DIR/var/log/server.log (only in daemon mode)') parser.add_option('-D', action='append', metavar='NAME=VALUE', dest='properties', help='Set a Java system property') return parser
#! /Volumes/projects/venvs/newa/bin/python import numpy as N from newa.factory import ObsnetDataFactory from newa.database.index import getDictTemplate # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # from optparse import OptionParser parser = OptionParser() parser.add_option('-d', action='store', type='string', dest='dataset_names', default=None) parser.add_option('-w', action='store', type='string', dest='working_dir', default=None) parser.add_option('-y', action='store_true', dest='test_run', default=False) parser.add_option('-z', action='store_true', dest='debug', default=False) options, args = parser.parse_args() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # factory = ObsnetDataFactory(options) manager = factory.getFileManager('index', 'r') dataset_name = args[0]
def get_options(): global options usage = '%s\n\t-R remote-cmd -H ip-file -P process-num -T timeout' % sys.argv[ 0] usage += '\n\t-S local-file -D remote-dir -H ip-file -P process-num -T timeout' usage += '\n\t-L local-cmd -H ip-file -P process-num -T timeout' usage += '\nThe pattern "IIPP" in options "RSDL" will be replaced by the ip contained in each process.' usage += '\nThe result file is /tmp/agent_result.csv' parser = OptionParser(usage) parser.add_option('-R', '--remote_cmd', action='store', help='Run a shell command in remote servers.') parser.add_option('-S', '--src_file', action='store', help='specify the file to remote servers.') parser.add_option('-D', '--dst_path', action='store', help='specify the path in remote servers.') parser.add_option('-L', '--local_cmd', action='store', help='Run a shell command in localhost.') parser.add_option('-H', '--host', action='store', default='/dev/stdin', help='Specify the file contains ip.') parser.add_option('-P', '--process', action='store', default=cpu_count(), type='int', help='Specify the num of processes.') parser.add_option('-T', '--timeout', action='store', default=0, type='int', help='Specify the seconds of timeout.') options, args = parser.parse_args() for opt in [options.src_file, options.dst_path, options.local_cmd]: if options.remote_cmd and opt: parser.print_help() sys.exit(1) for opt in [options.src_file, options.dst_path]: if options.local_cmd and opt: parser.print_help() sys.exit(1) if options.src_file and not options.dst_path or options.dst_path and not options.src_file: parser.print_help() sys.exit(1) if not options.remote_cmd and not options.src_file and not options.local_cmd: parser.print_help() sys.exit(1) return
import numpy as np from datetime import datetime, timedelta import os, time, sys, glob, copy import json from optparse import OptionParser # --- Subroutine(s) import eval_measures as metrics parser = OptionParser() # Switch : fetching obs metrics or corresponding parameters / best runs ? # 0 = metrics + par # 1 = classify best runs using CDF and metrics # 2 = best runs + uncertainty parser.add_option("--switch",dest="switch",metavar="SWITCH") parser.add_option("--nbest",dest="nbest",metavar="NBEST") parser.add_option("--metric",dest="metric",metavar="metric") parser.add_option("--swpar",dest="swpar",metavar="SWPAR") parser.add_option("--swsim",dest="swsim",metavar="SWSIM") parser.add_option("--ext",dest="ext",metavar="EXT") (options, args) = parser.parse_args() switch = int(options.switch) MCname = copy.copy(options.ext) if switch > 0: nbest = int(options.nbest) namemet = copy.copy(options.metric) if switch == 2:
return # It's either pinned, on no workspaces, or there is no match win.move_to_workspace(target) #} if __name__ == '__main__': from optparse import OptionParser, OptionGroup parser = OptionParser(usage="%prog [options] [action] ...", version="%%prog v%s" % __version__) parser.add_option( '-d', '--daemonize', action="store_true", dest="daemonize", default=False, help="Attempt to set up global " "keybindings using python-xlib and a D-Bus service using dbus-python. " "Exit if neither succeeds") parser.add_option('-b', '--bindkeys', action="store_true", dest="daemonize", default=False, help="Deprecated alias for --daemonize") parser.add_option('--debug', action="store_true", dest="debug", default=False, help="Display debug messages")
#!/bin/python from optparse import OptionParser ... parser = OptionParser() parser.add_option('-i', '--infile', dest='infile', help='Input file name') parser.add_option('-o', '--outfile', dest='outfile', help='Output file') (options, args) = parser.parse_args() import numpy as np S = np.load(options.infile) np.savetxt(options.outfile, S, delimiter=',')
if opts.print_col != None: s = set() print "Column: " + opts.print_col + ": " for k in o.keys(): s = s.union(set([o[k][opts.print_col]])) for r in s: print " " + r return None if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-a", "--map", dest="map", default=None, help="Map file.") parser.add_option("-b", "--print_meta", dest="print_meta", action="store_true", help="Print available metadata. ") parser.add_option("-c", "--print_ids", dest="print_ids", action="store_true", help="Print sample IDs.") parser.add_option("-d", "--print_col", dest="print_col",
XMFfile.write(' </Grid>'+"\n") XMFfile.write(' </Grid>'+"\n") XMFfile.write(' </Domain>'+"\n") XMFfile.write(' </Xdmf>'+"\n") XMFfile.close() if __name__ == '__main__': from optparse import OptionParser usage = "" parser = OptionParser(usage=usage) parser.add_option("-n","--size", help="number of processors for run", action="store", type="int", dest="size", default=1) parser.add_option("-s","--stride", help="stride for solution output", action="store", type="int", dest="stride", default=0) parser.add_option("-t","--finaltime", help="finaltime", action="store", type="int", dest="finaltime",
import sys from optparse import OptionParser # Get all the root classes from ROOT import * from math import * gROOT.ProcessLine(".x functions.C") # - M A I N ---------------------------------------------------------------------------------------- # Usage: ./cutflow.py -f ROOTFILE -n NUMBEROFEVENTS # Prepare the command line parser parser = OptionParser() parser.add_option("-f", "--file", dest="input_file", default='NeroNtuple.root', help="input root file [default: %default]") parser.add_option("-t", "--treename", dest="input_tree", default='events', help="root tree name [default: %default]") parser.add_option("-n", "--nprocs", dest="nprocs", type="int", default=10, help="number of processed entries [default: %default]") (options, args) = parser.parse_args()
raise exit() def exit_clean(): try: c.disconnect_all() except: pass exit() if __name__ == '__main__': from optparse import OptionParser p = OptionParser() p.set_usage('%prog [options] [CUSTOM_CONFIG_FILE]') p.set_description(__doc__) p.add_option('-r', '--n_retries', dest='n_retries', type='int', default=40, help='Number of times to try after an error before giving up. Default: 40') p.add_option('-p', '--skip_prog', dest='prog_fpga',action='store_false', default=True, help='Skip FPGA programming (assumes already programmed). Default: program the FPGAs') p.add_option('-e', '--skip_eq', dest='prog_eq',action='store_false', default=True, help='Skip configuration of the equaliser in the F engines. Default: set the EQ according to config file.') p.add_option('-c', '--skip_core_init', dest='prog_10gbe_cores',action='store_false', default=True, help='Skip configuring the 10GbE cores (ie starting tgtap drivers). Default: start all drivers') p.add_option('-o', '--start_output', dest='start_output',action='store_false', default=True, help='Begin outputting packetised data immediately. Default: Do not start the output.') p.add_option('-k', '--clk_chk', dest='clk_chk',action='store_false', default=True, help='Skip the F engine clock checks.') p.add_option('-v', '--verbose', dest='verbose',action='store_true', default=False, help='Be verbose about errors.') p.add_option('-s', '--spead', dest='spead',action='store_false', default=True, help='Do not send SPEAD metadata and data descriptor packets. Default: send all SPEAD info.') p.add_option('', '--prog_timeout', dest = 'prog_timeout_s', type = 'int', default = 2,
def do_main(ini, file_json, sql): uadb = UaDb.from_file(ini) rt = uadb.fetchall(sql, []) rs = rt.rows # print(rs) # js = {"rows": rs} s = json.dumps(rs, indent=4) with open(file_json, "w+") as f: f.write(s) os.chmod(file_json, 0o666) if __name__ == "__main__": parser = OptionParser() parser.add_option("-i", "--ini") parser.add_option("-j", "--json") parser.add_option("-t", "--table") parser.add_option("-s", "--sql") parser.add_option("-f", "--filesql") try: opts, args = parser.parse_args() except Exception: opts = None if opts is None or opts.json is None or opts.ini is None: print( "-i <db.ini> -j <file.json> [ -t <table> | -s <\"sql\"> | -f < file.sql>] " ) sys.exit(0) if opts.sql is not None: sql = opts.sql
def main(): usage = "python %prog >.< " description = """>.<""" optparser = OptionParser(version="%prog 1",description=description,usage=usage,add_help_option=False) optparser.add_option("-h","--help",action="help",help="Show this help message and exit.") #========major options============= optparser.add_option("-i","--interval",dest="interval",type="str", help="if raw , -i is 5 column summit200bp file") optparser.add_option("-t","--train",dest="train",type="str", help="10 top peaks for add weight") optparser.add_option("-o","--output",dest="output",type="str", help="") optparser.add_option("--w1",dest="w_plus",type="str",default = "/mnt/Storage2/home/huse/ATAC/Data/ATAC/Bam/GM12878_ATACseq_50k_p.bw", help="") optparser.add_option("--w2",dest="w_minus",type="str",default = "/mnt/Storage2/home/huse/ATAC/Data/ATAC/Bam/GM12878_ATACseq_50k_m.bw", help="") optparser.add_option("-b","--bg",dest="bgmatrix",type="str",default = "/mnt/Storage2/home/huse/ATAC/Data/ATAC/biasoffset/up4down4/GM12878_ATACseq_50k_bias_onPeak_u4d4s0_newcode.txt", help="sequence bias matrix at shift 0") # optparser.add_option("--bg2",dest="bgmatrix2",type="str",default = "/mnt/Storage2/home/huse/ATAC/Data/ATAC/biasoffset/up3down3/GM12878_ATACseq_50k_bias_onPeak_u3d3s2_newcode.txt", # help="sequence bias matrix at shift 2") #========minor options============= optparser.add_option("--Cspan",dest="Cspan",type="int",default = 25, help="region for get total signal in single bp, default = 25 means +-25bp(total 50bp) signal as total for each bp") optparser.add_option("--genome",dest="genome",type="str",default = "/mnt/Storage/home/huse/Data/Genome/hg19/hg19.2bit", help="2bit format") optparser.add_option("--left",dest="leftflank",type="int",default = 4, help="flnaking region for seqbias , 8-mer means left=right=4") optparser.add_option("--right",dest="rightflank",type="int",default = 4, help="flnaking region for seqbias , 8-mer means left=right=4") optparser.add_option("--offset",dest="offset",type="int",default = 9, help="offset related, distance of pair of +/- related cut,default = 9") optparser.add_option("--bpshift",dest="bpshift",type="int",default = 0, help="bp of shift center when calculate bias for given cut site,default is 0 ") (options,args) = optparser.parse_args() if not options.interval: optparser.print_help() sys.exit(1) interval = options.interval train = options.train out_bed = options.output w_plus = options.w_plus w_minus = options.w_minus bgmatrix = options.bgmatrix gen = options.genome lflank = options.leftflank rflank = options.rightflank Cspan = options.Cspan offset = options.offset wgt = weight(train,w_plus,w_minus,bgmatrix,Cspan,gen,lflank,rflank,offset,options.bpshift) sitepro_scan(interval,out_bed,w_plus,w_minus,bgmatrix,Cspan,gen,lflank,rflank,offset,options.bpshift,wgt)
exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0] sys.path.insert(0, os.path.abspath(os.path.join(exe_path, "..", ".."))) if __name__ == '__main__': module_name = os.path.split(sys.argv[0])[1] module_name = os.path.splitext(module_name)[0] else: module_name = __name__ import ruffus print(ruffus.__version__) parser = OptionParser(version="%%prog v1.0, ruffus v%s" % ruffus.ruffus_version.__version) parser.add_option("-t", "--target_tasks", dest="target_tasks", action="append", default=list(), metavar="JOBNAME", type="string", help="Target task(s) of pipeline.") parser.add_option( "-f", "--forced_tasks", dest="forced_tasks", action="append", default=list(), metavar="JOBNAME", type="string", help="Pipeline task(s) which will be included even if they are up to date." ) parser.add_option( "-j",
print("Final Recall of Lemmas :"+str(tot/nf))''' def setArgs(_tag, _pc): global proc_count, tag tag = _tag proc_count = _pc print('Tag, ProcCount: {}, {}'.format(tag, proc_count)) if __name__ == '__main__': #print('Number of arguments:', len(sys.argv), 'arguments.') #print('Argument List:', str(sys.argv)) parser = OptionParser() parser.add_option("-t", "--tag", dest="tag", help="Tag for feature set to use", metavar="TAG") parser.add_option("-p", "--procs", dest="proc_count", default = 4, help="Number of child process", metavar="PROCS") (options, args) = parser.parse_args() options = vars(options) _tag = options['tag'] if _tag is None: raise Exception('None is tag') pc = int(options['proc_count']) setArgs(_tag, pc) for i in range(6): with open(str(tag)+"result_sasi"+str(i)+".csv","w") as f: rd = csv.writer(f) rd.writerow(["Recall","Recall_word","Precision","Precision_word"])
import numpy as np import sys import pickle from optparse import OptionParser import time from keras_frcnn import config from keras import backend as K from keras.layers import Input from keras.models import Model from keras_frcnn import roi_helpers sys.setrecursionlimit(40000) parser = OptionParser() parser.add_option("-p", "--path", dest="test_path", help="Path to test data.") parser.add_option("-n", "--num_rois", type="int", dest="num_rois", help="Number of ROIs per iteration. Higher means more memory use.", default=32) parser.add_option("--config_filename", dest="config_filename", help= "Location to read the metadata related to the training (generated when training).", default="config.pickle") parser.add_option("--network", dest="network", help="Base network to use. Supports vgg or resnet50.", default='resnet50') (options, args) = parser.parse_args() if not options.test_path: # if filename is not given parser.error('Error: path to test data must be specified. Pass --path to command line') config_output_filename = options.config_filename
def main(): # argument processing usage = "usage: %prog [options]\n\n" + \ "Called standalone, will send one CAN VerifyNode (Global) " + \ "message.\n\n" + \ "Expect a single VerifiedNode reply in return\n" + \ " e.g. [180B7sss] nn nn nn nn nn nn\n" + \ "containing dest alias and NodeID\n\n" + \ "valid usages (default values):\n" + \ " ./verifyNodeGlobal.py\n" + \ " ./verifyNodeGlobal.py -a 0xAAA\n" + \ " ./verifyNodeGlobal.py -a 0xAAA " + \ "-n 0x2 0x1 0x99 0xff 0x00 0x1e\n\n" + \ "Default connection detail taken from connection.py" parser = OptionParser(usage=usage) parser.add_option("-a", "--alias", dest="alias", metavar="ALIAS", default=connection.thisNodeAlias, type=int, help="source alias") parser.add_option("-n", "--node", dest="nodeid", metavar="0x1 0x2 0x3 0x4 0x5 0x6", default=connection.testNodeID, type=int, nargs=6, help="destination Node ID") parser.add_option("-t", "--auto", action="store_true", dest="identifynode", default=False, help="find destination NodeID automatically") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="print verbose debug information") parser.add_option("-V", "--veryverbose", action="store_true", dest="veryverbose", default=False, help="print very verbose debug information") (options, args) = parser.parse_args() if options.veryverbose: connection.network.verbose = True ''' @todo identifynode option not currently implemented ''' #if identifynode : # import getUnderTestAlias # dest, nodeID = getUnderTestAlias.get(alias, None, verbose) # if nodeID == None : nodeID = otherNodeId # now execute retval = test(options.alias, options.nodeid, connection) connection.network.close() exit(retval)
n_regions = len(data_list) covar_array = numpy.zeros((n_bins, n_bins)) mean_wtheta = MeanWtheta(data_list) for data in data_list: for i in xrange(n_bins): for j in xrange(n_bins): covar_array[i, j] += ((n_regions - 1.0) / (n_regions))**2 * ( (data[i, 1] - mean_wtheta[i]) * (data[j, 1] - mean_wtheta[j])) return covar_array parser = OptionParser() parser.add_option("--input_tag", dest="input_tag", default="", action="store", type="str", help="Wtheta_tag to load") parser.add_option("--output_tag", dest="output_tag", default="", action="store", type="str", help="Name appended to output file") (options, args) = parser.parse_args() file_name_list = numpy.sort(glob("Wtheta_F?p??_" + options.input_tag)).tolist() print "# of Files:", len(file_name_list) data_list = [] for i in xrange(len(file_name_list)): gal_gal = numpy.zeros(14)
import ROOT import os from optparse import OptionParser parser=OptionParser() parser.add_option("-r","--input_dir",dest="input_dir",default="null",type="str") (options,args)=parser.parse_args() def main(): f_out = ROOT.TFile("hist_ttbar.root","RECREATE") input_root_list = [] for root_file in os.listdir(options.input_dir): if not ".root" in root_file:continue tmp_root_file = ROOT.TFile(os.path.join(options.input_dir,root_file)) for path in hist_dic: tmp_h1 = tmp_root_file.Get("%s"%(hist_dic[path].name)) #tmp_h1.Sumw2() hist_dic[path].h1.Add(hist_dic[path].h1, tmp_h1, 1, 1) tmp_root_file.Close() f_out.cd() for path in hist_dic: hist_dic[path].h1.Write() f_out.Close() main()
model = AAFModel(root) self.setModel(model) self.setWindowTitle(file_path) self.expandToDepth(1) self.resizeColumnToContents(0) self.resizeColumnToContents(1) if __name__ == "__main__": from PySide2 import QtWidgets from optparse import OptionParser parser = OptionParser() parser.add_option('-t','--toplevel',action="store_true", default=False) parser.add_option('-c','--compmobs',action="store_true", default=False) parser.add_option('-m','--mastermobs',action="store_true", default=False) parser.add_option('-s','--sourcemobs',action="store_true", default=False) parser.add_option('-d','--dictionary',action="store_true", default=False) parser.add_option('--metadict',action="store_true", default=False) parser.add_option('-r','--root',action="store_true", default=False) (options, args) = parser.parse_args() if not args: parser.error("not enough arguments") file_path = args[0] app = QtWidgets.QApplication(sys.argv)
import sys import copy from array import * from optparse import OptionParser import WprimetoVlq_Functions from WprimetoVlq_Functions import * gROOT.Macro("rootlogon.C") gROOT.LoadMacro("insertlogo.C+") parser = OptionParser() parser.add_option('-s', '--set', metavar='F', type='string', action='store', default='ttbarfulltuple', dest='set', help='data or QCD') (options, args) = parser.parse_args() leg = TLegend(0.5, 0.5, 0.84, 0.84) leg.SetFillColor(0) leg.SetBorderSize(0) ROOT.gROOT.Macro("rootlogon.C") fdata = ROOT.TFile("Pileup_2016_69200mb.root") fdataup = ROOT.TFile("Pileup_2016_72383mb.root") fdatadown = ROOT.TFile("Pileup_2016_66017mb.root")
def main(): from optparse import OptionParser parser = OptionParser( usage= "usage: %prog [-v] [--prefix PREFIX] [--no-exclude] [--force-submodules]" " [--extra EXTRA1 [EXTRA2]] [--dry-run] OUTPUT_FILE", version="%prog {0}".format(__version__)) parser.add_option('--prefix', type='string', dest='prefix', default=None, help="""prepend PREFIX to each filename in the archive. OUTPUT_FILE name is used by default to avoid tarbomb. You can set it to '' in order to explicitly request tarbomb""" ) parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='enable verbose mode') parser.add_option( '--no-exclude', action='store_false', dest='exclude', default=True, help= "don't read .gitattributes files for patterns containing export-ignore attrib" ) parser.add_option( '--force-submodules', action='store_true', dest='force_sub', help= 'force a git submodule init && git submodule update at each level before iterating submodules' ) parser.add_option('--extra', action='append', dest='extra', default=[], help="any additional files to include in the archive") parser.add_option( '--dry-run', action='store_true', dest='dry_run', help="don't actually archive anything, just show what would be done") options, args = parser.parse_args() if len(args) != 1: parser.error("You must specify exactly one output file") output_file_path = args[0] if path.isdir(output_file_path): parser.error("You cannot use directory as output") # avoid tarbomb if options.prefix is not None: options.prefix = path.join(options.prefix, '') else: import re output_name = path.basename(output_file_path) output_name = re.sub( '(\.zip|\.tar|\.tgz|\.txz|\.gz|\.bz2|\.xz|\.tar\.gz|\.tar\.bz2|\.tar\.xz)$', '', output_name) or "Archive" options.prefix = path.join(output_name, '') try: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('%(message)s')) GitArchiver.LOG.addHandler(handler) GitArchiver.LOG.setLevel( logging.DEBUG if options.verbose else logging.INFO) archiver = GitArchiver(options.prefix, options.exclude, options.force_sub, options.extra) archiver.create(output_file_path, options.dry_run) except Exception as e: parser.exit(2, "{0}\n".format(e)) sys.exit(0)
H.Scale(fRenorm) #print H , H.GetTitle() fOut.cd() H.Write() fIn.Close() fOut.Close() os.system('rm '+TargetCard) dcOut.write(TargetCard) # ------------------------------------------------------- MAIN -------------------------------------------- parser = OptionParser(usage="usage: %prog [options]") parser.add_option("-v", "--version", dest="Version", help="Datacards version" , default=DefaultVersion , type='string' ) parser.add_option("-c", "--channel", dest="channels", help="channel set to scale", default=[], type='string' , action='callback' , callback=combTools.list_maker('channels',',')) parser.add_option("-P", "--purpose", dest="purpose", help="purpose of the datacard (couplings, searches, mass, ...)", default="smhiggs", metavar="PATTERN") parser.add_option("-e", "--energy", dest="energy", help="energy (7,8,0=all)", type="int", default=0, metavar="SQRT(S)") parser.add_option("-m", "--masses", dest="masses", help="Run only these mass points", default=[] , type='string' , action='callback' , callback=combTools.list_maker('masses',',',float)) parser.add_option("-T", "--Type" , dest="Type" , help="Extrapolation Type (Mass,13TeV)" , default="PDFSplit" , type='string' ) parser.add_option("-d", "--dictionary", dest="Dictionary", help="Datacards Dictionary", default='Configs.HWW2012' , type='string' ) parser.add_option("-r", "--renameSyst", dest="renameSyst", help="Rename systematics" , default=[] , type='string' , action='callback' , callback=combTools.list_maker('renameSyst',',')) (options, args) = parser.parse_args() # Read Combination python config exec('from %s import *'%(options.Dictionary)) if options.Version == 'None' : options.Version=DefaultVersion
playlists = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["videoId"])) elif search_result["id"]["kind"] == "youtube#channel": channels.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["channelId"])) elif search_result["id"]["kind"] == "youtube#playlist": playlists.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["playlistId"])) print "Videos:\n", "\n".join(videos), "\n" print "Channels:\n", "\n".join(channels), "\n" print "Playlists:\n", "\n".join(playlists), "\n" if __name__ == "__main__": parser = OptionParser() parser.add_option("--q", dest="q", help="Search term", default="Anna Kendrick") parser.add_option("--max-results", dest="maxResults", help="Max results", default=25) (options, args) = parser.parse_args() youtube_search(options)
def PrintDatabase(Results): for key in Results: print str(key) + ":" print Results[key] if __name__ == "__main__": parser = OptionParser( usage= " %prog [options] dir1 dir2 ...\nProvide help to run/submit/resubmit crab jobs" ) parser.add_option("-l", "--loop", help="Run in loop", dest="loop", default=False, action='store_true') parser.add_option("-n", "--dryrun", help="Dry Run: Print command instead of re/submit", dest="dryrun", default=False, action='store_true') parser.add_option("-s", "--submit", help="Submit jobs", dest='submit', default=False, action='store_true') parser.add_option(
""" return state_table.get(proc.returncode, "error") def run_command(command_str): proc = subprocess.Popen(command_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) proc.wait() return proc def command_name(command_array): command = command_array[0] return os.path.basename(command) if __name__ == "__main__": parser = OptionParser() parser.add_option("--riemann-host", default="localhost", help="The address of Riemann") parser.add_option("--riemann-port", default=5555, help="The port Riemann is running on") parser.add_option("--tags", default=None, help="Optional tags for the event") parser.add_option("--ttl", default=None, help="An optional TTL for the event (in seconds)") parser.add_option("--states", default="ok:0", help="Describes a mapping of return codes and event states. e.g. ok:0,1|warn:2,3. Return codes without an explicit mapping are assumed error. default=ok:0") parser.add_option("--service", default=None, help="An optional service to the event. Defaults to the basename of the command that's run") parser.add_option("--debug", default=False, action='store_true', help="Output the event before it's sent to Riemann.") parser.add_option("--metric-from-stdout", default=False, action='store_true', help="Use stdout as the metric rather than the elapsed command walltime.") parser.add_option("--state-from-stdout", default=False, action='store_true', help="Use stdout as the state rather than the elapsed command walltime.") parser.add_option("--tcp", default=False, action='store_true', help="Use TCP transport instead of UDP.") parser.add_option("--host", default=None, help="Specify hostname.") parser.add_option("--omit-metric", default=False, action='store_true', help="Do not send the metric.") parser.add_option("--attributes", default=None, help="Comma separated list of key=value attribute pairs. e.g. foo=bar,biz=baz") options, command = parser.parse_args() if not command:
Pair.area : the area of the smallest repeat unit of the interface """ self.material1 = material1 self.material2 = material2 self.surface1 = surface1 self.surface2 = surface2 self.multiplicity1 = multiplicity1 self.multiplicity2 = multiplicity2 self.strains = strains self.max_vector = max_vector self.area = area #parser = argparse.ArgumentParser() parser = OptionParser() parser.add_option("-a", "--matera", action="store", type="string", dest="mater1", default="material.cif", help="The first material. Default material.cif") parser.add_option("-b", "--materb", action="store", type="string", dest="mater2", default="material-b.cif", help="The second material. Default material-b.cif") parser.add_option("-s", "--strain", action="store", type="float", dest="strain", default="0.04", help="Maximum strain between the interfaces. Default 0.04") parser.add_option("-l", "--limit", action="store", type="int", dest="limit", default=5, help="Maximum number of supercell expansions for each interface. Default 5") parser.add_option("-v", action="store_true", dest="verbose") #parser.add_option("-v", "--verbose", dest="verbose", type='bool', default=True, help="increase output verbosity") #parser.add_argument("--print_strains", help="increase output verbosity of strian output") (options, args) = parser.parse_args()
else: self.moves[s] = self.second self.g.add_edge(Node(u), Node(s)) if len(s) == self.n: self.g.add_leaf(Node(s)) i += 1 self._assign_values() if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-n", "--nmoves", dest="n", help="number of moves") parser.add_option("-f", "--first", dest="first", help="first player") parser.add_option("-s", "--second", dest="second", help="second player") parser.add_option("-b", "--base", dest="base", help="base of sequence digits") parser.add_option("-r", "--report", dest="report", help="generate report data") (options, args) = parser.parse_args() n = int(options.n) first = options.first second = options.second base = int(options.base) report = bool(options.report) g = Graph() # Create sequence graph
#Logging logger = logging.getLogger(SCRIPT) logger.setLevel(logging.INFO) hdlr = logging.FileHandler(LOG_FILE) hdlr.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(name)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) #Initial RDS API client = boto3.client('rds', region_name='ap-southeast-2') #Arguments parser = OptionParser() parser.add_option("-s", dest="SOURCE_DB", help="Source DB Identifier", action="store") parser.add_option("-k", "--key", dest="KEY_WORD", help="Key word of backups", action="store") (options, args) = parser.parse_args() all_snapshots_rsp = client.describe_db_snapshots( DBInstanceIdentifier=options.SOURCE_DB, SnapshotType='manual', MaxRecords=20 ) logger.info( "-s %s -k %s starting..." % ( options.SOURCE_DB, options.KEY_WORD ) ) filtered_snapshots = [] #loop over response and append SnapshotCreateTime and DBSnapshotIdentifier to a list for all_snapshots_key, all_snapshots_value in all_snapshots_rsp.items(): if all_snapshots_key == 'DBSnapshots':
return channel.COMPLETE def test(): return execute() parser = OptionParser( usage="%prog <options>\nCompute time needed to perform BLAS gemm " "computations between matrices of size (M, N) and (N, K)." ) parser.add_option( "-q", "--quiet", action="store_true", dest="quiet", default=False, help="If true, do not print the comparison table and config " "options", ) parser.add_option( "--print_only", action="store_true", dest="print_only", default=False, help="If true, do not perform gemm computations", ) parser.add_option( "-M", "--M", action="store", dest="M",