auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void placeItemsOnBoard() { int numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_GRENADES) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new LightGrenade()); numberOfItems++; } } numberOfItems = 0; LinkedList<Teleporter> teleporters = new LinkedList<>(); while (((double) numberOfItems) / grid.size() < NUMBER_OF_TELEPORTERS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { Teleporter teleporter = new Teleporter(getTeleporterDestination(teleporters), grid.get(position)); ((Square) grid.get(position)).addItem(teleporter); teleporters.add(teleporter); numberOfItems++; } } teleporters.get(0).setDestination(getTeleporterDestination(teleporters)); numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_IDENTITY_DISKS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new IdentityDisk()); numberOfItems++; } } }

Target:
private void placeItemsOnBoard() { int numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_GRENADES) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new LightGrenade()); numberOfItems++; } } numberOfItems = 0; List<Teleporter> teleporters = new ArrayList<>(); while (((double) numberOfItems) / grid.size() < NUMBER_OF_TELEPORTERS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { Teleporter teleporter = new Teleporter(getTeleporterDestination(teleporters), grid.get(position)); ((Square) grid.get(position)).addItem(teleporter); teleporters.add(teleporter); numberOfItems++; } } teleporters.remove(0); teleporters.get(0).setDestination(getTeleporterDestination(teleporters)); numberOfItems = 0; while (((double) numberOfItems) / grid.size() < NUMBER_OF_IDENTITY_DISKS) { Coordinate position = Coordinate.random(width, height); if (canPlaceItem(position)) { ((Square) grid.get(position)).addItem(new IdentityDisk()); numberOfItems++; } } }
Source:
public long getDisabledPartitions() { return _disabledPartitionsGauge.getValue(); }

Target:
protected long getDisabledPartitions() { return _disabledPartitionsGauge.getValue(); }
Source:
public void setUp() throws IOException { intermediatePath = new Path(String.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(String.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = File.createTempFile("dummy-test", ".jar"); dummyJarFile.deleteOnExit(); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); }

Target:
public void setUp() throws IOException { intermediatePath = new Path(String.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(String.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); }
Source:
private String getBrokerUrl(String loadUrl, String packageName, String signatureDigest) { if (!StringExtensions.IsNullOrBlank(packageName) && !StringExtensions.IsNullOrBlank(signatureDigest)) { try { return loadUrl + "&package_name=" + URLEncoder.encode(packageName, AuthenticationConstants.ENCODING_UTF8) + "&signature=" + signatureDigest; } catch (UnsupportedEncodingException e) { Log.e(TAG, "Encoding", e); } } return loadUrl; }

Target:
private String getBrokerUrl(String loadUrl, String packageName, String signatureDigest) { if (!StringExtensions.IsNullOrBlank(packageName) && !StringExtensions.IsNullOrBlank(signatureDigest)) { try { return loadUrl + "&package_name=" + URLEncoder.encode(packageName, AuthenticationConstants.ENCODING_UTF8) + "&signature=" + URLEncoder.encode(signatureDigest, AuthenticationConstants.ENCODING_UTF8); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Encoding", e); } } return loadUrl; }
Source:
private static void createSystemMetacards( EndpointUtil util, List<Metacard> systemTemplates, CatalogFramework catalogFramework) { Set<String> queryTitles = titlesTransform(util.getMetacardsByFilter(QUERY_TEMPLATE_TAG)); Set<String> resultTitles = titlesTransform(util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG)); List<Metacard> dedupedTemplateMetacards = Stream.concat( systemTemplates .stream() .filter(QueryTemplateMetacard::isQueryTemplateMetacard) .filter(metacard -> !queryTitles.contains(metacard.getTitle())), systemTemplates .stream() .filter(AttributeGroupMetacard::isAttributeGroupMetacard) .filter(metacard -> !resultTitles.contains(metacard.getTitle()))) .collect(Collectors.toList()); if (!dedupedTemplateMetacards.isEmpty()) { try { catalogFramework.create(new CreateRequestImpl(dedupedTemplateMetacards)); } catch (SourceUnavailableException | IngestException e) { LOGGER.warn("Could not load System Templates", e); } } }

Target:
private static void createSystemMetacards( EndpointUtil util, List<Metacard> systemTemplates, CatalogFramework catalogFramework) { Set<String> queryTitles = titlesTransform(util.getMetacardsByFilter(QUERY_TEMPLATE_TAG)); Set<String> resultTitles = titlesTransform(util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG)); List<Metacard> dedupedTemplateMetacards = Stream.concat( systemTemplates .stream() .filter(QueryTemplateMetacard::isQueryTemplateMetacard) .filter(metacard -> !queryTitles.contains(metacard.getTitle())), systemTemplates .stream() .filter(AttributeGroupMetacard::isAttributeGroupMetacard) .filter(metacard -> !resultTitles.contains(metacard.getTitle()))) .collect(Collectors.toList()); if (!dedupedTemplateMetacards.isEmpty()) { try { catalogFramework.create(new CreateRequestImpl(dedupedTemplateMetacards)); } catch (SourceUnavailableException | IngestException e) { throw new RuntimeException("Could not load System Templates", e); } } }
Source:
public void addRecentPage(int page) { BookmarksWidget.updateWidget(context); addRecentPage(page, true); }

Target:
public void addRecentPage(int page) { addRecentPage(page, true); }
Source:
public boolean isConstantOrParameterTreeNode() { if (leftOperandList != null && !leftOperandList.isConstantOrParameterTreeNode()) return false; if (rightOperandList != null && !rightOperandList.containsOnlyConstantAndParamNodes()) return false; return true; }

Target:
public boolean isConstantOrParameterTreeNode() { if (leftOperandList != null && !leftOperandList.containsOnlyConstantAndParamNodes()) return false; if (rightOperandList != null && !rightOperandList.containsOnlyConstantAndParamNodes()) return false; return true; }
Source:
public GetBucketResponse(final String id, final String location, final String name, final String storageClass, final String timeCreated) { super(); this.id = id; this.location = location; this.name = name; this.storageClass = storageClass; this.timeCreated = timeCreated; }

Target:
public GetBucketResponse(final String id, final String location, final String name, final String storageClass, final String timeCreated) { this.id = id; this.location = location; this.name = name; this.storageClass = storageClass; this.timeCreated = timeCreated; }
Source:
public String getNameTokenWithClass() { if (nameTokenPsiClass == null) { return ""; } String s = nameTokenPsiClass.getName().replace(".java", "") + "." + nameToken; return s; }

Target:
public String getNameTokenWithClass() { if (nameTokenPsiClass == null) { return ""; } return nameTokenPsiClass.getName().replace(".java", "") + "." + nameToken; }
Source:
public void setChecked(boolean checked) { if (_checked != checked) { _checked = checked; smartUpdate("checked", _checked); if (!_init && _indeterminate) { _indeterminate = false; smartUpdate("indeterminate", _indeterminate); } } }

Target:
public void setChecked(boolean checked) { if (_checked != checked) { _checked = checked; smartUpdate("checked", _checked); if (!_init && _indeterminate) { setIndeterminate(false); } } }
Source:
public void testUGIReLoginFromKeytab() throws Exception { String principal = "foo"; File keytab = new File(workDir, "foo.keytab"); kdc.createPrincipal(keytab, principal); UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath()); UserGroupInformation ugi = UserGroupInformation.getLoginUser(); Assert.assertTrue("UGI should be configured to login from keytab", ugi.isFromKeytab()); User user = getUser(ugi.getSubject()); final long firstLogin = user.getLastLogin(); final LoginContext login1 = user.getLogin(); Assert.assertNotNull(login1); Thread.sleep(1000); ugi.reloginFromKeytab(); final long secondLogin = user.getLastLogin(); final LoginContext login2 = user.getLogin(); Assert.assertTrue("User should have been able to relogin from keytab", secondLogin > firstLogin); Assert.assertNotNull(login2); Assert.assertNotSame(login1, login2); }

Target:
public void testUGIReLoginFromKeytab() throws Exception { String principal = "foo"; File keytab = new File(workDir, "foo.keytab"); kdc.createPrincipal(keytab, principal); UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath()); UserGroupInformation ugi = UserGroupInformation.getLoginUser(); Assert.assertTrue("UGI should be configured to login from keytab", ugi.isFromKeytab()); User user = getUser(ugi.getSubject()); final long firstLogin = user.getLastLogin(); final LoginContext login1 = user.getLogin(); Assert.assertNotNull(login1); Thread.sleep(2000); ugi.reloginFromKeytab(); final long secondLogin = user.getLastLogin(); final LoginContext login2 = user.getLogin(); Assert.assertTrue("User should have been able to relogin from keytab", secondLogin > firstLogin); Assert.assertNotNull(login2); Assert.assertNotSame(login1, login2); }
Source:
public PointSensitivities presentValueSensitivity( ResolvedCds cds, CreditRatesProvider ratesProvider, LocalDate referenceDate, ReferenceData refData) { if (isExpired(cds, ratesProvider)) { return PointSensitivities.empty(); } LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = recoveryRate(cds, ratesProvider); Pair<CreditDiscountFactors, LegalEntitySurvivalProbabilities> rates = reduceDiscountFactors(cds, ratesProvider); double signedNotional = cds.getBuySell().normalize(cds.getNotional()); PointSensitivityBuilder protectionLegSensi = protectionLegSensitivity(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate, recoveryRate) .multipliedBy(signedNotional); PointSensitivityBuilder riskyAnnuitySensi = riskyAnnuitySensitivity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate) .multipliedBy(-cds.getFixedRate() * signedNotional); return protectionLegSensi.combinedWith(riskyAnnuitySensi).build(); }

