List of usage examples for java.util ArrayList toArray
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a)
From source file:ArrayListToArray.java
public static void main(String args[]) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1);/*from ww w. j a v a 2s . co m*/ al.add(2); al.add(3); al.add(4); System.out.println("Contents of al: " + al); Integer ia[] = new Integer[al.size()]; ia = al.toArray(ia); int sum = 0; for (int i : ia) sum += i; System.out.println("Sum is: " + sum); }
From source file:Main.java
public static void main(String[] args) { ArrayList<String> al = new ArrayList<String>(); al.add("Java"); al.add("SQL"); al.add("Data"); System.out.println("ArrayList:" + al); String[] s1 = new String[al.size()]; String[] s2 = al.toArray(s1); System.out.println("s1 == s2:" + (s1 == s2)); System.out.println("s1:" + Arrays.toString(s1)); System.out.println("s2:" + Arrays.toString(s2)); s1 = new String[1]; s1[0] = "hello"; // Store hello in first element s2 = al.toArray(s1);//www .j av a 2 s . c o m System.out.println("s1 == s2:" + (s1 == s2)); System.out.println("s1:" + Arrays.toString(s1)); System.out.println("s2:" + Arrays.toString(s2)); }
From source file:MainClass.java
public static void main(String args[]) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1);/* w w w . j a v a 2 s . c o m*/ al.add(2); al.add(3); al.add(4); System.out.println("Contents of al: " + al); Integer ia[] = new Integer[al.size()]; ia = al.toArray(ia); int sum = 0; for (int i : ia) sum += i; System.out.println("Sum is: " + sum); }
From source file:Main.java
public static void main(String[] args) { ArrayList<Integer> arrlist = new ArrayList<Integer>(); arrlist.add(10);/*from w w w. j a va2 s .c o m*/ arrlist.add(12); arrlist.add(31); arrlist.add(49); // toArray copies content into other array Integer myArray[] = new Integer[arrlist.size()]; myArray = arrlist.toArray(myArray); System.out.println(Arrays.toString(myArray)); }
From source file:dk.dma.nogoservice.Application.java
public static void main(String[] args) { SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class); ArrayList<String> profiles = Lists.newArrayList(ApiProfiles.PRODUCTION, ApiProfiles.SECURITY); if (Boolean.getBoolean("disableSecurity")) { profiles.remove(ApiProfiles.SECURITY); }// w w w . j a v a 2s . c o m builder.profiles(profiles.toArray(new String[profiles.size()])).headless(false).run(args); }
From source file:com.tamingtext.classifier.bayes.ClassifyDocument.java
public static void main(String[] args) { log.info("Command-line arguments: " + Arrays.toString(args)); DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("input").withRequired(true) .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create()) .withDescription("Input file").withShortName("i").create(); Option modelOpt = obuilder.withLongName("model").withRequired(true) .withArgument(abuilder.withName("model").withMinimum(1).withMaximum(1).create()) .withDescription("Model to use when classifying data").withShortName("m").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create();/* www. j av a2 s. c o m*/ Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(modelOpt).withOption(helpOpt) .create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File inputFile = new File(cmdLine.getValue(inputOpt).toString()); if (!inputFile.isFile()) { throw new IllegalArgumentException(inputFile + " does not exist or is not a file"); } File modelDir = new File(cmdLine.getValue(modelOpt).toString()); if (!modelDir.isDirectory()) { throw new IllegalArgumentException(modelDir + " does not exist or is not a directory"); } BayesParameters p = new BayesParameters(); p.set("basePath", modelDir.getCanonicalPath()); Datastore ds = new InMemoryBayesDatastore(p); Algorithm a = new BayesAlgorithm(); ClassifierContext ctx = new ClassifierContext(a, ds); ctx.initialize(); //TODO: make the analyzer configurable StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); TokenStream ts = analyzer.tokenStream(null, new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); ArrayList<String> tokens = new ArrayList<String>(1000); while (ts.incrementToken()) { tokens.add(ts.getAttribute(CharTermAttribute.class).toString()); } String[] document = tokens.toArray(new String[tokens.size()]); ClassifierResult[] cr = ctx.classifyDocument(document, "unknown", 5); for (ClassifierResult r : cr) { System.err.println(r.getLabel() + "\t" + r.getScore()); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } catch (IOException e) { log.error("IOException", e); } catch (InvalidDatastoreException e) { log.error("InvalidDataStoreException", e); } finally { } }
From source file:edu.oregonstate.eecs.mcplan.ml.KMeans.java
/** * @param args//from www . j av a2 s .co m */ public static void main(final String[] args) { final int nclusters = 2; final ArrayList<RealVector> data = new ArrayList<RealVector>(); for (int x = -1; x <= 1; ++x) { for (int y = -1; y <= 1; ++y) { data.add(new ArrayRealVector(new double[] { x, y })); data.add(new ArrayRealVector(new double[] { x + 10, y + 10 })); } } final KMeans kmeans = new KMeans(nclusters, data.toArray(new RealVector[data.size()])); /* { @Override public double distance( final RealVector a, final RealVector b ) { return a.getL1Distance( b ); } }; */ kmeans.run(); for (int i = 0; i < kmeans.centers().length; ++i) { System.out.println("Center " + i + ": " + kmeans.centers()[i]); for (int j = 0; j < kmeans.clusters().length; ++j) { if (kmeans.clusters()[j] == i) { System.out.println("\tPoint " + data.get(j)); } } } }
From source file:POP3Mail.java
public static void main(String[] args) { try {/* w w w . j a v a 2s .c om*/ LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String server = null; String username = null; String password = null; if (new File("mail.properties").exists()) { Properties properties = new Properties(); try { properties.load(new FileInputStream(new File("mail.properties"))); server = properties.getProperty("server"); username = properties.getProperty("username"); password = properties.getProperty("password"); ArrayList<String> list = new ArrayList<String>( Arrays.asList(new String[] { server, username, password })); list.addAll(Arrays.asList(args)); args = list.toArray(new String[list.size()]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (args.length < 3) { System.err .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]"); System.exit(1); } server = args[0]; username = args[1]; password = args[2]; String proto = null; int messageid = -1; boolean implicit = false; for (int i = 3; i < args.length; ++i) { if (args[i].equals("-m")) { i += 1; messageid = Integer.parseInt(args[i]); } } // String proto = args.length > 3 ? args[3] : null; // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) // : false; POP3Client pop3; if (proto != null) { System.out.println("Using secure protocol: " + proto); pop3 = new POP3SClient(proto, implicit); } else { pop3 = new POP3Client(); } pop3.setDefaultPort(110); System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds pop3.setDefaultTimeout(60000); // suppress login details pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { pop3.connect(server); } catch (IOException e) { System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } try { if (!pop3.login(username, password)) { System.err.println("Could not login to server. Check password."); pop3.disconnect(); System.exit(1); } PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true); POP3MessageInfo[] messages = null; POP3MessageInfo[] identifiers = null; if (messageid == -1) { messages = pop3.listMessages(); identifiers = pop3.listUniqueIdentifiers(); } else { messages = new POP3MessageInfo[] { pop3.listMessage(messageid) }; } if (messages == null) { System.err.println("Could not retrieve message list."); pop3.disconnect(); return; } else if (messages.length == 0) { System.out.println("No messages"); pop3.logout(); pop3.disconnect(); return; } new File("../json").mkdirs(); int count = 0; for (POP3MessageInfo msginfo : messages) { if (msginfo.number != identifiers[count].number) { throw new RuntimeException(); } msginfo.identifier = identifiers[count].identifier; BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0); ++count; if (count % 100 == 0) { logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier)); } System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier)); if (reader == null) { System.err.println("Could not retrieve message header."); pop3.disconnect(); System.exit(1); } if (printMessageInfo(reader, msginfo.number, printWriter)) { } } printWriter.close(); pop3.logout(); pop3.disconnect(); } catch (IOException e) { e.printStackTrace(); return; } }
From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorFileSubsetGenerator.java
public static void main(String[] args) throws IOException, SOMToolboxException { // register and parse all options JSAPResult config = OptionFactory.parseResults(args, OPTIONS); String inputFileName = AbstractOptionFactory.getFilePath(config, "input"); String classInformationFileName = AbstractOptionFactory.getFilePath(config, "classInformationFile"); String outputFileName = AbstractOptionFactory.getFilePath(config, "output"); String[] keepClasses = config.getStringArray("classList"); boolean skipInstanceNames = false;// config.getBoolean("skipInstanceNames"); boolean skipInputsWithoutClass = false;// config.getBoolean("skipInputsWithoutClass"); boolean tabSeparatedClassFile = false;// config.getBoolean("tabSeparatedClassFile"); String inputFormat = config.getString("inputFormat"); if (inputFormat == null) { inputFormat = InputDataFactory.detectInputFormatFromExtension(inputFileName, "input"); }/* w ww. ja v a2 s .c o m*/ String outputFormat = config.getString("outputFormat"); if (outputFormat == null) { outputFormat = InputDataFactory.detectInputFormatFromExtension(outputFileName, "output"); } InputData data = InputDataFactory.open(inputFormat, inputFileName); if (classInformationFileName != null) { SOMLibClassInformation classInfo = new SOMLibClassInformation(classInformationFileName); data.setClassInfo(classInfo); } if (data.classInformation() == null) { throw new SOMToolboxException("Need to provide a class information file."); } Logger.getLogger("at.tuwien.ifs.somtoolbox") .info("Retaining elements of classes: " + Arrays.toString(keepClasses)); ArrayList<InputDatum> subData = new ArrayList<InputDatum>(); for (int i = 0; i < data.numVectors(); i++) { InputDatum datum = data.getInputDatum(i); String className = data.classInformation().getClassName(datum.getLabel()); System.out.println(datum.getLabel() + "=>" + className); if (ArrayUtils.contains(keepClasses, className)) { subData.add(datum); } } InputData subset = new SOMLibSparseInputData(subData.toArray(new InputDatum[subData.size()]), data.classInformation()); InputDataWriter.write(outputFileName, subset, outputFormat, tabSeparatedClassFile, skipInstanceNames, skipInputsWithoutClass); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.ExtractDataAndQueryAsSparseVectors.java
public static void main(String[] args) { String optKeys[] = { CommonParams.MAX_NUM_QUERY_PARAM, MAX_NUM_DATA_PARAM, CommonParams.MEMINDEX_PARAM, IN_QUERIES_PARAM, OUT_QUERIES_PARAM, OUT_DATA_PARAM, TEXT_FIELD_PARAM, TEST_QTY_PARAM, }; String optDescs[] = { CommonParams.MAX_NUM_QUERY_DESC, MAX_NUM_DATA_DESC, CommonParams.MEMINDEX_DESC, IN_QUERIES_DESC, OUT_QUERIES_DESC, OUT_DATA_DESC, TEXT_FIELD_DESC, TEST_QTY_DESC }; boolean hasArg[] = { true, true, true, true, true, true, true, true }; ParamHelper prmHlp = null;//from w w w .ja v a 2 s .c om try { prmHlp = new ParamHelper(args, optKeys, optDescs, hasArg); CommandLine cmd = prmHlp.getCommandLine(); Options opt = prmHlp.getOptions(); int maxNumQuery = Integer.MAX_VALUE; String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM); if (tmpn != null) { try { maxNumQuery = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(CommonParams.MAX_NUM_QUERY_PARAM, opt); } } int maxNumData = Integer.MAX_VALUE; tmpn = cmd.getOptionValue(MAX_NUM_DATA_PARAM); if (tmpn != null) { try { maxNumData = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(MAX_NUM_DATA_PARAM, opt); } } String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == memIndexPref) { UsageSpecify(CommonParams.MEMINDEX_PARAM, opt); } String textField = cmd.getOptionValue(TEXT_FIELD_PARAM); if (null == textField) { UsageSpecify(TEXT_FIELD_PARAM, opt); } textField = textField.toLowerCase(); int fieldId = -1; for (int i = 0; i < FeatureExtractor.mFieldNames.length; ++i) if (FeatureExtractor.mFieldNames[i].compareToIgnoreCase(textField) == 0) { fieldId = i; break; } if (-1 == fieldId) { Usage("Wrong field index, should be one of the following: " + String.join(",", FeatureExtractor.mFieldNames), opt); } InMemForwardIndex indx = new InMemForwardIndex( FeatureExtractor.indexFileName(memIndexPref, FeatureExtractor.mFieldNames[fieldId])); BM25SimilarityLucene bm25simil = new BM25SimilarityLucene(FeatureExtractor.BM25_K1, FeatureExtractor.BM25_B, indx); String inQueryFile = cmd.getOptionValue(IN_QUERIES_PARAM); String outQueryFile = cmd.getOptionValue(OUT_QUERIES_PARAM); if ((inQueryFile == null) != (outQueryFile == null)) { Usage("You should either specify both " + IN_QUERIES_PARAM + " and " + OUT_QUERIES_PARAM + " or none of them", opt); } String outDataFile = cmd.getOptionValue(OUT_DATA_PARAM); tmpn = cmd.getOptionValue(TEST_QTY_PARAM); int testQty = 0; if (tmpn != null) { try { testQty = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(TEST_QTY_PARAM, opt); } } ArrayList<DocEntry> testDocEntries = new ArrayList<DocEntry>(); ArrayList<DocEntry> testQueryEntries = new ArrayList<DocEntry>(); ArrayList<TrulySparseVector> testDocVectors = new ArrayList<TrulySparseVector>(); ArrayList<TrulySparseVector> testQueryVectors = new ArrayList<TrulySparseVector>(); if (outDataFile != null) { BufferedWriter out = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outDataFile))); ArrayList<DocEntryExt> docEntries = indx.getDocEntries(); for (int id = 0; id < Math.min(maxNumData, docEntries.size()); ++id) { DocEntry e = docEntries.get(id).mDocEntry; TrulySparseVector v = bm25simil.getDocSparseVector(e, false); if (id < testQty) { testDocEntries.add(e); testDocVectors.add(v); } outputVector(out, v); } out.close(); } Splitter splitOnSpace = Splitter.on(' ').trimResults().omitEmptyStrings(); if (outQueryFile != null) { BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inQueryFile))); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outQueryFile))); String queryText = XmlHelper.readNextXMLIndexEntry(inpText); for (int queryQty = 0; queryText != null && queryQty < maxNumQuery; queryText = XmlHelper .readNextXMLIndexEntry(inpText), queryQty++) { Map<String, String> queryFields = null; // 1. Parse a query try { queryFields = XmlHelper.parseXMLIndexEntry(queryText); } catch (Exception e) { System.err.println("Parsing error, offending QUERY:\n" + queryText); throw new Exception("Parsing error."); } String fieldText = queryFields.get(FeatureExtractor.mFieldsSOLR[fieldId]); if (fieldText == null) { fieldText = ""; } ArrayList<String> tmpa = new ArrayList<String>(); for (String s : splitOnSpace.split(fieldText)) tmpa.add(s); DocEntry e = indx.createDocEntry(tmpa.toArray(new String[tmpa.size()])); TrulySparseVector v = bm25simil.getDocSparseVector(e, true); if (queryQty < testQty) { testQueryEntries.add(e); testQueryVectors.add(v); } outputVector(out, v); } out.close(); } int testedQty = 0, diffQty = 0; // Now let's do some testing for (int iq = 0; iq < testQueryEntries.size(); ++iq) { DocEntry queryEntry = testQueryEntries.get(iq); TrulySparseVector queryVector = testQueryVectors.get(iq); for (int id = 0; id < testDocEntries.size(); ++id) { DocEntry docEntry = testDocEntries.get(id); TrulySparseVector docVector = testDocVectors.get(id); float val1 = bm25simil.compute(queryEntry, docEntry); float val2 = TrulySparseVector.scalarProduct(queryVector, docVector); ++testedQty; if (Math.abs(val1 - val2) > 1e5) { System.err.println( String.format("Potential mismatch BM25=%f <-> scalar product=%f", val1, val2)); ++diffQty; } } } if (testedQty > 0) System.out.println(String.format("Tested %d Mismatched %d", testedQty, diffQty)); } catch (ParseException e) { Usage("Cannot parse arguments: " + e, prmHlp != null ? prmHlp.getOptions() : null); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }