cli entrypoitns, sets up everything needed
497791
def cli_main():
    """"""
    SearchContext.commit()
    args = parser.parse_args()
    # open up a browser
    firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
    with contextlib.closing(firefox_remote):
        context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
        search = Search(parent=context)

        if args.fast:
            with context.use(FastSearch, Browser):
                main(search, args.query)
        else:
            with context.use(Browser):
                main(search, args.query)
1291432
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="sloancone",
        tunnel=False
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # 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,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
993231
def do_cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input):
    
    LOG.debug("Init command")
    click.secho("[+] Initializing project structure...", fg="green")

    no_build_msg = """
Project generated: {output_dir}/{name}

Steps you can take next within the project folder
===================================================
[*] Invoke Function: sam local invoke HelloWorldFunction --event event.json
[*] Start API Gateway locally: sam local start-api
""".format(output_dir=output_dir, name=name)

    build_msg = """
Project generated: {output_dir}/{name}

Steps you can take next within the project folder
===================================================
[*] Install dependencies
[*] Invoke Function: sam local invoke HelloWorldFunction --event event.json
[*] Start API Gateway locally: sam local start-api
""".format(output_dir=output_dir, name=name)

    no_build_step_required = (
        "python", "python3.7", "python3.6", "python2.7", "nodejs", "nodejs4.3", "nodejs6.10", "nodejs8.10", "ruby2.5")
    next_step_msg = no_build_msg if runtime in no_build_step_required else build_msg

    try:
        generate_project(location, runtime, dependency_manager, output_dir, name, no_input)
        if not location:
            click.secho(next_step_msg, bold=True)
            click.secho("Read {name}/README.md for further instructions\n".format(name=name), bold=True)
        click.secho("[*] Project initialization is now complete", fg="green")
    except GenerateProjectFailedError as e:
        raise UserException(str(e))
623746
function setup(global) {
  'use strict';

  if (process.env.NODE_ENV === 'production') {
    return;
  }

  if (!process.env.__REACT_DEVTOOLS_PORT__) {
    return;
  }

  const reactDevTools = require('react-devtools-core');
  try {
    reactDevTools.connectToDevTools({
      host: process.env.__REACT_DEVTOOLS_HOST__ || 'localhost',
      port: process.env.__REACT_DEVTOOLS_PORT__,
    });
  } catch (e) {
    console.error('Cannot connect to React DevTools')
  }
}
1022076
def _setup(self):
        
        role_directory = os.path.join(self._config.scenario.directory,
                                      self.options['roles-path'])
        if not os.path.isdir(role_directory):
            os.makedirs(role_directory)
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    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,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1152773
def setup(app):
    """"""
    app.connect("builder-inited", build_configuration_parameters)
    app.connect("autodoc-skip-member", skip_slots)
    app.add_stylesheet("css/custom.css")
123604
def set_up(self):
        """"""
        self.path.state = self.path.gen.joinpath("state")
        if self.path.state.exists():
            self.path.state.rmtree(ignore_errors=True)
        self.path.state.mkdir()

        for script in self.given.get("scripts", []):
            script_path = self.path.state.joinpath(script)

            if not script_path.dirname().exists():
                script_path.dirname().makedirs()

            script_path.write_text(self.given["scripts"][script])
            script_path.chmod("u+x")

        for filename, contents in self.given.get("files", {}).items():
            self.path.state.joinpath(filename).write_text(contents)

        self.python = hitchpylibrarytoolkit.project_build(
            "commandlib", self.path, self.given["python version"]
        ).bin.python

        self.example_py_code = (
            ExamplePythonCode(self.python, self.path.state)
            .with_code(self.given.get("code", ""))
            .with_setup_code(self.given.get("setup", ""))
        )
870628
def _setup_helper():
    """"""
    base = os.path.abspath(os.path.dirname(__file__))
    helper = os.path.join(base, "helper.sh")
    with open(helper) as fh:
        click.echo(fh.read())
440188
def start
      puts "\n******************************************************************************************************************************************\n\n"
      puts "  JumpStarting....\n".purple
      check_setup
      execute_install_command
      run_scripts_from_yaml(:run_after_install_command)
      parse_template_dir
      create_dirs
      populate_files_from_whole_templates
      populate_files_from_append_templates
      populate_files_from_line_templates
      remove_unwanted_files
      run_scripts_from_yaml(:run_after_jumpstart)
      check_for_strings_to_replace
      run_scripts_from_yaml(:run_after_string_replace)
      check_local_nginx_configuration
      exit_with_success
    end
