Example usage for java.util ListIterator previousIndex

List of usage examples for java.util ListIterator previousIndex

Introduction

In this page you can find the example usage for java.util ListIterator previousIndex.

Prototype

int previousIndex();

Source Link

Document

Returns the index of the element that would be returned by a subsequent call to #previous .

Usage

From source file:com.collective.celos.ci.testing.fixtures.compare.FixTableComparer.java

private Map<String, FixObjectCompareResult> compareRespectOrder(FixTable expected, FixTable actual) {
    Map<String, FixObjectCompareResult> fails = Maps.newLinkedHashMap();
    ListIterator<FixTable.FixRow> expIter = expected.getRows().listIterator();
    ListIterator<FixTable.FixRow> actIter = actual.getRows().listIterator();
    while (expIter.hasNext()) {
        FixTable.FixRow expRow = expIter.next();
        FixTable.FixRow actRow = actIter.next();

        FixObjectCompareResult result = compareFixRows(expected.getColumnNames(), expRow, actRow);
        if (result.getStatus() == FixObjectCompareResult.Status.FAIL) {
            fails.put("Row #" + expIter.previousIndex(), result);
        }/*from   ww  w  . j a v a  2s .c  o m*/
    }
    return fails;
}

From source file:eu.scidipes.toolkits.pawebapp.web.ItemsController.java

public String editItemHelper(final List<Form> formSubset, final Form form, final Model model,
        final RedirectAttributes redirectAttrs) {
    final ListIterator<Form> formIterator = formSubset.listIterator();

    while (formIterator.hasNext()) {
        final Form theForm = formIterator.next();
        if (theForm.equals(form)) {
            /* Jump back: */
            formIterator.previous();/*from  w  w  w  .  ja v  a 2s. c  o  m*/
            if (formIterator.hasPrevious()) {
                model.addAttribute("previous",
                        Integer.valueOf(formSubset.get(formIterator.previousIndex()).getFormID().intValue()));
            }
            /* Jump forward: */
            formIterator.next();
            if (formIterator.hasNext()) {
                model.addAttribute("next",
                        Integer.valueOf(formSubset.get(formIterator.nextIndex()).getFormID().intValue()));
            }
        }
    }
    model.addAttribute("saveAction", EDIT);

    final CurationPersistentIdentifier manifestCPID = form.getManifestCPID();
    final Map<DatasetRIL, Set<CoreRIType>> rilMembership = new HashMap<>();

    /* Fetch the current RIL membership for this form instance: */
    for (final DatasetRIL dsRIL : form.getParentBundle().getRils()) {

        final RepresentationInformation[] repInfo = dsRIL.getRil().getRepresentationInformationChildren();

        for (final RepresentationInformation coreRI : repInfo) {

            if (coreRI.getRepresentationInformation() instanceof RepInfoGroup) {
                final RepInfoGroup repInfoGroup = (RepInfoGroup) coreRI.getRepresentationInformation();

                for (final RepresentationInformation ri : repInfoGroup.getRepresentationInformationChildren()) {

                    if (ri.getCpid().equals(manifestCPID)) {

                        if (!rilMembership.containsKey(dsRIL)) {
                            rilMembership.put(dsRIL, new HashSet<CoreRIType>());
                        }
                        rilMembership.get(dsRIL).add(CoreRIType.fromClass(coreRI.getClass()));
                    }

                }

            }
        }
    }
    model.addAttribute("rilMembership", rilMembership);

    model.addAttribute("form", form);
    return "datasets/items/edit";
}

From source file:edu.oregonstate.eecs.mcplan.sim.OptionSimulator.java

