auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes attributes) { URI requestUri = request.getURI(); String servicePrincipal = makeServicePrincipal(remoteServiceName, requestUri.getHost()); GSSContext context = doAs(loginContext.getSubject(), () -> { GSSContext result = GSS_MANAGER.createContext( GSS_MANAGER.createName(servicePrincipal, null), SPNEGO_OID, clientCredential, INDEFINITE_LIFETIME); result.requestMutualAuth(true); result.requestConf(true); result.requestInteg(true); result.requestCredDeleg(false); return result; }); try { byte[] token = context.initSecContext(new byte[0], 0, 0); if (token == null) { throw new AuthenticationException(format("Failed to establish GSSContext for request %s", requestUri)); } return new SpnegoResult( UriUtil.normalizedUri(requestUri), headerInfo.getHeader(), format("%s %s", NEGOTIATE, Base64.getEncoder().encodeToString(token))); } catch (GSSException e) { throw new AuthenticationException(format("Failed to establish GSSContext for request %s", requestUri), e); } finally { try { context.dispose(); } catch (GSSException e) { } } }

Target:
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes attributes) { URI requestUri = request.getURI(); String servicePrincipal = makeServicePrincipal(remoteServiceName, requestUri.getHost()); GSSContext context = doAs(loginContext.getSubject(), () -> { GSSContext result = GSS_MANAGER.createContext( GSS_MANAGER.createName(servicePrincipal, null), SPNEGO_OID, clientCredential, INDEFINITE_LIFETIME); result.requestMutualAuth(true); result.requestConf(true); result.requestInteg(true); result.requestCredDeleg(false); return result; }); try { byte[] token = context.initSecContext(new byte[0], 0, 0); if (token == null) { throw new AuthenticationException(format("No token generated from GSSContext for request %s", requestUri)); } return new SpnegoResult( UriUtil.normalizedUri(requestUri), headerInfo.getHeader(), format("%s %s", NEGOTIATE, Base64.getEncoder().encodeToString(token))); } catch (GSSException e) { throw new AuthenticationException(format("Failed to establish GSSContext for request %s", requestUri), e); } finally { try { context.dispose(); } catch (GSSException e) { } } }
Source:
public void setUp() { if (CASE_DIRECTORY_PATH.toFile().exists()) { try { FileUtils.deleteDirectory(CASE_DIRECTORY_PATH.toFile()); } catch (IOException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } } assertFalse("Unable to delete existing test directory", CASE_DIRECTORY_PATH.toFile().exists()); CASE_DIRECTORY_PATH.toFile().mkdirs(); assertTrue("Unable to create test directory", CASE_DIRECTORY_PATH.toFile().exists()); try { Case.createAsCurrentCase(Case.CaseType.SINGLE_USER_CASE, CASE_DIRECTORY_PATH.toString(), new CaseDetails(CASE_NAME)); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } assertTrue(CASE_DIR.exists()); ImageDSProcessor dataSourceProcessor = new ImageDSProcessor(); try { ProcessorCallback callBack = DataSourceProcessorRunner.runDataSourceProcessor(dataSourceProcessor, IMAGE_PATH); List<Content> dataSourceContent = callBack.getDataSourceContent(); assertEquals(1, dataSourceContent.size()); List<String> errorMessages = callBack.getErrorMessages(); assertEquals(0, errorMessages.size()); } catch (AutoIngestDataSourceProcessor.AutoIngestDataSourceProcessorException | InterruptedException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }

Target:
public void setUp() { if (CASE_DIRECTORY_PATH.toFile().exists()) { try { FileUtils.deleteDirectory(CASE_DIRECTORY_PATH.toFile()); } catch (IOException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } } assertFalse(String.format("Unable to delete existing test directory '%s'.", CASE_DIRECTORY_PATH.toString()), CASE_DIRECTORY_PATH.toFile().exists()); CASE_DIRECTORY_PATH.toFile().mkdirs(); assertTrue(String.format("Unable to create test directory '%s'.", CASE_DIRECTORY_PATH.toString()), CASE_DIRECTORY_PATH.toFile().exists()); try { Case.createAsCurrentCase(Case.CaseType.SINGLE_USER_CASE, CASE_DIRECTORY_PATH.toString(), new CaseDetails(CASE_NAME)); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } assertTrue(CASE_DIR.exists()); ImageDSProcessor dataSourceProcessor = new ImageDSProcessor(); try { ProcessorCallback callBack = DataSourceProcessorRunner.runDataSourceProcessor(dataSourceProcessor, IMAGE_PATH); List<Content> dataSourceContentList = callBack.getDataSourceContent(); String errorMessage = String.format("The data source processor callback should produce 1 data source Content object, but the actual count was %d.", dataSourceContentList.size()); assertEquals(errorMessage, 1, dataSourceContentList.size()); List<String> callbackErrorMessageList = callBack.getErrorMessages(); errorMessage = String.format("The data source processor callback produced %d error messages.", callbackErrorMessageList.size()); assertEquals(errorMessage, 0, callbackErrorMessageList.size()); } catch (AutoIngestDataSourceProcessor.AutoIngestDataSourceProcessorException | InterruptedException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }
Source:
public void doTable(Parse table) { super.doTable(table); if(counts.wrong == 0 && counts.exceptions == 0) { table.parts.more = this.getSummary(); } }

Target:
public void doTable(Parse table) { super.doTable(table); table.parts.last().more = getSummary(); }
Source:
public void dispose () { if (parent != null && !parent.isDisposed()) { for (int element : EVENTS) { parent.removeListener (element, controlListener); } ScrollBar hBar = parent.getHorizontalBar (); if (hBar != null) hBar.removeListener (SWT.Selection, scrollbarListener); ScrollBar vBar = parent.getVerticalBar (); if (vBar != null) vBar.removeListener (SWT.Selection, scrollbarListener); } parent = null; editor = null; hadFocus = false; controlListener = null; scrollbarListener = null; }

Target:
public void dispose () { if (parent != null && !parent.isDisposed()) { for (int event : EVENTS) { parent.removeListener (event, controlListener); } ScrollBar hBar = parent.getHorizontalBar (); if (hBar != null) hBar.removeListener (SWT.Selection, scrollbarListener); ScrollBar vBar = parent.getVerticalBar (); if (vBar != null) vBar.removeListener (SWT.Selection, scrollbarListener); } parent = null; editor = null; hadFocus = false; controlListener = null; scrollbarListener = null; }
Source:
protected Command doGetCommand(Request request, EditPart targetEditPart) { boolean canHandle = false; if (!(targetEditPart instanceof DiagramEditPart) && !(targetEditPart instanceof CompartmentEditPart)) { if (request instanceof DropObjectsRequest && !getSourceEObjects(request).isEmpty()) { List<Collaboration> droppedProtocols = getSourceEObjects(request).stream().filter(Collaboration.class::isInstance) .map(Collaboration.class::cast) .collect(Collectors.toList()); if (droppedProtocols != null && !droppedProtocols.isEmpty()) { canHandle = canDrop(droppedProtocols); } } } return canHandle ? super.doGetCommand(request, targetEditPart) : null; }

Target:
protected Command doGetCommand(Request request, EditPart targetEditPart) { boolean canHandle = false; if (!(targetEditPart instanceof DiagramEditPart) && !(targetEditPart instanceof CompartmentEditPart)) { if (request instanceof DropObjectsRequest && !getSourceEObjects(request).isEmpty()) { List<Collaboration> droppedProtocols = getSourceEObjects(request).stream().filter(Collaboration.class::isInstance) .map(Collaboration.class::cast) .collect(Collectors.toList()); if (!droppedProtocols.isEmpty()) { canHandle = canDrop(droppedProtocols); } } } return canHandle ? super.doGetCommand(request, targetEditPart) : null; }
Source:
private List<LicensedComponent> createLicensedComponents() { final List<LicensedComponent> components = new ArrayList<>(); try { components.add(LicensedComponent.create("DMDirc", getLicences(FileUtils .getPathForResource(getClass().getResource("/com/dmdirc/licences"))))); pluginManager.getPluginInfos().forEach(p -> { final List<Licence> componentLicences = getLicences( p.getPath("/META-INF/licenses/")); if (!componentLicences.isEmpty()) { components.add(LicensedComponent .create(p.getMetaData().getFriendlyName(), componentLicences)); } } ); } catch (URISyntaxException ex) { LOGGER.warn("Unable to create component", ex); } return components; }

Target:
private List<LicensedComponent> createLicensedComponents() { final List<LicensedComponent> components = new ArrayList<>(); try { components.add(LicensedComponent.create("DMDirc", getLicences(FileUtils .getPathForResource(getClass().getResource("/com/dmdirc/licences"))))); pluginManager.getPluginInfos().forEach(p -> { final List<Licence> componentLicences = getLicences( p.getPath("/META-INF/licences/")); if (!componentLicences.isEmpty()) { components.add(LicensedComponent .create(p.getMetaData().getFriendlyName(), componentLicences)); } } ); } catch (URISyntaxException ex) { LOGGER.warn("Unable to create component", ex); } return components; }
Source:
public static String getMessagesFromThrowable(Throwable t){ final StringBuilder buf = new StringBuilder(); if (t.getLocalizedMessage() != null) { buf.append(t.getLocalizedMessage()); } else { buf.append(t.getClass().getName()); } Throwable t1 = t.getCause(); while (t1 != null) { if (t1.getLocalizedMessage() != null) { buf.append(": ").append(t1.getLocalizedMessage()); } else { buf.append(": ").append(t1.getClass().getName()); } t1 = t1.getCause(); } for (Throwable suppressed : t.getSuppressed()) { buf.append("\n").append(suppressed.getLocalizedMessage()); } return buf.toString(); }

Target:
public static String getMessagesFromThrowable(Throwable t){ final StringBuilder buf = new StringBuilder(); if (t.getLocalizedMessage() != null) { buf.append(t.getLocalizedMessage()); } else { buf.append(t.getClass().getName()); } Throwable t1 = t.getCause(); while (t1 != null) { if (t1.getLocalizedMessage() != null) { buf.append(": ").append(t1.getLocalizedMessage()); } else { buf.append(": ").append(t1.getClass().getName()); } t1 = t1.getCause(); } for (Throwable suppressed : t.getSuppressed()) { if (suppressed.getLocalizedMessage() != null) { buf.append("\n").append(suppressed.getLocalizedMessage()); } else { buf.append("\n").append(suppressed.getClass().getName()); } } return buf.toString(); }
Source:
public static File createOutputFile(File folderFile, String fileName, String prefix) throws IOException { if (folderFile == null) { throw new IllegalArgumentException("Incorrect path to folder."); } if (fileName == null || fileName.trim().isEmpty()) { throw new IllegalArgumentException("Incorrect file name"); } if (prefix == null) { throw new IllegalArgumentException("Incorrect prefix is used"); } StringBuilder resultPath = new StringBuilder(); resultPath.append(folderFile.getAbsoluteFile().getAbsolutePath()) .append(File.separator) .append(prefix); String extension = getExtension(fileName, resultPath); return createOutputFile(resultPath.toString(), extension, 0); }

Target:
public static File createOutputFile(File folderFile, String fileName, String prefix) { if (folderFile == null) { throw new IllegalArgumentException("Incorrect path to folder."); } if (fileName == null || fileName.trim().isEmpty()) { throw new IllegalArgumentException("Incorrect file name"); } if (prefix == null) { throw new IllegalArgumentException("Incorrect prefix is used"); } StringBuilder resultPath = new StringBuilder(); resultPath.append(folderFile.getAbsoluteFile().getAbsolutePath()) .append(File.separator) .append(prefix); String extension = getExtension(fileName, resultPath); return createOutputFile(resultPath.toString(), extension, 0); }
Source:
public static void setSchemaSupplier(Supplier<AvroSchemaHolder> factory) { if (threadSchemaSupplierFactory == null) { threadSchemaSupplierFactory = new ThreadLocal<Supplier<AvroSchemaHolder>>(); } if (LazyAvroCoder.threadSchemaSupplierFactory.get() != null) { throw BeamAdapterErrorCode.createSchemaSupplierAlreadyExists(null, threadSchemaSupplierFactory.get().toString()); } threadSchemaSupplierFactory.set(factory); }

Target:
public static void setSchemaSupplier(Supplier<AvroSchemaHolder> factory) { if (threadSchemaSupplierFactory == null) { threadSchemaSupplierFactory = new ThreadLocal<Supplier<AvroSchemaHolder>>(); } else if (LazyAvroCoder.threadSchemaSupplierFactory.get() != null) { throw BeamAdapterErrorCode.createSchemaSupplierAlreadyExists(null, threadSchemaSupplierFactory.get().toString()); } threadSchemaSupplierFactory.set(factory); }
Source:
private NMFTrainer(final ParameterWorker<Integer, Vector, Vector> parameterWorker, final VectorFactory vectorFactory, @Parameter(Rank.class) final int rank, @Parameter(StepSize.class) final double stepSize, @Parameter(Lambda.class) final double lambda, @Parameter(DecayRate.class) final double decayRate, @Parameter(DecayPeriod.class) final int decayPeriod, @Parameter(Parameters.MiniBatchSize.class) final int miniBatchSize, @Parameter(PrintMatrices.class) final boolean printMatrices, final NMFModelGenerator modelGenerator, final MemoryStore<Long> memoryStore, final TrainingDataProvider<Long, NMFData> trainingDataProvider, final MetricsMsgSender<WorkerMetrics> metricsMsgSender) { this.parameterWorker = parameterWorker; this.vectorFactory = vectorFactory; this.rank = rank; this.stepSize = stepSize; this.lambda = lambda; this.decayRate = decayRate; if (decayRate < 0.0 || decayRate > 1.0) { throw new RuntimeException("decay_rate must be a value between 0 and 1"); } this.decayPeriod = decayPeriod; if (decayPeriod < 0) { throw new RuntimeException("decay_period must a non-negative value"); } this.miniBatchSize = miniBatchSize; this.printMatrices = printMatrices; this.modelGenerator = modelGenerator; this.memoryStore = memoryStore; this.trainingDataProvider = trainingDataProvider; this.metricsMsgSender = metricsMsgSender; this.rMatrix = Maps.newHashMap(); this.gradients = Maps.newHashMap(); this.pushTracer = new Tracer(); this.pullTracer = new Tracer(); this.computeTracer = new Tracer(); }

Target:
private NMFTrainer(final ParameterWorker<Integer, Vector, Vector> parameterWorker, final VectorFactory vectorFactory, @Parameter(Rank.class) final int rank, @Parameter(StepSize.class) final double stepSize, @Parameter(Lambda.class) final double lambda, @Parameter(DecayRate.class) final double decayRate, @Parameter(DecayPeriod.class) final int decayPeriod, @Parameter(Parameters.MiniBatchSize.class) final int miniBatchSize, @Parameter(PrintMatrices.class) final boolean printMatrices, final NMFModelGenerator modelGenerator, final MemoryStore<Long> memoryStore, final TrainingDataProvider<Long, NMFData> trainingDataProvider, final MetricsMsgSender<WorkerMetrics> metricsMsgSender) { this.parameterWorker = parameterWorker; this.vectorFactory = vectorFactory; this.rank = rank; this.stepSize = stepSize; this.lambda = lambda; this.decayRate = decayRate; if (decayRate <= 0.0 || decayRate > 1.0) { throw new IllegalArgumentException("decay_rate must be larger than 0 and less than or equal to 1"); } this.decayPeriod = decayPeriod; if (decayPeriod <= 0) { throw new IllegalArgumentException("decay_period must be a positive value"); } this.miniBatchSize = miniBatchSize; this.printMatrices = printMatrices; this.modelGenerator = modelGenerator; this.memoryStore = memoryStore; this.trainingDataProvider = trainingDataProvider; this.metricsMsgSender = metricsMsgSender; this.rMatrix = Maps.newHashMap(); this.gradients = Maps.newHashMap(); this.pushTracer = new Tracer(); this.pullTracer = new Tracer(); this.computeTracer = new Tracer(); }
Source:
public void testAddSubrepoWithDirNoGitlinks() throws Exception { createNestedRepo("nested-repo"); StoredConfig config = db.getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_DIRNOGITLINKS, true); config.save(); assert (db.getConfig().get(WorkingTreeOptions.KEY).isDirNoGitLinks()); try (Git git = new Git(db)) { git.add().addFilepattern("nested-repo").call(); assertEquals( "[nested-repo/README1.md, mode:100644]" + "[nested-repo/README2.md, mode:100644]", indexState(0)); } config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_DIRNOGITLINKS, false); config.save(); File readme3 = new File(db.getWorkTree(), "nested-repo/README3.md"); FileUtils.createNewFile(readme3); PrintWriter writer = new PrintWriter(readme3); writer.print("content"); writer.close(); try (Git git = new Git(db)) { git.add().addFilepattern("nested-repo").call(); assertEquals( "[nested-repo/README1.md, mode:100644]" + "[nested-repo/README2.md, mode:100644]" + "[nested-repo/README3.md, mode:100644]", indexState(0)); } }