205343
public function setupCommand() {
		$serverPublicKeyString = Files::getFileContents('resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoServer.pub', FILE_TEXT);
		if ($serverPublicKeyString === FALSE) {
			$this->outputLine('Could not open resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoServer.pub, exiting.');
			$this->quit(1);
		}

		$serverPublicKeyFingerprint = $this->rsaWalletService->registerPublicKeyFromString($serverPublicKeyString);
		$this->outputLine('Registered sso demo server public key');

		$clientPrivateKeyString = Files::getFileContents('resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoClient.key', FILE_TEXT);
		if ($clientPrivateKeyString === FALSE) {
			$this->outputLine('Could not open resource://Flowpack.SingleSignOn.DemoInstance/Private/Fixtures/DemoClient.key, exiting.');
			$this->quit(2);
		}

		$clientPublicKeyFingerprint = $this->rsaWalletService->registerKeyPairFromPrivateKeyString($clientPrivateKeyString);
		$this->outputLine('Registered demo client key pair');

		$globalSettings = $this->yamlSource->load(FLOW_PATH_CONFIGURATION . '/Settings');
		$globalSettings['Flowpack']['SingleSignOn']['Client']['client']['publicKeyFingerprint'] = $clientPublicKeyFingerprint;
		$globalSettings['Flowpack']['SingleSignOn']['Client']['server']['DemoServer']['publicKeyFingerprint'] = $serverPublicKeyFingerprint;
		$this->yamlSource->save(FLOW_PATH_CONFIGURATION . '/Settings', $globalSettings);
		$this->outputLine('Updated settings');
	}
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
1373780
def main():
    """"""

    # Create command line parser.
    parser = argparse.ArgumentParser()

    # Adding command line arguments.
    parser.add_argument("username", help="Github Username", default=None)

    parser.add_argument(
        "--deep_dive",
        help=" ".join(
            [
                "If added considers repositories starred by users",
                "you follow along with repositories you have",
                "starred. Is significantly slower.",
            ]
        ),
        action="store_true",
        default=False,
    )

    # Parse command line arguments.
    arguments = parser.parse_args()

    if arguments.username is None:
        parser.print_help()
        return

    print("")
    print(
        crayons.white(
            "Authentication (with password) have higher rate limits."
        )
    )
    print(
        crayons.white(
            "Skipping password might cause failure due to rate limit."
        )
    )
    print("")

    password = getpass.getpass(
        crayons.blue(
            "Enter password (to skip press enter without entering anything): ",
            bold=True,
        )
    )

    try:
        gs = GitSuggest(
            username=arguments.username,
            password=password,
            token=None,
            deep_dive=arguments.deep_dive,
        )
    except BadCredentialsException:
        print("")
        print(
            crayons.red(
                "Incorrect password provided, to skip password enter nothing.",
                bold=True,
            )
        )
        exit()
    except TwoFactorException:
        print("")
        print(
            crayons.red(
                "\n".join(
                    [
                        "You have 2FA set up, please enter a personal access token.",
                        "You can generate one on https://github.com/settings/tokens",
                    ]
                ),
                bold=True,
            )
        )
        exit()

    print("")
    print(crayons.green("Suggestions generated!"))

    file_name = "/tmp/gitresults.html"
    repos = list(gs.get_suggested_repositories())

    r2h = ReposToHTML(arguments.username, repos)
    r2h.to_html(file_name)

    webbrowser.open_new("file://" + file_name)
797209
def init_app(self, app):
        """"""
        app.extensions['invenio-documents'] = self
        app.cli.add_command(cmd)
236025
def init_cli(self):
        
        if self.init_cli_cmds is None:
            self.init_cli_cmds = self.set_default_init_cli_cmds()

        for cli_cmd in self.init_cli_cmds:
            if isinstance(cli_cmd, list) and len(cli_cmd) >= 2:
                asynchronous = cli_cmd[1]
                if len(cli_cmd) > 2:
                    wait = cli_cmd[2]
                else:
                    wait = True
                self.execute_command(cli_cmd[0], wait=wait, asynchronous=asynchronous)
            else:
                self.execute_command(cli_cmd)
418161
def setup(cls) -> None:
        """"""
        cls.prepare()
        setuptools.setup(
            name=cls.name, version=cls.version, description=cls.description,
            long_description=cls.long_description, url=cls.url, download_url=cls.download_url,
            author=cls.author, author_email=cls.author_email,
            maintainer=cls.try_fields('maintainer', 'author'),
            maintainer_email=cls.try_fields('maintainer_email', 'author_email'),
            license=cls.license_str, classifiers=cls.classifiers, keywords=cls.keywords,
            packages=cls.packages, package_dir={'': cls.root_directory},
            include_package_data=True,
            package_data=cls.package_data, exclude_package_data=cls.exclude_package_data,
            install_requires=cls.install_requires, extras_require=cls.extras_require,
            python_requires=cls.python_requires,
            entry_points=cls.entry_points, test_suite=cls.test_suite)
390066
def setup():
    """"""
    install_requirements = ["attrdict"]
    if sys.version_info[:2] < (3, 4):
        install_requirements.append("pathlib")
    setup_requirements = ['six', 'setuptools>=17.1', 'setuptools_scm']
    needs_sphinx = {
        'build_sphinx',
        'docs',
        'upload_docs',
    }.intersection(sys.argv)
    if needs_sphinx:
        setup_requirements.append('sphinx')
    setuptools.setup(
        author="David Gidwani",
        author_email="david.gidwani@gmail.com",
        classifiers=[
            "Development Status :: 4 - Beta",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: BSD License",
            "Operating System :: OS Independent",
            "Programming Language :: Python",
            "Programming Language :: Python :: 2",
            "Programming Language :: Python :: 2.7",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.3",
            "Programming Language :: Python :: 3.4",
            "Topic :: Software Development",
            "Topic :: Software Development :: Libraries :: Python Modules",
        ],
        description="Painless access to namespaced environment variables",
        download_url="https://github.com/darvid/biome/tarball/0.1",
        install_requires=install_requirements,
        keywords="conf config configuration environment",
        license="BSD",
        long_description=readme(),
        name="biome",
        package_dir={'': 'src'},
        packages=setuptools.find_packages('./src'),
        setup_requires=setup_requirements,
        tests_require=["pytest"],
        url="https://github.com/darvid/biome",
        use_scm_version=True,
    )