This procedure is invoked to process the "subst" Tcl command.
See the user documentation for details on what it does.

@param interp the current interpreter.
@param argv command arguments.
@exception TclException if wrong # of args or invalid argument(s).
542035
public void cmdProc(Interp interp, TclObject argv[])
    throws TclException {
        int currentObjIndex, len, i;
        int objc = argv.length - 1;
        boolean doBackslashes = true;
        boolean doCmds = true;
        boolean doVars = true;
        StringBuffer result = new StringBuffer();
        String s;
        char c;

        for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) {
            if (!argv[currentObjIndex].toString().startsWith("-")) {
                break;
            }
            int opt = TclIndex.get(interp, argv[currentObjIndex],
                            validCmds, "switch", 0);
            switch (opt) {
                case OPT_NOBACKSLASHES:
                    doBackslashes = false;
                    break;
                case OPT_NOCOMMANDS:
                    doCmds = false;
                    break;
                case OPT_NOVARS:
                    doVars = false;
                    break;
                default:
                    throw new TclException(interp,
                                    "SubstCrCmd.cmdProc: bad option " + opt
                                    + " index to cmds");
            }
        }
        if (currentObjIndex != objc) {
            throw new TclNumArgsException(interp, currentObjIndex, argv,
                            "?-nobackslashes? ?-nocommands? ?-novariables? string");
        }

        /*
         * Scan through the string one character at a time, performing
         * command, variable, and backslash substitutions.
         */

        s = argv[currentObjIndex].toString();
        len = s.length();
        i = 0;
        while (i < len) {
            c = s.charAt(i);

            if ((c == '[') && doCmds) {
                ParseResult res;
                try {
                    interp.evalFlags = Parser.TCL_BRACKET_TERM;
                    interp.eval(s.substring(i + 1, len));
                    TclObject interp_result = interp.getResult();
                    interp_result.preserve();
                    res = new ParseResult(interp_result,
                                    i + interp.termOffset);
                } catch (TclException e) {
                    i = e.errIndex + 1;
                    throw e;
                }
                i = res.nextIndex + 2;
                result.append( res.value.toString() );
                res.release();
                /**
                 * Removed
                 (ToDo) may not be portable on Mac
                } else if (c == '\r') {
                   i++;
                 */
            } else if ((c == '$') && doVars) {
                ParseResult vres = Parser.parseVar(interp,
                                s.substring(i, len));
                i += vres.nextIndex;
                result.append( vres.value.toString() );
                vres.release();
            } else if ((c == '\\') && doBackslashes) {
                BackSlashResult bs = Interp.backslash(s, i, len);
                i = bs.nextIndex;
                if (bs.isWordSep) {
                    break;
                } else {
                    result.append( bs.c );
                }
            } else {
                result.append( c );
                i++;
            }
        }

        interp.setResult(result.toString());
    }
466716
def unrecognized_arguments_error(self, args, parsed, extras):
        

        # loop variants
        kwargs = vars(parsed)
        failed = list(extras)
        # initial values
        runtime, subparser, idx = (self, self.argparser, 0)
        # recursion not actually needed when it can be flattened.
        while isinstance(runtime, Runtime):
            cmd = kwargs.pop(runtime.action_key)
            # can happen if it wasn't set, or is set but from a default
            # value (thus not provided by args)
            action_idx = None if cmd not in args else args.index(cmd)
            if cmd not in args and cmd is not None:
                # this normally shouldn't happen, and the test case
                # showed that the parsing will not flip down to the
                # forced default subparser - this can remain a debug
                # message until otherwise.
                logger.debug(
                    "command for prog=%r is set to %r without being specified "
                    "as part of the input arguments - the following error "
                    "message may contain misleading references",
                    subparser.prog, cmd
                )
            subargs = args[idx:action_idx]
            subparsed, subextras = subparser.parse_known_args(subargs)
            if subextras:
                subparser.unrecognized_arguments_error(subextras)
                # since the failed arguments are in order
                failed = failed[len(subextras):]
                if not failed:
                    # have taken everything, quit now.
                    # also note that if cmd was really None it would
                    # cause KeyError below, but fortunately it also
                    # forced action_idx to be None which took all
                    # remaining tokens from failed, so definitely get
                    # out of here.
                    break

            # advance the values
            # note that any internal consistency will almost certainly
            # result in KeyError being raised.
            details = runtime.get_argparser_details(subparser)
            runtime = details.runtimes[cmd]
            subparser = details.subparsers[cmd]
            idx = action_idx + 1

        if failed:
            subparser.unrecognized_arguments_error(failed)
        sys.exit(2)
