auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void auth(ServletContextHandler ctx, Authenticator authType) { final String role = "can-access"; MappedLoginService users = new MappedLoginService() { @Override protected UserIdentity loadUser(String who) { return null; } @Override protected void loadUsers() throws IOException { putUser(username, new Password(password), new String[] { role }); } }; ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(new Constraint()); cm.getConstraint().setAuthenticate(true); cm.getConstraint().setDataConstraint(Constraint.DC_NONE); cm.getConstraint().setRoles(new String[] { role }); cm.setPathSpec("/*"); ConstraintSecurityHandler sec = new ConstraintSecurityHandler(); sec.setStrict(false); sec.setRealmName(realm); sec.setAuthenticator(authType); sec.setLoginService(users); ArrayList<ConstraintMapping> mappings = new ArrayList<ConstraintMapping>(); mappings.add(cm); <START> sec.setConstraintMappings(mappings); <END> sec.setHandler(ctx); contexts.removeHandler(ctx); contexts.addHandler(sec); }</code><technical_language>Jetty 7.2 dropped setConstraintMapping(ConstraintMapping[]) method signature? calling Jetty 8 removed a public method</technical_language>

Target:
private void auth(ServletContextHandler ctx, Authenticator authType) { final String role = "can-access"; MappedLoginService users = new MappedLoginService() { @Override protected UserIdentity loadUser(String who) { return null; } @Override protected void loadUsers() throws IOException { putUser(username, new Password(password), new String[] { role }); } }; ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(new Constraint()); cm.getConstraint().setAuthenticate(true); cm.getConstraint().setDataConstraint(Constraint.DC_NONE); cm.getConstraint().setRoles(new String[] { role }); cm.setPathSpec("/*"); ConstraintSecurityHandler sec = new ConstraintSecurityHandler(); sec.setStrict(false); sec.setRealmName(realm); sec.setAuthenticator(authType); sec.setLoginService(users); sec.setConstraintMappings(new ConstraintMapping[] { cm }); sec.setHandler(ctx); contexts.removeHandler(ctx); contexts.addHandler(sec); }
Source:
<code>public CauseOfBlockage getCauseOfBlockage() { Jenkins jenkins = Jenkins.getInstance(); if(isBlockedByShutdown(task)) return CauseOfBlockage.fromMessage(Messages._Queue_HudsonIsAboutToShutDown()); Label label = getAssignedLabel(); List<Node> allNodes = jenkins.getNodes(); if (allNodes.isEmpty()) label = null; if (label != null) { Set<Node> nodes = label.getNodes(); if (label.isOffline()) { if (nodes.size() != 1) return new BecauseLabelIsOffline(label); else return new BecauseNodeIsOffline(nodes.iterator().next()); } else { if (transientCausesOfBlockage != null && label.getIdleExecutors() > 0) { <START> return new CompositeCauseOfBlockage(transientCausesOfBlockage); <END> } if (nodes.size() != 1) return new BecauseLabelIsBusy(label); else return new BecauseNodeIsBusy(nodes.iterator().next()); } } else if (transientCausesOfBlockage != null && new ComputerSet().getIdleExecutors() > 0) { return new CompositeCauseOfBlockage(transientCausesOfBlockage); } else { return CauseOfBlockage.createNeedsMoreExecutor(Messages._Queue_WaitingForNextAvailableExecutor()); } }</code><technical_language>This is thread-safe I see. isAvailable() called iff clause this constructor. If fine eventual consistency, cache data local field</technical_language>

Target:
public CauseOfBlockage getCauseOfBlockage() { Jenkins jenkins = Jenkins.getInstance(); if(isBlockedByShutdown(task)) return CauseOfBlockage.fromMessage(Messages._Queue_HudsonIsAboutToShutDown()); List<CauseOfBlockage> causesOfBlockage = transientCausesOfBlockage; Label label = getAssignedLabel(); List<Node> allNodes = jenkins.getNodes(); if (allNodes.isEmpty()) label = null; if (label != null) { Set<Node> nodes = label.getNodes(); if (label.isOffline()) { if (nodes.size() != 1) return new BecauseLabelIsOffline(label); else return new BecauseNodeIsOffline(nodes.iterator().next()); } else { if (causesOfBlockage != null && label.getIdleExecutors() > 0) { return new CompositeCauseOfBlockage(causesOfBlockage); } if (nodes.size() != 1) return new BecauseLabelIsBusy(label); else return new BecauseNodeIsBusy(nodes.iterator().next()); } } else if (causesOfBlockage != null && new ComputerSet().getIdleExecutors() > 0) { return new CompositeCauseOfBlockage(causesOfBlockage); } else { return CauseOfBlockage.createNeedsMoreExecutor(Messages._Queue_WaitingForNextAvailableExecutor()); } }
Source:
<code>private TimestampsToSweep getTimestampsToSweepDescendingAndCleanupAborted(ShardAndStrategy shardStrategy, long minTsExclusive, long sweepTs, Multimap<Long, WriteInfo> writesByStartTs) { Map<Long, Long> startToCommitTs = commitTsCache.loadBatch(writesByStartTs.keySet()); Map<TableReference, Multimap<Cell, Long>> cellsToDelete = new HashMap<>(); List<Long> committedTimestamps = new ArrayList<>(); long lastSweptTs = minTsExclusive; boolean processedAll = true; List<Long> sortedStartTimestamps = startToCommitTs.keySet().stream().sorted().collect(Collectors.toList()); for (long startTs : sortedStartTimestamps) { long commitTs = startToCommitTs.get(startTs); if (commitTs == TransactionConstants.FAILED_COMMIT_TS) { lastSweptTs = startTs; writesByStartTs.get(startTs) .forEach(write -> cellsToDelete .computeIfAbsent(write.tableRef(), ignore -> HashMultimap.create()) .put(write.cell(), write.timestamp())); } else if (commitTs < sweepTs) { lastSweptTs = startTs; committedTimestamps.add(startTs); } else { processedAll = false; break; } } cellsToDelete.forEach((tableRef, multimap) -> { kvs.delete(tableRef, multimap); maybeMetrics.ifPresent(metrics -> metrics.updateAbortedWritesDeleted(shardStrategy, multimap.size())); <START> log.info("Deleted aborted writes from the KVS.", SafeArg.of("number", multimap.size())); <END> }); committedTimestamps.sort(Comparator.reverseOrder()); return TimestampsToSweep.of(committedTimestamps, lastSweptTs, processedAll); }</code><technical_language>log tableRef well, move log line lambda log total number of writes aborted</technical_language>

