============================================== end main programm / special cli param handling functions below...
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
60871
def main():
    ""
    logging.captureWarnings(True)
    args = build_parser().parse_args()
    # Configure logging
    args.setup_logging(args)
    # Dispatch into the appropriate subcommand function.
    try:
        return args.func(args)
    except SystemExit:
        raise
    except:
        logging.exception('Problem when running command. Sorry!')
        sys.exit(1)
223163
function(params, callback) {
      var t = this;
      if (params === '.break' && t.shellCmd) {
        t.shellCmd.kill();
      }
      if (NEW_REPL) {
        t.stream.emit('data', params + "\n");
      } else {
        t.stream.emit('data', params);
      }
      return callback(null);
    }
172211
function handle(options, callback) {
  if (_.isString(options)) {
    options = { path: options };
  }

  if (_.isObject(options)) {
    const opts = { };
    _.merge(opts, config, options);
    options = opts;
  } else {
    options = _.cloneDeep(config);
  }

  options.path = options.path || config.get("home");
  return stat(options.path, function(err, stats) {
    if (err) {
      return callback(err);
    }

    const done = wrap(stats, callback);

    if (stats.isDirectory()) {
      options.dirStats = stats;
      return processDir(options, done);
    } else if (stats.isFile()) {
      return processFile(options, done);
    }

    return callback(null, null);
  });
}
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);
    }
  }
313416
def run_cli
      exit_code = begin
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        Codewars::CLI.start(@argv)

        0
      rescue StandardError => e
        b = e.backtrace
        @stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
        1
      rescue SystemExit => e
        e.status
      ensure
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end

      @kernel.exit(exit_code)
    end
551272
def call(command, params)
      @command = command
      request = Net::HTTP::Get.new(uri.request_uri + "?" + params)
      response = http.request(request)
      Response.new(response.body, response)
    end
1312654
def main():
    '''
    '''

    # Customize parser

    parser = get_parser()
    subparsers = get_subparsers(parser)

    def help(return_code=0):
        '''print help, including the software version and active client 
           and exit with return code.
        '''

        version = helpme.__version__
        
        bot.custom(message='Command Line Tool v%s' %version,
                   prefix='\n[HelpMe] ', 
                   color='CYAN')

        parser.print_help()
        sys.exit(return_code)
    
    # If the user didn't provide any arguments, show the full help
    if len(sys.argv) == 1:
        help()
    try:
        args, unknown = parser.parse_known_args()
    except:
        sys.exit(0)

    extras = None
    if args.command in HELPME_HELPERS and len(unknown) > 0:
        extras = unknown

    # if environment logging variable not set, make silent

    if args.debug is False:
        os.environ['MESSAGELEVEL'] = "INFO"

    # Show the version and exit
    if args.version is True:
        print(helpme.__version__)
        sys.exit(0)

    if args.command == "config": from .config import main
    if args.command == "list": from .list import main
    if args.command in HELPME_HELPERS: from .help import main

    # Pass on to the correct parser
    return_code = 0
    try:
        main(args, extras)
        sys.exit(return_code)
    except UnboundLocalError:
        return_code = 1

    help(return_code)
1024133
def main(argv=None):
    """"""

    parser = argparse.ArgumentParser(
        description='Commands as arguments'
    )
    command_help = 'optional command to run, if no command given, enter an interactive shell'
    parser.add_argument('command', nargs='?',
                        help=command_help)
    arg_help = 'optional arguments for command'
    parser.add_argument('command_args', nargs=argparse.REMAINDER,
                        help=arg_help)

    args = parser.parse_args(argv)

    c = CmdLineApp()

    if args.command:
        # we have a command, run it and then exit
        c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
    else:
        # we have no command, drop into interactive mode
        c.cmdloop()
519329
private static void trueMain(String[] argv) throws Exception {
    if (argv.length != 1) {
      System.err.println("Please provide a params file as the sole command line argument");
      System.exit(-1);
    }
    final Parameters params = Parameters.loadSerifStyle(new File(argv[0]));

    final File outputDirectory = params.getCreatableDirectory("outputDirectory");
    final File corpusRoot = params.getExistingDirectory("corpusRoot");
    final int memory = params.getPositiveInteger("memoryInMB");
    final boolean storeDocs = params.getBoolean("storeDocs");
    final Predicate<File> fileFilter = getFileFilter(params);
    final IndriFileProcessor indriFileProcessor = params.getParameterInitializedObject(
        "indriFileProcessorClass", IndriFileProcessor.class);

    log.info("Building index for corpus {} format to {} using processor {}",
        corpusRoot, outputDirectory, indriFileProcessor.getClass().getName());

    final IndexEnvironment env = setupIndexer(outputDirectory, memory, storeDocs);

    recursiveIndex(corpusRoot, env, indriFileProcessor,
        fileFilter);
    log.info("Indexed {} documents", env.documentsIndexed());
    env.close();
    log.info("Index complete");
  }
