Java Code Examples for java.util.SortedSet#first()

The following examples show how to use java.util.SortedSet#first() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Creates a new instance of Tuplet event
 *
 * @param measure measure that contains this tuplet
 * @param point   location of tuplet sign
 * @param chords  the embraced chords
 * @param glyph   the underlying glyph
 */
private Tuplet (Measure measure,
                Point point,
                SortedSet<Chord> chords,
                Glyph glyph)
{
    super(measure, point, chords.first(), glyph);

    this.chords = chords;

    // Apply the tuplet factor to each chord embraced
    DurationFactor factor = getFactor(glyph);

    for (Chord chord : chords) {
        chord.setTupletFactor(factor);
    }

    // Link last embraced chord to this tuplet instance
    chords.last().addNotation(this);
}
 
Example 2
/**
 * Utility method for finding the median in a sorted set.
 * 
 * @return the median value in the set or null if set is empty
 */
public static <T> T findMedian(SortedSet<T> s) {
    if (s == null)
        return null;
    if (s.isEmpty())
        return null;
    
    int med = s.size() / 2;
    if (med == 0) {
        return s.first();
    }
    Iterator<T> itr = s.iterator();
    T t = null;
    int i = 0;
    while (itr.hasNext() && i < med) {
        t = itr.next();
        ++i;
    }
    return t;
}
 
Example 3
public double map(float x) {
    Sample t = new Sample(x, 0);
    SortedSet<Sample> aset = samples.headSet(t);
    SortedSet<Sample> bset = samples.tailSet(t);
    if (aset.isEmpty()) {
        return bset.first().y;
    } else {
        if (bset.isEmpty()) {
            return aset.last().y;
        } else {
            Sample a = aset.last();
            Sample b = bset.first();
            return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x);
        }
    }
}
 
Example 4
protected <T,U,V,I extends Path<T> & Indexer<List<Integer>,List<N>,? extends Path<U>>,L> V _startAgenda(boolean isLabeled, Pair<Map<I,V>, SortedSet<I>> chartAndAgenda, List<N> sortedNodes, 
			Semirings.Semiring<V> semr, int order, Path<U> relevantPath, Subroutine edgeOperation) {
		Map<I,V> chart = chartAndAgenda.getFirst();
		SortedSet<I> agenda = chartAndAgenda.getSecond();
		
		while (!agenda.isEmpty()) {
			I nextItem = agenda.first();
			agenda.remove(nextItem);	// pop
			if (_logger!=null)
				_logger.popped(nextItem, agenda.size());
			for (I item : arrive(isLabeled, sortedNodes, chart, semr, nextItem, relevantPath, edgeOperation)) {
				if (!agenda.contains(item)) {
					agenda.add(item);	// arrive at node jj[-1] given history jj[:-1]
				}
			}
			if (relevantPath!=null)
				relevantPath = relevantPath.getTail();
		}
		
//if (_logger!=null && relevantNodes==null)
//		_logger.close();
		
		if (semr!=null)	// sum of all histories going into the last node
			return arrivalsTo(sortedNodes, chart, semr, sortedNodes.size()-1, order);
		return null;
	}
 
Example 5
Source Project: mtas   File: MtasPosition.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new mtas position.
 *
 * @param positions the positions
 */
public MtasPosition(int[] positions) {
  SortedSet<Integer> list = new TreeSet<>();
  for (int p : positions) {
    list.add(p);
  }
  if (list.size() == 1) {
    mtasPositionType = POSITION_SINGLE;
    mtasPositionStart = list.first();
  } else {
    mtasPositionType = POSITION_SET;
    mtasPositionList = ArrayUtils
        .toPrimitive(list.toArray(new Integer[list.size()]));
    mtasPositionStart = list.first();
    mtasPositionEnd = list.last();
    if (mtasPositionList.length == (1 + mtasPositionEnd
        - mtasPositionStart)) {
      mtasPositionType = POSITION_RANGE;
      mtasPositionList = null;
    }
  }
}
 
Example 6
Source Project: proparse   File: Schema.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Lookup Database by name.
 * Called twice by lookupDatabase().
 */
private Database lookupDatabase2(String inName) {
	SortedSet dbTailSet = dbSet.tailSet(new Database(inName));
	if (dbTailSet.size() == 0)
		return null;
	Database db = (Database)(dbTailSet.first());
	if ( db == null || db.getName().compareToIgnoreCase(inName) != 0 )
		return null;
	return db;
}
 