Target:
private TimestampsToSweep getTimestampsToSweepDescendingAndCleanupAborted(ShardAndStrategy shardStrategy, long minTsExclusive, long sweepTs, Multimap<Long, WriteInfo> writesByStartTs) { Map<Long, Long> startToCommitTs = commitTsCache.loadBatch(writesByStartTs.keySet()); Map<TableReference, Multimap<Cell, Long>> cellsToDelete = new HashMap<>(); List<Long> committedTimestamps = new ArrayList<>(); long lastSweptTs = minTsExclusive; boolean processedAll = true; List<Long> sortedStartTimestamps = startToCommitTs.keySet().stream().sorted().collect(Collectors.toList()); for (long startTs : sortedStartTimestamps) { long commitTs = startToCommitTs.get(startTs); if (commitTs == TransactionConstants.FAILED_COMMIT_TS) { lastSweptTs = startTs; writesByStartTs.get(startTs) .forEach(write -> cellsToDelete .computeIfAbsent(write.tableRef(), ignore -> HashMultimap.create()) .put(write.cell(), write.timestamp())); } else if (commitTs < sweepTs) { lastSweptTs = startTs; committedTimestamps.add(startTs); } else { processedAll = false; break; } } cellsToDelete.forEach((tableRef, multimap) -> { kvs.delete(tableRef, multimap); maybeMetrics.ifPresent(metrics -> metrics.updateAbortedWritesDeleted(shardStrategy, multimap.size())); log.info("Deleted aborted writes from table {}.", SafeArg.of("number", multimap.size()), LoggingArgs.tableRef(tableRef)); }); return TimestampsToSweep.of(Lists.reverse(committedTimestamps), lastSweptTs, processedAll); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CTFCallsite other = (CTFCallsite) obj; if (!equalsNullable(fEventName, other.fEventName)) { return false; } if (!equalsNullable(fFileName, other.fFileName)) { return false; } if (!equalsNullable(fFunctionName, other.fFunctionName)) { return false; } if (fIp != other.fIp) { return false; } <START> return (fLineNumber == other.fLineNumber); <END> }</code><technical_language>stay consistent, I this check. "return true;" end normally</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CTFCallsite other = (CTFCallsite) obj; if (!equalsNullable(fEventName, other.fEventName)) { return false; } if (!equalsNullable(fFileName, other.fFileName)) { return false; } if (!equalsNullable(fFunctionName, other.fFunctionName)) { return false; } if (fIp != other.fIp) { return false; } if (fLineNumber != other.fLineNumber){ return false; } return true; }
Source:
<code>public String toString() { return "IlluminaNotificationDto [numCycles=" + numCycles + ", ImgCycle=" + ImgCycle + ", ScoreCycle=" + ScoreCycle + ", CallCycle=" <START> + CallCycle + ", getRunName()=" + getRunAlias() + ", getSequencerName()=" + getSequencerName() + ", getCompletionDate()=" <END> + getCompletionDate() + ", getStartDate()=" + getStartDate() + ", getContainerId()=" + getContainerSerialNumber() + ", getLaneCount()=" + getLaneCount() + ", getHealthType()=" + getHealthType() + ", getSequencerFolderPath()=" + getSequencerFolderPath() + ", isPairedEndRun()=" + isPairedEndRun() + ", getSoftware()=" + getSoftware() + "]"; }</code><technical_language>Update labels method names. Alternately, call super.toString for super attributes</technical_language>

Target:
public String toString() { return "IlluminaNotificationDto [numCycles=" + numCycles + ", ImgCycle=" + ImgCycle + ", ScoreCycle=" + ScoreCycle + ", CallCycle=" + CallCycle + ", getRunAlias()=" + getRunAlias() + ", getSequencerName()=" + getSequencerName() + ", getContainerSerialNumber()=" + getContainerSerialNumber() + ", getLaneCount()=" + getLaneCount() + ", getHealthType()=" + getHealthType() + ", getSequencerFolderPath()=" + getSequencerFolderPath() + ", isPairedEndRun()=" + isPairedEndRun() + ", getSoftware()=" + getSoftware() + ", getStartDate()=" + getStartDate() + ", getCompletionDate()=" + getCompletionDate() + "]"; }
Source:
<code>private void addUsername(EditText editText, ValidationEndListener validationEndListener) { String username = removeDelimiterFromUsername(editText.getText().toString()); editText.setText(" "); if (username.isEmpty() || mUsernameButtons.keySet().contains(username)) { if (validationEndListener != null) { validationEndListener.onValidationEnd(); } return; } final ViewGroup usernameButton = buttonizeUsername(username); mUsernameButtons.put(username, usernameButton); <START> validateAndStyleUsername(Arrays.asList(new String[]{username}), validationEndListener); <END> }</code><technical_language>modifying this line, feel free remove String array creation, suggests (Array.asList is a varargs method). Thanks</technical_language>

