Python-based Project Euler command line tool.
506537
def main(option, problem):
    """"""
    # No problem given (or given option ignores the problem argument)
    if problem == 0 or option in {skip, verify_all}:
        # Determine the highest problem number in the current directory
        files = problem_glob()
        problem = max(file.num for file in files) if files else 0

        # No Project Euler files in current directory (no glob results)
        if problem == 0:
            # Generate the first problem file if option is appropriate
            if option not in {cheat, preview, verify_all}:
                msg = "No Project Euler files found in the current directory."
                click.echo(msg)
                option = generate

            # Set problem number to 1
            problem = 1

        # --preview and no problem; preview the next problem
        elif option is preview:
            problem += 1

        # No option and no problem; generate next file if answer is
        # correct (verify() will exit if the solution is incorrect)
        if option is None:
            verify(problem)
            problem += 1
            option = generate

    # Problem given but no option; decide between generate and verify
    elif option is None:
        option = verify if Problem(problem).glob else generate

    # Execute function based on option
    option(problem)
    sys.exit(0)
746286
def p_program(p):
    
    p[0] = make_block(p[1], p[2], make_break(p.lineno(2), p[2]))
739950
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
    X,Y = t.shape
    pt = np.zeros((X,Y))
    ""
    for i in range(X):
        for j in range(Y):
            for k in t:
                tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+  np.sin(xmin+step*i)*np.sin(k[0]))
                if tmp < range_:
                    pt[i][j]+=k[2] / (1+tmp)
    return pt
1196407
def generator(self, t):
        """"""
        a = (np.exp(-self.theta * t) - 1) / (np.exp(-self.theta) - 1)
        return -np.log(a)
606470
def main():
    '''
    
    '''
    args = get_args()
    try:
        utils.make_output_dir(args.outdir)
        utils.init_logs(args, tool="NanoComp")
        args.format = nanoplotter.check_valid_format(args.format)
        settings = vars(args)
        settings["path"] = path.join(args.outdir, args.prefix)
        sources = [args.fastq, args.bam, args.summary, args.fasta]
        sourcename = ["fastq", "bam", "summary", "fasta"]
        if args.split_runs:
            split_dict = validate_split_runs_file(args.split_runs)
        datadf = nanoget.get_input(
            source=[n for n, s in zip(sourcename, sources) if s][0],
            files=[f for f in sources if f][0],
            threads=args.threads,
            readtype=args.readtype,
            names=args.names,
            barcoded=args.barcoded,
            combine="track")
        datadf, settings = filter_and_transform_data(datadf, vars(args))
        if args.raw:
            datadf.to_csv("NanoComp-data.tsv.gz", sep="\t", index=False, compression="gzip")
        if args.store:
            pickle.dump(
                obj=datadf,
                file=open(settings["path"] + "NanoComp-data.pickle", 'wb'))
        if args.split_runs:
            change_identifiers(datadf, split_dict)
        if args.barcoded:
            datadf["dataset"] = datadf["barcode"]
        identifiers = list(datadf["dataset"].unique())
        write_stats(
            datadfs=[datadf[datadf["dataset"] == i] for i in identifiers],
            outputfile=settings["path"] + "NanoStats.txt",
            names=identifiers)
        if args.plot != 'false':
            plots = make_plots(datadf, settings)
            make_report(plots, path.join(args.outdir, args.prefix))
        logging.info("Succesfully processed all input.")
    except Exception as e:
        logging.error(e, exc_info=True)
        raise