Target:
public void testAddSubrepoWithDirNoGitlinks() throws Exception { createNestedRepo("nested-repo"); StoredConfig config = db.getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_DIRNOGITLINKS, true); config.save(); assert (db.getConfig().get(WorkingTreeOptions.KEY).isDirNoGitLinks()); try (Git git = new Git(db)) { git.add().addFilepattern("nested-repo").call(); assertEquals( "[nested-repo/README1.md, mode:100644]" + "[nested-repo/README2.md, mode:100644]", indexState(0)); } config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_DIRNOGITLINKS, false); config.save(); writeTrashFile("nested-repo", "README3.md", "content"); try (Git git = new Git(db)) { git.add().addFilepattern("nested-repo").call(); assertEquals( "[nested-repo/README1.md, mode:100644]" + "[nested-repo/README2.md, mode:100644]" + "[nested-repo/README3.md, mode:100644]", indexState(0)); } }
Source:
protected void onBindDialogView(View view) { super.onBindDialogView(view); listView = (FilterListView) view.findViewById(android.R.id.list); clickedItemIndex = findIndexOfValue(mValue); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { clickedItemIndex = findIndexByLabel((String) parent.getItemAtPosition(position)); LocationListPreference.this.onClick(getDialog(), DialogInterface.BUTTON_POSITIVE); getDialog().dismiss(); } } ); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); CheckedItemAdapter adapter = new CheckedItemAdapter( getContext(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, getEntries() ); listView.setAdapter(adapter); clickedItemIndex = findIndexOfValue(getPersistedString(null)); listView.setSelection(clickedItemIndex); listView.setItemChecked(clickedItemIndex, true); listView.setTextFilterEnabled(true); listView.setFilterListener( new Filter.FilterListener() { @Override public void onFilterComplete(int count) { int index = findIndexByLabelInFilteredListView(getPersistedString(null)); listView.setItemChecked(index, true); } } ); EditText editText = (EditText) view.findViewById(R.id.filter); editText.addTextChangedListener( new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable editable) { listView.setFilterText(editable.toString()); } } ); editText.requestFocus(); }

