List of usage examples for java.util Scanner hasNext
public boolean hasNext()
From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java
/** * Reads user input from stdin//ww w . j a v a 2s.co m * * @param listPrompts list of prompts to display, asking for user input * @return a list containing user inputs */ private List<String> getUserInputFromStdin(List<String> listPrompts) { List<String> listUserInput = new ArrayList<String>(); Scanner console = new Scanner(System.in); Scanner lineTokenizer = null; for (String prompt : listPrompts) { System.out.println(prompt); try { lineTokenizer = new Scanner(console.nextLine()); } catch (NoSuchElementException nse) { console.close(); throw new NoSuchElementException(MessageFormat.format("Missing user input= {0}", prompt)); } if (lineTokenizer.hasNext()) { String userInput = lineTokenizer.next(); listUserInput.add(userInput); } } console.close(); return listUserInput; }
From source file:org.micromanager.plugins.magellan.propsandcovariants.LaserPredNet.java
private void readModel(String filename) throws FileNotFoundException { Scanner s = new Scanner(new File(filename)); double[][] w1 = new double[N_INPUTS][N_HIDDENS]; double[][] b1 = new double[1][N_HIDDENS]; double[][] w2 = new double[1][N_HIDDENS]; double[][] b2 = new double[1][1]; double[][] var = null; int index = 0; int matCount = 0; while (s.hasNext()) { String line = s.nextLine(); if (line.toLowerCase().startsWith("fc") || line.toLowerCase().startsWith("output")) { //new variable if (matCount == 0) { var = w1; } else if (matCount == 1) { var = b1; } else if (matCount == 2) { var = w2; } else { var = b2; }// w w w . j a v a 2s . c o m matCount++; index = 0; } else if (line.toLowerCase().startsWith("distance")) { break; } else { String[] entries = line.split(","); for (int i = 0; i < entries.length; i++) { try { var[index / var[0].length][index % var[0].length] = Double.parseDouble(entries[i]); } catch (Exception e) { int t = 6; } index++; } } } String meanStr = s.nextLine(); // means String[] entries = meanStr.split(","); distanceMeans_ = new double[N_HIST_BINS]; for (int i = 0; i < entries.length; i++) { distanceMeans_[i] = Double.parseDouble(entries[i]); } s.nextLine(); // burn SD title String sdStr = s.nextLine(); entries = sdStr.split(","); distanceSDs_ = new double[N_HIST_BINS]; for (int i = 0; i < entries.length; i++) { distanceSDs_[i] = Double.parseDouble(entries[i]); } s.nextLine(); // burn test values title int numTestVals = 4; testValuesOutput_ = new double[numTestVals]; testValues_ = new double[numTestVals][N_HIST_BINS + 3]; for (int i = 0; i < numTestVals; i++) { String valsString = s.nextLine(); entries = valsString.split(","); for (int k = 0; k < entries.length; k++) { testValues_[i][k] = Double.parseDouble(entries[k]); } testValuesOutput_[i] = Double.parseDouble(s.nextLine()); } //convert model to Apache commons matrices W1_ = (Array2DRowRealMatrix) MatrixUtils.createRealMatrix(w1); B1_ = (Array2DRowRealMatrix) MatrixUtils.createRealMatrix(b1); W2_ = (Array2DRowRealMatrix) MatrixUtils.createRealMatrix(w2); B2_ = (Array2DRowRealMatrix) MatrixUtils.createRealMatrix(b2); //Run tests byte[] output = forwardPass(testValues_); for (int k = 0; k < output.length; k++) { System.out.println("Calculated: " + (output[k] & 0xff) + "\tGround truth:" + testValuesOutput_[k]); } }
From source file:dtv.controller.FXMLMainController.java
private String getPreferences() throws Exception { if (filePrefs != null && filePrefs.canRead()) { Scanner scanner = new Scanner(filePrefs); String line;// ww w . ja va 2s . c o m while (scanner.hasNext()) { line = scanner.nextLine(); if (line.contains(FAV_TAG)) { String preferences = line.substring(1 + line.indexOf(">"), line.lastIndexOf("<")); Utils.prefTab = preferences.split(Utils.FAV_SEP); break; } } scanner.close(); } else { Utils.prefTab = Utils.PPREFS; } return Utils.getPreferences(); }
From source file:eremeykin.pete.plotter.PolarPlotterTopComponent.java
@Override public void update() { // for first rpt file if (model == null) { clear();//w ww .j av a 2 s .c o m return; } File[] rptFiles = home.listFiles(filter()); // catch if there is no such file if (rptFiles.length == 0) { clear(); return; } File firstRPT = rptFiles[0]; Scanner scanner; try { scanner = new Scanner(firstRPT); scanner.useDelimiter("\\s+|\n"); } catch (FileNotFoundException ex) { clear(); return; } List<Map.Entry<Double, Double>> tmpList = new ArrayList<>(); for (int i = 0; scanner.hasNext(); i++) { String line = scanner.next(); try { double x1 = Double.valueOf(line); line = scanner.next(); double x2 = Double.valueOf(line); // System.out.println("x1=" + x1 + "\nx2=" + x2); tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2)); } catch (NumberFormatException ex) { // only if it is the third or following line if (i > 1) { LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath()); JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error", JOptionPane.ERROR_MESSAGE); } } } if (tmpList.isEmpty()) { clear(); return; } fillData(tmpList); // fillData(tmpList, dataSeries, toleranceSeries); }
From source file:nu.nethome.home.items.web.GraphServlet.java
/** * This is the main enterence point of the class. This is called when a http request is * routed to this servlet.//from w ww. ja v a2s . com */ public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream p = res.getOutputStream(); Date startTime = null; Date stopTime = null; // Analyse arguments String fileName = req.getParameter("file"); if (fileName != null) fileName = getFullFileName(fromURL(fileName)); String startTimeString = req.getParameter("start"); String stopTimeString = req.getParameter("stop"); try { if (startTimeString != null) { startTime = m_Format.parse(startTimeString); } if (stopTimeString != null) { stopTime = m_Format.parse(stopTimeString); } } catch (ParseException e1) { e1.printStackTrace(); } String look = req.getParameter("look"); if (look == null) look = ""; TimeSeries timeSeries = new TimeSeries("Data", Minute.class); // Calculate time window Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date startOfDay = cal.getTime(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date startOfWeek = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, 1); Date startOfMonth = cal.getTime(); cal.set(Calendar.MONTH, Calendar.JANUARY); Date startOfYear = cal.getTime(); // if (startTime == null) startTime = startOfWeek; if (stopTime == null) stopTime = currentTime; if (startTime == null) startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L); try { // Open the data file File logFile = new File(fileName); Scanner fileScanner = new Scanner(logFile); Long startTimeMs = startTime.getTime(); Long month = 1000L * 60L * 60L * 24L * 30L; boolean doOptimize = true; boolean justOptimized = false; try { while (fileScanner.hasNext()) { try { // Get next log entry String line = fileScanner.nextLine(); if (line.length() > 21) { // Adapt the time format String minuteTime = line.substring(0, 16).replace('.', '-'); // Parse the time stamp Minute min = Minute.parseMinute(minuteTime); // Ok, this is an ugly optimization. If the current time position in the file // is more than a month (30 days) ahead of the start of the time window, we // quick read two weeks worth of data, assuming that there is 4 samples per hour. // This may lead to scanning past start of window if there are holes in the data // series. if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) { for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) { fileScanner.nextLine(); } justOptimized = true; continue; } // Detect if we have scanned past the window start position just after an optimization scan. // If this is the case it may be because of the optimization. In that case we have to switch // optimization off and start over. if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) { logFile = new File(fileName); fileScanner = new Scanner(logFile); doOptimize = false; continue; } justOptimized = false; // Check if value is within time window if ((min.getFirstMillisecond() > startTimeMs) && (min.getFirstMillisecond() < stopTime.getTime())) { // Parse the value double value = Double.parseDouble((line.substring(20)).replace(',', '.')); // Add the entry timeSeries.add(min, value); doOptimize = false; } } } catch (SeriesException se) { // Bad entry, for example due to duplicates at daylight saving time switch } catch (NumberFormatException nfe) { // Bad number format in a line, try to continue } } } catch (Exception e) { System.out.println(e.toString()); } finally { fileScanner.close(); } } catch (FileNotFoundException f) { System.out.println(f.toString()); } // Create a collection for plotting TimeSeriesCollection data = new TimeSeriesCollection(); data.addSeries(timeSeries); JFreeChart chart; int xSize = 750; int ySize = 450; // Customize colors and look of the Graph. if (look.equals("mobtemp")) { // Look for the mobile GUI chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false); XYPlot plot = chart.getXYPlot(); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); xSize = 175; ySize = 180; } else { // Create a Chart with time range as heading SimpleDateFormat localFormat = new SimpleDateFormat(); String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime); chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false); Paint background = new Color(0x9D8140); chart.setBackgroundPaint(background); TextTitle title = chart.getTitle(); // fix title Font titleFont = title.getFont(); titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0); title.setFont(titleFont); title.setPaint(Color.darkGray); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(background); plot.setDomainGridlinePaint(Color.darkGray); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); plot.setRangeGridlinePaint(Color.darkGray); XYItemRenderer renderer = plot.getRenderer(0); renderer.setSeriesPaint(0, Color.darkGray); xSize = 750; ySize = 450; } try { res.setContentType("image/png"); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "no-cache"); res.setStatus(HttpServletResponse.SC_OK); ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } p.flush(); p.close(); return; }
From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java
private void initComponents() { scrollPane1 = new JScrollPane(); textArea = new JTextArea(); textArea.setEditable(false);/*from ww w. jav a 2 s . co m*/ btnConnect = new JButton(); label1 = new JLabel(); label2 = new JLabel(); cmbPort = new JComboBox(); label3 = new JLabel(); labelnumber = new JLabel(); lblLogo = new JLabel(); cmbIp = new JComboBox(); //======== this ======== setTitle(Release.PRODUCT_RELEASE + " Worker " + VERSION); Container contentPane = getContentPane(); //======== scrollPane1 ======== { scrollPane1.setViewportView(textArea); } //---- btnConnect ---- btnConnect.setText("Connect"); btnConnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnConnectOnClick(e); } }); //---- label1 ---- label1.setText("Server IP:"); //---- label2 ---- label2.setText("Server port:"); //---- label3 ---- label3.setText(""); //---- labelnumber ---- labelnumber.setText(""); //---- label4 ---- lblLogo.setText("Distributed Mason 'failed to load image'"); lblLogo.setIcon(new ImageIcon("resources/image/carmineworker.png")); //---- comboBox ---- cmbIp.setEditable(true); cmbPort.setEditable(true); try { Scanner in = new Scanner(new FileInputStream("resources/files/urlworker")); while (in.hasNext()) { String line = in.nextLine(); String[] args = line.split(":"); cmbIp.addItem(args[0]); cmbPort.addItem(args[1]); } } catch (Exception e) { System.out.println("No worker story found!"); } cmbIp.setSelectedIndex(0); cmbPort.setSelectedIndex(0); GroupLayout contentPaneLayout = new GroupLayout(contentPane); contentPane.setLayout(contentPaneLayout); contentPaneLayout.setHorizontalGroup(contentPaneLayout.createParallelGroup().addGroup(contentPaneLayout .createSequentialGroup().addContainerGap() .addGroup(contentPaneLayout.createParallelGroup() .addComponent(lblLogo, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE) .addGroup(contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addGroup(contentPaneLayout.createParallelGroup().addComponent(label2) .addComponent(label1)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(contentPaneLayout .createParallelGroup(GroupLayout.Alignment.LEADING, false) .addComponent(cmbPort).addComponent(cmbIp, 0, 119, Short.MAX_VALUE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup() .addGap(78, 78, 78).addComponent(btnConnect)) .addGroup(contentPaneLayout.createSequentialGroup() .addGap(46, 46, 46).addComponent(label3) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelnumber, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)))) .addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup().addGap(9, 9, 9) .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 366, GroupLayout.PREFERRED_SIZE) .addGap(462, 462, 462)))) .addGap(20, 20, 20))); contentPaneLayout.setVerticalGroup(contentPaneLayout.createParallelGroup() .addGroup(contentPaneLayout.createSequentialGroup().addContainerGap(21, Short.MAX_VALUE) .addComponent(lblLogo, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(contentPaneLayout.createParallelGroup().addComponent(label1) .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(btnConnect).addComponent(cmbIp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(label2).addComponent(cmbPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(label3).addComponent(labelnumber))) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 238, GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16))); setSize(410, 495); setLocationRelativeTo(getOwner()); }
From source file:com.act.reachables.LoadAct.java
private Set<Integer> extractLD50vals(String annotation) { // an example of what we want to process is: "Oral, mouse: LD50 = 338 mg/kg; Oral, rat: LD50 = 1944 mg/kg" // a second example of what to process is: "Acute oral toxicity (LD<sub>50</sub>) in rats is 264 mg/kg." // a third example of what to process is : "Oral mouse and rat LD<sub>50</sub> are 338 mg/kg and 425 mg/kg respectively" // a fourth example of what to process is: "oral LD<sub>50</sub>s were 1,100-1,550 mg/kg; 1,450 mg/kg; and 1,490 mg/kg; respectively" // most of time it is specified as mg/kg but rarely we also have g/kg: "Oral LD50 in rat: >5 g/kg" Set<Integer> ld50s = new HashSet<Integer>(); int idx = 0;/* ww w. j a v a 2 s . co m*/ int len = annotation.length(); String[] locator = { "LD50", "LD<sub>50</sub>" }; int[] locator_len = { locator[0].length(), locator[1].length() }; int delta = 60; // 60 chars +- the locator for (int l = 0; l < locator.length; l++) { while ((idx = annotation.indexOf(locator[l], idx)) != -1) { // look around a few tokens to find numbers that we can use... int low = idx - delta < 0 ? 0 : idx - delta; int high = idx + delta > len ? len : idx + delta; String sub = annotation.substring(low, idx) + annotation.substring(idx + locator_len[l], high); Scanner scan = new Scanner(sub).useDelimiter("[^0-9,]+"); while (scan.hasNext()) { String scanned = scan.next().replaceAll(",", ""); try { ld50s.add(Integer.parseInt(scanned)); } catch (NumberFormatException e) { } } idx++; // so that we skip the occurrence that we just added } } return ld50s; }
From source file:mase.MaseManagerTerminal.java
public void run(File runnersFile, File jobsFile) { try {//from w w w .j a va2 s . c om if (runnersFile != null) { mng.loadRunners(runnersFile); } } catch (Exception ex) { ex.printStackTrace(); } try { if (jobsFile != null) { mng.loadJobs(jobsFile); } } catch (Exception ex) { ex.printStackTrace(); } final Scanner lineSC = new Scanner(System.in); while (true) { System.out.print("> "); String option = lineSC.next(); Scanner sc = new Scanner(lineSC.nextLine()); try { switch (option) { case "addrunner": mng.addRunner(sc.nextLine()); break; case "loadrunners": while (sc.hasNext()) { mng.loadRunners(new File(sc.next())); } break; case "addjobs": mng.addJob(sc.nextLine()); break; case "loadjobs": while (sc.hasNext()) { mng.loadJobs(new File(sc.next())); } break; case "remove": while (sc.hasNext()) { mng.removeFromWaiting(sc.next()); } break; case "killrunner": while (sc.hasNextInt()) { mng.killRunner(sc.nextInt()); } break; case "kill": while (sc.hasNext()) { mng.killJob(sc.next()); } break; case "killall": mng.failed.addAll(mng.waitingList); mng.waitingList.clear(); List<Job> running = new ArrayList<>(mng.running.values()); for (Job j : running) { mng.killJob(j.id); } break; case "output": int id = sc.nextInt(); int l = sc.hasNextInt() ? sc.nextInt() : lines; System.out.println(mng.getOutput(id, l)); break; case "jobs": while (sc.hasNext()) { String jobid = sc.next(); List<Job> found = mng.findJobs(jobid); for (Job j : found) { System.out.println(j.detailedToString() + "\n-----------------"); } } break; case "status": int ls = sc.hasNextInt() ? sc.nextInt() : lines; System.out.println("Completed: " + mng.completed.size() + "\tWaiting: " + mng.waitingList.size() + "\tFailed: " + mng.failed.size() + "\tRunning: " + mng.running.size() + "/" + mng.runners.size() + " " + (mng.runningStatus() ? "(ACTIVE)" : "(PAUSED)")); for (Entry<JobRunner, Job> e : mng.running.entrySet()) { System.out.println("== " + e.getValue() + " @ " + e.getKey() + " ========"); System.out.println(mng.getOutput(e.getKey().id, ls)); } break; case "list": while (sc.hasNext()) { String t = sc.next(); if (t.equals("failed")) { for (int i = mng.failed.size() - 1; i >= 0; i--) { Job j = mng.failed.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("completed")) { for (int i = mng.completed.size() - 1; i >= 0; i--) { Job j = mng.completed.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("waiting")) { for (int i = mng.waitingList.size() - 1; i >= 0; i--) { Job j = mng.waitingList.get(i); System.out.println(df.format(j.submitted) + " " + j); } } else if (t.equals("runners")) { for (JobRunner r : mng.runners.values()) { if (mng.running.containsKey(r)) { Job runningJob = mng.running.get(r); System.out .println(df.format(runningJob.started) + " " + r + " @ " + runningJob); } else { System.out.println("Idle " + r); } } } else { error("Unknown list: " + t); } } break; case "retry": while (sc.hasNext()) { mng.retryJob(sc.next()); } break; case "retryfailed": mng.retryFailed(); break; case "clear": while (sc.hasNext()) { String t = sc.next(); if (t.equals("failed")) { mng.failed.clear(); } else if (t.equals("completed")) { mng.completed.clear(); } else if (t.equals("waiting")) { mng.waitingList.clear(); } else if (t.equals("runners")) { List<Integer> runners = new ArrayList<>(mng.runners.keySet()); for (Integer r : runners) { mng.killRunner(r); } } else { error("Unknown list: " + t); } } break; case "priority": String type = sc.next(); while (sc.hasNext()) { String i = sc.next(); if (type.equals("top")) { mng.topPriority(i); } else if (type.equals("bottom")) { mng.lowestPriority(i); } } break; case "sort": String sort = sc.next(); if (sort.equals("job")) { mng.sortJobFirst(); } else if (sort.equals("date")) { mng.sortSubmissionDate(); } else { error("Unknown sorting method: " + sort); } break; case "pause": mng.pause(sc.hasNext() && sc.next().equals("force")); break; case "start": mng.resume(); break; case "exit": System.exit(0); break; case "set": String par = sc.next(); switch (par) { case "lines": lines = sc.nextInt(); break; case "maxtries": mng.setMaxTries(sc.nextInt()); break; } break; case "mute": this.mute = true; break; case "unmute": this.mute = false; break; case "help": System.out.println("Available commands:\n" + "-- addrunner runner_type [config]\n" + "-- loadrunners [file]...\n" + "-- addjobs job_params\n" + "-- loadjobs [file]...\n" + "-- killrunner [runner_id]...\n" + "-- remove [job_id]...\n" + "-- kill [job_id]...\n" + "-- killall \n" + "-- output runner_id [lines]\n" + "-- jobs [job_id]...\n" + "-- status [lines]\n" + "-- list [waiting|completed|failed|runners]...\n" + "-- retry [job_id]...\n" + "-- retryfailed \n" + "-- priority top|bottom [job_id]...\n" + "-- sort batch|job|date\n" + "-- clear [waiting|completed|failed|runners]...\n" + "-- pause [force]\n" + "-- start \n" + "-- mute|unmute \n" + "-- exit \n" + "-- set lines|tries value"); break; default: System.out.println("Unknown command. Try help."); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:decision_tree_learning.Matrix.java
public void loadArff(String filename) throws Exception, FileNotFoundException { m_data = new ArrayList<double[]>(); m_attr_name = new ArrayList<String>(); m_str_to_enum = new ArrayList<TreeMap<String, Integer>>(); m_enum_to_str = new ArrayList<TreeMap<Integer, String>>(); boolean READDATA = false; Scanner s = new Scanner(new File(filename)); while (s.hasNext()) { String line = s.nextLine().trim(); if (line.length() > 0 && line.charAt(0) != '%') { if (!READDATA) { Scanner t = new Scanner(line); String firstToken = t.next().toUpperCase(); if (firstToken.equals("@RELATION")) { String datasetName = t.nextLine(); }//from www .ja v a 2 s . c om if (firstToken.equals("@ATTRIBUTE")) { TreeMap<String, Integer> ste = new TreeMap<String, Integer>(); m_str_to_enum.add(ste); TreeMap<Integer, String> ets = new TreeMap<Integer, String>(); m_enum_to_str.add(ets); Scanner u = new Scanner(line); if (line.indexOf("'") != -1) u.useDelimiter("'"); u.next(); String attributeName = u.next(); if (line.indexOf("'") != -1) attributeName = "'" + attributeName + "'"; m_attr_name.add(attributeName); int vals = 0; String type = u.next().trim().toUpperCase(); if (type.equals("REAL") || type.equals("CONTINUOUS") || type.equals("INTEGER") || type.equals("NUMERIC")) { } else { try { String values = line.substring(line.indexOf("{") + 1, line.indexOf("}")); Scanner v = new Scanner(values); v.useDelimiter(","); while (v.hasNext()) { String value = v.next().trim(); if (value.length() > 0) { ste.put(value, new Integer(vals)); ets.put(new Integer(vals), value); vals++; } } } catch (Exception e) { throw new Exception("Error parsing line: " + line + "\n" + e.toString()); } } } if (firstToken.equals("@DATA")) { READDATA = true; } } else { double[] newrow = new double[cols()]; int curPos = 0; try { Scanner t = new Scanner(line); t.useDelimiter(","); while (t.hasNext()) { String textValue = t.next().trim(); //System.out.println(textValue); if (textValue.length() > 0) { double doubleValue; int vals = m_enum_to_str.get(curPos).size(); //Missing instances appear in the dataset as a double defined as MISSING if (textValue.equals("?")) { missing_val = true; doubleValue = MISSING; } // Continuous values appear in the instance vector as they are else if (vals == 0) { doubleValue = Double.parseDouble(textValue); } // Discrete values appear as an index to the "name" // of that value in the "attributeValue" structure else { doubleValue = m_str_to_enum.get(curPos).get(textValue); if (doubleValue == -1) { throw new Exception( "Error parsing the value '" + textValue + "' on line: " + line); } } newrow[curPos] = doubleValue; curPos++; } } } catch (Exception e) { throw new Exception("Error parsing line: " + line + "\n" + e.toString()); } m_data.add(newrow); } } } if (hasMissing()) postmodifyMetadata(); }
From source file:argendata.web.controller.DatasetController.java
@RequestMapping(method = RequestMethod.GET) public ModelAndView view(@RequestParam String qName, HttpSession session) { ModelAndView mav = new ModelAndView(); mav.addObject("mainURL", properties.getMainURL()); Dataset retrievedDataset = this.datasetService.getApprovedDatasetByQName(qName); if (retrievedDataset == null) { logger.info("El dataset no existe"); mav.setViewName("redirect:/bin/dataset/error"); return mav; }/* w ww . jav a 2s. com*/ String format = null; if (retrievedDataset.getDistribution() != null && retrievedDataset.getDistribution().getFormat() != null) { format = retrievedDataset.getDistribution().getFormat().toLowerCase(); } DatasetViewDTO dview; /* * Microsoft Office: doc, docx, xls, xlsx, ppt, pptx, pps; OpenDocument: * odt, ods, odp; OpenOffice:sxw, sxc, sxi; Other Formats: wpd, pdf, * rtf, txt, html, csv, tsv */ if (format != null && (format.endsWith("doc") || format.endsWith("docx") || format.endsWith("xls") || format.endsWith("xlsx") || format.endsWith("ppt") || format.endsWith("pptx") || format.endsWith("pps") || format.endsWith("odt") || format.endsWith("ods") || format.endsWith("odp") || format.endsWith("swx") || format.endsWith("sxi") || format.endsWith("wpd") || format.endsWith("pdf") || format.endsWith("rtf") || format.endsWith("txt") || format.endsWith("csv") || format.endsWith("tsv"))) { dview = new DatasetViewDTO(retrievedDataset, true); } else { dview = new DatasetViewDTO(retrievedDataset, false); } mav.addObject("dto", dview); String theDate = ""; /* Se pasa la fecha a un formato entendible por el usuario final */ String correctDate = dview.getDataset().getModified(); Scanner scanner = new Scanner(correctDate); scanner.useDelimiter("T"); if (scanner.hasNext()) { theDate = scanner.next(); Scanner scannerDate = new Scanner(theDate); scannerDate.useDelimiter("-"); String year = scannerDate.next(); String month = scannerDate.next(); String day = scannerDate.next(); theDate = year + "-" + month + "-" + day; } else { logger.error("No se pudo obtener la fecha de la ltima modificacin."); } mav.addObject("datasetDate", theDate); ArgendataUser user = (ArgendataUser) session.getAttribute("user"); if (user != null && user.isAdmin()) { mav.addObject("admin", true); } else { mav.addObject("admin", false); } if (user != null) { mav.addObject("logged", true); } else { mav.addObject("logged", false); } return mav; }