875269
def main():
    
    # Parse arguments
    parser = argparse.ArgumentParser(description="Convert rational numbers between bases.")
    parser.add_argument("-n", "--number", default=None,
                        help="The number to convert as a string, else stdin used.")
    parser.add_argument("-i", "--input-base", default=10,
                        help="The input base (default 10).")
    parser.add_argument("-o", "--output-base", default=10,
                        help="The output base (default 10).")
    parser.add_argument("-d", "--max_depth", default=10, type=int,
                        help="The maximum fractional digits (default 10).")
    parser.add_argument("-r", "--recurring", default=True, type=bool,
                        help="Boolean, if True will attempt to find recurring decimals (default True).")
    parser.add_argument("-s", "--string", type=bool,
                        help="Boolean, if True will output number as String, else as tuple (default False).")
    args = parser.parse_args()

    args.input_base = float(args.input_base)
    args.output_base = float(args.output_base)
    if args.input_base == int(args.input_base):
        args.input_base = int(args.input_base)
    if args.output_base == int(args.output_base):
        args.output_base = int(args.output_base)
    if (args.number):
        return base(args.number, args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    elif not sys.stdin.isatty():
        return base(sys.stdin.read().strip(), args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    else:
        raise ValueError("Please input a number!")
1222225
def run(ctx, cpu, gpu, env, message, data, mode, open_notebook, follow, tensorboard, gpu2, cpu2, max_runtime, task, command):
    
    # cli_default is used for any option that has default value
    cli_default = {'description': '', 'command': ''}
    # Error early if more than one --env is passed.  Then get the first/only
    # --env out of the list so all other operations work normally (they don't
    # expect an iterable). For details on this approach, see the comment above
    # the --env click option
    if not env:
        cli_default['env'] = DEFAULT_ENV
        env = None
    elif len(env) > 1:
        floyd_logger.error(
            "You passed more than one environment: {}. Please specify a single environment.".format(env)
        )
        sys.exit(1)
    else:
        env = env[0]

    if not mode:
        cli_default['mode'] = 'command'

    experiment_config = ExperimentConfigManager.get_config()
    access_token = AuthConfigManager.get_access_token()
    namespace = experiment_config.namespace or access_token.username

    if not ProjectClient().exists(experiment_config.name, namespace=namespace):
        floyd_logger.error('Invalid project id, please run '
                           '"floyd init PROJECT_NAME" before scheduling a job.')
        sys.exit(1)

    experiment_name = "{}/{}".format(namespace, experiment_config.name)

    success, data_ids, show_data_info = process_data_ids(data)
    if not success:
        sys.exit(2)

    # Create module
    module_inputs = [{'name': data_str.split(':')[1],
                      'type': 'dir'} for data_str in data_ids]

    instance_type = None
    if gpu2:
        instance_type = G2_INSTANCE_TYPE
    elif cpu2:
        instance_type = C2_INSTANCE_TYPE
    elif gpu:
        instance_type = G1_INSTANCE_TYPE
    elif cpu:
        instance_type = C1_INSTANCE_TYPE

    if not instance_type:
        cli_default['instance_type'] = C1_INSTANCE_TYPE

    yaml_config = read_yaml_config()
    arch = INSTANCE_ARCH_MAP[
        resolve_final_instance_type(instance_type, yaml_config, task, cli_default)
    ]
    if not validate_env(env or cli_default['env'], arch):
        sys.exit(3)

    command_str = ' '.join(command)
    if command_str and mode in ('jupyter', 'serve'):
        floyd_logger.error('Command argument "%s" cannot be used with mode: %s.\nSee http://docs.floydhub.com/guides/run_a_job/#mode for more information about run modes.', command_str, mode)  # noqa
        sys.exit(3)
    if command_str == '':
        # set to none so it won't override floyd config
        command_str = None

    module = Module(name=experiment_name,
                    description=message or '',
                    command=command_str,
                    mode=mode,
                    family_id=experiment_config.family_id,
                    inputs=module_inputs,
                    env=env,
                    instance_type=instance_type,
                    yaml_config=yaml_config,
                    task=task)

    try:
        module_id = ModuleClient().create(module, cli_default)
    except BadRequestException as e:
        if 'Project not found, ID' in e.message:
            floyd_logger.error(
                'ERROR: Please run "floyd init PROJECT_NAME" before scheduling a job.')
        else:
            floyd_logger.error('ERROR: %s', e.message)
        sys.exit(4)
    floyd_logger.debug("Created module with id : %s", module_id)

    # Create experiment request
    # Get the actual command entered in the command line
    if max_runtime:
        max_runtime = int(max_runtime)
    full_command = get_command_line(instance_type, env, message, data, mode, open_notebook, command_str)
    experiment_request = ExperimentRequest(name=experiment_name,
                                           description=message,
                                           full_command=full_command,
                                           module_id=module_id,
                                           max_runtime=max_runtime,
                                           env=env,
                                           data_ids=data_ids,
                                           family_id=experiment_config.family_id,
                                           instance_type=instance_type,
                                           yaml_config=yaml_config,
                                           task=task)
    expt_client = ExperimentClient()
    expt_info = expt_client.create(experiment_request, cli_default)
    floyd_logger.debug("Created job : %s", expt_info['id'])

    job_name = expt_info['name']

    show_new_job_info(expt_client, job_name, expt_info, mode, open_notebook, show_data_info)

    if follow:
        floyd_logger.info("\nFollow flag detected (--follow): Opening logs ...")
        instance_log_id = instance_log_id = get_log_id(job_name)
        follow_logs(instance_log_id)
171485
def euler_options(fn):
    """"""
    euler_functions = cheat, generate, preview, skip, verify, verify_all

    # Reverse functions to print help page options in alphabetical order
    for option in reversed(euler_functions):
        name, docstring = option.__name__, option.__doc__
        kwargs = {'flag_value': option, 'help': docstring}

        # Apply flag(s) depending on whether or not name is a single word
        flag = '--%s' % name.replace('_', '-')
        flags = [flag] if '_' in name else [flag, '-%s' % name[0]]

        fn = click.option('option', *flags, **kwargs)(fn)

    return fn
196168
def _generate_one_ephemeris(
        cmd):
    

    global cmdList
    cmd = cmdList[cmd]

    results = []
    for c in cmd:
        p = Popen(c[0], stdout=PIPE, stderr=PIPE, shell=True)
        stdout, stderr = p.communicate()

        if len(stderr) and len(stderr.split()) != 15:
            print stderr, len(stderr.split())
            return None
        elif "!!WARNING! WARNING! WARNING! WARNING!!" in stdout:
            print "%(stdout)s was not found in astorb.dat" % locals()
            return None

        # SPLIT RESULTS INTO LIST OF DICTIONARIES
        r = stdout.strip().split("\n")
        keys = r[0].strip().split(',')
        lines = r[1:]
        for l in lines:
            # CREATE DICTIONARY FROM KEYS AND VALUES
            values = l.strip().split(',')
            for k, v in zip(keys, values):
                v = v.strip().replace("/", "")
                try:
                    v = float(v)
                except:
                    pass
            result = dict(zip(keys, values))
            result["object_name"] = c[1]
            results.append(result)
    return results
72616
def main(input_dir, output_dir):
    """"""

    import ballet.util.log
    ballet.util.log.enable(logger=logger, level='INFO', echo=False)
    ballet.util.log.enable(logger=ballet.util.log.logger, level='INFO',
                           echo=False)

    X_df, y_df = load_data(input_dir=input_dir)
    out = build()

    mapper_X = out['mapper_X']
    encoder_y = out['encoder_y']

    X_ft = mapper_X.transform(X_df)
    y_ft = encoder_y.transform(y_df)

    save_features(X_ft, output_dir)
    save_targets(y_ft, output_dir)
273868
def main():
    
    parser = optparse.OptionParser(usage="usage: pylon [options] input_file",
                                   version="%prog 0.4.4")

    parser.add_option("-o", "--output", dest="output", metavar="FILE",
        help="Write the solution report to FILE.")

#    parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
#        default=False, help="Print less information.")

    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
        default=False, help="Print more information.")

#    parser.add_option("-g", "--gui", action="store_true", dest="gui",
#        default=False, help="Use the portable graphical interface to Pylon.")

#    parser.add_option("-n", "--no-report", action="store_true",
#        dest="no_report", default=False, help="Suppress report output.")

    parser.add_option("-d", "--debug", action="store_true", dest="debug",
        default=False, help="Print debug information.")

    parser.add_option("-t", "--input-type", dest="type", metavar="TYPE",
        default="any", help="The argument following the -t is used to "
        "indicate the format type of the input data file. The types which are "
        "currently supported include: matpower, psse [default: %default]"
        " If not specified Pylon will try to determine the type according to "
        "the file name extension and the file header.")

    parser.add_option("-s", "--solver", dest="solver", metavar="SOLVER",
        default="acpf", help="The argument following the -s is used to"
        "indicate the type of routine to use in solving. The types which are "
        "currently supported are: 'dcpf', 'acpf', 'dcopf', 'acopf', 'udopf' "
        "and 'none' [default: %default].")

    parser.add_option("-a", "--algorithm", action="store_true",
        metavar="ALGORITHM", dest="algorithm", default="newton",
        help="Indicates the algorithm type to be used for AC power flow. The "
        "types which are currently supported are: 'newton' and 'fdpf' "
        "[default: %default].")

    parser.add_option("-T", "--output-type", dest="output_type",
        metavar="OUTPUT_TYPE", default="rst", help="Indicates the output "
        "format type.  The type swhich are currently supported include: rst, "
        "matpower, csv, excel and none [default: %default].")

    (options, args) = parser.parse_args()

    if options.verbose:
        logger.setLevel(logging.INFO)
    elif options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.ERROR)

    # Output.
    outext = {'psse': '.raw', 'matpower': '.m'}
    if options.output:
        if options.output == "-":
            outfile = sys.stdout
            logger.setLevel(logging.CRITICAL) # must stay quiet