Target:
private void addUsername(EditText editText, ValidationEndListener validationEndListener) { String username = removeDelimiterFromUsername(editText.getText().toString()); resetEditTextContent(editText); if (username.isEmpty() || mUsernameButtons.keySet().contains(username)) { if (validationEndListener != null) { validationEndListener.onValidationEnd(); } return; } final ViewGroup usernameButton = buttonizeUsername(username); mUsernameButtons.put(username, usernameButton); validateAndStyleUsername(Collections.singletonList(username), validationEndListener); }
Source:
<code>public Map<String, Object> getMetaData(String iconName) throws IconException { <START> return this.getMetaData(iconName, getIconSet(iconName).getName()); <END> }</code><technical_language>This means getIconSet called for common case. I add a private getMetaData(String iconName, IconSet iconSet) call rest of getMetaData() methods</technical_language>

Target:
public Map<String, Object> getMetaData(String iconName) throws IconException { return this.getMetaData(iconName, getIconSet(iconName)); }
Source:
<code>protected TaxRule determineTaxRuleToUseForDataPopulation(PaymentWorksVendor pmwVendor, String pmwVendorFipsTaxCountryCode) { <START> TaxRule foundRule = TaxRule.OTHER; <END> if (isIndividualUsSsn(pmwVendor, pmwVendorFipsTaxCountryCode)) { foundRule = TaxRule.INDIVIDUAL_US_SSN; } else if (isIndividualUsEin(pmwVendor, pmwVendorFipsTaxCountryCode)) { foundRule = TaxRule.INDIVIDUAL_US_EIN; } else if (isNotIndividualUs(pmwVendor, pmwVendorFipsTaxCountryCode)) { foundRule = TaxRule.NOT_INDIVIDUAL_US; } else if (isForeignIndividual(pmwVendor, pmwVendorFipsTaxCountryCode)) { foundRule = TaxRule.FOREIGN_INDIVIDUAL; } else if (isForeignEntity(pmwVendor, pmwVendorFipsTaxCountryCode)) { foundRule = TaxRule.FOREIGN_ENTITY; } else { LOG.error("determineTaxRuleToUseForDataPopulation, unknown tax rule for request " + pmwVendor.getId()); } return foundRule; }</code><technical_language>this called taxRule? foundRule denotes a boolean this is case here</technical_language>

