auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean set(ItemStack itemStack, Map<Key<?>, Object> keyValues) { itemStack.setItemDamage(itemStack.getMaxDamage() - (int) keyValues.get(Keys.ITEM_DURABILITY)); final boolean unbreakable = (boolean) keyValues.get(Keys.UNBREAKABLE); if (unbreakable) { itemStack.setItemDamage(0); } if (!itemStack.hasTagCompound()) { itemStack.setTagCompound(new NBTTagCompound()); } <START> itemStack.getTagCompound().setBoolean("Unbreakable", unbreakable); <END> return true; }</code><technical_language>Extract string NbtDataUtil please</technical_language>

Target:
public boolean set(ItemStack itemStack, Map<Key<?>, Object> keyValues) { itemStack.setItemDamage(itemStack.getMaxDamage() - (int) keyValues.get(Keys.ITEM_DURABILITY)); final boolean unbreakable = (boolean) keyValues.get(Keys.UNBREAKABLE); if (unbreakable) { itemStack.setItemDamage(0); } if (!itemStack.hasTagCompound()) { itemStack.setTagCompound(new NBTTagCompound()); } itemStack.getTagCompound().setBoolean(NbtDataUtil.ITEM_UNBREAKABLE, unbreakable); return true; }
Source:
<code>protected void publishEvents(ZbResponse zbResponse) { String zbResponseStr = zbResponse.getMessage(); String id = this.extractIdFromZbResponse(zbResponseStr); logger.debug("Found event from ID {}", id); if (id == null) { logger.debug(" => ignoring null ID"); return; } Vector<String> listOfItemNames = ZibaseBinding.getBindingProvider().getItemNamesById(id); if (listOfItemNames == null) { return; } logger.debug("trying to publish events for {}", id); for (String itemName : listOfItemNames) { Item item = ZibaseBinding.getBindingProvider().getItemByName(itemName); <START> if (item != null) { <END> ZibaseBindingConfig config = ZibaseBinding.getBindingProvider() .getItemConfigByUniqueId(itemName + "_" + id); logger.debug("Getting config for (id = {}) ", itemName, id); if (config != null) { synchronized (item) { org.openhab.core.types.State value = config.getOpenhabStateFromZibaseValue(zibase, zbResponseStr); logger.debug("publishing update for : {}", itemName, value); eventPubisher.postUpdate(itemName, value); } } } } }</code><technical_language>consider inverting this if</technical_language>

Target:
protected void publishEvents(ZbResponse zbResponse) { String zbResponseStr = zbResponse.getMessage(); String id = this.extractIdFromZbResponse(zbResponseStr); logger.debug("Found event from ID {}", id); if (id == null) { logger.debug(" => ignoring null ID"); return; } Vector<String> listOfItemNames = ZibaseBinding.getBindingProvider().getItemNamesById(id); if (listOfItemNames == null) { return; } logger.debug("trying to publish events for {}", id); for (String itemName : listOfItemNames) { Item item = ZibaseBinding.getBindingProvider().getItemByName(itemName); if (item == null) { continue; } ZibaseBindingConfig config = ZibaseBinding.getBindingProvider() .getItemConfigByUniqueId(itemName + "_" + id); logger.debug("Getting config for (id = {}) ", itemName, id); if (config == null) { continue; } synchronized (item) { org.openhab.core.types.State value = config.getOpenhabStateFromZibaseValue(zibase, zbResponseStr); logger.debug("publishing update for : {}", itemName, value); eventPublisher.postUpdate(itemName, value); } } }
Source:
<code><START> @Override public <END> GlusterLocalLogicalVolumeListReturn glusterLogicalVolumeList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.logicalVolumeList").build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterLocalLogicalVolumeListReturn(response); }</code><technical_language>Coding conventions: @Override line please</technical_language>

Target:
public GlusterLocalLogicalVolumeListReturn glusterLogicalVolumeList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.logicalVolumeList").build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterLocalLogicalVolumeListReturn(response); }
Source:
<code>protected void makeInstallButton() { actionButton.classList.add("btn-primary"); actionButton.classList.remove("btn-danger"); <START> actionButton.textContent = "Install"; <END> }</code><technical_language>Missing i18n</technical_language>

Target:
protected void makeInstallButton() { actionButton.classList.add("btn-primary"); actionButton.classList.remove("btn-danger"); actionButton.textContent = constants.InstallServiceTask(); }
Source:
<code>ImmutableList<TransferSegmentRange> updateNotTransferredSegmentRangeStatus(TransferSegmentStatus newStatus, <START> List<TransferSegmentRange> beforeTransferRanges) { <END> return beforeTransferRanges.stream().map(range -> { if (range.getStatus().getSegmentState() == NOT_TRANSFERRED) { return range.updateStatus(newStatus); } return range; }).collect(ImmutableList.toImmutableList()); }</code><technical_language>Line exceeds limit</technical_language>

Target:
private ImmutableList<TransferSegmentRange> updateNotTransferredSegmentRangeStatus( TransferSegmentStatus newStatus, List<TransferSegmentRange> beforeTransferRanges) { return beforeTransferRanges.stream().map(range -> { if (range.getStatus().getSegmentState() == NOT_TRANSFERRED) { return range.updateStatus(newStatus); } return range; }).collect(ImmutableList.toImmutableList()); }
Source:
<code>protected boolean validateComponents(Map<Component, List<ComponentProcess>> components) { long filteredComponentCount = components.entrySet().stream().filter(componentEntry -> { Component component = componentEntry.getKey(); List<ComponentProcess> componentProcesses = componentEntry.getValue(); if (component.getName().equals(COMPONENT_STORM_UI_SERVER)) { return validateComponentProcesses(componentProcesses); } else if (component.getName().equals(COMPONENT_NIMBUS)) { <START> return validateComponentProcesses(componentProcesses); <END> } else { return false; } }).count(); return filteredComponentCount == 2; }</code><technical_language>simplified java if (component.getName().equals(COMPONENT_STORM_UI_SERVER) || component.getName().equals(COMPONENT_NIMBUS)) { return validateComponentProcesses(componentProcesses); } simplified a ternary operator</technical_language>