#            options.output_type = "none"
        else:
            outfile = open(options.output, "wb")
    elif options.output_type is not None:
        if options.output_type in outext.keys():
            inname, ext = os.path.splitext(args[0])
            outfile = inname + outext[options.output_type]
        else:
            outfile = sys.stdout
    else:
        outfile = sys.stdout
#        if not options.no_report:
#            logger.setLevel(logging.CRITICAL) # must stay quiet

    # Input.
    if len(args) > 1:
        parser.print_help()
        sys.exit(1)
    elif (len(args) == 0) or (args[0] == "-"):
        filename = ""
        if sys.stdin.isatty():
            # True if the file is connected to a tty device, and False
            # otherwise (pipeline or file redirection).
            parser.print_help()
            sys.exit(1)
        else:
            # Handle piped input ($ cat ehv3.raw | pylon | rst2pdf -o ans.pdf).
            infile = sys.stdin
    else:
        filename = args[0]
        infile = open(filename, "rb")

    if options.type == "any":
        type = detect_data_file(infile, filename)
    else:
        type = options.type

    # Get the case from the input file-like object.
    case = read_case(infile, type)

    if case is not None:
        # Routine (and algorithm) selection.
        if options.solver == "dcpf":
            solver = DCPF(case)
        elif options.solver == "acpf":
            if options.algorithm == "newton":
                solver = NewtonPF(case)
            elif options.algorithm == "fdpf":
                solver = FastDecoupledPF(case)
            else:
                logger.critical("Invalid algorithm [%s]." % options.algorithm)
                sys.exit(1)
        elif options.solver == "dcopf":
            solver = OPF(case, True)
        elif options.solver == "acopf":
            solver = OPF(case, False)
        elif options.solver == "udopf":
            solver = UDOPF(case)
        elif options.solver == "none":
            solver = None
        else:
            logger.critical("Invalid solver [%s]." % options.solver)