Target:
protected TaxRule determineTaxRuleToUseForDataPopulation(PaymentWorksVendor pmwVendor, String pmwVendorFipsTaxCountryCode) { TaxRule taxRule = TaxRule.OTHER; if (isIndividualUsSsn(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.INDIVIDUAL_US_SSN; } else if (isIndividualUsEin(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.INDIVIDUAL_US_EIN; } else if (isNotIndividualUs(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.NOT_INDIVIDUAL_US; } else if (isForeignIndividualWithSSN(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.FOREIGN_INDIVIDUAL_US_TAX_PAYER; } else if (isForeignIndividual(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.FOREIGN_INDIVIDUAL; } else if (isForeignEntity(pmwVendor, pmwVendorFipsTaxCountryCode)) { taxRule = TaxRule.FOREIGN_ENTITY; } else { LOG.error("determineTaxRuleToUseForDataPopulation, unknown tax rule for request " + pmwVendor.getId()); } return taxRule; }
Source:
<code>public void validateAmountsIncorrectDebitCredit() { file.getConcurStandardAccountingExtractDetailLines().get(0).setJounalDebitCredit("foo"); <START> String message = "The should throw an error due to incorrect debitCredit field"; <END> assertFalse("The should throw an error due to incorrect debitCredit field", concurStandardAccountingExtractService.validateAmounts(file)); }</code><technical_language>this local variable. removed</technical_language>

Target:
public void validateAmountsIncorrectDebitCredit() { setBadDebitCredit(); assertFalse("The should throw an error due to incorrect debitCredit field", concurStandardAccountingValidationService.validateAmountsAndDebitCreditCode(file)); }
Source:
<code>public Server deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { Server serverBase = null; if (jsonElement.getAsJsonObject().get("image").isJsonObject()) { serverBase = apply((ServerInternal) context.deserialize(jsonElement, ServerInternal.class)); } <START> else { <END> serverBase = apply((ServerInternalWithoutImage) context.deserialize(jsonElement, ServerInternalWithoutImage.class)); } Server.Builder<?> result = Server.builder().fromServer(serverBase); ServerExtendedStatus extendedStatus = context.deserialize(jsonElement, ServerExtendedStatus.class); if (!Objects.equal(extendedStatus, ServerExtendedStatus.builder().build())) { result.extendedStatus(extendedStatus); } ServerExtendedAttributes extraAttributes = context.deserialize(jsonElement, ServerExtendedAttributes.class); if (!Objects.equal(extraAttributes, ServerExtendedAttributes.builder().build())) { result.extendedAttributes(extraAttributes); } return result.build(); }</code><technical_language>[minor[ } else { line</technical_language>

Target:
public Server deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { Server serverBase; if (jsonElement.getAsJsonObject().get("image").isJsonObject()) { serverBase = apply((ServerInternal) context.deserialize(jsonElement, ServerInternal.class)); } else { serverBase = apply((ServerInternalWithoutImage) context.deserialize(jsonElement, ServerInternalWithoutImage.class)); } Server.Builder<?> result = Server.builder().fromServer(serverBase); ServerExtendedStatus extendedStatus = context.deserialize(jsonElement, ServerExtendedStatus.class); if (!Objects.equal(extendedStatus, ServerExtendedStatus.builder().build())) { result.extendedStatus(extendedStatus); } ServerExtendedAttributes extraAttributes = context.deserialize(jsonElement, ServerExtendedAttributes.class); if (!Objects.equal(extraAttributes, ServerExtendedAttributes.builder().build())) { result.extendedAttributes(extraAttributes); } return result.build(); }
Source:
<code>public final static boolean verify(HashResult hash1, HashResult hash2){ <START> if(hash1.compareTo(hash2) == 0){ <END> return true; } return false; }</code><technical_language>HashResult.compareTo( ) compares HashResult.type, HashResult.result (yes, **that** is wrong, fixed AFAIK). Also, please compare hashes in a is insensitive timing attacks, Comparable.compareTo( ) guarantee property</technical_language>

Target:
public final static boolean verify(HashResult hash1, HashResult hash2){ return hash1.equals(hash2); }
Source:
<code>public DocumentRevision createDocumentFromRevision(MutableDocumentRevision rev) throws IOException { if (rev.docId == null) { rev.docId = CouchUtils.generateDocumentId(); } try { this.getSQLDatabase().beginTransaction(); BasicDocumentRevision saved = createDocument(rev.docId, rev.body); this.attachmentManager.setAttachments(saved, rev.attachments); this.getSQLDatabase().setTransactionSuccessful(); <START> DocumentRevision updatedWithAttachments = this.getDocument(saved.getId(), saved.getRevision()); <END> return updatedWithAttachments; } finally { this.getSQLDatabase().endTransaction(); } }</code><technical_language>This feel setAttachments call creates a new revision. setAttachments set attachments revision, call? in database, name misleading</technical_language>

Target:
public BasicDocumentRevision createDocumentFromRevision(MutableDocumentRevision rev) throws IOException { Preconditions.checkNotNull(rev, "DocumentRevision can not be null"); if (rev.docId == null) { rev.docId = CouchUtils.generateDocumentId(); } AttachmentManager.PreparedAndSavedAttachments preparedAndSavedAttachments = this.attachmentManager.prepareAttachments(rev.attachments != null ? rev.attachments.values() : null); try { this.getSQLDatabase().beginTransaction(); BasicDocumentRevision saved = createDocument(rev.docId, rev.body); this.attachmentManager.setAttachments(saved, preparedAndSavedAttachments); this.getSQLDatabase().setTransactionSuccessful(); BasicDocumentRevision updatedWithAttachments = this.getDocument(saved.getId(), saved.getRevision()); return updatedWithAttachments; } finally { this.getSQLDatabase().endTransaction(); } }
Source:
<code>public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityProcessingTimeInMs.update(processingStartTimeMs - operationStartTimeMs); try { if (exception == null) { DataNodeId dataNodeId = getDataNodeId(restRequest); LOGGER.trace("Getting peer hosts for {}:{}", dataNodeId.getHostname(), dataNodeId.getPort()); Set<DataNodeId> peerDataNodeIds = new HashSet<>(); List<? extends ReplicaId> replicaIdList = clusterMap.getReplicaIds(dataNodeId); for (ReplicaId replicaId : replicaIdList) { List<? extends ReplicaId> peerReplicaIds = replicaId.getPeerReplicaIds(); for (ReplicaId peerReplicaId : peerReplicaIds) { peerDataNodeIds.add(peerReplicaId.getDataNodeId()); } } <START> StringBuilder peerSb = new StringBuilder(); <END> for (DataNodeId peerDataNodeId : peerDataNodeIds) { peerSb.append(peerDataNodeId.getHostname()).append(":").append(peerDataNodeId.getPort()).append(","); } if (peerSb.length() > 0) { peerSb.deleteCharAt(peerSb.length() - 1); } String peerStr = peerSb.toString(); ReadableStreamChannel channel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(peerStr.getBytes())); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, "text/plain"); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, channel.getSize()); callback.onCompletion(channel, null); } else { callback.onCompletion(null, exception); } } catch (Exception e) { callback.onCompletion(null, e); } finally { metrics.getPeersProcessingTimeInMs.update(SystemTime.getInstance().milliseconds() - processingStartTimeMs); } }</code><technical_language>decide a comma separated list instead of a JSON object for this response in GET replicas in ambry-admin</technical_language>

Target:
public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs); ReadableStreamChannel channel = null; try { if (exception == null) { DataNodeId dataNodeId = getDataNodeId(restRequest); LOGGER.trace("Getting peer hosts for {}:{}", dataNodeId.getHostname(), dataNodeId.getPort()); Set<DataNodeId> peerDataNodeIds = new HashSet<>(); List<? extends ReplicaId> replicaIdList = clusterMap.getReplicaIds(dataNodeId); for (ReplicaId replicaId : replicaIdList) { List<? extends ReplicaId> peerReplicaIds = replicaId.getPeerReplicaIds(); for (ReplicaId peerReplicaId : peerReplicaIds) { peerDataNodeIds.add(peerReplicaId.getDataNodeId()); } } channel = getResponseBody(peerDataNodeIds); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_TYPE, "application/json"); restResponseChannel.setHeader(RestUtils.Headers.CONTENT_LENGTH, channel.getSize()); } } catch (Exception e) { exception = e; } finally { metrics.getPeersProcessingTimeInMs.update(SystemTime.getInstance().milliseconds() - processingStartTimeMs); callback.onCompletion(exception == null ? channel : null, exception); } }
Source:
<code>public void offerProducerCredit(final SimpleString address, final int credits, final int threshold, final Receiver receiver) { try { if (creditRunnable != null && !creditRunnable.isRun()) return; PagingManager pagingManager = manager.getServer().getPagingManager(); creditRunnable = new CreditRunnable() { boolean isRun = false; @Override public boolean isRun() { return isRun; } @Override public void run() { connection.lock(); try { if (receiver.getCredit() <= threshold) { int topUp = credits - receiver.getCredit(); <START> System.out.println("topUp = " + topUp); <END> if (topUp > 0) { receiver.flow(topUp); } } } finally { isRun = true; connection.unlock(); } connection.flush(); } }; if (address == null) { pagingManager.checkMemory(creditRunnable); } else { final PagingStore store = manager.getServer().getPagingManager().getPageStore(address); store.checkMemory(creditRunnable); } } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>a logger remove this think</technical_language>

Target:
public void offerProducerCredit(final SimpleString address, final int credits, final int threshold, final Receiver receiver) { try { if (creditRunnable != null && !creditRunnable.isRun()) return; PagingManager pagingManager = manager.getServer().getPagingManager(); creditRunnable = new CreditRunnable() { boolean isRun = false; @Override public boolean isRun() { return isRun; } @Override public void run() { connection.lock(); try { if (receiver.getCredit() <= threshold) { int topUp = credits - receiver.getCredit(); if (topUp > 0) { receiver.flow(topUp); } } } finally { isRun = true; connection.unlock(); } connection.flush(); } }; if (address == null) { pagingManager.checkMemory(creditRunnable); } else { final PagingStore store = manager.getServer().getPagingManager().getPageStore(address); store.checkMemory(creditRunnable); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InDoubtTxInfoImpl that = (InDoubtTxInfoImpl) o; return status == that.status && isLocal == that.isLocal && Objects.equals(xid, that.xid) && <START> Objects.equals(internalId, that.internalId) && <END> Objects.equals(owners, that.owners); }</code><technical_language>==</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InDoubtTxInfoImpl that = (InDoubtTxInfoImpl) o; return internalId == that.internalId && status == that.status && isLocal == that.isLocal && Objects.equals(xid, that.xid) && Objects.equals(owners, that.owners); }
Source:
<code>public void migrateWithRetry() { <START> final int max_retry = 3; <END> for (int i = 0; i < max_retry; i++) { try { logger.info("Database migration started"); migrate(); logger.info("Database migration successfully finished."); return; } catch (RuntimeException re) { logger.warn(re.toString()); if (i == max_retry - 1) { logger.error("Critical error!!. Database migration failed."); } else { logger.warn("Database migration failed. Retry"); try { Thread.sleep(30 * 1000); } catch (InterruptedException ie) { } } } } logger.error("Database migration aborted."); }</code><technical_language>minor: camel case</technical_language>

Target:
public void migrateWithRetry() { final int maxRetry = 3; for (int i = 0; i < maxRetry; i++) { try { logger.info("Database migration started"); migrate(); logger.info("Database migration successfully finished."); return; } catch (RuntimeException re) { logger.warn(re.toString()); if (i == maxRetry - 1) { logger.error("Critical error!!. Database migration failed."); } else { logger.warn("Database migration failed. Retry"); try { Thread.sleep(30 * 1000); } catch (InterruptedException ie) { } } } } logger.error("Database migration aborted."); }
Source:
<code>public void initializeFrom(ILaunchConfiguration config) { String remoteConnection = null; try { remoteConnection = config.getAttribute( IRemoteConnectionConfigurationConstants.ATTR_REMOTE_CONNECTION, EMPTY_STRING); } catch (CoreException ce) { logError(ce); remoteConnection = EMPTY_STRING; } String[] items = fConnectionCombo.getItems(); int i = 0; <START> for (i = 0; i < items.length; i++) <END> if (items[i].equals(remoteConnection)) break; if (i < items.length) { fConnectionCombo.select(i); } else { setErrorMessage(MessageFormat.format( Messages.RemoteSystemTab_Error_ConnectionNotFound, remoteConnection)); setDefaultConnection(); setDirty(true); } updateConnectionButtons(); }</code><technical_language>Please for one-liners</technical_language>

Target:
public void initializeFrom(ILaunchConfiguration config) { String remoteConnection = null; try { remoteConnection = config.getAttribute( IRemoteConnectionConfigurationConstants.ATTR_REMOTE_CONNECTION, EMPTY_STRING); } catch (CoreException ce) { logError(ce); remoteConnection = EMPTY_STRING; } String[] items = fConnectionCombo.getItems(); int i = 0; for (i = 0; i < items.length; i++) { if (items[i].equals(remoteConnection)) { break; } } if (i < items.length) { fConnectionCombo.select(i); } else { setErrorMessage(MessageFormat.format( Messages.RemoteSystemTab_Error_ConnectionNotFound, remoteConnection)); setDefaultConnection(); setDirty(true); } updateConnectionButtons(); if(fShowSystemInfoCheck != null && ! fShowSystemInfoCheck.isDisposed() && fShowSystemInfoCheck.getSelection() == false) { fSystemInfoText.setText(Messages.RemoteSystemTab_ShowSystemInfo_NoInformation); } }
Source:
<code>@Override public void onResponse(Call<AggregatedFeedContent> call, Response<AggregatedFeedContent> response) { if (response.isSuccessful()) { List<Card> cards = new ArrayList<>(); AggregatedFeedContent content = response.body(); <START> cards.add(new FeaturedArticleCard(content.tfa(), DATE, site)); <END> cards.add(new NewsListCard(content.news(), DATE, site)); cb.success(cards); } else { L.v(response.message()); cb.error(new IOException(response.message())); } }</code><technical_language>check tfa() is null, news() below, skip creating card in case</technical_language>

Target:
@Override public void onResponse(Call<AggregatedFeedContent> call, Response<AggregatedFeedContent> response) { if (response.isSuccessful()) { List<Card> cards = new ArrayList<>(); AggregatedFeedContent content = response.body(); if (content.tfa() != null) { cards.add(new FeaturedArticleCard(content.tfa(), DATE, site)); } if (content.news() != null) { cards.add(new NewsListCard(content.news(), DATE, site)); } cb.success(cards); } else { L.v(response.message()); cb.error(new IOException(response.message())); } }
Source:
<code>public Expression visitExpression(ManifoldParser.ExpressionContext context) { <START> if (context.expression().size() == 2) { <END> return new FunctionInvocationExpression( visit(context.expression(0)), visit(context.expression(1)) ); } else { return visitChildren(context); } }</code><technical_language>magic constant 2 is a smell here, happening clarified a bit</technical_language>

Target:
public Expression visitExpression(ManifoldParser.ExpressionContext context) { if (context.getChildCount() == 3 && context.getChild(1).getText().equals("=")) { return new VariableAssignmentExpression( visit(context.expression(0)), visit(context.expression(1)) ); } else if (context.expression().size() == 2) { return new FunctionInvocationExpression( visit(context.expression(0)), visit(context.expression(1)) ); } else { return visitChildren(context); } }
Source:
<code>public static ServicePolicyInterface getServicePolicyForVds(VDS vds) { ServicePolicyInterface retVal = null; Guid vdsGroupId = vds.getvds_group_id(); VDSGroup vdsGroup = vdsGroupDao.get(vdsGroupId); <START> <END> if (vdsGroup != null) { retVal = virtServicePolicy; } return retVal; }</code><technical_language>I a Cluster removed while Host is monitor, cluster Null</technical_language>

Target:
public static ServicePolicyInterface getServicePolicyForVds(VDS vds) { Guid vdsGroupId = vds.getvds_group_id(); VDSGroup vdsGroup = vdsGroupDao.get(vdsGroupId); return virtServicePolicy; }
Source:
<code>public DiscoveryJerseyProvider(EncoderWrapper jsonEncoder, DecoderWrapper jsonDecoder) { this.jsonEncoder = jsonEncoder == null ? CodecWrappers.getEncoder(LegacyJacksonJson.class) : jsonEncoder; this.jsonDecoder = jsonDecoder == null ? CodecWrappers.getDecoder(LegacyJacksonJson.class) : jsonDecoder; LOGGER.info("Using JSON encoding codec {}", this.jsonEncoder.codecName()); LOGGER.info("Using JSON decoding codec {}", this.jsonDecoder.codecName()); if (jsonEncoder instanceof CodecWrappers.JacksonJsonMini) { throw new UnsupportedOperationException("Encoder: " + jsonEncoder.codecName() + "is not supported for the client"); } if (isJacksonXmlOnClasspath()) { <START> this.xmlEncoder = CodecWrappers.getEncoder("JacksonXml"); <END> this.xmlDecoder = CodecWrappers.getDecoder("JacksonXml"); LOGGER.info("Using XML encoding codec {}", this.xmlEncoder.codecName()); LOGGER.info("Using XML decoding codec {}", this.xmlDecoder.codecName()); } else { this.xmlEncoder = null; this.xmlDecoder = null; } }</code><technical_language>class instead of raw strings</technical_language>

Target:
public DiscoveryJerseyProvider(EncoderWrapper jsonEncoder, DecoderWrapper jsonDecoder) { this.jsonEncoder = jsonEncoder == null ? CodecWrappers.getEncoder(LegacyJacksonJson.class) : jsonEncoder; this.jsonDecoder = jsonDecoder == null ? CodecWrappers.getDecoder(LegacyJacksonJson.class) : jsonDecoder; LOGGER.info("Using JSON encoding codec {}", this.jsonEncoder.codecName()); LOGGER.info("Using JSON decoding codec {}", this.jsonDecoder.codecName()); if (jsonEncoder instanceof CodecWrappers.JacksonJsonMini) { throw new UnsupportedOperationException("Encoder: " + jsonEncoder.codecName() + "is not supported for the client"); } this.xmlEncoder = CodecWrappers.getEncoder(CodecWrappers.XStreamXml.class); this.xmlDecoder = CodecWrappers.getDecoder(CodecWrappers.XStreamXml.class); LOGGER.info("Using XML encoding codec {}", this.xmlEncoder.codecName()); LOGGER.info("Using XML decoding codec {}", this.xmlDecoder.codecName()); }
Source:
<code>public KafkaMessage nextRecord(String topic, long timeout) throws InterruptedException { KafkaMessage message = null; BlockingQueue<KafkaMessage> queue = topicQueue.get(topic); if (queue != null) { message = queue.poll(timeout, TimeUnit.MILLISECONDS); <START> } <END> return message; }</code><technical_language>kind of here, serious. worth throw IllegalArgumentException if queue is null (didn't break unexpected for me, removeTopic test)</technical_language>

Target:
public KafkaMessage nextRecord(String topic, long timeout) throws InterruptedException { KafkaMessage message = null; BlockingQueue<KafkaMessage> queue = topicQueue.get(topic); if (queue != null) { message = queue.poll(timeout, TimeUnit.MILLISECONDS); } else { log.warn("Tried to take record from non-existant topic queue: {}", topic); } return message; }
Source:
<code>public void test() throws Exception { TestInvokable invokable = new TestInvokable(); CheckpointBarrierUnaligner unaligner = new CheckpointBarrierUnaligner(new int[]{1}, ChannelStateWriter.NO_OP, "test", invokable); for (RuntimeEvent e : events) { if (e instanceof CancelCheckpointMarker) { unaligner.processCancellationBarrier((CancelCheckpointMarker) e); } else if (e instanceof CheckpointBarrier) { <START> unaligner.processBarrier((CheckpointBarrier) e, 0, 0); <END> } else { throw new IllegalArgumentException("unexpected event type: " + e); } } assertEquals(shouldAbortCheckpoint, invokable.checkpointAborted); assertEquals(shouldTriggerCheckpoint, invokable.checkpointTriggered); }</code><technical_language>test notifyBarrierReceived</technical_language>

Target:
public void test() throws Exception { TestInvokable invokable = new TestInvokable(); CheckpointBarrierUnaligner unaligner = new CheckpointBarrierUnaligner(new int[]{numChannels}, ChannelStateWriter.NO_OP, "test", invokable); for (RuntimeEvent e : events) { if (e instanceof CancelCheckpointMarker) { unaligner.processCancellationBarrier((CancelCheckpointMarker) e); } else if (e instanceof CheckpointBarrier) { unaligner.processBarrier((CheckpointBarrier) e, channel, 0); } else { throw new IllegalArgumentException("unexpected event type: " + e); } } assertEquals("expectAbortCheckpoint", expectAbortCheckpoint, invokable.checkpointAborted); assertEquals("expectTriggerCheckpoint", expectTriggerCheckpoint, invokable.checkpointTriggered); }
Source:
<code>public void update(String body) throws IOException { owner.root.retrieve() <START> .method("POST") <END> .with("body", body) .method("PATCH") .withUrlPath(getApiRoute()) .to(GHIssueComment.class); this.body = body; }</code><technical_language>Multiple method(*) methods</technical_language>

Target:
public void update(String body) throws IOException { owner.root.createRequest() .method("PATCH") .with("body", body) .withUrlPath(getApiRoute()) .fetch(GHIssueComment.class); this.body = body; }
Source:
<code>public final View getView(int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); switch (type) { case SectionRow.ITEM: { convertView = mInflater.inflate(R.layout.row_course_outline_list, parent, false); ViewHolder tag = getTag(convertView); convertView.setTag(tag); break; } case SectionRow.SECTION: { convertView = mInflater.inflate(R.layout.row_section_header, parent, false); break; } case SectionRow.COURSE_CARD: { if (convertView == null) { convertView = mInflater.inflate(R.layout.row_course_card, parent, false); } break; } case SectionRow.LAST_ACCESSED_ITEM: { if (convertView == null) { convertView = mInflater.inflate(R.layout.row_last_accessed, parent, false); } break; } default: { throw new IllegalArgumentException(String.valueOf(type)); } } <START> switch (type) { <END> case SectionRow.ITEM: { return getRowView(position, convertView); } case SectionRow.SECTION: { return getHeaderView(position, convertView); } case SectionRow.COURSE_CARD: { return getCardView(convertView); } case SectionRow.LAST_ACCESSED_ITEM: { return getLastAccessedView(position, convertView); } default: { throw new IllegalArgumentException(String.valueOf(type)); } } }</code><technical_language>is need 2 switch statements this function</technical_language>

Target:
public final View getView(int position, View convertView, ViewGroup parent) { final int type = getItemViewType(position); switch (type) { case SectionRow.ITEM: { convertView = inflater.inflate(R.layout.row_course_outline_list, parent, false); ViewHolder tag = getTag(convertView); convertView.setTag(tag); return getRowView(position, convertView); } case SectionRow.SECTION: { convertView = inflater.inflate(R.layout.row_section_header, parent, false); return getHeaderView(position, convertView); } case SectionRow.COURSE_CARD: { if (convertView == null) { convertView = inflater.inflate(R.layout.row_course_card, parent, false); } return getCardView(convertView); } case SectionRow.LAST_ACCESSED_ITEM: { if (convertView == null) { convertView = inflater.inflate(R.layout.row_last_accessed, parent, false); } return getLastAccessedView(position, convertView); } default: { throw new IllegalArgumentException(String.valueOf(type)); } } }
Source:
<code>protected void initTemplateDisks(List<DiskImage> disks) { Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> list = new ArrayList<>(); <START> for (Disk disk : disks) { <END> DiskModel diskModel = new DiskModel(); diskModel.getAlias().setEntity(disk.getDiskAlias()); diskModel.getVolumeType().setIsAvailable(false); switch (disk.getDiskStorageType()) { case IMAGE: DiskImage diskImage = (DiskImage) disk; diskModel.setSize(new EntityModel<>((int) diskImage.getSizeInGigabytes())); ListModel volumes = new ListModel(); volumes.setItems((diskImage.getVolumeType() == VolumeType.Preallocated ? new ArrayList<>(Arrays.asList(new VolumeType[]{VolumeType.Preallocated})) : AsyncDataProvider.getInstance().getVolumeTypeList()), diskImage.getVolumeType()); diskModel.setVolumeType(volumes); break; case CINDER: CinderDisk cinderDisk = (CinderDisk) disk; diskModel.setSize(new EntityModel<>((int) cinderDisk.getSizeInGigabytes())); ListModel volumeTypes = new ListModel(); volumeTypes.setItems(new ArrayList<>(Arrays.asList(cinderDisk.getVolumeType())), cinderDisk.getVolumeType()); diskModel.setVolumeType(volumeTypes); break; } diskModel.setDisk(disk); list.add(diskModel); } getModel().setDisks(list); updateIsDisksAvailable(); initStorageDomains(); }</code><technical_language>iterating List<DiskImage> safely DiskImage type of loop variable save cast line 641</technical_language>

Target:
protected void initTemplateDisks(List<DiskImage> disks) { Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> list = new ArrayList<>(); for (DiskImage disk : disks) { DiskModel diskModel = new DiskModel(); diskModel.getAlias().setEntity(disk.getDiskAlias()); diskModel.getVolumeType().setIsAvailable(false); switch (disk.getDiskStorageType()) { case IMAGE: diskModel.setSize(new EntityModel<>((int) disk.getSizeInGigabytes())); ListModel volumes = new ListModel(); volumes.setItems((disk.getVolumeType() == VolumeType.Preallocated ? new ArrayList<>(Arrays.asList(new VolumeType[]{VolumeType.Preallocated})) : AsyncDataProvider.getInstance().getVolumeTypeList()), disk.getVolumeType()); diskModel.setVolumeType(volumes); break; case CINDER: CinderDisk cinderDisk = (CinderDisk) disk; diskModel.setSize(new EntityModel<>((int) cinderDisk.getSizeInGigabytes())); ListModel volumeTypes = new ListModel(); volumeTypes.setItems(new ArrayList<>(Arrays.asList(cinderDisk.getVolumeType())), cinderDisk.getVolumeType()); diskModel.setVolumeType(volumeTypes); break; } diskModel.setDisk(disk); list.add(diskModel); } getModel().setDisks(list); updateIsDisksAvailable(); initStorageDomains(); }
Source:
<code>public void doUserCancel_chargeStatusDuringAuthorisation_DoesNotNeedCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(false); when(mockChargeDao.findByExternalId(externalChargeId)).thenReturn(Optional.of(chargeEntity)); chargeCancelService.doUserCancel(externalChargeId); verify(mockPaymentProvider, never()).cancel(any()); verify(chargeService).transitionChargeState(externalChargeId, USER_CANCELLED); <START> verifyNoMoreInteractions(ignoreStubs(mockChargeDao)); <END> }</code><technical_language>purpose for verifying interactions mockChargeDao</technical_language>

Target:
public void doUserCancel_chargeStatusDuringAuthorisation_DoesNotNeedCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(false); when(mockChargeDao.findByExternalId(externalChargeId)).thenReturn(Optional.of(chargeEntity)); chargeCancelService.doUserCancel(externalChargeId); verify(mockPaymentProvider, never()).cancel(any()); verify(chargeService).transitionChargeState(externalChargeId, USER_CANCELLED); }
Source:
<code>private void maybeDeleteActiveConsumers(final String groupId, final Admin adminClient) throws ExecutionException, InterruptedException { final DescribeConsumerGroupsResult describeResult = adminClient.describeConsumerGroups( Collections.singleton(groupId), new DescribeConsumerGroupsOptions().timeoutMs(10 * 1000)); final List<MemberDescription> members = new ArrayList<>(describeResult.describedGroups().get(groupId).get().members()); if (!members.isEmpty()) { if (options.has(forceOption)) { System.out.println("Force deleting all active members in the group: " + groupId); <START> adminClient.removeMembersFromConsumerGroup(groupId, new RemoveMembersFromConsumerGroupOptions()).all(); <END> } else { throw new IllegalStateException("Consumer group '" + groupId + "' is still active " + "and has following members: " + members + ". " + "Make sure to stop all running application instances before running the reset tool." + "Try set '--force' in the cmdline to force delete active members."); } } }</code><technical_language>check member removal result proceeding? If call failed, operation fail error message result IMHO</technical_language>