Target:
protected boolean validateComponents(Map<Component, List<ComponentProcess>> components) { long filteredComponentCount = components.entrySet().stream().filter(componentEntry -> { Component component = componentEntry.getKey(); List<ComponentProcess> componentProcesses = componentEntry.getValue(); if (component.getName().equals(COMPONENT_STORM_UI_SERVER) || component.getName().equals(COMPONENT_NIMBUS)) { return isComponentProcessesValid(componentProcesses); } else { return false; } }).count(); return filteredComponentCount == 2; }
Source:
<code>public void invoke(Long value, Context context) throws Exception { int parallelism = state.lastRecordInPartitions.length; int partition = (int) (value % parallelism); long lastRecord = state.lastRecordInPartitions[partition]; if (value < lastRecord) { state.numOutOfOrderness++; if (firstOutOfOrder) { LOG.info( "Out of order records current={} and last={} @ subtask ({} attempt)", value, lastRecord, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstOutOfOrder = false; } } else if (value == lastRecord) { state.numDuplicates++; if (firstDuplicate) { LOG.info( "Duplicate record @ subtask ({} attempt)", value, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstDuplicate = false; } } else if (lastRecord != -1) { long expectedValue = lastRecord + parallelism * parallelism; if (value != expectedValue) { state.numLostValues++; if (firstLostValue) { LOG.info( "Lost records current={}, expected={}, and last={} @ subtask ({} attempt)", value, expectedValue, lastRecord, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstLostValue = false; } } } state.lastRecordInPartitions[partition] = value; state.numOutput++; if (backpressure) { <START> if (random.nextInt(100) == 42) { Thread.sleep(100); <END> } } }</code><technical_language>Simplify Thread.sleep(1)</technical_language>

Target:
public void invoke(Long value, Context context) throws Exception { int parallelism = state.lastRecordInPartitions.length; int partition = (int) (value % parallelism); long lastRecord = state.lastRecordInPartitions[partition]; if (value < lastRecord) { state.numOutOfOrderness++; if (firstOutOfOrder) { LOG.info( "Out of order records current={} and last={} @ subtask ({} attempt)", value, lastRecord, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstOutOfOrder = false; } } else if (value == lastRecord) { state.numDuplicates++; if (firstDuplicate) { LOG.info( "Duplicate record @ subtask ({} attempt)", value, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstDuplicate = false; } } else if (lastRecord != -1) { long expectedValue = lastRecord + parallelism * parallelism; if (value != expectedValue) { state.numLostValues++; if (firstLostValue) { LOG.info( "Lost records current={}, expected={}, and last={} @ subtask ({} attempt)", value, expectedValue, lastRecord, getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getAttemptNumber()); firstLostValue = false; } } } state.lastRecordInPartitions[partition] = value; state.numOutput++; if (backpressure) { Thread.sleep(1); } }
Source:
<code>public void shouldDownloadProxyRepositoryIndex(@MavenRepository(repositoryId = REPOSITORY_RELEASES_4, setup = MavenIndexedRepositorySetup.class) Repository repository, @MavenTestArtifact(repositoryId = REPOSITORY_RELEASES_4, id = "org.carlspring.strongbox.indexes:strongbox-test", versions = { "1.0", "1.1" }, classifiers = { "javadoc", "sources" }) List<Path> artifactPaths, @MavenRepository(repositoryId = REPOSITORY_PROXY_4) @Remote(url = PROXY_4_REPOSITORY_URL) Repository proxyRepository) throws IOException { hostedRepositoryIndexCreator.apply(repository); proxyRepositoryIndexCreator.apply(proxyRepository); String url = getContextBaseUrl() + "/storages/" + STORAGE0 + "/" + REPOSITORY_PROXY_4 + "/.index/nexus-maven-repository-index.gz"; mockMvc.header(new Header("User-Agent", "Maven/*")) .get(url) .peek() .then() .statusCode(HttpStatus.OK.value()) <START> .contentType(org.carlspring.strongbox.net.MediaType.APPLICATION_X_GZIP_VALUE) <END> .body(CoreMatchers.notNullValue()); }</code><technical_language>import -> import static org.carlspring.strongbox.net.MediaType.APPLICATION_X_GZIP_VALUE;</technical_language>

Target:
public void shouldDownloadProxyRepositoryIndex(@MavenRepository(repositoryId = REPOSITORY_RELEASES_4, setup = MavenIndexedRepositorySetup.class) Repository repository, @MavenTestArtifact(repositoryId = REPOSITORY_RELEASES_4, id = "org.carlspring.strongbox.indexes:strongbox-test", versions = { "1.0", "1.1" }, classifiers = { "javadoc", "sources" }) List<Path> artifactPaths, @MavenRepository(repositoryId = REPOSITORY_PROXY_4) @Remote(url = PROXY_4_REPOSITORY_URL) Repository proxyRepository) throws IOException { hostedRepositoryIndexCreator.apply(repository); proxyRepositoryIndexCreator.apply(proxyRepository); String url = getContextBaseUrl() + "/storages/" + STORAGE0 + "/" + REPOSITORY_PROXY_4 + "/.index/nexus-maven-repository-index.gz"; mockMvc.header(new Header("User-Agent", "Maven/*")) .get(url) .peek() .then() .statusCode(HttpStatus.OK.value()) .contentType(APPLICATION_X_GZIP_VALUE) .body(CoreMatchers.notNullValue()); }
Source:
<code>private void buildPathFilters(List<Filter> filters, String fieldName, Set<String> values) throws ZepException { if (values == null || values.isEmpty()) return; final Analyzer analyzer = new LucenePathAnalyzer(); for (String value : values) { final Filter filter; String value_without_leading_wildcard = StringUtils.trimLeadingCharacter(value, '*'); if (value_without_leading_wildcard.startsWith("/")) { value = value_without_leading_wildcard.toLowerCase(); if (value.endsWith("/")) { filter = filterCache.get(PREFIX, new Term(nonAnalyzed(fieldName), value)); } else if (value.endsWith("*")) { value = value.substring(0, value.length() - 1); if (value.endsWith("*")) { value = value.substring(0, value.length() - 1); <START> } <END> filter = filterCache.get(PREFIX, new Term(nonAnalyzed(fieldName), value)); } else { filter = filterCache.get(TERMS, new Term(nonAnalyzed(fieldName), value + "/")); } } else { final MultiPhraseQuery pq = new MultiPhraseQuery(); filter = new QueryWrapperFilter(pq); List<String> tokens = getTokens(fieldName, analyzer, value); for (String token : tokens) { Term[] terms = getMatchingTerms(fieldName, reader, token); if (terms.length == 0) { pq.add(new Term(fieldName, token)); } else { pq.add(terms); } } } filters.add(filter); } }</code><technical_language>asterisks end of string? algorithm collapsed number of consecutive asterisks (or no) asterisk provide long-term benefit</technical_language>

Target:
private void buildPathFilters(List<Filter> filters, String fieldName, Set<String> values) throws ZepException { if (values == null || values.isEmpty()) return; final Analyzer analyzer = new LucenePathAnalyzer(); for (String value : values) { final Filter filter; String value_without_leading_wildcard = StringUtils.trimLeadingCharacter(value, '*'); if (value_without_leading_wildcard.startsWith("/")) { value = value_without_leading_wildcard.toLowerCase(); if (value.endsWith("/")) { filter = filterCache.get(PREFIX, new Term(nonAnalyzed(fieldName), value)); } else if (value.endsWith("*")) { value = StringUtils.trimTrailingCharacter(value, '*'); filter = filterCache.get(PREFIX, new Term(nonAnalyzed(fieldName), value)); } else { filter = filterCache.get(TERMS, new Term(nonAnalyzed(fieldName), value + "/")); } } else { final MultiPhraseQuery pq = new MultiPhraseQuery(); filter = new QueryWrapperFilter(pq); List<String> tokens = getTokens(fieldName, analyzer, value); for (String token : tokens) { Term[] terms = getMatchingTerms(fieldName, reader, token); if (terms.length == 0) { pq.add(new Term(fieldName, token)); } else { pq.add(terms); } } } filters.add(filter); } }
Source:
<code>private final boolean closeOpenStatements() { <START> boolean success = true; <END> final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); success = success ? !poolEntry.evict : false; } } openStatements.clear(); } return success; }</code><technical_language>Move boolean success = true; if (size > 0) conditional..</technical_language>

Target:
private final boolean closeOpenStatements() { final int size = openStatements.size(); if (size <= 0) { return true; } boolean success = true; for (int i = 0; i < size; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); success &= !poolEntry.evict; } } openStatements.clear(); return success; }
Source:
<code>public TaskTracker tasks() throws SemanticException { try { Database dbInMetadata = readDbMetadata(); String dbName = dbInMetadata.getName(); Task<? extends Serializable> dbRootTask = null; LoadOpType opType = getLoadOpType(dbName); switch (opType) { case LOAD_NEW: dbRootTask = createDbTask(dbInMetadata); break; case LOAD_REPLACE: case LOAD_INVALID: if (existEmptyDb(dbName)) { <START> dbRootTask = alterDbTask(dbInMetadata); <END> } else { throw new InvalidOperationException( "Database " + dbName + " is not empty. One or more tables/functions exist."); } break; case LOAD_SKIP: return tracker; } dbRootTask.addDependentTask(setOwnerInfoTask(dbInMetadata)); tracker.addTask(dbRootTask); return tracker; } catch (Exception e) { throw new SemanticException(e); } }</code><technical_language>behavior for default db ..for other DBs if database is present checkpoint property match throw error</technical_language>