Target:
public PointSensitivityBuilder presentValueSensitivity( ResolvedCds cds, CreditRatesProvider ratesProvider, LocalDate referenceDate, ReferenceData refData) { if (isExpired(cds, ratesProvider)) { return PointSensitivityBuilder.none(); } LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = recoveryRate(cds, ratesProvider); Pair<CreditDiscountFactors, LegalEntitySurvivalProbabilities> rates = reduceDiscountFactors(cds, ratesProvider); double signedNotional = cds.getBuySell().normalize(cds.getNotional()); PointSensitivityBuilder protectionLegSensi = protectionLegSensitivity(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate, recoveryRate) .multipliedBy(signedNotional); PointSensitivityBuilder riskyAnnuitySensi = riskyAnnuitySensitivity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate) .multipliedBy(-cds.getFixedRate() * signedNotional); return protectionLegSensi.combinedWith(riskyAnnuitySensi); }
Source:
public void testNormalFlow() throws Exception { PartitionId partitionId = new MockPartitionId(); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, System.currentTimeMillis(), Utils.Infinite_Time, blobSize, CloudBlobMetadata.EncryptionOrigin.NONE, vcrKmsContext, cryptoAgentFactory); assertTrue("Expected upload to return true", azureDest.uploadBlob(blobId, blobSize, cloudBlobMetadata, inputStream)); assertFalse("Expected duplicate upload to return false", azureDest.uploadBlob(blobId, blobSize, cloudBlobMetadata, inputStream)); long expirationTime = Utils.Infinite_Time; assertTrue("Expected update to return true", azureDest.updateBlobExpiration(blobId, expirationTime)); CloudBlobMetadata metadata = azureDest.getBlobMetadata(Collections.singletonList(blobId)).get(blobId.getID()); assertEquals(expirationTime, metadata.getExpirationTime()); long deletionTime = System.currentTimeMillis() + 1000; assertTrue("Expected deletion to return true", azureDest.deleteBlob(blobId, deletionTime)); metadata = azureDest.getBlobMetadata(Collections.singletonList(blobId)).get(blobId.getID()); assertEquals(deletionTime, metadata.getDeletionTime()); }