@Override
public void takeAction(final JointAction<Option<S, A>> j) {
    action_count_ += 1;/*from   w w  w  .  j av  a2 s  .c o  m*/
    //      System.out.println( "Setting option " + o + " for player " + turn_ );

    // Find all options that terminated
    final ArrayList<Option<S, A>> term = new ArrayList<Option<S, A>>();
    for (int i = 0; i < turn_.size(); ++i) {
        assert (active_.get(i) == null);
        term.add(terminated_.get(i));
        terminated_.set(i, null);
    }
    pushFrame(turn_, term);

    // Activate new options
    for (int i = 0; i < turn_.size(); ++i) {
        assert (j.get(i) != null);
        final Option<S, A> o = j.get(i);
        active_.set(i, o);
        o.start(base_.state(), base_.t());
    }

    assert (history_.size() == action_count_); // TODO: Debugging

    // Take actions according to active options until one or more
    // options terminates.
    final long told = base_.t();
    final long tnew = told;
    while (true) {
        final S s = base_.state();
        if (base_.isTerminalState()) {
            return;
        }

        // See if any options terminate
        final ListIterator<Option<S, A>> check_itr = active_.listIterator();
        final TIntArrayList next_turn = new TIntArrayList();
        while (check_itr.hasNext()) {
            final Option<S, A> ocheck = check_itr.next();
            if (terminate(s, base_.t(), ocheck)) {
                //               System.out.println( "! Option " + (check_itr.previousIndex()) + " terminated" );
                check_itr.set(null);
                final int pidx = check_itr.previousIndex();
                terminated_.set(pidx, ocheck);
                next_turn.add(pidx);
            }
        }

        // If they do, wait for new options
        if (!next_turn.isEmpty()) {
            turn_ = next_turn;
            return;
        }

        // Construct a JointAction over primitive actions and execute it
        final JointAction.Builder<A> ab = new JointAction.Builder<A>(Nplayers_);
        for (int i = 0; i < Nplayers_; ++i) {
            final Option<S, A> o = active_.get(i);
            assert (o != null);
            o.setState(s, base_.t());
            ab.a(i, o.getAction());
        }
        base_.takeAction(ab.finish());

        //         System.out.println( "Take action " + base_.getTurn() + " " + a );
        history_.peek().steps += 1;
        // TODO: Give pi its reward
        // pi.actionResult( ??? );
    }
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

public TropixObject getHomeDirectoryPath(final String userId, final List<String> pathParts) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("getPath called with userId %s and path parts %s", userId,
                Iterables.toString(pathParts)));
    }//from  w w w  . j a v  a2s. com
    final StringBuilder joins = new StringBuilder(), wheres = new StringBuilder();
    final ListIterator<String> pathPartsIter = pathParts.listIterator(pathParts.size());
    final LinkedList<String> parameters = Lists.newLinkedList();
    while (pathPartsIter.hasPrevious()) {
        int index = pathPartsIter.previousIndex() + 1;
        final String pathPart = pathPartsIter.previous();

        int nextObjectBackIndex = pathPartsIter.previousIndex() + 1;
        joins.append(String.format(" inner join o%d.permissionParents as o%d ", index, nextObjectBackIndex));
        wheres.append(String.format(" and o%d.deletedTime is null", index));
        wheres.append(String.format(" and o%d.committed is true", index));
        addConstraintForPathPart(pathPart, index, wheres, parameters);
    }

    final String queryString = String.format(
            "User u, TropixObject o%d %s where u.cagridId = :userId %s and u.homeFolder.id = o0.id",
            pathParts.size(), joins.toString(), wheres.toString());
    return executePathQuery(userId, String.format("o%d", pathParts.size()), queryString, 1, parameters);
}

From source file:edu.umn.msi.tropix.persistence.dao.hibernate.TropixObjectDaoImpl.java

public TropixObject getGroupDirectoryPath(final String userId, final List<String> pathParts) {
    final StringBuilder joins = new StringBuilder(), wheres = new StringBuilder();
    final ListIterator<String> pathPartsIter = pathParts.listIterator(pathParts.size());
    final LinkedList<String> parameters = Lists.newLinkedList();
    while (pathPartsIter.hasPrevious()) {
        int index = pathPartsIter.previousIndex();
        final String pathPart = pathPartsIter.previous();
        wheres.append(String.format(" and o%d.deletedTime is null", index));
        wheres.append(String.format(" and o%d.committed is true", index));
        addConstraintForPathPart(pathPart, index, wheres, parameters);
        if (pathPartsIter.hasPrevious()) {
            int nextObjectBackIndex = pathPartsIter.previousIndex();
            joins.append(/*w w  w .  ja  va  2s . c o m*/
                    String.format(" inner join o%d.permissionParents as o%d ", index, nextObjectBackIndex));
        }
    }

    final int lastIndex = pathParts.size() - 1;
    final String objectType = lastIndex == 0 ? "Folder" : "TropixObject";
    final String queryString = String.format(
            "%s o%d %s inner join o0.permissions p left join p.users u left join p.groups g left join g.users gu where (u.cagridId = :userId or gu.cagridId = :userId) and o0.parentFolder is null %s and o0.class is Folder",
            objectType, lastIndex, joins.toString(), wheres.toString());
    return executePathQuery(userId, String.format("o%d", lastIndex), queryString, 0, parameters);
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Searches the finger table for the right-most occurrence of {@code ptr}.
 * @param ptr pointer to search for/* w  w  w .  j  a  v  a  2s  .c  o  m*/
 * @return index of occurrence, or -1 if not found
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code ptr}'s id has a different limit bit size than the base pointer's id
 */
public int getMaximumIndex(Pointer ptr) {
    Validate.notNull(ptr);
    Validate.isTrue(IdUtils.getBitLength(ptr.getId()) == bitCount);

    Id id = ptr.getId();
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();

        if (ie.pointer.equals(ptr)) {
            return lit.previousIndex() + 1;
        }
    }

    return -1;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Removes all fingers before {@code id} (does not remove {@code id} itself).
 *
 * @param id id of which all fingers before it will be removed
 * @return number of fingers that were cleared
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id} has a different limit bit size than base pointer's id, or if {@code id} is equivalent
 * to base pointer's id/*from   w w  w  .  j  a  va 2  s  .c  om*/
 */
