List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:org.pgptool.gui.ui.importkey.KeyImporterPm.java
private boolean loadKey(File[] filesToLoad) { try {/*from w w w .j a va 2 s . c o m*/ Map<String, Throwable> exceptions = new HashMap<>(); List<Key> loadedKeys = loadKeysSafe(filesToLoad, exceptions); if (exceptions.size() > 0) { String msg = buildSummaryMessage("error.keysLoadedStatistics", loadedKeys.size(), exceptions); UiUtils.messageBox(null, msg, Messages.get("term.attention"), JOptionPane.ERROR_MESSAGE); } if (loadedKeys.size() > 0) { loadedKeys.sort(keySorterByNameAsc); keys.getList().addAll(loadedKeys); actionDoImport.setEnabled(true); return true; } } catch (Throwable t) { EntryPoint.reportExceptionToUser("exception.failedToReadKey", t); } return false; }
From source file:com.thoughtworks.go.server.service.UserService.java
public List<UserModel> allUsersForDisplay(SortableColumn column, SortDirection direction) { List<UserModel> userModels = allUsersForDisplay(); Comparator<UserModel> userModelComparator = direction.forColumn(column); userModels.sort(userModelComparator); return userModels; }
From source file:io.warp10.script.WarpScriptLib.java
public static void registerExtensions() { Properties props = WarpConfig.getProperties(); if (null == props) { return;/* w w w .j av a2s . c om*/ } // // Extract the list of extensions // Set<String> ext = new LinkedHashSet<String>(); if (props.containsKey(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS)) { String[] extensions = props.getProperty(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS).split(","); for (String extension : extensions) { ext.add(extension.trim()); } } for (Object key : props.keySet()) { if (!key.toString().startsWith(Configuration.CONFIG_WARPSCRIPT_EXTENSION_PREFIX)) { continue; } ext.add(props.get(key).toString().trim()); } // Sort the extensions List<String> sortedext = new ArrayList<String>(ext); sortedext.sort(null); boolean failedExt = false; // // Determine the possible jar from which WarpScriptLib was loaded // String wsljar = null; URL wslurl = WarpScriptLib.class .getResource('/' + WarpScriptLib.class.getCanonicalName().replace('.', '/') + ".class"); if (null != wslurl && "jar".equals(wslurl.getProtocol())) { wsljar = wslurl.toString().replaceAll("!/.*", "").replaceAll("jar:file:", ""); } for (String extension : sortedext) { // If the extension name contains '#', remove everything up to the last '#', this was used as a sorting prefix if (extension.contains("#")) { extension = extension.replaceAll("^.*#", ""); } try { // // Locate the class using the current class loader // URL url = WarpScriptLib.class.getResource('/' + extension.replace('.', '/') + ".class"); if (null == url) { LOG.error("Unable to load extension '" + extension + "', make sure it is in the class path."); failedExt = true; continue; } Class cls = null; // // If the class was located in a jar, load it using a specific class loader // so we can have fat jars with specific deps, unless the jar is the same as // the one from which WarpScriptLib was loaded, in which case we use the same // class loader. // if ("jar".equals(url.getProtocol())) { String jarfile = url.toString().replaceAll("!/.*", "").replaceAll("jar:file:", ""); ClassLoader cl = WarpScriptLib.class.getClassLoader(); // If the jar differs from that from which WarpScriptLib was loaded, create a dedicated class loader if (!jarfile.equals(wsljar)) { cl = new WarpClassLoader(jarfile, WarpScriptLib.class.getClassLoader()); } cls = Class.forName(extension, true, cl); } else { cls = Class.forName(extension, true, WarpScriptLib.class.getClassLoader()); } //Class cls = Class.forName(extension); WarpScriptExtension wse = (WarpScriptExtension) cls.newInstance(); wse.register(); System.out.println("LOADED extension '" + extension + "'"); } catch (Exception e) { throw new RuntimeException(e); } } if (failedExt) { throw new RuntimeException("Some WarpScript extensions could not be loaded, aborting."); } }
From source file:org.apache.samza.system.hdfs.partitioner.DirectoryPartitioner.java
private List<FileMetadata> getFilteredFiles(String streamName) { List<FileMetadata> filteredFiles = new ArrayList<>(); List<FileMetadata> allFiles = fileSystemAdapter.getAllFiles(streamName); LOG.info(String.format("List of all files for %s: %s", streamName, allFiles)); allFiles.stream()//w w w . j a v a2s. c o m .filter(file -> file.getPath().matches(whiteListRegex) && !file.getPath().matches(blackListRegex)) .forEach(filteredFiles::add); // sort the files to have a consistent order filteredFiles.sort((f1, f2) -> f1.getPath().compareTo(f2.getPath())); LOG.info(String.format("List of filtered files for %s: %s", streamName, filteredFiles)); return filteredFiles; }
From source file:pcgen.gui2.sources.AdvancedSourceSelectionPanel.java
public void setSourceSelection(SourceSelectionFacade sources) { if (sources == null || sources.getGameMode() == null) { Logging.errorPrint("Invalid source selection " + sources + "- ignoring."); return;//from w w w .java2 s. co m } GameModeFacade selectedGame = sources.getGameMode().get(); for (int i = 0; i < gameModeList.getModel().getSize(); i++) { GameModeDisplayFacade gmdf = (GameModeDisplayFacade) gameModeList.getModel().getElementAt(i); if (gmdf.getGameMode() == selectedGame) { gameModeList.setSelectedItem(gmdf); } } List<CampaignFacade> wrap = new ArrayList<>(ListFacades.wrap(sources.getCampaigns())); wrap.sort(Comparators.toStringIgnoreCaseCollator()); selectedCampaigns.setContents(wrap); }
From source file:eu.project.ttc.engines.morpho.CompostAE.java
@Override public void collectionProcessComplete() throws AnalysisEngineProcessException { SubTaskObserver observer = observerResource.getTaskObserver(TASK_NAME); observer.setTotalTaskWork(termIndexResource.getTermIndex().getWords().size()); LOGGER.info("Starting morphologyical compound detection for TermIndex {}", this.termIndexResource.getTermIndex().getName()); LOGGER.debug(this.toString()); wrMeasure = termIndexResource.getTermIndex().getWRMeasure(); swtLemmaIndex = termIndexResource.getTermIndex().getCustomIndex(TermIndexes.SINGLE_WORD_LEMMA); buildCompostIndex();/*w ww.j a va2s. c o m*/ final MutableLong cnt = new MutableLong(0); Timer progressLoggerTimer = new Timer("Morphosyntactic splitter AE"); progressLoggerTimer.schedule(new TimerTask() { @Override public void run() { int total = termIndexResource.getTermIndex().getWords().size(); CompostAE.LOGGER.info("Progress: {}% ({} on {})", String.format("%.2f", ((float) cnt.longValue() * 100) / total), cnt.longValue(), total); } }, 5000l, 5000l); int observingStep = 100; for (Term swt : termIndexResource.getTermIndex().getTerms()) { if (!swt.isSingleWord()) continue; cnt.increment(); if (cnt.longValue() % observingStep == 0) { observer.work(observingStep); } /* * Do not do native morphology splitting * if a composition already exists. */ Word word = swt.getWords().get(0).getWord(); if (word.isCompound()) continue; Map<Segmentation, Double> scores = computeScores(word.getLemma()); if (scores.size() > 0) { List<Segmentation> segmentations = Lists.newArrayList(scores.keySet()); /* * compare segmentations in a deterministic way. */ segmentations.sort(new Comparator<Segmentation>() { @Override public int compare(Segmentation o1, Segmentation o2) { int comp = Double.compare(scores.get(o2), scores.get(o1)); if (comp != 0) return comp; comp = Integer.compare(o1.getSegments().size(), o2.getSegments().size()); if (comp != 0) return comp; for (int i = 0; i < o1.getSegments().size(); i++) { comp = Integer.compare(o2.getSegments().get(i).getEnd(), o1.getSegments().get(i).getEnd()); if (comp != 0) return comp; } return 0; } }); Segmentation bestSegmentation = segmentations.get(0); // build the word component from segmentation WordBuilder builder = new WordBuilder(word); for (Segment seg : bestSegmentation.getSegments()) { String lemma = segmentLemmaCache.getUnchecked(seg.getLemma()); builder.addComponent(seg.getBegin(), seg.getEnd(), lemma); if (seg.isNeoclassical()) builder.setCompoundType(CompoundType.NEOCLASSICAL); else builder.setCompoundType(CompoundType.NATIVE); } builder.create(); // log the word composition if (LOGGER.isTraceEnabled()) { List<String> componentStrings = Lists.newArrayList(); for (Component component : word.getComponents()) componentStrings.add(component.toString()); LOGGER.trace("{} [{}]", word.getLemma(), Joiner.on(' ').join(componentStrings)); } } } //finalize progressLoggerTimer.cancel(); LOGGER.debug("segment score cache size: {}", segmentScoreEntries.size()); LOGGER.debug("segment score hit count: " + segmentScoreEntries.stats().hitCount()); LOGGER.debug("segment score hit rate: " + segmentScoreEntries.stats().hitRate()); LOGGER.debug("segment score eviction count: " + segmentScoreEntries.stats().evictionCount()); termIndexResource.getTermIndex().dropCustomIndex(TermIndexes.SINGLE_WORD_LEMMA); segmentScoreEntries.invalidateAll(); segmentLemmaCache.invalidateAll(); }
From source file:org.pgptool.gui.ui.encryptone.EncryptOnePm.java
private void initModelProperties() { sourceFile = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(), "sourceFile"); sourceFile.getModelPropertyAccessor().addPropertyChangeListener(onSourceFileModified); isUseSameFolder = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(true), "saveToSameFolder"); isUseSameFolder.getModelPropertyAccessor().addPropertyChangeListener(onUseSameFolderChanged); targetFile = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(), "targetFile"); targetFile.getModelPropertyAccessor().addPropertyChangeListener(onTargetFileChanged); targetFileEnabled = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(), "targetFile"); List<Key> allKeys = keyRingService.readKeys(); allKeys.sort(new ComparatorKeyByNameImpl()); availabileRecipients = new ModelListProperty<Key>(this, new ValueAdapterReadonlyImpl<List<Key>>(allKeys), "availabileRecipients"); selectedRecipients = new ModelMultSelInListProperty<Key>(this, new ValueAdapterHolderImpl<List<Key>>(new ArrayList<Key>()), "projects", availabileRecipients); selectedRecipients.getModelMultSelInListPropertyAccessor() .addListExEventListener(onRecipientsSelectionChanged); isNoPrivateKeysSelected = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(), "isNoPrivateKeysSelected"); onRecipientsSelectionChanged.onListChanged(); isDeleteSourceAfter = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(false), "deleteSourceAfter"); isOpenTargetFolderAfter = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(false), "openTargetFolder"); onUseSameFolderChanged.propertyChange(null); isDisableControls = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(false), "isDisableControls"); isProgressVisible = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(false), "isProgressVisible"); progressValue = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(0), "progressValue"); progressNote = new ModelProperty<>(this, new ValueAdapterHolderImpl<>(""), "progressNote"); progressHandler = new ProgressHandlerPmMixinImpl(isProgressVisible, progressValue, progressNote); }
From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.java
public static void produceLCMSPathwayHeatmaps(File lcmsDir, String outData, String outImg, String outAnalysis, List<ChemicalAssociatedWithPathway> pathwayChems, Pair<List<ScanData<StandardWell>>, Double> allStandardScans, Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans, Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans, Double fontScale, boolean makeHeatmaps, Map<Integer, String> searchIons) throws Exception { String fmt = "pdf"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); // Generate the data file and graphs. try (FileOutputStream fos = new FileOutputStream(outData)) { List<String> graphLabels = new ArrayList<>(); List<Double> yMaxList = new ArrayList<>(); List<String> pathwayProductHeaderFields = new ArrayList<>(); for (PATHWAY_PRODUCT_HEADER_FIELDS field : PATHWAY_PRODUCT_HEADER_FIELDS.values()) { pathwayProductHeaderFields.add(field.name()); }//from w w w .j a v a 2 s. co m TSVWriter<String, String> resultsWriter = new TSVWriter<>(pathwayProductHeaderFields); resultsWriter.open(new File(outAnalysis)); for (ChemicalAssociatedWithPathway chem : pathwayChems) { System.out.format("Processing data for pathway chemical %s\n", chem.getChemical()); Double maxIntensity = 0.0d; String pathwayStepIon = null; if (searchIons != null && searchIons.containsKey(chem.getId())) { pathwayStepIon = searchIons.get(chem.getId()); } MS1.IonMode mode = MS1.getIonModeOfIon(pathwayStepIon); // Extract the first available List<ScanData<StandardWell>> stdScan = new ArrayList<>(); for (ScanData<StandardWell> scan : allStandardScans.getLeft()) { if (chem.getChemical().equals(scan.getWell().getChemical()) && chem.getChemical().equals(scan.getTargetChemicalName())) { if (mode.toString().toLowerCase() .equals(scan.getScanFile().getMode().toString().toLowerCase())) { stdScan.add(scan); MS1ScanForWellAndMassCharge scanResults = scan.getMs1ScanResults(); Double intensity = pathwayStepIon == null ? scanResults.getMaxYAxis() : scanResults.getMaxIntensityForIon(pathwayStepIon); if (intensity != null) { maxIntensity = Math.max(maxIntensity, intensity); } } } } if (stdScan.size() == 0) { System.err.format("WARNING: unable to find standard well scan for chemical %s\n", chem.getChemical()); } List<ScanData<LCMSWell>> matchingPosScans = new ArrayList<>(); for (ScanData<LCMSWell> scan : allPositiveScans.getLeft()) { if (chem.getChemical().equals(scan.getTargetChemicalName())) { if (mode.toString().toLowerCase() .equals(scan.getScanFile().getMode().toString().toLowerCase())) { matchingPosScans.add(scan); MS1ScanForWellAndMassCharge scanResults = scan.getMs1ScanResults(); Double intensity = pathwayStepIon == null ? scanResults.getMaxYAxis() : scanResults.getMaxIntensityForIon(pathwayStepIon); if (intensity != null) { maxIntensity = Math.max(maxIntensity, intensity); } } } } matchingPosScans.sort(LCMS_SCAN_COMPARATOR); List<ScanData<LCMSWell>> matchingNegScans = new ArrayList<>(); for (ScanData<LCMSWell> scan : allNegativeScans.getLeft()) { if (chem.getChemical().equals(scan.getTargetChemicalName())) { if (mode.toString().toLowerCase() .equals(scan.getScanFile().getMode().toString().toLowerCase())) { matchingNegScans.add(scan); MS1ScanForWellAndMassCharge scanResults = scan.getMs1ScanResults(); Double intensity = pathwayStepIon == null ? scanResults.getMaxYAxis() : scanResults.getMaxIntensityForIon(pathwayStepIon); if (intensity != null) { maxIntensity = Math.max(maxIntensity, intensity); } } } } matchingNegScans.sort(LCMS_SCAN_COMPARATOR); List<ScanData> allScanData = new ArrayList<>(); List<ScanData<LCMSWell>> positiveAndNegativeData = new ArrayList<>(); positiveAndNegativeData.addAll(matchingPosScans); positiveAndNegativeData.addAll(matchingNegScans); allScanData.addAll(stdScan); allScanData.addAll(positiveAndNegativeData); allScanData.add(BLANK_SCAN); Map<ScanData<LCMSWell>, XZ> result = WaveformAnalysis .pickBestRepresentativeRetentionTimeFromStandardWells(stdScan, pathwayStepIon, positiveAndNegativeData); WriteAndPlotMS1Results.writePathwayProductOutput(resultsWriter, chem.getChemical(), positiveAndNegativeData, pathwayStepIon, result); Set<String> pathwayStepIons = pathwayStepIon == null ? null : Collections.singleton(pathwayStepIon); // Write all the scan data out to a single data file. for (ScanData scanData : allScanData) { graphLabels.addAll(AnalysisHelper.writeScanData(fos, lcmsDir, maxIntensity, scanData, makeHeatmaps, false, pathwayStepIons)); } // Save one max intensity per graph so we can plot with them later. for (ScanData<LCMSWell> scan : allScanData) { if (!scan.getKind().equals(ScanData.KIND.BLANK)) { Double intensity = pathwayStepIon == null ? scan.getMs1ScanResults().getMaxYAxis() : scan.getMs1ScanResults().getMaxIntensityForIon(pathwayStepIon); yMaxList.add(intensity); } else { // Add a 0 intensity for the blank scan yMaxList.add(0.0d); } } } resultsWriter.close(); // We need to pass the yMax values as an array to the Gnuplotter. Double[] yMaxes = yMaxList.toArray(new Double[yMaxList.size()]); Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale); if (makeHeatmaps) { plotter.plotHeatmap(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), null, fmt, 11.0, 8.5, yMaxes, outImg + ".gnuplot"); } else { plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time", null, "intensity", fmt, null, null, yMaxes, outImg + ".gnuplot"); } } }
From source file:com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand.java
private void commandDocs(StringBuilder result) { List<ParameterDescription> parameters = commander.getParameters(); parameters.sort(Comparator.comparing(ParameterDescription::getNames)); int parameterCount = 0; for (ParameterDescription parameter : parameters) { if (GlobalOptions.isGlobalOption(parameter.getLongestName())) { parameterCount++;/*from www . jav a2 s. co m*/ } } String longDescription = getLongDescription() != null ? getLongDescription() : getDescription(); result.append("## ").append(fullCommandName).append("\n\n").append(longDescription).append("\n\n") .append("#### Usage").append("\n```\n").append(fullCommandName); ParameterDescription mainParameter = commander.getMainParameter(); if (mainParameter != null) { result.append(" ").append(getMainParameter().toUpperCase()); } if (parameters.size() > parameterCount) { result.append(" [parameters]"); } if (!subcommands.isEmpty()) { result.append(" [subcommands]"); } result.append("\n```\n"); if (!parameters.isEmpty()) { if (getCommandName() == "hal") { result.append("#### Global Parameters\n"); } for (ParameterDescription parameter : parameters) { if (GlobalOptions.isGlobalOption(parameter.getLongestName())) { // Omit printing global parameters for everything but the top-level command if (getCommandName() == "hal") { parameterDoc(result, parameter); } } } result.append("\n"); } if (parameters.size() > parameterCount) { result.append("#### Parameters\n"); if (mainParameter != null) { result.append('`').append(getMainParameter().toUpperCase()).append('`').append(": ") .append(mainParameter.getDescription()).append("\n"); } for (ParameterDescription parameter : parameters) { if (!GlobalOptions.isGlobalOption(parameter.getLongestName())) { parameterDoc(result, parameter); } } result.append("\n"); } if (!subcommands.isEmpty()) { result.append("#### Subcommands\n"); List<String> keys = new ArrayList<>(subcommands.keySet()); keys.sort(String::compareTo); for (String key : keys) { NestableCommand subcommand = subcommands.get(key); String modifiers = ""; if (subcommand instanceof DeprecatedCommand) { modifiers += " _(Deprecated)_ "; } String shortDescription = subcommand.getShortDescription() != null ? subcommand.getShortDescription() : subcommand.getDescription(); result.append(" * ").append("`").append(key).append("`").append(modifiers).append(": ") .append(shortDescription).append("\n"); } } result.append("\n---\n"); }
From source file:org.cloudsimplus.sla.responsetime.CloudletResponseTimeMinimizationExperiment.java
/** * Selects a VM to run a Cloudlet that will minimize the Cloudlet response * time.//from w w w. j a va 2s .co m * * @param cloudlet the Cloudlet to select a VM to * @return the selected Vm */ private Vm selectVmForCloudlet(Cloudlet cloudlet) { List<Vm> createdVms = cloudlet.getBroker().getVmsCreatedList(); Log.printLine("\t\tCreated VMs: " + createdVms); Comparator<Vm> sortByNumberOfFreePes = Comparator.comparingInt(vm -> getExpectedNumberOfFreeVmPes(vm)); Comparator<Vm> sortByExpectedCloudletResponseTime = Comparator .comparingDouble(vm -> getExpectedCloudletResponseTime(cloudlet, vm)); createdVms.sort(sortByNumberOfFreePes.thenComparing(sortByExpectedCloudletResponseTime).reversed()); Vm mostFreePesVm = createdVms.stream().findFirst().orElse(Vm.NULL); Vm selectedVm = createdVms.stream() .filter(vm -> getExpectedNumberOfFreeVmPes(vm) >= cloudlet.getNumberOfPes()) .filter(vm -> getExpectedCloudletResponseTime(cloudlet, vm) <= responseTimeSlaContract).findFirst() .orElse(mostFreePesVm); return selectedVm; }