#            sys.exit(1)
            solver = None

        # Output writer selection.
        if options.output_type == "matpower":
            writer = MATPOWERWriter(case)
        elif options.output_type == "psse":
            writer = PSSEWriter(case)
        elif options.output_type == "rst":
            writer = ReSTWriter(case)
        elif options.output_type == "csv":
            from pylon.io.excel import CSVWriter
            writer = CSVWriter(case)
        elif options.output_type == "excel":
            from pylon.io.excel import ExcelWriter
            writer = ExcelWriter(case)
        elif options.output_type == "pickle":
            writer = PickleWriter(case)
        else:
            logger.critical("Invalid output type [%s]." % options.output_type)
            sys.exit(1)

        if solver is not None:
            solver.solve()
        if options.output_type != "none":
            writer.write(outfile)
            print('Output file {0} written'.format(outfile))
    else:
        logger.critical("Unable to read case data.")

    # Don't close stdin or stdout.
    if len(args) == 1:
        infile.close()
    if options.output and not (options.output == "-"):
        outfile.close()
295845
def main():
    """"""
    arguments = sys.argv[1:]
    # If no arguments are given, the help text of pip-accel is printed.
    if not arguments:
        usage()
        sys.exit(0)
    # If no install subcommand is given we pass the command line straight
    # to pip without any changes and exit immediately afterwards.
    if 'install' not in arguments:
        # This will not return.
        os.execvp('pip', ['pip'] + arguments)
    else:
        arguments = [arg for arg in arguments if arg != 'install']
    config = Config()
    # Initialize logging output.
    coloredlogs.install(
        fmt=config.log_format,
        level=config.log_verbosity,
    )
    # Adjust verbosity based on -v, -q, --verbose, --quiet options.
    for argument in list(arguments):
        if match_option(argument, '-v', '--verbose'):
            coloredlogs.increase_verbosity()
        elif match_option(argument, '-q', '--quiet'):
            coloredlogs.decrease_verbosity()
    # Perform the requested action(s).
    try:
        accelerator = PipAccelerator(config)
        accelerator.install_from_arguments(arguments)
    except NothingToDoError as e:
        # Don't print a traceback for this (it's not very user friendly) and
        # exit with status zero to stay compatible with pip. For more details
        # please refer to https://github.com/paylogic/pip-accel/issues/47.
        logger.warning("%s", e)
        sys.exit(0)
    except Exception:
        logger.exception("Caught unhandled exception!")
        sys.exit(1)