Example 7
@Override
public E first() {
    SortedSet<E> firstSet = new TreeSet<>(comparator());
    for (SortedSet<E> set : sets) {
        E s = set.first();
        if (s != null) {
            firstSet.add(s);
        }
    }
    return firstSet.first();
}
 
Example 8
Source Project: regulators   File: FeedbackRegulator.java    License: Apache License 2.0 5 votes vote down vote up
private List<Stop> reorderStops(final List<Stop> STOPS) {
    /*
    0.0 -> 0.611
    0.5 -> 0.0 & 1.0
    1.0 -> 0.389
     */
    double range     = 0.778;
    double halfRange = range * 0.5;

    Map<Double, Color> stopMap = new HashMap<>();
    for (Stop stop : STOPS) { stopMap.put(stop.getOffset(), stop.getColor()); }

    List<Stop>        sortedStops     = new ArrayList<>(STOPS.size());
    SortedSet<Double> sortedFractions = new TreeSet<>(stopMap.keySet());
    if (sortedFractions.last() < 1) {
        stopMap.put(1.0, stopMap.get(sortedFractions.last()));
        sortedFractions.add(1.0);
    }
    if (sortedFractions.first() > 0) {
        stopMap.put(0.0, stopMap.get(sortedFractions.first()));
        sortedFractions.add(0.0);
    }
    for (double fraction : sortedFractions) {
        double offset = fraction * range - halfRange;
        offset = offset < 0 ? 1.0 + offset : offset;
        sortedStops.add(new Stop(offset, stopMap.get(fraction)));
    }
    return sortedStops;
}
 
Example 9
Source Project: estatio   File: LeaseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void createAddress(Lease lease, IAgreementRoleCommunicationChannelType addressType) {
    final AgreementRoleType agreementRoleType =
            agreementRoleTypeRepository.find(LeaseAgreementRoleTypeEnum.TENANT);

    final AgreementRole agreementRole = lease.findRoleWithType(agreementRoleType, ld(2010, 7, 15));
    AgreementRoleCommunicationChannelType agreementRoleCommunicationChannelType =
            agreementRoleCommunicationChannelTypeRepository.find(addressType);

    final SortedSet<CommunicationChannel> channels =
            communicationChannelRepository.findByOwnerAndType(
                    lease.getSecondaryParty(), CommunicationChannelType.POSTAL_ADDRESS);

    final CommunicationChannel postalAddress = channels.first();
    agreementRole.addCommunicationChannel(agreementRoleCommunicationChannelType, postalAddress, null);
}
 
Example 10
Source Project: htmlunit   File: HtmlPage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DomElement getElementById(final String elementId) {
    final SortedSet<DomElement> elements = idMap_.get(elementId);
    if (elements != null) {
        return elements.first();
    }
    return null;
}
 
Example 11
Source Project: HtmlUnit-Android   File: HtmlPage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DomElement getElementById(final String elementId) {
    final SortedSet<DomElement> elements = idMap_.get(elementId);
    if (elements != null) {
        return elements.first();
    }
    return null;
}
 
Example 12
public ActionForward searchPerson(final ActionMapping mapping, final ActionForm actionForm, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final ManageSecondCycleThesisSearchBean searchPersonForm = getRenderedObject("searchPersonForm");

    final SortedSet<Person> people = searchPersonForm.findPersonBySearchString();
    if (people.size() == 1) {
        final Person person = people.first();
        return showPersonThesisDetails(mapping, request, person);
    }
    request.setAttribute("people", people);

    return firstPage(searchPersonForm, mapping, request, response);
}
 
Example 13
public YearMonthDay getNextPossibleLessonInstanceDate() {

        SortedSet<YearMonthDay> allLessonDates = getAllLessonDates();
        LessonInstance lastLessonInstance = getLastLessonInstance();

        if (lastLessonInstance != null) {
            YearMonthDay day = lastLessonInstance.getDay();
            SortedSet<YearMonthDay> nextLessonDates = allLessonDates.tailSet(day);
            nextLessonDates.remove(day);
            return nextLessonDates.isEmpty() ? null : nextLessonDates.first();
        }

        return allLessonDates.isEmpty() ? null : allLessonDates.first();
    }
 
Example 14
/**
 * Determine the proper OmrShape for the provided bar group.
 *
 * @param items inters that compose the barline group (perhaps including dots)
 * @return the corresponding OmrShape
 */
