List of usage examples for java.util List size
int size();
From source file:kindleclippings.word.QuizletSync.java
public static void main(String[] args) throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException, BadLocationException { JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt")); fc.setMultiSelectionEnabled(true);/*from w ww. j a va 2s .c om*/ int result = fc.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) { return; } File[] clf = fc.getSelectedFiles(); if (clf == null || clf.length == 0) return; ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100); progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); progress.setProgress(0); try { progress.setNote("checking Quizlet account"); progress.setProgress(5); Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs(); QuizletAPI api = new QuizletAPI(prefs.get("access_token", null)); Collection<TermSet> sets = null; try { progress.setNote("checking Quizlet library"); progress.setProgress(10); sets = api.getSets(prefs.get("user_id", null)); } catch (IOException e) { if (e.toString().contains("401")) { // Not Authorized => Token has been revoked kindleclippings.quizlet.QuizletSync.clearPrefs(); prefs = kindleclippings.quizlet.QuizletSync.getPrefs(); api = new QuizletAPI(prefs.get("access_token", null)); sets = api.getSets(prefs.get("user_id", null)); } else { throw e; } } progress.setProgress(15); progress.setMaximum(15 + clf.length * 10); progress.setNote("uploading new notes"); int pro = 15; int addedSets = 0; int updatedTerms = 0; int updatedSets = 0; for (File f : clf) { progress.setProgress(pro); List<Clipping> clippings = readClippingsFile(f); if (clippings == null) { pro += 10; continue; } if (clippings.isEmpty()) { pro += 10; continue; } if (clippings.size() < 2) { pro += 10; continue; } String book = clippings.get(0).getBook(); progress.setNote(book); TermSet termSet = null; String x = book.toLowerCase().replaceAll("\\W", ""); for (TermSet t : sets) { if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) { termSet = t; break; } } if (termSet == null) { addSet(api, book, clippings); addedSets++; pro += 10; continue; } // compare against existing terms boolean hasUpdated = false; for (Clipping cl : clippings) { if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) { kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl); updatedTerms++; hasUpdated = true; } } pro += 10; if (hasUpdated) updatedSets++; } if (updatedTerms == 0 && addedSets == 0) { JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync", JOptionPane.OK_OPTION); } else { if (addedSets > 0) { JOptionPane.showMessageDialog(null, String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets", addedSets, updatedSets, updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } else { JOptionPane.showMessageDialog(null, String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets), "QuizletSync", JOptionPane.OK_OPTION); } } } finally { progress.close(); } System.exit(0); }
From source file:com.fun.rrs.common.excel.ExportExcel.java
/** * /* w ww .ja v a 2s . c o m*/ */ public static void main(String[] args) throws Throwable { List<String> headerList = new ArrayList<String>(); for (int i = 1; i <= 10; i++) { headerList.add("" + i); } List<String> dataRowList = new ArrayList<String>(); for (int i = 1; i <= headerList.size(); i++) { dataRowList.add("?" + i); } List<List<String>> dataList = new ArrayList<List<String>>(); for (int i = 1; i <= 100; i++) { dataList.add(dataRowList); } ExportExcel ee = new ExportExcel("", headerList); for (int i = 0; i < dataList.size(); i++) { Row row = ee.addRow(); for (int j = 0; j < dataList.get(i).size(); j++) { ee.addCell(row, j, dataList.get(i).get(j)); } } ee.writeFile("target/export.xlsx"); ee.dispose(); log.debug("Export success."); }
From source file:AwsConsoleApp.java
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS VPN connection creator"); System.out.println("==========================================="); init();//from w ww. j ava 2 s . c o m List<String> CIDRblocks = new ArrayList<String>(); String vpnType = null; String vpnGatewayId = null; String customerGatewayId = null; String customerGatewayInfoPath = null; String routes = null; options.addOption("h", "help", false, "show help."); options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)"); options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)"); options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)"); options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24"); options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; // Parse command line options try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) help(); if (cmd.hasOption("vt")) { log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt")); vpnType = cmd.getOptionValue("vt"); // Whatever you want to do with the setting goes here } else { log.log(Level.SEVERE, "Missing vt option"); help(); } if (cmd.hasOption("vgw")) { log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw")); vpnGatewayId = cmd.getOptionValue("vgw"); } else { log.log(Level.SEVERE, "Missing vgw option"); help(); } if (cmd.hasOption("cgw")) { log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw")); customerGatewayId = cmd.getOptionValue("cgw"); } else { log.log(Level.SEVERE, "Missing cgw option"); help(); } if (cmd.hasOption("r")) { log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r")); routes = cmd.getOptionValue("r"); String[] routeItems = routes.split(","); CIDRblocks = Arrays.asList(routeItems); } else { log.log(Level.SEVERE, "Missing r option"); help(); } if (cmd.hasOption("vi")) { log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi")); customerGatewayInfoPath = cmd.getOptionValue("vi"); } else { log.log(Level.SEVERE, "Missing vi option"); help(); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse comand line properties", e); help(); } /* * Amazon VPC * Create and delete VPN tunnel to customer VPN hardware */ try { //String vpnType = "ipsec.1"; //String vpnGatewayId = "vgw-eca54d85"; //String customerGatewayId = "cgw-c16e87a8"; //List<String> CIDRblocks = new ArrayList<String>(); //CIDRblocks.add("10.77.77.0/24"); //CIDRblocks.add("172.16.1.0/24"); //CIDRblocks.add("172.18.1.0/24"); //CIDRblocks.add("10.66.66.0/24"); //CIDRblocks.add("10.8.1.0/24"); //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml"; Boolean staticRoutesOnly = true; List<String> connectionIds = new ArrayList<String>(); List<String> connectionIdList = new ArrayList<String>(); connectionIdList = vpnExists(connectionIds); if (connectionIdList.size() == 0) { CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId, vpnGatewayId); CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult(); VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification(); vpnspec.setStaticRoutesOnly(staticRoutesOnly); vpnReq.setOptions(vpnspec); System.out.println("Creating VPN connection"); vpnRes = ec2.createVpnConnection(vpnReq); String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId(); String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration(); //System.out.println("Customer Gateway Info:" + customerGatewayInfo); // Write Customer Gateway Info to file System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath); try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) { out.print(customerGatewayInfo); } System.out.println("Creating VPN routes"); for (String destCIDR : CIDRblocks) { CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest(); CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult(); routeReq.setDestinationCidrBlock(destCIDR); routeReq.setVpnConnectionId(vpnConnId); routeRes = ec2.createVpnConnectionRoute(routeReq); } // Parse XML file File file = new File(customerGatewayInfoPath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(customerGatewayInfoPath); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression exprGetipAddress = xpath .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address"); NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET); if (vpnGateway != null) { for (int i = 0; i < vpnGateway.getLength(); i++) { String vpnGatewayIP = vpnGateway.item(i).getTextContent(); System.out .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP); } } System.out.println("=============================================="); XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key"); NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET); if (presharedKeyList != null) { for (int i = 0; i < presharedKeyList.getLength(); i++) { String pre_shared_key = presharedKeyList.item(i).getTextContent(); System.out.println( "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key); } } System.out.println("Creating VPN creation completed!"); } else { boolean yn; Scanner scan = new Scanner(System.in); System.out.println("Enter yes or no to delete VPN connection: "); String input = scan.next(); String answer = input.trim().toLowerCase(); while (true) { if (answer.equals("yes")) { yn = true; break; } else if (answer.equals("no")) { yn = false; System.exit(0); } else { System.out.println("Sorry, I didn't catch that. Please answer yes/no"); } } // Delete all existing VPN connections System.out.println("Deleting AWS VPN connection(s)"); for (String vpnConID : connectionIdList) { DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult(); DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest(); delVPNreq.setVpnConnectionId(vpnConID); delVPNres = ec2.deleteVpnConnection(delVPNreq); System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID); } } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }
From source file:sdmx.net.service.RESTQueryable.java
public static void main(String args[]) { RESTQueryable registry = new RESTQueryable("ESTAT", "http://www.ec.europa.eu/eurostat/SDMX/diss-web/rest"); List<DataflowType> dfs = registry.listDataflows(); for (int i = 0; i < dfs.size(); i++) { System.out.println(dfs.get(i).getName()); }/* w ww .j a va 2s . c om*/ }
From source file:kindleclippings.quizlet.QuizletSync.java
public static void main(String[] args) throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException { ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading Kindle clippings file", 0, 100);/* ww w. j ava 2s. c om*/ progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); progress.setProgress(0); try { Map<String, List<Clipping>> books = readClippingsFile(); if (books == null) return; if (books.isEmpty()) { JOptionPane.showMessageDialog(null, "no clippings to be uploaded", "QuizletSync", JOptionPane.OK_OPTION); return; } progress.setNote("checking Quizlet account"); progress.setProgress(5); Preferences prefs = getPrefs(); QuizletAPI api = new QuizletAPI(prefs.get("access_token", null)); Collection<TermSet> sets = null; try { progress.setNote("checking Quizlet library"); progress.setProgress(10); sets = api.getSets(prefs.get("user_id", null)); } catch (IOException e) { if (e.toString().contains("401")) { // Not Authorized => Token has been revoked clearPrefs(); prefs = getPrefs(); api = new QuizletAPI(prefs.get("access_token", null)); sets = api.getSets(prefs.get("user_id", null)); } else { throw e; } } progress.setProgress(15); progress.setMaximum(15 + books.size()); progress.setNote("uploading new notes"); Map<String, TermSet> indexedSets = new HashMap<String, TermSet>(sets.size()); for (TermSet t : sets) { indexedSets.put(t.getTitle(), t); } int pro = 15; int createdSets = 0; int createdTerms = 0; int updatedTerms = 0; for (List<Clipping> c : books.values()) { String book = c.get(0).getBook(); progress.setNote(book); progress.setProgress(pro++); TermSet termSet = indexedSets.get(book); if (termSet == null) { if (c.size() < 2) { System.err.println("ignored [" + book + "] (need at least two notes)"); continue; } addSet(api, book, c); createdSets++; createdTerms += c.size(); continue; } // compare against existing terms for (Clipping cl : c) { if (!checkExistingTerm(cl, termSet)) { addTerm(api, termSet, cl); updatedTerms++; } } } progress.setProgress(pro++); if (createdSets == 0 && updatedTerms == 0) { JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync", JOptionPane.OK_OPTION); } else if (createdSets > 0) { JOptionPane.showMessageDialog(null, String.format( "Done.\nCreated %d new sets with %d cards, and added %d cards to existing sets", createdSets, createdTerms, updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } else { JOptionPane.showMessageDialog(null, String.format("Done.\nAdded %d cards to existing sets", updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } } finally { progress.close(); } System.exit(0); }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception//from ww w. j av a 2 s. c o m */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step4MTurkOutputCollector.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDirWithArgumentPairs = args[0]; File[] resultFiles;//from w w w . j ava 2 s . co m if (args[1].contains("*")) { File path = new File(args[1]); File directory = path.getParentFile(); String regex = path.getName().replaceAll("\\*", ""); List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { regex }, false)); resultFiles = new File[files.size()]; for (int i = 0; i < files.size(); i++) { resultFiles[i] = files.get(i); } } else { // result file is a comma-separated list of CSV files from MTurk String[] split = args[1].split(","); resultFiles = new File[split.length]; for (int i = 0; i < split.length; i++) { resultFiles[i] = new File(split[i]); } } File outputDir = new File(args[2]); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new IOException("Cannot create directory " + outputDir); } } // error if output folder not empty to prevent any confusion by mixing files if (!FileUtils.listFiles(outputDir, null, false).isEmpty()) { throw new IllegalArgumentException("Output dir " + outputDir + " is not empty"); } // collected assignments with empty reason for rejections Set<String> assignmentsWithEmptyReason = new HashSet<>(); // parse with first line as header MTurkOutputReader mTurkOutputReader = new MTurkOutputReader(resultFiles); Collection<File> files = FileUtils.listFiles(new File(inputDirWithArgumentPairs), new String[] { "xml" }, false); if (files.isEmpty()) { throw new IOException("No xml files found in " + inputDirWithArgumentPairs); } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Map<String, Integer>> assignmentsPerHits = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); String hitTypeId = record.get("hittypeid"); if (!wasRejected) { // update statistics if (!assignmentsPerHits.containsKey(hitTypeId)) { assignmentsPerHits.put(hitTypeId, new HashMap<String, Integer>()); } if (!assignmentsPerHits.get(hitTypeId).containsKey(hitID)) { assignmentsPerHits.get(hitTypeId).put(hitID, 0); } assignmentsPerHits.get(hitTypeId).put(hitID, assignmentsPerHits.get(hitTypeId).get(hitID) + 1); } } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Integer> approvedAssignmentsPerHit = new HashMap<>(); Map<String, Integer> rejectedAssignmentsPerHit = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean approved = "Approved".equals(record.get("assignmentstatus")); boolean rejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); if (approved) { // update statistics if (!approvedAssignmentsPerHit.containsKey(hitID)) { approvedAssignmentsPerHit.put(hitID, 0); } approvedAssignmentsPerHit.put(hitID, approvedAssignmentsPerHit.get(hitID) + 1); } else if (rejected) { // update statistics if (!rejectedAssignmentsPerHit.containsKey(hitID)) { rejectedAssignmentsPerHit.put(hitID, 0); } rejectedAssignmentsPerHit.put(hitID, rejectedAssignmentsPerHit.get(hitID) + 1); } else { throw new IllegalStateException( "Unknown state: " + record.get("assignmentstatus") + " HITID: " + hitID); } } // System.out.println("Approved: " + approvedAssignmentsPerHit); // System.out.println("Rejected: " + rejectedAssignmentsPerHit); System.out.println("Approved (values): " + new HashSet<>(approvedAssignmentsPerHit.values())); System.out.println("Rejected (values): " + new HashSet<>(rejectedAssignmentsPerHit.values())); // rejection statistics int totalRejected = 0; for (Map.Entry<String, Integer> rejectionEntry : rejectedAssignmentsPerHit.entrySet()) { totalRejected += rejectionEntry.getValue(); } System.out.println("Total rejections: " + totalRejected); /* // generate .success files for adding more annotations for (File resultFile : resultFiles) { String hitTypeID = mTurkOutputReader.getHitTypeIdForFile().get(resultFile); // assignments for that hittypeid (= file) Map<String, Integer> assignments = assignmentsPerHits.get(hitTypeID); prepareUpdateHITsFiles(assignments, hitTypeID, resultFile); } */ int totalSavedPairs = 0; // load all previously prepared argument pairs for (File file : files) { List<ArgumentPair> argumentPairs = (List<ArgumentPair>) XStreamTools.getXStream().fromXML(file); List<AnnotatedArgumentPair> annotatedArgumentPairs = new ArrayList<>(); for (ArgumentPair argumentPair : argumentPairs) { AnnotatedArgumentPair annotatedArgumentPair = new AnnotatedArgumentPair(argumentPair); // is there such an answer? String key = "Answer." + argumentPair.getId(); // iterate only if there is such column to save time if (mTurkOutputReader.getColumnNames().contains(key)) { // now find the results for (Map<String, String> record : mTurkOutputReader) { if (record.containsKey(key)) { // extract the values AnnotatedArgumentPair.MTurkAssignment assignment = new AnnotatedArgumentPair.MTurkAssignment(); boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); // only non-rejected (if required) if (!wasRejected) { String hitID = record.get("hitid"); String workerID = record.get("workerid"); String assignmentId = record.get("assignmentid"); try { assignment.setAssignmentAcceptTime( DATE_FORMAT.parse(record.get("assignmentaccepttime"))); assignment.setAssignmentSubmitTime( DATE_FORMAT.parse(record.get("assignmentsubmittime"))); assignment.setHitComment(record.get("Answer.feedback")); assignment.setHitID(hitID); assignment.setTurkID(workerID); assignment.setAssignmentId(assignmentId); // and answer specific fields String valueRaw = record.get(key); // so far the label has had format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only true label String label = valueRaw.split("_")[2]; assignment.setValue(label); String reason = record.get(key + "_reason"); // missing reason if (reason == null) { assignmentsWithEmptyReason.add(assignmentId); } else { assignment.setReason(reason); // get worker's stance String stanceRaw = record.get(key + "_stance"); if (stanceRaw != null) { // parse stance String stance = stanceRaw.split("_stance_")[1]; assignment.setWorkerStance(stance); } // we take maximal 5 assignments Collections.sort(annotatedArgumentPair.mTurkAssignments, new Comparator<AnnotatedArgumentPair.MTurkAssignment>() { @Override public int compare(AnnotatedArgumentPair.MTurkAssignment o1, AnnotatedArgumentPair.MTurkAssignment o2) { return o1.getAssignmentAcceptTime() .compareTo(o2.getAssignmentAcceptTime()); } }); if (annotatedArgumentPair.mTurkAssignments .size() < MAXIMUM_ASSIGNMENTS_PER_HIT) { annotatedArgumentPair.mTurkAssignments.add(assignment); } } } catch (IllegalArgumentException | NullPointerException ex) { System.err.println("Malformed annotations for HIT " + hitID + ", worker " + workerID + ", assignment " + assignmentId + "; " + ex.getMessage() + ", full record: " + record); } } } } } // and if there are some annotations, add it to the result set if (!annotatedArgumentPair.mTurkAssignments.isEmpty()) { annotatedArgumentPairs.add(annotatedArgumentPair); } } if (!annotatedArgumentPairs.isEmpty()) { File outputFile = new File(outputDir, file.getName()); XStreamTools.toXML(annotatedArgumentPairs, outputFile); System.out.println("Saved " + annotatedArgumentPairs.size() + " annotated pairs to " + outputFile); totalSavedPairs += annotatedArgumentPairs.size(); } } System.out.println("Total saved " + totalSavedPairs + " pairs"); // print assignments with empty reasons if (!assignmentsWithEmptyReason.isEmpty()) { System.out.println( "== Assignments with empty reason:\nassignmentIdToReject\tassignmentIdToRejectComment"); for (String assignmentId : assignmentsWithEmptyReason) { System.out.println( assignmentId + "\t\"Dear worker, you did not fill the required field with a reason.\""); } } }
From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java
/** * @param args// w w w .j a v a2 s . co m */ public static void main(String[] args) { // Setup parameters int verbosity = 1; String output_format = "xml", grammar_filename = null, filename_to_parse = null; // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("f")) { output_format = c_line.getOptionValue("f"); } // Get grammar file @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no grammar file specified"); System.exit(ERR_ARGUMENTS); } grammar_filename = remaining_args.get(0); // Get file to parse, if any if (remaining_args.size() >= 2) { filename_to_parse = remaining_args.get(1); } // Read grammar file BnfParser parser = null; try { parser = new BnfParser(new File(grammar_filename)); } catch (InvalidGrammarException e) { System.err.println("ERROR: invalid grammar"); System.exit(ERR_GRAMMAR); } catch (IOException e) { System.err.println("ERROR reading grammar " + grammar_filename); System.exit(ERR_IO); } assert parser != null; // Read input file BufferedReader bis = null; if (filename_to_parse == null) { // Read from stdin bis = new BufferedReader(new InputStreamReader(System.in)); } else { // Read from file try { bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse)))); } catch (FileNotFoundException e) { System.err.println("ERROR: file not found " + filename_to_parse); System.exit(ERR_IO); } } assert bis != null; String str; StringBuilder input_file = new StringBuilder(); try { while ((str = bis.readLine()) != null) { input_file.append(str).append("\n"); } } catch (IOException e) { System.err.println("ERROR reading input"); System.exit(ERR_IO); } String file_contents = input_file.toString(); // Parse contents of file ParseNode p_node = null; try { p_node = parser.parse(file_contents); } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) { System.err.println("ERROR parsing input\n"); e.printStackTrace(); System.exit(ERR_PARSE); } if (p_node == null) { System.err.println("ERROR parsing input\n"); System.exit(ERR_PARSE); } assert p_node != null; // Output parse node to desired format PrintStream output = System.out; OutputFormatVisitor out_vis = null; if (output_format.compareToIgnoreCase("xml") == 0) { // Output to XML out_vis = new XmlVisitor(); } else if (output_format.compareToIgnoreCase("dot") == 0) { // Output to DOT out_vis = new GraphvizVisitor(); } else if (output_format.compareToIgnoreCase("txt") == 0) { // Output to indented plain text out_vis = new IndentedTextVisitor(); } else if (output_format.compareToIgnoreCase("json") == 0) { // Output to JSON } if (out_vis == null) { System.err.println("ERROR: unknown output format " + output_format); System.exit(ERR_ARGUMENTS); } assert out_vis != null; p_node.prefixAccept(out_vis); output.print(out_vis.toOutputString()); // Terminate without error System.exit(ERR_OK); }
From source file:com.topsem.common.io.excel.ExportExcel.java
/** * //from w w w.j a va2 s . co m */ public static void main(String[] args) throws Throwable { List<String> headerList = Lists.newArrayList(); for (int i = 1; i <= 10; i++) { headerList.add("" + i); } List<String> dataRowList = Lists.newArrayList(); for (int i = 1; i <= headerList.size(); i++) { dataRowList.add("?" + i); } List<List<String>> dataList = Lists.newArrayList(); for (int i = 1; i <= 100; i++) { dataList.add(dataRowList); } ExportExcel ee = new ExportExcel("", headerList); for (int i = 0; i < dataList.size(); i++) { Row row = ee.addRow(); for (int j = 0; j < dataList.get(i).size(); j++) { ee.addCell(row, j, dataList.get(i).get(j)); } } ee.writeFile("target/export.xlsx"); ee.dispose(); log.debug("Export success."); }
From source file:bsc.spark.examples.terasort.ehiggs.TeraScheduler.java
public static void main(String[] args) throws IOException { TeraScheduler problem = new TeraScheduler("block-loc.txt", "nodes"); for (Host host : problem.hosts) { System.out.println(host); }/*from ww w. j ava 2 s .c o m*/ LOG.info("starting solve"); problem.solve(); List<Split> leftOvers = new ArrayList<Split>(); for (int i = 0; i < problem.splits.length; ++i) { if (problem.splits[i].isAssigned) { System.out.println("sched: " + problem.splits[i]); } else { leftOvers.add(problem.splits[i]); } } for (Split cur : leftOvers) { System.out.println("left: " + cur); } System.out.println("left over: " + leftOvers.size()); LOG.info("done"); }