Target:
protected void onBindDialogView(View view) { super.onBindDialogView(view); listView = (FilterListView) view.findViewById(android.R.id.list); clickedItemIndex = findIndexOfValue(mValue); listView.setOnItemClickListener(this); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); final CheckedItemAdapter adapter = new CheckedItemAdapter( getContext(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, getEntries() ); listView.setAdapter(adapter); clickedItemIndex = findIndexOfValue(getPersistedString(null)); listView.setSelection(clickedItemIndex); listView.setItemChecked(clickedItemIndex, true); final Filter.FilterListener filterListener = new Filter.FilterListener() { @Override public void onFilterComplete(int count) { int index = findIndexByLabelInFilteredListView(getPersistedString(null)); listView.setItemChecked(index, true); } }; SearchView cityNameSearchView = (SearchView) view.findViewById(R.id.filter); cityNameSearchView.setOnQueryTextListener( new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText, filterListener); return true; } } ); cityNameSearchView.requestFocus(); }
Source:
public void whenPropertyIsVerySimpleThenTypeInfoIsCorrect() { PropertyMetaModel bert = new PropertyMetaModel(null, "bert", int.class, Optional.empty(), false, false, false, false); assertEquals("int", bert.getTypeName()); assertEquals("int", bert.getTypeNameGenericsed()); assertEquals("int", bert.getTypeNameForGetter()); assertEquals("int", bert.getTypeNameForSetter()); }

