List of usage examples for java.util Collections reverseOrder
@SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder()
From source file:com.coderadar.controller.MainController.java
private void sort(List<String> sortlist) { if (!CollectionUtils.isEmpty(sortlist)) { Collections.sort(sortlist); Collections.sort(sortlist, Collections.reverseOrder()); }//from ww w . ja v a 2 s .com }
From source file:net.tsquery.DataEndpoint.java
@SuppressWarnings("unchecked") private JSONObject PlotToStandardJSON(Plot plot, long tsFrom, long tsTo, int topN) { final JSONObject plotObject = new JSONObject(); JSONArray seriesArray = new JSONArray(); final TreeMap<Double, JSONObject> weightMap = new TreeMap<>(Collections.reverseOrder()); for (DataPoints dataPoints : plot.getDataPoints()) { double weight = 0; JSONArray dataArray = new JSONArray(); StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append(dataPoints.metricName()).append(": "); Map<String, String> tags = dataPoints.getTags(); for (String s : tags.keySet()) { nameBuilder.append(String.format("%s=%s, ", s, tags.get(s))); }//from w ww . j a v a 2s . c o m nameBuilder.setLength(nameBuilder.length() - 2); for (DataPoint point : dataPoints) { long timestamp = point.timestamp(); if (timestamp < tsFrom || timestamp > tsTo) continue; double dpValue = getValue(point); JSONArray values = new JSONArray(); values.add(timestamp * 1000); values.add(dpValue); weight += ((dpValue) / 1000000.0); dataArray.add(values); } JSONObject series = new JSONObject(); series.put("name", nameBuilder.toString()); series.put("data", dataArray); while (weightMap.containsKey(weight)) weight -= 0.00000001; weightMap.put(weight, series); } int counter = 0; for (Map.Entry<Double, JSONObject> entry : weightMap.entrySet()) { seriesArray.add(entry.getValue()); ++counter; if ((topN > 0) && (counter >= topN)) break; } plotObject.put("plot", seriesArray); return plotObject; }
From source file:org.silverpeas.migration.jcr.service.repository.DocumentRepository.java
/** * Copy the document to another attached object. * * @param session//from ww w .j a v a2 s. c o m * @param document * @param destination the foreingId holding reference to the copy. * @return * @throws RepositoryException * @throws IOException */ public SimpleDocumentPK copyDocument(Session session, HistorisedDocument document, WAPrimaryKey destination) throws RepositoryException, IOException { prepareComponentAttachments(destination.getInstanceId(), document.getFolder()); SimpleDocumentPK pk = new SimpleDocumentPK(null, destination.getInstanceId()); List<SimpleDocument> history = document.getHistory(); history.add(document); Collections.reverseOrder(); SimpleDocument targetDoc = new HistorisedDocument(history.remove(0)); targetDoc.setNodeName(null); targetDoc.setPK(pk); targetDoc.setDocumentType(document.getDocumentType()); targetDoc.setForeignId(destination.getId()); targetDoc.computeNodeName(); pk = createDocument(session, targetDoc); unlock(session, targetDoc, false); for (SimpleDocument doc : history) { lock(session, targetDoc, document.getUpdatedBy()); targetDoc = new HistorisedDocument(doc); targetDoc.setPK(pk); targetDoc.setForeignId(destination.getId()); updateDocument(session, targetDoc); unlock(session, targetDoc, false); } return pk; }
From source file:edu.cmu.cs.lti.discoursedb.annotation.brat.io.BratService.java
/** * Imports a thread in Brat stand-off format into discoursedb. * /*from w w w.j a v a 2 s .co m*/ * @param inputFolder folder with the brat annotation and meta data * @param baseFileName the base filename for the current thread to be imported * @return an info object containing lists of ids of annotations and featured to be deleted after the import * @throws IOException if any exception occurs while reading the brat annotations or meta data */ @Transactional(value = "coreTransactionManager", propagation = Propagation.REQUIRED, readOnly = false) private CleanupInfo importThreadFromBrat(String inputFolder, String baseFileName) throws IOException { Assert.hasText(inputFolder, "inputFolder parameter cannot be empty [importThread(" + inputFolder + ", " + baseFileName + ")]"); Assert.hasText(baseFileName, "baseFileName parameter cannot be empty [importThread(" + inputFolder + ", " + baseFileName + ")]"); File annFile = new File(inputFolder, baseFileName + ".ann"); File offsetFile = new File(inputFolder, baseFileName + ".offsets"); File versionsFile = new File(inputFolder, baseFileName + ".versions"); // get mapping from entity to offset TreeMap<Integer, OffsetInfo> offsetToOffsetInfo = getOffsetToOffsetInfoMap(offsetFile); // keep track of versions of orginally exported annotations and features Map<String, VersionInfo> annotationBratIdToVersionInfo = getBratIdToDdbIdMap(versionsFile, AnnotationSourceType.DDB_ANNOTATION); Map<String, VersionInfo> featureBratIdToVersionInfo = getBratIdToDdbIdMap(versionsFile, AnnotationSourceType.DDB_FEATURE); DiscoursePart dp = dpService .findOne(Long.parseLong(baseFileName.substring(baseFileName.lastIndexOf("_") + 1))).get(); SystemUser sysUser = sysUserService.getSystemUser().get(); //Init ddb annotation stats for deletion handling Set<Long> ddbAnnotationIds = new HashSet<>(); Set<Long> ddbFeatureIds = new HashSet<>(); //extract annotations on Contributions for (AnnotationInstance anno : annoService.findContributionAnnotationsByDiscoursePart(dp)) { ddbAnnotationIds.add(anno.getId()); anno.setAnnotator(sysUser); ; if (anno.getFeatures() != null) { ddbFeatureIds.addAll(anno.getFeatures().stream().map(f -> f.getId()).collect(Collectors.toList())); } } //extract annotations on Content entities for (AnnotationInstance anno : annoService.findCurrentRevisionAnnotationsByDiscoursePart(dp)) { ddbAnnotationIds.add(anno.getId()); anno.setAnnotator(sysUser); if (anno.getFeatures() != null) { ddbFeatureIds.addAll(anno.getFeatures().stream().map(f -> f.getId()).collect(Collectors.toList())); } } log.info(ddbAnnotationIds.size() + " annotations within current thread available in DiscoursDB."); log.info(ddbFeatureIds.size() + " features within current thread available in DiscoursDB."); List<String> bratStandoffEncodedStrings = FileUtils.readLines(annFile); //sorting in reverse order assures that Attribute annotations (A) are imported after text-bound annotations (T) Collections.sort(bratStandoffEncodedStrings, Collections.reverseOrder()); for (String bratStandoffEncodedString : bratStandoffEncodedStrings) { // create BratAnnotation object from Brat-Stand-off-Encoded String // offset correction will be done later BratAnnotation bratAnno = new BratAnnotation(bratStandoffEncodedString); if (bratAnno.getType() == BratAnnotationType.BRAT_TEXT) { Entry<Integer, OffsetInfo> offset = offsetToOffsetInfo.floorEntry(bratAnno.getBeginIndex()); Contribution contrib = contribService.findOne(offset.getValue().getDiscourseDbContributionId()) .get(); Content content = contentService.findOne(offset.getValue().getDiscourseDbContentId()).get(); long separatorStartIndex = offset.getKey(); long separatorEndIndex = separatorStartIndex + BratSeparator.length; long textEndIndex = separatorEndIndex + content.getText().length(); // CONTRIBUTION LABEL: Annotation is completely within a separator if (bratAnno.getBeginIndex() >= separatorStartIndex && bratAnno.getBeginIndex() <= separatorEndIndex && bratAnno.getEndIndex() >= separatorStartIndex && bratAnno.getEndIndex() <= separatorEndIndex) { // check if annotation already existed before if (annotationBratIdToVersionInfo.keySet().contains(bratAnno.getId())) { VersionInfo entityInfo = annotationBratIdToVersionInfo.get(bratAnno.getId()); ddbAnnotationIds.remove(entityInfo.getDiscourseDBEntityId()); //update deletion stats AnnotationInstance existingAnno = annoService .findOneAnnotationInstance(entityInfo.getDiscourseDBEntityId()).get(); //check if the anno version in the database still matches the anno version we initially exported if (existingAnno.getEntityVersion() == entityInfo.getDiscourseDBEntityVersion()) { existingAnno.setBeginOffset(0); existingAnno.setEndOffset(0); existingAnno.setType(bratAnno.getAnnotationLabel()); } else { log.error( "Entity changed in DiscourseDB since the data was last import but also changed in the exported file. Cannot import annotation."); } } else { // anno is new and didn't exist in ddb before AnnotationInstance newAnno = annoService .createTypedAnnotation(bratAnno.getAnnotationLabel()); annoService.addAnnotation(contrib, newAnno); contribService.save(contrib); //this should happen in addAnnotation. Filed Issue #15 //update version file annotationBratIdToVersionInfo.put(bratAnno.getId(), new VersionInfo(AnnotationSourceType.DDB_ANNOTATION, bratAnno.getId(), newAnno.getId(), newAnno.getEntityVersion())); } } // SPAN ANNOTATION WITHIN CONTRIBUTION TEXT (does neither span over separator nor over multiple contributions) else if (bratAnno.getBeginIndex() > separatorEndIndex && bratAnno.getBeginIndex() <= textEndIndex && bratAnno.getEndIndex() > separatorEndIndex && bratAnno.getEndIndex() <= textEndIndex) { // calculate offset corrected index values for span annotation int offsetCorrectedBeginIdx = bratAnno.getBeginIndex() - offset.getKey() - BratSeparator.length - 1; int offsetCorrectedEndIdx = bratAnno.getEndIndex() - offset.getKey() - BratSeparator.length - 1; // check if annotation already existed before if (annotationBratIdToVersionInfo.keySet().contains(bratAnno.getId())) { VersionInfo entityInfo = annotationBratIdToVersionInfo.get(bratAnno.getId()); ddbAnnotationIds.remove(entityInfo.getDiscourseDBEntityId()); //update deletion stats // Anno already existed. Check for changes. AnnotationInstance existingAnno = annoService .findOneAnnotationInstance(entityInfo.getDiscourseDBEntityId()).get(); //check if the anno version in the database still matches the anno version we initially exported //if so, we can update if (existingAnno.getEntityVersion() == entityInfo.getDiscourseDBEntityVersion()) { existingAnno.setBeginOffset(offsetCorrectedBeginIdx); existingAnno.setEndOffset(offsetCorrectedEndIdx); existingAnno.setType(bratAnno.getAnnotationLabel()); } else { log.error( "Entity changed in DiscourseDB since the data was last import but also changed in the exported file. Cannot import annotation."); } } else { // Anno is new and didn't exist in ddb before. Create it. AnnotationInstance newAnno = annoService .createTypedAnnotation(bratAnno.getAnnotationLabel()); newAnno.setBeginOffset(offsetCorrectedBeginIdx); newAnno.setEndOffset(offsetCorrectedEndIdx); annoService.addAnnotation(content, newAnno); contentService.save(content); //this should happen in addAnnotation. Filed Issue #15 //update version file annotationBratIdToVersionInfo.put(bratAnno.getId(), new VersionInfo(AnnotationSourceType.DDB_ANNOTATION, bratAnno.getId(), newAnno.getId(), newAnno.getEntityVersion())); } } else { log.error( "Annotation extends over contribution separator(s) AND text. You can only annotate within a separator or within a contribution. Skipping this annotation..."); } } else if (bratAnno.getType() == BratAnnotationType.BRAT_NOTE) { VersionInfo entityInfo = featureBratIdToVersionInfo.get(bratAnno.getId()); // check if feature already existed before if (featureBratIdToVersionInfo.keySet().contains(bratAnno.getId())) { ddbFeatureIds.remove(entityInfo.getDiscourseDBEntityId()); //update deletion stats // feature already existed Feature existingFeature = annoService.findOneFeature(entityInfo.getDiscourseDBEntityId()).get(); //check if the feature version in the database still matches the feature version we initially exported if (existingFeature.getEntityVersion() == entityInfo.getDiscourseDBEntityVersion()) { //check for and apply changes if (existingFeature.getValue().equalsIgnoreCase(bratAnno.getAnnotationLabel())) { existingFeature.setValue(bratAnno.getAnnotationLabel()); } } else { log.error( "Entity changed in DiscourseDB since the data was last import but also changed in the exported file. Cannot import feature."); } } else { // feature didn't exist in database yet. Create it. VersionInfo referenceAnnotationInfo = annotationBratIdToVersionInfo .get(bratAnno.getSourceAnnotationId()); if (referenceAnnotationInfo != null) { AnnotationInstance referenceAnno = annoService .findOneAnnotationInstance(referenceAnnotationInfo.getDiscourseDBEntityId()).get(); Feature newFeature = annoService.createTypedFeature(bratAnno.getNoteText(), bratAnno.getType().name()); //update version file featureBratIdToVersionInfo.put(bratAnno.getId(), new VersionInfo(AnnotationSourceType.DDB_FEATURE, bratAnno.getId(), newFeature.getId(), newFeature.getEntityVersion())); annoService.addFeature(referenceAnno, newFeature); annoService.saveFeature(newFeature); //this should happen in addFeature. Filed Issue #15 } else { log.error("Cannot find the annotation this feature applies to."); } } } else { //Implement import capabilities for other Brat Annotation types here log.error("Unsupported Annotation type " + bratAnno.getType() + " Skipping."); } } //Regenerate the version infos updated data from the newly created annotations List<VersionInfo> updatedVersionInfo = new ArrayList<>(); updatedVersionInfo.addAll(annotationBratIdToVersionInfo.values()); updatedVersionInfo.addAll(featureBratIdToVersionInfo.values()); FileUtils.writeLines(versionsFile, updatedVersionInfo); //return info about entities to be deleted return new CleanupInfo(versionsFile, ddbFeatureIds, ddbAnnotationIds); }
From source file:com.rr.generic.ui.forum.forumController.java
@RequestMapping(value = "/getTopicMessages.do", method = RequestMethod.GET) public @ResponseBody ModelAndView getTopicMessages( @RequestParam(value = "topicId", required = true) Integer topicId) throws Exception { List<topicMessages> topicMessages = new ArrayList<topicMessages>(); List<forumMessages> messages = forumManager.getTopicMessages(topicId); if (!messages.isEmpty()) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = null;// w w w . ja va 2s. com topicMessages newmessage = null; List<forumMessages> topicDateMessages = new ArrayList<forumMessages>(); for (forumMessages message : messages) { Date date2 = sdf.parse(message.getDateCreated().toString()); if (date1 == null) { date1 = date2; newmessage = new topicMessages(); newmessage.setMessageDate(message.getDateCreated()); List<forumMessages> messageReplies = forumManager.getTopicMessageReplies(message.getId()); if (!messageReplies.isEmpty()) { for (forumMessages reply : messageReplies) { List<forumDocuments> documentList = forumManager.getMessageDocuments(reply.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } reply.setForumDocuments(documentList); } } message.setReplies(messageReplies); } List<forumDocuments> documentList = forumManager.getMessageDocuments(message.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } message.setForumDocuments(documentList); } topicDateMessages.add(message); } else if (date2.before(date1)) { newmessage.setMessages(topicDateMessages); topicMessages.add(newmessage); newmessage = new topicMessages(); topicDateMessages = new ArrayList<forumMessages>(); newmessage.setMessageDate(message.getDateCreated()); List<forumMessages> messageReplies = forumManager.getTopicMessageReplies(message.getId()); if (!messageReplies.isEmpty()) { for (forumMessages reply : messageReplies) { List<forumDocuments> documentList = forumManager.getMessageDocuments(reply.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } reply.setForumDocuments(documentList); } } message.setReplies(messageReplies); } List<forumDocuments> documentList = forumManager.getMessageDocuments(message.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } message.setForumDocuments(documentList); } topicDateMessages.add(message); date1 = date2; } else { List<forumMessages> messageReplies = forumManager.getTopicMessageReplies(message.getId()); if (!messageReplies.isEmpty()) { for (forumMessages reply : messageReplies) { List<forumDocuments> documentList = forumManager.getMessageDocuments(reply.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } reply.setForumDocuments(documentList); } } message.setReplies(messageReplies); } List<forumDocuments> documentList = forumManager.getMessageDocuments(message.getId()); if (!documentList.isEmpty()) { for (forumDocuments doc : documentList) { doc.setEncodedTitle(URLEncoder.encode(doc.getDocumentTitle(), "UTF-8")); } message.setForumDocuments(documentList); } topicDateMessages.add(message); } } /* Add last entry */ newmessage.setMessages(topicDateMessages); topicMessages.add(newmessage); } Collections.sort(topicMessages, Collections.reverseOrder()); ModelAndView mav = new ModelAndView(); mav.setViewName("/forum/messages"); mav.addObject("topicMessages", topicMessages); mav.addObject("allowCreate", allowCreate); return mav; }
From source file:com.liato.bankdroid.banking.banks.CSN.java
@Override public void updateTransactions(Account account, Urllib urlopen) throws LoginException, BankException { super.updateTransactions(account, urlopen); if (account.getAliasfor() == null || account.getAliasfor().length() == 0) return;//from w w w. j a va 2s .c om Matcher matcher; try { response = urlopen.open("https://www.csn.se/studiemedel/utbetalningar/utbetalningar.do?javascript=off"); matcher = reTransactions.matcher(response); ArrayList<Transaction> transactions = new ArrayList<Transaction>(); while (matcher.find()) { /* * Capture groups: * GROUP EXAMPLE DATA * 1: Date 2010-11-25 * 2: Specification Vecka 47-50 * 3: Status Utbetald * 4: Amount 8,140 * */ transactions.add(new Transaction(matcher.group(1).trim(), Html.fromHtml(matcher.group(2)).toString().trim() + " (" + Html.fromHtml(matcher.group(3)).toString().trim() + ")", Helpers.parseBalance(matcher.group(4).replace(",", "")))); } response = urlopen.open( "https://www.csn.se/aterbetalning/vadSkallJagBetalUnderAret/betalningstillfallen.do?javascript=off"); matcher = reTransactions.matcher(response); while (matcher.find()) { /* * Capture groups: * GROUP EXAMPLE DATA * 1: Date 2010-11-25 * 2: Specification Bankgiro 5580-3084 * 3: OCR-number 4576225900 * 4: Amount 1,234 * */ transactions.add(new Transaction(matcher.group(1).trim(), Html.fromHtml(matcher.group(2)).toString().trim() + " (" + Html.fromHtml(matcher.group(3)).toString().trim() + ")", Helpers.parseBalance(matcher.group(4).replace(",", "")).negate())); } response = urlopen.open( "https://www.csn.se/aterbetalning/harMinaInbetalningarKommitIn/registreradeInbetalningar.do?javascript=off"); matcher = reCompletedPayments.matcher(response); while (matcher.find()) { /* * Capture groups: * GROUP EXAMPLE DATA * 1: Date 2006-08-21 * 2: Specification terkrav frsta halvret 2006 ln 1 * 3: Amount 1,050 * */ transactions.add( new Transaction(matcher.group(1).trim(), Html.fromHtml(matcher.group(2)).toString().trim(), Helpers.parseBalance(matcher.group(3).replace(",", "")).negate())); } Collections.sort(transactions, Collections.reverseOrder()); account.setTransactions(transactions); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:business.services.FileService.java
public List<String> getAccessLogFilenames() { try {// www. ja va2 s .c om List<String> logFiles = new ArrayList<String>(); for (Path p : Files.newDirectoryStream(fileSystem.getPath("./logs/"), "dntp-access*.log")) { logFiles.add(p.getFileName().toString()); } Collections.sort(logFiles, Collections.reverseOrder()); return logFiles; } catch (IOException e) { log.error(e); throw new FileDownloadError(); } }
From source file:wassilni.pl.navigationdrawersi.ui.Search.java
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Spinner spinner = (Spinner) parent;/*from w ww .j av a 2s .c o m*/ TextView myText = (TextView) view; if (spinner.getSelectedItemPosition() == 1) {//sort the result high price // Toast.makeText(getApplicationContext()," ", Toast.LENGTH_SHORT).show(); Collections.sort(searchResults, Collections.reverseOrder()); showDate(); } else if (spinner.getSelectedItemPosition() == 2) {//sort the result lower price // Toast.makeText(getApplicationContext()," ", Toast.LENGTH_SHORT).show(); Collections.sort(searchResults); showDate(); } }
From source file:scorePairing.ExtendPairing.java
private ResultsFromEvaluateCost generatePairingAndNullSpaceUsingMatchingPointWithPropertiesNostaticlist( ResultsFromEvaluateCost resultSeed, final CollectionOfPointsWithPropertiesIfc shape1, final CollectionOfPointsWithPropertiesIfc shape2, AlgoParameters algoParameters) { // Both points has StrikingProperties not none and they all match (also if only one of course) Map<Integer, List<PairPointWithDistance>> mapforAllMatchingStrikingProperties = new LinkedHashMap<>(); // Both points has more than one striking properties and at least one of them match List<PairPointWithDistance> listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance = new ArrayList<>(); // Both points has None Striking Properties List<PairPointWithDistance> listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance = new ArrayList<>(); // One point has None striking property and the others has striking properties List<PairPointWithDistance> listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance = new ArrayList<>(); // Both points has Striking properties but not a single one is matching List<PairPointWithDistance> listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance = new ArrayList<>(); for (int i = 0; i < shape1.getSize(); i++) { for (int j = 0; j < shape2.getSize(); j++) { // Only Pairs of matching properties point are kept PointWithPropertiesIfc pointWithProperties1 = shape1.getPointFromId(i); PointWithPropertiesIfc pointWithProperties2 = shape2.getPointFromId(j); RealMatrix matrix = resultSeed.getRotationMatrix(); float[] vector1 = new float[3]; for (int k = 0; k < 3; k++) { vector1[k] = (float) (pointWithProperties2.getCoords().getCoords()[k] + resultSeed.getTranslationVectorToTranslateShape2ToOrigin().getEntry(k)); }//from w w w . ja va 2 s. c o m double[] vector2 = new double[3]; for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { vector2[k] += matrix.getEntry(k, l) * vector1[l]; } } for (int k = 0; k < 3; k++) { vector1[k] = (float) (vector2[k] - resultSeed.getTranslationVectorToTranslateShape2ToOrigin().getEntry(k) + resultSeed.getTranslationVector().getEntry(k)); } double distance = MathTools.computeDistance(pointWithProperties1.getCoords().getCoords(), vector1); if (distance < algoParameters.getDISTANCE_MIN_FOR_EXTENDED_PAIRING_FROM_SEED()) { PairPointWithDistance pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance = new PairPointWithDistance( i, j, distance); int countOfMatchingStrikingPropertiesWhenAllAreMatching = StrikingPropertiesTools .evaluatePointsMatchingAllNotNoneProperties(pointWithProperties1, pointWithProperties2); if (countOfMatchingStrikingPropertiesWhenAllAreMatching > 0) { AddToMap.addElementToAMapOfList(mapforAllMatchingStrikingProperties, countOfMatchingStrikingPropertiesWhenAllAreMatching, pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); continue; } if (StrikingPropertiesTools.evaluatePointsMatchingOneButNotAllNotNoneProperties( pointWithProperties1, pointWithProperties2)) { listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance.add( pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); continue; } if (StrikingPropertiesTools.evaluatePointsMatchingOnlyNoneProperties(pointWithProperties1, pointWithProperties2)) { listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance.add( pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); continue; } if (StrikingPropertiesTools.evaluatePointsNoneMatchingANotNONEtoOnlyNoneProperties( pointWithProperties1, pointWithProperties2)) { listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance.add( pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); continue; } if (StrikingPropertiesTools.evaluatePointsNoneMatchingANotNONEtoNotNoneProperties( pointWithProperties1, pointWithProperties2)) { listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance.add( pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); continue; } } } } // for (Entry<Integer, List<PairPointWithDistance>> entry: mapforAllMatchingStrikingProperties.entrySet()){ // cleanListPairsFromPointsInvolvedInSeedPairings(resultSeed.getPairingAndNullSpaces(), entry.getValue()); // } // cleanListPairsFromPointsInvolvedInSeedPairings(resultSeed.getPairingAndNullSpaces(), listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance); // cleanListPairsFromPointsInvolvedInSeedPairings(resultSeed.getPairingAndNullSpaces(), listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance); // cleanListPairsFromPointsInvolvedInSeedPairings(resultSeed.getPairingAndNullSpaces(), listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance); // cleanListPairsFromPointsInvolvedInSeedPairings(resultSeed.getPairingAndNullSpaces(), listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance); for (Map.Entry<Integer, List<PairPointWithDistance>> entry : mapforAllMatchingStrikingProperties .entrySet()) { Collections.sort(entry.getValue(), new PairPointWithDistance.LowestDistancePairPointWithDistance()); } Collections.sort(listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance, new PairPointWithDistance.LowestDistancePairPointWithDistance()); Collections.sort(listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance, new PairPointWithDistance.LowestDistancePairPointWithDistance()); Collections.sort(listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance, new PairPointWithDistance.LowestDistancePairPointWithDistance()); Collections.sort(listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance, new PairPointWithDistance.LowestDistancePairPointWithDistance()); // loop on the list // when a point already found is found then skip the pair // for (Entry<Integer, List<PairPointWithDistance>> entry: mapforAllMatchingStrikingProperties.entrySet()){ // cleanOfDuplicatePoints(entry.getValue()); // } // cleanOfDuplicatePoints(listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance); // cleanOfDuplicatePoints(listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance); // cleanOfDuplicatePoints(listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance); // cleanOfDuplicatePoints(listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance); // Now I should try to pair unpaired point so far // clean the list of pairs matching distance but without matching properties OF pairs having points in matching properties list List<PairPointWithDistance> globalList = new ArrayList<>(); List<Integer> keys = new ArrayList<>(); keys.addAll(mapforAllMatchingStrikingProperties.keySet()); Collections.sort(keys, Collections.reverseOrder()); for (Integer key : keys) { globalList.addAll(mapforAllMatchingStrikingProperties.get(key)); } globalList.addAll(listPairsMatchingOneAmongOthersStrikingPropertiesWithShortDistance); globalList.addAll(listPairsMatchingOnlyNoneStrikingPropertiesWithShortDistance); globalList.addAll(listPairsNoneMatchingWithoutStrikingPropertiesWithShortDistance); globalList.addAll(listPairsNonMatchingWithoutStrikingPropertiesWithShortDistance); cleanOfDuplicatePoints(globalList); // now i can build the pairing // initial pairing might be on minishape and shape1 and aligned shape on a larger set like Shape //PairingAndNullSpaces newPairingAndNewNullSpaces = deepCopyNewPairingAndNewNullSpacesAndExtendIfNeeded(resultSeed.getPairingAndNullSpaces(), shape1, shape2); double newcost = 0.0; double newdistanceResidual = 0.0; RealMatrix newRotationMatrix = resultSeed.getRotationMatrix().copy(); RealVector newtranslationVector = resultSeed.getTranslationVector().copy(); RealVector newtranslationVectorToTranslateShape2ToOrigin = resultSeed .getTranslationVectorToTranslateShape2ToOrigin().copy(); Map<Integer, Integer> newpairing = new LinkedHashMap<>(); List<Integer> newnullSpaceOfMap1 = new ArrayList<>(); List<Integer> newnullSpaceOfMap2 = new ArrayList<>(); PairingAndNullSpaces newPairingAndNullSpaces = new PairingAndNullSpaces(newpairing, newnullSpaceOfMap1, newnullSpaceOfMap2); float newratioPairedPointInQuery = 0.0f; ResultsFromEvaluateCost extendedResult = new ResultsFromEvaluateCost(newcost, newdistanceResidual, newRotationMatrix, newtranslationVector, newtranslationVectorToTranslateShape2ToOrigin, newPairingAndNullSpaces, newratioPairedPointInQuery, algoParameters); fillNullSpaceMap1(shape1, extendedResult.getPairingAndNullSpaces()); fillNullSpaceMap2(shape2, extendedResult.getPairingAndNullSpaces()); // loop on new pairs and add Iterator<PairPointWithDistance> itr = globalList.iterator(); while (itr.hasNext()) { PairPointWithDistance pairPointWithDistance = itr.next(); if (pairPointWithDistance.getDistance() < 0.7) { // We really use the sorting for very short distances if (extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap1() .contains(Integer.valueOf(pairPointWithDistance.getPairInteger().point1)) && extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap2() .contains(Integer.valueOf(pairPointWithDistance.getPairInteger().point2))) { extendedResult.getPairingAndNullSpaces().getPairing().put( pairPointWithDistance.getPairInteger().point1, pairPointWithDistance.getPairInteger().point2); boolean toto = extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap1() .remove(Integer.valueOf(pairPointWithDistance.getPairInteger().point1)); boolean toto2 = extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap2() .remove(Integer.valueOf(pairPointWithDistance.getPairInteger().point2)); itr.remove(); } } } Collections.sort(globalList, new PairPointWithDistance.LowestDistancePairPointWithDistance()); Iterator<PairPointWithDistance> itr2 = globalList.iterator(); while (itr2.hasNext()) { PairPointWithDistance pairPointWithDistance = itr2.next(); if (extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap1() .contains(Integer.valueOf(pairPointWithDistance.getPairInteger().point1)) && extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap2() .contains(Integer.valueOf(pairPointWithDistance.getPairInteger().point2))) { extendedResult.getPairingAndNullSpaces().getPairing().put( pairPointWithDistance.getPairInteger().point1, pairPointWithDistance.getPairInteger().point2); boolean toto = extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap1() .remove(Integer.valueOf(pairPointWithDistance.getPairInteger().point1)); boolean toto2 = extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap2() .remove(Integer.valueOf(pairPointWithDistance.getPairInteger().point2)); } } if (debug == true) { boolean validPairing = PairingTools.validate(extendedResult.getPairingAndNullSpaces()); if (validPairing == false) { System.out.println("Extended pairing is not valid"); } // for debug I recheck if there are remaining short distance List<PairPointWithDistance> remainingShortDistance = new ArrayList<>(); for (Integer point1 : extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap1()) { PointWithPropertiesIfc pointWithProperties1 = shape1.getPointFromId(point1); for (Integer point2 : extendedResult.getPairingAndNullSpaces().getNullSpaceOfMap2()) { PointWithPropertiesIfc pointWithProperties2 = shape2.getPointFromId(point2); RealMatrix matrix = extendedResult.getRotationMatrix(); float[] vector1 = new float[3]; for (int k = 0; k < 3; k++) { vector1[k] = (float) (pointWithProperties2.getCoords().getCoords()[k] + extendedResult.getTranslationVectorToTranslateShape2ToOrigin().getEntry(k)); } double[] vector2 = new double[3]; for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { vector2[k] += matrix.getEntry(k, l) * vector1[l]; } } for (int k = 0; k < 3; k++) { vector1[k] = (float) (vector2[k] - extendedResult.getTranslationVectorToTranslateShape2ToOrigin().getEntry(k) + extendedResult.getTranslationVector().getEntry(k)); } double distance = MathTools.computeDistance(pointWithProperties1.getCoords().getCoords(), vector1); if (distance < algoParameters.getDISTANCE_MIN_FOR_EXTENDED_PAIRING_FROM_SEED()) { PairPointWithDistance pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance = new PairPointWithDistance( point1, point2, distance); remainingShortDistance.add( pairPointIdsFromMinishape1andMinishape2WithMatchingStrikingPropertiesWithDistance); //System.out.println(distance); } } } System.out.println("remainingShortDistance = " + remainingShortDistance.size()); if (remainingShortDistance.size() > 10) { System.out.println(); } } return extendedResult; }
From source file:org.projectforge.timesheet.TimesheetDao.java
public List<TimesheetDO> getTimeperiodOverlapList(final TimesheetListFilter actionFilter) { if (actionFilter.getUserId() != null) { final QueryFilter queryFilter = new QueryFilter(actionFilter); final Set<Integer> set = getTimesheetsWithTimeoverlap(actionFilter.getUserId()); if (set == null || set.size() == 0) { // No time sheets with overlap found. return new ArrayList<TimesheetDO>(); }// w w w .j a v a2 s . c o m queryFilter.add(Restrictions.in("id", set)); final List<TimesheetDO> result = getList(queryFilter); for (final TimesheetDO entry : result) { entry.setMarked(true); } Collections.sort(result, Collections.reverseOrder()); return result; } return getList(actionFilter); }