%prog pasa pasa_db fastafile

    Run EVM in TIGR-only mode.
175312
def pasa(args):
    
    p = OptionParser(pasa.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    pasa_db, fastafile = args

    termexons = "pasa.terminal_exons.gff3"
    if need_update(fastafile, termexons):
        cmd = "$ANNOT_DEVEL/PASA2/scripts/pasa_asmbls_to_training_set.dbi"
        cmd += ' -M "{0}:mysql.tigr.org" -p "access:access"'.format(pasa_db)
        cmd += ' -g {0}'.format(fastafile)
        sh(cmd)

        cmd = "$EVM/PasaUtils/retrieve_terminal_CDS_exons.pl"
        cmd += " trainingSetCandidates.fasta trainingSetCandidates.gff"
        sh(cmd, outfile=termexons)

    return termexons
59222
def _run():
    """"""
    args = parse_args()

    # register signal handler
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    # set up logging
    log_formatter = logging.Formatter("%(asctime)s %(filename)s(line %(lineno)d) "
                                      "%(levelname)s: %(message)s")
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    # add file handler if specified
    if args.log_file:
        file_handler = logging.FileHandler(args.log_file)
        file_handler.setFormatter(log_formatter)
        root_logger.addHandler(file_handler)

    # check vm_num and vm_index value
    if args.vm_num < 1:
        print "vm_num value cannot be negative!"
        return
    if args.vm_index < 1 or args.vm_index > args.vm_num:
        print "vm_index value cannot be negative or greater than vm_num!"
        return

    if args.create_conf_dir:
        if args.create_HMA:
            hma_dir = return_abs_path(args.create_conf_dir, 'vpns')
            hma.create_config_files(hma_dir)
        elif args.create_IPVANISH:
            ipvanish_dir = return_abs_path(args.create_conf_dir, 'vpns')
            ipvanish.create_config_files(ipvanish_dir)
        elif args.create_PUREVPN:
            purevpn_dir = return_abs_path(args.create_conf_dir, 'vpns')
            purevpn.create_config_files(purevpn_dir)
        elif args.create_VPNGATE:
            vpngate_dir = return_abs_path(args.create_conf_dir, 'vpns')
            vpngate.create_config_files(vpngate_dir)
        # create the config files for the openvpn config files
        create_config_files(args.create_conf_dir)
    else:
        # sanity check tls_auth and key_direction
        if (args.tls_auth is not None and args.key_direction is None) or \
                (args.tls_auth is None and args.key_direction is not None):
            logging.error("tls_auth and key_direction must be specified "
                          "together!")
            return

        scan_vpns(directory=args.directory, auth_file=args.auth_file,
                  crt_file=args.crt_file, tls_auth=args.tls_auth,
                  key_direction=args.key_direction, exclude_list=args.exclude_list,
                  shuffle_lists=args.shuffle_lists, vm_num=args.vm_num,
                  vm_index=args.vm_index, reduce_vp=args.reduce_vp)
949879
def main(argv):
    """"""
    del argv
    engine = make_gtp_instance(FLAGS.load_file,
                               cgos_mode=FLAGS.cgos_mode,
                               kgs_mode=FLAGS.kgs_mode,
                               minigui_mode=FLAGS.minigui_mode)
    dbg("GTP engine ready\n")
    for msg in sys.stdin:
        if not engine.handle_msg(msg.strip()):
            break
218578
def main(args=None, prog=None):
    """"""
    args = args if args is not None else sys.argv[1:]
    prog = prog if prog is not None else sys.argv[0]
    # Prevent broken pipe exception from being raised.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
    p = argparse.ArgumentParser(prog=prog)
    p.add_argument('-o', '--output', metavar='PATH',
                   type=argparse.FileType('w'), default=sys.stdout,
                   help='Write output to PATH')
    p.add_argument('--api', help='Match API', default=None)
    p.add_argument('--profile', help='Match profile', default=None)
    p.add_argument('--support', default=None,
                   help='Match extension support string')
    g = p.add_mutually_exclusive_group()
    g.add_argument('--list-apis', action='store_true', dest='list_apis',
                   help='List apis in registry', default=False)
    g.add_argument('--list-profiles', action='store_true', default=False,
                   dest='list_profiles', help='List profiles in registry')
    g.add_argument('--list-supports', action='store_true',
                   dest='list_supports', default=False,
                   help='List extension support strings')
    p.add_argument('registry', type=argparse.FileType('rb'), nargs='?',
                   default=stdin, help='Registry path')
    args = p.parse_args(args)
    o = args.output
    try:
        registry = load(args.registry)
        if args.list_apis:
            for x in sorted(registry.get_apis()):
                print(x, file=o)
            return 0
        elif args.list_profiles:
            for x in sorted(registry.get_profiles()):
                print(x, file=o)
            return 0
        elif args.list_supports:
            for x in sorted(registry.get_supports()):
                print(x, file=o)
            return 0
        apis = group_apis(registry, None, None, args.api, args.profile,
                          args.support)
        for api in apis:
            print('#ifndef', api.name, file=o)
            print('#define', api.name, file=o)
            print(api.text, file=o)
            print('#endif', file=o)
            print('', file=o)
    except:
        e = sys.exc_info()[1]
        print(prog, ': error: ', e, sep='', file=sys.stderr)
        return 1
    return 0
973393
def _run_cortex(fastq, indexes, params, out_base, dirs, config):
    
    print(out_base)
    fastaq_index = "{0}.fastaq_index".format(out_base)
    se_fastq_index = "{0}.se_fastq".format(out_base)
    pe_fastq_index = "{0}.pe_fastq".format(out_base)
    reffasta_index = "{0}.list_ref_fasta".format(out_base)
    with open(se_fastq_index, "w") as out_handle:
        out_handle.write(fastq + "\n")
    with open(pe_fastq_index, "w") as out_handle:
        out_handle.write("")
    with open(fastaq_index, "w") as out_handle:
        out_handle.write("{0}\t{1}\t{2}\t{2}\n".format(params["sample"], se_fastq_index,
                                                       pe_fastq_index))
    with open(reffasta_index, "w") as out_handle:
        for x in indexes["fasta"]:
            out_handle.write(x + "\n")
    os.environ["PERL5LIB"] = "{0}:{1}:{2}".format(
        os.path.join(dirs["cortex"], "scripts/calling"),
        os.path.join(dirs["cortex"], "scripts/analyse_variants/bioinf-perl/lib"),
        os.environ.get("PERL5LIB", ""))
    kmers = sorted(params["kmers"])
    kmer_info = ["--first_kmer", str(kmers[0])]
    if len(kmers) > 1:
        kmer_info += ["--last_kmer", str(kmers[-1]),
                      "--kmer_step", str(kmers[1] - kmers[0])]
    subprocess.check_call(["perl", os.path.join(dirs["cortex"], "scripts", "calling", "run_calls.pl"),
                           "--fastaq_index", fastaq_index,
                           "--auto_cleaning", "yes", "--bc", "yes", "--pd", "yes",
                           "--outdir", os.path.dirname(out_base), "--outvcf", os.path.basename(out_base),
                           "--ploidy", str(config["algorithm"].get("ploidy", 2)),
                           "--stampy_hash", indexes["stampy"],
                           "--stampy_bin", os.path.join(dirs["stampy"], "stampy.py"),
                           "--refbindir", os.path.dirname(indexes["cortex"][0]),
                           "--list_ref_fasta",  reffasta_index,
                           "--genome_size", str(params["genome_size"]),
                           "--max_read_len", "30000",
                           #"--max_var_len", "4000",
                           "--format", "FASTQ", "--qthresh", "5", "--do_union", "yes",
                           "--mem_height", "17", "--mem_width", "100",
                           "--ref", "CoordinatesAndInCalling", "--workflow", "independent",
                           "--vcftools_dir", dirs["vcftools"],
                           "--logfile", "{0}.logfile,f".format(out_base)]
                          + kmer_info)
    final = glob.glob(os.path.join(os.path.dirname(out_base), "vcfs",
                                   "{0}*FINALcombined_BC*decomp.vcf".format(os.path.basename(out_base))))
    # No calls, need to setup an empty file
    if len(final) != 1:
        print("Did not find output VCF file for {0}".format(out_base))
        return None
    else:
        return final[0]
931615
def _run_main(main, argv):
  """"""
  if FLAGS.run_with_pdb:
    sys.exit(pdb.runcall(main, argv))
  elif FLAGS.run_with_profiling or FLAGS.profile_file:
    # Avoid import overhead since most apps (including performance-sensitive
    # ones) won't be run with profiling.
    import atexit
    if FLAGS.use_cprofile_for_profiling:
      import cProfile as profile
    else:
      import profile
    profiler = profile.Profile()
    if FLAGS.profile_file:
      atexit.register(profiler.dump_stats, FLAGS.profile_file)
    else:
      atexit.register(profiler.print_stats)
    retval = profiler.runcall(main, argv)
    sys.exit(retval)
  else:
    sys.exit(main(argv))
351999
def gpp(argv=None):
    """"""
    if argv is None:
        argv = sys.argv[1:]
    argv.insert(0, 'preview')
    return main(argv)
886330
def fasta(args):
    
    from jcvi.formats.sizes import Sizes

    p = OptionParser(fasta.__doc__)
    p.add_option("--extend", default=1000, type="int",
                 help="Extend seq flanking the gaps [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    mapout, sfasta = args
    Flank = opts.extend
    pf = mapout.split(".")[0]
    mapbed = pf + ".bed"
    bm = BinMap(mapout)
    bm.print_to_bed(mapbed)

    bed = Bed(mapbed, sorted=False)
    markersbed = pf + ".markers.bed"
    fw = open(markersbed, "w")
    sizes = Sizes(sfasta).mapping
    for b in bed:
        accn = b.accn
        scf, pos = accn.split(".")
        pos = int(pos)
        start = max(0, pos - Flank)
        end = min(pos + Flank, sizes[scf])
        print("\t".join(str(x) for x in \
                    (scf, start, end, accn)), file=fw)

    fw.close()

    fastaFromBed(markersbed, sfasta, name=True)
1001126
def run(configobj=None):
    
    acs2d(configobj['input'],
          exec_path=configobj['exec_path'],
          time_stamps=configobj['time_stamps'],
          verbose=configobj['verbose'],
          quiet=configobj['quiet']
          )
261585
def asm(args):
    
    p = OptionParser(asm.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(p.print_help())

    asmfile, = args
    prefix = asmfile.rsplit(".", 1)[0]
    ctgfastafile = prefix + ".ctg.fasta"
    scffastafile = prefix + ".scf.fasta"
    fp = open(asmfile)
    ctgfw = open(ctgfastafile, "w")
    scffw = open(scffastafile, "w")

    for rec in iter_records(fp):
        type = rec.type
        if type == "CCO":
            fw = ctgfw
            pp = "ctg"
        elif type == "SCF":
            fw = scffw
            pp = "scf"
        else:
            continue

        id = rec.get_field("acc")
        id = id.translate(None, "()").split(",")[0]
        seq = rec.get_field("cns").translate(None, "-")
        s = SeqRecord(Seq(seq), id=pp + id, description="")
        SeqIO.write([s], fw, "fasta")
        fw.flush()

    fw.close()
320719
def run(self, oslom_exec, oslom_args, log_filename):
        """"""
        args = [oslom_exec, "-f", self.get_path(OslomRunner.TMP_EDGES_FILE)]
        args.extend(oslom_args)
        with open(log_filename, "w") as logwriter:
            start_time = time.time()
            retval = subprocess.call(
                args, cwd=self.working_dir,
                stdout=logwriter, stderr=subprocess.STDOUT)
            self.last_result = {
                "args": args, "retval": retval,
                "time": time.time() - start_time,
                "output_dir": self.get_path(
                    "{}_oslo_files".format(OslomRunner.TMP_EDGES_FILE))
            }
            return self.last_result
195672
def run_mrtrans(align_fasta, recs, work_dir, outfmt="paml"):
    
    align_file = op.join(work_dir, "prot-align.fasta")
    nuc_file = op.join(work_dir, "nuc.fasta")
    output_file = op.join(work_dir, "nuc-align.mrtrans")

    # make the prot_align file and nucleotide file
    align_h0 = open(align_file + "0", "w")
    align_h0.write(str(align_fasta))
    align_h0.close()
    prot_seqs = {}
    i = 0
    for rec in SeqIO.parse(align_h0.name, "fasta"):
        prot_seqs[i] = rec.seq
        i += 1
    align_h = open(align_file, "w")
    for i, rec in enumerate(recs):
        if len(rec.id) > 30:
            rec.id = rec.id[:28] + "_" + str(i)
            rec.description = ""
        print(">{0}\n{1}".format(rec.id, prot_seqs[i]), file=align_h)
    align_h.close()
    SeqIO.write(recs, file(nuc_file, "w"), "fasta")

    # run the program
    cl = MrTransCommandline(align_file, nuc_file, output_file, outfmt=outfmt)
    r, e = cl.run()
    if e is None:
        print("\tpal2nal:", cl, file=sys.stderr)
        return output_file
    elif e.read().find("could not translate") >= 0:
        print("***pal2nal could not translate", file=sys.stderr)
        return None
54127
def run(self, templ, *args):
        
        curs = self._conn.cursor()
        query = curs.mogrify(templ, args)
        if self.debug:
            print(query)
        curs.execute(query)
        return curs
252992
def run(self, pcap):
        
        tmpdir = None
        try:
            tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
            proc = Popen(self._suri_cmd(pcap, tmpdir), stdout=PIPE,
                     stderr=PIPE, universal_newlines=True)
            stdout, stderr = proc.communicate()
            if proc.returncode != 0:
                raise Exception("\n".join(["Execution failed return code: {0}" \
                                .format(proc.returncode), stderr or ""]))

            with open(os.path.join(tmpdir, 'fast.log')) as tmp:
                return (parse_version(stdout),
                    [ x for x in parse_alert(tmp.read()) ])
        finally:
            if tmpdir:
                shutil.rmtree(tmpdir)
1332882
def run(args):
    
    (opts, args) = PARSER.parse_args(args) if args else PARSER.parse_args()
    if not len(args):
        PARSER.print_usage()
        sys.exit(1)

    outfilename = args[0] + ".html"
    if len(args) > 1:
        outfilename = args[1]

    report = parser.Junit(args[0])
    html = report.html()

    with open(outfilename, "wb") as outfile:
        outfile.write(html.encode('utf-8'))
266465
def main(argv=None):
    """"""
    arguments = cli_common(__doc__, argv=argv)
    plugin = 'benchmark' if arguments['benchmark'] else None

    if arguments['-g']:
        template.generate_config(plugin, arguments['<FILE>'])
    else:
        with open(arguments['<FILE>']) as istr:
            context = json.load(istr)
        kwargs = dict(no_input=True, extra_context=context)
        if arguments['--output-dir']:
            kwargs.update(output_dir=arguments['--output-dir'])
        if arguments['--interactive']:
            kwargs.update(no_input=False)
        logging.info(
            'generating template in directory ' + kwargs.get('output_dir', os.getcwd())
        )
        template.generate_template(plugin, **kwargs)
118209
def main(argv=None):
    """"""
    parser = ArgumentParser(prog="pygenstub")
    parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
    parser.add_argument("files", nargs="*", help="generate stubs for given files")
    parser.add_argument(
        "-m",
        "--module",
        action="append",
        metavar="MODULE",
        dest="modules",
        default=[],
        help="generate stubs for given modules",
    )
    parser.add_argument(
        "-o", "--output", metavar="PATH", dest="out_dir", help="change the output directory"
    )
    parser.add_argument(
        "--generic", action="store_true", default=False, help="generate generic stubs"
    )
    parser.add_argument("--debug", action="store_true", help="enable debug messages")

    argv = argv if argv is not None else sys.argv
    arguments = parser.parse_args(argv[1:])

    # set debug mode
    if arguments.debug:
        logging.basicConfig(level=logging.DEBUG)
        _logger.debug("running in debug mode")

    out_dir = arguments.out_dir if arguments.out_dir is not None else ""
    if (out_dir == "") and (len(arguments.modules) > 0):
        print("Output directory must be given when generating stubs for modules.")
        sys.exit(1)

    modules = []
    for path in arguments.files:
        paths = Path(path).glob("**/*.py") if Path(path).is_dir() else [Path(path)]
        for source in paths:
            if str(source).startswith(os.path.pardir):
                source = source.absolute().resolve()
            if (out_dir != "") and source.is_absolute():
                source = source.relative_to(source.root)
            destination = Path(out_dir, source.with_suffix(".pyi"))
            modules.append((source, destination))

    for mod_name in arguments.modules:
        modules.extend(get_pkg_paths(mod_name, out_dir))

    for source, destination in modules:
        _logger.info("generating stub for %s to path %s", source, destination)
        with source.open() as f:
            code = f.read()
        try:
            stub = get_stub(code, generic=arguments.generic)
        except Exception as e:
            print(source, "-", e, file=sys.stderr)
            continue

        if stub != "":
            if not destination.parent.exists():
                destination.parent.mkdir(parents=True)
            with destination.open("w") as f:
                f.write("# " + EDIT_WARNING + "\n\n" + stub)