List of usage examples for java.util LinkedList getLast
public E getLast()
From source file:mulavito.algorithms.shortestpath.ksp.Yen.java
@Override protected List<List<E>> getShortestPathsIntern(final V source, final V target, int k) { LinkedList<List<E>> found_paths = new LinkedList<List<E>>(); PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>(); DijkstraShortestPath<V, E> blockedDijkstra; // Check if target is reachable from source. if (dijkstra.getDistance(source, target) == null) return found_paths; // Add Dijkstra solution, the first shortest path. found_paths.add(dijkstra.getPath(source, target)); while (found_paths.size() < k) { List<E> curShortestPath = found_paths.getLast(); int maxIndex = curShortestPath.size(); List<V> curShortestPathNodes = new LinkedList<V>(); curShortestPathNodes.add(source); for (E e : found_paths.getLast()) { V v = graph.getEndpoints(e).getFirst(); if (!curShortestPathNodes.contains(v)) curShortestPathNodes.add(v); v = graph.getEndpoints(e).getSecond(); if (!curShortestPathNodes.contains(v)) curShortestPathNodes.add(v); }//from ww w . ja va 2 s .com curShortestPathNodes.remove(target); // Split path into Head and NextEdge for (int i = 0; i < maxIndex; i++) { List<E> head = curShortestPath.subList(0, i); // V deviation = head.isEmpty() ? source : graph.getEndpoints(head.get(i - 1)).getSecond(); V deviation = curShortestPathNodes.get(i); // 1. Block edges. Graph<V, E> blocked = blockFilter(head, deviation, curShortestPathNodes, found_paths); // 2. Get shortest path in graph with blocked edges. blockedDijkstra = new DijkstraShortestPath<V, E>(blocked, nev); Number dist = blockedDijkstra.getDistance(deviation, target); if (dist == null) continue; List<E> tail = blockedDijkstra.getPath(deviation, target); // 3. Combine head and tail into new path. List<E> candidate = new ArrayList<E>(); candidate.addAll(head); candidate.addAll(tail); // Check if we already found this solution boolean duplicate = false; for (WeightedPath path : prioQ) if (ListUtils.isEqualList(path.getPath(), candidate)) { duplicate = true; break; } if (!duplicate) prioQ.add(new WeightedPath(candidate)); } if (prioQ.isEmpty()) break; // We have not found any new candidate! else found_paths.add(prioQ.poll().getPath()); } return found_paths; }
From source file:org.openmrs.module.chartsearch.solr.ChartSearchSearcher.java
/** * Adds filter Queries to the query for selected categories returned from the UI * /*from w ww. java 2 s. c o m*/ * @param query * @param selectedCats */ public void addSelectedFilterQueriesToQuery(SolrQuery query, List<String> selectedCats) { String filterQuery = ""; LinkedList<String> selectedCategories = new LinkedList<String>(); selectedCategories.addAll(selectedCats); if (selectedCategories == null || selectedCategories.isEmpty()) { } else { LinkedList<CategoryFilter> existingCategories = new LinkedList<CategoryFilter>(); existingCategories.addAll(getChartSearchService().getAllCategoryFilters()); int indexOfFirstSelected = selectedCategories.indexOf(selectedCategories.getFirst()); int indexOfLastSelected = selectedCategories.indexOf(selectedCategories.getLast()); int indexOfFirstExisting = existingCategories.indexOf(existingCategories.getFirst()); int indexOfLastExisting = existingCategories.indexOf(existingCategories.getLast()); for (int i = indexOfFirstSelected; i <= indexOfLastSelected; i++) { String currentSelected = selectedCategories.get(i); for (int j = indexOfFirstExisting; j <= indexOfLastExisting; j++) { CategoryFilter currentExisting = existingCategories.get(j); String currentExistingName = currentExisting.getCategoryName(); if (currentSelected.equals(currentExistingName.toLowerCase())) { if (i != indexOfLastSelected) { filterQuery += currentExisting.getFilterQuery() + " OR "; } else filterQuery += currentExisting.getFilterQuery(); } } } query.addFilterQuery(filterQuery); } }
From source file:ch.icclab.cyclops.resource.impl.TelemetryResource.java
/** * In this method, usage made is calculated on per resource basis in the cumulative meters * * Pseudo Code/*from w ww . jav a 2 s . com*/ * 1. Traverse through the linkedlist * 2. Subtract the volumes of i and (i+1) samples * 3. Set the difference into the i sample object * 4. Add the updates sample object into an arraylist * * @param cMeterArr This is an arrayList of type CumulativeMeterData containing sample object with the usage information * @param linkedList This is a Linked List of type CumulativeMeterData containing elements from a particular resource * @return An arrayList of type CumulativeMeterData containing sample objects with the usage information */ private ArrayList<CumulativeMeterData> calculateCumulativeMeterUsage(ArrayList<CumulativeMeterData> cMeterArr, LinkedList<CumulativeMeterData> linkedList) { long diff; //BigInteger maxMeterValue ; for (int i = 0; i < (linkedList.size() - 1); i++) { if ((i + 1) <= linkedList.size()) { diff = linkedList.get(i).getVolume() - linkedList.get(i + 1).getVolume(); if (diff < 0) { linkedList.get(i).setUsage(0); //TODO: Update the negative difference usecase } else { linkedList.get(i).setUsage(diff); } cMeterArr.add(linkedList.get(i)); } } cMeterArr.add(linkedList.getLast()); return cMeterArr; }
From source file:org.kitodo.production.forms.dataeditor.StructurePanel.java
void deleteSelectedMediaUnit() { Optional<MediaUnit> selectedMediaUnit = getSelectedMediaUnit(); if (!selectedMediaUnit.isPresent()) { return;/*ww w.j a v a2 s. c om*/ } LinkedList<MediaUnit> ancestors = MetadataEditor.getAncestorsOfMediaUnit(selectedMediaUnit.get(), dataEditor.getWorkpiece().getMediaUnit()); if (ancestors.isEmpty()) { // The selected element is the root node of the tree. return; } MediaUnit parent = ancestors.getLast(); parent.getChildren().remove(selectedMediaUnit.get()); show(); }
From source file:org.kitodo.production.forms.dataeditor.StructurePanel.java
void deleteSelectedStructure() { Optional<IncludedStructuralElement> selectedStructure = getSelectedStructure(); if (!selectedStructure.isPresent()) { /*//ww w . ja v a 2 s . com * No element is selected or the selected element is not a structure * but, for example, a media unit. */ return; } LinkedList<IncludedStructuralElement> ancestors = MetadataEditor .getAncestorsOfStructure(selectedStructure.get(), structure); if (ancestors.isEmpty()) { // The selected element is the root node of the tree. return; } IncludedStructuralElement parent = ancestors.getLast(); parent.getChildren().remove(selectedStructure.get()); show(); }
From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java
/** * Determine the thread pool to be used for post processing based on some characteristics of the request * The plugins will yield a list of callables that could potentially be evaluated in parallel * Whether we evaluate in parallel is made here. * @param pvName//from w ww .java 2 s . c o m * @param postProcessor * @return */ private static RetrievalExecutorResult determineExecutorForPostProcessing(String pvName, PVTypeInfo typeInfo, LinkedList<TimeSpan> requestTimes, HttpServletRequest req, PostProcessor postProcessor) { long memoryConsumption = postProcessor.estimateMemoryConsumption(pvName, typeInfo, requestTimes.getFirst().getStartTime(), requestTimes.getLast().getEndTime(), req); double memoryConsumptionInMB = (double) memoryConsumption / (1024 * 1024); DecimalFormat twoSignificantDigits = new DecimalFormat("###,###,###,###,###,###.##"); logger.debug("Memory consumption estimate from postprocessor for pv " + pvName + " is " + memoryConsumption + "(bytes) ~= " + twoSignificantDigits.format(memoryConsumptionInMB) + "(MB)"); // For now, we only use the current thread to execute in serial. // Once we get the unit tests for the post processors in a more rigorous shape, we can start using the ForkJoinPool. // There are some complexities in using the ForkJoinPool - in this case, we need to convert to using synchronized versions of the SummaryStatistics and DescriptiveStatistics // We also still have the issue where we can add a sample twice because of the non-transactional nature of ETL. // However, there is a lot of work done by the PostProcessors in estimateMemoryConsumption so leave this call in place. return new RetrievalExecutorResult(new CurrentThreadExecutorService(), requestTimes); }
From source file:org.artifactory.storage.db.binstore.service.BinaryStoreImpl.java
private void setBinaryProvidersContext(LinkedList<BinaryProviderBase> binaryProviders) { if (!(binaryProviders.getFirst() instanceof UsageTrackingBinaryProvider)) { throw new IllegalStateException("The first binary provider should be read tracking!"); }//from w ww . j a v a 2 s .c o m // Make sure the last one is the empty binary provider if (!(binaryProviders.getLast() instanceof EmptyBinaryProvider)) { binaryProviders.add(new EmptyBinaryProvider()); } FileBinaryProvider foundFileBinaryProvider = null; BinaryProviderBase previous = null; for (BinaryProviderBase binaryProvider : binaryProviders) { if (previous != null) { // Set next to previous previous.setContext(new BinaryProviderContextImpl(this, binaryProvider)); } if (foundFileBinaryProvider == null && previous instanceof FileBinaryProvider) { foundFileBinaryProvider = (FileBinaryProvider) previous; } previous = binaryProvider; } fileBinaryProvider = foundFileBinaryProvider; firstBinaryProvider = (UsageTrackingBinaryProvider) binaryProviders.getFirst(); }
From source file:net.gaast.giggity.ScheduleViewActivity.java
public void finishNavDrawer() { if (sched == null) { Log.e("finishNavDrawer", "Called before critical was loaded?"); return;/*from www .j a v a 2s .com*/ } LinkedList<Date> days = sched.getDays(); TextView dr = (TextView) drawerLayout.findViewById(R.id.date_range); dr.setText(Giggity.dateRange(days.getFirst(), days.getLast())); if (sched.getLinks() != null) { ViewGroup menu = (LinearLayout) drawerLayout.findViewById(R.id.menu); View sep = menu.findViewById(R.id.custom_sep); sep.setVisibility(View.VISIBLE); for (final Schedule.Link link : sched.getLinks()) { TextView item = (TextView) getLayoutInflater().inflate(R.layout.burger_menu_item, null); item.setText(link.getTitle()); item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openLink(link, true); drawerLayout.closeDrawers(); } }); menu.addView(item, menu.indexOfChild(sep)); } } }
From source file:org.apache.axis2.deployment.util.Utils.java
/** * Normalize a uri containing ../ and ./ paths. * * @param uri The uri path to normalize/*w ww. j a v a 2s .co m*/ * @return The normalized uri */ public static String normalize(String uri) { if ("".equals(uri)) { return uri; } int leadingSlashes; for (leadingSlashes = 0; leadingSlashes < uri.length() && uri.charAt(leadingSlashes) == '/'; ++leadingSlashes) { // FIXME: this block is empty!! } boolean isDir = (uri.charAt(uri.length() - 1) == '/'); StringTokenizer st = new StringTokenizer(uri, "/"); LinkedList clean = new LinkedList(); while (st.hasMoreTokens()) { String token = st.nextToken(); if ("..".equals(token)) { if (!clean.isEmpty() && !"..".equals(clean.getLast())) { clean.removeLast(); if (!st.hasMoreTokens()) { isDir = true; } } else { clean.add(".."); } } else if (!".".equals(token) && !"".equals(token)) { clean.add(token); } } StringBuffer sb = new StringBuffer(); while (leadingSlashes-- > 0) { sb.append('/'); } for (Iterator it = clean.iterator(); it.hasNext();) { sb.append(it.next()); if (it.hasNext()) { sb.append('/'); } } if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } return sb.toString(); }
From source file:jext2.DataBlockAccess.java
/** Get up to maxBlocks BlockNrs for the logical fileBlockNr. I dont really like to change behavior * by specifing a flag variable but this is more or less like the linux implementation. Use getBlocks * or getBlocksAllocate./*from ww w. j a va2 s. co m*/ * @param inode Inode of the data block * @param fileBlockNr the logical block address * @param maxBlocks maximum blocks returned * @param create true: create blocks if nesseccary; false: just read * @return list of block nrs; if create=false null is returned if block does not exist * @throws NoSpaceLeftOnDevice * @throws FileTooLarge * @throws IOException */ @MustReturnLock private LinkedList<Long> getBlocks(long fileBlockNr, long maxBlocks, boolean create) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge { if (fileBlockNr < 0 || maxBlocks < 1) throw new IllegalArgumentException(); LinkedList<Long> result = new LinkedList<Long>(); int[] offsets; long[] blockNrs; int depth; int existDepth; hierarchyLock.readLock().lock(); offsets = blockToPath(fileBlockNr); depth = offsets.length; blockNrs = getBranch(offsets); existDepth = blockNrs.length; /* Simplest case - block found, no allocation needed */ if (depth == existDepth) { long firstBlockNr = blockNrs[depth - 1]; result.addFirst(firstBlockNr); long blocksToBoundary = 0; if (depth >= 2) /* indirect blocks */ blocksToBoundary = superblock.getAddressesPerBlock() - offsets[depth - 1] - 1; else /* direct blocks */ blocksToBoundary = Constants.EXT2_NDIR_BLOCKS - offsets[0] - 1; int count = 1; while (count < maxBlocks && count <= blocksToBoundary) { long nextByNumber = firstBlockNr + count; long nextOnDisk = -1; if (depth >= 2) /* indirect blocks */ nextOnDisk = blocks.readBlockNumberFromBlock(blockNrs[depth - 2], offsets[depth - 1] + count); else /* direct blocks */ nextOnDisk = inode.getBlock()[offsets[0] + count]; /* check if next neighbor block belongs to inode */ if (nextByNumber == nextOnDisk) { result.addLast(nextByNumber); count++; } else { break; } } assert hierarchyLock.getReadHoldCount() == 1 : "Returning without holding lock"; return result; } assert hierarchyLock.getReadHoldCount() == 1 : "Should have a read lock around"; /* Next simple case - plain lookup mode */ if (!create) { assert hierarchyLock.getReadHoldCount() == 1 : "Returning without holding lock"; return null; } hierarchyLock.readLock().unlock(); /* Okay, we need to do block allocation. */ hierarchyLock.writeLock().lock(); long goal = findGoal(fileBlockNr, blockNrs, offsets); int count = depth - existDepth; LinkedList<Long> newBlockNrs = allocBranch(count, goal, offsets, blockNrs); spliceBranch(fileBlockNr, offsets, blockNrs, newBlockNrs); result.add(newBlockNrs.getLast()); hierarchyLock.readLock().lock(); hierarchyLock.writeLock().unlock(); /* Again return with an open read lock */ assert hierarchyLock.getReadHoldCount() == 1 : "Returning without holding lock"; return result; }