public void map( Object unused, Text line, OutputCollector<LongWritable, PostingSongArrayWritable> output, Reporter reporter) throws IOException { StringTokenizer str = new StringTokenizer(line.toString(), " |\t"); if (nRatings == 0) { userId = Long.parseLong(str.nextToken()); nRatings = Integer.parseInt(str.nextToken()); songsRatings.clear(); totalRate = 0; } else { long songId = Long.parseLong(str.nextToken()); int rate = Integer.parseInt(str.nextToken()); songsRatings.add(new PostingSong(songId, rate)); totalRate += rate; nRatings--; if (nRatings == 0) { nRatings = songsRatings.size(); songsValue.setArray(songsRatings); output.collect(userIdKey, songsValue); nRatings = 0; } } }
@Override public void map( LongWritable key, Text value, OutputCollector<Text, Text> out, Reporter reporter) throws IOException { if (output == null) { output = out; } int time = 0, counter = 0; String line = value.toString(), v = ""; StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { String k = tokenizer.nextToken(); if ((v = logMap.remove(k)) == null) { time = Integer.parseInt(tokenizer.nextToken()); v = time + " 1"; logMap.put(k, v); } else { StringTokenizer valueTokenizer = new StringTokenizer(v); time = Integer.parseInt(tokenizer.nextToken()) + Integer.parseInt(valueTokenizer.nextToken()); counter = Integer.parseInt(valueTokenizer.nextToken()) + 1; v = time + " " + counter; logMap.put(k, v); } } }
private boolean funcLocMixVeloOk(ccr.app.Context ctx1, ccr.app.Context ctx2) { java.lang.String v1 = (java.lang.String) ctx1.get(Context.FLD_OBJECT); java.lang.String v2 = (java.lang.String) ctx1.get(Context.FLD_TIMESTAMP); java.lang.String v3 = (java.lang.String) ctx2.get(Context.FLD_OBJECT); java.lang.String v4 = (java.lang.String) ctx2.get(Context.FLD_TIMESTAMP); if (v1 == null || v2 == null || v3 == null || v4 == null) { return false; } java.util.StringTokenizer st = new java.util.StringTokenizer(v1); double x1 = Double.parseDouble(st.nextToken()); double y1 = Double.parseDouble(st.nextToken()); st = new java.util.StringTokenizer(v3); double x2 = Double.parseDouble(st.nextToken()); double y2 = Double.parseDouble(st.nextToken()); double dist = Coordinates.calDist(x1, y1, x2, y2); long t = TimeFormat.convert(v4) - TimeFormat.convert(v2) - STAY_TIME; boolean result = false; double vmin = (VELOCITY * ((double) t / 1000) - 2 * ERR) / ((double) t / 1000); double vmax = (VELOCITY * ((double) t / 1000) + 2 * ERR) / ((double) t / 1000); double ve = dist / ((double) t / 1000); if (ve >= vmin && ve <= vmax) { result = true; } return result; }
@Override public boolean parse(GameMode gameMode, String value, URI source) { final StringTokenizer aTok = new StringTokenizer(value, "\t"); if (!aTok.hasMoreTokens()) { Logging.errorPrint("Empty tag in miscinfo.ACTYPE"); return false; } final String acType = aTok.nextToken(); while (aTok.hasMoreTokens()) { final String aString = aTok.nextToken(); if (aString.startsWith("ADD:")) { Collection<ACControl> controls = parseACControl(aString.substring(4)); if (controls == null) { return false; } gameMode.addACAdds(acType, controls); } else if (aString.startsWith("REMOVE:")) { Collection<ACControl> controls = parseACControl(aString.substring(7)); if (controls == null) { return false; } gameMode.addACRemoves(acType, controls); } else { Logging.errorPrint("Incorrect tag in miscinfo.ACTYPE: " + aString); return false; } } return true; }
private boolean funcLocMixVeloOk(Context ctx1, Context ctx2) { // boolean function 4 String v1 = (String) ctx1.get(Context.FLD_OBJECT); String v2 = (String) ctx1.get(Context.FLD_TIMESTAMP); String v3 = (String) ctx2.get(Context.FLD_OBJECT); String v4 = (String) ctx2.get(Context.FLD_TIMESTAMP); if (v1 == null || v2 == null || v3 == null || v4 == null) { return false; } StringTokenizer st = new StringTokenizer(v1); double x1 = Double.parseDouble(st.nextToken()); double y1 = Double.parseDouble(st.nextToken()); st = new StringTokenizer(v3); double x2 = Double.parseDouble(st.nextToken()); double y2 = Double.parseDouble(st.nextToken()); double dist = Coordinates.calDist(x1, y1, x2, y2); long t = TimeFormat.convert(v4) - TimeFormat.convert(v2) - STAY_TIME; // Different here // The velocity should be between vmin and vmax boolean result = false; double vmin = (VELOCITY * ((double) t / 1000) - 2 * ERR) / ((double) t / 1000); double vmax = (VELOCITY * ((double) t / 1000) + 2 * ERR) / ((double) t / 1000); double ve = dist / ((double) t / 1000); if (ve >= vmin && ve <= vmax) { result = true; } return result; }
public Object get(String key) { if (this.myKey.equals(key)) { return this; } else if (this.children.containsKey(key)) { return this.children.get(key); } else if (key.startsWith(this.myKey)) { String smallKey = StringUtils.minus(key, this.myKey + "."); StringTokenizer tokenizer = new StringTokenizer(smallKey, "."); BundleContent bcont = this; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (bcont.children.containsKey(token)) { bcont = bcont.children.get(token); } else { return "!" + key + "!"; } } return bcont; } else { StringTokenizer tokenizer = new StringTokenizer(key, "."); if (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (this.children.containsKey(token)) { return this.children.get(token); } else { return "!" + key + "!"; } } else { return "!" + key + "!"; } } }
/** Metodo que le os clientes de um ficheiro */ public void lerLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades) throws FileNotFoundException, IOException { BufferedReader readLoc = new BufferedReader(new FileReader(fileLocalidades)); BufferedReader readLig = new BufferedReader(new FileReader(fileLigacoes)); int nrligacoes; while (readLoc.ready() && nrlocalidades > 0) { String linhaLoc = readLoc.readLine(); StringTokenizer stLoc = new StringTokenizer(linhaLoc, "|"); nrligacoes = stLoc.countTokens() - 2; Localidade localidade = new Localidade(stLoc.nextToken(), stLoc.nextToken()); while (nrligacoes > 0 && readLig.ready()) { String linhaLig = readLig.readLine(); StringTokenizer stLig = new StringTokenizer(linhaLig, "|"); stLig.nextToken(); Ligacao lig = new Ligacao( stLig.nextToken(), Double.valueOf(stLig.nextToken()), Double.valueOf(stLig.nextToken())); localidade.addLigacao(lig); nrligacoes--; } this.addLocalidade(localidade); nrlocalidades--; } readLoc.close(); readLig.close(); }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int cases = 1; while (true) { st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); if (n == 0 && m == 0) break; a = new int[n]; b = new int[m]; dp = new int[n + 1][m + 1]; st = new StringTokenizer(in.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); Arrays.fill(dp[i], -1); } Arrays.fill(dp[n], -1); st = new StringTokenizer(in.readLine()); for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken()); System.out.println("Twin Towers #" + cases); System.out.println("Number of Tiles : " + LCS(0, 0)); System.out.println(); cases++; } in.close(); System.exit(0); }
/** * Constructor for the Name class Accepts <First Name>,<MiddleName>,<LastName> * or <LastName>;<MiddleName>;<FirstName> and tokenizes them to the appropriate * fields * * @param name String name delimited by , or ; check header for details */ Name(String name) { // Create two tokenizers, one each for , and ; delimited names StringTokenizer sTokComma = new StringTokenizer(name, Name.DELIMITER_COMMA); StringTokenizer sTokSemiColon = new StringTokenizer(name, Name.DELIMITER_SEMI_COLON); // Assume that incomplete names are never supplied // Implying: We must get 3 tokens if (sTokComma.countTokens() == 3) { // Set things right the brute way, since we know 3 tokens exist this.fname = sTokComma.nextToken(); this.mname = sTokComma.nextToken(); this.lname = sTokComma.nextToken(); } else if (sTokSemiColon.countTokens() == 3) { // Set things right the brute way, since we know 3 tokens exist // Caution, Reversed order! this.lname = sTokSemiColon.nextToken(); this.mname = sTokSemiColon.nextToken(); this.fname = sTokSemiColon.nextToken(); } else { // Actually try throw a MalformedNameException but later System.err.println( "MalformedNameException: Name must only be" + "<FirstName>,<MiddleName>,<LastName> or" + "<LastName>;<MiddleName>;<FirstName>"); } }
public Connection connect(String url, Properties info) throws SQLException { if (ConnectionLogger.isInfoEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("connect to URL ").append(url).append(" with properties: ").append(info.toString()); ConnectionLogger.info(sb.toString()); } if (!acceptsURL(url)) throw new SQLException("Invalid URL" + url); url = "jdbc:" + url.substring(urlPrefix.length()); StringTokenizer ts = new StringTokenizer(url, ":/;=&?", false); String targetDriver = null; while (ts.hasMoreTokens()) { String s = ts.nextToken(); logger.debug("s = " + s); if (targetDriverParameter.equals(s) && ts.hasMoreTokens()) { targetDriver = ts.nextToken(); break; } } if (targetDriver == null) throw new SQLException("Can't find targetDriver parameter in URL: " + url); url = url.substring(0, url.length() - targetDriver.length() - targetDriverParameter.length() - 2); try { Class.forName(targetDriver); return ConnectionLoggingProxy.wrap(DriverManager.getConnection(url, info)); } catch (Exception e) { ConnectionLogger.error(e.getMessage(), e); throw new SQLException(e.getMessage()); } }
/** * Called once to load collection handler information for the various collection handlers (Java * 1.1, Java 1.2) based on the configuration file. */ private static synchronized void loadInfo() { if (_info == null) { Vector allInfo; Info[] info; StringTokenizer tokenizer; Class infoClass; Method method; allInfo = new Vector(); LocalConfiguration config = LocalConfiguration.getInstance(); tokenizer = new StringTokenizer( config.getProperty("org.exolab.castor.mapping.collections", ""), ", "); while (tokenizer.hasMoreTokens()) { try { if (CollectionHandlers.class.getClassLoader() != null) infoClass = CollectionHandlers.class.getClassLoader().loadClass(tokenizer.nextToken()); else infoClass = Class.forName(tokenizer.nextToken()); method = infoClass.getMethod("getCollectionHandlersInfo", (Class[]) null); info = (Info[]) method.invoke(null, (Object[]) null); for (int i = 0; i < info.length; ++i) allInfo.addElement(info[i]); } catch (Exception except) { // System.err.println( "CollectionHandlers: " + except.toString() ); } } _info = new Info[allInfo.size()]; allInfo.copyInto(_info); } }
@FXML private void buttonListenerEdit(ActionEvent event) { Employee emp = new Employee(); try { emp.setId(Integer.parseInt(tfInfoId.getText())); emp.setName(tfInfoName.getText()); emp.setPosition(tfInfoPos.getText()); emp.setStreet(tfInfoStreet.getText()); StringTokenizer tokens = new StringTokenizer(tfInfoCSZ.getText(), ","); // REQ#2 String cityState = tokens.nextToken().toString(); String zip = tokens.nextToken(); emp.setCity(cityState.substring(0, cityState.length() - 3)); emp.setState(cityState.substring(cityState.length() - 2)); emp.setZip(zip); emp.setPayRate(Double.parseDouble(tfInfoPayRate.getText())); Environment.updateEmployee(emp); lblEditConfirm.setText("Employee Updated"); } catch (MinimumWageException e) { // REQ#11 REQ#12 lblWageError.setVisible(true); } catch (Exception e) { lblEditConfirm.setText("Error Could Not Update Employee"); } if (rbHourly.isSelected()) { initialize(); populateHourlyEmployee(); } else if (rbSalary.isSelected()) { initialize(); populateSalaryEmployee(); } }
@Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Text outputKey = new Text(); Text outputValue = new Text(); double valA = a; double valB = b; for (Text val : values) { StringTokenizer valStringTokenizer = new StringTokenizer(val.toString(), TAB); String valKey = valStringTokenizer.nextToken(); if (valKey.equals("a")) { valA += Double.parseDouble(valStringTokenizer.nextToken()); } if (valKey.equals("b")) { valB += Double.parseDouble(valStringTokenizer.nextToken()); } } double val = valA * valB; if (val > 0) { outputKey.set(key); outputValue.set(val + TAB + "null"); // 相似性综合 context.write(outputKey, outputValue); } }
/** * Returns an <code>FontWeightRange</code> object holding the range values of the specified <code> * String</code>. * * @param weightRangeString the value range string * @return an <code>FontWeightRange</code> object holding the value ranges */ public static FontWeightRange valueOf(String weightRangeString) { StringTokenizer rangeToken = new StringTokenizer(weightRangeString, ".."); FontWeightRange weightRange = null; if (rangeToken.countTokens() == 2) { String weightString = rangeToken.nextToken().trim(); try { int start = Integer.parseInt(weightString); if (start % 100 != 0) { log.error("font-weight start range is not a multiple of 100"); } int end = Integer.parseInt(rangeToken.nextToken()); if (end % 100 != 0) { log.error("font-weight end range is not a multiple of 100"); } if (start <= end) { weightRange = new FontWeightRange(start, end); } else { log.error("font-weight start range is greater than end range"); } } catch (NumberFormatException e) { log.error("invalid font-weight value " + weightString); } } return weightRange; }
/* * Read frequency in transxchange specific format */ static int readTransxchangeFrequency(String inString) { int freq = 0; inString = inString.substring(2, inString.length()); // Skip "PT" if (inString.indexOf('H') > 0) { // Hours StringTokenizer st = new StringTokenizer(inString, "H"); int i = 0; while (st.hasMoreTokens() && i < 1) { freq = Integer.parseInt(st.nextToken()) * 60 * 60; i++; } inString = inString.substring(inString.indexOf('H') + 1, inString.length()); } if (inString.indexOf('M') > 0) { // Minutes StringTokenizer st = new StringTokenizer(inString, "M"); int i = 0; while (st.hasMoreTokens() && i < 1) { freq += Integer.parseInt(st.nextToken()) * 60; i++; } inString = inString.substring(inString.indexOf('M') + 1, inString.length()); } if (inString.indexOf('S') > 0) { // Seconds StringTokenizer st = new StringTokenizer(inString, "S"); int i = 0; while (st.hasMoreTokens() && i < 1) { freq += Integer.parseInt(st.nextToken()); i++; } } return freq; }
/** * Reads and stores the mime type setting corresponding to a file extension, by reading text from * an InputStream. If a mime type setting already exists when this method is run, the mime type * value is replaced with the newer one. * * @param is * @throws IOException */ public void loadAndReplaceMimetypes(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.length() == 0) { // Ignore comments and empty lines. } else { StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { String mimetype = st.nextToken(); while (st.hasMoreTokens()) { String extension = st.nextToken(); extensionToMimetypeMap.put(extension, mimetype); if (log.isDebugEnabled()) { log.debug( "Setting mime type for extension '" + extension + "' to '" + mimetype + "'"); } } } else { if (log.isDebugEnabled()) { log.debug("Ignoring mimetype with no associated file extensions: '" + line + "'"); } } } } }
/** * @param item the tweet to preprocess * @return the tweet after pre-processing */ public String preprocessDocument(String item) { String result_fin = ""; String result = item; StringTokenizer st1 = new StringTokenizer(result, " ,?![]"); while (st1.hasMoreTokens()) { String str = st1.nextToken(); result = removeUrl(str); if (!_opt.isRemoveEmoticons()) result = replaceEmoticons(result); else result = removeEmoticons(result); StringTokenizer st2 = new StringTokenizer(result, ".:#)(_"); String tmp = ""; String tmp2 = ""; while (st2.hasMoreTokens()) { tmp = st2.nextToken(); tmp = recognizeLaugh(tmp); tmp2 = tmp2 + " " + removeUsername(tmp); } result = tmp2; result = result.replaceAll("lu+v+", "love"); result = removeRepeatedCharacters(result); // result = removeSymbols(result); result_fin = result_fin + result; } return result_fin; }
/** * ************************************************************************* loadHashFromFile - * loads a hastable from a file the format of the file is inflected_word base_form with a space * between both words ************************************************************************ */ private HashMap<String, ArrayList<String>> loadHashFromFile(String filename) { HashMap<String, ArrayList<String>> hashtable = new HashMap<String, ArrayList<String>>(); try { BufferedReader br = new BufferedReader(new FileReader(filename)); StringTokenizer st; for (; ; ) { String line = br.readLine(); if (line == null) { br.close(); break; } else { st = new StringTokenizer(line, " "); ArrayList<String> baseList = new ArrayList<String>(); String inflected = st.nextToken(); while (st.hasMoreTokens()) { baseList.add(st.nextToken()); } hashtable.put(inflected, baseList); } } } catch (Exception e) { // System.out.println(line); System.out.println("Error:" + e); } return hashtable; }
protected void buildPanel(String strPath) { BufferedReader reader = WFileUtil.openReadFile(strPath); String strLine; if (reader == null) return; try { while ((strLine = reader.readLine()) != null) { if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@")) continue; StringTokenizer sTokLine = new StringTokenizer(strLine, ":"); // first token is the label e.g. Password Length if (sTokLine.hasMoreTokens()) { createLabel(sTokLine.nextToken(), this); } // second token is the value String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : ""; if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no")) createChkBox(strValue, this); else createTxf(strValue, this); } } catch (Exception e) { Messages.writeStackTrace(e); // e.printStackTrace(); Messages.postDebug(e.toString()); } }
public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("barn1.in")); out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out"))); StringTokenizer nstr = new StringTokenizer(f.readLine()); int m = Integer.parseInt(nstr.nextToken()); int s = Integer.parseInt(nstr.nextToken()); occupied = new ArrayList<ArrayList<Integer>>(); occupied.add(new ArrayList<Integer>()); for (int i = 0; i < s; i++) { try { nstr = new StringTokenizer(f.readLine()); occupied.get(0).add(Integer.parseInt(nstr.nextToken())); } catch (NullPointerException e) { break; } } Collections.sort(occupied.get(0)); int bound = m - 1; if (occupied.get(0).size() - 1 < bound) { bound = occupied.get(0).size() - 1; } for (int i = 0; i < bound; i++) { findMaxCut(); } int total = 0; int len = occupied.size(); for (int i = 0; i < len; i++) { ArrayList<Integer> arr = occupied.get(i); int len2 = arr.size(); total += arr.get(len2 - 1) - arr.get(0) + 1; } out.println(total); out.close(); System.exit(0); }
/** * Returns a vector with column names of the dataset, listed in "list". If a column cannot be * found or the list is empty the ones from the default list are returned. * * @param list comma-separated list of attribute names * @param defaultList the default list of attribute names * @param inst the instances to get the attribute names from * @return a vector containing attribute names */ protected Vector determineColumnNames(String list, String defaultList, Instances inst) { Vector result; Vector atts; StringTokenizer tok; int i; String item; // get attribute names atts = new Vector(); for (i = 0; i < inst.numAttributes(); i++) atts.add(inst.attribute(i).name().toLowerCase()); // process list result = new Vector(); tok = new StringTokenizer(list, ","); while (tok.hasMoreTokens()) { item = tok.nextToken().toLowerCase(); if (atts.contains(item)) { result.add(item); } else { result.clear(); break; } } // do we have to return defaults? if (result.size() == 0) { tok = new StringTokenizer(defaultList, ","); while (tok.hasMoreTokens()) result.add(tok.nextToken().toLowerCase()); } return result; }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; StringTokenizer stk; while ((line = in.readLine()) != null) { stk = new StringTokenizer(line); int n = Integer.parseInt(stk.nextToken()); int k = Integer.parseInt(stk.nextToken()); int m = Integer.parseInt(stk.nextToken()); long[][] dp = new long[n + 1][k + 1]; dp[0][0] = 1; for (int i = 1; i <= n; ++i) // units for (int j = 1; j <= k; ++j) // bars for (int l = 1; l <= m && l <= i; ++l) // size of the next bar dp[i][j] += dp[i - l][j - 1]; System.out.println(dp[n][k]); } in.close(); System.exit(0); }
/** * Read all cineplex * * @return * @throws IOException */ public static ArrayList<Cineplex> readCineplex() throws IOException { ArrayList stringArray = (ArrayList) read("data/cineplexes.txt"); ArrayList alr = new ArrayList(); // to store data for (int i = 0; i < stringArray.size(); i++) { String st = (String) stringArray.get(i); // get individual 'fields' of the string separated by SEPARATOR StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass // in // the // string // to // the // string // tokenizer // using // delimiter // "|" int cineplexId = Integer.parseInt(star.nextToken().trim()); String cineplexName = star.nextToken().trim(); Cineplex u = new Cineplex(cineplexId, cineplexName); // add to list alr.add(u); } return alr; }
private static String getResponseHeaderLocation(String urlActual, URLConnection con) throws IOException { String location = HttpUtil.getResponseHeader((URLConnection) con, "Location"); if (!StringUtils.isEmpty(location)) { location = location.trim(); if (location.startsWith("/")) { StringTokenizer st = new StringTokenizer(urlActual, "/", true); // true // para // que // devuelva // los // separadores // como // tokens String domain = ""; if (st.countTokens() < 4) { throw new IOException("No se puede extraer el dominio de la url: " + urlActual); } else { domain = st.nextToken() + st.nextToken() + st.nextToken() + st.nextToken(); } location = domain + location; } } return location; }
/*Set a option when both the price and name are sent as a * string*/ protected void setOptionSetDetail1(String optionString, int index) throws AutoException { int i = 0; StringTokenizer st = new StringTokenizer(optionString, ","); String temp; while (st.hasMoreTokens()) { temp = st.nextToken(); StringTokenizer st1 = new StringTokenizer(temp, "$"); if (st1.countTokens() == 2) { this.option.add(new Options()); this.option.get(i).setOptionName1(st1.nextToken()); try { try { this.option.get(i).setPrice(Float.parseFloat((st1.nextToken()))); } catch (NumberFormatException e4) { this.option.get(i).setPrice(0); throw new AutoException(4, index); } } catch (AutoException e) { } i++; } else { this.option.get(i).setOptionName1(""); this.option.get(i).setPrice(0); throw new AutoException(5, index); } } }
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader a = new BufferedReader(new InputStreamReader(System.in)); String inp; int n; // int k; // double balance; inp = a.readLine(); StringTokenizer st = new StringTokenizer(inp); n = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); String inp2; inp2 = a.readLine(); StringTokenizer st2 = new StringTokenizer(inp2); int[] numbers = new int[n]; // int d=0; int count = 0; for (int i = 0; i < n; i++) { numbers[i] = Integer.parseInt(st2.nextToken()); // System.out.println(numbers[i]); } Arrays.sort(numbers); for (int i = 0; i < n; i++) { count += binaryLeft(0, i - 1, numbers, i); count += binaryRight(i + 1, n - 1, numbers, i); } System.out.println(count / 2); }
public void execute(Session session, String line, PrintStream out, PrintStream err) { // Parse command line. StringTokenizer st = new StringTokenizer(line, " "); // Ignore the command name. st.nextToken(); // Check for optional argument. String property = null; if (st.countTokens() >= 1) { property = st.nextToken().trim(); } try { if (session.getAttribute(Activator.CURRENT) == null) { throw new Exception("No configuration open currently"); } Dictionary dict = (Dictionary) session.getAttribute(Activator.EDITED); if (dict == null) { Configuration cfg = (Configuration) session.getAttribute(Activator.CURRENT); dict = cfg.getProperties(); session.setAttribute(Activator.EDITED, dict); } Object oldValue = dict.remove(property); if (oldValue == null) { throw new Exception("No property named " + property + " in current configuration."); } } catch (Exception e) { out.println("Unset failed. Details:"); String reason = e.getMessage(); out.println(reason == null ? "<unknown>: " + e.toString() : reason); } }
private Map checkForProperties(TipiContext context, Enumeration e) { Map result = new HashMap(); while (e.hasMoreElements()) { String current = (String) e.nextElement(); if (current.startsWith("-D")) { String prop = current.substring(2); try { StringTokenizer st = new StringTokenizer(prop, "="); String name = st.nextToken(); String value = st.nextToken(); System.setProperty(name, value); result.put(name, value); } catch (NoSuchElementException ex) { logger.info("Error parsing system property"); } } if ("tipidef".equals(current)) { tipiDef = myServletConfig.getInitParameter(current); logger.info("Startup def: " + tipiDef); continue; } context.setSystemProperty(current, myServletConfig.getInitParameter(current)); } return result; }
// Read from file public void readFile(String fileName) { // TODO Auto-generated method stub try { FileReader frStream = new FileReader(fileName); BufferedReader brStream = new BufferedReader(frStream); String inputLine; int i = 0; Vector<Object> currentRow = new Vector<Object>(); while ((inputLine = brStream.readLine()) != null) { // Ignore the file comment if (inputLine.startsWith("#")) continue; // Extract the column name if (inputLine.startsWith("$")) { StringTokenizer st1 = new StringTokenizer(inputLine.substring(1), " "); while (st1.hasMoreTokens()) colName.addElement(st1.nextToken()); } else // Extract data and put into the row records { StringTokenizer st1 = new StringTokenizer(inputLine, " "); currentRow = new Vector<Object>(); while (st1.hasMoreTokens()) currentRow.addElement(st1.nextToken()); data.addElement(currentRow); } } brStream.close(); } catch (IOException ex) { System.out.println("Error in readFile method! " + ex); } }
/** * Determines the command denoted by the line. * * @param line the text as typed in at the console. * @return the command represented by the line, or NONE if the line is empty. * @throws InvalidCommandException if no recognizable command was found on a non-empty line. */ static Command getCommand(String line) throws InvalidCommandException { StringTokenizer tokenizer = new StringTokenizer(line); if (!tokenizer.hasMoreTokens()) { return NONE; } String command = tokenizer.nextToken(); /* Check for a manifest command */ for (Command c : Command.values()) { if (c.manifest && c.name().equalsIgnoreCase(command)) { if (!tokenizer.hasMoreTokens()) { return c; } /* Extra token. */ throw new InvalidCommandException( "Unexpected argument: " + tokenizer.nextToken() + " for command: " + command); } } /* A stock update command, token following arg must be a price*/ if (!tokenizer.hasMoreTokens()) { throw new InvalidCommandException("Unknown command: " + command + "\n" + StockQuotes.usage()); } String price = tokenizer.nextToken(); try { Float.parseFloat(price); if (tokenizer.hasMoreTokens()) { throw new InvalidCommandException("Extraneous argument: " + tokenizer.nextToken()); } } catch (NumberFormatException e) { throw new InvalidCommandException("Stock price must be a numeric value, not: " + price); } return UPDATE; }