Target:
public TaskTracker tasks() throws SemanticException { try { Database dbInMetadata = readDbMetadata(); String dbName = dbInMetadata.getName(); Task<? extends Serializable> dbRootTask = null; ReplLoadOpType loadDbType = getLoadDbType(dbName); switch (loadDbType) { case LOAD_NEW: dbRootTask = createDbTask(dbInMetadata); break; case LOAD_REPLACE: dbRootTask = alterDbTask(dbInMetadata); break; default: break; } if (dbRootTask != null) { dbRootTask.addDependentTask(setOwnerInfoTask(dbInMetadata)); tracker.addTask(dbRootTask); } return tracker; } catch (Exception e) { throw new SemanticException(e); } }
Source:
<code>protected void execute() { logger.debug("Querying Netatmo API"); for (String userid : credentialsCache.keySet()) { OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials.noAccessToken()) { oauthCredentials.refreshAccessToken(); } weatherBinding.execute(oauthCredentials, this.providers, this.eventPublisher); <START> welcomeBinding.execute(oauthCredentials, this.providers, this.eventPublisher); <END> } }</code><technical_language>this smarter call weather binding if weather items configured vice versa for camera items</technical_language>

Target:
protected void execute() { logger.debug("Querying Netatmo API"); for (String userid : credentialsCache.keySet()) { OAuthCredentials oauthCredentials = getOAuthCredentials(userid); if (oauthCredentials.noAccessToken()) { oauthCredentials.refreshAccessToken(); } boolean bWeather = false; boolean bCamera = false; for (final NetatmoBindingProvider provider : providers) { for (final String itemName : provider.getItemNames()) { final String sItemType = provider.getItemType(itemName); if (NETATMO_WEATHER.equals(sItemType)) { bWeather = true; } else if (NETATMO_CAMERA.equals(sItemType)) { bCamera = true; } if (bWeather && bCamera) { break; } } } if (bWeather) { weatherBinding.execute(oauthCredentials, this.providers, this.eventPublisher); } if (bCamera) { cameraBinding.execute(oauthCredentials, this.providers, this.eventPublisher); } } }
Source:
<code>public OutputBufferMemoryManager(long maxBufferedBytes, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor) { requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"); checkArgument(maxBufferedBytes > 0, "maxBufferedBytes must be > 0"); this.maxBufferedBytes = maxBufferedBytes; <START> this.systemMemoryContextSupplier = Suppliers.memoize(() -> systemMemoryContextSupplier.get()); <END> this.notificationExecutor = requireNonNull(notificationExecutor, "notificationExecutor is null"); notFull = SettableFuture.create(); notFull.set(null); }</code><technical_language>nit: Suppliers.memoize(systemMemoryContextSupplier::get)</technical_language>

Target:
public OutputBufferMemoryManager(long maxBufferedBytes, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor) { requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"); checkArgument(maxBufferedBytes > 0, "maxBufferedBytes must be > 0"); this.maxBufferedBytes = maxBufferedBytes; this.systemMemoryContextSupplier = Suppliers.memoize(systemMemoryContextSupplier::get); this.notificationExecutor = requireNonNull(notificationExecutor, "notificationExecutor is null"); notFull = SettableFuture.create(); notFull.set(null); }
Source:
<code>private List<TmfTraceElement> filterTraceElementByTimeRange(List<TmfTraceElement> elements, IProgressMonitor progressMonitor) { SubMonitor subMonitor = SubMonitor.convert(progressMonitor, elements.size()); List<TmfTraceElement> filteredElements = new ArrayList<>(); <START> for (TmfTraceElement tmfTraceElement : elements) { ITmfTimestamp traceStartTime = tmfTraceElement.getStartTime(); ITmfTimestamp traceEndTime = tmfTraceElement.getEndTime(); if (traceStartTime == null || traceEndTime == null) { Queue<TmfTraceElement> queue = new ConcurrentLinkedQueue<>(); queue.add(tmfTraceElement); UpdateTraceBoundsJob job = new UpdateTraceBoundsJob(Messages.SelectTracesWizardPage_UpdateTraceBoundsJobName, queue); job.run(subMonitor.newChild(1)); try { job.join(); } catch (InterruptedException e) { subMonitor.setCanceled(true); } traceStartTime = tmfTraceElement.getStartTime(); traceEndTime = tmfTraceElement.getEndTime(); } else { subMonitor.worked(1); } if (subMonitor.isCanceled()) { return elements; } if (isInTimeRange(traceStartTime, traceEndTime)) { filteredElements.add(tmfTraceElement); } } <END> return filteredElements; }</code><technical_language>control flow more like: List<TmfTraceElement> a = {trace elements null start end times}; List<TmfTraceElement> b = {trace elements null start end times} Run job b List<TmfTraceElement> c = {t in a\/b t intersects range}. avoiding spawn/joining a job traceElement</technical_language>

Target:
private List<TmfTraceElement> filterTraceElementByTimeRange(List<TmfTraceElement> elements, IProgressMonitor progressMonitor) { SubMonitor subMonitor = SubMonitor.convert(progressMonitor, elements.size()); List<TmfTraceElement> filteredElements = new ArrayList<>(); List<TmfTraceElement> knownBounds = new ArrayList<>(); Queue<TmfTraceElement> unknownBounds = new ConcurrentLinkedQueue<>(); Iterable<TmfTraceElement> traceElements = Iterables.concat(knownBounds, unknownBounds); for (TmfTraceElement tmfTraceElement : elements) { if (tmfTraceElement.getStartTime() == null || tmfTraceElement.getEndTime() == null) { unknownBounds.add(tmfTraceElement); } else { knownBounds.add(tmfTraceElement); } } if (!unknownBounds.isEmpty()) { UpdateTraceBoundsJob job = new UpdateTraceBoundsJob(Messages.SelectTracesWizardPage_UpdateTraceBoundsJobName, new ConcurrentLinkedQueue<>(unknownBounds)); job.run(subMonitor.newChild(1)); } for (TmfTraceElement element : traceElements) { if (isInTimeRange(element.getStartTime(), element.getEndTime())) { filteredElements.add(element); } } return filteredElements; }
Source:
<code>public boolean apply(Layer layer, SubLayer sublayer, Ability source, Game game) { for(Permanent permanent : game.getState().getBattlefield().getActivePermanents(filter, source.getControllerId(), source.getSourceId(), game)) { switch (layer) { case TypeChangingEffects_4: <START> if(!permanent.getSubtype(game).contains("Zombie")) { <END> permanent.getSubtype(game).add("Zombie"); } break; case ColorChangingEffects_5: permanent.getColor(game).setColor(ObjectColor.BLACK); break; } } return true; }</code><technical_language>need check prrmanent.hasSubtype. permanents generic subtypes missed</technical_language>

Target:
public boolean apply(Layer layer, SubLayer sublayer, Ability source, Game game) { for(Permanent permanent : game.getState().getBattlefield().getActivePermanents(filter, source.getControllerId(), source.getSourceId(), game)) { switch (layer) { case TypeChangingEffects_4: if(!permanent.hasSubtype("Zombie", game)) { permanent.getSubtype(game).add("Zombie"); } break; case ColorChangingEffects_5: permanent.getColor(game).setColor(ObjectColor.BLACK); break; } } return true; }
Source:
<code>private void removeGeoNamesMetacardsFromCatalog( String resource, ProgressCallback extractionCallback) { extractionCallback.updateProgress(0); Optional<CatalogProvider> catalogProviderOptional = catalogProviders.stream().findFirst(); if (catalogProviderOptional.isPresent()) { CatalogProvider catalogProvider = catalogProviderOptional.get(); if (StringUtils.isNotBlank(resource)) { filter = filterBuilder.allOf( filterBuilder .attribute(GeoEntryAttributes.IMPORT_LOCATION) .is() .equalTo() .text(resource), filter); } Query query = new QueryImpl( filter, 1, BATCH_SIZE, SortBy.NATURAL_ORDER, false, TimeUnit.SECONDS.toMillis(90)); QueryRequest queryRequest = new QueryRequestImpl(query); LOGGER.trace("Removing existing geonames data with filter: {}", filter); int retries = 0; while (retries < maxRetries) { boolean errorOccurred = false; List<Serializable> metacardsToDelete = null; try { QueryResponse response = catalogFramework.query(queryRequest); metacardsToDelete = response .getResults() .stream() .map(Result::getMetacard) .map(Metacard::getId) .collect(Collectors.toList()); } catch (Exception e) { LOGGER.debug("Unable to query for metacards.", e); errorOccurred = true; } if (!errorOccurred && CollectionUtils.isEmpty(metacardsToDelete)) { break; } if (!errorOccurred) { LOGGER.trace("Deleting GeoNames metacards", metacardsToDelete.size()); try { removeMetacards(catalogProvider, extractionCallback, metacardsToDelete); } catch (IngestException e) { LOGGER.debug("Unable to delete metacards.", e); errorOccurred = true; } } retries++; if (errorOccurred && retries < maxRetries) { try { <START> Thread.sleep(WAIT_TIME_MSEC); <END> } catch (InterruptedException ignore) { } } } } extractionCallback.updateProgress(50); }</code><technical_language>concern thread sleeping here</technical_language>

Target:
private void removeGeoNamesMetacardsFromCatalog( String resource, ProgressCallback extractionCallback) throws UnsupportedQueryException, SourceUnavailableException, FederationException, IngestException { extractionCallback.updateProgress(0); Optional<CatalogProvider> catalogProviderOptional = catalogProviders.stream().findFirst(); if (catalogProviderOptional.isPresent()) { CatalogProvider catalogProvider = catalogProviderOptional.get(); if (StringUtils.isNotBlank(resource)) { filter = filterBuilder.allOf( filterBuilder .attribute(GeoEntryAttributes.IMPORT_LOCATION) .is() .equalTo() .text(resource), filter); } while (true) { Query query = new QueryImpl( filter, 1, BATCH_SIZE, SortBy.NATURAL_ORDER, false, TimeUnit.SECONDS.toMillis(90)); QueryRequest queryRequest = new QueryRequestImpl(query); LOGGER.trace("Removing existing geonames data with filter: {}", filter); QueryResponse response = catalogFramework.query(queryRequest); List<Serializable> metacardsToDelete = response .getResults() .stream() .map(Result::getMetacard) .map(Metacard::getId) .collect(Collectors.toList()); if (CollectionUtils.isEmpty(metacardsToDelete)) { break; } LOGGER.trace("Deleting GeoNames metacards", metacardsToDelete.size()); removeMetacards(catalogProvider, extractionCallback, metacardsToDelete); } } extractionCallback.updateProgress(50); }
Source:
<code>public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new AsciiNameValidation() }); List<IValidation> cidrValidations = new ArrayList<IValidation>(); cidrValidations.add(new NotEmptyValidation()); if (getIpVersion().getSelectedItem() == IpVersion.IPV4) { <START> cidrValidations.add(new CidrValidation()); <END> } getCidr().validateEntity(cidrValidations.toArray(new IValidation[0])); getIpVersion().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); return getName().getIsValid() && getCidr().getIsValid() && getIpVersion().getIsValid(); }</code><technical_language>I notice before, this in NetworkModel, trinary comparison operator</technical_language>