578629
protected void processSystemArg(DefaultCommandLine cl, String arg) {
        int i = arg.indexOf("=");
        String name = arg.substring(2, i);
        String value = arg.substring(i + 1, arg.length());
        cl.addSystemProperty(name, value);
    }
1219133
public static void main(String argv[])
    {
        String srcFile = "randam_orig.png";
        try
        {
            System.out.println("Reading: "+srcFile);
            BufferedImage src = ImageIO.read(new File(srcFile));
            ImageScale3x scaler = new ImageScale3x(src);
            BufferedImage out = scaler.getScaledImage();

            String outFile = srcFile.substring(0,srcFile.length()-4);
            outFile += "3x";
            outFile += ".png";
            System.out.println("Writing: "+outFile);
            ImageIO.write(out,"PNG",new File(outFile));
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
5933
public static void main(String[] args) throws Exception {
    ArgP argp = new ArgP();
    CliOptions.addCommon(argp);
    argp.addOption("--use-data-table",
        "Scan against the raw data table instead of the meta data table.");
    args = CliOptions.parse(argp, args);
    if (args == null) {
      usage(argp, "Invalid usage");
      System.exit(2);
    } else if (args.length < 1) {
      usage(argp, "Not enough arguments");
      System.exit(2);
    }
    
    final boolean use_data_table = argp.has("--use-data-table");
    
    Config config = CliOptions.getConfig(argp);
    final TSDB tsdb = new TSDB(config);
    tsdb.checkNecessaryTablesExist().joinUninterruptibly();
    
    int rc;
    try {
      rc = runCommand(tsdb, use_data_table, args);
    } finally {
      try {
        tsdb.getClient().shutdown().joinUninterruptibly();
        LOG.info("Gracefully shutdown the TSD");
      } catch (Exception e) {
        LOG.error("Unexpected exception while shutting down", e);
        rc = 42;
      }
    }
    System.exit(rc);
  }
1170336
private int doall(String cmd, String argv[], int startindex) {
    int exitCode = 0;
    int i = startindex;
    boolean rmSkipTrash = false;
    
    // Check for -skipTrash option in rm/rmr
    if(("-rm".equals(cmd) || "-rmr".equals(cmd)) 
        && "-skipTrash".equals(argv[i])) {
      rmSkipTrash = true;
      i++;
    }

    //
    // for each source file, issue the command
    //
    for (; i < argv.length; i++) {
      try {
        //
        // issue the command to the fs
        //
        if ("-cat".equals(cmd)) {
          cat(argv[i], true);
        } else if ("-du".equals(cmd)) {
          du(argv[i]);
        } else if ("-dus".equals(cmd)) {
          dus(argv[i]);
        } else if (Count.matches(cmd)) {
          new Count(argv, i, getConf()).runAll();
        } else if ("-text".equals(cmd)) {
          text(argv[i]);
        } else if ("-decompress".equals(cmd)) {
          decompress(argv[i]);
        }
      } catch (RemoteException e) {
        //
        // This is a error returned by hadoop server. Print
        // out the first line of the error message.
        //
        exitCode = -1;
        try {
          String[] content;
          content = e.getLocalizedMessage().split("\n");
          System.err.println(cmd.substring(1) + ": " +
                             content[0]);
        } catch (Exception ex) {
          System.err.println(cmd.substring(1) + ": " +
                             ex.getLocalizedMessage());
        }
      } catch (IOException e) {
        //
        // IO exception encountered locally.
        //
        exitCode = -1;
        String content = e.getLocalizedMessage();
        if (content != null) {
          content = content.split("\n")[0];
        }
        System.err.println(cmd.substring(1) + ": " +
                          content);
      }
    }
    return exitCode;
  }
632665
public static void main(String[] args) {

        JLAN_DISABLED = true;
        boolean wrongUsage = false;
        String webInfPath = null;
        String script = null;
        String servletMapping = null;
        String defaultWebApp = null;
        String additional = null;
        int errorCode = -1;
        if (args.length > 4) {
            wrongUsage = true;
        } else {
            for (int i = 0; i < args.length; i++) {
                String arg = args[i];
                if (arg.startsWith(SHELL_PARAM_BASE)) {
                    webInfPath = arg.substring(SHELL_PARAM_BASE.length());
                } else if (arg.startsWith(SHELL_PARAM_SCRIPT)) {
                    script = arg.substring(SHELL_PARAM_SCRIPT.length());
                } else if (arg.startsWith(SHELL_PARAM_SERVLET_MAPPING)) {
                    servletMapping = arg.substring(SHELL_PARAM_SERVLET_MAPPING.length());
                } else if (arg.startsWith(SHELL_PARAM_DEFAULT_WEB_APP)) {
                    defaultWebApp = arg.substring(SHELL_PARAM_DEFAULT_WEB_APP.length());
                } else if (arg.startsWith(SHELL_PARAM_ADDITIONAL_COMMANDS)) {
                    additional = arg.substring(SHELL_PARAM_ADDITIONAL_COMMANDS.length());
                } else if (arg.startsWith(SHELL_PARAM_ERROR_CODE)) {
                    errorCode = Integer.valueOf(arg.substring(SHELL_PARAM_ERROR_CODE.length())).intValue();
                } else if (arg.startsWith(SHELL_PARAM_JLAN)) {
                    JLAN_DISABLED = false;
                } else {
                    System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_WRONG_USAGE_0));
                    wrongUsage = true;
                }
            }
        }
        if (wrongUsage) {
            System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_USAGE_1, CmsShell.class.getName()));
        } else {

            I_CmsShellCommands additionalCommands = null;
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additional)) {
                try {
                    Class<?> commandClass = Class.forName(additional);
                    additionalCommands = (I_CmsShellCommands)commandClass.newInstance();
                } catch (Exception e) {
                    System.out.println(
                        Messages.get().getBundle().key(Messages.GUI_SHELL_ERR_ADDITIONAL_COMMANDS_1, additional));
                    e.printStackTrace();
                    return;
                }
            }
            boolean interactive = true;
            FileInputStream stream = null;
            if (script != null) {
                try {
                    stream = new FileInputStream(script);
                } catch (IOException exc) {
                    System.out.println(Messages.get().getBundle().key(Messages.GUI_SHELL_ERR_SCRIPTFILE_1, script));
                }
            }
            if (stream == null) {
                // no script-file, use standard input stream
                stream = new FileInputStream(FileDescriptor.in);
                interactive = true;
            }
            CmsShell shell = new CmsShell(
                webInfPath,
                servletMapping,
                defaultWebApp,
                "${user}@${project}:${siteroot}|${uri}>",
                additionalCommands,
                System.out,
                System.err,
                interactive);
            shell.m_errorCode = errorCode;
            shell.execute(stream);
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
678807
private void check_args(final String argv[]) {

	if (argv[0].charAt(0) == '-') {
	    if (argv[0].equals("-?")) {
		print_usage();
		printInstanceNames();
		System.exit(0);
	    } else {
		print_usage();
		System.exit(-1);
	    }
	}
	ds_instance_name = argv[0];

	if (argv.length > 1) {
	    int ind = 1;
	    String dlist;
	    while (ind < argv.length) {
		if (argv[ind].charAt(0) == '-') {
		    switch (argv[ind].charAt(1)) {

		    //
		    // The verbose option
		    //

		    case 'v':
			if (argv[ind].length() == 2) {
			    if (argv.length - 1 > ind) {
				if (argv[ind + 1].charAt(0) == '-') {
				    set_trace_level(4);
				} else {
				    print_usage();
				    System.exit(-1);
				}
			    } else {
				set_trace_level(4);
			    }
			    ind++;
			} else {
			    final String level_str = argv[ind].substring(2);
			    int level = 0;
			    try {
				level = Integer.parseInt(level_str);
			    } catch (final NumberFormatException ex) {
				print_usage();
				System.exit(-1);
			    }

			    set_trace_level(level);
			    ind++;
			}
			break;

		    //
		    // Device server without database
		    //

		    case 'n':
			if (argv[ind].equals("-nodb") == false) {
			    print_usage();
			    System.exit(-1);
			} else {
			    _UseDb = false;
			    ind++;
			}
			break;

		    //
		    // Device list (for device server without database)
		    //

		    case 'd':
			if (argv[ind].equals("-dlist") == false) {
			    print_usage();
			    System.exit(-1);
			} else {
			    if (_UseDb == true) {
				print_usage();
				System.exit(-1);
			    }

			    ind++;
			    if (ind == argv.length) {
				print_usage();
				System.exit(-1);
			    } else {
				dlist = argv[ind].toLowerCase();

				//
				// Extract each device name
                    //
				String str;
				int start = 0;
				int pos;

				while ((pos = dlist.indexOf(',', start)) != -1) {
				    str = dlist.substring(start, pos);
				    start = pos + 1;
				    cmd_line_name_list.addElement(str);
				}
				if (start != dlist.length()) {
				    str = dlist.substring(start);
				    cmd_line_name_list.addElement(str);
				}

				//
				// Check that the same device name is not used
				// twice
				//

				int i, j;
				for (i = 0; i < cmd_line_name_list.size(); i++) {
				    for (j = 0; j < cmd_line_name_list.size(); j++) {
					if (i != j) {
					    if (cmd_line_name_list.elementAt(i).equals(
						    cmd_line_name_list.elementAt(j))) {
						System.err
							.println("Each device name must have different name");
						System.exit(-1);
					    }
					}
				    }
				}

			    }
			}
			break;

		    default:
			ind++;
			break;
		    }
		} else {
		    if (argv[ind - 1].substring(0, 2).equals("-v")) {
			print_usage();
			System.exit(-1);
		    }
		    ind++;
		}
	    }
	}

	//
	// Build server name in lower-case letters
	//

	real_server_name = ds_exec_name + "/" + ds_instance_name;
	ds_exec_name = ds_exec_name.toLowerCase();
	ds_instance_name = ds_instance_name.toLowerCase();

	ds_name = new StringBuffer(ds_exec_name);
	ds_name.append("/");
	ds_name.append(ds_instance_name);

	//
	// Check that the server name is not too long
	//

	if (ds_name.length() > Tango_MaxServerNameLength) {
	    System.err.println("The device server name is too long! Max length is "
		    + Tango_MaxServerNameLength + " characters.");
	    System.exit(-1);
	}
    }