35552
def main():
    
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("path", nargs="+", help="File or directory path")
    parser.add_argument("--exclude", nargs="+", help="Exclude glob patterns")
    parser.add_argument(
        "--no-recursive",
        dest="recursive",
        action="store_false",
        help="Search directories recursively",
    )
    parser.add_argument(
        "--ignore-invalid", action="store_true", help="Ignore invalid paths"
    )
    parser.add_argument(
        "--pycharm", action="store_true", help="Enable PyCharm integration"
    )
    parser.add_argument(
        "--diff",
        dest="show_diff",
        action="store_true",
        help="Show diff and do not modify any files",
    )
    parser.add_argument(
        "--dry-run", action="store_true", help="Process files but do not write results"
    )
    parser.add_argument("--debug", action="store_true", help="Debug level logging")

    args = parser.parse_args()
    d1_common.util.log_setup(args.debug)

    repo_path = d1_dev.util.find_repo_root_by_path(__file__)
    repo = git.Repo(repo_path)

    specified_file_path_list = get_specified_file_path_list(args)
    # tracked_path_list = list(d1_dev.util.get_tracked_files(repo))
    # format_path_list = sorted(
    #     set(specified_file_path_list).intersection(tracked_path_list)
    # )
    format_path_list = specified_file_path_list
    for format_path in format_path_list:
        comment_unused_imports(args, format_path)
1103599
function consoleOutput(param, record) {
  {
    const outKey = record.level >= Level.ERROR ? 'stderr' : 'stdout';
    process[outKey].write(`${param}\n`);
  }
}
785749
static function init() {

		switch( PHP_SAPI ) {
		// Ideally we want to be runnning as CLI
		case 'cli':
			break;
		// Special conditions to ensure CGI runs as CLI
		case 'cgi':
			// Ensure resource constants are defined
			if( ! defined('STDERR') ){
				define( 'STDERR', fopen('php://stderr', 'w') );
			}
			if( ! defined('STDOUT') ){
				define( 'STDOUT', fopen('php://stdout', 'w') );
			}
			break;
		default:
			echo "Command line only\n";
			exit(1);
		}
		
		// Default error logger function
		PLUG::set_error_logger( array(__CLASS__,'format_logline') );
		
		// parse command line arguments from argv global
		global $argv, $argc;
		// first cli arg is always current script. second arg will be script arg passed to shell wrapper
		for( $i = 1; $i < $argc; $i++ ){
			$arg = $argv[ $i ];
			
			// Each command line argument may take following forms:
			//  1. "Any single argument", no point parsing this unless it follows #2 below
			//  2. "-aBCD", one or more switches, parse into 'a'=>true, 'B'=>true, and so on
			//  3. "-a value", flag used with following value, parsed to 'a'=>'value'
			//  4. "--longoption", GNU style long option, parse into 'longoption'=>true
			//  5. "--longoption=value", as above, but parse into 'longoption'=>'value'
			//  6."any variable name = any value" 
			
			$pair = explode( '=', $arg, 2 );
			if( isset($pair[1]) ){
				$name = trim( $pair[0] );
				if( strpos($name,'--') === 0 ){
					// #5. trimming "--" from option, tough luck if you only used one "-"
					$name = trim( $name, '-' );
				}
				// else is #6, any pair
				$name and self::$args[$name] = trim( $pair[1] );
			}
			
			else if( strpos($arg,'--') === 0 ){
				// #4. long option, no value
				$name = trim( $arg, "-\n\r\t " );
				$name and self::$args[ $name ] = true;
			}
			
			else if( $arg && $arg{0} === '-' ){
				$flags = preg_split('//', trim($arg,"-\n\r\t "), -1, PREG_SPLIT_NO_EMPTY );
				foreach( $flags as $flag ){
					self::$args[ $flag ] = true;
				}
				// leave $flag set incase a value follows.
				continue;
			}

			// else is a standard argument. use as value only if it follows a flag, e.g "-a apple"
			else if( isset($flag) ){
				self::$args[ $flag ] = trim( $arg );
			}

			// dispose of last flag
			unset( $flag );
			// next arg 
		}
	}
756721
function exec(cmd, args, stdin, callback) {
            var stdout = concat();
            var stderr = concat();

            var process = child_process.spawn(cmd, args, {
                stdio: [stdin || 'ignore', 'pipe', 'pipe']
            });
            process.stdout.pipe(stdout);
            process.stderr.pipe(stderr);
            process.on('exit', function(code, signal) {
              var err;
              if (code) {
                err = new Error(code);
                err.code = code;
                err.signal = signal;
              }
              callback(err, stdout, stderr);
            });
            process.on('error', function (err) {
              callback(err, stdout, stderr);
            });
        }