Target:
public void testNormalFlow() throws Exception { PartitionId partitionId = new MockPartitionId(); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, System.currentTimeMillis(), Utils.Infinite_Time, blobSize, CloudBlobMetadata.EncryptionOrigin.VCR, vcrKmsContext, cryptoAgentFactory); assertTrue("Expected upload to return true", azureDest.uploadBlob(blobId, blobSize, cloudBlobMetadata, inputStream)); assertFalse("Expected duplicate upload to return false", azureDest.uploadBlob(blobId, blobSize, cloudBlobMetadata, inputStream)); long expirationTime = Utils.Infinite_Time; assertTrue("Expected update to return true", azureDest.updateBlobExpiration(blobId, expirationTime)); CloudBlobMetadata metadata = azureDest.getBlobMetadata(Collections.singletonList(blobId)).get(blobId.getID()); assertEquals(expirationTime, metadata.getExpirationTime()); long deletionTime = System.currentTimeMillis() + 1000; assertTrue("Expected deletion to return true", azureDest.deleteBlob(blobId, deletionTime)); metadata = azureDest.getBlobMetadata(Collections.singletonList(blobId)).get(blobId.getID()); assertEquals(deletionTime, metadata.getDeletionTime()); }
Source:
public InnerBuilder newBuilder( final KieProject project) { Path nioPath = Paths.convert(project.getRootPath()); Optional<KieAFBuilder> builder = builderUtils.getBuilder(project.getRootPath().toURI(),nioPath); if(!builder.isPresent()){ throw new RuntimeException("Isn't possible create a Builder :"+ project.getRootPath().toURI() + " because the project isn't a Git FS project"); } DefaultKieAFBuilder defaultKieBuilder = (DefaultKieAFBuilder)builder.get(); Path workingDir = defaultKieBuilder.getInfo().getPrjPath(); KieModuleMetaData kieModuleMetaData =kieModuleMetaDataCache.getMetadata(workingDir); if(kieModuleMetaData != null){ return getInnerBuilderWithAlreadyPresentData(project, kieModuleMetaData); }else { return runNewBuild(project, builder.get()); } }

Target:
public InnerBuilder newBuilder(final KieProject project) { Path nioPath = Paths.convert(project.getRootPath()); Optional<KieAFBuilder> builder = builderUtils.getBuilder(project.getRootPath().toURI(), nioPath); if (!builder.isPresent()) { throw new RuntimeException("Isn't possible create a Builder :" + project.getRootPath().toURI() + " because the project isn't a Git FS project"); } DefaultKieAFBuilder defaultKieBuilder = (DefaultKieAFBuilder) builder.get(); Path workingDir = defaultKieBuilder.getInfo().getPrjPath(); KieModuleMetaData kieModuleMetaData = (KieModuleMetaData)kieModuleMetaDataCache.getKieModuleMetaData(workingDir); if (kieModuleMetaData != null) { return getInnerBuilderWithAlreadyPresentData(project, kieModuleMetaData); } else { return runNewBuild(project, builder.get()); } }
Source:
Builder name(String filename) { if (filename == null || filename.isEmpty()) { throw new IllegalArgumentException("A non-empty filename must be provided"); } this.fileName = filename; return this; }

Target:
Builder name(String filename) { if (filename == null || filename.isEmpty()) { throw new IllegalArgumentException("A non-empty filename must be provided"); } if (filename.endsWith(".realm")) { if (filename.length() == 6) { throw new IllegalArgumentException("'.realm' is not a valid filename"); } else { filename = filename.substring(0, filename.length() - 6); } } this.filename = filename; return this; }
Source:
public void run(final int iteration) { final long iterationBegin = System.currentTimeMillis(); final Map<Long, Document> workloadMap = memoryStore.getAll(); final List<Document> workload = new ArrayList<>(workloadMap.values()); final int numEMBlocks = memoryStore.getNumBlocks(); final int numDocuments = workload.size(); int numSampledDocuments = 0; for (int batchIdx = 0; batchIdx < numMiniBatchPerIter; batchIdx++) { resetTracers(); final int batchSize = numDocuments / numMiniBatchPerIter + ((numDocuments % numMiniBatchPerIter > batchIdx) ? 1 : 0); sampler.sample(workload.subList(numSampledDocuments, numSampledDocuments + batchSize), computeTracer, pushTracer, pullTracer); numSampledDocuments += batchSize; LOG.log(Level.INFO, "{0} documents out of {1} have been sampled", new Object[]{numSampledDocuments, numDocuments}); } final double elapsedTime = (System.currentTimeMillis() - iterationBegin) / 1000.0D; LOG.log(Level.INFO, "Start computing log likelihood"); final List<int[]> wordTopicCounts = parameterWorker.pull(vocabList); final int[] wordTopicCountsSummary = wordTopicCounts.remove(numVocabs); final Metrics appMetrics = buildAppMetrics(statCalculator.computeDocLLH(workload), statCalculator.computeWordLLH(wordTopicCounts, wordTopicCountsSummary)); final WorkerMetrics workerMetrics = buildMetricsMsg(iteration, appMetrics, numEMBlocks, workload.size(), elapsedTime); LOG.log(Level.INFO, "WorkerMetrics {0}", workerMetrics); sendMetrics(workerMetrics); }

