List of usage examples for java.util Collections reverse
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void reverse(List<?> list)
This method runs in linear time.
From source file:com.threewks.thundr.module.Modules.java
public void runStopLifecycle(InjectionContext injectionContext) { List<Module> reverseOrder = new LinkedList<Module>(orderedModules); Collections.reverse(reverseOrder); for (Module injectionConfiguration : reverseOrder) { injectionConfiguration.stop(injectionContext); status.put(injectionConfiguration, ModuleStatus.Stopped); }//from w ww.j a va 2 s .c o m }
From source file:com.autsia.bracer.BracerParser.java
/** * Parses the math expression (complicated formula) and stores the result * * @param expression <code>String</code> input expression (math formula) * @throws <code>ParseException</code> if the input expression is not * correct * @since 3.0//from ww w . j ava2 s . co m */ public void parse(String expression) throws ParseException { /* cleaning stacks */ stackOperations.clear(); stackRPN.clear(); /* * make some preparations: remove spaces; handle unary + and -, handle * degree character */ expression = expression.replace(" ", "").replace("", "*" + Double.toString(Math.PI) + "/180") .replace("(-", "(0-").replace(",-", ",0-").replace("(+", "(0+").replace(",+", ",0+") .replace("true", "1").replace("false", "0").replace("or", "|").replace("and", "&"); if (expression.charAt(0) == '-' || expression.charAt(0) == '+') { expression = "0" + expression; } /* splitting input string into tokens */ StringTokenizer stringTokenizer = new StringTokenizer(expression, OPERATORS + SEPARATOR + "()", true); /* loop for handling each token - shunting-yard algorithm */ while (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); if (isSeparator(token)) { while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } } else if (isOpenBracket(token)) { stackOperations.push(token); } else if (isCloseBracket(token)) { while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } stackOperations.pop(); if (!stackOperations.empty() && isFunction(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } } else if (isNumber(token)) { if (token.equals(IMAGINARY)) { stackRPN.push(complexFormat.format(new Complex(0, 1))); } else if (token.contains(IMAGINARY)) { stackRPN.push(complexFormat.format(complexFormat.parse("0+" + token))); } else { stackRPN.push(token); } } else if (isOperator(token)) { while (!stackOperations.empty() && isOperator(stackOperations.lastElement()) && getPrecedence(token) <= getPrecedence(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } stackOperations.push(token); } else if (isFunction(token)) { stackOperations.push(token); } else { throw new ParseException("Unrecognized token: " + token, 0); } } while (!stackOperations.empty()) { stackRPN.push(stackOperations.pop()); } /* reverse stack */ Collections.reverse(stackRPN); }
From source file:org.kuali.maven.plugins.graph.tree.TreeHelper.java
/** * <p>/*from w ww . j av a 2 s .c om*/ * Display every node in the path from this node back to the root. * </p> */ public void showPath(Node<MavenContext> node) { Node<MavenContext>[] path = node.getPath(); List<Node<MavenContext>> pathList = Arrays.asList(path); Collections.reverse(pathList); for (Node<MavenContext> pathNode : pathList) { show(pathNode); } }
From source file:IntegerMap.java
/** * Returns an iterator on the keys, sorted by values descending. * /*from www .ja va 2s. c om*/ * @return an iterator on the keys */ public Iterator iteratorSortedByValueReverse() { final List keys = new ArrayList(map.keySet()); Collections.sort(keys, comparator); Collections.reverse(keys); return keys.iterator(); }
From source file:com.mothsoft.alexis.engine.retrieval.TwitterRetrievalTaskImpl.java
private void handleSourceImpl(final TwitterSource twitterSource) { final SocialConnection socialConnection = twitterSource.getSocialConnection(); final AccessToken accessToken = new AccessToken(socialConnection.getOauthToken(), socialConnection.getOauthTokenSecret()); final List<Status> statuses = this.twitterService.getHomeTimeline(accessToken, twitterSource.getLastTweetId(), (short) 800); if (statuses != null && statuses.size() > 0) { logger.info("Twitter retrieval found " + statuses.size() + " Tweets for user: " + socialConnection.getRemoteUsername()); // the newest tweet in the timeline will be our starting point for // the next fetch twitterSource.setLastTweetId(statuses.get(0).getId()); // import these in reverse order to ensure newest ones have the // highest document IDs Collections.reverse(statuses); final Long userId = twitterSource.getUserId(); final User user = this.userDao.get(userId); for (final Status status : statuses) { final Long tweetId = status.getId(); Tweet tweet = this.tweetDao.getTweetByRemoteTweetId(tweetId); final boolean isAdd = (tweet == null); if (isAdd) { // TODO - is this right? // Twitter allows 2 different styles of retweets. The // ones that are actually retweets show as tweeted by the // original user. Others may show // "RT @original thing original said" tweeted // by the new person final boolean retweet = status.isRetweet(); final twitter4j.User tweeter; final String text; twitter4j.User retweeter = null; final List<TweetLink> links; final List<TweetMention> mentions; final List<TweetHashtag> hashtags; if (retweet) { tweeter = status.getRetweetedStatus().getUser(); text = status.getRetweetedStatus().getText(); retweeter = status.getUser(); links = readLinks(status.getRetweetedStatus()); mentions = readMentions(status.getRetweetedStatus()); hashtags = readHashtags(status.getRetweetedStatus()); } else { tweeter = status.getUser(); text = status.getText(); links = readLinks(status); mentions = readMentions(status); hashtags = readHashtags(status); }/* w w w . java 2 s .c om*/ final URL profileImageUrl = tweeter.getProfileImageUrlHttps(); final Date createdAt = status.getCreatedAt(); tweet = new Tweet(tweetId, createdAt, tweeter.getScreenName(), tweeter.getName(), profileImageUrl, text, links, mentions, hashtags, retweet, retweet ? retweeter.getScreenName() : null); this.documentDao.add(tweet); } final DocumentUser documentUser = new DocumentUser(tweet, user); if (isAdd || !tweet.getDocumentUsers().contains(documentUser)) { tweet.getDocumentUsers().add(new DocumentUser(tweet, user)); this.documentDao.update(tweet); } } } else { logger.info("Twitter retrieval found no Tweets for user: " + socialConnection.getRemoteUsername()); } twitterSource.setRetrievalDate(new Date()); this.sourceDao.update(twitterSource); }
From source file:com.nextep.designer.synch.services.impl.ReverseSynchronizationService.java
@Override public void reverseSynchronize(IReverseSynchronizationContext context, IProgressMonitor monitor) { monitor.beginTask(SynchMessages.getString("synch.reverse.mainTask"), //$NON-NLS-1$ 5 + context.getItemsToSynchronize().size()); progress(monitor, SynchMessages.getString("synch.reverse.computeDependencies"), 1); //$NON-NLS-1$ // Sorting the elements to import by their dependencies final List<IVersionable<?>> sortedVersionables = VersionableSorter.sort(context.getVersionablesToImport()); progress(monitor, SynchMessages.getString("synch.reverse.computeRemovals"), 1); //$NON-NLS-1$ // Adding reverse sorted deletions List<IVersionable<?>> versionablesToRemove = VersionableSorter.sort(context.getVersionablesToRemove()); progress(monitor, SynchMessages.getString("synch.reverse.computeRemovalDependencies"), 1); //$NON-NLS-1$ Collections.reverse(versionablesToRemove); sortedVersionables.addAll(versionablesToRemove); progress(monitor, SynchMessages.getString("synch.reverse.processing"), 1); //$NON-NLS-1$ // Iterating over elements to import and delegate to the appropriate method final Map<IVersionable<?>, IComparisonItem> versionableItemsMap = context.getVersionableItemsMap(); final IWorkspace currentView = VCSPlugin.getViewService().getCurrentWorkspace(); for (final IVersionable<?> v : sortedVersionables) { final IComparisonItem item = versionableItemsMap.get(v); if (monitor.isCanceled()) { return; }//from ww w .j a v a 2 s .c o m /* * Each call to a method that modifies the current view or one of its objects has been * encapsulated with a try/catch block so that no unexpected runtime exception * interrupts the reverse synchronization process. */ switch (item.getDifferenceType()) { case MISSING_TARGET: monitor.subTask( MessageFormat.format(SynchMessages.getString("synch.reverse.addElement"), v.getType() //$NON-NLS-1$ .getName().toLowerCase(), v.getName(), currentView.getName())); try { addToView(currentView, getNewElementsTargetModule(), v, context); } catch (RuntimeException rte) { LOGGER.error(MessageFormat.format(SynchMessages.getString("synch.reverse.addElementError"), v //$NON-NLS-1$ .getType().getName().toLowerCase(), v.getName(), currentView.getName()) + rte.getMessage(), rte); } break; case DIFFER: monitor.subTask( MessageFormat.format(SynchMessages.getString("synch.reverse.updateElement"), v.getType() //$NON-NLS-1$ .getName().toLowerCase(), v.getName(), currentView.getName())); try { updateIntoView(currentView, item, context); } catch (RuntimeException rte) { LOGGER.error(MessageFormat.format(SynchMessages.getString("synch.reverse.updateElementError"), v //$NON-NLS-1$ .getType().getName().toLowerCase(), v.getName(), currentView.getName()) + rte.getMessage(), rte); } break; case MISSING_SOURCE: monitor.subTask(MessageFormat.format(SynchMessages.getString("synch.reverse.removeElement"), v //$NON-NLS-1$ .getType().getName().toLowerCase(), v.getName(), currentView.getName())); try { removeFromView(v, context); } catch (RuntimeException rte) { LOGGER.error(MessageFormat.format(SynchMessages.getString("synch.reverse.removeElementError"), v //$NON-NLS-1$ .getType().getName().toLowerCase(), v.getName(), currentView.getName()) + rte.getMessage(), rte); } break; } monitor.worked(1); } context.getImportPolicy().finalizeImport(); // Explicitly saving import container as some use case may not save it if (getNewElementsTargetModule() != null) { CorePlugin.getIdentifiableDao().save(getNewElementsTargetModule()); // Linking everything VersionHelper.relink(getNewElementsTargetModule()); } // We explicitly require a marker full recomputation (DES-904) CorePlugin.getService(IMarkerService.class).computeAllMarkers(); monitor.done(); }
From source file:de.alpharogroup.lang.ObjectExtensionsTest.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test(enabled = false)/*from w w w . ja va 2 s.c o m*/ public void testCompareTo() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { final List<Person> persons = new ArrayList<>(); final Person obelix = new Person(); obelix.setGender(Gender.MALE); obelix.setName("obelix"); final Person asterix = new Person(); asterix.setGender(Gender.MALE); asterix.setName("asterix"); final Person miraculix = new Person(); miraculix.setGender(Gender.MALE); miraculix.setName("miraculix"); final int i = ObjectExtensions.compareTo(asterix, obelix, "name"); System.out.println(i); persons.add(obelix); persons.add(asterix); persons.add(miraculix); System.out.println("Unsorted Persons:"); System.out.println(persons.toString()); final Comparator defaultComparator = new BeanComparator("name"); Collections.sort(persons, defaultComparator); System.out.println("Sorted Persons by name:"); System.out.println(persons.toString()); Collections.reverse(persons); System.out.println("Sorted Persons by name reversed:"); System.out.println(persons.toString()); }
From source file:com.pactera.edg.am.metamanager.extractor.adapter.mapping.impl.CommonMappingServiceImpl.java
/** * ?//from w ww .ja v a 2 s. c o m * * @param elements * @param parentMetadata * @param parentMetaModel * @return */ private Set<MMMetaModel> genRootMetaModels(List<Element> elements, MMMetadata parentMetadata, MMMetaModel parentMetaModel) { Set<MMMetaModel> metaModels = new HashSet<MMMetaModel>(2); // list???,???,??? Collections.reverse(elements); /** * ??,?? */ Set<String> duplicateElement = new HashSet<String>(); for (Element element : elements) { String modelId = element.attributeValue("class"); String code = element.selectSingleNode("./attributes/instancecode").getText(); if (code == null || code.equals("")) { log.warn(new StringBuilder("Code!").append(",:").append(modelId).toString()); continue; } String duplicateString = new StringBuilder().append(code).append("_").append(modelId).toString(); if (duplicateElement.contains(duplicateString)) { // ?,?CODE?,?? log.warn(new StringBuilder("??Element:").append(code).append(",:").append(modelId) .toString()); continue; } duplicateElement.add(duplicateString); MMMetadata relativeMetadata = parentMetadata; MMMetaModel relativeModel = parentMetaModel; // ?Excel? Node pathNode = element.selectSingleNode("./path"); if (pathNode != null) { relativeMetadata = genRelativeMetadata(parentMetadata, pathNode.getText()); if (relativeMetadata == null) { continue; } relativeModel = new MMMetaModel(); relativeModel.setCode(relativeMetadata.getClassifierId()); } MMMetaModel cntMetaModel = getMetaModel(relativeModel, metaModels, element); MMMetadata metadata = genMetadata(relativeMetadata, cntMetaModel, element); // cntMetaModel.addMetadata(metadata); // cntMetaModel.setHasMetadata(true); List<Element> childElements = element.selectNodes("./instances/instance"); if (childElements != null && childElements.size() > 0) { genMetaModels(childElements, metadata, cntMetaModel); // cntMetaModel.setHasChildMetaModel(true); } } return metaModels; }
From source file:de.tudarmstadt.ukp.csniper.webapp.search.xmi.XmiContextProvider.java
@Override public ItemContext getContext(EvaluationItem aItem, int aLeftSize, int aRightSize) throws IOException { Timer timer = new Timer(); File base = new File(new File(corpusService.getRepositoryPath(), aItem.getCollectionId().toUpperCase()), XMI);/* w ww . ja va2 s . c om*/ String docId = aItem.getDocumentId(); JCasState state = jcasThreadLocal.get(); // FIXME sometimes cas is not being reused (because of state.documentId==null - is this only // available for a limited timed?) if ((state.documentId == null) || (state.collectionId == null) || !StringUtils.equals(state.documentId, docId) || !StringUtils.equals(state.collectionId, aItem.getCollectionId())) { timer.start(); InputStream is = null; try { // No need to reset the CAS - the XmiCasDeserializer does that is = new GZIPInputStream(new FileInputStream(new File(base, docId + ".xmi.gz"))); XmiCasDeserializer.deserialize(is, state.jcas.getCas()); state.documentId = aItem.getDocumentId(); state.collectionId = aItem.getCollectionId(); } catch (IllegalStateException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } finally { closeQuietly(is); } timer.stop(); log.debug("Reading the XMI took " + timer.getTime() + "ms"); } else { log.debug("Reusing CAS"); } timer.reset(); timer.start(); // text offset based String text = state.jcas.getDocumentText(); // Absolute offsets int windowBegin = Math.max(0, (int) aItem.getBeginOffset() - aLeftSize); int windowEnd = Math.min(text.length(), (int) aItem.getEndOffset() + aRightSize); // Relative offsets int unitBegin = (int) aItem.getBeginOffset() - windowBegin; int unitEnd = (int) aItem.getEndOffset() - windowBegin; StringBuilder windowText = new StringBuilder(text.substring(windowBegin, windowEnd)); List<Token> tokens = JCasUtil.selectCovered(state.jcas, Token.class, (int) aItem.getBeginOffset(), (int) aItem.getEndOffset()); int unitEndDisplacement = 0; int matchEndDisplacement = 0; int matchBeginDisplacement = 0; boolean anyMatchSet = false; int matchBeginOffset = aItem.getOriginalTextMatchBegin(); int matchEndOffset = aItem.getOriginalTextMatchEnd(); if (aItem.isOriginalMatchSet()) { matchBeginOffset = aItem.getOriginalTextMatchBegin(); matchEndOffset = aItem.getOriginalTextMatchEnd(); anyMatchSet = true; } else if (aItem.isTokenMatchSet()) { matchBeginOffset = tokens.get(aItem.getTokenMatchBegin()).getBegin(); matchEndOffset = tokens.get(aItem.getTokenMatchEnd()).getEnd(); anyMatchSet = true; } Collections.reverse(tokens); // default: output pos with tokens if (outputPos) { for (Token t : tokens) { if (t.getPos() != null && t.getPos().getPosValue() != null) { String postfix = "/" + t.getPos().getPosValue(); windowText.insert(t.getEnd() - windowBegin, postfix); unitEndDisplacement += postfix.length(); if (anyMatchSet) { if ((t.getEnd() <= matchEndOffset) && (t.getBegin() >= matchBeginOffset)) { matchEndDisplacement += postfix.length(); } if (t.getEnd() <= matchBeginOffset) { matchBeginDisplacement += postfix.length(); } } } } } ItemContext ctx = new ItemContext(windowText.toString(), windowBegin, windowEnd, unitBegin, unitEnd + unitEndDisplacement); if (anyMatchSet) { ctx.setMatch(matchBeginOffset - windowBegin + matchBeginDisplacement, matchEndOffset - windowBegin + matchBeginDisplacement + matchEndDisplacement); } ctx.setTextLength(text.length()); timer.stop(); log.debug("Extracting the context took " + timer.getTime() + "ms"); return ctx; }
From source file:com.charts.ThreeMonthChart.java
protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException { ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>(); DateFormat df;// w ww.j av a 2 s . c om if (currentStock instanceof Index) df = new SimpleDateFormat("y-MM-dd"); else df = new SimpleDateFormat("d-MM-yy"); String threeMonthDate = df.format(DayRange.three_month); ArrayList<String> historicalData = currentStock.get_historical_data(); int length = historicalData.size(); for (int i = 1; i < length; i++) { String[] data = historicalData.get(i).split(","); Date date = df.parse(data[0]); double open = Double.parseDouble(data[1]); double high = Double.parseDouble(data[2]); double low = Double.parseDouble(data[3]); double close = Double.parseDouble(data[4]); this.close.add(new Day(date), close); double volume; try { volume = Double.parseDouble(data[5]); } catch (NumberFormatException nfe) { volume = 0; } if (data[0].equals(threeMonthDate)) { break; } OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume); dataItems.add(item); } Collections.reverse(dataItems); OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]); return OHLCData; }