Setup the testing environment
 @param [Array<String>] args The argument array of options for configuring Beaker
 See 'beaker --help' for full list of supported command line options
507896
def setup(args = [])
      options_parser = Beaker::Options::Parser.new
      options = options_parser.parse_args(args)
      options[:debug] = true
      RSpec.configuration.logger = Beaker::Logger.new(options)
      options[:logger] = logger
      RSpec.configuration.hosts = []
      RSpec.configuration.options = options
    end
1333814
public static void main(final String[] args) throws Exception {
        if (args.length != 2) {
            throw new RuntimeException("Invalid build configuration. No command-line arguments specified");
        }
        final var buildDir = args[0];
        final var projectDir = args[1];
        new ConfigurationMetadataGenerator(buildDir, projectDir).execute();
    }
1233466
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="qubits"
    )
    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 varname == "import":
            varname = "iimport"
        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,))

    if init:
        from . import workspace
        ws = workspace(
            log=log,
            pathToWorkspace=pathToWorkspace
        )
        ws.setup()
        return

    # IMPORT THE SIMULATION SETTINGS
    (allSettings,
     programSettings,
     limitingMags,
     sampleNumber,
     peakMagnitudeDistributions,
     explosionDaysFromSettings,
     extendLightCurveTail,
     relativeSNRates,
     lowerRedshiftLimit,
     upperRedshiftLimit,
     redshiftResolution,
     restFrameFilter,
     kCorrectionTemporalResolution,
     kCorPolyOrder,
     kCorMinimumDataPoints,
     extinctionType,
     extinctionConstant,
     hostExtinctionDistributions,
     galacticExtinctionDistribution,
     surveyCadenceSettings,
     snLightCurves,
     surveyArea,
     CCSNRateFraction,
     transientToCCSNRateFraction,
     extraSurveyConstraints,
     lightCurvePolyOrder,
     logLevel) = cu.read_in_survey_parameters(
        log,
        pathToSettingsFile=pathToSettingsFile
    )

    logFilePath = pathToOutputDirectory + "/qubits.log"
    del log
    log = _set_up_command_line_tool(
        level=str(logLevel),
        logFilePath=logFilePath
    )

    # dbConn, log = cu.settings(
    #     pathToSettingsFile=pathToSettingsFile,
    #     dbConn=False,
    #     log=True
    # )

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

    resultsDict = {}

    pathToOutputPlotDirectory = pathToOutputDirectory + "/plots/"
    dcu.dryx_mkdir(
        log,
        directoryPath=pathToOutputPlotDirectory
    )

    pathToResultsFolder = pathToOutputDirectory + "/results/"
    dcu.dryx_mkdir(
        log,
        directoryPath=pathToResultsFolder
    )

    if not programSettings['Extract Lightcurves from Spectra'] and not programSettings['Generate KCorrection Database'] and not programSettings['Run the Simulation'] and not programSettings['Compile and Plot Results']:
        print "All stages of the simulatation have been switched off. Please switch on at least one stage of the simulation under the 'Programming Settings' in the settings file `%(pathToSettingsFile)s`" % locals()

    # GENERATE THE DATA FOR SIMULATIONS
    if programSettings['Extract Lightcurves from Spectra']:
        log.info('generating the Lightcurves')
        dg.generate_model_lightcurves(
            log=log,
            pathToSpectralDatabase=pathToSpectralDatabase,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            explosionDaysFromSettings=explosionDaysFromSettings,
            extendLightCurveTail=extendLightCurveTail,
            polyOrder=lightCurvePolyOrder
        )
        print "The lightcurve file can be found here: %(pathToOutputDirectory)stransient_light_curves.yaml" % locals()
        print "The lightcurve plots can be found in %(pathToOutputPlotDirectory)s" % locals()

    if programSettings['Generate KCorrection Database']:
        log.info('generating the kcorrection data')
        dg.generate_kcorrection_listing_database(
            log,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToSpectralDatabase=pathToSpectralDatabase,
            restFrameFilter=restFrameFilter,
            temporalResolution=kCorrectionTemporalResolution,
            redshiftResolution=redshiftResolution,
            redshiftLower=lowerRedshiftLimit,
            redshiftUpper=upperRedshiftLimit + redshiftResolution)
        log.info('generating the kcorrection polynomials')
        dg.generate_kcorrection_polynomial_database(
            log,
            pathToOutputDirectory=pathToOutputDirectory,
            restFrameFilter=restFrameFilter,
            kCorPolyOrder=kCorPolyOrder,  # ORDER OF THE POLYNOMIAL TO FIT
            kCorMinimumDataPoints=kCorMinimumDataPoints,
            redshiftResolution=redshiftResolution,
            redshiftLower=lowerRedshiftLimit,
            redshiftUpper=upperRedshiftLimit + redshiftResolution,
            plot=programSettings['Generate KCorrection Plots'])

        print "The k-correction database has been generated here: %(pathToOutputDirectory)sk_corrections" % locals()
        if programSettings['Generate KCorrection Plots']:
            print "The k-correction polynomial plots can also be found in %(pathToOutputDirectory)sk_corrections" % locals()

    if programSettings['Run the Simulation']:
        # CREATE THE OBSERVABLE UNIVERSE!
        log.info('generating the redshift array')
        redshiftArray = u.random_redshift_array(
            log,
            sampleNumber,
            lowerRedshiftLimit,
            upperRedshiftLimit,
            redshiftResolution=redshiftResolution,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])
        resultsDict['Redshifts'] = redshiftArray.tolist()

        log.info('generating the SN type array')
        snTypesArray = u.random_sn_types_array(
            log,
            sampleNumber,
            relativeSNRates,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])
        resultsDict['SN Types'] = snTypesArray.tolist()

        log.info('generating peak magnitudes for the SNe')
        peakMagnitudesArray = u.random_peak_magnitudes(
            log,
            peakMagnitudeDistributions,
            snTypesArray,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the SN host extictions array')
        hostExtinctionArray = u.random_host_extinction(
            log,
            sampleNumber,
            extinctionType,
            extinctionConstant,
            hostExtinctionDistributions,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the SN galactic extictions array')
        galacticExtinctionArray = u.random_galactic_extinction(
            log,
            sampleNumber,
            extinctionType,
            extinctionConstant,
            galacticExtinctionDistribution,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the raw lightcurves for the SNe')
        rawLightCurveDict = u.generate_numpy_polynomial_lightcurves(
            log,
            snLightCurves=snLightCurves,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the k-correction array for the SNe')
        kCorrectionArray = u.build_kcorrection_array(
            log,
            redshiftArray,
            snTypesArray,
            snLightCurves,
            pathToOutputDirectory=pathToOutputDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the observed lightcurves for the SNe')
        observedFrameLightCurveInfo, peakAppMagList = u.convert_lightcurves_to_observered_frame(
            log,
            snLightCurves=snLightCurves,
            rawLightCurveDict=rawLightCurveDict,
            redshiftArray=redshiftArray,
            snTypesArray=snTypesArray,
            peakMagnitudesArray=peakMagnitudesArray,
            kCorrectionArray=kCorrectionArray,
            hostExtinctionArray=hostExtinctionArray,
            galacticExtinctionArray=galacticExtinctionArray,
            restFrameFilter=restFrameFilter,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            polyOrder=lightCurvePolyOrder,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('generating the survey observation cadence')
        cadenceDictionary = ss.survey_cadence_arrays(
            log,
            surveyCadenceSettings,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info('determining if the SNe are discoverable by the survey')
        discoverableList = ss.determine_if_sne_are_discoverable(
            log,
            redshiftArray=redshiftArray,
            limitingMags=limitingMags,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            pathToOutputDirectory=pathToOutputDirectory,
            pathToOutputPlotDirectory=pathToOutputPlotDirectory,
            plot=programSettings['Plot Simulation Helper Plots'])

        log.info(
            'determining the day (if and) when each SN is first discoverable by the survey')
        ripeDayList = ss.determine_when_sne_are_ripe_for_discovery(
            log,
            redshiftArray=redshiftArray,
            limitingMags=limitingMags,
            discoverableList=discoverableList,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            plot=programSettings['Plot Simulation Helper Plots'])

        # log.info('determining the day when each SN is disappears fainter than the survey limiting mags')
        # disappearDayList = determine_when_discovered_sne_disappear(
        #     log,
        #     redshiftArray=redshiftArray,
        #     limitingMags=limitingMags,
        #     ripeDayList=ripeDayList,
        #     observedFrameLightCurveInfo=observedFrameLightCurveInfo,
        #     plot=programSettings['Plot Simulation Helper Plots'])

        log.info('determining if and when each SN is discovered by the survey')
        lightCurveDiscoveryDayList, surveyDiscoveryDayList, snCampaignLengthList = ss.determine_if_sne_are_discovered(
            log,
            limitingMags=limitingMags,
            ripeDayList=ripeDayList,
            cadenceDictionary=cadenceDictionary,
            observedFrameLightCurveInfo=observedFrameLightCurveInfo,
            extraSurveyConstraints=extraSurveyConstraints,
            plot=programSettings['Plot Simulation Helper Plots'])

        resultsDict[
            'Discoveries Relative to Peak Magnitudes'] = lightCurveDiscoveryDayList
        resultsDict[
            'Discoveries Relative to Survey Year'] = surveyDiscoveryDayList
        resultsDict['Campaign Length'] = snCampaignLengthList
        resultsDict['Cadence Dictionary'] = cadenceDictionary
        resultsDict['Peak Apparent Magnitudes'] = peakAppMagList

        now = datetime.now()
        now = now.strftime("%Y%m%dt%H%M%S")
        fileName = pathToOutputDirectory + \
            "/simulation_results_%s.yaml" % (now,)
        stream = file(fileName, 'w')
        yamlContent = dict(allSettings.items() + resultsDict.items())
        yaml.dump(yamlContent, stream, default_flow_style=False)
        stream.close()

        print "The simulation output file can be found here: %(fileName)s. Remember to update your settings file 'Simulation Results File Used for Plots' parameter with this filename before compiling the results." % locals()
        if programSettings['Plot Simulation Helper Plots']:
            print "The simulation helper-plots found in %(pathToOutputPlotDirectory)s" % locals()

    # COMPILE AND PLOT THE RESULTS
    if programSettings['Compile and Plot Results']:
        pathToYamlFile = pathToOutputDirectory + "/" + \
            programSettings['Simulation Results File Used for Plots']
        result_log = r.log_the_survey_settings(log, pathToYamlFile)
        snSurveyDiscoveryTimes, lightCurveDiscoveryTimes, snTypes, redshifts, cadenceDictionary, peakAppMagList, snCampaignLengthList = r.import_results(
            log, pathToYamlFile)
        snRatePlotLink, totalRate, tooFaintRate, shortCampaignRate = r.determine_sn_rate(
            log,
            lightCurveDiscoveryTimes,
            snSurveyDiscoveryTimes,
            redshifts,
            surveyCadenceSettings=surveyCadenceSettings,
            lowerRedshiftLimit=lowerRedshiftLimit,
            upperRedshiftLimit=upperRedshiftLimit,
            redshiftResolution=redshiftResolution,
            surveyArea=surveyArea,
            CCSNRateFraction=CCSNRateFraction,
            transientToCCSNRateFraction=transientToCCSNRateFraction,
            peakAppMagList=peakAppMagList,
            snCampaignLengthList=snCampaignLengthList,
            extraSurveyConstraints=extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """
## Results ##

This simulated survey discovered a total of **%s** transients per year. An extra **%s** transients were detected but deemed too faint to constrain a positive transient identification and a further **%s** transients where detected but an observational campaign of more than **%s** days could not be completed to ensure identification. See below for the various output plots.

        """ % (totalRate, tooFaintRate, shortCampaignRate, extraSurveyConstraints["Observable for at least ? number of days"])
        cadenceWheelLink = r.plot_cadence_wheel(
            log,
            cadenceDictionary,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (cadenceWheelLink,)
        discoveryMapLink = r.plot_sn_discovery_map(
            log,
            snSurveyDiscoveryTimes,
            peakAppMagList,
            snCampaignLengthList,
            redshifts,
            extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (discoveryMapLink,)
        ratioMapLink = r.plot_sn_discovery_ratio_map(
            log,
            snSurveyDiscoveryTimes,
            redshifts,
            peakAppMagList,
            snCampaignLengthList,
            extraSurveyConstraints,
            pathToOutputPlotFolder=pathToOutputPlotDirectory)
        result_log += """%s""" % (ratioMapLink,)
        result_log += """%s""" % (snRatePlotLink,)

        now = datetime.now()
        now = now.strftime("%Y%m%dt%H%M%S")
        mdLogPath = pathToResultsFolder + \
            "simulation_result_log_%s.md" % (now,)
        mdLog = open(mdLogPath, 'w')
        mdLog.write(result_log)
        mdLog.close()

        dmd.convert_to_html(
            log=log,
            pathToMMDFile=mdLogPath,
            css="amblin"
        )

        print "Results can be found here: %(pathToResultsFolder)s" % locals()
        html = mdLogPath.replace(".md", ".html")
        print "Open this file in your browser: %(html)s" % locals()

    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
1008509
public static void main(String[] args) {
		try {
			// get the config directory first
			String configDir = null;

			if (args.length >= 2 && args[0].equals("-configDir")) {
				configDir = args[1];
			}

			if (configDir == null) {
				System.err
					.println("Error: Configuration directory must be specified.\nWebFrontend -configDir <directory>\n");
				System.exit(1);
				return;
			}

			// load the global configuration
			GlobalConfiguration.loadConfiguration(configDir);
			Configuration config = GlobalConfiguration.getConfiguration();
			
			// add stratosphere base dir to config
			config.setString(ConfigConstants.STRATOSPHERE_BASE_DIR_PATH_KEY, configDir+"/..");

			// get the listening port
			int port = config.getInteger(ConfigConstants.WEB_FRONTEND_PORT_KEY,
				ConfigConstants.DEFAULT_WEBCLIENT_PORT);

			// start the server
			WebInterfaceServer server = new WebInterfaceServer(config, port);
			LOG.info("Starting web frontend server on port " + port + '.');
			server.start();
			server.join();
		} catch (Throwable t) {
			LOG.error("Unexpected exception: " + t.getMessage(), t);
		}
	}
1325323
def parse_options(args)
      opt_parser = OptionParser.new do |opts|
        # Set a banner, displayed at the top
        # of the help screen.
        opts.banner = 'Usage: k9 [options] [<filename.rb>]'
        # Define the options, and what they do
        options[:version] = false
        opts.on('-v', '--version', 'JRubyArt Version') do
          options[:version] = true
        end

        options[:install] = false
        opts.on('-i', '--install', 'Installs jruby-complete and examples') do
          options[:install] = true
        end

        options[:check] = false
        opts.on('-?', '--check', 'Prints configuration') do
          options[:check] = true
        end

        options[:app] = false
        opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do
          options[:export] = true
        end

        options[:watch] = false
        opts.on('-w', '--watch', 'Watch/run the sketch') do
          options[:watch] = true
        end

        options[:run] = false
        opts.on('-r', '--run', 'Run the sketch') do
          options[:run] = true
        end

        options[:live] = false
        opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do
          options[:live] = true
        end

        options[:create] = false
        opts.on('-c', '--create', 'Create new outline sketch') do
          options[:create] = true
        end

        # This displays the help screen, all programs are
        # assumed to have this option.
        opts.on('-h', '--help', 'Display this screen') do
          puts opts
          exit
        end
      end
      @argc = opt_parser.parse(args)
      @filename = argc.shift
    end
738290
def start(**args)

      platform = args[:platform]
      file_path = args[:file_path]

      # Validate environment variable
      if ENV['platform'].nil?
        if platform.nil?
          puts 'No platform detected in environment and none passed to start...'
          exit
        end
        ENV['platform'] = platform
      end

      sleep 3

      # Appium ports
      ios_port = 4725
      android_port = 4727
      default_port = 4725

      platform = ENV['platform']

      # Platform is required
      check_platform platform

      platform = platform.downcase
      ENV['BASE_DIR'] = Dir.pwd

      # Check if multithreaded for distributing tests across devices
      threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i
      parallel = threads != 1

      if platform != 'all'
        pid = fork do
          if !parallel
            ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub"
            @server.start_single_appium platform, default_port
          else
            ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub'
            @server.launch_hub_and_nodes platform
          end
          setup(platform, file_path, threads, parallel)
        end

        puts "PID: #{pid}"
        setup_signal_handler(pid)
        Process.waitpid(pid)
      else # Spin off 2 sub-processes, one for Android connections and another for iOS,
        # each with redefining environment variables for the server url, number of threads and platform
        ios_pid = fork do
          ENV['THREADS'] = threads.to_s
          if parallel
            ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub'
            puts 'Start iOS'
            @server.launch_hub_and_nodes 'ios'
          else
            ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub"
            puts 'Start iOS'
            @server.start_single_appium 'ios', ios_port
          end
          setup('ios', file_path, threads, parallel)
        end

        android_pid = fork do
          ENV['THREADS'] = threads.to_s
          if parallel
            ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub'
            puts 'Start Android'
            @server.launch_hub_and_nodes 'android'
          else
            ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub"
            puts 'Start Android'
            @server.start_single_appium 'android', android_port
          end
          setup('android', file_path, threads, parallel)
        end

        puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}"
        setup_signal_handler(ios_pid, android_pid)
        [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) }
      end

      # Kill any existing Appium and Selenium processes
      kill_process 'appium'
      kill_process 'selenium'
    end
206533
protected void configure(String[] args) throws IOException {
    for (String arg : args) {
      if (arg.startsWith("--input=")) {
        FileRef ref = createInput();
        ref.setPath(arg.substring(arg.indexOf('=') + 1));
      } else if (arg.startsWith("--output=")) {
        FileRef ref = createOutput();
        ref.setPath(arg.substring(arg.indexOf('=') + 1));
      } else if (arg.startsWith("--libdefined=")) {
        FunctionNamePredicate libdefined = new FunctionNamePredicate();
        libdefined.setPattern(arg.substring(arg.indexOf('=') + 1));
        addConfiguredLibdefined(libdefined);
      } else {
        throw new IllegalArgumentException(arg);
      }
    }
  }
1082834
def add_default_args(args, obj)
      if @command.args && args.size < @command.arg_size - 1
        # leave off last arg since its an option
        @command.args.slice(0..-2).each_with_index {|arr,i|
          next if args.size >= i + 1 # only fill in once args run out
          break if arr.size != 2 # a default arg value must exist
          begin
            args[i] = @command.file_parsed_args ? obj.instance_eval(arr[1]) : arr[1]
          rescue Exception
            raise Scientist::Error, "Unable to set default argument at " +
              "position #{i+1}.\nReason: #{$!.message}"
          end
        }
      end
    end
458823
public static void main(String[] args) {
    int exitCode = 1;
    try {
      logLevel(args, new InstancedConfiguration(ConfigurationUtils.defaults()));
      exitCode = 0;
    } catch (ParseException e) {
      printHelp("Unable to parse input args: " + e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      System.err.println(String.format("Failed to set log level: %s", e.getMessage()));
    }
    System.exit(exitCode);
  }
1359266
def main() -> None:
    
    main_only_quicksetup_rootlogger(level=logging.DEBUG)
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "input_file",
        help="Input PDF (which is not modified by this program)")
    parser.add_argument(
        "output_file",
        help="Output PDF")
    parser.add_argument(
        "--slice_horiz", type=int, default=1,
        help="Slice the input PDF first into this many parts horizontally")
    parser.add_argument(
        "--slice_vert", type=int, default=1,
        help="Slice the input PDF first into this many parts vertically")
    parser.add_argument(
        "--longedge", action="store_true",
        help="Create PDF for long-edge duplex printing, not short edge")
    parser.add_argument(
        "--overwrite", action="store_true",
        help="Allow overwriting of an existing output file")
    parser.add_argument(
        "--unittest", action="store_true",
        help="Run unit tests and exit (you must pass dummy values for "
             "input/output files to use these tests)")
    # ... because requiring dummy input/output filenames for unit testing
    # is less confusing for the majority of users than showing syntax in
    # which they are optional!
    args = parser.parse_args()

    if args.unittest:
        log.warning("Performing unit tests")
        # unittest.main() doesn't play nicely with argparse; they both
        # use sys.argv by default (and we end up with what looks like garbage
        # from the argparse help facility); but this works:
        unittest.main(argv=[sys.argv[0]])
        sys.exit(EXIT_SUCCESS)

    success = convert_to_foldable(
        input_filename=os.path.abspath(args.input_file),
        output_filename=os.path.abspath(args.output_file),
        slice_horiz=args.slice_horiz,
        slice_vert=args.slice_vert,
        overwrite=args.overwrite,
        longedge=args.longedge
    )
    sys.exit(EXIT_SUCCESS if success else EXIT_FAILURE)
989366
public static void main(String[] args) {
    org.apache.commons.cli.Options cliOptions = createCliOptions();
    try {
      CommandLine cli = parseCli(args, cliOptions);
      Options options = loadOptions(cli);
      validate(options);
      ConstraintParser parser = new ConstraintParser(options);
      try {
        output(parser, options.getOutputFile());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } catch (IncompleteCliException e) {
      // If the command line is not complete just print usage and help
      printErrorWithUsageAndHelp(cliOptions);
    }
  }
861635
public void run(String[] args) {
		System.out.println("SampleStarter.run(String[])");
		System.out.println("- args.length: " + args.length);
		for (String arg : args) System.out.println("  - " + arg);
		System.out.println(this);
	}
448353
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,))

    from fundamentals.mysql import sqlite2mysql
    converter = sqlite2mysql(
        log=log,
        settings=settings,
        pathToSqlite=pathToSqliteDB,
        tablePrefix=tablePrefix,
        dbConn=dbConn
    )
    converter.convert_sqlite_to_mysql()

    return
1275820
def main(prog_args=None):
    
    if prog_args is None:
        prog_args = sys.argv

    parser = optparse.OptionParser()
    parser.usage = """Usage: %[prog] [options] [<path>]"""
    parser.add_option("-t", "--test-program", dest="test_program",
        default="nose", help="specifies the test-program to use. Valid values"
        " include `nose` (or `nosetests`), `django`, `py` (for `py.test`), "
        '`symfony`, `jelix` `phpunit` and `tox`')
    parser.add_option("-d", "--debug", dest="debug", action="store_true",
        default=False)
    parser.add_option('-s', '--size-max', dest='size_max', default=25,
        type="int", help="Sets the maximum size (in MB) of files.")
    parser.add_option('--custom-args', dest='custom_args', default='',
        type="str",
        help="Defines custom arguments to pass after the test program command")
    parser.add_option('--ignore-dirs', dest='ignore_dirs', default='',
        type="str",
        help="Defines directories to ignore.  Use a comma-separated list.")
    parser.add_option('-y', '--quiet', dest='quiet', action="store_true",
        default=False,
        help="Don't ask for any input.")

    opt, args = parser.parse_args(prog_args)

    if args[1:]:
        path = args[1]
    else:
        path = '.'


    try:
        watcher = Watcher(path, opt.test_program, opt.debug, opt.custom_args, 
            opt.ignore_dirs, opt.quiet)
        watcher_file_size = watcher.file_sizes()
        if watcher_file_size > opt.size_max:
            message =  "It looks like the total file size (%dMb) is larger  than the `max size` option (%dMb).\nThis may slow down the file comparison process, and thus the daemon performances.\nDo you wish to continue? [y/N] " % (watcher_file_size, opt.size_max)

            if not opt.quiet and not ask(message):
                raise CancelDueToUserRequest('Ok, thx, bye...')

        print "Ready to watch file changes..."
        watcher.loop()
    except (KeyboardInterrupt, SystemExit):
        # Ignore when you exit via Crtl-C
        pass
    except Exception, msg:
        print msg

    print "Bye"
430298
def run(create_app, config, description=None, args=None, namespace=None, options=None):
    
    import argparse

    class HelpFormatter(
        # argparse.RawTextHelpFormatter,
        argparse.RawDescriptionHelpFormatter,
        # argparse.ArgumentDefaultsHelpFormatter,
        # argparse.HelpFormatter,
        ):
        pass

    # Get configurations data if
    envName = getattr(config, 'ENV', None)
    envMap = getattr(config, 'envMap', None)
    envHelp = getattr(config, 'envHelp', {})
    envSelectVar = getattr(config, 'envSelectVar', None)
    configurations = getattr(config, 'configurations', None)
    envSelectable = callable(getattr(config, 'select', None))
    envPrintable = config.__str__ is not object.__str__

    parser = argparse.ArgumentParser(
        description = description or getattr(config, 'description',
            'runs Flask-based web application using Python WSGI reference server'),
        epilog = ''.join((
            '\n\noptional environment variables:\n{}'.format(
                '\n'.join(sorted('  {:<20}  {}'.format(envMap[key], envHelp.get(key, ''))
                for key in envMap))) if envMap else '',
            '\n\navailable environment configurations (*: active):\n{}'.format(
                '\n'.join('{} {}'.format(
                    '*' if envName in c.names else ' ',
                    ' | '.join(c.names)
                ) for c in configurations)) if configurations else '',
        )),
        formatter_class = HelpFormatter)

    parser.add_argument('-b', '--bind', metavar='[HOST|:PORT]', default='127.0.0.1:5000',
        help = 'bind to HOST:PORT (default: 127.0.0.1:5000)')

    debug = config.DEBUG
    debugMsg = ' (default in {})'.format(config.ENV)
    debugTrueMsg = debugMsg if debug else ''
    debugFalseMsg = debugMsg if not debug else ''

    parser.add_argument('-r', '--reload', action='store_true', default=debug,
        help = 'reload server on code change' + debugTrueMsg)
    parser.add_argument('-R', '--no-reload', action='store_false', dest='reload',
        help = 'do not reload server on code change' + debugFalseMsg)

    parser.add_argument('-d', '--debug', action='store_true', default=debug,
        help = 'show debugger on exception' + debugTrueMsg)
    parser.add_argument('-D', '--no-debug', action='store_false', dest='debug',
        help = 'do not show debugger on exception' + debugFalseMsg)

    if envSelectable:
        parser.add_argument('-e', '--env', default=config.ENV,
            help = 'select environment config (default: {})'.format(config.ENV))

    if envPrintable:
        if envSelectable:
            parser.add_argument('-E', '--show-env', nargs='?', const=True,
                help = 'show environment config and exit ({}default: {})'
                    .format('*: all, ' if configurations else '', config.ENV))
        else:
            parser.add_argument('-E', '--show-env', action='store_true',
                help = 'show environment config and exit')

    parser.add_argument('-g', '--gen-key', action='store_true',
        help = 'generate a good secret key and exit')


    args = parser.parse_args(args, namespace)

    if args.gen_key:
        # See http://flask.pocoo.org/docs/0.10/quickstart/#sessions
        import os
        key = os.urandom(24)
        return print(key)
        # return print('{0}\n{0!r}'.format(key))

    if envSelectable and args.env:
        config = config.select(args.env)

    if envPrintable and args.show_env:
        if configurations and args.show_env == '*':
            print('\n\n'.join('# {}\n{}'.format(' | '.join(c.names), c) for c in configurations))
        elif args.show_env is True:
            print(config)
        else:
            print(config.select(args.show_env))

        return

    host, port = (args.bind + ':').split(':')[:2]
    host = host or '127.0.0.1'
    port = int(port) if port else 5000

    return create_app(config).run(host, port, args.debug, use_reloader=args.reload, **(options or {}))
1125427
public static void main(final String args[]) {
        int exitCode = 1;
        final Setup setup = new Setup();
        try {
            setup.execute(args);
            exitCode = 0;
        } catch (Throwable exc) {
            System.err.println("ERROR: " + exc.getMessage());
        }
        System.exit(exitCode);
    }
653407
def setup_bootstrap_args(args, data)
      # We need to remove the --bootstrap option, if it exists
      args -= ['--bootstrap']
      args[1] = data['ssh_host']

      # And set up the node-specific data but ONLY if defined
      args += ['-N', data['name']] if data['name']
      args += ['-E', data['chef_environment']] if data['chef_environment']
      args += ['--ssh-port', data['ssh_port']] if data['ssh_port']
      args += ['--run-list', data['run_list'].join(',')] if data['run_list']
      attrs = attributes_for_bootstrap(data)
      args += ['--json-attributes', attrs.to_json] unless attrs.empty?
      args
    end