List of usage examples for java.lang Integer parseInt
public static int parseInt(String s) throws NumberFormatException
From source file:mase.stat.MasterTournament.java
public static void main(String[] args) throws Exception { List<File> sampleFolders = new ArrayList<>(); List<File> testFolders = new ArrayList<>(); int freq = 0; String name = ""; boolean self = false; String individuals = null;/*from w ww.j a v a2 s. c o m*/ int elite = 0; for (int x = 0; x < args.length; x++) { if (args[x].equalsIgnoreCase(TEST_FOLDER)) { File folder = new File(args[1 + x++]); if (!folder.exists()) { throw new Exception("Folder does not exist: " + folder.getAbsolutePath()); } testFolders.add(folder); } else if (args[x].equalsIgnoreCase(SAMPLE_FOLDER)) { File folder = new File(args[1 + x++]); if (!folder.exists()) { throw new Exception("Folder does not exist: " + folder.getAbsolutePath()); } sampleFolders.add(folder); } else if (args[x].equalsIgnoreCase(BOTH_FOLDER)) { File folder = new File(args[1 + x++]); if (!folder.exists()) { throw new Exception("Folder does not exist: " + folder.getAbsolutePath()); } sampleFolders.add(folder); testFolders.add(folder); } else if (args[x].equalsIgnoreCase(FREQUENCY)) { freq = Integer.parseInt(args[1 + x++]); } else if (args[x].equalsIgnoreCase(ELITE)) { elite = Integer.parseInt(args[1 + x++]); } else if (args[x].equalsIgnoreCase(OUTNAME)) { name = args[1 + x++]; } else if (args[x].equalsIgnoreCase(SELF)) { self = true; } else if (args[x].equalsIgnoreCase(INDIVIDUALS)) { individuals = args[1 + x++]; } } if (testFolders.isEmpty() || sampleFolders.isEmpty()) { System.out.println("Nothing to evaluate!"); return; } MaseProblem sim = Reevaluate.createSimulator(args); MasterTournament mt = new MasterTournament(sampleFolders, testFolders, sim, name); if (individuals != null) { mt.makeIndsTournaments(individuals); } else if (self) { mt.makeSelfTournaments(freq); } else { mt.makeSampleTournaments(freq, elite); } mt.executor.shutdown(); }
From source file:hyperloglog.tools.HyperLogLogCLI.java
public static void main(String[] args) { Options options = new Options(); addOptions(options);/*w w w. j av a 2s. c o m*/ CommandLineParser parser = new BasicParser(); CommandLine cli = null; long n = 0; long seed = 123; EncodingType enc = EncodingType.SPARSE; int p = 14; int hb = 64; boolean bitPack = true; boolean noBias = true; int unique = -1; String filePath = null; BufferedReader br = null; String outFile = null; String inFile = null; FileOutputStream fos = null; DataOutputStream out = null; FileInputStream fis = null; DataInputStream in = null; try { cli = parser.parse(options, args); if (!(cli.hasOption('n') || cli.hasOption('f') || cli.hasOption('d'))) { System.out.println("Example usage: hll -n 1000 " + "<OR> hll -f /tmp/input.txt " + "<OR> hll -d -i /tmp/out.hll"); usage(options); return; } if (cli.hasOption('n')) { n = Long.parseLong(cli.getOptionValue('n')); } if (cli.hasOption('e')) { String value = cli.getOptionValue('e'); if (value.equals(EncodingType.DENSE.name())) { enc = EncodingType.DENSE; } } if (cli.hasOption('p')) { p = Integer.parseInt(cli.getOptionValue('p')); if (p < 4 && p > 16) { System.out.println("Warning! Out-of-range value specified for p. Using to p=14."); p = 14; } } if (cli.hasOption('h')) { hb = Integer.parseInt(cli.getOptionValue('h')); } if (cli.hasOption('c')) { noBias = Boolean.parseBoolean(cli.getOptionValue('c')); } if (cli.hasOption('b')) { bitPack = Boolean.parseBoolean(cli.getOptionValue('b')); } if (cli.hasOption('f')) { filePath = cli.getOptionValue('f'); br = new BufferedReader(new FileReader(new File(filePath))); } if (filePath != null && cli.hasOption('n')) { System.out.println("'-f' (input file) specified. Ignoring -n."); } if (cli.hasOption('s')) { if (cli.hasOption('o')) { outFile = cli.getOptionValue('o'); fos = new FileOutputStream(new File(outFile)); out = new DataOutputStream(fos); } else { System.err.println("Specify output file. Example usage: hll -s -o /tmp/out.hll"); usage(options); return; } } if (cli.hasOption('d')) { if (cli.hasOption('i')) { inFile = cli.getOptionValue('i'); fis = new FileInputStream(new File(inFile)); in = new DataInputStream(fis); } else { System.err.println("Specify input file. Example usage: hll -d -i /tmp/in.hll"); usage(options); return; } } // return after deserialization if (fis != null && in != null) { long start = System.currentTimeMillis(); HyperLogLog deserializedHLL = HyperLogLogUtils.deserializeHLL(in); long end = System.currentTimeMillis(); System.out.println(deserializedHLL.toString()); System.out.println("Count after deserialization: " + deserializedHLL.count()); System.out.println("Deserialization time: " + (end - start) + " ms"); return; } // construct hll and serialize it if required HyperLogLog hll = HyperLogLog.builder().enableBitPacking(bitPack).enableNoBias(noBias).setEncoding(enc) .setNumHashBits(hb).setNumRegisterIndexBits(p).build(); if (br != null) { Set<String> hashset = new HashSet<String>(); String line; while ((line = br.readLine()) != null) { hll.addString(line); hashset.add(line); } n = hashset.size(); } else { Random rand = new Random(seed); for (int i = 0; i < n; i++) { if (unique < 0) { hll.addLong(rand.nextLong()); } else { int val = rand.nextInt(unique); hll.addLong(val); } } } long estCount = hll.count(); System.out.println("Actual count: " + n); System.out.println(hll.toString()); System.out.println("Relative error: " + HyperLogLogUtils.getRelativeError(n, estCount) + "%"); if (fos != null && out != null) { long start = System.currentTimeMillis(); HyperLogLogUtils.serializeHLL(out, hll); long end = System.currentTimeMillis(); System.out.println("Serialized hyperloglog to " + outFile); System.out.println("Serialized size: " + out.size() + " bytes"); System.out.println("Serialization time: " + (end - start) + " ms"); out.close(); } } catch (ParseException e) { System.err.println("Invalid parameter."); usage(options); } catch (NumberFormatException e) { System.err.println("Invalid type for parameter."); usage(options); } catch (FileNotFoundException e) { System.err.println("Specified file not found."); usage(options); } catch (IOException e) { System.err.println("Exception occured while reading file."); usage(options); } }
From source file:edu.oregonstate.eecs.mcplan.domains.yahtzee2.YahtzeeClient.java
/** * @param args/* ww w. j a va 2 s . co m*/ * @throws IOException */ public static void main(final String[] args) throws IOException { final RandomGenerator rng = new MersenneTwister(42); final YahtzeeState s0 = new YahtzeeState(rng); final YahtzeeSimulator sim = new YahtzeeSimulator(rng, s0); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (!sim.state().isTerminal()) { printState(sim.state()); final String cmd = reader.readLine(); final String[] parts = cmd.split(" "); if ("keep".equals(parts[0])) { final int[] keepers = new int[Hand.Nfaces]; for (int i = 1; i < parts.length; ++i) { final int v = Integer.parseInt(parts[i]); keepers[v - 1] += 1; } sim.takeAction(new JointAction<YahtzeeAction>(new KeepAction(keepers))); } else if ("score".equals(parts[0])) { final YahtzeeScores category = YahtzeeScores.valueOf(parts[1]); sim.takeAction(new JointAction<YahtzeeAction>(new ScoreAction(category))); } else if ("undo".equals(parts[0])) { sim.untakeLastAction(); } else { System.out.println("!!! Bad command"); } } System.out.println("********** Terminal **********"); printState(sim.state()); }
From source file:mecard.MetroService.java
public static void main(String[] args) { // First get the valid options Options options = new Options(); // add t option c to config directory true=arg required. options.addOption("c", true, "configuration file directory path, include all sys dependant dir seperators like '/'."); // add t option c to config directory true=arg required. options.addOption("v", false, "Metro server version information."); try {//from ww w.ja v a 2 s . com // parse the command line. CommandLineParser parser = new BasicParser(); CommandLine cmd; cmd = parser.parse(options, args); if (cmd.hasOption("v")) { System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION); } // get c option value String configDirectory = cmd.getOptionValue("c"); PropertyReader.setConfigDirectory(configDirectory); } catch (ParseException ex) { // Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex); System.out.println( new Date() + "Unable to parse command line option. Please check your service configuration."); System.exit(799); } Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT); String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort); try { int port = Integer.parseInt(portString); serverSocket = new ServerSocket(port); } catch (IOException ex) { String msg = " Could not listen on port: " + portString; // Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex); System.out.println(new Date() + msg + ex.getMessage()); } catch (NumberFormatException ex) { String msg = "Could not parse port number defined in configuration file."; // Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex); System.out.println(new Date() + msg + ex.getMessage()); } while (listening) { try { new SocketThread(serverSocket.accept()).start(); } catch (IOException ex) { String msg = "unable to start server socket; either accept or start failed."; // Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex); System.out.println(new Date() + msg); } } try { serverSocket.close(); } catch (IOException ex) { String msg = "failed to close the server socket."; // Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex); System.out.println(new Date() + msg); } }
From source file:ca.cutterslade.match.scheduler.Main.java
public static void main(final String[] args) throws InterruptedException { final CommandLineParser parser = new PosixParser(); try {/* w w w. j a v a 2 s . com*/ final CommandLine line = parser.parse(OPTIONS, args); final int teams = Integer.parseInt(line.getOptionValue('t')); final int tiers = Integer.parseInt(line.getOptionValue('r')); final int gyms = Integer.parseInt(line.getOptionValue('g')); final int courts = Integer.parseInt(line.getOptionValue('c')); final int times = Integer.parseInt(line.getOptionValue('m')); final int days = Integer.parseInt(line.getOptionValue('d')); final int size = Integer.parseInt(line.getOptionValue('z')); final Configuration config; if (line.hasOption("random")) config = Configuration.RANDOM_CONFIGURATION; else config = new Configuration(ImmutableMap.<SadFaceFactor, Integer>of(), line.hasOption("randomMatches"), line.hasOption("randomSlots"), line.hasOption("randomDays")); final Scheduler s = new Scheduler(config, teams, tiers, gyms, courts, times, days, size); System.out.println(summary(s)); } catch (final ParseException e) { final HelpFormatter f = new HelpFormatter(); final PrintWriter pw = new PrintWriter(System.err); f.printHelp(pw, 80, "match-scheduler", null, OPTIONS, 2, 2, null, true); pw.println( "For example: match-scheduler -t 48 -r 3 -d 12 -m 2 -g 3 -c 2 -z 4 --randomMatches --randomSlots"); pw.close(); } }
From source file:com.chschmid.huemorse.server.HueMorse.java
public static void main(String args[]) throws Exception { // Application Title System.out.println(TITLE);/*from w w w . j av a 2 s.c o m*/ // Apache CLI Parser Options options = getCLIOptions(); CommandLineParser parser = new PosixParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("b")) bridgeIP = line.getOptionValue("b"); else if (!(line.hasOption("s"))) { System.out.println(ERROR_NO_IP); return; } if (line.hasOption("c")) cli = true; if (line.hasOption("d")) DEBUG = true; if (line.hasOption("l")) lightID = Integer.parseInt(line.getOptionValue("l")); if (line.hasOption("u")) username = line.getOptionValue("u"); if (line.hasOption("s")) search = true; if (line.hasOption("h")) { printHelp(); return; } } catch (ParseException exp) { System.out.println(HUEMORSE + ": " + exp.getMessage()); System.out.println(ERROR_CLI); return; } hue = new HueMorseInterface(); if (search && bridgeIP.equals("")) searchAndListBridges(); else { if (DEBUG) { System.out.println("Bridge IP: " + bridgeIP); System.out.println("Username: " + username); } hue.connect(bridgeIP, username); hue.setLightID(lightID); if (search) searchAndListLights(); else { if (cli) simpleCommandLineInterface(); else startServers(); } } hue.close(); System.exit(0); }
From source file:com.khubla.jvmbasic.jvmbasicwww.JVMBASICWWW.java
public static void main(String[] args) { try {//from www. java 2 s . c o m System.out.println("khubla.com jvmBasic www server"); /* * options */ final Options options = new Options(); Option oo = Option.builder().argName(SOURCEDIR_OPTION).longOpt(SOURCEDIR_OPTION).type(String.class) .hasArg().required(false).desc("source dir").build(); options.addOption(oo); oo = Option.builder().argName(CLASSDIR_OPTION).longOpt(CLASSDIR_OPTION).type(String.class).hasArg() .required(false).desc("class dir").build(); options.addOption(oo); oo = Option.builder().argName(PORT_OPTION).longOpt(PORT_OPTION).type(String.class).hasArg() .required(false).desc("TCP port").build(); options.addOption(oo); /* * parse */ final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final Exception e) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("posix", options); System.exit(0); } /* * input dir */ final String sourceDir = cmd.getOptionValue(SOURCEDIR_OPTION, SOURCEDIR_DEFAULT); /* * class dir */ final String classdir = cmd.getOptionValue(CLASSDIR_OPTION, CLASSDIR_DEFAULT); /* * port */ int port = Integer.parseInt(cmd.getOptionValue(PORT_OPTION, PORT_DEFAULT)); /* * output the config */ System.out.println("Source directory: " + sourceDir); System.out.println("Class directory: " + classdir); System.out.println("HTTP port: " + port); /* * configuration */ final ServerConfiguration serverConfiguration = new ServerConfiguration(sourceDir, classdir, port); /* * server */ final JVMBasicWebServer jvmBasicWebServer = new JVMBasicWebServer(serverConfiguration); jvmBasicWebServer.listen(); } catch (final Exception e) { e.printStackTrace(); } }
From source file:edu.usc.pgroup.floe.client.commands.Scale.java
/** * Entry point for Scale command.//w ww . j a v a 2 s.co m * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option dirOption = OptionBuilder.withArgName("direction").hasArg().isRequired() .withDescription("Scale Direction.").create("dir"); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Pellet Name").create("pellet"); Option cntOption = OptionBuilder.withArgName("num").hasArg().withType(new String()) .withDescription("Number of instances to scale up/down").create("cnt"); options.addOption(dirOption); options.addOption(appOption); options.addOption(pelletNameOption); options.addOption(cntOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String dir = line.getOptionValue("dir"); String app = line.getOptionValue("app"); String pellet = line.getOptionValue("pellet"); String cnt = line.getOptionValue("cnt"); LOGGER.info("direction: {}", dir); LOGGER.info("Application: {}", app); LOGGER.info("Pellet: {}", pellet); LOGGER.info("count: {}", cnt); ScaleDirection direction = Enum.valueOf(ScaleDirection.class, dir); int count = Integer.parseInt(cnt); try { FloeClient.getInstance().getClient().scale(direction, app, pellet, count); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:net.recommenders.plista.client.Client.java
/** * This method starts the server//ww w. ja v a 2 s . c o m * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { final Properties properties = new Properties(); String fileName = ""; String recommenderClass = null; String handlerClass = null; if (args.length < 3) { fileName = System.getProperty("propertyFile"); } else { fileName = args[0]; recommenderClass = args[1]; handlerClass = args[2]; } // load the team properties try { properties.load(new FileInputStream(fileName)); } catch (IOException e) { logger.error(e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } Recommender recommender = null; recommenderClass = (recommenderClass != null ? recommenderClass : properties.getProperty("plista.recommender")); System.out.println(recommenderClass); lognum = Integer.parseInt(properties.getProperty("plista.lognum")); try { final Class<?> transformClass = Class.forName(recommenderClass); recommender = (Recommender) transformClass.newInstance(); } catch (Exception e) { logger.error(e.getMessage()); throw new IllegalArgumentException("No recommender specified or recommender not available."); } // configure log4j /*if (args.length >= 4 && args[3] != null) { PropertyConfigurator.configure(args[0]); } else { PropertyConfigurator.configure("log4j.properties"); }*/ // set up and start server AbstractHandler handler = null; handlerClass = (handlerClass != null ? handlerClass : properties.getProperty("plista.handler")); System.out.println(handlerClass); try { final Class<?> transformClass = Class.forName(handlerClass); handler = (AbstractHandler) transformClass.getConstructor(Properties.class, Recommender.class) .newInstance(properties, recommender); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); throw new IllegalArgumentException("No handler specified or handler not available."); } final Server server = new Server(Integer.parseInt(properties.getProperty("plista.port", "8080"))); server.setHandler(handler); logger.debug("Serverport " + server.getConnectors()[0].getPort()); server.start(); server.join(); }
From source file:cn.webank.ecif.index.server.EcifIndexServer.java
/** * @param args/*w ww . j a v a 2s. co m*/ */ public static void main(String[] args) { final EcifIndexServer server = new EcifIndexServer(); // start spring context; final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.getEnvironment().setActiveProfiles("product"); context.setConfigLocation("application.xml"); context.refresh(); context.start(); // thread pool construct ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class); server.setTaskThreadPool(taskThreadPool); ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class); server.setSchedulerThreadPool(fixedThreadPool); EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory", EcifThreadFactory.class); server.setThreadFactory(threadFactory); Properties props = context.getBean("ecifProperties", java.util.Properties.class); WeBankServiceDispatcher serviceDispatcher = context.getBean( "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class); ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource", ReloadableResourceBundleMessageSource.class); String topics = props.getProperty("listener.topics"); String[] splits = topics.split(","); SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager", SolaceManager.class); MessageListener messageLisener = new MessageListener( // props.getProperty("listener.queue"), Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")), taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")), serviceDispatcher, solaceManager, bundleMessageSource); server.addListenerOnSchedule(messageLisener); // register shutdownhook Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { // close resource if (context != null) { context.close(); } } catch (Exception e) { LOG.error("shutdown error", e); } } }); // hold server try { LOG.info("ecif-index server start ok!"); server.start(); } catch (Exception e) { try { // close resource server.shutDown(); if (context != null) { context.close(); } } catch (Exception ex) { LOG.error("shutdown error", ex); } } LOG.info("ecif-index server stop !"); }