Target:
private void maybeDeleteActiveConsumers(final String groupId, final Admin adminClient) throws ExecutionException, InterruptedException { final DescribeConsumerGroupsResult describeResult = adminClient.describeConsumerGroups( Collections.singleton(groupId), new DescribeConsumerGroupsOptions().timeoutMs(10 * 1000)); final List<MemberDescription> members = new ArrayList<>(describeResult.describedGroups().get(groupId).get().members()); if (!members.isEmpty()) { if (options.has(forceOption)) { System.out.println("Force deleting all active members in the group: " + groupId); try { adminClient.removeMembersFromConsumerGroup(groupId, new RemoveMembersFromConsumerGroupOptions()).all().get(); } catch (Exception e) { throw e; } } else { throw new IllegalStateException("Consumer group '" + groupId + "' is still active " + "and has following members: " + members + ". " + "Make sure to stop all running application instances before running the reset tool." + " You can use option '--force' to remove active members from the group."); } } }
Source:
<code>public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { <START> ArrayList<SongMetadata> music = new ArrayList<SongMetadata>(metadataList); <END> Collections.sort(music); return Collections.unmodifiableList(music); } }</code><technical_language>For large libraries, sorting call getLibrary introduce a lot of latency. a minimum, I want move sort synchronized block, in short long term sort in updateLibrary, is a infrequent action</technical_language>