362670
function invokeCommand(command, argv, isInternalCommand) {

  const globs = getGlobs();

  if (globs.length === 0) {
    return invokeCommandError(command, isInternalCommand);
  }

  const modulesAnswered = getModulesAnswered(command, argv, globs);
  const modulesAnsweredLength = modulesAnswered.length;

  if (modulesAnsweredLength === 0) {
    return invokeCommandError(command, isInternalCommand);
  }

  const modulesAnsweredPlural = modulesAnsweredLength === 1 ? 'module' : 'modules';

  logger.verbose(
    `Successfully passed ${command} to ${modulesAnsweredLength} ${modulesAnsweredPlural}:`
  );
  logger.verbose(modulesAnswered.join(', '));
}
739342
public static void main(String[] argv) throws Exception {
    System.exit(ToolRunner.run(null, new PiEstimator(), argv));
  }
1244805
public static void main(String[] args) throws Exception {

    try {

      RulePrunerParameters params = new RulePrunerParameters();
      JCommander jct = new JCommander(params, args);

      if (0 == args.length) {
        jct.usage();
      }
      else {

        // get params printed
        //
        StringBuffer sb = new StringBuffer(1024);
        sb.append("Rule pruner CLI v.1").append(CR);
        sb.append("parameters:").append(CR);

        sb.append("  input file:           ").append(RulePrunerParameters.IN_FILE).append(CR);
        sb.append("  output file:          ").append(RulePrunerParameters.OUT_FILE).append(CR);
        sb.append("  SAX num. reduction:   ").append(RulePrunerParameters.SAX_NR_STRATEGY)
            .append(CR);
        sb.append("  SAX norm. threshold:  ").append(RulePrunerParameters.SAX_NORM_THRESHOLD)
            .append(CR);
        sb.append("  GI Algorithm:         ")
            .append(RulePrunerParameters.GI_ALGORITHM_IMPLEMENTATION).append(CR);
        sb.append("  Grid boundaries:      ").append(RulePrunerParameters.GRID_BOUNDARIES)
            .append(CR);

        if (!(Double.isNaN(RulePrunerParameters.SUBSAMPLING_FRACTION))) {
          sb.append("  Subsampling fraction: ").append(RulePrunerParameters.SUBSAMPLING_FRACTION)
              .append(CR);
        }

        // printer out the params before starting
        System.err.print(sb.toString());

        // read the data in
        String dataFName = RulePrunerParameters.IN_FILE;
        double[] ts = TSProcessor.readFileColumn(dataFName, 0, 0);
        if (!(Double.isNaN(RulePrunerParameters.SUBSAMPLING_FRACTION))) {
          ts = Arrays.copyOfRange(ts, 0,
              (int) Math.round((double) ts.length * RulePrunerParameters.SUBSAMPLING_FRACTION));
        }

        // printer out the params before starting
        System.err.println("  working with series of " + ts.length + " points ... " + CR);

        // parse the boundaries params
        int[] boundaries = toBoundaries(RulePrunerParameters.GRID_BOUNDARIES);

        // create the output file
        BufferedWriter bw = new BufferedWriter(
            new FileWriter(new File(RulePrunerParameters.OUT_FILE)));
        bw.write(OUTPUT_HEADER);

        ArrayList<SampledPoint> res = new ArrayList<SampledPoint>();

        // we need to use this in the loop
        RulePruner rp = new RulePruner(ts);

        // iterate over the grid evaluating the grammar
        //
        for (int WINDOW_SIZE = boundaries[0]; WINDOW_SIZE < boundaries[1]; WINDOW_SIZE += boundaries[2]) {
          for (int PAA_SIZE = boundaries[3]; PAA_SIZE < boundaries[4]; PAA_SIZE += boundaries[5]) {

            // check for invalid cases
            if (PAA_SIZE > WINDOW_SIZE) {
              continue;
            }

            for (int ALPHABET_SIZE = boundaries[6]; ALPHABET_SIZE < boundaries[7]; ALPHABET_SIZE += boundaries[8]) {

              SampledPoint p = rp.sample(WINDOW_SIZE, PAA_SIZE, ALPHABET_SIZE,
                  RulePrunerParameters.GI_ALGORITHM_IMPLEMENTATION,
                  RulePrunerParameters.SAX_NR_STRATEGY, RulePrunerParameters.SAX_NORM_THRESHOLD);

              bw.write(p.toLogString() + "\n");

              res.add(p);
            }
          }
        }

        bw.close();

        Collections.sort(res, new ReductionSorter());

        System.out.println("\nApparently, the best parameters are " + res.get(0).toString());

      }
    }
    catch (Exception e) {
      System.err.println("error occured while parsing parameters " + Arrays.toString(args) + CR
          + StackTrace.toString(e));
      System.exit(-1);
    }

  }
