List of usage examples for java.io PrintWriter flush
public void flush()
From source file:com.norconex.collector.http.HttpCollector.java
/** * Invokes the HTTP Collector from the command line. * @param args Invoke it once without any arguments to get a * list of command-line options./*from w w w.j ava 2 s . c om*/ */ public static void main(String[] args) { CommandLine cmd = parseCommandLineArguments(args); String action = cmd.getOptionValue(ARG_ACTION); File configFile = new File(cmd.getOptionValue(ARG_CONFIG)); File varFile = null; if (cmd.hasOption(ARG_VARIABLES)) { varFile = new File(cmd.getOptionValue(ARG_VARIABLES)); } try { HttpCollector conn = new HttpCollector(configFile, varFile); if (ARG_ACTION_START.equalsIgnoreCase(action)) { conn.crawl(false); } else if (ARG_ACTION_RESUME.equalsIgnoreCase(action)) { conn.crawl(true); } else if (ARG_ACTION_STOP.equalsIgnoreCase(action)) { conn.stop(); } } catch (Exception e) { File errorFile = new File("./error-" + System.currentTimeMillis() + ".log"); System.err.println("\n\nAn ERROR occured:\n\n" + e.getLocalizedMessage()); System.err.println( "\n\nDetails of the error has been stored at: " + errorFile.getAbsolutePath() + "\n\n"); try { PrintWriter w = new PrintWriter(errorFile); e.printStackTrace(w); w.flush(); w.close(); } catch (FileNotFoundException e1) { throw new HttpCollectorException("Cannot write error file.", e1); } } }
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 {//from www .j a v a 2s. c o 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:com.bstek.dorado.idesupport.StandaloneRuleSetExporter.java
public static void main(String[] args) throws Exception { String ruleSetFile = null;//from w ww .j a va 2 s .c o m String doradoHome = null; if (args.length >= 2) { ruleSetFile = args[0]; doradoHome = args[1]; } else { throw new IllegalArgumentException(); } if (StringUtils.isEmpty(doradoHome)) { doradoHome = System.getenv("DORADO_HOME"); } StandaloneRuleSetExporter instance = new StandaloneRuleSetExporter(doradoHome); FileOutputStream fos = new FileOutputStream(ruleSetFile); PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, Constants.DEFAULT_CHARSET)); try { instance.exportRuleSet(writer); } finally { writer.flush(); writer.close(); fos.close(); } }
From source file:com.kappaware.logtrawler.Main.java
@SuppressWarnings("static-access") static public void main(String[] argv) throws Throwable { Config config;/*from www . ja v a 2 s . co m*/ Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file") .withDescription("JSON configuration file").create("c")); options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder") .withDescription("Folder to monitor").create("f")); options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion") .withDescription("Exclusion regex").create("x")); options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint") .withDescription("Endpoint for admin REST").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow") .withDescription("Target to post result on").create("o")); options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname") .withDescription("This hostname").create("h")); options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d")); options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type") .withDescription("Valid MIME type").create("m")); options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin") .withDescription("Allowed admin network").create("a")); options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file") .withDescription("Generate JSON configuration file").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size") .withDescription("Max JSON batch (array) size").create("b")); CommandLineParser clParser = new BasicParser(); CommandLine line; String configFile = null; try { // parse the command line argument line = clParser.parse(options, argv); if (line.hasOption("c")) { configFile = line.getOptionValue("c"); config = Json.fromJson(Config.class, new BufferedReader(new InputStreamReader(new FileInputStream(configFile)))); } else { config = new Config(); } if (line.hasOption("f")) { String[] fs = line.getOptionValues("f"); // Get the first agent (Create it if needed) if (config.getAgents() == null || config.getAgents().size() == 0) { Config.Agent agent = new Config.Agent("default"); config.addAgent(agent); } Config.Agent agent = config.getAgents().iterator().next(); for (String f : fs) { agent.addFolder(new Config.Agent.Folder(f, false)); } } if (line.hasOption("e")) { String e = line.getOptionValue("e"); config.setAdminEndpoint(e); } if (line.hasOption("o")) { String[] es = line.getOptionValues("o"); if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { for (String s : es) { agent.addOuputFlow(s); } } } } if (line.hasOption("h")) { String e = line.getOptionValue("h"); config.setHostname(e); } if (line.hasOption("x")) { if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { if (agent.getFolders() != null) { for (Folder folder : agent.getFolders()) { String[] exs = line.getOptionValues("x"); for (String ex : exs) { folder.addExcludedPath(ex); } } } } } } if (line.hasOption("m")) { if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { String[] exs = line.getOptionValues("m"); for (String ex : exs) { agent.addLogMimeType(ex); } } } } if (line.hasOption("a")) { String[] exs = line.getOptionValues("a"); for (String ex : exs) { config.addAdminAllowedNetwork(ex); } } if (line.hasOption("d")) { config.setDisplayDot(true); } if (line.hasOption("b")) { Integer i = getIntegerParameter(line, "b"); if (config.getAgents() != null) { for (Agent agent : config.getAgents()) { agent.setOutputMaxBatchSize(i); } } } config.setDefault(); if (line.hasOption("g")) { String fileName = line.getOptionValue("g"); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false))); out.println(Json.toJson(config, true)); out.flush(); out.close(); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong usage(options, exp.getMessage()); return; } try { // Check config if (config.getAgents() == null || config.getAgents().size() < 1) { throw new ConfigurationException("At least one folder to monitor must be provided!"); } Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>(); for (Config.Agent agent : config.getAgents()) { agentHandlerByName.put(agent.getName(), new AgentHandler(agent)); } if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) { new AdminServer(config, agentHandlerByName); } } catch (ConfigurationException e) { log.error(e.toString()); System.exit(1); } catch (Throwable t) { log.error("Error in main", t); System.exit(2); } }
From source file:Anaphora_Resolution.ParseAllXMLDocuments.java
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException { // File dataFolder = new File("DataToPort"); // File[] documents; String grammar = "grammar/englishPCFG.ser.gz"; String[] options = { "-maxLength", "100", "-retainTmpSubcategories" }; //LexicalizedParser lp = new LexicalizedParser(grammar, options); LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"); ///*from ww w.j a va 2 s.com*/ // if (dataFolder.isDirectory()) { // documents = dataFolder.listFiles(); // } else { // documents = new File[] {dataFolder}; // } // int currfile = 0; // int totfiles = documents.length; // for (File paper : documents) { // currfile++; // if (paper.getName().equals(".DS_Store")||paper.getName().equals(".xml")) { // currfile--; // totfiles--; // continue; // } // System.out.println("Working on "+paper.getName()+" (file "+currfile+" out of "+totfiles+")."); // // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // This is for XML // DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Document doc = docBuilder.parse(paper.getAbsolutePath()); // // NodeList textlist = doc.getElementsByTagName("text"); // for(int i=0; i < textlist.getLength(); i++) { // Node currentnode = textlist.item(i); // String wholetext = textlist.item(i).getTextContent(); String wholetext = "How about other changes for example the ways of doing the work and \n" + "\n" + "Iwould say security has , there 's more pressure put on people now than there used to be because obviously , especially after Locherbie , they tightened up on security and there 's a lot more pressure now especially from the ETR and stuff like that \n" + "People do n't feel valued any more , they feel I do n't know I think they feel that nobody cares about them really anyway \n"; //System.out.println(wholetext); //Iterable<List<? extends HasWord>> sentences; ArrayList<Tree> parseTrees = new ArrayList<Tree>(); String asd = ""; int j = 0; StringReader stringreader = new StringReader(wholetext); DocumentPreprocessor dp = new DocumentPreprocessor(stringreader); @SuppressWarnings("rawtypes") ArrayList<List> sentences = preprocess(dp); for (List sentence : sentences) { parseTrees.add(lp.apply(sentence)); // Parsing a new sentence and adding it to the parsed tree ArrayList<Tree> PronounsList = findPronouns(parseTrees.get(j)); // Locating all pronouns to resolve in the sentence Tree corefedTree; for (Tree pronounTree : PronounsList) { parseTrees.set(parseTrees.size() - 1, HobbsResolve(pronounTree, parseTrees)); // Resolving the coref and modifying the tree for each pronoun } StringWriter strwr = new StringWriter(); PrintWriter prwr = new PrintWriter(strwr); TreePrint tp = new TreePrint("penn"); tp.printTree(parseTrees.get(j), prwr); prwr.flush(); asd += strwr.toString(); j++; } String armando = ""; for (Tree sentence : parseTrees) { for (Tree leaf : Trees.leaves(sentence)) armando += leaf + " "; } System.out.println(wholetext); System.out.println(); System.out.println("......"); System.out.println(armando); System.out.println("All done."); // currentnode.setTextContent(asd); // } // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(paper); // transformer.transform(source, result); // // System.out.println("Done"); // } }
From source file:Who.java
public static void main(String[] v) { Socket s = null;//w w w .ja v a2 s . c om PrintWriter out = null; BufferedReader in = null; try { // Connect to port 79 (the standard finger port) on the host. String hostname = "www.java2s.com"; s = new Socket(hostname, 79); // Set up the streams out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); in = new BufferedReader(new InputStreamReader(s.getInputStream())); // Send a blank line to the finger server, telling it that we want // a listing of everyone logged on instead of information about an // individual user. out.print("\n"); out.flush(); // Send it out // Now read the server's response // The server should send lines terminated with \n or \r. String line; while ((line = in.readLine()) != null) { System.out.println(line); } System.out.println("Who's Logged On: " + hostname); } catch (IOException e) { System.out.println("Who's Logged On: Error"); } // Close the streams! finally { try { in.close(); out.close(); s.close(); } catch (Exception e) { } } }
From source file:io.werval.cli.DamnSmallDevShell.java
public static void main(String[] args) { Options options = declareOptions();//from ww w. j a v a 2 s . co m CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); // Handle --help if (cmd.hasOption("help")) { PrintWriter out = new PrintWriter(System.out); printHelp(options, out); out.flush(); System.exit(0); } // Handle --version if (cmd.hasOption("version")) { System.out.print(String.format( "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n" + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n" + "OS name: %s, version: %s, arch: %s\n", VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home"), Locale.getDefault().toString(), System.getProperty("file.encoding"), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))); System.out.flush(); System.exit(0); } // Debug final boolean debug = cmd.hasOption('d'); // Temporary directory final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp")); if (debug) { System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'."); } // Handle commands @SuppressWarnings("unchecked") List<String> commands = cmd.getArgList(); if (commands.isEmpty()) { commands = Collections.singletonList("start"); } if (debug) { System.out.println("Commands to be executed: " + commands); } Iterator<String> commandsIterator = commands.iterator(); while (commandsIterator.hasNext()) { String command = commandsIterator.next(); switch (command) { case "new": System.out.println(LOGO); newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd); break; case "clean": cleanCommand(debug, tmpDir); break; case "devshell": System.out.println(LOGO); devshellCommand(debug, tmpDir, cmd); break; case "start": System.out.println(LOGO); startCommand(debug, tmpDir, cmd); break; case "secret": secretCommand(); break; default: PrintWriter out = new PrintWriter(System.err); System.err.println("Unknown command: '" + command + "'"); printHelp(options, out); out.flush(); System.exit(1); break; } } } catch (IllegalArgumentException | ParseException | IOException ex) { PrintWriter out = new PrintWriter(System.err); printHelp(options, out); out.flush(); System.exit(1); } catch (WervalException ex) { ex.printStackTrace(System.err); System.err.flush(); System.exit(1); } }
From source file:com.kse.bigdata.main.Driver.java
public static void main(String[] args) throws Exception { /********************************************************************************** ** Merge the source files into one. ** /** Should change the directories of each file before executing the program ** ***********************************************************************************/ // String inputFileDirectory = "/media/bk/??/BigData_Term_Project/Debug"; // String resultFileDirectory = "/media/bk/??/BigData_Term_Project/debug.csv"; // File resultFile = new File(resultFileDirectory); // if(!resultFile.exists()) // new SourceFileMerger(inputFileDirectory, resultFileDirectory).mergeFiles(); /********************************************************************************** * Hadoop Operation./*from w ww. j a va2s. c o m*/ * Befort Start, Check the Length of Sequence We Want to Predict. **********************************************************************************/ Configuration conf = new Configuration(); //Enable MapReduce intermediate compression as Snappy conf.setBoolean("mapred.compress.map.output", true); conf.set("mapred.map.output.compression.codec", "org.apache.hadoop.io.compress.SnappyCodec"); //Enable Profiling //conf.setBoolean("mapred.task.profile", true); String testPath = null; String inputPath = null; String outputPath = null; int sampleSize = 1; ArrayList<String> results = new ArrayList<String>(); for (int index = 0; index < args.length; index++) { /* * Mandatory command */ //Extract input path string from command line. if (args[index].equals("-in")) inputPath = args[index + 1]; //Extract output path string from command line. if (args[index].equals("-out")) outputPath = args[index + 1]; //Extract test data path string from command line. if (args[index].equals("-test")) testPath = args[index + 1]; /* * Optional command */ //Extract a number of neighbors. if (args[index].equals("-nn")) conf.setInt(Reduce.NUMBER_OF_NEAREAST_NEIGHBOR, Integer.parseInt(args[index + 1])); //Whether job uses normalization or not. if (args[index].equals("-norm")) conf.setBoolean(Map.NORMALIZATION, true); //Extract the number of sample size to test. if (args[index].equals("-s")) sampleSize = Integer.valueOf(args[index + 1]); //Whether job uses mean or median //[Default : mean] if (args[index].equals("-med")) conf.setBoolean(Reduce.MEDIAN, true); } String outputFileName = "part-r-00000"; SequenceSampler sampler = new SequenceSampler(testPath, sampleSize); LinkedList<Sequence> testSequences = sampler.getRandomSample(); // Test Sequence // String testSeqString = "13.591-13.674-13.778-13.892-13.958-14.049-14.153-14.185-14.169-14.092-13.905-13.702-13.438-13.187-13.0-12.914-12.868-12.766-12.62-12.433-12.279-12.142-12.063-12.025-100"; // Sequence testSeq = new Sequence(testSeqString); // LinkedList<Sequence> testSequences = new LinkedList<>(); // testSequences.add(testSeq); for (Sequence seq : testSequences) { /* ******************** Hadoop Launch *********************** */ System.out.println(seq.getTailString()); conf.set(Map.INPUT_SEQUENCE, seq.toString()); Job job = new Job(conf); job.setJarByClass(Driver.class); job.setJobName("term-project-driver"); job.setMapperClass(Map.class); job.setMapOutputKeyClass(NullWritable.class); job.setMapOutputValueClass(Text.class); // Should think another way to implement the combiner class // Current Implementation is not helpful to Job. // job.setCombinerClass(Combiner.class); //Set 1 for number of reduce task for keeping 100 most neighbors in sorted set. job.setNumReduceTasks(1); job.setReducerClass(Reduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(inputPath)); FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.waitForCompletion(true); /* * if job finishes, get result of the job and store it in results(list). */ try { FileSystem hdfs = FileSystem.get(new Configuration()); BufferedReader fileReader = new BufferedReader( new InputStreamReader(hdfs.open(new Path(outputPath + "/" + outputFileName)))); String line; while ((line = fileReader.readLine()) != null) { results.add(seq.getSeqString() + " " + line); } fileReader.close(); hdfs.delete(new Path(outputPath), true); hdfs.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } /* * if all jobs finish, store results of jobs to output/result.txt file. */ String finalOutputPath = "output/result.csv"; try { FileSystem hdfs = FileSystem.get(new Configuration()); Path file = new Path(finalOutputPath); if (hdfs.exists(file)) { hdfs.delete(file, true); } OutputStream os = hdfs.create(file); PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os, "UTF-8")); //CSV File Header printWriter.println("Actual,Predicted,MER,MAE"); printWriter.flush(); for (String result : results) { String[] tokens = result.split("\\s+"); printWriter.println(tokens[0] + "," + tokens[1] + "," + tokens[2] + "," + tokens[3]); printWriter.flush(); } printWriter.close(); hdfs.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:client.Client.java
/** * @param args the command line arguments *//*from www . jav a 2 s . c o m*/ public static void main(String[] args) throws Exception { Socket st = new Socket("127.0.0.1", 1604); BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream())); PrintWriter p = new PrintWriter(st.getOutputStream()); while (true) { String s = r.readLine(); new Thread() { @Override public void run() { String[] ar = s.split("\\|"); if (s.startsWith("HALLO")) { String str = ""; try { str = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { } p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|" + System.getProperty("os.name") + "|" + str); p.flush(); } if (s.startsWith("msg")) { String text = fromHex(ar[1]); String title = ar[2]; int i = Integer.parseInt(ar[3]); JOptionPane.showMessageDialog(null, text, title, i); } if (s.startsWith("execute")) { String cmd = ar[1]; try { Runtime.getRuntime().exec(cmd); } catch (Exception e) { } } if (s.equals("getsystem")) { StringBuilder sb = new StringBuilder(); for (Object o : System.getProperties().entrySet()) { Map.Entry e = (Map.Entry) o; sb.append("\n" + e.getKey() + "|" + e.getValue()); } p.println("systeminfos|" + toHex(sb.toString().substring(1))); p.flush(); } } }.start(); } }
From source file:ch.epfl.lsir.xin.test.SVDPPTest.java
/** * @param args/*from ww w. ja va 2 s. c o m*/ */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//SVDPP"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//SVDPlusPlus.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); logger.flush(); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); logger.flush(); double totalMAE = 0; double totalRMSE = 0; double totalPrecision = 0; double totalRecall = 0; double totalMAP = 0; double totalNDCG = 0; double totalMRR = 0; double totalAUC = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); logger.flush(); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { if (testRatings.get(i).getValue() < 5) continue; testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a SVD++ recommendation model."); logger.flush(); SVDPlusPlus algo = new SVDPlusPlus(trainRatingMatrix, false, ".//localModels//" + config.getString("NAME")); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); //rating prediction accuracy double RMSE = 0; double MAE = 0; double precision = 0; double recall = 0; double map = 0; double ndcg = 0; double mrr = 0; double auc = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()), itemIDIndexMapping.get(rating.getItemID()), false); if (prediction > algo.getMaxRating()) prediction = algo.getMaxRating(); if (prediction < algo.getMinRating()) prediction = algo.getMinRating(); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: " + MAE + " RMSE: " + RMSE); //ranking accuracy if (algo.getTopN() > 0) { HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>(); for (int i = 0; i < trainRatingMatrix.getRow(); i++) { ArrayList<ResultUnit> rec = algo.getRecommendationList(i); if (rec == null) continue; int total = testRatingMatrix.getUserRatingNumber(i); if (total == 0)//this user is ignored continue; results.put(i, rec); } RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix); precision = generator.getPrecisionN(); totalPrecision = totalPrecision + precision; recall = generator.getRecallN(); totalRecall = totalRecall + recall; map = generator.getMAPN(); totalMAP = totalMAP + map; ndcg = generator.getNDCGN(); totalNDCG = totalNDCG + ndcg; mrr = generator.getMRRN(); totalMRR = totalMRR + mrr; auc = generator.getAUC(); totalAUC = totalAUC + auc; System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc); logger.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc); } logger.flush(); } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); System.out.println("Precision@N: " + totalPrecision / F); System.out.println("Recall@N: " + totalRecall / F); System.out.println("MAP@N: " + totalMAP / F); System.out.println("MRR@N: " + totalMRR / F); System.out.println("NDCG@N: " + totalNDCG / F); System.out.println("AUC@N: " + totalAUC / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n" + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F); logger.flush(); logger.close(); }