Target:
public void whenPropertyIsVerySimpleThenTypeInfoIsCorrect() { PropertyMetaModel bert = new PropertyMetaModel(null, "bert", int.class, Optional.empty(), false, false, false, false); assertEquals("int", bert.getTypeName()); assertEquals("int", bert.getTypeNameGenerified()); assertEquals("int", bert.getTypeNameForGetter()); assertEquals("int", bert.getTypeNameForSetter()); }
Source:
public void dispose() { session.removeListener(this); SessionManager.INSTANCE.removeSessionsListener(this); session = null; treeViewer = null; manageSessionActionProvider = null; siriusCommonContentModelProvider = null; menuManager = null; }

Target:
public void dispose() { session.removeListener(this); SessionManager.INSTANCE.removeSessionsListener(this); session = null; treeViewer = null; manageSessionActionProvider = null; siriusCommonContentModelProvider = null; menuManager = null; toolkit = null; }
Source:
public static void selectGlobalTypeFilter(final Activity activity, final Action1<CacheType> okayListener) { final List<CacheType> cacheTypes = new ArrayList<>(); cacheTypes.add(CacheType.ALL); cacheTypes.add(CacheType.TRADITIONAL); cacheTypes.add(CacheType.MULTI); cacheTypes.add(CacheType.MYSTERY); final List<CacheType> sorted = new ArrayList<>(Arrays.asList(CacheType.values())); sorted.removeAll(cacheTypes); Collections.sort(sorted, new Comparator<CacheType>() { @Override public int compare(final CacheType left, final CacheType right) { return TextUtils.COLLATOR.compare(left.getL10n(), right.getL10n()); } }); cacheTypes.addAll(sorted); int checkedItem = cacheTypes.indexOf(Settings.getCacheType()); if (checkedItem < 0) { checkedItem = 0; } final String[] items = new String[cacheTypes.size()]; for (int i = 0; i < cacheTypes.size(); i++) { items[i] = cacheTypes.get(i).getL10n(); } final Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.menu_filter); builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { final CacheType cacheType = cacheTypes.get(position); Settings.setCacheType(cacheType); okayListener.call(cacheType); dialog.dismiss(); } }); builder.create().show(); }

