List of usage examples for java.lang String equals
public boolean equals(Object anObject)
From source file:catalina.startup.BootstrapService.java
/** * Main method, used for testing only./*from w w w . j a v a2s. c o m*/ * * @param args Command line arguments to be processed */ public static void main(String args[]) { // Set the debug flag appropriately for (int i = 0; i < args.length; i++) { if ("-debug".equals(args[i])) debug = 1; } if (service == null) { service = new BootstrapService(); try { BootstrapServiceContext p0 = new BootstrapServiceContext(); p0.setArguments(args); service.init(p0); } catch (Throwable t) { t.printStackTrace(); return; } } try { String command = args[0]; if (command.equals("start")) { service.start(); } else if (command.equals("stop")) { service.stop(); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.akana.demo.freemarker.templatetester.App.java
public static void main(String[] args) { final Options options = new Options(); @SuppressWarnings("static-access") Option optionContentType = OptionBuilder.withArgName("content-type").hasArg() .withDescription("content type of model").create("content"); @SuppressWarnings("static-access") Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg() .withDescription("url path and parameters in HTTP Request Line format").create("url"); @SuppressWarnings("static-access") Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg() .withDescription("root data object name, defaults to 'message'").create("root"); @SuppressWarnings("static-access") Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths") .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources") .create("messages"); @SuppressWarnings("static-access") Option optionDebugMessages = OptionBuilder.hasArg(false) .withDescription("Shows debug information about template processing").create("debug"); Option optionHelp = new Option("help", "print this message"); options.addOption(optionHelp);//from www. j a va 2s. c o m options.addOption(optionContentType); options.addOption(optionUrlPath); options.addOption(optionRootMessageName); options.addOption(optionAdditionalMessages); options.addOption(optionDebugMessages); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); // Check for help flag if (cmd.hasOption("help")) { showHelp(options); return; } String[] remainingArguments = cmd.getArgs(); if (remainingArguments.length < 2) { showHelp(options); return; } String ftlPath, dataPath = "none"; ftlPath = remainingArguments[0]; dataPath = remainingArguments[1]; String contentType = "text/xml"; // Discover content type from file extension String ext = FilenameUtils.getExtension(dataPath); if (ext.equals("json")) { contentType = "json"; } else if (ext.equals("txt")) { contentType = "txt"; } // Override discovered content type if (cmd.hasOption("content")) { contentType = cmd.getOptionValue("content"); } // Root data model name String rootMessageName = "message"; if (cmd.hasOption("root")) { rootMessageName = cmd.getOptionValue("root"); } // Additional data models String[] additionalModels = new String[0]; if (cmd.hasOption("messages")) { additionalModels = cmd.getOptionValues("messages"); } // Debug Info if (cmd.hasOption("debug")) { System.out.println(" Processing ftl : " + ftlPath); System.out.println(" with data model: " + dataPath); System.out.println(" with content-type: " + contentType); System.out.println(" data model object: " + rootMessageName); if (cmd.hasOption("messages")) { System.out.println("additional models: " + additionalModels.length); } } Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(".")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* Create the primary data-model */ Map<String, Object> message = new HashMap<String, Object>(); if (contentType.contains("json") || contentType.contains("txt")) { message.put("contentAsString", FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8)); } else { message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath))); } if (cmd.hasOption("url")) { message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url"))); } Map<String, Object> root = new HashMap<String, Object>(); root.put(rootMessageName, message); if (additionalModels.length > 0) { for (int i = 0; i < additionalModels.length; i++) { Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType); root.put("message" + i, m); } } /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate(ftlPath); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } catch (ParseException e) { showHelp(options); System.exit(1); } catch (IOException e) { System.out.println("Unable to parse ftl."); e.printStackTrace(); } catch (SAXException e) { System.out.println("XML parsing issue."); e.printStackTrace(); } catch (ParserConfigurationException e) { System.out.println("Unable to configure parser."); e.printStackTrace(); } catch (TemplateException e) { System.out.println("Unable to parse template."); e.printStackTrace(); } }
From source file:org.dspace.app.cris.batch.ScriptDeleteRP.java
/** * Batch script to delete a RP. See the technical documentation for further * details./*www .ja va 2 s .com*/ */ public static void main(String[] args) { log.info("#### START DELETE: -----" + new Date() + " ----- ####"); Context dspaceContext = null; ApplicationContext context = null; try { dspaceContext = new Context(); dspaceContext.turnOffAuthorisationSystem(); DSpace dspace = new DSpace(); ApplicationService applicationService = dspace.getServiceManager() .getServiceByName("applicationService", ApplicationService.class); CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "help"); options.addOption("r", "researcher", true, "RP id to delete"); options.addOption("s", "silent", false, "no interactive mode"); CommandLine line = parser.parse(options, args); if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ScriptHKURPDelete \n", options); System.out.println("\n\nUSAGE:\n ScriptHKURPDelete -r <id> \n"); System.out.println("Please note: add -s for no interactive mode"); System.exit(0); } Integer rpId = null; boolean delete = false; boolean silent = line.hasOption('s'); Item[] items = null; if (line.hasOption('r')) { rpId = ResearcherPageUtils.getRealPersistentIdentifier(line.getOptionValue("r"), ResearcherPage.class); ResearcherPage rp = applicationService.get(ResearcherPage.class, rpId); if (rp == null) { if (!silent) { System.out.println("RP not exist...exit"); } log.info("RP not exist...exit"); System.exit(0); } log.info("Use browse indexing"); BrowseIndex bi = BrowseIndex.getBrowseIndex(plugInBrowserIndex); // now start up a browse engine and get it to do the work for us BrowseEngine be = new BrowseEngine(dspaceContext); String authKey = ResearcherPageUtils.getPersistentIdentifier(rp); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(dspaceContext); scope.setBrowseIndex(bi); // scope.setOrder(order); scope.setFilterValue(authKey); scope.setAuthorityValue(authKey); scope.setResultsPerPage(Integer.MAX_VALUE); scope.setBrowseLevel(1); BrowseInfo binfo = be.browse(scope); log.debug("Find " + binfo.getResultCount() + "item(s) for the reseracher " + authKey); items = binfo.getItemResults(dspaceContext); if (!silent && rp != null) { System.out.println(MESSAGE_ONE); // interactive mode System.out.println("Attempting to remove Researcher Page:"); System.out.println("StaffNo:" + rp.getSourceID()); System.out.println("FullName:" + rp.getFullName()); System.out .println("the researcher has " + items.length + " relation(s) with item(s) in the HUB"); System.out.println(); System.out.println(QUESTION_ONE); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); String answer = reader.readLine(); if (answer.equals("yes")) { delete = true; } else { System.out.println("Exit without delete"); log.info("Exit without delete"); System.exit(0); } } else { delete = true; } } else { System.out.println("\n\nUSAGE:\n ScriptHKURPDelete <-v> -r <RPid> \n"); System.out.println("-r option is mandatory"); log.error("-r option is mandatory"); System.exit(1); } if (delete) { if (!silent) { System.out.println("Deleting..."); } log.info("Deleting..."); cleanAuthority(dspaceContext, items, rpId); applicationService.delete(ResearcherPage.class, rpId); dspaceContext.complete(); } if (!silent) { System.out.println("Ok...Bye"); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { if (dspaceContext != null && dspaceContext.isValid()) { dspaceContext.abort(); } if (context != null) { context.publishEvent(new ContextClosedEvent(context)); } } log.info("#### END: -----" + new Date() + " ----- ####"); System.exit(0); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildRetrofitLexicons.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_DESC); options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC); options.addOption(OUT_FILE_PARAM, null, true, OUT_FILE_DESC); options.addOption(MIN_PROB_PARAM, null, true, MIN_PROB_DESC); options.addOption(FORMAT_PARAM, null, true, FORMAT_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {/* ww w . j a va2 s . c om*/ CommandLine cmd = parser.parse(options, args); String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); int gizaIterQty = -1; if (cmd.hasOption(CommonParams.GIZA_ITER_QTY_PARAM)) { gizaIterQty = Integer.parseInt(cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM)); } else { Usage("Specify: " + CommonParams.GIZA_ITER_QTY_PARAM, options); } String outFileName = cmd.getOptionValue(OUT_FILE_PARAM); if (null == outFileName) { Usage("Specify: " + OUT_FILE_PARAM, options); } String indexDir = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == indexDir) { Usage("Specify: " + CommonParams.MEMINDEX_DESC, options); } FormatType outType = FormatType.kOrig; String outTypeStr = cmd.getOptionValue(FORMAT_PARAM); if (null != outTypeStr) { if (outTypeStr.equals(ORIG_TYPE)) { outType = FormatType.kOrig; } else if (outTypeStr.equals(WEIGHTED_TYPE)) { outType = FormatType.kWeighted; } else if (outTypeStr.equals(UNWEIGHTED_TYPE)) { outType = FormatType.kUnweighted; } else { Usage("Unknown format type: " + outTypeStr, options); } } float minProb = 0; if (cmd.hasOption(MIN_PROB_PARAM)) { minProb = Float.parseFloat(cmd.getOptionValue(MIN_PROB_PARAM)); } else { Usage("Specify: " + MIN_PROB_PARAM, options); } System.out.println(String.format( "Saving lexicon to '%s' (output format '%s'), keep only entries with translation probability >= %f", outFileName, outType.toString(), minProb)); // We use unlemmatized text here, because lemmatized dictionary is going to be mostly subset of the unlemmatized one. InMemForwardIndex textIndex = new InMemForwardIndex(FeatureExtractor.indexFileName(indexDir, FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID])); InMemForwardIndexFilterAndRecoder filterAndRecoder = new InMemForwardIndexFilterAndRecoder(textIndex); String prefix = gizaRootDir + "/" + FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID] + "/"; GizaVocabularyReader answVoc = new GizaVocabularyReader(prefix + "source.vcb", filterAndRecoder); GizaVocabularyReader questVoc = new GizaVocabularyReader(prefix + "target.vcb", filterAndRecoder); GizaTranTableReaderAndRecoder gizaTable = new GizaTranTableReaderAndRecoder(false, // we don't need to flip the table for the purpose prefix + "/output.t1." + gizaIterQty, filterAndRecoder, answVoc, questVoc, (float) FeatureExtractor.DEFAULT_PROB_SELF_TRAN, minProb); BufferedWriter outFile = new BufferedWriter(new FileWriter(outFileName)); for (int srcWordId = 0; srcWordId <= textIndex.getMaxWordId(); ++srcWordId) { GizaOneWordTranRecs tranRecs = gizaTable.getTranProbs(srcWordId); if (null != tranRecs) { String wordSrc = textIndex.getWord(srcWordId); StringBuffer sb = new StringBuffer(); sb.append(wordSrc); for (int k = 0; k < tranRecs.mDstIds.length; ++k) { float prob = tranRecs.mProbs[k]; if (prob >= minProb) { int dstWordId = tranRecs.mDstIds[k]; if (dstWordId == srcWordId && outType != FormatType.kWeighted) continue; // Don't duplicate the word, unless it's probability weighted sb.append(' '); String dstWord = textIndex.getWord(dstWordId); if (null == dstWord) { throw new Exception( "Bug or inconsistent data: Couldn't retriev a word for wordId = " + dstWordId); } if (dstWord.indexOf(':') >= 0) throw new Exception( "Illegal dictionary word '" + dstWord + "' b/c it contains ':'"); sb.append(dstWord); if (outType != FormatType.kOrig) { sb.append(':'); sb.append(outType == FormatType.kWeighted ? prob : 1); } } } outFile.write(sb.toString()); outFile.newLine(); } } outFile.close(); } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } System.out.println("Terminated successfully!"); }
From source file:ColumnStorage.TestColumnStorage.java
public static void main(String[] argv) throws Exception { try {/*from w w w. ja v a 2s. co m*/ if (argv.length < 1) { System.out.println("TestColumnStorage cmd[write | read ]"); return; } String cmd = argv[0]; if (cmd.equals("write")) { writeFile1(); writeFile2(); writeFile3(); } else { if (argv.length < 2) { System.out.println("TestColumnStorage read line"); return; } fieldMap.addField(new Field(ConstVar.FieldType_Byte, ConstVar.Sizeof_Byte, (short) 0)); fieldMap.addField(new Field(ConstVar.FieldType_Short, ConstVar.Sizeof_Short, (short) 1)); fieldMap.addField(new Field(ConstVar.FieldType_Int, ConstVar.Sizeof_Int, (short) 2)); fieldMap.addField(new Field(ConstVar.FieldType_Long, ConstVar.Sizeof_Long, (short) 3)); fieldMap.addField(new Field(ConstVar.FieldType_Float, ConstVar.Sizeof_Float, (short) 4)); fieldMap.addField(new Field(ConstVar.FieldType_Byte, ConstVar.Sizeof_Byte, (short) 5)); fieldMap.addField(new Field(ConstVar.FieldType_Short, ConstVar.Sizeof_Short, (short) 6)); fieldMap.addField(new Field(ConstVar.FieldType_Int, ConstVar.Sizeof_Int, (short) 7)); fieldMap.addField(new Field(ConstVar.FieldType_Long, ConstVar.Sizeof_Long, (short) 8)); fieldMap.addField(new Field(ConstVar.FieldType_Double, ConstVar.Sizeof_Double, (short) 9)); fieldMap.addField(new Field(ConstVar.FieldType_String, 0, (short) 10)); int line = Integer.valueOf(argv[1]); getRecordByLine1(line); } } catch (IOException e) { e.printStackTrace(); System.out.println("get IOException:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); System.out.println("get exception:" + e.getMessage()); } }
From source file:Replier.java
/** Main program entry point. */ public static void main(String argv[]) { // Values to be read from parameters String broker = DEFAULT_BROKER_NAME; String username = DEFAULT_USER_NAME; String password = DEFAULT_PASSWORD; String queue = DEFAULT_QUEUE; String mode = DEFAULT_MODE;//from ww w .ja v a 2 s .co m // Check parameters for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.equals("-b")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing broker name:port"); System.exit(1); } broker = argv[++i]; continue; } if (arg.equals("-u")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing user name"); System.exit(1); } username = argv[++i]; continue; } if (arg.equals("-p")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing password"); System.exit(1); } password = argv[++i]; continue; } if (arg.equals("-qr")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing queue"); System.exit(1); } queue = argv[++i]; continue; } if (arg.equals("-m")) { if (i == argv.length - 1 || argv[i + 1].startsWith("-")) { System.err.println("error: missing mode"); System.exit(1); } mode = argv[++i]; if (!(mode.equals("uppercase") || mode.equals("lowercase"))) { System.err.println("error: mode must be 'uppercase' or 'lowercase'"); System.exit(1); } continue; } if (arg.equals("-h")) { printUsage(); System.exit(1); } // Invalid argument System.err.println("error: unexpected argument: " + arg); printUsage(); System.exit(1); } // Start the JMS client. Replier replier = new Replier(); replier.start(broker, username, password, queue, mode); }
From source file:ShowImage.java
public static void main(String args[]) throws IOException { List<File> files = ImageIOUtils.getFiles(args, new String[] { "ntf", "nsf" }); for (Iterator iter = files.iterator(); iter.hasNext();) { try {//from w w w. j av a 2 s .c o m File file = (File) iter.next(); log.debug("Reading: " + file.getAbsolutePath()); NITFReader imageReader = (NITFReader) ImageIOUtils.getImageReader("nitf", file); for (int i = 0; i < imageReader.getRecord().getImages().length; ++i) { log.debug(file.getName() + "[" + i + "]"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageSubheader subheader = imageReader.getRecord().getImages()[i].getSubheader(); subheader.print(new PrintStream(stream)); log.debug(stream.toString()); try { int numBands = subheader.getBandCount(); String irep = subheader.getImageRepresentation().getStringData().trim(); int bitsPerPixel = subheader.getNumBitsPerPixel().getIntData(); int nBytes = (bitsPerPixel - 1) / 8 + 1; if (irep.equals("RGB") && numBands == 3) { BufferedImage image = imageReader.read(i); ImageIOUtils.showImage(image, file.getName() + "[" + i + "]", true); } else { // read each band, separately for (int j = 0; j < numBands; ++j) { if (nBytes == 1 || nBytes == 2 || nBytes == 4 || nBytes == 8) { ImageReadParam readParam = imageReader.getDefaultReadParam(); readParam.setSourceBands(new int[] { j }); BufferedImage image = imageReader.read(i, readParam); ImageIOUtils.showImage(image, file.getName() + "[" + i + "][" + j + "]", true); ImageIO.write(image, "jpg", new FileOutputStream("image" + i + "_" + j + ".jpg")); // downsample // readParam.setSourceSubsampling(2, 2, 0, // 0); // BufferedImage smallerImage = imageReader // .read(i, readParam); // // ImageIOUtils.showImage(smallerImage, // "DOWNSAMPLED: " + file.getName()); } } } } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); log.error(ExceptionUtils.getStackTrace(e)); } } } catch (Exception e) { log.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:me.timothy.ddd.DrunkDuckDispatch.java
License:asdf
public static void main(String[] args) throws LWJGLException { try {//from w w w . j av a 2 s . c o m float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2; float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2; boolean fullscreen = false, defaultDisplay = !fullscreen; File resolutionInfo = new File("graphics.json"); if (resolutionInfo.exists()) { try (FileReader fr = new FileReader(resolutionInfo)) { JSONObject obj = (JSONObject) new JSONParser().parse(fr); Set<?> keys = obj.keySet(); for (Object o : keys) { if (o instanceof String) { String key = (String) o; switch (key.toLowerCase()) { case "width": defaultDisplayWidth = JSONCompatible.getFloat(obj, key); break; case "height": defaultDisplayHeight = JSONCompatible.getFloat(obj, key); break; case "fullscreen": fullscreen = JSONCompatible.getBoolean(obj, key); defaultDisplay = !fullscreen; break; } } } } catch (IOException | ParseException e) { e.printStackTrace(); } float expHeight = defaultDisplayWidth * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH); float expWidth = defaultDisplayHeight * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT); if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) { if (defaultDisplayHeight < expHeight) { System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n", defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight); defaultDisplayHeight = expHeight; } else { System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n", defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight); defaultDisplayWidth = expWidth; } } } File dir = null; String os = getOS(); if (os.equals("windows")) { dir = new File(System.getenv("APPDATA"), "timgames/"); } else { dir = new File(System.getProperty("user.home"), ".timgames/"); } File lwjglDir = new File(dir, "lwjgl-2.9.1/"); Resources.init(); Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip", "Necessary LWJGL natives couldn't be found, I can attempt " + "to download it, but I make no promises", "Unfortunately I was unable to download it, so I'll open up the " + "link to the official download. Make sure you get LWJGL version 2.9.1, " + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip", new Runnable() { @Override public void run() { if (!Desktop.isDesktopSupported()) { JOptionPane.showMessageDialog(null, "I couldn't " + "even do that! Download it manually and try again"); return; } try { Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php")); } catch (IOException | URISyntaxException e) { JOptionPane.showMessageDialog(null, "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck"); System.exit(1); } } }, 5843626); Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1"); System.setProperty("org.lwjgl.librarypath", new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath")); Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142); Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142); Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168); Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321); File resFolder = new File("resources/"); if (!resFolder.exists() && !new File("player-still.png").exists()) { Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484); Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png"); new File("resources.zip").delete(); } File soundFolder = new File("sounds/"); if (!soundFolder.exists()) { soundFolder.mkdirs(); Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip", 1984977); Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf"); new File(soundFolder, "sounds.zip").delete(); } AppGameContainer appgc; ddd = new DrunkDuckDispatch(); appgc = new AppGameContainer(ddd); appgc.setTargetFrameRate(60); appgc.setShowFPS(false); appgc.setAlwaysRender(true); if (fullscreen) { DisplayMode[] modes = Display.getAvailableDisplayModes(); DisplayMode current, best = null; float ratio = 0f; for (int i = 0; i < modes.length; i++) { current = modes[i]; float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH; float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT; System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY); if (rX == rY && rX > ratio) { best = current; ratio = rX; } } if (best == null) { System.out.println("Failed to find an appropriately scaled resolution, using default display"); defaultDisplay = true; } else { appgc.setDisplayMode(best.getWidth(), best.getHeight(), true); SizeScaleSystem.setRealHeight(best.getHeight()); SizeScaleSystem.setRealWidth(best.getWidth()); System.out.println("I choose " + best.getWidth() + "x" + best.getHeight()); } } if (defaultDisplay) { SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth)); SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight)); appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false); } ddd.logger.info( "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight()); appgc.start(); } catch (SlickException ex) { LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex); } }
From source file:com.wittawat.wordseg.Main.java
public static void main(String[] args) throws Exception { Console con = System.console(); if (con == null) { System.out.println("The system must support console to run the program."); System.exit(1);//from ww w .ja v a 2 s. c o m } // Load model System.out.println("Loading model ..."); Classifier model = Data.getDefaultModel(); System.out.println("Finished loading model."); System.out.println(getAgreement()); boolean isUseDict = true; // Dummy statement to eliminate all lazy loading System.out.println("\n" + new NukeTokenizer3( "?????", model, isUseDict).tokenize() + "\n"); System.out.println(getHelp()); final String SET_DICT_PAT_STR = "\\s*set\\s+dict\\s+(true|false)\\s*"; final Pattern SET_DICT_PAT = Pattern.compile(SET_DICT_PAT_STR); while (true) { System.out.print(">> "); String line = con.readLine(); if (line != null && !line.trim().equals("")) { line = line.trim(); try { if (line.equals("h") || line.equals("help")) { System.out.println(getHelp()); } else if (line.equals("about")) { System.out.println(getAbout()); } else if (line.equals("agreement")) { System.out.println(getAgreement()); } else if (SET_DICT_PAT.matcher(line).find()) { Matcher m = SET_DICT_PAT.matcher(line); m.find(); String v = m.group(1); isUseDict = v.equals("true"); System.out.println("Dictionary will " + (isUseDict ? "" : "not ") + "be used."); } else if (line.matches("q|quit|exit")) { System.out.println("Bye"); System.exit(0); } else if (line.contains(":tokfile:")) { String[] splits = line.split(":tokfile:"); String in = splits[0]; String out = splits[1]; String content = FileUtils.readFileToString(new File(in)); long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println("Time to tokenize: " + (end - start) + " ms."); FileUtils.writeStringToFile(new File(out), tokenized); } else if (line.contains(":tokfile")) { String[] splits = line.split(":tokfile"); String in = splits[0]; String content = FileUtils.readFileToString(new File(in)); long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println(tokenized); System.out.println("Time to tokenize: " + (end - start) + " ms."); } else if (line.contains(":tok:")) { String[] splits = line.split(":tok:"); String inText = splits[0]; String out = splits[1]; long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println("Time to tokenize: " + (end - start) + " ms."); FileUtils.writeStringToFile(new File(out), tokenized); } else if (line.contains(":tok")) { String[] splits = line.split(":tok"); String inText = splits[0]; long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println(tokenized); System.out.println("Time to tokenize: " + (end - start) + " ms."); } else { System.out.println("Unknown command"); } } catch (Exception e) { System.out.println("Error. See the exception."); e.printStackTrace(); } } } }
From source file:hyperloglog.tools.HyperLogLogCLI.java
public static void main(String[] args) { Options options = new Options(); addOptions(options);/*from w w w. j av a2 s . 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); } }