public int clearBefore(Id id) {
    Validate.notNull(id);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    Id baseId = basePtr.getId();

    if (id.equals(baseId)) {
        throw new IllegalArgumentException();
    }

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        Id testId = ie.pointer.getId();

        if (Id.comparePosition(baseId, id, testId) > 0) {
            int position = lit.previousIndex() + 1;
            clearBefore(position);
            return position;
        }
    }

    return 0;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Removes a pointer in to the finger table. If the pointer doesn't exist in the finger table, does nothing. See the
 * constraints/guarantees mentioned in the class Javadoc: {@link FingerTable}.
 * @param ptr pointer to put in as finger
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code ptr}'s id has a different limit bit size than the base pointer's id, or if {@code ptr} has
 * an id that matches the base pointer's id
 *//*from   w ww . j a  va  2  s .c  o  m*/
public void remove(ExternalPointer<A> ptr) {
    Validate.notNull(ptr);
    Validate.isTrue(IdUtils.getBitLength(ptr.getId()) == bitCount);

    Id id = ptr.getId();
    A address = ptr.getAddress();
    Id baseId = basePtr.getId();

    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);
    Validate.isTrue(!id.equals(baseId));

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();

        if (ie.pointer instanceof InternalPointer) { // don't bother inspecting internal pointers since we can only remove
                                                     // external pointers
            continue;
        }

        ExternalPointer<A> testPtr = (ExternalPointer<A>) ie.pointer;
        Id testId = testPtr.getId();
        A testAddress = testPtr.getAddress();

        if (id.equals(testId) && address.equals(testAddress)) {
            remove(lit.previousIndex() + 1);
            break;
        }
    }
}

From source file:marytts.modules.phonemiser.AllophoneSet.java

/**
 * Syllabify a string of allophones. If stress markers are provided, they are preserved; otherwise, primary stress will be
 * assigned to the initial syllable./*from  w w  w. j av a  2s  .  c o  m*/
 * <p>
 * The syllabification algorithm itself follows the <i>Core Syllabification Principle (CSP)</i> from <blockquote>G.N. Clements
 * (1990) "The role of the sonority cycle in core syllabification." In: J. Kingston &amp; M.E. Beckman (Eds.),
 * <em>Papers in Laboratory Phonology I: Between the Grammar and Physics of Speech</em>, Ch. 17, pp. 283-333, Cambridge
 * University Press.</blockquote>
 *
 * @param phoneString
 *            phoneString
 * @return a syllabified string; individual allophones are separated by spaces, and syllables, by dashes.
 * @throws IllegalArgumentException
 *             if the <b>phoneString</b> is empty or contains a symbol that satisfies none of the following conditions:
 *             <ol>
 *             <li>the symbol corresponds to an Allophone, or</li> <li>the symbol is a stress symbol (cf. {@link Stress}), or
 *             </li> <li>the symbol is a syllable boundary (<code>-</code>)</li>
 *             </ol>
 * 
 */