Target:
public static void selectGlobalTypeFilter(final Activity activity, final Action1<CacheType> okayListener) { final List<CacheType> cacheTypes = new ArrayList<>(); cacheTypes.add(CacheType.ALL); cacheTypes.add(CacheType.TRADITIONAL); cacheTypes.add(CacheType.MULTI); cacheTypes.add(CacheType.MYSTERY); final List<CacheType> sorted = new ArrayList<>(Arrays.asList(CacheType.values())); sorted.removeAll(cacheTypes); Collections.sort(sorted, new Comparator<CacheType>() { @Override public int compare(final CacheType left, final CacheType right) { return TextUtils.COLLATOR.compare(left.getL10n(), right.getL10n()); } }); cacheTypes.addAll(sorted); final int checkedItem = Math.max(0, cacheTypes.indexOf(Settings.getCacheType())); final String[] items = new String[cacheTypes.size()]; for (int i = 0; i < cacheTypes.size(); i++) { items[i] = cacheTypes.get(i).getL10n(); } final Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.menu_filter); builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { final CacheType cacheType = cacheTypes.get(position); Settings.setCacheType(cacheType); okayListener.call(cacheType); dialog.dismiss(); } }); builder.create().show(); }
Source:
public TimeZone getTransactionTimeZone() { String tzName = execConfig.get(String.class, "transaction_timezone", "UTC"); return TimeZone.getTimeZone(tzName); }

Target:
public DateTimeZone getTransactionTimeZone() { return execConfig.get(DateTimeZone.class, "transaction_time_zone", DateTimeZone.UTC); }
Source:
static void initProviderAsynchronously(@NonNull IProject project) { synchronized (INSTANCE.projects) { if (INSTANCE.projects.contains(project)) { return; } INSTANCE.projects.add(project); } INSTANCE.schedule(); }

Target:
private static void initProviderAsynchronously( @NonNull IProject project) { synchronized (INSTANCE.projects) { if (INSTANCE.projects.contains(project)) { return; } INSTANCE.projects.add(project); } INSTANCE.schedule(); }
Source:
public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String authKey, final String authIV, final String serverUrl, final ISSLCertificateCallback sslCertificateCallback) throws OpenShiftException { return getConnection(clientId, username, password, authKey, authIV, serverUrl, sslCertificateCallback, createDHECipherExclusionRegex()); }