Target:
public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new AsciiNameValidation() }); getCidr().validateEntity(new IValidation[] { getIpVersion().getSelectedItem() == IpVersion.IPV4 ? new CidrValidation() : new NotEmptyValidation() }); getIpVersion().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); return getName().getIsValid() && getCidr().getIsValid() && getIpVersion().getIsValid(); }
Source:
<code><START> public boolean equals(Object other) { <END> if (this.getClass() == other.getClass()) { FeedbackResponseAttributes otherFeedbackResponse = (FeedbackResponseAttributes) other; return customEquals(this.feedbackSessionName, otherFeedbackResponse.feedbackSessionName) && customEquals(this.courseId, otherFeedbackResponse.courseId) && customEquals(this.feedbackQuestionId, otherFeedbackResponse.feedbackQuestionId) && customEquals(this.giver, otherFeedbackResponse.giver) && customEquals(this.recipient, otherFeedbackResponse.recipient); } else { return false; } }</code><technical_language>forget write test for equals method</technical_language>

Target:
public boolean equals(Object other) { if (other == null) { return false; } else if (this == other) { return true; } else if (this.getClass() == other.getClass()) { FeedbackResponseAttributes otherFeedbackResponse = (FeedbackResponseAttributes) other; return Objects.equals(this.feedbackSessionName, otherFeedbackResponse.feedbackSessionName) && Objects.equals(this.courseId, otherFeedbackResponse.courseId) && Objects.equals(this.feedbackQuestionId, otherFeedbackResponse.feedbackQuestionId) && Objects.equals(this.giver, otherFeedbackResponse.giver) && Objects.equals(this.recipient, otherFeedbackResponse.recipient); } else { return false; } }
Source:
<code>public String toString() { <START> if (this.m_password == null) { <END> return null; } return new String(this.m_password); }</code><technical_language>In general I instantiate (immutable) null Password. I passing a null parameter constructor. this considered a bug instead throw a runtime exception? update copyright date 2017</technical_language>