Target:
public void run(final int iteration) { final long iterationBeginMs = System.currentTimeMillis(); resetTracers(); final Map<Long, Document> workloadMap = memoryStore.getAll(); final List<Document> workload = new ArrayList<>(workloadMap.values()); final int numEMBlocks = memoryStore.getNumBlocks(); final int numDocuments = workload.size(); int numSampledDocuments = 0; for (int batchIdx = 0; batchIdx < numMiniBatchPerIter; batchIdx++) { final int batchSize = numDocuments / numMiniBatchPerIter + ((numDocuments % numMiniBatchPerIter > batchIdx) ? 1 : 0); sampler.sample(workload.subList(numSampledDocuments, numSampledDocuments + batchSize), computeTracer, pushTracer, pullTracer); numSampledDocuments += batchSize; LOG.log(Level.INFO, "{0} documents out of {1} have been sampled", new Object[]{numSampledDocuments, numDocuments}); } final double elapsedTimeSec = (System.currentTimeMillis() - iterationBeginMs) / 1000.0D; LOG.log(Level.INFO, "Start computing log likelihood"); final List<int[]> wordTopicCounts = parameterWorker.pull(vocabList); final int[] wordTopicCountsSummary = wordTopicCounts.remove(numVocabs); final Metrics appMetrics = buildAppMetrics(statCalculator.computeDocLLH(workload), statCalculator.computeWordLLH(wordTopicCounts, wordTopicCountsSummary)); final WorkerMetrics workerMetrics = buildMetricsMsg(iteration, appMetrics, numEMBlocks, workload.size(), elapsedTimeSec); LOG.log(Level.INFO, "WorkerMetrics {0}", workerMetrics); sendMetrics(workerMetrics); }
Source:
public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, List<IBinding> suggestions, boolean isLastParameter) throws CModelException { List<Variable> typeMatches = evaluateVisibleMatches(expectedType, suggestions); typeMatches = removeDuplicates(typeMatches); orderMatches(typeMatches, paramName); ICompletionProposal[] ret = new ICompletionProposal[typeMatches.size()]; int i = 0; int replacementLength = 0; for (Iterator<Variable> it = typeMatches.iterator(); it.hasNext();) { Variable v = it.next(); if (i == 0) { fAlreadyMatchedNames.add(v.name); replacementLength = v.name.length(); } String displayString = v.name; final char[] triggers; if (isLastParameter) { triggers = v.triggerChars; } else { triggers = new char[v.triggerChars.length + 1]; System.arraycopy(v.triggerChars, 0, triggers, 0, v.triggerChars.length); triggers[triggers.length - 1] = ','; } ret[i++] = new PositionBasedCompletionProposal(v.name, pos, replacementLength, getImage(v.descriptor), displayString, null, null, triggers); } return ret; }

Target:
public ICompletionProposal[] parameterProposals(IType expectedType, String paramName, Position pos, List<IBinding> suggestions, boolean isLastParameter) throws CModelException { List<Variable> typeMatches = evaluateVisibleMatches(expectedType, suggestions); typeMatches = removeDuplicates(typeMatches); orderMatches(typeMatches, paramName); ICompletionProposal[] ret = new ICompletionProposal[typeMatches.size()]; int i = 0; int replacementLength = 0; for (Variable v : typeMatches) { if (i == 0) { fAlreadyMatchedNames.add(v.name); replacementLength = v.name.length(); } String displayString = v.name; final char[] triggers; if (isLastParameter) { triggers = v.triggerChars; } else { triggers = new char[v.triggerChars.length + 1]; System.arraycopy(v.triggerChars, 0, triggers, 0, v.triggerChars.length); triggers[triggers.length - 1] = ','; } ret[i++] = new PositionBasedCompletionProposal(v.name, pos, replacementLength, getImage(v.descriptor), displayString, null, null, triggers); } return ret; }
Source:
protected static Frame makeFrame(final ChannelHandlerContext ctx, final RequestMessage msg, final MessageSerializer serializer, final boolean useBinary, final List<Object> aggregate, final ResponseStatusCode code, final Map<String,Object> responseMetaData) throws Exception { Context context = new Context(msg, ctx, null, null, null, null); ResponseHandlerContext rhc = new ResponseHandlerContext(context); return makeFrame(rhc, msg, serializer, useBinary, aggregate, code, responseMetaData); }

Target:
protected static Frame makeFrame(final ChannelHandlerContext ctx, final RequestMessage msg, final MessageSerializer serializer, final boolean useBinary, final List<Object> aggregate, final ResponseStatusCode code, final Map<String,Object> responseMetaData) throws Exception { final Context context = new Context(msg, ctx, null, null, null, null); final ResponseHandlerContext rhc = new ResponseHandlerContext(context); return makeFrame(rhc, msg, serializer, useBinary, aggregate, code, responseMetaData); }
Source:
protected void onPostExecute(Bitmap bitmapResult) { super.onPostExecute(bitmapResult); if (bitmapResult == null || cancelAsyncTasks || !isAdded() || map == null) { return; } Person marker = person; if (!markers.contains(marker)) { markers.add(marker); clusterManager.addItem(marker); } if (marker.getEmail().equals(MainApplication.emailBeingTracked)) { Log.d(TAG, "onPostExecute - showInfoWindow open"); map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), DEFAULT_ZOOM)); } else if (MainApplication.firstTimeZoom && MainApplication.emailBeingTracked == null && MainApplication.user.getEmail() != null && marker.getEmail().equals(MainApplication.user.getEmail()) && marker.getPosition() != null) { MainApplication.firstTimeZoom = false; map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), DEFAULT_ZOOM)); } clusterManager.cluster(); }

Target:
protected void onPostExecute(Bitmap bitmapResult) { super.onPostExecute(bitmapResult); if (bitmapResult == null || cancelAsyncTasks || !isAdded() || map == null) { return; } Person marker = person; if (!markers.contains(marker)) { markers.add(marker); clusterManager.addItem(marker); } else { clusterManager.removeItem(marker); clusterManager.addItem(marker); } if (marker.getEmail().equals(MainApplication.emailBeingTracked)) { Log.d(TAG, "onPostExecute - showInfoWindow open"); map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), DEFAULT_ZOOM)); } else if (MainApplication.firstTimeZoom && MainApplication.emailBeingTracked == null && MainApplication.user.getEmail() != null && marker.getEmail().equals(MainApplication.user.getEmail()) && marker.getPosition() != null) { MainApplication.firstTimeZoom = false; map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), DEFAULT_ZOOM)); } clusterManager.cluster(); }
Source:
public static <K, V> HashMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new HashMap<>(HashArrayMappedTrie.<K, V> empty().put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4)); }