private OmrShape getBarGroupShape (SortedSet<Inter> items)
{
    final Inter first = items.first();
    final Inter last = items.last();

    if (first instanceof RepeatDotInter) {
        if (last instanceof RepeatDotInter) {
            return OmrShape.repeatRightLeft;
        } else {
            return OmrShape.repeatRight;
        }
    } else {
        if (last instanceof RepeatDotInter) {
            return OmrShape.repeatLeft;
        } else {
            // No repeat dot on either side
            final Shape firstShape = first.getShape();
            final Shape lastShape = last.getShape();

            if (firstShape == Shape.THICK_BARLINE) {
                if (lastShape == Shape.THICK_BARLINE) {
                    return OmrShape.barlineHeavyHeavy;
                } else {
                    return OmrShape.barlineReverseFinal;
                }
            } else {
                if (lastShape == Shape.THICK_BARLINE) {
                    return OmrShape.barlineFinal;
                } else {
                    return OmrShape.barlineDouble;
                }
            }
        }
    }
}
 
Example 15
/**
 * Retrieve individual page partwise instances, by unmarshalling MusicXML
 * data from the page string fragments
 *
 * @param pageFragments the sequence of input fragments (one string per
 *                      page)
 * @return the related sequence of partwise instances (one instance per
 *         page)
 * @throws JAXBException
 */
private SortedMap<Integer, ScorePartwise> unmarshallPages (
        Map<Integer, String> pageFragments)
        throws JAXBException
{
    ///watch.start("Unmarshalling pages");

    // Access the page fragments in the right order
    SortedSet<Integer> pageNumbers = new TreeSet<>(
            pageFragments.keySet());
    logger.info("About to read fragments {}", pageNumbers);

    /** For user feedback */
    String range = " of [" + pageNumbers.first() + ".."
                   + pageNumbers.last() + "]...";

    /* Load pages content */
    SortedMap<Integer, ScorePartwise> pages = new TreeMap<>();

    for (int pageNumber : pageNumbers) {
        watch.start("Unmarshalling page #" + pageNumber);

        ///logger.info("Unmarshalling fragment " + pageNumber + range);
        String rawFragment = pageFragments.get(pageNumber);

        // Filter out invalid XML characters if any
        WrappedBoolean stripped = new WrappedBoolean(false);
        String fragment = XmlUtil.stripNonValidXMLCharacters(
                rawFragment,
                stripped);

        if (stripped.isSet()) {
            logger.warn("Illegal XML characters found in fragment #{}",
                    pageNumber);
            statuses.put(pageNumber, Status.CHARACTERS_SKIPPED);
        }

        ByteArrayInputStream is = new ByteArrayInputStream(
                fragment.getBytes());

        try {
            ScorePartwise partwise = Marshalling.unmarshal(is);
            pages.put(pageNumber, partwise);
        } catch (Exception ex) {
            logger.warn("Could not unmarshall fragment #{} {}",
                    pageNumber, ex);
            statuses.put(pageNumber, Status.FRAGMENT_FAILED);
        }
    }

    return pages;
}
 
Example 16
private Summary getLastSummary() {
    SortedSet<Summary> summaries = getSummariesSortedByNewestDate();
    return (summaries.isEmpty()) ? null : summaries.first();
}
 
Example 17
@Override
public boolean process(AudioEvent audioEvent) {
		float[] buffer = audioEvent.getFloatBuffer().clone();
	float[] magnitudes = new float[buffer.length/2];
	float[] chroma = new float[12];
	fft.forwardTransform(buffer);
	fft.modulus(buffer, magnitudes);
	
	//make chroma with C as starting point (MIDI key 0) 
	for(int i = 0 ; i < magnitudes.length ;i++){
		//only process from MIDI key 29 (43Hz) to 107 (3951Hz) 
		if(binStartingPointsInCents[i] > 2900 && binStartingPointsInCents[i] < 10700){
			magnitudes[i] = (float) Math.log1p(magnitudes[i]);
			int  chromaIndex = Math.round(binStartingPointsInCents[i]/100) % 12;
			chroma[chromaIndex] += magnitudes[i];
		}
	}
	
	//normalize on the euclidean norm
	float squares = 0;
	for(int i = 0 ; i < chroma.length ; i++){
		squares += chroma[i] * chroma[i];
	}
	squares = (float) Math.sqrt(squares);
	for(int i = 0 ; i < chroma.length ; i++){
		chroma[i] = chroma[i]/squares;
	}
	
	//keep a running median
	for(int i = 0 ; i < chroma.length ; i++){
		orderedMagnitudes.add(chroma[i]);
		if(orderedMagnitudes.size()==1){
			currentMedian = chroma[i];
		}else{
			SortedSet<Float> h = orderedMagnitudes.headSet(currentMedian,true);
            SortedSet<Float> t = orderedMagnitudes.tailSet(currentMedian,false);
            int x = 1 - orderedMagnitudes.size() % 2;
            if (h.size() < t.size() + x)
            	currentMedian = t.first();
            else if (h.size() > t.size() + x)
            	currentMedian = h.last();
		}
	}
	
	
	//use the running median to binarize chroma
	for(int i = 0 ; i < chroma.length ; i++){
		if(chroma[i] > currentMedian)
			chroma[i] = 1;
		else
			chroma[i] = 0;
	}
	
	
			
	float timeStamp = (float) audioEvent.getTimeStamp();
	this.magnitudes.put(timeStamp , magnitudes);
	this.chromaMagnitudes.put(timeStamp, chroma);
			
	return true;
}
 
