Example usage for java.util SortedSet last

List of usage examples for java.util SortedSet last

Introduction

In this page you can find the example usage for java.util SortedSet last.

Prototype

E last();

Source Link

Document

Returns the last (highest) element currently in this set.

Usage

From source file:com.cloudera.oryx.kmeans.computation.cluster.KSketchIndex.java

public Distance getDistance(RealVector vec, int id, boolean approx) {
    double distance = Double.POSITIVE_INFINITY;
    int closestPoint = -1;
    if (approx) {
        if (updated) {
            rebuildIndices();//from   w  ww.  j  a  v a2s.c  o  m
        }

        BitSet q = index(vec);
        List<BitSet> index = indices.get(id);
        SortedSet<Idx> lookup = Sets.newTreeSet();
        for (int j = 0; j < index.size(); j++) {
            Idx idx = new Idx(hammingDistance(q, index.get(j)), j);
            if (lookup.size() < projectionSamples) {
                lookup.add(idx);
            } else if (idx.compareTo(lookup.last()) < 0) {
                lookup.add(idx);
                lookup.remove(lookup.last());
            }
        }

        List<RealVector> p = points.get(id);
        List<Double> lsq = lengthSquared.get(id);
        for (Idx idx : lookup) {
            double lenSq = lsq.get(idx.getIndex());
            double length = vec.getNorm();
            double d = length * length + lenSq - 2 * vec.dotProduct(p.get(idx.getIndex()));
            if (d < distance) {
                distance = d;
                closestPoint = idx.getIndex();
            }
        }
    } else { // More expensive exact computation
        List<RealVector> px = points.get(id);
        List<Double> lsq = lengthSquared.get(id);
        for (int j = 0; j < px.size(); j++) {
            RealVector p = px.get(j);
            double lenSq = lsq.get(j);
            double length = vec.getNorm();
            double d = length * length + lenSq - 2 * vec.dotProduct(p);
            if (d < distance) {
                distance = d;
                closestPoint = j;
            }
        }
    }

    return new Distance(distance, closestPoint);
}

From source file:net.sourceforge.fenixedu.domain.alumni.AlumniReportFile.java

public PhysicalAddress getLastPersonalAddress(final Person person) {
    if (person.getStudent().getAlumni() != null) {
        return person.getStudent().getAlumni().getLastPersonalAddress();
    }//w ww.jav  a2  s. c om

    SortedSet<PhysicalAddress> addressSet = new TreeSet<PhysicalAddress>(DomainObjectUtil.COMPARATOR_BY_ID);
    addressSet.addAll(person.getPhysicalAddresses());
    return !addressSet.isEmpty() && addressSet.last() != null ? addressSet.last() : null;
}

From source file:io.selendroid.common.SelendroidCapabilities.java

private String getDefaultVersion(Set<String> keys, String appName) {
    SortedSet<String> listOfApps = new TreeSet<String>();
    for (String key : keys) {
        if (key.split(":")[0].contentEquals(appName)) {
            listOfApps.add(key);//from   w  ww  .j  a v a  2s.  c  om
        }
    }
    return listOfApps.size() > 0 ? listOfApps.last() : null;
}

From source file:com.alibaba.otter.shared.arbitrate.impl.zookeeper.lock.DistributedLock.java

/**
 * lock??watch????lock?//from www .  j a v  a2  s.co  m
 */