48739
public static void main(String argv[]) throws Exception {   
    DnsMonitorSecurityManager.setTheManager();
    AvatarShell shell = null;
    try {
      shell = new AvatarShell();
    } catch (RPC.VersionMismatch v) {
      System.err.println("Version Mismatch between client and server"
          + "... command aborted.");
      System.exit(-1);
    } catch (IOException e) {
      System.err.println("Bad connection to AvatarNode. command aborted.");
      System.exit(-1);
    }

    int res;
    try {
      res = ToolRunner.run(shell, argv);
    } finally {
      shell.close();
    }
    System.exit(res);
  }
1303150
public static void main(String[] args) throws Exception {

		final ParameterTool params = ParameterTool.fromArgs(args);

		// set up the execution environment
		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		// make parameters available in the web interface
		env.getConfig().setGlobalJobParameters(params);

		// get input data
		DataSet<String> text;
		if (params.has("input")) {
			// read the text file from given input path
			text = env.readTextFile(params.get("input"));
		} else {
			// get default test text data
			System.out.println("Executing WordCount example with default input data set.");
			System.out.println("Use --input to specify file input.");
			text = WordCountData.getDefaultTextLineDataSet(env);
		}

		DataSet<Tuple2<String, Integer>> counts =
				// split up the lines in pairs (2-tuples) containing: (word,1)
				text.flatMap(new Tokenizer())
				// group by the tuple field "0" and sum up tuple field "1"
				.groupBy(0)
				.sum(1);

		// emit result
		if (params.has("output")) {
			counts.writeAsCsv(params.get("output"), "\n", " ");
			// execute program
			env.execute("WordCount Example");
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			counts.print();
		}

	}