662836
def main():
    """"""

    if '--' in sys.argv:
        cli_args = sys.argv[1:sys.argv.index('--')]
        backend_args = sys.argv[sys.argv.index('--') + 1:]
    else:
        cli_args = sys.argv[1:]
        backend_args = []

    args = _cmdline_parser.parse_args(cli_args)
    debug = False
    if args.verbose is None:
        logging_level = logging.WARNING
    elif args.verbose == 1:
        logging_level = logging.INFO
    elif args.verbose == 2:
        logging_level = logging.DEBUG
        debug = True
    else:
        print('error: I can only be so garrulous, try -vv.', file=sys.stderr)
        sys.exit(1)

    logging.basicConfig(level=logging_level)

    if args.spec and args.spec[0].startswith('+') and args.spec[0].endswith('.py'):
        # Hack: Special case for defining a spec in Python for testing purposes
        # Use this if you want to define a Stone spec using a Python module.
        # The module should should contain an api variable that references a
        # :class:`stone.api.Api` object.
        try:
            api = imp.load_source('api', args.api[0]).api  # pylint: disable=redefined-outer-name
        except ImportError as e:
            print('error: Could not import API description due to:',
                  e, file=sys.stderr)
            sys.exit(1)
    else:
        if args.spec:
            specs = []
            read_from_stdin = False
            for spec_path in args.spec:
                if spec_path == '-':
                    read_from_stdin = True
                elif not spec_path.endswith('.stone'):
                    print("error: Specification '%s' must have a .stone extension."
                          % spec_path,
                          file=sys.stderr)
                    sys.exit(1)
                elif not os.path.exists(spec_path):
                    print("error: Specification '%s' cannot be found." % spec_path,
                          file=sys.stderr)
                    sys.exit(1)
                else:
                    with open(spec_path) as f:
                        specs.append((spec_path, f.read()))
            if read_from_stdin and specs:
                print("error: Do not specify stdin and specification files "
                      "simultaneously.", file=sys.stderr)
                sys.exit(1)

        if not args.spec or read_from_stdin:
            specs = []
            if debug:
                print('Reading specification from stdin.')

            if six.PY2:
                UTF8Reader = codecs.getreader('utf8')
                sys.stdin = UTF8Reader(sys.stdin)
                stdin_text = sys.stdin.read()
            else:
                stdin_buffer = sys.stdin.buffer  # pylint: disable=no-member,useless-suppression
                stdin_text = io.TextIOWrapper(stdin_buffer, encoding='utf-8').read()

            parts = stdin_text.split('namespace')
            if len(parts) == 1:
                specs.append(('stdin.1', parts[0]))
            else:
                specs.append(
                    ('stdin.1', '%snamespace%s' % (parts.pop(0), parts.pop(0))))
                while parts:
                    specs.append(('stdin.%s' % (len(specs) + 1),
                                  'namespace%s' % parts.pop(0)))

        if args.filter_by_route_attr:
            route_filter, route_filter_errors = parse_route_attr_filter(
                args.filter_by_route_attr, debug)
            if route_filter_errors:
                print('Error(s) in route filter:', file=sys.stderr)
                for err in route_filter_errors:
                    print(err, file=sys.stderr)
                sys.exit(1)

        else:
            route_filter = None

        if args.route_whitelist_filter:
            with open(args.route_whitelist_filter) as f:
                route_whitelist_filter = json.loads(f.read())
        else:
            route_whitelist_filter = None

        try:
            # TODO: Needs version
            api = specs_to_ir(specs, debug=debug,
                              route_whitelist_filter=route_whitelist_filter)
        except InvalidSpec as e:
            print('%s:%s: error: %s' % (e.path, e.lineno, e.msg), file=sys.stderr)
            if debug:
                print('A traceback is included below in case this is a bug in '
                      'Stone.\n', traceback.format_exc(), file=sys.stderr)
            sys.exit(1)
        if api is None:
            print('You must fix the above parsing errors for generation to '
                  'continue.', file=sys.stderr)
            sys.exit(1)

        if args.whitelist_namespace_routes:
            for namespace_name in args.whitelist_namespace_routes:
                if namespace_name not in api.namespaces:
                    print('error: Whitelisted namespace missing from spec: %s' %
                          namespace_name, file=sys.stderr)
                    sys.exit(1)
            for namespace in api.namespaces.values():
                if namespace.name not in args.whitelist_namespace_routes:
                    namespace.routes = []
                    namespace.route_by_name = {}
                    namespace.routes_by_name = {}

        if args.blacklist_namespace_routes:
            for namespace_name in args.blacklist_namespace_routes:
                if namespace_name not in api.namespaces:
                    print('error: Blacklisted namespace missing from spec: %s' %
                          namespace_name, file=sys.stderr)
                    sys.exit(1)
                else:
                    namespace = api.namespaces[namespace_name]
                    namespace.routes = []
                    namespace.route_by_name = {}
                    namespace.routes_by_name = {}

        if route_filter:
            for namespace in api.namespaces.values():
                filtered_routes = []
                for route in namespace.routes:
                    if route_filter.eval(route):
                        filtered_routes.append(route)

                namespace.routes = []
                namespace.route_by_name = {}
                namespace.routes_by_name = {}
                for route in filtered_routes:
                    namespace.add_route(route)

        if args.attribute:
            attrs = set(args.attribute)
            if ':all' in attrs:
                attrs = {field.name for field in api.route_schema.fields}
        else:
            attrs = set()

        for namespace in api.namespaces.values():
            for route in namespace.routes:
                for k in list(route.attrs.keys()):
                    if k not in attrs:
                        del route.attrs[k]

        # Remove attrs that weren't specified from the route schema
        for field in api.route_schema.fields[:]:
            if field.name not in attrs:
                api.route_schema.fields.remove(field)
                del api.route_schema._fields_by_name[field.name]
            else:
                attrs.remove(field.name)

        # Error if specified attr isn't even a field in the route schema
        if attrs:
            attr = attrs.pop()
            print('error: Attribute not defined in stone_cfg.Route: %s' %
                  attr, file=sys.stderr)
            sys.exit(1)

    if args.backend in _builtin_backends:
        backend_module = __import__(
            'stone.backends.%s' % args.backend, fromlist=[''])
    elif not os.path.exists(args.backend):
        print("error: Backend '%s' cannot be found." % args.backend,
              file=sys.stderr)
        sys.exit(1)
    elif not os.path.isfile(args.backend):
        print("error: Backend '%s' must be a file." % args.backend,
              file=sys.stderr)
        sys.exit(1)
    elif not Compiler.is_stone_backend(args.backend):
        print("error: Backend '%s' must have a .stoneg.py extension." %
              args.backend, file=sys.stderr)
        sys.exit(1)
    else:
        # A bit hacky, but we add the folder that the backend is in to our
        # python path to support the case where the backend imports other
        # files in its local directory.
        new_python_path = os.path.dirname(args.backend)
        if new_python_path not in sys.path:
            sys.path.append(new_python_path)
        try:
            backend_module = imp.load_source('user_backend', args.backend)
        except Exception:
            print("error: Importing backend '%s' module raised an exception:" %
                  args.backend, file=sys.stderr)
            raise

    c = Compiler(
        api,
        backend_module,
        backend_args,
        args.output,
        clean_build=args.clean_build,
    )
    try:
        c.build()
    except BackendException as e:
        print('%s: error: %s raised an exception:\n%s' %
              (args.backend, e.backend_name, e.traceback),
              file=sys.stderr)
        sys.exit(1)

    if not sys.argv[0].endswith('stone'):
        # If we aren't running from an entry_point, then return api to make it
        # easier to do debugging.
        return api