Target:
public static <K, V> HashMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return of(k1, v1, k2, v2, k3, v3).put(k4, v4); }
Source:
public void connect(ITerminalControl control) { fControl = control; new OutputReadJob(fProcess.getInputStream()).schedule(); new OutputReadJob(fProcess.getErrorStream()).schedule(); fControl.setState(TerminalState.CONNECTED); }

Target:
public void connect(ITerminalControl control) { if (control == null) { throw new IllegalArgumentException("Invalid ITerminalControl"); } fControl = control; new OutputReadJob(fProcess.getInputStream()).schedule(); new OutputReadJob(fProcess.getErrorStream()).schedule(); fControl.setState(TerminalState.CONNECTED); }
Source:
public void setAllowDeletes(final boolean canDelete) { allowAnyDeletes = canDelete; if (!canDelete) allowBranchDeletes = false; }

Target:
public void setAllowDeletes(final boolean canDelete) { allowAnyDeletes = canDelete; }
Source:
public void update(ModelEvent event) { if (event.part == ModelPart.MODEL) { this.model = (Model) event.data; final String[] classifiers = new String[4]; classifiers[0] = Resources.getMessage("ViewClassificationAttributes.7"); classifiers[1] = Resources.getMessage("ViewClassificationAttributes.8"); classifiers[2] = Resources.getMessage("ViewClassificationAttributes.9"); classifiers[3] = Resources.getMessage("ViewClassificationAttributes.10"); this.combo.setItems(classifiers); this.combo.select(0); this.configs = new HashMap<String, ARXClassificationConfiguration>(); this.configs.put(classifiers[0], this.model.getClassificationModel().getLogisticRegressionConfiguration()); this.configs.put(classifiers[1], this.model.getClassificationModel().getNaiveBayesConfiguration()); this.configs.put(classifiers[2], this.model.getClassificationModel().getRandomForestConfiguration()); this.configs.put(classifiers[3], this.model.getClassificationModel().getSVMConfiguration()); updateTable(this.model.getClassificationModel().getLogisticRegressionConfiguration()); } }

Target:
public void update(ModelEvent event) { if (event.part == ModelPart.MODEL) { this.model = (Model) event.data; final String[] classifiers = new String[4]; classifiers[0] = Resources.getMessage("ViewClassificationAttributes.7"); classifiers[1] = Resources.getMessage("ViewClassificationAttributes.8"); classifiers[2] = Resources.getMessage("ViewClassificationAttributes.9"); classifiers[3] = Resources.getMessage("ViewClassificationAttributes.10"); this.combo.setItems(classifiers); this.configs = new HashMap<String, ARXClassificationConfiguration>(); this.configs.put(classifiers[0], this.model.getClassificationModel().getLogisticRegressionConfiguration()); this.configs.put(classifiers[1], this.model.getClassificationModel().getNaiveBayesConfiguration()); this.configs.put(classifiers[2], this.model.getClassificationModel().getRandomForestConfiguration()); this.configs.put(classifiers[3], this.model.getClassificationModel().getSVMConfiguration()); this.combo.select(0); updateTable(this.model.getClassificationModel().getLogisticRegressionConfiguration()); } }
Source:
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { if (!isAdded()) { return; } super.onCreateOptionsMenu(menu, inflater); optionsMenu = menu; FeedMenuHandler.onCreateOptionsMenu(inflater, menu); iconTintManager.updateTint(); if (feed != null) { MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, feed.getTitle()); } if (feed == null || feed.getLink() == null) { menu.findItem(R.id.share_link_item).setVisible(false); menu.findItem(R.id.visit_website_item).setVisible(false); } isUpdatingFeed = MenuItemUtils.updateRefreshMenuItem(menu, R.id.refresh_item, updateRefreshMenuItemChecker); }

Target:
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { if (!isAdded()) { return; } super.onCreateOptionsMenu(menu, inflater); optionsMenu = menu; FeedMenuHandler.onCreateOptionsMenu(inflater, menu); iconTintManager.updateTint(); if (feed != null) { MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, feed.getTitle()); } else { MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, ""); } if (feed == null || feed.getLink() == null) { menu.findItem(R.id.share_link_item).setVisible(false); menu.findItem(R.id.visit_website_item).setVisible(false); } isUpdatingFeed = MenuItemUtils.updateRefreshMenuItem(menu, R.id.refresh_item, updateRefreshMenuItemChecker); }
Source:
public ApplicabilityIds getApplicabilityIds() { ApplicabilityIds ids = new ApplicabilityIds(); return ids; }

Target:
public ApplicabilityIds getApplicabilityIds() { return null; }
Source:
private void findAndPerformClick(final By addSubmitButtonLocator) { final WebElement addSubmitButton = find(addSubmitButtonLocator); final Actions builder = new Actions(driver); ((JavascriptExecutor) driver).executeScript( "arguments[0].scrollIntoView();", addSubmitButton ); builder.moveToElement(addSubmitButton).click(addSubmitButton); builder.perform(); }

Target:
private void findAndPerformClick(final By addSubmitButtonLocator) { final WebElement addSubmitButton = find(addSubmitButtonLocator); final Actions builder = new Actions(driver); new Scroller().scrollIntoView(addSubmitButton, driver); addSubmitButton.click(); builder.perform(); }
Source:
protected void finishModelStage(OperationContext context, ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, Resource model) throws OperationFailedException { super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); if (!context.isBooting()) { TransformerOperationAttachment attachment = TransformerOperationAttachment.getOrCreate(context); attachment.attachIfAbsent(PreviousAttributeValueOperationContextAttachment.KEY, new PreviousAttributeValueOperationContextAttachment(oldValue.clone())); } }