139546
public boolean run(String... arguments) throws Exception {
        try {
            if (isFlag(HELP, arguments)) {
                parser.printHelp(stdOut);
            } else if (isFlag(VERSION, arguments)) {
                parser.printVersion(stdOut);
            } else {
                final Namespace namespace = parser.parseArgs(arguments);
                final Command command = requireNonNull(commands.get(namespace.getString(COMMAND_NAME_ATTR)),
                    "Command is not found");
                try {
                    command.run(bootstrap, namespace);
                } catch (Throwable e) {
                    // The command failed to run, and the command knows
                    // best how to cleanup / debug exception
                    command.onError(this, namespace, e);
                    return false;
                }
            }
            return true;
        } catch (HelpScreenException ignored) {
            // This exception is triggered when the user passes in a help flag.
            // Return true to signal that the process executed normally.
            return true;
        } catch (ArgumentParserException e) {
            stdErr.println(e.getMessage());
            e.getParser().printHelp(stdErr);
            return false;
        }
    }
1316796
public void run(ExpectState state) throws Exception {
        int flags = 0; // TCL.NAMESPACE_ONLY

        // TODO Inject expect object, so that expect wrapper can access it
        // clear previous expect_out
        //interp.unsetVar("expect_out", flags);

        String buffer = state.getBuffer();
        logger.trace("Setting var expect_out(buffer) to " + buffer);
        interp.setVar("expect_out", "buffer", buffer, flags);

        int group = 0;
        while(true) {
            String match = state.getMatch(group);
            String index = group + ",string";
            group++;
            if( match == null )
                break;
            logger.trace("Setting var expect_out(" + index +") to " + match);
            interp.setVar("expect_out", index , match, flags);
        }

        ExpectEmulation.setExpContinue(interp, false);

        if( tclCode != null && tclCode.toString().length() > 0 ) {
            logger.debug("Running a tcl bit of code: " + tclCode.toString());

            try {
                interp.eval(tclCode, 0);
            } catch(TclException e) {
                logger.warn("Exception: " + e);
                throw new Exception( interp.getResult().toString(), e);
            }
            if( ExpectEmulation.isExpContinue(interp) ) {
                logger.info("Asked to continue");
                state.exp_continue();
            }
        }
        //interp.unsetVar("expect_out", flags);

    }
