Main entry point for transfer command line tool.

    This essentially will marshall the user to the functions they need.
500802
def main(args = None):
    '''
    
    '''

    parser = argparse.ArgumentParser(description = 'Tool to perform transfer learning')

    parser.add_argument('-c','--configure',
                        action = 'store_true',
                        help = 'Configure transfer')

    parser.add_argument('-e','--export',
                        action = 'store_true',
                        dest = 'export_config',
                        help = 'Export configuration and models')

    parser.add_argument('-i','--import',
                        action = 'store',
                        type = str,
                        default = None,
                        dest = 'import_config',
                        help = 'Import configuration and models')

    parser.add_argument('-p','--project',
                        action = 'store',
                        type = str,
                        default = None,
                        dest = 'project',
                        help = 'Specify a project, if not supplied it will be picked from configured projects')

    parser.add_argument('-r','--run',
                        action = 'store_true',
                        help = 'Run all transfer learning operations')

    parser.add_argument('-f','--final',
                        action = 'store_true',
                        help = 'Run final training on all layers: Warning SLOW!')

    parser.add_argument('-l','--last-weights',
                        action = 'store_true',
                        dest = 'last',
                        help = 'Restart from the last weights, rather than the best intermediate weights')

    parser.add_argument('--predict',
                        action = 'store',
                        type = str,
                        default = None,
                        const = 'default',
                        dest = 'predict',
                        nargs='?',
                        help = 'Predict model on file or directory')

    parser.add_argument('--prediction-rest-api',
                        action = 'store_true',
                        dest = 'rest_api',
                        help = 'Start rest api to make predictions on files or directories')

    if len(sys.argv) == 1:
        parser.print_help()
        return

    args = parser.parse_args()

    if args.import_config is not None:
        import_config(args.import_config)
        return
    elif args.export_config:
        project = select_project(args.project)
        weights = model_input(project)
        ind = model_individual_input(project, weights)
        export_config(project, weights, ind)
        return
    elif args.configure:
        configure()
        return
    else:
        project = select_project(args.project)

    if args.run:

        if project['is_array'] == False:
            project = images_to_array(project)
            update_config(project)

        if project['is_augmented'] == False:
            project = augment_arrays(project)
            update_config(project)

        if project['is_pre_model'] == False:
            project = pre_model(project)
            update_config(project)

        project = train_model(project, final = args.final, last = args.last)
        update_config(project)

        print('')
        print(colored('Completed modeling round: ' + str(project['model_round']), 'cyan'))
        print('')
        print('Best current model: ', colored(project['best_weights'], 'yellow'))
        print('Last current model: ', colored(project['last_weights'], 'yellow'))
        print('')
        print('To further refine the model, run again with:')
        print('')
        print(colored('    transfer --run --project ' + project['name'], 'green'))
        print('')
        print('To make predictions:')
        print('')
        print(colored('    transfer --predict [optional dir or file] --project ' + project['name'], 'yellow'))
        print('')

    elif args.rest_api:
        if project['server_weights'] is not None:
            start_server(project, 'server_weights')

        elif project['best_weights'] is not None:
            weights = model_input(project)
            start_server(project, weights)

        else:
            print('Model is not trained.  Please first run your project:')
            print('')
            print(colored('    transfer --run', 'green'))
            print('')
    elif args.predict is not None:
        if args.predict == 'default':

            completer = Completer()
            readline.set_completer_delims('\t')
            readline.parse_and_bind('tab: complete')
            readline.set_completer(completer.path_completer)
            args.predict = str_input('Enter a path to file(s): ')
        if project['server_weights'] is not None:
            predict_model(project, 'server_weights', args.predict)

        elif project['best_weights'] is not None:
            weights = model_input(project)
            print('Predicting on image(s) in: ', colored(args.predict, 'yellow'))
            predict_model(project, weights, args.predict)

        else:
            print('Model is not trained.  Please first run your project:')
            print('')
            print(colored('    transfer --run', 'green'))
            print('')
932478
def main():
    
    name = sys.argv[1]
    path = filepath.FilePath('.stat').temporarySibling()
    path.makedirs()
    func = makeBenchmarkRunner(path, sys.argv[1:])
    try:
        bench(name, path, func)
    finally:
        path.remove()