Target:
protected void finishModelStage(OperationContext context, ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, Resource model) throws OperationFailedException { super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); if (!context.isBooting()) { TransformerOperationAttachment attachment = TransformerOperationAttachment.getOrCreate(context); InitialAttributeValueOperationContextAttachment valuesAttachment = attachment.getAttachment(InitialAttributeValueOperationContextAttachment.INITIAL_VALUES_ATTACHMENT); if (valuesAttachment == null) { valuesAttachment = new InitialAttributeValueOperationContextAttachment(); attachment.attach(InitialAttributeValueOperationContextAttachment.INITIAL_VALUES_ATTACHMENT, valuesAttachment); } valuesAttachment.putIfAbsentInitialValue(Operations.getPathAddress(operation), attributeName, oldValue); } }
Source:
private IStatus copy(final StringBuilder sb, final IProgressMonitor monitor) { ITmfEventRequest request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY, fStart, (int) (fEnd - fStart + 1), ExecutionType.FOREGROUND) { @Override public void handleData(ITmfEvent event) { super.handleData(event); if (monitor.isCanceled()) { cancel(); return; } monitor.worked(1); if (fFilter == null || fFilter.matches(event)) { try { boolean needTab = false; for (TmfEventTableColumn column : fColumns) { if (needTab) { sb.append('\t'); } sb.append(column.getItemString(event)); needTab = true; } sb.append('\n'); } catch (java.lang.OutOfMemoryError e) { sb.setLength(0); sb.trimToSize(); showErrorDialog(); cancel(); } } } }; fTrace.sendRequest(request); try { request.waitForCompletion(); } catch (InterruptedException e) { Activator.getDefault().logError("Wait for completion interrupted for copy to clipboard ", e); } return Status.OK_STATUS; }

Target:
private IStatus copy(final StringBuilder sb, final IProgressMonitor monitor) { ITmfEventRequest request = new TmfEventRequest(ITmfEvent.class, TmfTimeRange.ETERNITY, fStartRank, (int) (fEndRank - fStartRank + 1), ExecutionType.FOREGROUND) { @Override public void handleData(ITmfEvent event) { super.handleData(event); if (monitor.isCanceled()) { cancel(); return; } monitor.worked(1); if (fFilter == null || fFilter.matches(event)) { try { boolean needTab = false; for (TmfEventTableColumn column : fColumns) { if (needTab) { sb.append('\t'); } sb.append(column.getItemString(event)); needTab = true; } sb.append(LINE_SEPARATOR); } catch (java.lang.OutOfMemoryError e) { sb.setLength(0); sb.trimToSize(); showErrorDialog(); cancel(); } } } }; fTrace.sendRequest(request); try { request.waitForCompletion(); } catch (InterruptedException e) { Activator.getDefault().logError("Wait for completion interrupted for copy to clipboard ", e); } return Status.OK_STATUS; }
Source:
public boolean hasNext() { while (currentChunk != null) { if (alignmentIterator == null) { if (currentChunk.getChunkStart() < recordRangleInfo.getTotalReferencesLength()) { alignmentIterator = new SRAAlignmentIterator(run, header, cachedReferences, recordRangleInfo, currentChunk); if (validationStringency != null) { alignmentIterator.setValidationStringency(validationStringency); } } } if (alignmentIterator != null && alignmentIterator.hasNext()) { return true; } if (unalignmentIterator == null) { if (currentChunk.getChunkEnd() > recordRangleInfo.getTotalReferencesLength()) { unalignmentIterator = new SRAUnalignmentIterator(run, header, recordRangleInfo, currentChunk); if (validationStringency != null) { unalignmentIterator.setValidationStringency(validationStringency); } } } if (unalignmentIterator != null && unalignmentIterator.hasNext()) { return true; } alignmentIterator = null; unalignmentIterator = null; if (chunksIterator.hasNext()) { currentChunk = chunksIterator.next(); } else { currentChunk = null; } } return false; }

Target:
public boolean hasNext() { while (currentChunk != null) { if (alignmentIterator == null) { if (currentChunk.getChunkStart() < recordRangeInfo.getTotalReferencesLength()) { alignmentIterator = new SRAAlignmentIterator(accession, run, header, cachedReferences, recordRangeInfo, currentChunk); if (validationStringency != null) { alignmentIterator.setValidationStringency(validationStringency); } } } if (alignmentIterator != null && alignmentIterator.hasNext()) { return true; } if (unalignmentIterator == null) { if (currentChunk.getChunkEnd() > recordRangeInfo.getTotalReferencesLength()) { unalignmentIterator = new SRAUnalignmentIterator(accession, run, header, recordRangeInfo, currentChunk); if (validationStringency != null) { unalignmentIterator.setValidationStringency(validationStringency); } } } if (unalignmentIterator != null && unalignmentIterator.hasNext()) { return true; } alignmentIterator = null; unalignmentIterator = null; if (chunksIterator.hasNext()) { currentChunk = chunksIterator.next(); } else { currentChunk = null; } } return false; }
Source:
public void prepareClusterRoleChange() { if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE && replicationManager != null) { replicationManager.prepareClusterRoleChange(); } else { log.warn("Illegal prepareSiteRoleChange when cluster{} with role {}", localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); } }