Example 18
Source Project: opt4j   File: CrossoverListXPoint.java    License: MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Pair<G> crossover(G p1, G p2) {

	ListGenotype<Object> o1 = p1.newInstance();
	ListGenotype<Object> o2 = p2.newInstance();

	int size = p1.size();

	if (x <= 0 || x > size - 1) {
		throw new IllegalArgumentException(this.getClass() + " : x is " + x + " for binary vector size " + size);
	}

	SortedSet<Integer> points = new TreeSet<>();

	while (points.size() < x) {
		points.add(random.nextInt(size - 1) + 1);
	}

	int flip = 0;
	boolean select = random.nextBoolean();

	for (int i = 0; i < size; i++) {
		if (i == flip) {
			select = !select;

			if (points.size() > 0) {
				flip = points.first();
				points.remove(flip);
			}
		}

		if (select) {
			o1.add(p1.get(i));
			o2.add(p2.get(i));
		} else {
			o1.add(p2.get(i));
			o2.add(p1.get(i));
		}
	}

	Pair<G> offspring = new Pair<>((G) o1, (G) o2);
	return offspring;
}
 
Example 19
public CommunicationChannel default0PrecededBy() {
    final SortedSet<CommunicationChannel> partyChannels = communicationChannelsForRolesParty();
    return !partyChannels.isEmpty() ? partyChannels.first() : null;
}
 
Example 20
/**
 * 1) Create a central config channel (A) add a bunch of files &amp; dirs
 * 2) Call ConfigurationManager.countCentrallyManagedFiles and verify
 *      that we have the correct answer
 * 3) Create a new channel and add ONE file thats new and One file
 *      duplicate of a file in Channel (A) ...
 * 4) Call ConfigurationManager.countCentrallyManagedFiles and verify
 *      that the answer is number of files in Channel A + 1
 * @throws Exception under exceptional circumstances
 */

public void testCountCentrallyManagedFiles() throws Exception {
    user.getOrg().addRole(RoleFactory.CONFIG_ADMIN);
    user.addPermanentRole(RoleFactory.CONFIG_ADMIN);
    Server s = makeServerForChannelCountTests();
    ConfigFileCount actual = cm.countCentrallyManagedPaths(s, user);

    assertEquals(EXPECTED_COUNT, actual);

    final ConfigChannel c = s.getConfigChannels().get(0);

    SortedSet files = c.getConfigFiles();
    assertEquals(files.size(), EXPECTED_COUNT.getFiles() +
                                    EXPECTED_COUNT.getDirectories());
    //now add a new channel -
    // (with some file/ directory intersections)

    ConfigFile fl = (ConfigFile) files.first();
    final String path = fl.getConfigFileName().getPath();

    ConfigChannel cc = ConfigTestUtils.createConfigChannel(user.getOrg());

    //Create a Duplicate Path and add it to the new channel
    final ConfigFile fl2 = cc.createConfigFile(
                                ConfigFileState.normal(),
                                path);
    ConfigTestUtils.createConfigRevision(fl2,
                    ConfigFileType.file());

    //Now Create a NEW Path and add it to the new channel
    ConfigFile fl3 = ConfigTestUtils.createConfigFile(cc);
    ConfigTestUtils.createConfigRevision(fl3,
                            ConfigFileType.file());

    s.subscribeAt(cc, 0);
    ServerFactory.save(s);
    actual = cm.countCentrallyManagedPaths(s, user);

    ConfigFileCount expected = ConfigFileCount.create(
                                            EXPECTED_COUNT.getFiles() + 1,
                                            EXPECTED_COUNT.getDirectories(), 0);
    assertEquals(expected, actual);
}