1174950
public static void main(String[] argv) {
    if (argv.length == 0) {
      printUsage("");
      System.exit(-1);
    }

    String inputPathsString = null;
    Path outputPath = null;
    String shardsString = null;
    String indexPath = null;
    int numShards = -1;
    int numMapTasks = -1;
    Configuration conf = new Configuration();
    String confPath = null;

    // parse the command line
    for (int i = 0; i < argv.length; i++) { // parse command line
      if (argv[i].equals("-inputPaths")) {
        inputPathsString = argv[++i];
      } else if (argv[i].equals("-outputPath")) {
        outputPath = new Path(argv[++i]);
      } else if (argv[i].equals("-shards")) {
        shardsString = argv[++i];
      } else if (argv[i].equals("-indexPath")) {
        indexPath = argv[++i];
      } else if (argv[i].equals("-numShards")) {
        numShards = Integer.parseInt(argv[++i]);
      } else if (argv[i].equals("-numMapTasks")) {
        numMapTasks = Integer.parseInt(argv[++i]);
      } else if (argv[i].equals("-conf")) {
        // add as a local FS resource
        confPath = argv[++i];
        conf.addResource(new Path(confPath));
      } else {
        System.out.println("Unknown option " + argv[i] + " w/ value "
            + argv[++i]);
      }
    }
    LOG.info("inputPaths = " + inputPathsString);
    LOG.info("outputPath = " + outputPath);
    LOG.info("shards     = " + shardsString);
    LOG.info("indexPath  = " + indexPath);
    LOG.info("numShards  = " + numShards);
    LOG.info("numMapTasks= " + numMapTasks);
    LOG.info("confPath   = " + confPath);

    Path[] inputPaths = null;
    Shard[] shards = null;

    JobConf jobConf = new JobConf(conf);
    IndexUpdateConfiguration iconf = new IndexUpdateConfiguration(jobConf);

    if (inputPathsString != null) {
      jobConf.set("mapred.input.dir", inputPathsString);
    }
    inputPaths = FileInputFormat.getInputPaths(jobConf);
    if (inputPaths.length == 0) {
      inputPaths = null;
    }

    if (outputPath == null) {
      outputPath = FileOutputFormat.getOutputPath(jobConf);
    }

    if (inputPaths == null || outputPath == null) {
      System.err.println("InputPaths and outputPath must be specified.");
      printUsage("");
      System.exit(-1);
    }

    if (shardsString != null) {
      iconf.setIndexShards(shardsString);
    }
    shards = Shard.getIndexShards(iconf);
    if (shards != null && shards.length == 0) {
      shards = null;
    }

    if (indexPath == null) {
      indexPath = getIndexPath(conf);
    }
    if (numShards <= 0) {
      numShards = getNumShards(conf);
    }

    if (shards == null && indexPath == null) {
      System.err.println("Either shards or indexPath must be specified.");
      printUsage("");
      System.exit(-1);
    }

    if (numMapTasks <= 0) {
      numMapTasks = jobConf.getNumMapTasks();
    }

    try {
      // create shards and set their directories if necessary
      if (shards == null) {
        shards = createShards(indexPath, numShards, conf);
      }

      long startTime = now();
      try {
        IIndexUpdater updater =
            (IIndexUpdater) ReflectionUtils.newInstance(
                iconf.getIndexUpdaterClass(), conf);
        LOG.info("sea.index.updater = "
            + iconf.getIndexUpdaterClass().getName());

        updater.run(conf, inputPaths, outputPath, numMapTasks, shards);
        LOG.info("Index update job is done");

      } finally {
        long elapsedTime = now() - startTime;
        LOG.info("Elapsed time is  " + (elapsedTime / 1000) + "s");
        System.out.println("Elapsed time is " + (elapsedTime / 1000) + "s");
      }
    } catch (Exception e) {
      e.printStackTrace(System.err);
    }
  }