Target:
public void prepareClusterRoleChange() { if (localClusterDescriptor.getRole() == ClusterRole.ACTIVE && replicationManager != null) { replicationManager.prepareClusterRoleChange(); } else { log.warn("Illegal prepareClusterRoleChange when cluster{} with role {}", localClusterDescriptor.getClusterId(), localClusterDescriptor.getRole()); } }
Source:
protected ICommand getAfterSetCommand(SetRequest request) { CompositeCommand compositeCommand = new CompositeCommand("Set CapsulePart Type"); EStructuralFeature feature = request.getFeature(); if (UMLPackage.eINSTANCE.getTypedElement_Type().equals(feature)) { Object newValue = request.getValue(); EObject elementToEdit = request.getElementToEdit(); if (elementToEdit instanceof Property && newValue instanceof Type) { Property property = (Property) elementToEdit; Type newType = (Type) newValue; if (CapsulePartUtils.completesCycle(newType, property)) { LiteralInteger newLowerValue = (LiteralInteger) ModelUtils.create((EObject) null, UMLPackage.Literals.LITERAL_INTEGER); newLowerValue.setValue(0); ICommand setLowerBoundsCommand = new SetValueCommand(new SetRequest(request.getElementToEdit(), UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue(), newLowerValue)); compositeCommand.add(setLowerBoundsCommand); } if ((Strings.isNullOrEmpty((property).getName()) || NewElementUtil.isCreatedElement(property))) { String name = newType.getName(); if (!Strings.isNullOrEmpty(name)) { String newName = NewElementUtil.getUniqueName(property, newType); ICommand setNameCommand = new SetValueCommand(new SetRequest(request.getElementToEdit(), UMLPackage.eINSTANCE.getNamedElement_Name(), newName)); compositeCommand.add(setNameCommand); } } } } return compositeCommand.isEmpty() ? super.getAfterSetCommand(request) : compositeCommand; }

Target:
protected ICommand getAfterSetCommand(SetRequest request) { CompositeCommand compositeCommand = new CompositeCommand("Set CapsulePart Type"); EStructuralFeature feature = request.getFeature(); if (UMLPackage.eINSTANCE.getTypedElement_Type().equals(feature)) { Object newValue = request.getValue(); EObject elementToEdit = request.getElementToEdit(); if (elementToEdit instanceof Property && newValue instanceof Type) { Property property = (Property) elementToEdit; Type newType = (Type) newValue; if (CapsulePartUtils.completesCycle(newType, property)) { LiteralInteger newLowerValue = (LiteralInteger) ModelUtils.create(property, UMLPackage.Literals.LITERAL_INTEGER); newLowerValue.setValue(0); ICommand setLowerBoundsCommand = new SetValueCommand(new SetRequest(request.getElementToEdit(), UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue(), newLowerValue)); compositeCommand.add(setLowerBoundsCommand); } if ((Strings.isNullOrEmpty((property).getName()) || NewElementUtil.isCreatedElement(property))) { String name = newType.getName(); if (!Strings.isNullOrEmpty(name)) { String newName = NewElementUtil.getUniqueName(property, newType); ICommand setNameCommand = new SetValueCommand(new SetRequest(request.getElementToEdit(), UMLPackage.eINSTANCE.getNamedElement_Name(), newName)); compositeCommand.add(setNameCommand); } } } } return compositeCommand.isEmpty() ? super.getAfterSetCommand(request) : compositeCommand; }
Source:
@Override public void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; readingList = null; super.onDestroyView(); }

Target:
@Override public void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; readingList = null; readingLists.set(Collections.<ReadingList>emptyList()); super.onDestroyView(); }
Source:
private void stopLogging() { NetworkTrafficInterceptor networkTrafficInterceptor = driver.getProxy(); if ( networkTrafficInterceptor != null ) { Har har = networkTrafficInterceptor.getHar(); for (HarEntry entry : har.getLog().getEntries()) { URL url = null; try { url = new URL(entry.getRequest().getUrl()); if (url.getHost().contains("wikia")) { Boolean isHttps = entry.getRequest().getUrl().startsWith("https"); PageObjectLogging.log("VISITED URL", "Url: " + entry.getRequest().getUrl(), !Configuration.getForceHttps() || isHttps); } } catch (MalformedURLException e) { PageObjectLogging.log("MALFORMED URL", "Url: " + entry.getRequest().getUrl(), false); } } } String html = VelocityWrapper.fillLastLogRow(); CommonUtils.appendTextToFile(logPath, html); testStarted = false; }

Target:
private void stopLogging() { driver = DriverProvider.getActiveDriver(); if ( driver.getProxy() != null && Configuration.getForceHttps()) { Har har = driver.getProxy().getHar(); for (HarEntry entry : har.getLog().getEntries()) { URL url = null; try { url = new URL(entry.getRequest().getUrl()); if (url.getHost().contains("wikia")) { Boolean isHttps = entry.getRequest().getUrl().startsWith("https"); PageObjectLogging.log("VISITED URL", "Url: " + entry.getRequest().getUrl(), !Configuration.getForceHttps() || isHttps); } } catch (MalformedURLException e) { PageObjectLogging.log("MALFORMED URL", "Url: " + entry.getRequest().getUrl(), false); } } } String html = VelocityWrapper.fillLastLogRow(); CommonUtils.appendTextToFile(logPath, html); testStarted = false; }
Source:
public void nextPage() { if (!this.hasNext()) return; model.setPage(model.getPage() + 1); model.setFetchData(null, model.getCurrentStartCursor(), false); this.fetch(false); }