private Boolean acquireLock(final BooleanMutex mutex) {
    try {
        do {
            if (id == null) {// ?lock
                long sessionId = getSessionId();
                String prefix = "x-" + sessionId + "-";
                // 
                String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL);
                int index = path.lastIndexOf("/");
                id = StringUtils.substring(path, index + 1);
                idName = new LockNode(id);
            }

            if (id != null) {
                List<String> names = zookeeper.getChildren(root);
                if (names.isEmpty()) {
                    logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName);
                    unlock();// ??
                } else {
                    // ?
                    SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                    for (String name : names) {
                        sortedNames.add(new LockNode(name));
                    }

                    if (sortedNames.contains(idName) == false) {
                        logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName);
                        unlock();// ??
                        continue;
                    }

                    // ?ownerId
                    ownerId = sortedNames.first().getName();
                    if (mutex != null && isOwner()) {
                        mutex.set(true);// ?
                        return true;
                    } else if (mutex == null) {
                        return isOwner();
                    }

                    SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                    if (!lessThanMe.isEmpty()) {
                        // ?
                        LockNode lastChildName = lessThanMe.last();
                        lastChildId = lastChildName.getName();
                        // watcher?
                        IZkConnection connection = zookeeper.getConnection();
                        // zkclient?zk?lock??watcher?zk?
                        ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
                        Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() {

                            public void asyncProcess(WatchedEvent event) {
                                if (!mutex.state()) { // ?????lock
                                    acquireLock(mutex);
                                } else {
                                    logger.warn("locked successful.");
                                }
                            }

                        });

                        if (stat == null) {
                            acquireLock(mutex);// ????watcher?
                        }
                    } else {
                        if (isOwner()) {
                            mutex.set(true);
                        } else {
                            logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName);
                            unlock();// ?idownerId??
                        }
                    }
                }
            }
        } while (id == null);
    } catch (KeeperException e) {
        exception = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (InterruptedException e) {
        interrupt = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (Throwable e) {
        other = e;
        if (mutex != null) {
            mutex.set(true);
        }
    }

    if (isOwner() && mutex != null) {
        mutex.set(true);
    }
    return Boolean.FALSE;
}

From source file:net.sourceforge.fenixedu.domain.studentCurriculum.RootCurriculumGroup.java

public CycleCurriculumGroup getLastOrderedCycleCurriculumGroup() {
    final SortedSet<CycleCurriculumGroup> cycleCurriculumGroups = new TreeSet<CycleCurriculumGroup>(
            CycleCurriculumGroup.COMPARATOR_BY_CYCLE_TYPE_AND_ID);
    cycleCurriculumGroups.addAll(getInternalCycleCurriculumGroups());

    return cycleCurriculumGroups.isEmpty() ? null : cycleCurriculumGroups.last();
}

From source file:net.sourceforge.fenixedu.domain.Alumni.java

public PhysicalAddress getLastPersonalAddress() {
    SortedSet<PhysicalAddress> addressSet = new TreeSet<PhysicalAddress>(DomainObjectUtil.COMPARATOR_BY_ID);
    addressSet.addAll(getStudent().getPerson().getPhysicalAddresses());
    return !addressSet.isEmpty() && addressSet.last() != null ? addressSet.last() : null;
}

From source file:org.apache.kylin.common.KylinConfigBase.java

private static String getFileName(String homePath, Pattern pattern) {
    File home = new File(homePath);
    SortedSet<String> files = Sets.newTreeSet();
    if (home.exists() && home.isDirectory()) {
        File[] listFiles = home.listFiles();
        if (listFiles != null) {
            for (File file : listFiles) {
                final Matcher matcher = pattern.matcher(file.getName());
                if (matcher.matches()) {
                    files.add(file.getAbsolutePath());
                }/*from  w ww  . java 2s  . c  o m*/
            }
        }
    }
    if (files.isEmpty()) {
        throw new RuntimeException("cannot find " + pattern.toString() + " in " + homePath);
    } else {
        return files.last();
    }
}

From source file:com.hmsinc.epicenter.integrator.service.PatientService.java

private PatientDetail parseDetails(final HL7Message message, final Patient patient) throws HL7Exception {

    final Terser t = message.getTerser();

    // Create new set of Details
    PatientDetail patientDetail = new PatientDetail();
    patientDetail.setPatient(patient);//from www  .j  a v  a  2 s  .c  om

    // Zipcode
    String zipcode = t.get("/PID-11-5");

    try {
        if (zipcode == null) {
            throw new InvalidZipcodeException("No patient zipcode provided.");
        }
        patientDetail.setZipcode(zipcode);
    } catch (InvalidZipcodeException ize) {
        logger.error(ize.getMessage());
        statisticsService.updateProviderStats(message, StatisticsService.StatsType.INCOMPLETE,
                "missing: " + IncompleteDataException.IncompleteDataType.ZIPCODE);
    }

    // Date of Birth
    final String dob = StringUtils.trimToNull(t.get("/PID-7"));
    if (dob == null) {
        logger.warn("No date of birth set in message");
    } else {
        patientDetail.setDateOfBirth(ER7Utils.fromER7Date(dob));
    }

    // Gender
    String genderAbbr = StringUtils.trimToNull(t.get("/PID-8"));
    if (genderAbbr == null) {
        genderAbbr = "U";
        logger.warn("No gender set in message");
        statisticsService.updateProviderStats(message, StatisticsService.StatsType.INCOMPLETE,
                "missing: " + IncompleteDataException.IncompleteDataType.GENDER);
    }

    patientDetail.setGender(attributeRepository.getGenderByAbbreviation(genderAbbr));

    final SortedSet<PatientDetail> sortedDetails = patient.getPatientDetails();

    if (patient.getPatientId() == null) {

        // Just save it.
        logger.debug("Saving details without patientID");
        sortedDetails.add(patientDetail);

    } else if (sortedDetails.size() == 0) {

        // Just save it.
        logger.debug("Creating initial detail record");
        sortedDetails.add(patientDetail);

    } else {

        final PatientDetail latestDetail = sortedDetails.last();
        if (patientDetail.equals(latestDetail)) {

            patientDetail = latestDetail;
            logger.debug("Using existing detail record: {}", latestDetail.getId());

        } else {

            logger.debug("Creating updated detail record");
            logger.debug("Old: {}  New: {}", latestDetail, patientDetail);
            sortedDetails.add(patientDetail);

        }
    }

    return patientDetail;
}

From source file:com.opengamma.integration.coppclark.CoppClarkHolidayFileReader.java

private void mergeDates(HolidayDocument existingDoc, HolidayDocument newDoc) {
    if (newDoc.getHoliday().getHolidayDates().size() == 0) {
        return;/*from  www .  j a  va 2s.  com*/
    }

    // merge dates
    SortedSet<LocalDate> existingDates = new TreeSet<LocalDate>(existingDoc.getHoliday().getHolidayDates());
    SortedSet<LocalDate> newDates = new TreeSet<LocalDate>(newDoc.getHoliday().getHolidayDates());
    List<LocalDate> result = new ArrayList<LocalDate>(newDates);
    result.addAll(0, existingDates.headSet(newDates.first()));
    result.addAll(existingDates.tailSet(newDates.last().plusYears(1).withDayOfYear(1))); // file is based on whole years

    // store into new document
    newDoc.getHoliday().getHolidayDates().clear();
    newDoc.getHoliday().getHolidayDates().addAll(result);
}

From source file:org.apache.blur.kvs.HdfsKeyValueStore.java

public void cleanupOldFiles() throws IOException {
    _writeLock.lock();//  ww  w  .j a  va2 s  . c o m
    try {
        if (!isOpenForWriting()) {
            return;
        }
        SortedSet<FileStatus> fileStatusSet = getSortedSet(_path);
        if (fileStatusSet == null || fileStatusSet.size() < 1) {
            return;
        }
        Path newestGen = fileStatusSet.last().getPath();
        if (!newestGen.equals(_outputPath)) {
            throw new IOException("No longer the owner of [" + _path + "]");
        }
        Set<Path> existingFiles = new HashSet<Path>();
        for (FileStatus fileStatus : fileStatusSet) {
            existingFiles.add(fileStatus.getPath());
        }
        Set<Entry<BytesRef, Value>> entrySet = _pointers.entrySet();
        existingFiles.remove(_outputPath);
        for (Entry<BytesRef, Value> e : entrySet) {
            Path p = e.getValue()._path;
            existingFiles.remove(p);
        }
        for (Path p : existingFiles) {
            LOG.info("Removing file no longer referenced [{0}]", p);
            _fileSystem.delete(p, false);
        }
    } finally {
        _writeLock.unlock();
    }
}