851395
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs option handling operations from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-action", metavar="action", dest="action", required=True,
                        help="The action to perform on the options: join=create single string, "\
                             "split=create array from quoted option, code=generate code from options")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="The option(s) to process")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, packages=True)

    try:
        if parsed.action == "join":
            output = "cmdline = \"" + backquote(join_options(parsed.option)) + "\""
        elif parsed.action == "split" and len(parsed.option) == 1:
            output = "options = [\n"
            opts = split_options(parsed.option[0])
            for idx, opt in enumerate(opts):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]"
        elif parsed.action == "code":
            options = parsed.option[:]
            cname = None
            # classname + options?
            if options[0].find(".") > -1:
                cname = options[0]
                options = options[1:]
            output = "options = [ \n"
            for idx, opt in enumerate(options):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]\n"
            if cname is not None:
                output += 'handler = OptionHandler(JavaObject.new_instance("' + cname + '"))\n'
                output += 'handler.options = options\n'
        else:
            raise Exception("Unsupported action: " + parsed.action)
        if output is not None:
            print(output)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
674821
def main(argv=None):  # suppress(unused-function)
    
    argv = argv or sys.argv

    if "--" not in argv:
        sys.stderr.write("""Must specify command after '--'.\n""")
        return 1

    cmd_index = argv.index("--")
    args, cmd = (argv[1:cmd_index], argv[cmd_index + 1:])

    parser = argparse.ArgumentParser(description="""Cache results from jobs""")
    parser.add_argument("--dependencies",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of paths which, if more recent than the last time this job was invoked, will cause the job to be re-invoked.""")
    parser.add_argument("--output-files",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of expected output paths form this command, which, if they do not exist, will cause the job to be re-invoked.""")
    parser.add_argument("--stamp-directory",
                        metavar="DIRECTORY",
                        type=str,
                        help="""A directory to store cached results from this command. If a matching invocation is used and the files specified in --dependencies and --output-files are up-to-date, then the cached stdout, stderr and return code is used and the command is not run again.""")
    parser.add_argument("--use-hashes",
                        action="store_true",
                        help="""Use hash comparison in order to determine if dependencies have changed since the last invocation of the job. This method is slower, but can withstand files being copied or moved.""")
    namespace = parser.parse_args(args)
    stamp_directory = namespace.stamp_directory
    if namespace.use_hashes:
        method = jobstamp.HashMethod
    else:
        method = jobstamp.MTimeMethod

    result = jobstamp.run(_run_cmd,
                          cmd,
                          jobstamps_dependencies=namespace.dependencies,
                          jobstamps_output_files=namespace.output_files,
                          jobstamps_cache_output_directory=stamp_directory,
                          jobstamps_method=method)

    sys.stdout.write(result["stdout"].decode())
    sys.stderr.write(result["stderr"].decode())
    return result["code"]
880354
def main(args=sys.argv):
    

    if len(args) < 2:
        return usage("Command expected")

    command = args[1]
    rest = args[2:]

    if "create".startswith(command):
        return cli_create(rest)
    elif "query".startswith(command):
        return cli_query(rest)
    elif "verify".startswith(command):
        return cli_verify(rest)
    else:
        return usage("Unknown command: %s" % command)
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
911934
def main():
    
    global server_address

    # check the version
    if (sys.version_info[:2] != (2, 5)):
        sys.stderr.write("Python 2.5 only\n")
        sys.exit(1)

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "host", nargs='?',
        help="address of host (default %r)" % (SERVER_HOST,),
        default=SERVER_HOST,
        )
    parser.add_argument(
        "port", nargs='?', type=int,
        help="server port (default %r)" % (SERVER_PORT,),
        default=SERVER_PORT,
        )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # extract the server address and port
    host = args.host
    port = args.port
    server_address = (host, port)
    if _debug: _log.debug("    - server_address: %r", server_address)

    # build the stack
    this_console = ConsoleClient()
    if _debug: _log.debug("    - this_console: %r", this_console)

    this_middle_man = MiddleMan()
    if _debug: _log.debug("    - this_middle_man: %r", this_middle_man)

    this_director = TCPClientDirector()
    if _debug: _log.debug("    - this_director: %r", this_director)

    bind(this_console, this_middle_man, this_director)
    bind(MiddleManASE(), this_director)

    # create a task manager for scheduled functions
    task_manager = TaskManager()
    if _debug: _log.debug("    - task_manager: %r", task_manager)

    # don't wait to connect
    this_director.connect(server_address)

    if _debug: _log.debug("running")

    run()