Target:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { return Collections.unmodifiableList(new ArrayList<SongMetadata>(metadataList)); } }
Source:
<code>public ClusterHealthStatus getHealthStatus(String[] indexNames) { try { Response response = lowLevelClient.performRequest("GET", String.format("/_cluster/health/%s", getIndexesAsString(indexNames))); try (InputStream is = response.getEntity().getContent()) { Map<String, Object> map = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); return ClusterHealthStatus.fromString((String) map.get("status")); } } catch (IOException e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>new RuntimeException -> new NuxeoException everywhere</technical_language>

Target:
public ClusterHealthStatus getHealthStatus(String[] indexNames) { try { Response response = lowLevelClient.performRequest("GET", String.format("/_cluster/health/%s", getIndexesAsString(indexNames))); try (InputStream is = response.getEntity().getContent()) { Map<String, Object> map = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); return ClusterHealthStatus.fromString((String) map.get("status")); } } catch (IOException e) { throw new NuxeoException(e); } }
Source:
<code>private UserAnonymized getUserAnonymizedByID(UUID id) { UserAnonymized entity = UserAnonymized.getRepository().findOne(id); if (entity == null) { <START> throw InvalidDataException.analysisUserNotFound(id); <END> } return entity; }</code><technical_language>Please stick "Login ID", a term code base</technical_language>

