List of usage examples for java.util TreeSet contains
public boolean contains(Object o)
From source file:edu.utexas.cs.tactex.BalancingManagerService.java
@Override public double getFudgeCorrection(int currentTimeslotIndex) { // extract data for prediction ArrayList<Double> pastErrors = new ArrayList<Double>(); TreeSet<Integer> debugTimeslots = new TreeSet<Integer>(); for (Entry<Integer, Double> e : timeslotConsumption.descendingMap().entrySet()) { Integer timeslot = e.getKey(); Double actualConsumption = e.getValue(); Double prediction = timeslotPredictions.get(timeslot); if (prediction != null) { pastErrors.add(actualConsumption - prediction); // debug: debugTimeslots.add(timeslot); // stop when there are MEMORY_LENGTH elements if (pastErrors.size() >= MEMORY_LENGTH) break; }// w ww. jav a 2 s . c o m } for (int i = currentTimeslotIndex - 24; i < currentTimeslotIndex; ++i) { if (!debugTimeslots.contains(i)) log.error("Timeslot " + i + " doesn't exist in fudge data for ts " + currentTimeslotIndex); } // compute prediction double fudgeFactor; if (pastErrors.size() >= MIN_DATA_SIZE) { // compute mean fraction double total = 0; for (Double error : pastErrors) { total += error; log.debug("fudge error " + error + " total " + total); } double meanError = total / pastErrors.size(); fudgeFactor = -meanError; // - due to consumption being negative } else { log.debug("getFudgeCorrection() doesn't have enough data, returning default"); fudgeFactor = 0.0; } log.debug("BalancingManager, fudge-factor=" + fudgeFactor); return fudgeFactor; }
From source file:org.accada.epcis.repository.query.Schedule.java
/** * Sets the field of a GregorianCalender to its minimum, which is defined as * the minimal possible value according to the calendar type possibly * superseded by the defined values in the schedule we have. Returns whether * the new value has been set and is valid. * /*from ww w .ja va 2s . c o m*/ * @param cal * Calendar to adjust. * @param field * Field to adjust. * @return Returns whether the new value has been set and is valid. * @throws ImplementationException * Almost any error. */ private boolean setFieldToMinimum(final GregorianCalendar cal, final int field) throws ImplementationExceptionResponse { int min; TreeSet<Integer> values = getValues(field); if (values.isEmpty()) { min = cal.getActualMinimum(field); } else { min = Math.max(values.first().intValue(), cal.getActualMinimum(field)); if (min > cal.getActualMaximum(field)) { min = cal.getActualMaximum(field); if (!values.contains(Integer.valueOf(min)) || min < cal.getActualMinimum(field) || min > cal.getActualMaximum(field)) { return false; } } } cal.set(field, min); return true; }
From source file:org.structnetalign.merge.BronKerboschMergeJob.java
@Override public List<NavigableSet<Integer>> call() throws Exception { logger.info("Searching for cliques on job " + index + " containing " + graph.getVertexCount() + " vertices and " + graph.getHomologyCount() + " homology edges"); // find the cliques BronKerboschCliqueFinder<Integer, HomologyEdge> finder = new BronKerboschCliqueFinder<>(); // these cliques are ordered from largest to smallest Collection<Set<Integer>> cliques = finder.transform(graph.getHomology()); // just report the cliques we're using logger.info("Job " + index + ": " + "Found " + cliques.size() + " maximal cliques"); int i = 1;/* w w w . j a v a 2 s . c o m*/ for (Set<Integer> clique : cliques) { logger.debug("Job " + index + ": " + "Clique " + i + ": " + clique); i++; } // partition the cliques by sets of interactions // we call these (maximal) degenerate sets List<NavigableSet<Integer>> simpleDegenerateSets = new ArrayList<NavigableSet<Integer>>(); for (Set<Integer> clique : cliques) { NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>(); for (int v : clique) { Collection<Integer> neighbors = graph.getInteractionNeighbors(v); String hash = hashVertexInteractions(neighbors); NavigableSet<Integer> degenerateSet = degenerateSetMap.get(hash); if (degenerateSet == null) { degenerateSet = new TreeSet<>(); degenerateSetMap.put(hash, degenerateSet); } degenerateSet.add(v); logger.trace("Job " + index + ": " + "Found " + hash + " --> " + degenerateSetMap.get(hash)); } for (NavigableSet<Integer> set : degenerateSetMap.values()) { simpleDegenerateSets.add(set); } } /* * Now sort the degenerate sets from largest to smallest. * Take into account the edge case where the sizes are the same. */ Comparator<NavigableSet<Integer>> comparator = new Comparator<NavigableSet<Integer>>() { @Override public int compare(NavigableSet<Integer> clique1, NavigableSet<Integer> clique2) { if (CollectionUtils.isEqualCollection(clique1, clique2)) return 0; if (clique1.size() < clique2.size()) { return 1; } else if (clique1.size() > clique2.size()) { return -1; } else { Iterator<Integer> iter1 = clique1.iterator(); Iterator<Integer> iter2 = clique2.iterator(); while (iter1.hasNext()) { // we know they're the same size int v1 = iter1.next(); int v2 = iter2.next(); if (v1 < v2) { return 1; } else if (v1 > v2) { return -1; } } } // they're the same throughout, so they're equal return 0; } }; List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(simpleDegenerateSets.size()); sortedDegenerateSets.addAll(simpleDegenerateSets); Collections.sort(sortedDegenerateSets, comparator); /* * Now we want to return only the maximal maximal degenerate sets. */ TreeSet<String> verticesAlreadyUsed = new TreeSet<String>(); List<NavigableSet<Integer>> finalDegenerateSets = new ArrayList<>(sortedDegenerateSets.size()); int nTrivial = 0; int nWeak = 0; // a degenerate set is weak if it contains a vertex that is added first forcliques: for (NavigableSet<Integer> set : sortedDegenerateSets) { // discard trivial degenerate sets if (set.size() < 2) { nTrivial++; continue; } // verify that we haven't already used any vertex in this degenerate set for (int v : set) { String hash = NetworkUtils.hash(v); // use MD5 for safety if (verticesAlreadyUsed.contains(hash)) { // discard this degenerate set and do NOT say we've used any of these vertices nWeak++; continue forcliques; } } // we haven't used any vertex in this degenerate set // now add all of these vertices // do NOT add before, or we'll add vertices we haven't used yet for (int v : set) { String hash = NetworkUtils.hash(v); verticesAlreadyUsed.add(hash); } finalDegenerateSets.add(set); // keep this degenerate set } logger.info("Job " + index + ": " + "Found " + finalDegenerateSets.size() + " strong nontrivial maximal degenerate sets found (" + nTrivial + " trivial and " + nWeak + " weak)"); return finalDegenerateSets; }
From source file:org.jbpm.formModeler.components.editor.WysiwygFormEditor.java
protected synchronized String generateDecoratorName(Form form) { TreeSet names = new TreeSet(); for (Field pff : form.getFormFields()) { names.add(pff.getFieldName());/*from w w w .j a v a 2 s.co m*/ } String name = ":decorator_0"; for (int i = 1; names.contains(name); name = ":decorator_" + (i++)) ; return name; }
From source file:org.apache.hadoop.dfs.NamenodeFsck.java
private DatanodeInfo bestNode(DFSClient dfs, DatanodeInfo[] nodes, TreeSet<DatanodeInfo> deadNodes) throws IOException { if ((nodes == null) || (nodes.length - deadNodes.size() < 1)) { throw new IOException("No live nodes contain current block"); }/* w ww .j av a 2 s .c om*/ DatanodeInfo chosenNode; do { chosenNode = nodes[r.nextInt(nodes.length)]; } while (deadNodes.contains(chosenNode)); return chosenNode; }
From source file:net.spfbl.data.White.java
public static TreeSet<String> getAllTokens(String value) { TreeSet<String> whiteSet = new TreeSet<String>(); if (Subnet.isValidIP(value)) { String ip = Subnet.normalizeIP(value); if (SET.contains(ip)) { whiteSet.add(ip);//from w ww. ja v a2s .c om } } else if (Subnet.isValidCIDR(value)) { String cidr = Subnet.normalizeCIDR(value); if (CIDR.contains((String) null, cidr)) { whiteSet.add(cidr); } TreeSet<String> set = SET.getAll(); for (String ip : set) { if (Subnet.containsIP(cidr, ip)) { whiteSet.add(ip); } } for (String ip : set) { if (SubnetIPv6.containsIP(cidr, ip)) { whiteSet.add(ip); } } } else if (value.startsWith(".")) { String hostname = value; TreeSet<String> set = SET.getAll(); for (String key : set) { if (key.endsWith(hostname)) { whiteSet.add(key); } } for (String mx : set) { String hostKey = '.' + mx.substring(1); if (hostKey.endsWith(hostname)) { whiteSet.add(hostKey); } } } else if (SET.contains(value)) { whiteSet.add(value); } return whiteSet; }
From source file:com.ecyrd.jspwiki.plugin.PluginManager.java
/** * {@inheritDoc}//from w ww. j a v a2 s . co m */ public Collection modules() { TreeSet<WikiModuleInfo> ls = new TreeSet<WikiModuleInfo>(); for (Iterator i = m_pluginClassMap.values().iterator(); i.hasNext();) { WikiModuleInfo wmi = (WikiModuleInfo) i.next(); if (!ls.contains(wmi)) ls.add(wmi); } return ls; }
From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java
/** * Set the headers in the response object, excluding the Gzip header * @param pageInfo// w ww . j a v a 2s .c om * @param response */ protected void setHeaders(final PageInfo pageInfo, final HttpServletResponse response) { Collection<Header<? extends Serializable>> headers = pageInfo.getHeaders(); // Track which headers have been set so all headers of the same name // after the first are added TreeSet<String> setHeaders = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); for (Header<? extends Serializable> header : headers) { String name = header.getName(); switch (header.getType()) { case STRING: if (setHeaders.contains(name)) { response.addHeader(name, (String) header.getValue()); } else { setHeaders.add(name); response.setHeader(name, (String) header.getValue()); } break; case DATE: if (setHeaders.contains(name)) { response.addDateHeader(name, (Long) header.getValue()); } else { setHeaders.add(name); response.setDateHeader(name, (Long) header.getValue()); } break; case INT: if (setHeaders.contains(name)) { response.addIntHeader(name, (Integer) header.getValue()); } else { setHeaders.add(name); response.setIntHeader(name, (Integer) header.getValue()); } break; default: throw new IllegalArgumentException("No mapping for Header: " + header); } } }
From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java
@Override public String doInBackground(Void... voids) { String dst = null;//from ww w . j a va2 s . c om String filename = mSrc.substring(mSrc.lastIndexOf("/") + 1, mSrc.lastIndexOf(".")); ArrayList<Rectangle> rects = new ArrayList<Rectangle>(); for (String s : mRectangles) rects.add(new Rectangle(s)); mSquareNum = rects.size(); mHorizStarts = new int[mSquareNum]; mHorizEnds = new int[mSquareNum]; mVertStarts = new int[mSquareNum]; mVertEnds = new int[mSquareNum]; mKeys = new String[mSquareNum]; for (int i = 0; i < mSquareNum; i++) { mHorizStarts[i] = rects.get(i).x0 / 16; mHorizEnds[i] = rects.get(i).xEnd / 16; mVertStarts[i] = rects.get(i).y0 / 16; mVertEnds[i] = rects.get(i).yEnd / 16; } mNewId = null; boolean permissionToSelf = false; JSONArray permissions = new JSONArray(); try { JSONObject obj = new JSONObject(); JSONArray usernames; obj.put(JSON_PROTOCOLVERSION, CURRENT_VERSION); obj.put(JSON_FILENAME, filename); obj.put(JSON_IMGHEIGHT, mHeight); obj.put(JSON_IMGWIDTH, mWidth); permissions.put(obj); for (int i = 0; i < mSquareNum; i++) { TreeSet<String> auxSet = new TreeSet<String>(); // helps in checking a permission is not granted twice obj = new JSONObject(); obj.put(JSON_HSTART, mHorizStarts[i]); obj.put(JSON_HEND, mHorizEnds[i]); obj.put(JSON_VSTART, mVertStarts[i]); obj.put(JSON_VEND, mVertEnds[i]); usernames = new JSONArray(); usernames.put(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); auxSet.add(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); for (String str : rects.get(i).getPermissionsArrayList()) { if (!auxSet.contains(str.toLowerCase(Locale.ENGLISH))) { usernames.put(str.toLowerCase(Locale.ENGLISH)); auxSet.add(str.toLowerCase(Locale.ENGLISH)); } else if (str.equalsIgnoreCase(mMainActivity.getUserEmail())) permissionToSelf = true; } obj.put(JSON_USERNAME, usernames); permissions.put(obj); } } catch (JSONException jsonex) { // Will never happen: every value is either a number, or a correctly formatted email } if (permissionToSelf) { publishProgress(5); } DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_ONESTEPUPLOAD; HttpPost httppost = new HttpPost(target); while (mCookie == null) { // loop until authentication finishes, if necessary mCookie = mMainActivity.getCurrentCookie(); } try { StringEntity permissionsEntity = new StringEntity(permissions.toString()); permissionsEntity.setContentType(new BasicHeader("Content-Type", "application/json")); httppost.setEntity(permissionsEntity); httppost.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue()); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { mConnectionSucceeded = false; throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); mConnectionSucceeded = false; } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: " + successState.get(JSON_REASON)); } else { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get("reason")); } } else { // everything went OK mNewId = jsonArray.getJSONObject(1).getString(JSON_PICTUREID); for (int i = 0; i < mSquareNum; i++) { mKeys[i] = jsonArray.getJSONObject(i + 2).getString(JSON_KEY); } if (mNewId == null) { mConnectionSucceeded = false; Log.e(APP_TAG, "Encryption: Error connecting to server"); } else { publishProgress(10); String date = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date()); File directory = new File( Environment.getExternalStorageDirectory() + "/" + APP_TAG); if (!directory.exists()) { directory.mkdir(); } dst = Environment.getExternalStorageDirectory() + "/" + APP_TAG + "/" + ENCRYPTED_FILE_PREFIX + filename + "_" + date + ".jpg"; mSuccess = MainActivity.encodeWrapperRegions(mSrc, dst, mSquareNum, mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mNewId); addToGallery(dst); } } } } catch (JSONException jsonEx) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } } } catch (ClientProtocolException e) { mConnectionSucceeded = false; } catch (IOException e) { mConnectionSucceeded = false; } return dst; }
From source file:edu.fullerton.ldvw.ImageHistory.java
/** * Add a table of buttons/links and info to control display and deletion * * @param imgCnt total number of records in selection */// ww w.ja v a 2 s .c o m private PageItemList getNavBar(int imgCnt, boolean isBottom, String frmName) throws WebUtilException, LdvTableException, SQLException { PageItemList ret = new PageItemList(); PageTable navBar = new PageTable(); PageTableRow cmds = new PageTableRow(); // add next/prev buttons if applicable PageFormButton prevBtn = new PageFormButton("submitAct", "<", "Prev"); prevBtn.setEnabled(strt > 0); cmds.add(prevBtn); String botSuffix = isBottom ? "2" : ""; int curPage = strt / cnt + 1; int nPage = (imgCnt + cnt - 1) / cnt; PageItemList pageSel = new PageItemList(); pageSel.add("Page: "); PageFormText pageNum = new PageFormText("pageNum" + botSuffix, String.format("%1$,d", curPage)); pageNum.setSize(3); pageNum.setMaxLen(6); pageNum.addEvent("onchange", "historySubmit('Go" + botSuffix + "', this);"); pageSel.add(pageNum); pageSel.add(String.format(" of %d ", nPage)); cmds.add(pageSel); PageFormButton nextBtn = new PageFormButton("submitAct", ">", "Next"); nextBtn.setEnabled(curPage < nPage); cmds.add(nextBtn); int stop = Math.min(strt + cnt, imgCnt); String showing = String.format("Showing %1$d-%2$d for:", strt + 1, stop); cmds.add(showing); // add selection by user String cn = vuser.getCn(); TreeMap<String, Integer> ucounts = imgTbl.getCountByUser(); String[] usrs = new String[ucounts.size() + 1]; String sel = "All"; usrs[0] = "All"; int i = 1; for (Map.Entry<String, Integer> entry : ucounts.entrySet()) { String u = entry.getKey(); Integer cnts = entry.getValue(); String opt = String.format("%1$s (%2$d)", u, cnts); if (userWanted.equalsIgnoreCase(u)) { sel = opt; } usrs[i] = opt; i++; } if (!isBottom) { // allow them to select another user (or all) PageFormSelect usrSel = new PageFormSelect("usrSel", usrs); usrSel.setSelected(sel); usrSel.addEvent("onchange", "this.form.submit()"); PageItemList owner = new PageItemList(); owner.add(new PageItemString("Owner: ", false)); owner.add(usrSel); cmds.add(owner); // Group selector TreeSet<String> groups = imgGrpTbl.getGroups(userWanted); if (!groups.isEmpty()) { PageItemList grpPIL = new PageItemList(); grpPIL.add(new PageItemString("Group: ", false)); groups.add("All"); PageFormSelect grpSel = new PageFormSelect("group"); grpSel.add(groups); String curGroup = request.getParameter("group"); if (curGroup != null && !curGroup.isEmpty() && groups.contains(curGroup)) { grpSel.setSelected(curGroup); } else { grpSel.setSelected("All"); } grpSel.addEvent("onchange", "document." + frmName + ".submit()"); grpPIL.add(grpSel); cmds.add(grpPIL); } } cmds.setClassAll("noborder"); navBar.addRow(cmds); ret.add(navBar); if (!isBottom) { // New table because this one has fewer columns and we want to hide it by default navBar = new PageTable(); navBar.setClassName("hidable"); navBar.addStyle("display", "none"); // allow them to change image size PageTableRow cmd2 = new PageTableRow(); String[] sizes = { "original", "small", "med" }; PageFormSelect sizeSel = new PageFormSelect("size", sizes); String curSize = request.getParameter("size"); if (curSize != null && !curSize.isEmpty() && ArrayUtils.contains(sizes, curSize)) { sizeSel.setSelected(curSize); } sizeSel.addEvent("onchange", "document." + frmName + ".submit()"); PageItemString lbl; lbl = new PageItemString("Size: ", false); lbl.setAlign(PageItem.Alignment.RIGHT); cmd2.add(lbl); PageTableColumn col; col = new PageTableColumn(sizeSel); cmd2.add(col); cmd2.add(); cmd2.add(); cmd2.setClassAll("noborder"); navBar.addRow(cmd2); cmd2 = new PageTableRow(); lbl = new PageItemString("Selections: ", false); lbl.setAlign(PageItem.Alignment.RIGHT); cmd2.add(lbl); PageFormButton selAll = new PageFormButton("selAll", "Select all", "selall"); selAll.setType("button"); selAll.addEvent("onclick", "setChkBoxByClass('selBox',true)"); cmd2.add(selAll); PageFormButton clrAll = new PageFormButton("selAll", "Clear all", "clrall"); clrAll.setType("button"); clrAll.addEvent("onclick", "setChkBoxByClass('selBox', false)"); cmd2.add(clrAll); cmd2.add(); cmd2.setClassAll("noborder"); navBar.addRow(cmd2); if (userWanted.equalsIgnoreCase(vuser.getCn()) || vuser.isAdmin()) { cmd2 = new PageTableRow(); lbl = new PageItemString("Delete images: ", false); lbl.setAlign(PageItem.Alignment.RIGHT); cmd2.add(lbl); col = new PageTableColumn(new PageFormSubmit("submitAct", "Delete Selected")); cmd2.add(col); cmd2.add(); cmd2.add(); cmd2.setClassAll("noborder"); navBar.addRow(cmd2); } PageTableRow grpRow = new PageTableRow(); lbl = new PageItemString("My groups: ", false); lbl.setAlign(PageItem.Alignment.RIGHT); grpRow.add(lbl); TreeSet<String> myGroup = imgGrpTbl.getGroups(curUser); if (!myGroup.contains("Favorites")) { myGroup.add("Favorites"); } myGroup.remove("Last result"); PageFormSelect grpSel = new PageFormSelect("op_group"); grpSel.add(myGroup); String curGroup = request.getParameter("groupSel"); if (curGroup != null && !curGroup.isEmpty() && myGroup.contains(curGroup)) { grpSel.setSelected(curGroup); } else { grpSel.setSelected("Favorites"); } grpRow.add(grpSel); grpRow.add(new PageFormSubmit("submitAct", "Add to grp")); grpRow.add(new PageFormSubmit("submitAct", "Del from grp")); grpRow.setClassAll("noborder"); navBar.addRow(grpRow); grpRow = new PageTableRow(); lbl = new PageItemString("New Group: ", false); lbl.setAlign(PageItem.Alignment.RIGHT); grpRow.add(lbl); PageFormText grpNameTxt = new PageFormText("newGrpName", "<new group name>"); grpNameTxt.addEvent("onfocus", "if(this.value == '<new group name>'){ this.value = ''; }"); grpNameTxt.addEvent("onblur", "if(this.value == ''){ this.value = '<new group name>'; }"); grpRow.add(grpNameTxt); PageFormSubmit newGrpBtn = new PageFormSubmit("submitAct", "New grp"); grpRow.add(newGrpBtn); grpRow.add(); grpRow.setClassAll("noborder"); navBar.addRow(grpRow); ret.add(navBar); PageItemString optBtn = new PageItemString("+More options"); optBtn.addEvent("onclick", "showByClass('hidable',this)"); optBtn.setClassName("showCmd"); ret.addBlankLines(1); ret.add(optBtn); } vpage.includeJS("showByClass.js"); return ret; }