646310
def main(args=None):
    
    # Base command line parser. Help is not allowed because command
    # line is parsed in two stages - in the first stage is found setting
    # module of the application, in the second stage are found management
    # command's arguments.
    parser = ArgumentParser(add_help=False)
    parser.add_argument(
        '-s', '--settings',
        dest='settings', action='store', type=str, default=None,
        help=_('application settings module')
    )

    # Get settings module
    try:
        settings = get_app_settings(parser, args)
    except ImportError as exc:
        parser.error(_("Invalid application settings module: {}").format(exc))

    # Get management commands and add their arguments into command
    # line parser
    commands = get_management_commands(settings)
    subparsers = parser.add_subparsers(
        dest='action', help=_('specify action')
    )
    for command_cls in six.itervalues(commands):
        subparser = subparsers.add_parser(
            command_cls.name, help=command_cls.help)
        for command_args, kwargs in command_cls.arguments:
            subparser.add_argument(*command_args, **kwargs)

    # Get config class and add its arguments into command line parser
    if settings:
        config_cls = get_config_class(settings)
        if not issubclass(config_cls, Config):
            raise TypeError(
                "Config class must be subclass of the "
                "shelter.core.config.Config")
        for config_args, kwargs in config_cls.arguments:
            parser.add_argument(*config_args, **kwargs)
    else:
        config_cls = Config

    # Add help argument and parse command line
    parser.add_argument(
        '-h', '--help', action='help',
        help=_('show this help message and exit')
    )
    cmdline_args = parser.parse_args(args)
    if not cmdline_args.action:
        parser.error(_('No action'))

    # Run management command
    command_cls = commands[cmdline_args.action]
    if command_cls.settings_required and not settings:
        parser.error(_(
            "Settings module is not defined. You must either set "
            "'SHELTER_SETTINGS_MODULE' environment variable or "
            "'-s/--settings' command line argument."
        ))
    try:
        config = config_cls(settings, cmdline_args)
    except ImproperlyConfiguredError as exc:
        parser.error(str(exc))
    command = command_cls(config)
    try:
        command()
    except Exception:
        traceback.print_exc(file=sys.stderr)
        sys.stderr.flush()
        if multiprocessing.active_children():
            # If main process has children processes, exit immediately without
            # cleaning. It is a workaround, because parent process waits for
            # non-daemon children.
            os._exit(1)
        sys.exit(1)
    sys.exit(0)
1132305
def main():
    ''' 

    '''
    import sys
    from bokeh.command.bootstrap import main as _main

   # Main entry point (see setup.py)
    _main(sys.argv)