847452
def main():
    '''  '''
    app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version)
    # add tasks
    vocab_task = app.add_task('vocab', func=gen_vocab)
    vocab_task.add_argument('input', help='Input file')
    vocab_task.add_argument('--output', help='Output file', default=None)
    vocab_task.add_argument('--stopwords', help='Stop word to ignore', default=None)
    vocab_task.add_argument('-k', '--topk', help='Only select the top k frequent elements', default=None, type=int)
    # run app
    app.run()
150635
def euler(self, euler):
        
        assert(len(euler) == 3)
        self._euler = np.array(euler)

        # mark other representations as outdated, will get generated on next
        # read
        self._q = None
        self._dcm = None
746468
def euler_tour_dfs(G, source=None):
    
    if source is None:
        # produce edges for all components
        nodes = G
    else:
        # produce edges for components with source
        nodes = [source]
    yielder = []
    visited = set()
    for start in nodes:
        if start in visited:
            continue
        visited.add(start)
        stack = [(start, iter(G[start]))]
        while stack:
            parent, children = stack[-1]
            try:
                child = next(children)
                if child not in visited:
                    # yielder += [[parent, child]]
                    yielder += [parent]
                    visited.add(child)
                    stack.append((child, iter(G[child])))
            except StopIteration:
                if stack:
                    last = stack[-1]
                    yielder += [last[0]]
                stack.pop()
    return yielder
24009
def main():
	""""""
	commands = ['update', 'list', 'get', 'info', 'count', 'search', 'download']
	parser = argparse.ArgumentParser(description="Command line access to software repositories for TI calculators, primarily ticalc.org and Cemetech")
	parser.add_argument("action", metavar="ACTION", type=str, help="The calcpkg command to execute (count, get, info, list, update)")
	parser.add_argument("string", metavar="STRING", type=str, help="The string to search for when using count, get, info, or list commands", nargs="?", default="")
	
	parser.add_argument("-c", "--category", dest="category", help="Limit searching to a specified category", default="")
	parser.add_argument("-e", "--extension", dest="extension", help="Limit searching to a specified file extension", default="")
	parser.add_argument("-f", "--filename", dest="searchFiles", action="store_true", help="Search by archive filenames rather than descriptive package name")
	parser.add_argument("-g", "--game", dest="game", action="store_true", help="Limit searching to games only")
	parser.add_argument("-m", "--math", dest="math", action="store_true", help="Limit searching to math and science programs only")
	parser.add_argument("-r", "--repository", dest="repo", help="Limit searching by one repository- default is to use all", default="")
	parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Always provide verbose output")
	parser.add_argument("-x", "--extract", dest="extract", action="store_true", help="After downloading, autoextract archive files when possible")
	parser.add_argument("-y", "--assume-yes", dest="prompt", action="store_false", help="Never prompt for verification of command")
	args = parser.parse_args()

	#Verify that a valid command was specified
	if not args.action in commands:
		print "Error: Invalid action specified, action must be one of " + str(commands)
		return
	
	#args.category is special
	if args.category != "":
		category = "/" + args.category + "/"
	else:
		category = ""
	
	#Initialize repositories; all behind-the-scene processing is done by plugins in calcrepo.repos
	repositories = createRepoObjects()
	if args.repo != "":
		for repoName, repository in repositories.iteritems():
			if repoName != args.repo:
				repositories[repoName] = None
	
	#Now, run commands for each repo		
	for name, repository in repositories.iteritems():
		if repository != None:
			repository.setRepoData(args.string, category, args.extension, args.math, args.game, args.searchFiles)
			if args.action == "update":
				repository.updateRepoIndexes(args.verbose)
			elif (args.action == "list" or args.action == "search"):
				repository.searchIndex()
			elif (args.action == "get" or args.action == "download"):
				repository.searchIndex()
				repository.downloadFiles(args.prompt, args.extract)
			elif args.action == "info":
				repository.getFileInfos()
			elif args.action == "count":
				repository.countIndex()
1187975
def main():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('input',
                        metavar='INPUT',
                        help='Input directory with PNG files')
    parser.add_argument('output', nargs='?',
                        metavar='OUTPUT',
                        help='Output directory')
    parser.add_argument('--apikey',
                        metavar='APIKEY',
                        default=find_apikey(),
                        help='TinyPNG API Key')

    args = parser.parse_args()
    _main(args)