Target:
private UserAnonymized getUserAnonymizedByID(UUID id) { UserAnonymized entity = UserAnonymized.getRepository().findOne(id); if (entity == null) { throw InvalidDataException.loginIDNotFound(id); } return entity; }
Source:
<code>private static File getPathForFeature(FeatureNameType featureName) { switch(featureName) { case COMMANDLOG : <START> return new File(VoltDB.instance().getCommandLogPath()); <END> case COMMANDLOGSNAPSHOT : return new File(VoltDB.instance().getCommandLogSnapshotPath()); case DROVERFLOW: return new File(VoltDB.instance().getDROverflowPath()); case EXPORTOVERFLOW: return new File(VoltDB.instance().getExportOverflowPath()); case SNAPSHOTS: return new File(VoltDB.instance().getSnapshotPath()); default: return null; } }</code><technical_language>VoltFile</technical_language>

Target:
private static VoltFile getPathForFeature(FeatureNameType featureName) { switch(featureName) { case COMMANDLOG : return new VoltFile(VoltDB.instance().getCommandLogPath()); case COMMANDLOGSNAPSHOT : return new VoltFile(VoltDB.instance().getCommandLogSnapshotPath()); case DROVERFLOW: return new VoltFile(VoltDB.instance().getDROverflowPath()); case EXPORTOVERFLOW: return new VoltFile(VoltDB.instance().getExportOverflowPath()); case SNAPSHOTS: return new VoltFile(VoltDB.instance().getSnapshotPath()); default: return null; } }
Source:
<code><START> int length() <END> { return (int) Math.pow( 2, dimension ); }</code><technical_language>final</technical_language>

Target:
final int length() { return (int) Math.pow( 2, dimension ); }