Target:
public String toString() { return new String(this.m_password); }
Source:
<code><START> public boolean equals(final Object o) { <END> if (this == o) { return true; } if (!(o instanceof DiagramNavigatorItemImpl)) { return false; } DiagramNavigatorItemImpl that = (DiagramNavigatorItemImpl) o; return name.equals(that.name); }</code><technical_language>Missing hashCode method</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof DiagramNavigatorItemImpl)) { return false; } final DiagramNavigatorItemImpl that = (DiagramNavigatorItemImpl) o; return name.equals(that.name); }
Source:
<code>public static List<Total> orderedValues() { <START> List<Total> orderedTotals = new ArrayList<>(); <END> orderedTotals.add(SUM); orderedTotals.add(MAX); orderedTotals.add(MIN); orderedTotals.add(AVG); orderedTotals.add(MED); orderedTotals.add(NAT); return orderedTotals; }</code><technical_language>user Arrays.asList</technical_language>

Target:
public static List<Total> orderedValues() { return Arrays.asList(SUM, MAX, MIN, AVG, MED, NAT); }
Source:
<code>public static AmazonS3 getAmazonS3Client(String accessKey, String secretKey, <START> Map<String, String> options) { <END> AmazonS3 client = s3Clients.get(key(accessKey, secretKey, options)); if (null == client) { Region region = null; URL endpoint = null; String signer = null; if (options != null) { if (options.get(OPTS.S3_ENDPOINT.name()) != null) { try { endpoint = new URL(options.get(OPTS.S3_ENDPOINT.name())); } catch (MalformedURLException e) { String err = "The provided S3 Endpoint URL is invalid: " + e.getMessage(); throw new StorageException(err, e); } if (options.get(OPTS.S3_SIGNER_TYPE.name()) != null) { signer = options.get(OPTS.S3_SIGNER_TYPE.name()); } } else if (options.get(OPTS.AWS_REGION.name()) != null) { region = com.amazonaws.services.s3.model.Region.fromValue( options.get(OPTS.AWS_REGION.name())).toAWSRegion(); } } client = newS3Client(accessKey, secretKey, region, endpoint, signer); s3Clients.put(key(accessKey, secretKey, options), client); } return client; }</code><technical_language>prefer parameters stay aligned originally</technical_language>