public String syllabify(String phoneString) throws IllegalArgumentException {
    // Before we process, a sanity check:
    if (phoneString.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot syllabify empty phone string");
    }

    // First, split phoneString into a List of allophone Strings...
    List<String> allophoneStrings = splitIntoAllophoneList(phoneString, true);
    // ...and create from it a List of generic Objects
    List<Object> phonesAndSyllables = new ArrayList<Object>(allophoneStrings);

    // Create an iterator
    ListIterator<Object> iterator = phonesAndSyllables.listIterator();

    // First iteration (left-to-right):
    // CSP (a): Associate each [+syllabic] segment to a syllable node.
    Syllable currentSyllable = null;
    while (iterator.hasNext()) {
        String phone = (String) iterator.next();
        try {
            // either it's an Allophone
            Allophone allophone = getAllophone(phone);
            if (allophone.isSyllabic()) {
                // if /6/ immediately follows a non-diphthong vowel, it should be appended instead of forming its own syllable
                boolean appendR = false;
                if (allophone.getFeature("ctype").equals("r")) {
                    // it's an /6/
                    if (iterator.previousIndex() > 1) {
                        Object previousPhoneOrSyllable = phonesAndSyllables.get(iterator.previousIndex() - 1);
                        if (previousPhoneOrSyllable == currentSyllable) {
                            // the /6/ immediately follows the current syllable
                            if (!currentSyllable.getLastAllophone().isDiphthong()) {
                                // the vowel immediately preceding the /6/ is not a diphthong
                                appendR = true;
                            }
                        }
                    }
                }
                if (appendR) {
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                } else {
                    currentSyllable = new Syllable(allophone);
                    iterator.set(currentSyllable);
                }
            }
        } catch (IllegalArgumentException e) {
            // or a stress or boundary marker
            if (!getIgnoreChars().contains(phone)) {
                throw e;
            }
        }
    }

    // Second iteration (right-to-left):
    // CSP (b): Given P (an unsyllabified segment) preceding Q (a syllabified segment), adjoin P to the syllable containing Q
    // iff P has lower sonority rank than Q (iterative).
    currentSyllable = null;
    boolean foundPrimaryStress = false;
    iterator = phonesAndSyllables.listIterator(phonesAndSyllables.size());
    while (iterator.hasPrevious()) {
        Object phoneOrSyllable = iterator.previous();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else if (currentSyllable == null) {
            // haven't seen a Syllable yet in this iteration
            continue;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- prepend to the Syllable
                Allophone allophone = getAllophone(phone);
                if (allophone.sonority() < currentSyllable.getFirstAllophone().sonority()) {
                    iterator.remove();
                    currentSyllable.prependAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                // it's a provided stress marker -- assign it to the Syllable
                switch (phone) {
                case Stress.PRIMARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.PRIMARY);
                    foundPrimaryStress = true;
                    break;
                case Stress.SECONDARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.SECONDARY);
                    break;
                case "-":
                    iterator.remove();
                    // TODO handle syllable boundaries
                    break;
                default:
                    throw e;
                }
            }
        }
    }

    // Third iteration (left-to-right):
    // CSP (c): Given Q (a syllabified segment) followed by R (an unsyllabified segment), adjoin R to the syllable containing
    // Q iff has a lower sonority rank than Q (iterative).
    Syllable initialSyllable = currentSyllable;
    currentSyllable = null;
    iterator = phonesAndSyllables.listIterator();
    while (iterator.hasNext()) {
        Object phoneOrSyllable = iterator.next();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- append to the Syllable
                Allophone allophone;
                try {
                    allophone = getAllophone(phone);
                } catch (IllegalArgumentException e) {
                    // or a stress or boundary marker -- remove
                    if (getIgnoreChars().contains(phone)) {
                        iterator.remove();
                        continue;
                    } else {
                        throw e;
                    }
                }
                if (currentSyllable == null) {
                    // haven't seen a Syllable yet in this iteration
                    iterator.remove();
                    if (initialSyllable == null) {
                        // haven't seen any syllable at all
                        initialSyllable = new Syllable(allophone);
                        iterator.add(initialSyllable);
                    } else {
                        initialSyllable.prependAllophone(allophone);
                    }
                } else {
                    // append it to the last seen Syllable
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

    // if primary stress was not provided, assign it to initial syllable
    if (!foundPrimaryStress) {
        initialSyllable.setStress(Stress.PRIMARY);
    }

    // join Syllables with dashes and return the String
    return StringUtils.join(phonesAndSyllables, " - ");
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/**********************************************
 * /*  www .jav  a2s. c om*/
 * insertListInListByDate
 * @param singleArtistEventList
 * 
 **********************************************/
public void insertListInListByDate(LinkedList<ArtistEvent> singleArtistEventList) {
    /*
     * If this artist List is empty just return
     */
    if (singleArtistEventList.isEmpty())
        return;

    /*
     * If the big list is empty just add this one to it
     */
    if (artistEventList.isEmpty()) {
        artistEventList.addAll(singleArtistEventList);
        return;
    }

    /*
     * Insert the items (normal case)
     */
    ListIterator<ArtistEvent> artistEventListIterator = artistEventList.listIterator(0);
    ListIterator<ArtistEvent> singleArtistEventListIterator = singleArtistEventList.listIterator(0);
    ArtistEvent artistEvent;
    ArtistEvent singleArtistEvent;
    while (singleArtistEventListIterator.hasNext()) {
        /*
         * Not yet at the end of the big list
         */
        if (artistEventListIterator.hasNext()) {
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEvent = artistEventListIterator.next();
            while (singleArtistEvent.dateInMillis > artistEvent.dateInMillis) {
                if (artistEventListIterator.hasNext())
                    artistEvent = artistEventListIterator.next();
                else {
                    if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE) {
                        return;
                    } else {
                        break; // TODO: add missing items to the big list
                    }
                }
            }
            artistEventListIterator.previous();
            artistEventListIterator.add(singleArtistEvent);
        }
        /*
         * At the end of the big list (but not of the 'small' list
         */
        else {
            if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE)
                return;
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEventListIterator.add(singleArtistEvent);
            artistEventListIterator.next();
        }
    }

    /*
     * Keep the list size in check
     */
    while (artistEventList.size() > MAX_EVENT_LIST_SIZE)
        artistEventList.removeLast();
}