List of usage examples for java.io PrintWriter println
public void println(Object x)
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];//w ww. j a v a 2s . co m File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; // for oversampling using graph transitivity properties use this // String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter"; Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } int totalGoldPairsCounter = 0; Map<String, Integer> goldDataDistribution = new HashMap<>(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", ""); PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8"); pw.println("#id\tlabel\ta1\ta2"); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel, multipleParagraphsToSingleLine(argumentPair.getArg1().getText()), multipleParagraphsToSingleLine(argumentPair.getArg2().getText())); pairsPerTopicCounter++; int sameInOnePair = 0; // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; } } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } totalGoldPairsCounter += pairsPerTopicCounter; statsPerTopic.addValue(pairsPerTopicCounter); pw.close(); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); System.out.println("Total gold pairs: " + totalGoldPairsCounter); System.out.println(statsPerTopic); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println("Total pairs: " + totalPairs); System.out.println(goldDataDistribution); }
From source file:gov.nist.healthcare.ttt.webapp.api.GetCCDAFolderTest.java
public static void main(String[] args) throws Exception { long startTime = System.currentTimeMillis(); JSONObject res = new JSONObject(); HashMap<String, Object> json = new HashMap<>(); String sha = getHTML(//w w w . ja v a2 s.c o m "https://api.github.com/repos/siteadmin/2015-Certification-C-CDA-Test-Data/branches/master") .getJSONObject("commit").get("sha").toString(); JSONArray filesArray = getHTML( "https://api.github.com/repos/siteadmin/2015-Certification-C-CDA-Test-Data/git/trees/" + sha + "?recursive=1").getJSONArray("tree"); HashMap<String, Object> resultMap = new HashMap<>(); for (int i = 0; i < filesArray.length(); i++) { JSONObject file = filesArray.getJSONObject(i); if (!files2ignore.contains(file.get("path"))) { // Get path array String[] path = file.get("path").toString().split("/"); // System.out.println(String.join("/", path)); // for(String dir : path) { // if(Pattern.matches(extensionRegex, dir)) { // System.out.println("File!! " + dir); // } // } // json = buildJson2(new HashMap<>(), path, false, true); // resultMap = deepMerge(resultMap, json); // System.out.println(new JSONObject(json).toString(2)); buildJson3(resultMap, path); } } // String[] test = {"test", "retest", "file.txt"}; // json = buildJson2(json, test, false, true); System.out.println(new JSONObject(resultMap).toString(2)); PrintWriter out = new PrintWriter("filename.txt"); out.println(new JSONObject(resultMap).toString(2)); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Running time: " + totalTime / 1000.0 + "s"); // Try download // URL website = new URL("https://raw.githubusercontent.com/siteadmin/2015-Certification-C-CDA-Test-Data/master/Receiver%20SUT%20Test%20Data/170.315_b1_ToC_Amb/170.315_b1_toc_amb_ccd_r11_sample1_v1.xml"); // InputStream strm = website.openStream(); // System.out.println(IOUtils.toString(strm)); }
From source file:net.socket.bio.TimeClient.java
/** * @param args//from w w w . ja v a 2s . c o m */ public static void main(String[] args) { int port = 8089; if (args != null && args.length > 0) { try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e) { // } } Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); out.println("QUERY TIME ORDER"); out.println("QUERY TIME ORDER"); String test = StringUtils.repeat("hello tcp", 1000); out.println(test); System.out.println("Send order 2 server succeed."); String resp = in.readLine(); System.out.println("Now is : " + resp); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(socket); } }
From source file:com.adobe.aem.demomachine.Json2Csv.java
public static void main(String[] args) throws IOException { String inputFile1 = null;/*from w ww. j a v a 2 s . com*/ String inputFile2 = null; String outputFile = null; HashMap<String, String> hmReportSuites = new HashMap<String, String>(); // Command line options for this tool Options options = new Options(); options.addOption("c", true, "Filename 1"); options.addOption("r", true, "Filename 2"); options.addOption("o", true, "Filename 3"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { inputFile1 = cmd.getOptionValue("c"); } if (cmd.hasOption("r")) { inputFile2 = cmd.getOptionValue("r"); } if (cmd.hasOption("o")) { outputFile = cmd.getOptionValue("o"); } if (inputFile1 == null || inputFile1 == null || outputFile == null) { System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // List of customers and report suites for these customers String sInputFile1 = readFile(inputFile1, Charset.defaultCharset()); sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\""); // Processing the list of report suites for each customer try { JSONArray jCustomers = new JSONArray(sInputFile1.trim()); for (int i = 0, size = jCustomers.length(); i < size; i++) { JSONObject jCustomer = jCustomers.getJSONObject(i); Iterator<?> keys = jCustomer.keys(); String companyName = null; while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("company")) { companyName = jCustomer.getString(key); } } keys = jCustomer.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("report_suites")) { JSONArray jReportSuites = jCustomer.getJSONArray(key); for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) { hmReportSuites.put(jReportSuites.getString(j), companyName); System.out.println(jReportSuites.get(j) + " for company " + companyName); } } } } // Creating the out put file PrintWriter writer = new PrintWriter(outputFile, "UTF-8"); writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents" + "\",\"" + "Last Updated" + "\""); // Processing the list of SOLR collections String sInputFile2 = readFile(inputFile2, Charset.defaultCharset()); sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\""); JSONObject jResults = new JSONObject(sInputFile2.trim()); JSONArray jCollections = jResults.getJSONArray("result"); for (int i = 0, size = jCollections.length(); i < size; i++) { JSONObject jCollection = jCollections.getJSONObject(i); String id = null; String number = null; String lastupdate = null; Iterator<?> keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("_id")) { id = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("noOfDocs")) { number = jCollection.getString(key); } } keys = jCollection.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("latestUpdateDate")) { lastupdate = jCollection.getString(key); } } Date d = new Date(Long.parseLong(lastupdate)); System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + "," + new SimpleDateFormat("MM-dd-yyyy").format(d)); writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\"" + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\""); } writer.close(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String filename = "fileName.txt"; String[] linesToWrite = new String[] { "a", "b" }; boolean appendToFile = true; PrintWriter pw = null; if (appendToFile) { pw = new PrintWriter(new FileWriter(filename, true)); } else {//ww w .ja v a2 s . co m pw = new PrintWriter(new FileWriter(filename)); // pw = new PrintWriter(new FileWriter(filename, false)); } for (int i = 0; i < linesToWrite.length; i++) { pw.println(linesToWrite[i]); } pw.flush(); pw.close(); }
From source file:CopyLines.java
public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try {/*from ww w . ja v a2 s. com*/ inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }
From source file:com.jaeksoft.searchlib.util.StringUtils.java
public static void main(String[] args) throws IOException { List<String> lines = FileUtils.readLines(new File(args[0])); FileWriter fw = new FileWriter(new File(args[1])); PrintWriter pw = new PrintWriter(fw); for (String line : lines) pw.println(StringEscapeUtils.unescapeHtml(line)); pw.close();/*from w w w.j a va2s .co m*/ fw.close(); }
From source file:ca.mcgill.networkdynamics.geoinference.evaluation.CrossValidationScorer.java
public static void main(String[] args) throws Exception { if (args.length != 4) { System.out.println("java CVS predictions-dir/ " + "cv-gold-dir/ results.txt error-sample.tsv"); return;/* ww w. ja va 2 s . com*/ } File predDir = new File(args[0]); File cvDir = new File(args[1]); TDoubleList errors = new TDoubleArrayList(10_000_000); TLongSet locatedUsers = new TLongHashSet(10_000_000); TLongSet allUsers = new TLongHashSet(10_000_000); TLongObjectMap<TDoubleList> userToErrors = new TLongObjectHashMap<TDoubleList>(); TLongDoubleMap tweetIdToError = new TLongDoubleHashMap(10_000_000); TLongObjectMap<double[]> idToPredLoc = new TLongObjectHashMap<double[]>(); int tweetsSeen = 0; int tweetsLocated = 0; BufferedReader cvBr = new BufferedReader(new FileReader(new File(cvDir, "folds.info.tsv"))); for (String foldLine = null; (foldLine = cvBr.readLine()) != null;) { String[] cols = foldLine.split("\t"); String foldName = cols[0]; System.out.printf("Scoring results for fold %s%n", foldName); File foldPredictionsFile = new File(predDir, foldName + ".results.tsv.gz"); File goldLocFile = new File(cvDir, foldName + ".gold-locations.tsv"); if (foldPredictionsFile.exists()) { BufferedReader br = Files.openGz(foldPredictionsFile); for (String line = null; (line = br.readLine()) != null;) { String[] arr = line.split("\t"); long id = Long.parseLong(arr[0]); idToPredLoc.put(id, new double[] { Double.parseDouble(arr[1]), Double.parseDouble(arr[2]) }); } br.close(); } System.out.printf("loaded predictions for %d tweets; " + "scoring predictions%n", idToPredLoc.size()); BufferedReader br = new BufferedReader(new FileReader(goldLocFile)); for (String line = null; (line = br.readLine()) != null;) { String[] arr = line.split("\t"); long id = Long.parseLong(arr[0]); long userId = Long.parseLong(arr[1]); allUsers.add(userId); tweetsSeen++; double[] predLoc = idToPredLoc.get(id); if (predLoc == null) continue; tweetsLocated++; locatedUsers.add(userId); double[] goldLoc = new double[] { Double.parseDouble(arr[2]), Double.parseDouble(arr[3]) }; double dist = Geometry.getDistance(predLoc, goldLoc); errors.add(dist); tweetIdToError.put(id, dist); TDoubleList userErrors = userToErrors.get(userId); if (userErrors == null) { userErrors = new TDoubleArrayList(); userToErrors.put(userId, userErrors); } userErrors.add(dist); } br.close(); } errors.sort(); System.out.println("Num errors to score: " + errors.size()); double auc = 0; double userCoverage = 0; double tweetCoverage = tweetsLocated / (double) tweetsSeen; double medianMaxUserError = Double.NaN; double medianMedianUserError = Double.NaN; if (errors.size() > 0) { auc = computeAuc(errors); userCoverage = locatedUsers.size() / ((double) allUsers.size()); TDoubleList maxUserErrors = new TDoubleArrayList(locatedUsers.size()); TDoubleList medianUserErrors = new TDoubleArrayList(locatedUsers.size()); for (TDoubleList userErrors : userToErrors.valueCollection()) { userErrors.sort(); maxUserErrors.add(userErrors.get(userErrors.size() - 1)); medianUserErrors.add(userErrors.get(userErrors.size() / 2)); } maxUserErrors.sort(); medianMaxUserError = maxUserErrors.get(maxUserErrors.size() / 2); medianUserErrors.sort(); medianMedianUserError = medianUserErrors.get(medianUserErrors.size() / 2); // Compute CDF int[] errorsPerKm = new int[MAX_KM]; for (int i = 0; i < errors.size(); ++i) { int error = (int) (Math.round(errors.get(i))); errorsPerKm[error]++; } // The accumulated sum of errors per km int[] errorsBelowEachKm = new int[errorsPerKm.length]; for (int i = 0; i < errorsBelowEachKm.length; ++i) { errorsBelowEachKm[i] = errorsPerKm[i]; if (i > 0) errorsBelowEachKm[i] += errorsBelowEachKm[i - 1]; } final double[] cdf = new double[errorsBelowEachKm.length]; double dSize = errors.size(); // to avoid casting all the time for (int i = 0; i < cdf.length; ++i) cdf[i] = errorsBelowEachKm[i] / dSize; } PrintWriter pw = new PrintWriter(new File(args[2])); pw.println("AUC\t" + auc); pw.println("user coverage\t" + userCoverage); pw.println("tweet coverage\t" + tweetCoverage); pw.println("median-max error\t" + medianMaxUserError); pw.close(); // Choose a random sampling of 10K tweets to pass on to the authors // here. PrintWriter errorsPw = new PrintWriter(args[3]); TLongList idsWithErrors = new TLongArrayList(tweetIdToError.keySet()); idsWithErrors.shuffle(new Random()); // Choose the first 10K for (int i = 0, chosen = 0; i < idsWithErrors.size() && chosen < 10_000; ++i) { long id = idsWithErrors.get(i); double[] prediction = idToPredLoc.get(id); double error = tweetIdToError.get(id); errorsPw.println(id + "\t" + error + "\t" + prediction[0] + "\t" + prediction[1]); ++chosen; } errorsPw.close(); }
From source file:UseConverters.java
public static void main(String[] args) { try {/*from w w w . j a v a 2 s .c om*/ BufferedReader fromKanji = new BufferedReader( new InputStreamReader(new FileInputStream("kanji.txt"), "EUC_JP")); PrintWriter toSwedish = new PrintWriter(new OutputStreamWriter( // XXX // check // enco new FileOutputStream("sverige.txt"), "ISO8859_3")); // reading and writing here... String line = fromKanji.readLine(); System.out.println("-->" + line + "<--"); toSwedish.println(line); fromKanji.close(); toSwedish.close(); } catch (UnsupportedEncodingException exc) { System.err.println("Bad encoding" + exc); return; } catch (IOException err) { System.err.println("I/O Error: " + err); return; } }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);//from w w w . j a v a2 s.c o m } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }