List of usage examples for java.util List subList
List<E> subList(int fromIndex, int toIndex);
From source file:ShuffleTest.java
public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); for (int i = 1; i <= 49; i++) numbers.add(i);//from w ww.j av a 2s.c om Collections.shuffle(numbers); List<Integer> winningCombination = numbers.subList(0, 6); Collections.sort(winningCombination); System.out.println(winningCombination); }
From source file:Main.java
public static void main(String[] argv) throws Exception { List list1 = new ArrayList(); List list2 = new ArrayList(); list1.addAll(list2);// www. java2s . c o m list1.removeAll(list2); list1.retainAll(list2); list1.clear(); int newSize = 2; list1.subList(newSize, list1.size()).clear(); }
From source file:Main.java
public static void main(String[] argv) throws Exception { List<String> list1 = new ArrayList(); List<String> list2 = new ArrayList(); list1.addAll(list2);/*from w w w .ja v a 2 s . com*/ list1.removeAll(list2); list1.retainAll(list2); list1.clear(); int newSize = 2; list1.subList(newSize, list1.size()).clear(); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java
public static void main(String[] args) throws Exception { String inputDir = args[0];/*from www . ja v a 2 s. c o m*/ // /tmp File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // pseudo-random final Random random = new Random(1); int totalPairsCount = 0; // read all debates for (File file : IOHelper.listXmlFiles(new File(inputDir))) { Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8")); // get two stances SortedSet<String> originalStances = debate.getStances(); // cleaning: some debate has three or more stances (data are inconsistent) // remove those with only one argument SortedSet<String> stances = new TreeSet<>(); for (String stance : originalStances) { if (debate.getArgumentsForStance(stance).size() > 1) { stances.add(stance); } } if (stances.size() != 2) { throw new IllegalStateException( "2 stances per debate expected, was " + stances.size() + ", " + stances); } // for each stance, get pseudo-random N arguments for (String stance : stances) { List<Argument> argumentsForStance = debate.getArgumentsForStance(stance); // shuffle Collections.shuffle(argumentsForStance, random); // and get max first N arguments List<Argument> selectedArguments = argumentsForStance.subList(0, argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size() : MAX_SELECTED_ARGUMENTS_PRO_SIDE); List<ArgumentPair> argumentPairs = new ArrayList<>(); // now create pairs for (int i = 0; i < selectedArguments.size(); i++) { for (int j = (i + 1); j < selectedArguments.size(); j++) { Argument arg1 = selectedArguments.get(i); Argument arg2 = selectedArguments.get(j); ArgumentPair argumentPair = new ArgumentPair(); argumentPair.setDebateMetaData(debate.getDebateMetaData()); // assign arg1 and arg2 pseudo-randomly // (not to have the same argument as arg1 all the time) if (random.nextBoolean()) { argumentPair.setArg1(arg1); argumentPair.setArg2(arg2); } else { argumentPair.setArg1(arg2); argumentPair.setArg2(arg1); } // set unique id argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId()); argumentPairs.add(argumentPair); } } String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); totalPairsCount += argumentPairs.size(); } } System.out.println("Total pairs generated: " + totalPairsCount); }
From source file:Main.java
public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Oracle"); list.add("CSS"); list.add("XML"); System.out.println("List: " + list); int count = list.size(); System.out.println("Size of List: " + count); // Print each element with its index for (int i = 0; i < count; i++) { String element = list.get(i); System.out.println("Index=" + i + ", Element=" + element); }/*from ww w.j a v a 2 s. co m*/ List<String> subList = list.subList(1, 3); System.out.println(subList); // Remove "CSS" from the list list.remove("CSS"); // Same as list.remove(2); System.out.println(list); }
From source file:edu.illinois.cs.cogcomp.utils.Utils.java
public static void main(String[] args) throws Exception { //romanization(); String[] arabic_names = { "Urdu", "Arabic", "Egyptian_Arabic", "Mazandarani", "Pashto", "Persian", "Western_Punjabi" }; String[] devanagari_names = { "Newar", "Hindi", "Marathi", "Nepali", "Sanskrit" }; String[] cyrillic_names = { "Chuvash", "Bashkir", "Bulgarian", "Chechen", "Kirghiz", "Macedonian", "Russian", "Ukrainian" }; //for(String name : arabic_names){ //System.out.println(name + " : " + WAVE("models/probs-"+name+"-Urdu.txt")); //getSize(name); //}/*from w w w . j a v a 2 s . co m*/ String lang = "Arabic"; String wikidata = "Data/wikidata." + lang; List<String> allnames = LineIO.read("/Users/stephen/Dropbox/papers/NAACL2016/data/all-names2.txt"); List<Example> training = readWikiData(wikidata); training = training.subList(0, 2000); SPModel m = new SPModel(training); m.Train(5); TopList<Double, String> res = m.Generate("stephen"); System.out.println(res); List<String> outlines = new ArrayList<>(); int i = 0; for (String nameAndLabel : allnames) { if (i % 100 == 0) { System.out.println(i); } i++; String[] s = nameAndLabel.split("\t"); String name = s[0]; String label = s[1]; String[] sname = name.split(" "); String line = ""; for (String tok : sname) { res = m.Generate(tok.toLowerCase()); if (res.size() > 0) { String topcand = res.getFirst().getSecond(); line += topcand + " "; } else { } } if (line.trim().length() > 0) { outlines.add(line.trim() + "\t" + label); } } LineIO.write("/Users/stephen/Dropbox/papers/NAACL2016/data/all-names-" + lang + "2.txt", outlines); // Transliterator t = Transliterator.getInstance("Any-am_FONIPA"); // // String result = t.transform("Stephen"); // System.out.println(result); // // Enumeration<String> tids = t.getAvailableIDs(); // // while(tids.hasMoreElements()){ // String e = tids.nextElement(); // System.out.println(e); // } }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step10RemoveEmptyDocuments.java
public static void main(String[] args) throws IOException { // input dir - list of xml query containers File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs();/*from w w w . java2 s . c om*/ } boolean crop = args.length >= 3 && "crop".equals(args[2]); // first find the maximum of zero-sized documents int maxMissing = 7; /* // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); // first find the maximum of zero-sized documents in a query int missingInQuery = 0; for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { // boilerplate removal if (rankedResults.plainText == null || rankedResults.plainText.isEmpty()) { missingInQuery++; } } maxMissing = Math.max(missingInQuery, maxMissing); } */ System.out.println("Max zeroLengthDocuments in query: " + maxMissing); // max is 7 = we're cut-off at 93 // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); List<QueryResultContainer.SingleRankedResult> nonEmptyDocsList = new ArrayList<>(); for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { // collect non-empty documents if (rankedResults.plainText != null && !rankedResults.plainText.isEmpty()) { nonEmptyDocsList.add(rankedResults); } } System.out.println("Non-empty docs coune: " + nonEmptyDocsList.size()); if (crop) { // now cut at 93 nonEmptyDocsList = nonEmptyDocsList.subList(0, (100 - maxMissing)); System.out.println("After cropping: " + nonEmptyDocsList.size()); } System.out.println("After cleaning: " + nonEmptyDocsList.size()); queryResultContainer.rankedResults.clear(); queryResultContainer.rankedResults.addAll(nonEmptyDocsList); // and save the query to output dir File outputFile = new File(outputDir, queryResultContainer.qID + ".xml"); FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8"); System.out.println("Finished " + outputFile); } }
From source file:org.n52.oss.testdata.sml.GeneratorClient.java
/** * @param args//from w w w . java 2 s . co m */ public static void main(String[] args) { if (sending) log.info("Starting insertion of test sensors into " + sirURL); else log.warn("Starting generation of test sensors, NOT sending!"); TestSensorFactory factory = new TestSensorFactory(); // create sensors List<TestSensor> sensors = new ArrayList<TestSensor>(); for (int i = 0; i < nSensorsToGenerate; i++) { TestSensor s = factory.createRandomTestSensor(); sensors.add(s); log.info("Added new random sensor: " + s); } ArrayList<String> insertedSirIds = new ArrayList<String>(); // insert sensors to service int startOfSubList = 0; int endOfSubList = nSensorsInOneInsertRequest; while (endOfSubList <= sensors.size() + nSensorsInOneInsertRequest) { List<TestSensor> currentSensors = sensors.subList(startOfSubList, Math.min(endOfSubList, sensors.size())); if (currentSensors.isEmpty()) break; try { String[] insertedSirIDs = insertSensorsInSIR(currentSensors); if (insertedSirIDs == null) { log.error("Did not insert dummy sensors."); } else { insertedSirIds.addAll(Arrays.asList(insertedSirIDs)); } } catch (HttpException e) { log.error("Error inserting sensors.", e); } catch (IOException e) { log.error("Error inserting sensors.", e); } startOfSubList = Math.min(endOfSubList, sensors.size()); endOfSubList = endOfSubList + nSensorsInOneInsertRequest; if (sending) { try { if (log.isDebugEnabled()) log.debug("Sleeping for " + SLEEP_BETWEEN_REQUESTS + " msecs."); Thread.sleep(SLEEP_BETWEEN_REQUESTS); } catch (InterruptedException e) { log.error("Interrupted!", e); } } } log.info("Added sensors (ids in sir): " + Arrays.toString(insertedSirIds.toArray())); }
From source file:com.appeligo.epg.EpgIndexer.java
public static void main(String[] args) throws Exception { HessianProxyFactory factory = new HessianProxyFactory(); EPGProvider epg = (EPGProvider) factory.create(EPGProvider.class, "http://localhost/epg/channel.epg"); Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -5);/*from w w w. j av a 2s. c o m*/ cal.set(Calendar.DATE, 1); String[] lineups = new String[] { "SDTW-C", "P-C", "P-DC", "P-S", "M-C", "M-DC", "M-S", "E-C", "E-DC", "E-S", "H-C", "H-DC", "H-S" }; List<String> ids = epg.getModifiedProgramIds(cal.getTime()); int count = 0; long average = 0; int counter = 0; int added = 0; while (count < ids.size()) { System.err.println("in loop: " + counter + ", " + count + "," + ids.size()); int subsetSize = (ids.size() < 100 ? ids.size() : 100); counter++; if (count % 1000 == 0) { log.debug("Index programs into the Lucene Index. Current have processed " + count + " programs out of " + ids.size()); } int endIndex = (count + subsetSize > ids.size() ? ids.size() : count + subsetSize); List<String> subset = ids.subList(count, endIndex); count += subsetSize; long time = System.currentTimeMillis(); HashMap<String, List<ScheduledProgram>> schedules = new HashMap<String, List<ScheduledProgram>>(); for (String lineup : lineups) { ScheduledProgram[] programs = epg.getNextShowingList(lineup, subset); for (ScheduledProgram program : programs) { if (program != null) { List<ScheduledProgram> schedule = schedules.get(program.getProgramId()); if (schedule == null) { schedule = new ArrayList<ScheduledProgram>(); schedules.put(program.getProgramId(), schedule); } schedule.add(program); added++; } } } long after = System.currentTimeMillis(); long diff = after - time; average += diff; System.err.println(diff + " - " + (average / counter) + " added: " + added); } // EpgIndexer indexer = new EpgIndexer(programIndex, epg, lineup); // Calendar cal = Calendar.getInstance(); // cal.set(Calendar.DAY_OF_MONTH, 24); // cal.set(Calendar.HOUR_OF_DAY, 0); // indexer.updateEpgIndex(cal.getTime()); }
From source file:com.strider.datadefender.DataDefender.java
@SuppressWarnings("unchecked") public static void main(final String[] args) throws ParseException, DatabaseDiscoveryException, IOException, SAXException, TikaException, java.text.ParseException, FileDiscoveryException { final long startTime = System.currentTimeMillis(); // Ensure we are not trying to run second instance of the same program final ApplicationLock al = new ApplicationLock("DataDefender"); if (al.isAppActive()) { LOG.error("Another instance of this program is already active"); displayExecutionTime(startTime); System.exit(1);/*from www . j a v a 2 s .c om*/ } LOG.info("Command-line arguments: " + Arrays.toString(args)); final Options options = createOptions(); final CommandLine line = getCommandLine(options, args); @SuppressWarnings("unchecked") List<String> unparsedArgs = line.getArgList(); if (line.hasOption("help") || (args.length == 0) || (unparsedArgs.size() < 1)) { help(options); displayExecutionTime(startTime); return; } if (line.hasOption("debug")) { LogManager.getRootLogger().setLevel(Level.DEBUG); } else { LogManager.getRootLogger().setLevel(Level.INFO); } final String cmd = unparsedArgs.get(0); // get & remove command arg unparsedArgs = unparsedArgs.subList(1, unparsedArgs.size()); List<String> errors = new ArrayList(); if ("file-discovery".equals(cmd)) { errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String fileDiscoveryPropertyFile = line.getOptionValue('F', "filediscovery.properties"); final Properties fileDiscoveryProperties = loadPropertiesFromClassPath(fileDiscoveryPropertyFile); final FileDiscoverer discoverer = new FileDiscoverer(); discoverer.discover(fileDiscoveryProperties); displayExecutionTime(startTime); return; } // Get db properties file from command line argument or use default db.properties final String dbPropertiesFile = line.getOptionValue('P', "db.properties"); errors = PropertyCheck.checkDtabaseProperties(dbPropertiesFile); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final Properties props = loadProperties(dbPropertiesFile); try (final IDBFactory dbFactory = IDBFactory.get(props);) { switch (cmd) { case "anonymize": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String anonymizerPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties anonymizerProperties = loadProperties(anonymizerPropertyFile); final IAnonymizer anonymizer = new DatabaseAnonymizer(); anonymizer.anonymize(dbFactory, anonymizerProperties); break; case "generate": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final IGenerator generator = new DataGenerator(); final String generatorPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties generatorProperties = loadProperties(generatorPropertyFile); generator.generate(dbFactory, generatorProperties); break; case "database-discovery": if (line.hasOption('c')) { errors = PropertyCheck.check(cmd, 'c'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String columnPropertyFile = line.getOptionValue('C', "columndiscovery.properties"); final Properties columnProperties = loadProperties(columnPropertyFile); final ColumnDiscoverer discoverer = new ColumnDiscoverer(); discoverer.discover(dbFactory, columnProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } else if (line.hasOption('d')) { errors = PropertyCheck.check(cmd, 'd'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String datadiscoveryPropertyFile = line.getOptionValue('D', "datadiscovery.properties"); final Properties dataDiscoveryProperties = loadProperties(datadiscoveryPropertyFile); final DatabaseDiscoverer discoverer = new DatabaseDiscoverer(); discoverer.discover(dbFactory, dataDiscoveryProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } break; default: help(options); break; } } displayExecutionTime(startTime); }