357256
public static void main(String[] args) throws Exception {

		// Checking input parameters
		final ParameterTool params = ParameterTool.fromArgs(args);

		// set up input for the stream of integer pairs

		// obtain execution environment and set setBufferTimeout to 1 to enable
		// continuous flushing of the output buffers (lowest latency)
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment()
				.setBufferTimeout(1);

		// make parameters available in the web interface
		env.getConfig().setGlobalJobParameters(params);

		// create input stream of integer pairs
		DataStream<Tuple2<Integer, Integer>> inputStream;
		if (params.has("input")) {
			inputStream = env.readTextFile(params.get("input")).map(new FibonacciInputMap());
		} else {
			System.out.println("Executing Iterate example with default input data set.");
			System.out.println("Use --input to specify file input.");
			inputStream = env.addSource(new RandomFibonacciSource());
		}

		// create an iterative data stream from the input with 5 second timeout
		IterativeStream<Tuple5<Integer, Integer, Integer, Integer, Integer>> it = inputStream.map(new InputMap())
				.iterate(5000);

		// apply the step function to get the next Fibonacci number
		// increment the counter and split the output with the output selector
		SplitStream<Tuple5<Integer, Integer, Integer, Integer, Integer>> step = it.map(new Step())
				.split(new MySelector());

		// close the iteration by selecting the tuples that were directed to the
		// 'iterate' channel in the output selector
		it.closeWith(step.select("iterate"));

		// to produce the final output select the tuples directed to the
		// 'output' channel then get the input pairs that have the greatest iteration counter
		// on a 1 second sliding window
		DataStream<Tuple2<Tuple2<Integer, Integer>, Integer>> numbers = step.select("output")
				.map(new OutputMap());

		// emit results
		if (params.has("output")) {
			numbers.writeAsText(params.get("output"));
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			numbers.print();
		}

		// execute the program
		env.execute("Streaming Iteration Example");
	}