467051
def cli_action(args):
    
    problem = read_param_file(args.paramfile)
    param_values = sample(problem, seed=args.seed)
    np.savetxt(args.output, param_values, delimiter=args.delimiter,
               fmt='%.' + str(args.precision) + 'e')
965960
def main(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser(description="""Aggregate results of
            nestly runs""")
    subparsers = parser.add_subparsers()
    delim_parser = subparsers.add_parser('delim', help="""Combine control files
            with delimited files.""")
    delim_parser.set_defaults(func=delim)
    key_group = delim_parser.add_mutually_exclusive_group()
    key_group.add_argument('-k', '--keys', help="""Comma separated list of
            keys from the JSON file to include [default: all keys]""",
            type=comma_separated_values)
    key_group.add_argument('-x', '--exclude-keys', help="""Comma separated
            list of keys from the JSON file not to include [default:
            %(default)s]""", type=comma_separated_values)
    delim_parser.add_argument('-m', '--missing-action', choices=('fail',
        'warn'), help="""Action to take when a file is missing [default:
        %(default)s]""", default='fail')
    delim_parser.add_argument('file_template', help="""Template for the
            delimited file to read in each directory [e.g. '{run_id}.csv']""")
    delim_parser.add_argument('control_files', metavar="control.json",
            help="""Control files""", nargs="*")
    delim_parser.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    delim_parser.add_argument('-s', '--separator', default=DEFAULT_SEP,
            help="""Separator [default: %(default)s]""")
    delim_parser.add_argument('-t', '--tab', action='store_const',
            dest='separator', const='\t', help="""Files are tab-separated""")
    delim_parser.add_argument('-o', '--output', default=sys.stdout,
        type=argparse.FileType('w'), help="""Output file [default: stdout]""")

    arguments = parser.parse_args()

    arguments.func(arguments)