Target:
public static AmazonS3 getAmazonS3Client(String accessKey, String secretKey, Map<String, String> options) { AmazonS3 client = s3Clients.get(key(accessKey, secretKey, options)); if (null == client) { Region region = null; URL endpoint = null; String signer = null; if (options != null) { if (options.get(OPTS.SWIFT_S3_ENDPOINT.name()) != null) { try { endpoint = new URL(options.get(OPTS.SWIFT_S3_ENDPOINT.name())); } catch (MalformedURLException e) { String err = "The provided Swift S3 Endpoint URL is invalid: " + e.getMessage(); throw new StorageException(err, e); } if (options.get(OPTS.SWIFT_S3_SIGNER_TYPE.name()) != null) { signer = options.get(OPTS.SWIFT_S3_SIGNER_TYPE.name()); } } else if (options.get(OPTS.AWS_REGION.name()) != null) { region = com.amazonaws.services.s3.model.Region.fromValue( options.get(OPTS.AWS_REGION.name())).toAWSRegion(); } } client = newS3Client(accessKey, secretKey, region, endpoint, signer); s3Clients.put(key(accessKey, secretKey, options), client); } return client; }
Source:
<code>public Serializable getClassificationByMaxProb(AttributesMap attributes) { PredictionMap predictionMap = predict(attributes); double maxProb = 0; Serializable classification = null; for (Serializable prediction : predictionMap.keySet()) { double prob = predictionMap.get(prediction); if (prob > maxProb) { maxProb = prob; classification = prediction; } } <START> assert (classification != null); <END> return classification; }</code><technical_language>interested hear team of "assert", I trend is exception thrown, assert do if specific command line params passed jvm. a result, assert is considered bad (hence Guava's Preconditions class)</technical_language>

Target:
public Serializable getClassificationByMaxProb(AttributesMap attributes) { PredictionMap predictionMap = predict(attributes); double maxProb = 0; Serializable classification = null; for (Serializable prediction : predictionMap.keySet()) { double prob = predictionMap.get(prediction); if (prob > maxProb) { maxProb = prob; classification = prediction; } } if (classification == null) throw new RuntimeException("unable to make a classification"); return classification; }
Source:
<code>public void verifyNoDomainForMemoryWhenDomainIsNotActive() { for (StorageDomainStatus storageDomainStatus : StorageDomainStatus.values()) { if (storageDomainStatus != StorageDomainStatus.Active) { validStorageDomain.setStatus(storageDomainStatus); <START> verifyNoDomainForMemory(Arrays.asList(validStorageDomain)); <END> } } }</code><technical_language>Please Collections.singletonList()</technical_language>

Target:
public void verifyNoDomainForMemoryWhenDomainIsNotActive() { for (StorageDomainStatus storageDomainStatus : StorageDomainStatus.values()) { if (storageDomainStatus != StorageDomainStatus.Active) { validStorageDomain.setStatus(storageDomainStatus); verifyNoDomainForMemory(Collections.singletonList(validStorageDomain)); } } }
Source:
<code>public DataSource as(@NonNull String alias) { if(alias == null) { throw new IllegalArgumentException("alias is null"); <START> } <END> super.alias = alias; return this; }</code><technical_language>1. Removed @throws IllegalArgumentException alias is null. is required declare throwing a runtime exception. declared this in other places e.g. Database class well. 2. Remove extra empty line if(alias == null) {. 3. Add a space if (alias. if (alias == null). 4. Add . (full stop) end of "alias is null" -> alias is null. 5. Do for other methods</technical_language>

Target:
public DataSource as(@NonNull String alias) { if (alias == null) { throw new IllegalArgumentException("alias is null."); } super.alias = alias; return this; }
Source:
<code>public AbstractCookieConfig(ConfigReader configReader) { Assert.notNull(configReader); this.name = configReader.getString(configKeyFor(NAME)); Assert.hasText(this.name, NAME + " cannot be null or empty."); this.comment = configReader.getString(configKeyFor(COMMENT)); this.domain = configReader.getString(configKeyFor(DOMAIN)); this.path = configReader.getString(configKeyFor(PATH)); this.secure = configReader.getBoolean(configKeyFor(SECURE)); this.httpOnly = configReader.getBoolean(configKeyFor(HTTP_ONLY)); <START> this.maxAge = 1; <END> }</code><technical_language>In AccountCookieConfig had: this.maxAge = Math.max(-1, configReader.getInt(MAX_AGE));. is set 1. forgot update intentional? For latter, is rationale for this change</technical_language>

Target:
public AbstractCookieConfig(ConfigReader configReader) { Assert.notNull(configReader); this.name = configReader.getString(configKeyFor(NAME)); Assert.hasText(this.name, NAME + " cannot be null or empty."); this.comment = configReader.getString(configKeyFor(COMMENT)); this.domain = configReader.getString(configKeyFor(DOMAIN)); this.path = configReader.getString(configKeyFor(PATH)); this.secure = configReader.getBoolean(configKeyFor(SECURE)); this.httpOnly = configReader.getBoolean(configKeyFor(HTTP_ONLY)); }
Source:
<code>protected String createBody() { StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>\n"); sb.append("<orders xmlns=\"http:acme.com\">\n"); <START> sb.append(" <order id=\"1\" xmlns=\"http:acme.com\">Camel in Action</order>\n"); <END> sb.append(" <order id=\"2\">ActiveMQ in Action</order>\n"); sb.append(" <order id=\"3\">DSL in Action</order>\n"); sb.append("</orders>"); return sb.toString(); }</code><technical_language>duplicate test original as-is in new test check for inherited root namespace test conditions</technical_language>

Target:
protected String createBody() { StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>\n"); sb.append("<orders xmlns=\"http:acme.com\">\n"); sb.append(" <order id=\"1\">Camel in Action</order>\n"); sb.append(" <order id=\"2\">ActiveMQ in Action</order>\n"); sb.append(" <order id=\"3\">DSL in Action</order>\n"); sb.append("</orders>"); return sb.toString(); }
Source:
<code>public void addListener(Object listener) { ListenerHolder listenerHolder = new ListenerHolder(listener, encoder, wrapper); Cache unwrapped = super.unwrapCache(this.cache); <START> if(unwrapped instanceof CacheImpl) { <END> ((CacheImpl)unwrapped).addListener(listenerHolder); } else { super.addListener(listener); } }</code><technical_language>Nitpick: space</technical_language>

Target:
public void addListener(Object listener) { ListenerHolder listenerHolder = new ListenerHolder(listener, keyEncoderClass, valueEncoderClass, keyWrapperClass, valueWrapperClass); Cache unwrapped = super.unwrapCache(this.cache); if (unwrapped instanceof CacheImpl) { ((CacheImpl) unwrapped).addListener(listenerHolder); } else { super.addListener(listener); } }
Source:
<code><START> public DockerOkHttpClientSupplier(SSLContextWithKeysSupplier sslContextWithKeysSupplier) { <END> this.sslContextWithKeysSupplier = sslContextWithKeysSupplier; }</code><technical_language>constructor package private</technical_language>

Target:
DockerOkHttpClientSupplier(SSLContextWithKeysSupplier sslContextWithKeysSupplier) { this.sslContextWithKeysSupplier = sslContextWithKeysSupplier; }
Source:
<code>public void showInvalidURLSnackbar(String message) { <START> String action = "EDIT"; <END> final int length = Snackbar.LENGTH_LONG; View.OnClickListener clickEvent = view -> { mUrl.requestFocus(); mUrl.selectAll(); }; createSnackbar(message, action, length, clickEvent).show(); }</code><technical_language>@tmarzeion this in string resources</technical_language>

Target:
public void showInvalidURLSnackbar(String message) { createSnackbar(message) .setAction(getResources().getString(R.string.snackbar_edit), view -> { mUrl.requestFocus(); mUrl.selectAll(); }) .show(); }
Source:
<code>public Notification createNotification(Intent inboundIntent) { final NotificationData data = readInboundIntent(inboundIntent); if (null == data) { return null; } MPLog.d(LOGTAG, "MP FCM notification received: " + data.message); final PendingIntent contentIntent = PendingIntent.getActivity( context, 0, data.intent, PendingIntent.FLAG_UPDATE_CURRENT ); builder. <START> setDefaults(MPConfig.getInstance(context).getNotificationDefaults()). <END> setWhen(now). setContentTitle(data.title). setContentText(data.message). setTicker(data.message). setContentIntent(contentIntent); maybeSetNotificationBarIcon(data); maybeSetLargeIcon(data); maybeSetExpandableNotification(data); maybeSetCustomIconColor(data); maybeSetChannel(); final Notification n = buildNotification(); n.flags |= Notification.FLAG_AUTO_CANCEL; return n; }</code><technical_language>this is deprecated API 26 (O) in favor of enabling notif properties channel. for clarity, setDefaults for API 26 enableVibration, enableLights, etc... for API 26</technical_language>

Target:
Notification createNotification(Intent inboundIntent) { parseIntent(inboundIntent); if (this.mData == null) { return null; } if (this.mData.isSilent()) { MPLog.d(LOGTAG, "Notification will not be shown because \'mp_silent = true\'"); return null; } if (this.mData.getMessage() == null) { MPLog.d(LOGTAG, "Notification will not be shown because 'mp_message' was null"); return null; } if (this.mData.getMessage().equals("")) { MPLog.d(LOGTAG, "Notification will not be shown because 'mp_message' was empty"); return null; } buildNotificationFromData(); Notification n; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { n = mBuilder.build(); } else { n = mBuilder.getNotification(); } if (!mData.isSticky()) { n.flags |= Notification.FLAG_AUTO_CANCEL; } return n; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; <START> if (obj == null) <END> return false; if (getClass() != obj.getClass()) return false; Attribute other = (Attribute) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (state != other.state) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }</code><technical_language>I personally prefer check if(!(obj instanceof Attribute)) instead of checks for null class</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Attribute)) return false; Attribute other = (Attribute) obj; if (!key.equals(other.key)) return false; if (state != other.state) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }
Source:
<code>public void testToString() { String expectedOutput = "/usr/bin/local:10:1: error: errMsg"; assertEquals(expectedOutput, this.violationMessage.toString()); <START> ViolationMessage emptyViolationMessage = ViolationMessage.EMPTY; <END> assertThat(emptyViolationMessage.toString(), IsEmptyString.isEmptyString()); }</code><technical_language>Remove of ViolationMessage.EMPTY</technical_language>