Target:
public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String authKey, final String authIV, final String serverUrl, final ISSLCertificateCallback sslCertificateCallback) throws OpenShiftException { return getConnection(clientId, username, password, authKey, authIV, serverUrl, sslCertificateCallback, createCipherExclusionRegex(getConfiguration())); }
Source:
public static <T> List<T> safeGetList(Map map, String key, Class<T> type) { List<?> unchecked = safeGet(map, key, List.class); if (unchecked == null) { return null; } try { return (List<T>) unchecked.stream().map(type::cast).collect(Collectors.toList()); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a List containing type {}", key, type.getName()); } return null; }

Target:
public static <T> List<T> safeGetList(Map map, String key, Class<T> type) { List<?> unchecked = safeGet(map, key, List.class); if (unchecked == null) { return Collections.emptyList(); } try { return (List<T>) unchecked.stream().map(type::cast).collect(Collectors.toList()); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a List containing type {}", key, type.getName()); } return Collections.emptyList(); }
Source:
public String getLatestPatchSet() { RevisionInfo topmost = getRevisionInfoByNumber(new Integer(fSelectedRevision.get_number()).toString()); return topmost.getId(); }

Target:
public String getLatestPatchSet() { EMap<String, RevisionInfo> revisions = fChangeInfo.getRevisions(); int topNumber = 0; for (Entry<String, RevisionInfo> entry : revisions.entrySet()) { if (entry.getValue().get_number() > topNumber) { topNumber = entry.getValue().get_number(); } } RevisionInfo topmost = getRevisionInfoByNumber(new Integer(topNumber).toString()); return topmost.getId(); }
Source:
private Optional<Deadline> createOperationDeadline() { Deadline contextDeadline = Context.current().getDeadline(); if (contextDeadline != null) { return Optional.of(contextDeadline); } else if (useTimeout) { return Optional.of(Deadline.after(requestTimeoutMs, TimeUnit.MILLISECONDS)); } else { return Optional.absent(); } }

Target:
private Optional<Deadline> createOperationDeadline() { Optional<Deadline> deadline = Optional.fromNullable(Context.current().getDeadline()); if (useTimeout) { deadline = deadline.or(Optional.of(Deadline.after(requestTimeoutMs, TimeUnit.MILLISECONDS))); } return deadline; }
Source:
private static void deleteFolderContents(IProject project, String folderName) { IFolder folder = project.getFolder(folderName); class DeleteContents implements IResourceVisitor { @Override public boolean visit(IResource resource) throws CoreException { if (!folder.equals(resource)) { resource.delete(true, null); return false; } return true; } } if (folder.isAccessible()) { try { folder.accept(new DeleteContents()); } catch (CoreException e) { String message = "Failed to delete contents of folder " + folderName + " of project " + project.getName(); throw new AssertionError(message, e); } } }

Target:
private static void deleteFolderContents(IProject project, String folderName) { try { IFolder folder = project.getFolder(folderName); folder.delete(true, null); folder.create(true, false, null); } catch (CoreException e) { throw new AssertionError("Failed to delete folder: " + folderName + " in project: " + project.getName(), e); } }
Source:
public CommandCallback getCallback() { return Injector.injectMembers(new ConcurrentChildCommandsExecutionCallback()); }

Target:
public CommandCallback getCallback() { return callbackProvider.get(); }
Source:
public void setIgnoredPlayerTimeout(IUser user, long time) { UUID uuid = user.getBase().getUniqueId(); System.out.println("UUID: " + uuid); System.out.println("Map: " + ignoredPlayerTimeouts); ignoredPlayerTimeouts.put(uuid, time); System.out.println("Map (final): " + ignoredPlayerTimeouts); setIgnoredPlayerTimeouts(ignoredPlayerTimeouts); }

Target:
public void setIgnoredPlayerTimeout(IUser user, long time) { UUID uuid = user.getBase().getUniqueId(); ignoredPlayerTimeouts.put(uuid, time); setIgnoredPlayerTimeouts(ignoredPlayerTimeouts); }
Source:
public void complete() { if (completed || subscriber.isUnsubscribed()) { return; } try { super.complete(); if (getOutput() != null) { if (getOutput().hasError()) { subscriber.onError(new RedisCommandExecutionException(getOutput().getError())); completed = true; return; } Object result = getOutput().get(); if (!(getOutput() instanceof StreamingOutput<?>) && result != null) { if (dissolve && result instanceof Collection) { Collection<T> collection = (Collection<T>) result; for (T t : collection) { subscriber.onNext(t); } } else { subscriber.onNext((T) result); } } } subscriber.onCompleted(); } finally { completed = true; } }

Target:
public void complete() { if (completed || subscriber.isUnsubscribed()) { return; } try { super.complete(); if (getOutput() != null) { Object result = getOutput().get(); if (!(getOutput() instanceof StreamingOutput<?>) && result != null) { if (dissolve && result instanceof Collection) { Collection<T> collection = (Collection<T>) result; for (T t : collection) { subscriber.onNext(t); } } else { subscriber.onNext((T) result); } } if (getOutput().hasError()) { subscriber.onError(new RedisCommandExecutionException(getOutput().getError())); completed = true; return; } } subscriber.onCompleted(); } finally { completed = true; } }
Source:
public void should_work_and_log_warning_when_deprecated_key() throws Exception { settings.setProperty(JavaScriptPlugin.TS_LCOV_REPORT_PATHS, UT_LCOV + ", " + IT_LCOV); coverageSensor.execute(context); testTwoFilesContext(); assertThat(logTester.logs(LoggerLevel.WARN)).contains("The use of sonar.typescript.lcov.reportPaths for coverage import is deprecated, use sonar.javascript.lcov.reportPaths instead!"); }

Target:
public void should_work_and_log_warning_when_deprecated_key() throws Exception { settings.setProperty(JavaScriptPlugin.LCOV_REPORT_PATHS, ""); settings.setProperty(JavaScriptPlugin.TS_LCOV_REPORT_PATHS, TWO_REPORTS); coverageSensor.execute(context); assertTwoReportsCoverageDataPresent(); assertThat(logTester.logs(LoggerLevel.WARN)).contains(DEPRECATED_MESSAGE); }
Source:
private void checkChangedField(AllTypes allTypes, final String... fieldNames) { assertNotNull(fieldNames); allTypes.addChangeListener(new RealmObjectChangeListener<RealmModel>() { @Override public void onChange(RealmModel object, ObjectChangeSet changeSet) { assertEquals(fieldNames.length, changeSet.getChangedFields().length); for (String name : fieldNames) { assertTrue(changeSet.isFieldChanged(name)); assertFalse(changeSet.isFieldChanged(name + "NotThere")); for (String field : changeSet.getChangedFields()) { if (field.equals(name)) { break; } fail("Cannot find field " + name + " in field changes."); } } looperThread.testComplete(); } }); looperThread.keepStrongReference.add(allTypes); }

Target:
private void checkChangedField(AllTypes allTypes, final String... fieldNames) { assertNotNull(fieldNames); allTypes.addChangeListener(new RealmObjectChangeListener<RealmModel>() { @Override public void onChange(RealmModel object, ObjectChangeSet changeSet) { assertEquals(fieldNames.length, changeSet.getChangedFields().length); List<String> changedFields = Arrays.asList(changeSet.getChangedFields()); for (String name : fieldNames) { assertTrue(changeSet.isFieldChanged(name)); assertFalse(changeSet.isFieldChanged(name + "NotThere")); if (!changedFields.contains(name)) { fail("Cannot find field " + name + " in field changes."); } } looperThread.testComplete(); } }); looperThread.keepStrongReference.add(allTypes); }
Source:
private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { return Response.created(URI.create("v1/resource/securityroles")).entity(savedRole).build(); } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }

Target:
private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { return Response.created(URI.create("v1/resource/securityroles/" + URLEncoder.encode(savedRole.getRoleName()))).entity(savedRole).build(); } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }
Source:
private void setPendingStatusesToAllEligibleTasks(List<EligibleTaskDescriptor> eligibleTasks) { List<EligibleTaskDescriptorImpl> notPendingYet = eligibleTasks.stream() .map(task -> (EligibleTaskDescriptorImpl) task) .filter(task -> !task.getInternal() .getStatus() .equals(TaskStatus.PENDING)) .collect(Collectors.toList()); notPendingYet.forEach(task -> { if (task.getInternal().getScheduledTime() == -1) { task.getInternal().setScheduledTime(System.currentTimeMillis()); } task.getInternal().setStatus(TaskStatus.PENDING); }); notPendingYet.forEach(task -> { getDBManager().updateTaskStatus(task, TaskStatus.PENDING); getDBManager().updateScheduledTime(task.getJobId().longValue(), task.getTaskId().longValue(), task.getInternal().getScheduledTime()); }); }

Target:
private void setPendingStatusesToAllEligibleTasks(List<EligibleTaskDescriptor> eligibleTasks) { List<EligibleTaskDescriptorImpl> notPendingYet = eligibleTasks.stream() .map(task -> (EligibleTaskDescriptorImpl) task) .filter(task -> !task.getInternal() .getStatus() .equals(TaskStatus.PENDING)) .collect(Collectors.toList()); notPendingYet.forEach(task -> { if (task.getInternal().getScheduledTime() == -1) { task.getInternal().setScheduledTime(System.currentTimeMillis()); } task.getInternal().setStatus(TaskStatus.PENDING); }); notPendingYet.forEach(task -> { getDBManager().updateTaskStatusAndScheduledTime(task, TaskStatus.PENDING, task.getInternal().getScheduledTime()); }); }
Source:
private void filterValues(String filterRaw, boolean synchronous) { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } String[] searchTerms = filterRaw.split(" "); for(int i = 0 ; i < searchTerms.length ; ++i) { searchTerms[i] = StringUtils.normalize(searchTerms[i]); } mCurrentSortThread = new EntitySearcher(filterRaw, searchTerms); mCurrentSortThread.startThread(); if(synchronous) { try { mCurrentSortThread.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }

Target:
private void filterValues(String filterRaw, boolean synchronous) { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } String[] searchTerms = filterRaw.split("\\s+"); for(int i = 0 ; i < searchTerms.length ; ++i) { searchTerms[i] = StringUtils.normalize(searchTerms[i]); } mCurrentSortThread = new EntitySearcher(filterRaw, searchTerms); mCurrentSortThread.startThread(); if(synchronous) { try { mCurrentSortThread.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Source:
public void fill(Composite parent) { if (!checkWidget(parent)) { return; } int flags = SWT.PUSH; if (action != null) { if (action.getStyle() == IAction.AS_CHECK_BOX) { flags = SWT.TOGGLE; } if (action.getStyle() == IAction.AS_RADIO_BUTTON) { flags = SWT.RADIO; } } Button b = new Button(parent, flags); b.setData(this); b.addListener(SWT.Dispose, getButtonListener()); b.addListener(SWT.Selection, getButtonListener()); if (action.getHelpListener() != null) { b.addHelpListener(action.getHelpListener()); } widget = b; update(null); action.addPropertyChangeListener(propertyListener); if (action != null) { String commandId = action.getActionDefinitionId(); ExternalActionManager.ICallback callback = ExternalActionManager.getInstance().getCallback(); if ((callback != null) && (commandId != null)) { callback.addPropertyChangeListener(commandId, actionTextListener); } } }

Target:
public void fill(Composite parent) { if (widget != null || parent == null) { return; } int flags = SWT.PUSH; if (action != null) { if (action.getStyle() == IAction.AS_CHECK_BOX) { flags = SWT.TOGGLE; } if (action.getStyle() == IAction.AS_RADIO_BUTTON) { flags = SWT.RADIO; } } Button b = new Button(parent, flags); b.setData(this); b.addListener(SWT.Dispose, getButtonListener()); b.addListener(SWT.Selection, getButtonListener()); if (action.getHelpListener() != null) { b.addHelpListener(action.getHelpListener()); } widget = b; update(null); action.addPropertyChangeListener(propertyListener); if (action != null) { String commandId = action.getActionDefinitionId(); ExternalActionManager.ICallback callback = ExternalActionManager.getInstance().getCallback(); if ((callback != null) && (commandId != null)) { callback.addPropertyChangeListener(commandId, actionTextListener); } } }
Source:
private void scheduleManagerUpdate(IContributionManager mgr) { boolean workaroundEnabled = Boolean.getBoolean(ECLIPSE_WORKAROUND_BUG467000); if (!workaroundEnabled) { mgr.update(false); return; } synchronized (mgrToUpdate) { if (this.mgrToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display != null && !display.isDisposed()) { display.timerExec(100, new Runnable() { @Override public void run() { Collection<IContributionManager> toUpdate = new LinkedHashSet<>(); synchronized (mgrToUpdate) { toUpdate.addAll(mgrToUpdate); mgrToUpdate.clear(); } for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrToUpdate.add(mgr); } } }

Target:
private void scheduleManagerUpdate(IContributionManager mgr) { if (!ECLIPSE_WORKAROUND_BUG467000) { mgr.update(false); return; } synchronized (mgrToUpdate) { if (this.mgrToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display != null && !display.isDisposed()) { display.timerExec(100, new Runnable() { @Override public void run() { Collection<IContributionManager> toUpdate = new LinkedHashSet<>(); synchronized (mgrToUpdate) { toUpdate.addAll(mgrToUpdate); mgrToUpdate.clear(); } for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrToUpdate.add(mgr); } } }
Source:
public void testStarvationDetected() throws Exception { final int stripeIdx = 0; stripedExecSvc.execute(stripeIdx, new TestRunnable(true)); assertFalse(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 0, 3000)); stripedExecSvc.execute(stripeIdx, new TestRunnable()); assertTrue(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 1, 10000)); assertTrue(stripedExecSvc.isStarvationDetected()); }

Target:
public void testStarvationDetected() throws Exception { final int stripeIdx = 0; stripedExecSvc.execute(stripeIdx, new TestRunnable(true)); sleepASec(); assertFalse(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 0, 2000)); stripedExecSvc.execute(stripeIdx, new TestRunnable()); assertTrue(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 1, 10000)); assertTrue(stripedExecSvc.detectStarvation()); }
Source:
protected void parse() { enabled = getBooleanFromConfig(ENABLED, true); uiEnabled = getBooleanFromConfig(UI_ENABLED, true); secureOnly = getBooleanFromConfig(SECURE_ONLY, false); disableKey = getBooleanFromConfig(DISABLE_KEY, false); incErrorDetails = getBooleanFromConfig(INC_ERROR_DETAILS, false); autofillKey = getBooleanFromConfig(AUTOFILL_KEY, false); enableJSONP = getBooleanFromConfig(ENABLE_JSONP, false); noKeyForViews = getBooleanFromConfig(NO_KEY_FOR_VIEWS, false); reportPermErrors = getBooleanFromConfig(REPORT_PERM_ERRORS, false); nonceTimeToLiveInSecs = getIntFromConfig(NONCE_TTL_IN_SECS, 5000); try { key = getConfig().getString(API_KEY, ""); } catch (ConversionException e) { LOGGER.warn("Failed to load the option '" + key + "' caused by:", e); key = ""; } loadPermittedAddresses(); try { this.confirmRemovePermittedAddress = getConfig().getBoolean(CONFIRM_REMOVE_EXCLUDED_DOMAIN, true); } catch (ConversionException e) { LOGGER.error("Error while loading the confirm remove permitted address option: " + e.getMessage(), e); } }

Target:
protected void parse() { enabled = getBooleanFromConfig(ENABLED, true); uiEnabled = getBooleanFromConfig(UI_ENABLED, true); secureOnly = getBooleanFromConfig(SECURE_ONLY, false); disableKey = getBooleanFromConfig(DISABLE_KEY, false); incErrorDetails = getBooleanFromConfig(INC_ERROR_DETAILS, false); autofillKey = getBooleanFromConfig(AUTOFILL_KEY, false); enableJSONP = getBooleanFromConfig(ENABLE_JSONP, false); noKeyForSafeOps = getBooleanFromConfig(NO_KEY_FOR_SAFE_OPS, false); reportPermErrors = getBooleanFromConfig(REPORT_PERM_ERRORS, false); nonceTimeToLiveInSecs = getIntFromConfig(NONCE_TTL_IN_SECS, DEFAULT_NONCE_TTL_IN_SECS); try { key = getConfig().getString(API_KEY, ""); } catch (ConversionException e) { LOGGER.warn("Failed to load the option '" + key + "' caused by:", e); key = ""; } loadPermittedAddresses(); try { this.confirmRemovePermittedAddress = getConfig().getBoolean(CONFIRM_REMOVE_EXCLUDED_DOMAIN, true); } catch (ConversionException e) { LOGGER.error("Error while loading the confirm remove permitted address option: " + e.getMessage(), e); } }
Source:
public boolean verifyToken(JWT token, RSAPublicKey publicKey) throws TokenServiceException { boolean rc; PublicKey key; try { if (publicKey == null) { key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias(null)).getPublicKey(); } else { key = publicKey; } JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key); rc = token.verify(verifier); } catch (KeyStoreException | KeystoreServiceException e) { throw new TokenServiceException("Cannot verify token.", e); } return rc; }

Target:
public boolean verifyToken(JWT token, RSAPublicKey publicKey) throws TokenServiceException { boolean rc; PublicKey key; try { if (publicKey == null) { key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias()).getPublicKey(); } else { key = publicKey; } JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key); rc = token.verify(verifier); } catch (KeyStoreException | KeystoreServiceException e) { throw new TokenServiceException("Cannot verify token.", e); } return rc; }
Source:
public void start(final BundleContext bundleContext) { WebAppConfigurationService webAppConfigurationService = new WebAppConfigurationDataHolder(); bundleContext.registerService(WebAppConfigurationService.class.getName(), webAppConfigurationService, null); log.debug("WebappConfigService was registered!"); if (!CarbonUtils.isRunningInStandaloneMode()) { Thread th = new Thread() { public void run() { try { bundleContext.getBundle().uninstall(); } catch (Throwable e) { log.warn("Error occurred while uninstalling webapp-mgt UI bundle", e); } } }; try { th.join(); } catch (InterruptedException ignored) { } th.start(); } }

Target:
public void start(final BundleContext bundleContext) { WebAppConfigurationService webAppConfigurationService = new WebAppConfigurationDataHolder(); bundleContext.registerService(WebAppConfigurationService.class.getName(), webAppConfigurationService, null); if (log.isDebugEnabled()) { log.debug("WebappConfigService was registered!"); } if (!CarbonUtils.isRunningInStandaloneMode()) { Thread th = new Thread() { public void run() { try { bundleContext.getBundle().uninstall(); } catch (Throwable e) { log.warn("Error occurred while uninstalling webapp-mgt UI bundle", e); } } }; try { th.join(); } catch (InterruptedException ignored) { } th.start(); } }
Source:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); numConnections.decrementAndGet(); log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }

Target:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }
Source:
private Stream<VirtualMachineLease> groupEvaluator(Set<VirtualMachineLease> groupCandidates) { Map<VirtualMachineLease, Double> scores = new HashMap<>(); scoringEvaluators.forEach(e -> { Optional<? super Object> optionalContext = Optional.empty(); for (VirtualMachineLease lease : groupCandidates) { double currentScore = scores.getOrDefault(lease, 0.0); if (currentScore != NOT_REMOVABLE_MARKER) { ScaleDownConstraintEvaluator.Result result = e.evaluate(lease, optionalContext); double newScore = result.getScore(); if (newScore == 0) { scores.put(lease, NOT_REMOVABLE_MARKER); } else { scores.put(lease, currentScore + newScore); } optionalContext = result.getContext(); } } }); return scores.entrySet().stream() .filter(e -> e.getValue() != NOT_REMOVABLE_MARKER) .sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) .map(Map.Entry::getKey); }

Target:
private Stream<VirtualMachineLease> groupEvaluator(Set<VirtualMachineLease> groupCandidates) { Map<VirtualMachineLease, Double> scores = new HashMap<>(); scoringEvaluators.forEach((e, weight) -> { Optional<? super Object> optionalContext = Optional.empty(); for (VirtualMachineLease lease : groupCandidates) { double currentScore = scores.getOrDefault(lease, 0.0); if (currentScore != NOT_REMOVABLE_MARKER) { ScaleDownConstraintEvaluator.Result result = e.evaluate(lease, optionalContext); double newScore = result.getScore() * weight; if (newScore == 0) { scores.put(lease, NOT_REMOVABLE_MARKER); } else { scores.put(lease, currentScore + newScore); } optionalContext = result.getContext(); } } }); return scores.entrySet().stream() .filter(e -> e.getValue() != NOT_REMOVABLE_MARKER) .sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) .map(Map.Entry::getKey); }