List of usage examples for com.google.common.collect Lists newArrayList
@GwtCompatible(serializable = true) public static <E> ArrayList<E> newArrayList()
From source file:com.googlecode.java2objc.main.Main.java
public static void main(String[] args) throws Exception { args = AndroidYoutubeQuery.getArgs(); if (args.length == 0) { printUsageAndExit();/*from w w w .j a va2 s. c om*/ } Config config = new Config(); List<String> javaFiles = Lists.newArrayList(); for (String arg : args) { if (arg.startsWith("--")) { // A configuration setting config.update(arg); } else { // Probably a Java file javaFiles.add(arg); } } Main main = new Main(config, javaFiles); main.execute(); }
From source file:com.google.devtools.build.android.idlclass.IdlClass.java
public static void main(String[] args) throws IOException { OptionsParser optionsParser = OptionsParser.newOptionsParser(IdlClassOptions.class); optionsParser.parseAndExitUponError(args); IdlClassOptions options = optionsParser.getOptions(IdlClassOptions.class); Preconditions.checkNotNull(options.manifestProto); Preconditions.checkNotNull(options.classJar); Preconditions.checkNotNull(options.outputClassJar); Preconditions.checkNotNull(options.outputSourceJar); Preconditions.checkNotNull(options.tempDir); List<Path> idlSources = Lists.newArrayList(); for (String idlSource : optionsParser.getResidue()) { idlSources.add(Paths.get(idlSource)); }//from ww w. ja va 2s. c o m Manifest manifest = readManifest(options.manifestProto); writeClassJar(options, idlSources, manifest); writeSourceJar(options, idlSources, manifest); }
From source file:com.sccl.attech.generate.Generate.java
/** * The main method./*www.j ava 2 s . c o m*/ * * @param args the arguments * @throws Exception the exception */ public static void main(String[] args) throws Exception { // ========== ?? ====================1412914 // ?????? // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.sccl.attech.modules"; String moduleName = "mobil"; // ???sys String subModuleName = ""; // ????? String className = "updateApp"; // ??user List<GenerateField> fields = Lists.newArrayList(); fields.add(new GenerateField("name", "??")); fields.add(new GenerateField("type", "")); fields.add(new GenerateField("version", "")); fields.add(new GenerateField("path", "")); String classAuthor = "zzz"; // zhaozz String functionName = "App?"; // ?? // ??? //Boolean isEnable = false; Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; // ? File projectPath = new DefaultResourceLoader().getResource("").getFile(); while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) { projectPath = projectPath.getParentFile(); } logger.info("Project Path: {}", projectPath); // ? String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/sccl/attech/generate/template", "/", separator); logger.info("Template Path: {}", tplPath); // Java String javaPath = StringUtils.replaceEach( projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." }, new String[] { separator, separator }); logger.info("Java Path: {}", javaPath); // String viewPath = StringUtils.replace(projectPath + "/WebRoot/pages", "/", separator); logger.info("View Path: {}", viewPath); String resPath = StringUtils.replace(projectPath + "/WebRoot/assets/js", "/", separator); logger.info("Res Path: {}", resPath); // ??? Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setDirectoryForTemplateLoading(new File(tplPath)); // ??? Map<String, Object> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("fields", fields); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("tableName", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "_" + StringUtils.lowerCase(subModuleName) : "") + "_" + model.get("className")); model.put("urlPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "") + "/" + model.get("className")); model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+ model.get("urlPrefix")); model.put("permissionPrefix", model.get("moduleName") + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "") + ":" + model.get("className")); // ? Entity Template template = cfg.getTemplate("entity.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info("Entity: {}", filePath); // ? Dao template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Dao.java"; writeFile(content, filePath); logger.info("Dao: {}", filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Service.java"; writeFile(content, filePath); logger.info("Service: {}", filePath); // ? Controller createJavaFile(subModuleName, separator, javaPath, cfg, model); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "Form.html"; writeFile(content, filePath); logger.info("ViewForm: {}", filePath); // ? ViewFormJs template = cfg.getTemplate("viewFormJs.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "FormCtrl.js"; writeFile(content, filePath); logger.info("ViewFormJs: {}", filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "List.html"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); // ? ViewListJs template = cfg.getTemplate("viewListJs.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = resPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + "ListCtrl.js"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); // ? ??sql template = cfg.getTemplate("sql.ftl"); model.put("uid", IdGen.uuid()); model.put("uid1", IdGen.uuid()); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath//+separator+StringUtils.substringAfterLast(model.get("packageName"),".") + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("className") + ".sql"; writeFile(content, filePath); logger.info("ViewList: {}", filePath); logger.info("Generate Success."); }
From source file:com.ondeck.datapipes.examples.SimpleFlowExample.java
public static void main(String[] args) throws FlowException { /**//from w w w . j ava 2 s . co m * A Dataprovider step is required to provide input to a Flow */ DataProviderStep<String> dataProviderStep = new DataProviderStep<>(TypeToken.of(String.class)); /** * Step one is a FunctionStep that takes a String argument and converts it into an Integer. * The parent of this step is the dataProviderStep. */ FunctionStep<String, Integer> stepOne = new FunctionStep<>(new Function<String, Integer>() { @Override public Integer apply(String sourceValue) { List<Integer> list = Lists.newArrayList(); list.add(Integer.valueOf(sourceValue)); System.out.println("Step One : Input string is " + sourceValue + ". Converting to int."); return Integer.valueOf(sourceValue); } }, dataProviderStep, TypeToken.of(Integer.class)); /** * Step two is a FunctionStep that takes the result of step one and multiplies it by two. */ FunctionStep<Integer, Integer> stepTwo = new FunctionStep<>(new Function<Integer, Integer>() { @Override public Integer apply(Integer sourceValue) { System.out.println("Step Two : Multiplying input by 2"); return sourceValue * 2; } }, stepOne, TypeToken.of(Integer.class)); /** * Finally use an executor to execute the flow. */ String[] inputs = new String[] { "1", "50", "12" }; for (String i : inputs) { SimpleExecuteVisitor<Integer> executeVisitor = new SimpleExecuteVisitor<>(); executeVisitor.addInput(new TypeToken<String>() { }, i); Integer result = executeVisitor.execute(stepTwo); System.out.println("Result is " + result); System.out.println(); } }
From source file:edu.umd.jyothivinjumur.AnalyzeBigramRelativeFrequencyTuple.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;//from w w w. ja v a 2s. com CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<Tuple, FloatWritable>> pairs = SequenceFileUtils.readDirectory(new Path(inputPath)); List<PairOfWritables<Tuple, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<Tuple, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<Tuple, FloatWritable> p : pairs) { Tuple bigram = p.getLeftElement(); if (bigram.get(0).equals("light")) { list1.add(p); } if (bigram.get(0).equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter1.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter2.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:com.spotify.cassandra.opstools.SSTableTimestampViewer.java
/** * @param args a list of sstables whose metadata we're interested in *///ww w.j av a 2 s .c om public static void main(String[] args) throws IOException { PrintStream out = System.out; if (args.length == 0) { out.println("Usage: spcassandra-sstable-timestamp <sstable filenames>"); System.exit(1); } List<TimeMetadata> metadata = Lists.newArrayListWithExpectedSize(args.length); for (String fname : args) { Descriptor descriptor = Descriptor.fromFilename(fname); SSTableMetadata md = SSTableMetadata.serializer.deserialize(descriptor).left; metadata.add(new TimeMetadata(descriptor.toString(), md.minTimestamp, md.maxTimestamp, new java.io.File(descriptor.baseFilename() + "-Data.db").length())); } Collections.sort(metadata, new Comparator<TimeMetadata>() { public int compare(TimeMetadata o1, TimeMetadata o2) { return Long.compare(o1.minTimestamp, o2.minTimestamp); } }); long[] timespanHistogram = new long[metadata.size() + 1]; SortedSet<TimeMetadata> currentOverlaps = new TreeSet<>(new Comparator<TimeMetadata>() { public int compare(TimeMetadata o1, TimeMetadata o2) { return Long.compare(o1.maxTimestamp, o2.maxTimestamp); } }); List<Interval<Long, Integer>> intervals = Lists.newArrayList(); long currentTime = 0; boolean wasMax = false; for (TimeMetadata md : metadata) { while (currentOverlaps.size() > 0 && currentOverlaps.first().maxTimestamp < md.minTimestamp) { intervals.add(new Interval<>(currentTime, !wasMax, currentOverlaps.first().maxTimestamp, true, currentOverlaps.size())); timespanHistogram[currentOverlaps.size()] += currentOverlaps.first().maxTimestamp - currentTime; currentTime = currentOverlaps.first().maxTimestamp; wasMax = true; currentOverlaps.remove(currentOverlaps.first()); } if (currentTime != 0) { intervals.add(new Interval<>(currentTime, !wasMax, md.minTimestamp, false, currentOverlaps.size())); timespanHistogram[currentOverlaps.size()] += md.minTimestamp - currentTime; } currentTime = md.minTimestamp; wasMax = false; currentOverlaps.add(md); } while (currentOverlaps.size() > 0) { intervals.add(new Interval<>(currentTime, !wasMax, currentOverlaps.first().maxTimestamp, true, currentOverlaps.size())); timespanHistogram[currentOverlaps.size()] += currentOverlaps.first().maxTimestamp - currentTime; currentTime = currentOverlaps.first().maxTimestamp; wasMax = true; currentOverlaps.remove(currentOverlaps.first()); } for (TimeMetadata md : metadata) out.println(md); for (Interval<Long, Integer> interval : intervals) out.println(interval); out.println(); for (int i = 0; i < timespanHistogram.length; i++) out.printf("Total time covered by %s sstables: %s (%.2f%%)%n", i, timespanHistogram[i], (double) timespanHistogram[i] / (currentTime - metadata.get(0).minTimestamp) * 100); }
From source file:org.spongepowered.repoindexer.EntryPoint.java
public static void main(String args[]) { try {// w w w. j a va 2 s. c o m JCommander jc = new JCommander(Cmd.getInstance(), args); Artifact artifact; artifactslist = Lists.newArrayList(); String[] repostuff = Cmd.getInstance().mavencoord.split(":"); artifact = new Artifact(new Repo(Cmd.getInstance().mavenrepo), repostuff[0], repostuff[1]); String[] sets = Cmd.getInstance().extra.split("%"); for (String s : sets) { System.out.println(s); String[] tmp = s.split("\\^"); if (tmp.length > 1) { if (tmp[0].equals("null")) { tmp[0] = null; } if (tmp[1].equals("null")) { tmp[1] = null; } artifact.addVariation(new Variation(tmp[0], tmp[1])); System.out.println("added variation " + tmp[0] + " " + tmp[1]); } } //artifact.addVariation(new Variation(null, "exe")); //artifact.addVariation(new Variation(null, "zip")); //File location = new File("/Users/progwml6/repos/mc/repoindex/src/main/dltemplates/index.mustache"); File out = new File("build/repoindexer/index.html"); if (!out.getParentFile().exists()) { out.getParentFile().mkdirs(); } process(new File(Cmd.getInstance().loc), out, artifact, Cmd.getInstance().url, Cmd.getInstance().user, Cmd.getInstance().pass, Cmd.getInstance().base, Cmd.getInstance().ftpmode ? FTPType.FTP : FTPType.SFTP); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.mahout.cf.taste.example.kddcup.track1.Track1Runner.java
public static void main(String[] args) throws Exception { File dataFileDirectory = new File(args[0]); if (!dataFileDirectory.exists() || !dataFileDirectory.isDirectory()) { throw new IllegalArgumentException("Bad data file directory: " + dataFileDirectory); }/*from www . j a v a2s .c o m*/ long start = System.currentTimeMillis(); KDDCupDataModel model = new KDDCupDataModel(KDDCupDataModel.getTrainingFile(dataFileDirectory)); Track1Recommender recommender = new Track1Recommender(model); long end = System.currentTimeMillis(); log.info("Loaded model in {}s", (end - start) / 1000); start = end; Collection<Track1Callable> callables = Lists.newArrayList(); for (Pair<PreferenceArray, long[]> tests : new DataFileIterable( KDDCupDataModel.getTestFile(dataFileDirectory))) { PreferenceArray userTest = tests.getFirst(); callables.add(new Track1Callable(recommender, userTest)); } int cores = Runtime.getRuntime().availableProcessors(); log.info("Running on {} cores", cores); ExecutorService executor = Executors.newFixedThreadPool(cores); List<Future<byte[]>> results = executor.invokeAll(callables); executor.shutdown(); end = System.currentTimeMillis(); log.info("Ran recommendations in {}s", (end - start) / 1000); start = end; OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(args[1]))); try { for (Future<byte[]> result : results) { for (byte estimate : result.get()) { out.write(estimate); } } } finally { Closeables.close(out, false); } end = System.currentTimeMillis(); log.info("Wrote output in {}s", (end - start) / 1000); }
From source file:com.sina.dip.twill.HelloWorld.java
public static void main(String[] args) { String zkStr = "localhost:2181"; YarnConfiguration yarnConfiguration = new YarnConfiguration(); final TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfiguration, zkStr); twillRunner.start();//from ww w .ja v a2s .c o m String yarnClasspath = yarnConfiguration.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH, "/usr/lib/hadoop/*,/usr/lib/hadoop-0.20-mapreduce/*,/usr/lib/hadoop-hdfs/*,/usr/lib/hadoop-mapreduce/*,/usr/lib/hadoop-yarn/*"); List<String> applicationClassPaths = Lists.newArrayList(); Iterables.addAll(applicationClassPaths, Splitter.on(",").split(yarnClasspath)); final TwillController controller = twillRunner.prepare(new HelloWorldRunnable()) .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out, true))) .withApplicationClassPaths(applicationClassPaths) .withBundlerClassAcceptor(new HadoopClassExcluder()).start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { Futures.getUnchecked(controller.terminate()); } finally { twillRunner.stop(); } } }); try { controller.awaitTerminated(); } catch (ExecutionException e) { e.printStackTrace(); } }
From source file:javaapplication3.RunRandomForestSeq.java
public static void main(String[] args) throws IOException { String outputFile = "data/out"; String inputFile = "data/DataFraud1MTest.csv"; String modelFile = "data/forest.seq"; String infoFile = "data/DataFraud1M.info"; Path dataPath = new Path(inputFile); // test data path Path datasetPath = new Path(infoFile); Path modelPath = new Path(modelFile); // path where the forest is stored Path outputPath = new Path(outputFile); // path to predictions file, if null do not output the predictions Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); FileSystem outFS = FileSystem.get(conf); //log.info("Loading the forest..."); System.out.println("Loading the forest"); DecisionForest forest = DecisionForest.load(conf, modelPath); if (forest == null) System.err.println("No decision forest found!"); //log.error("No Decision Forest found!"); // load the dataset Dataset dataset = Dataset.load(conf, datasetPath); DataConverter converter = new DataConverter(dataset); //log.info("Sequential classification..."); System.out.println("Sequential classification"); long time = System.currentTimeMillis(); Random rng = RandomUtils.getRandom(); List<double[]> resList = Lists.newArrayList(); if (fs.getFileStatus(dataPath).isDir()) { //the input is a directory of files testDirectory(outputPath, converter, forest, dataset, resList, rng, fs, dataPath, outFS); } else {/*from w w w . ja v a2 s. c om*/ // the input is one single file testFile(dataPath, outputPath, converter, forest, dataset, resList, rng, outFS, fs); } time = System.currentTimeMillis() - time; //log.info("Classification Time: {}", DFUtils.elapsedTime(time)); System.out.println("Classification time: " + DFUtils.elapsedTime(time)); if (dataset.isNumerical(dataset.getLabelId())) { RegressionResultAnalyzer regressionAnalyzer = new RegressionResultAnalyzer(); double[][] results = new double[resList.size()][2]; regressionAnalyzer.setInstances(resList.toArray(results)); //log.info("{}", regressionAnalyzer); System.out.println(regressionAnalyzer.toString()); } else { ResultAnalyzer analyzer = new ResultAnalyzer(Arrays.asList(dataset.labels()), "unknown"); for (double[] r : resList) { analyzer.addInstance(dataset.getLabelString(r[0]), new ClassifierResult(dataset.getLabelString(r[1]), 1.0)); } //log.info("{}", analyzer); System.out.println(analyzer.toString()); } }