Target:
public void testToString() { String expectedOutput = "/usr/bin/local:10:1: error: errMsg"; assertEquals(expectedOutput, this.violationMessage.toString()); }
Source:
<code>public final void onMessage(final ByteBuffer buffer) { final Request req = AbstractServerWebSocketHandler.Decoder.parseRequest(buffer); LOG.info("Got a response from the submission server!"); LOG.info(req.getSessionInfo()); final String[] sessionInfo = req.getSessionInfo().split("\\+"); LOG.info(sessionInfo[1]); final MultiConnectionState state = getStateFromId(sessionInfo[1]); LOG.info("State {}", state); if (req.getRequestType() == MessageType.DATA_REQUEST) { final DataResult.Builder result2 = DataResult.newBuilder(); try { final DataResult result = DataResult.parseFrom(req.getOtherData()); result2.clearResults(); for (ItemResult item : result.getResultsList()) { if (item.hasAdvanceQuery() && item.getQuery() == ItemQuery.EXPERIMENT) { final ExperimentReview rev = ExperimentReview.parseFrom(item.getAdvanceQuery()); if (rev.getShowUserNames()) { <START> LOG.error("Attempting to change out usernames!"); <END> result2.addResults(item); } else { result2.addResults(item); } } else { result2.addResults(item); } } } catch (InvalidProtocolBufferException e) { LOG.info("Exception {}", e); } final Request.Builder builder = Request.newBuilder(req); builder.setSessionInfo(sessionInfo[0]); final SocketSession connection = getConnectionFromState(state); builder.setOtherData(result2.build().toByteString()); if (connection == null) { LOG.error("SOCKET IS NULL"); } this.getParentServer().send(getConnectionFromState(state), builder.build()); } }</code><technical_language>this info</technical_language>