Target:
public void nextPage() { if (!this.hasNext()) { return; } model.setPage(model.getPage() + 1); model.setFetchData(null, model.getCurrentStartCursor(), false); this.fetch(false); }
Source:
private void finalizeMetadataChunk() { finalBlobProperties = new BlobProperties(getBlobSize(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs()); if (getNumDataChunks() > 1) { List<StoreKey> orderedChunkIdList = new ArrayList<>(indexToChunkIds.values()); buf = MetadataContentSerDe.serializeMetadataContent(routerConfig.routerMaxPutChunkSizeBytes, getBlobSize(), orderedChunkIdList); onFillComplete(false); } else { blobId = (BlobId) indexToChunkIds.get(0); state = ChunkState.Complete; operationCompleted.set(true); } }

Target:
private void finalizeMetadataChunk() { finalBlobProperties = new BlobProperties(getBlobSize(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs()); if (getNumDataChunks() > 1) { List<StoreKey> orderedChunkIdList = new ArrayList<>(indexToChunkIds.values()); buf = MetadataContentSerDe.serializeMetadataContent(routerConfig.routerMaxPutChunkSizeBytes, getBlobSize(), orderedChunkIdList); onFillComplete(false); } else { blobId = (BlobId) indexToChunkIds.get(0); state = ChunkState.Complete; operationCompleted = true; } }
Source:
public void testLoadPropertiesWithProperties() throws Exception { Properties testProperties = PROPERTIES_LOADER.loadProperties(propertiesFile.getCanonicalPath()); Assert.assertEquals( "Returns the correct properties", exampleMap.entrySet(), testProperties.entrySet()); }

Target:
public void testLoadPropertiesWithProperties() throws Exception { Properties testProperties = PROPERTIES_LOADER.loadProperties(propertiesFile.getCanonicalPath()); assertThat(testProperties.entrySet(), equalTo(EXAMPLE_MAP.entrySet())); }
Source:
public JsonInclude.Value getDefaultInclusion(Class<?> baseType, Class<?> propertyType, JsonInclude.Value defaultIncl) { JsonInclude.Value v0 = getConfigOverride(propertyType).getIncludeAsProperty(); if (v0 != null) { return v0; } JsonInclude.Value v1 = getConfigOverride(baseType).getInclude(); if (v1 != null) { return v1; } return defaultIncl; }

Target:
public JsonInclude.Value getDefaultInclusion(Class<?> baseType, Class<?> propertyType, JsonInclude.Value defaultIncl) { JsonInclude.Value baseOverride = getConfigOverride(baseType).getInclude(); JsonInclude.Value propOverride = getConfigOverride(propertyType).getIncludeAsProperty(); JsonInclude.Value result = JsonInclude.Value.mergeAll(defaultIncl, baseOverride, propOverride); return result; }
Source:
private boolean isVmDevicesChanged(Guid vmId, String vdsmHash, long fetchTime) { if (vdsmHash != null) { TimestampedHash previousHash = vmDevicesHashes.get(vmId); if (previousHash == null || previousHash.getFetchTime() < fetchTime) { vmDevicesHashes.put(vmId, new TimestampedHash(vdsmHash, fetchTime)); return previousHash == null || !Objects.equals(previousHash.getHash(), vdsmHash); } else { return false; } } else { return false; } }

Target:
private boolean isVmDevicesChanged(Guid vmId, String vdsmHash, long fetchTime) { if (vdsmHash == null) { return false; } synchronized (devicesStatusesLock) { DevicesStatus previousStatus = vmDevicesStatuses.get(vmId); boolean previousHashUpdate = previousStatus != null && UPDATE_HASH.equals(previousStatus.getHash()); if (previousStatus == null || previousHashUpdate || fetchTimeBefore(previousStatus.getFetchTime(), fetchTime)) { vmDevicesStatuses.put(vmId, new DevicesStatus(vdsmHash, fetchTime)); return previousStatus == null || !previousHashUpdate && !Objects.equals(previousStatus.getHash(), vdsmHash); } else { return false; } } }
Source:
private static void fillRepresentations(Swagger swagger, Contract contract) { if (swagger.getDefinitions() == null) { return; } for (String key : swagger.getDefinitions().keySet()) { Representation representation = new Representation(); Model model = swagger.getDefinitions().get(key); representation.setDescription(model.getDescription()); representation.setName(key); representation.setRaw(false); fillRwadefProperties(model, representation); contract.getRepresentations().add(representation); } }

Target:
private static void fillRepresentations(Swagger swagger, Contract contract) { if (swagger.getDefinitions() == null) { return; } for (String key : swagger.getDefinitions().keySet()) { Model model = swagger.getDefinitions().get(key); Representation representation = new Representation(); representation.setDescription(model.getDescription()); representation.setName(key); representation.setRaw(false); fillRwadefProperties(model, representation); contract.getRepresentations().add(representation); } }
Source:
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) { List<String> hosts = model.listHosts(); if (namePattern != null) { final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate(); hosts = hosts.stream() .filter(matchesPattern) .collect(Collectors.toList()); } if (!hostSelectors.isEmpty()) { final Map<String, Map<String, String>> hostsAndLabels = hosts.stream() .collect(Collectors.toMap(Function.identity(), host -> model.getHostStatus(host).getLabels() ) ); final List<HostSelector> selectors = hostSelectors.stream() .map(HostSelector::parse) .collect(Collectors.toList()); final HostMatcher matcher = new HostMatcher(hostsAndLabels); hosts = matcher.getMatchingHosts(selectors); } return hosts; }

Target:
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) { List<String> hosts = model.listHosts(); if (namePattern != null) { final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate(); hosts = hosts.stream() .filter(matchesPattern) .collect(Collectors.toList()); } if (!hostSelectors.isEmpty()) { final List<HostSelector> selectors = hostSelectors.stream() .map(selectorStr -> { final HostSelector parsed = HostSelector.parse(selectorStr); if (parsed == null) { throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST) .entity("Invalid host selector: " + selectorStr) .build() ); } return parsed; }) .collect(Collectors.toList()); final Map<String, Map<String, String>> hostsAndLabels = hosts.stream() .collect(Collectors.toMap(Function.identity(), host -> model.getHostStatus(host).getLabels() ) ); final HostMatcher matcher = new HostMatcher(hostsAndLabels); hosts = matcher.getMatchingHosts(selectors); } return hosts; }