1047490
def main(cls, args, settings=None, userdata=None): # pylint: disable=too-many-branches,too-many-statements
        
        # Packet Configuration
        logger.info('Using Packet configuration from %s', Focus.info(args.conf.name))
        try:
            conf = json.loads(args.conf.read())
        except ValueError as msg:
            logger.error('Unable to parse %s: %s', args.conf.name, msg)
            return 1

        # Handle Tags
        if args.tags and (args.create_spot or args.create_demand):
            logger.info('Assigning the following tags to the instance: %r', args.tags)

        if args.only:
            try:
                args.only = UserData.parse_only_criterias(args.only)
            except ValueError:
                logger.error('-only requires format of: name=value')
                return 1
            logging.info('Using filter %r to return only matching devices.', args.only)

        # Packet Manager
        try:
            cluster = PacketManager(conf)
        except PacketManagerException as msg:
            logger.error(msg)
            return 1
        project = cluster.conf.get('projects').get(args.project)

        # List Operations
        if args.list_projects:
            cluster.print_projects(cluster.list_projects())

        if args.list_plans:
            cluster.print_plans(cluster.list_plans())

        if args.list_spot_prices:
            cluster.print_spot_prices(cluster.list_spot_prices())

        if args.list_operating_systems:
            cluster.print_operating_systems(cluster.list_operating_systems())

        if args.list_facilities:
            cluster.print_facilities(cluster.list_facilities())

        if args.list_devices and args.project:
            cluster.print_devices(cluster.list_devices(project, conditions=args.only))

        if args.create_volume:
            if len(args.create_volume) < 4:
                logger.error('Not enough arguments for creating a volume storage.')
                return 1
            [plan, size, region, label] = args.create_volume
            try:
                cluster.create_volume(project, plan, size, region, label)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Pre-Checks
        if (args.create_spot or args.create_demand) \
                and (args.region and args.plan):
            logging.info('Validating requested remote capacities ...')
            try:
                status = cluster.validate_capacity([
                    [args.region, args.plan, str(args.count)]
                ])
                if status:
                    logger.info('Requested capacities are available.')
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Creation
        if args.create_spot \
                and args.region \
                and args.plan \
                and args.max_spot_price \
                and args.os:
            try:
                devices = cluster.create_spot(project_id=project,
                                              facility=args.region,
                                              plan=args.plan,
                                              operating_system=args.os,
                                              spot_price_max=args.max_spot_price,
                                              tags=args.tags,
                                              userdata=userdata,
                                              count=args.count)
                cluster.print_devices(devices)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.create_demand \
                and args.region \
                and args.plan \
                and args.os:
            try:
                devices = cluster.create_demand(project_id=project,
                                                facility=args.region,
                                                plan=args.plan,
                                                tags=args.tags,
                                                operating_system=args.os,
                                                userdata=userdata,
                                                count=args.count)
                cluster.print_devices(devices)
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        # Device Operations
        if args.reboot:
            try:
                cluster.reboot(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.stop:
            try:
                cluster.stop(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        if args.terminate:
            try:
                cluster.terminate(cluster.list_devices(project, conditions=args.only))
            except PacketManagerException as msg:
                logger.error(msg)
                return 1

        return 0
280461
def main():
    
    from datetime import datetime

    # Initialize Command-Line and User-Config Settings, Log
    # -----------------------------------------------------

    beg_time = datetime.now()
    # Process command-line arguments to determine action
    # If no subcommand (e.g. 'import') is given, returns 'None' --> exit
    args, sub_clargs = load_command_line_args()
    if args is None:
        return

    # Create a logging object
    log = load_log(args)

    # Run configuration/setup interactive script
    if args.command == 'setup':
        setup_user_config(log)
        return

    # Make sure configuration file exists, or that's what we're doing
    # (with the 'setup' subcommand)
    if not os.path.isfile(_CONFIG_PATH):
        raise RuntimeError("'{}' does not exist.  "
                           "Run `astrocats setup` to configure."
                           "".format(_CONFIG_PATH))

    git_vers = get_git()
    title_str = "Astrocats, version: {}, SHA: {}".format(__version__, git_vers)
    log.warning("\n\n{}\n{}\n{}\n".format(title_str, '=' * len(title_str),
                                          beg_time.ctime()))

    # Load the user settings from the home directory
    args = load_user_config(args, log)

    # Choose Catalog and Operation(s) to perform
    # ------------------------------------------
    mod_name = args.command
    log.debug("Importing specified module: '{}'".format(mod_name))
    # Try to import the specified module
    try:
        mod = importlib.import_module('.' + mod_name, package='astrocats')
    except Exception as err:
        log.error("Import of specified module '{}' failed.".format(mod_name))
        log_raise(log, str(err), type(err))

    # Run the `main.main` method of the specified module
    log.debug("Running `main.main()`")
    mod.main.main(args, sub_clargs, log)

    end_time = datetime.now()
    log.warning("\nAll complete at {}, After {}".format(end_time, end_time -
                                                        beg_time))
    return
98238
def main(argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs) -> Optional[CompletedProcess]:
    
    parser = ArgumentParser(description="There are a few packages providing commands. Try e.g. `pip install scanpy-scripts`!")
    parser.set_defaults(func=parser.print_help)
    
    subparsers: DelegatingSubparsersAction = parser.add_subparsers(
        action=DelegatingSubparsersAction,
        _command='scanpy',
        _runargs={**runargs, 'check': check},
    )
    
    parser_settings = subparsers.add_parser('settings')
    parser_settings.set_defaults(func=cmd_settings)
    
    args = parser.parse_args(argv)
    return args.func()
105738
def main():
    """"""
    # Dynamically determine all the providers available and gather command line arguments.
    parsed_args = generate_cli_main_parser().parse_args()

    log_level = logging.getLevelName(parsed_args.log_level)
    logging.basicConfig(stream=sys.stdout, level=log_level,
                        format='%(message)s')
    logger.debug('Arguments: %s', parsed_args)

    # In the CLI context, will get configuration interactively:
    #   * from the command line
    #   * from the environment variables
    #   * from lexicon configuration files found in given --config-dir (default is current dir)
    config = ConfigResolver()
    config.with_args(parsed_args).with_env().with_config_dir(parsed_args.config_dir)

    client = Client(config)

    results = client.execute()

    handle_output(results, parsed_args.output, config.resolve('lexicon:action'))
298724
def main():
    
    arg_parse = setup_argparse()
    args = arg_parse.parse_args()

    if not args.quiet:
        print('GNS3 Topology Converter')

    if args.debug:
        logging_level = logging.DEBUG
    else:
        logging_level = logging.WARNING

    logging.basicConfig(level=logging_level,
                        format=LOG_MSG_FMT, datefmt=LOG_DATE_FMT)

    logging.getLogger(__name__)

    # Add the main topology to the list of files to convert
    if args.topology == 'topology.net':
        args.topology = os.path.join(os.getcwd(), 'topology.net')

    topology_files = [{'file': topology_abspath(args.topology),
                       'snapshot': False}]

    # Add any snapshot topologies to be converted
    topology_files.extend(get_snapshots(args.topology))

    topology_name = name(args.topology, args.name)

    # Do the conversion
    for topology in topology_files:
        do_conversion(topology, topology_name, args.output, args.debug)
464220
def transfer_command(
    batch,
    sync_level,
    recursive,
    destination,
    source,
    label,
    preserve_mtime,
    verify_checksum,
    encrypt,
    submission_id,
    dry_run,
    delete,
    deadline,
    skip_activation_check,
    notify,
    perf_cc,
    perf_p,
    perf_pp,
    perf_udt,
):
    
    source_endpoint, cmd_source_path = source
    dest_endpoint, cmd_dest_path = destination

    if recursive and batch:
        raise click.UsageError(
            (
                "You cannot use --recursive in addition to --batch. "
                "Instead, use --recursive on lines of --batch input "
                "which need it"
            )
        )

    if (cmd_source_path is None or cmd_dest_path is None) and (not batch):
        raise click.UsageError(
            ("transfer requires either SOURCE_PATH and DEST_PATH or " "--batch")
        )

    # because python can't handle multiple **kwargs expansions in a single
    # call, we need to get a little bit clever
    # both the performance options (of which there are a few), and the
    # notification options (also there are a few) have elements which should be
    # omitted in some cases
    # notify comes to us clean, perf opts need more care
    # put them together into a dict before passing to TransferData
    kwargs = {}
    perf_opts = dict(
        (k, v)
        for (k, v) in dict(
            perf_cc=perf_cc, perf_p=perf_p, perf_pp=perf_pp, perf_udt=perf_udt
        ).items()
        if v is not None
    )
    kwargs.update(perf_opts)
    kwargs.update(notify)

    client = get_client()
    transfer_data = TransferData(
        client,
        source_endpoint,
        dest_endpoint,
        label=label,
        sync_level=sync_level,
        verify_checksum=verify_checksum,
        preserve_timestamp=preserve_mtime,
        encrypt_data=encrypt,
        submission_id=submission_id,
        delete_destination_extra=delete,
        deadline=deadline,
        skip_activation_check=skip_activation_check,
        **kwargs
    )

    if batch:

        @click.command()
        @click.option("--recursive", "-r", is_flag=True)
        @click.argument("source_path", type=TaskPath(base_dir=cmd_source_path))
        @click.argument("dest_path", type=TaskPath(base_dir=cmd_dest_path))
        def process_batch_line(dest_path, source_path, recursive):
            """
            Parse a line of batch input and turn it into a transfer submission
            item.
            """
            transfer_data.add_item(
                str(source_path), str(dest_path), recursive=recursive
            )

        shlex_process_stdin(
            process_batch_line,
            (
                "Enter transfers, line by line, as\n\n"
                "    [--recursive] SOURCE_PATH DEST_PATH\n"
            ),
        )
    else:
        transfer_data.add_item(cmd_source_path, cmd_dest_path, recursive=recursive)

    if dry_run:
        formatted_print(
            transfer_data,
            response_key="DATA",
            fields=(
                ("Source Path", "source_path"),
                ("Dest Path", "destination_path"),
                ("Recursive", "recursive"),
            ),
        )
        # exit safely
        return

    # autoactivate after parsing all args and putting things together
    # skip this if skip-activation-check is given
    if not skip_activation_check:
        autoactivate(client, source_endpoint, if_expires_in=60)
        autoactivate(client, dest_endpoint, if_expires_in=60)

    res = client.submit_transfer(transfer_data)
    formatted_print(
        res,
        text_format=FORMAT_TEXT_RECORD,
        fields=(("Message", "message"), ("Task ID", "task_id")),
    )
1277253
def main(command_line_args=None):
    ''''''
    log = None
    if not command_line_args:
        command_line_args = sys.argv
    try:
        start_time = time.time()
        args = parse_command_line_args(command_line_args)
        log = utils.Logger(args)
        command_validator.preflight(args, log)
        log.info('connor begins (v{})', __version__)
        log.info('logging to [{}]', args.log_file)
        utils.log_environment_info(log, args)
        bam_tags = bamtag.build_bam_tags()
        base_annotated_writer = writers.build_writer(args.input_bam,
                                                      args.annotated_output_bam,
                                                      bam_tags,
                                                      args)
        sort_filter_by_name = args.filter_order == 'name'
        annotated_writer = writers.LoggingWriter(base_annotated_writer,
                                                 log,
                                                 sort_filter_by_name)
        consensus_writer = writers.build_writer(args.input_bam,
                                                 args.output_bam,
                                                 bam_tags,
                                                 args)
        _dedup_alignments(args, consensus_writer, annotated_writer, log)
        annotated_writer.close(log)
        consensus_writer.close(log)
        warning = ' **See warnings above**' if log.warning_occurred else ''
        elapsed_time = int(time.time() - start_time)
        log.info("connor complete ({} seconds, {}mb peak memory).{}",
             elapsed_time,
             utils.peak_memory(),
             warning)
    except utils.UsageError as usage_error:
        message = "connor usage problem: {}".format(str(usage_error))
        print(message, file=sys.stderr)
        print("See 'connor --help'.", file=sys.stderr)
        sys.exit(1)
    except Exception: #pylint: disable=broad-except
        if log:
            show = log.error
        else:
            show = partial(print, file=sys.stderr)
        show("An unexpected error occurred")
        show(traceback.format_exc())
        exit(1)
231098
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    if os.path.isfile(pathToYaml):
        from fundamentals.mysql import yaml_to_database
        # PARSE YAML FILE CONTENTS AND ADD TO DATABASE
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn
        )
        yaml2db.add_yaml_file_content_to_database(
            filepath=pathToYaml,
            deleteFile=deleteFlag
        )
        basename = os.path.basename(pathToYaml)
        print "Content of %(basename)s added to database" % locals()

    else:
        from fundamentals.mysql import yaml_to_database
        yaml2db = yaml_to_database(
            log=log,
            settings=settings,
            dbConn=dbConn,
            pathToInputDir=pathToYaml,
            deleteFiles=deleteFlag
        )
        yaml2db.ingest()
        print "Content of %(pathToYaml)s directory added to database" % locals()

    return