Target:
public final void onMessage(final ByteBuffer buffer) { final Request req = AbstractServerWebSocketHandler.Decoder.parseRequest(buffer); LOG.info("Got a response from the submission server!"); LOG.info(req.getSessionInfo()); final String[] sessionInfo = req.getSessionInfo().split("\\+"); LOG.info(sessionInfo[1]); final MultiConnectionState state = getStateFromId(sessionInfo[1]); LOG.info("State {}", state); if (req.getRequestType() == MessageType.DATA_REQUEST) { final DataResult.Builder result2 = DataResult.newBuilder(); try { final DataResult result = DataResult.parseFrom(req.getOtherData()); result2.clearResults(); for (ItemResult item : result.getResultsList()) { if (item.hasAdvanceQuery() && item.getQuery() == ItemQuery.EXPERIMENT) { final ExperimentReview rev = ExperimentReview.parseFrom(item.getAdvanceQuery()); if (rev.getShowUserNames()) { LOG.info("Attempting to change out usernames!"); result2.addResults(item); } else { result2.addResults(item); } } else { result2.addResults(item); } } } catch (InvalidProtocolBufferException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } final Request.Builder builder = Request.newBuilder(req); builder.setSessionInfo(sessionInfo[0]); final SocketSession connection = getConnectionFromState(state); builder.setOtherData(result2.build().toByteString()); if (connection == null) { LOG.error("SOCKET IS NULL"); } this.getParentServer().send(getConnectionFromState(state), builder.build()); } }
Source:
<code>public Result doWork() { final boolean[] result = new boolean[1]; String patientIdTobeUpdated = getInputData().getString(PatientTable.Column.ID); PatientDAO patientDAO = new PatientDAO(); Patient patientTobeUpdated = patientDAO.findPatientByID(patientIdTobeUpdated); updatePatient(patientTobeUpdated, new DefaultResponseCallbackListener() { @Override public void onResponse() { result[0] = true; handler.post(new Runnable() { @Override public void run() { ToastUtil.success("Patient " + patientTobeUpdated.getPerson().getName().getNameString() + " updated"); } }); } @Override public void onErrorResponse(String errorMessage) { result[0] = false; <START> handler.post(new Runnable() { <END> @Override public void run() { ToastUtil.error("Patient " + patientTobeUpdated.getPerson().getName().getNameString() + " cannot be updated due to server error will retry sync "); } }); } }); return result[0] == true ? Result.success() : Result.retry(); }</code><technical_language>care of destroying handler/removing callbacks activity/fragment destroyed</technical_language>

Target:
public Result doWork() { final boolean[] result = new boolean[1]; String patientIdTobeUpdated = getInputData().getString(PatientTable.Column.ID); PatientDAO patientDAO = new PatientDAO(); Patient patientTobeUpdated = patientDAO.findPatientByID(patientIdTobeUpdated); updatePatient(patientTobeUpdated, new DefaultResponseCallbackListener() { @Override public void onResponse() { result[0] = true; Message msg = new Message(); msg.obj = patientTobeUpdated.getPerson().getName().getNameString(); msg.what = ON_SUCCESS; mHandler.sendMessage(msg); } @Override public void onErrorResponse(String errorMessage) { result[0] = false; Message msg = new Message(); msg.obj = patientTobeUpdated.getPerson().getName().getNameString(); msg.what = ON_FAILURE; mHandler.sendMessage(msg); } }); return result[0] ? Result.success() : Result.retry(); }