auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void performDiskUpdate(final boolean unlockImage) { if (shouldPerformMetadataUpdate()) { updateMetaDataDescription((DiskImage) getNewDisk()); } final Disk disk = getDiskDao().get(getParameters().getDiskId()); applyUserChanges(disk); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getVmStaticDAO().incrementDbGeneration(getVm().getId()); updateDeviceProperties(); getBaseDiskDao().update(disk); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; diskImage.setQuotaId(getQuotaId()); if (unlockImage && diskImage.getImageStatus() == ImageStatus.LOCKED) { diskImage.setImageStatus(ImageStatus.OK); } getImageDao().update(diskImage.getImage()); updateQuota(diskImage); updateDiskProfile(); <START> } else { <END> updateLunProperties(); } reloadDisks(); updateBootOrder(); setSucceeded(true); return null; } private void updateDeviceProperties() { if (updateReadOnlyRequested()) { vmDeviceForVm.setIsReadOnly(getNewDisk().getReadOnly()); getVmDeviceDao().update(vmDeviceForVm); } if (getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface()) { getVmDeviceDao().clearDeviceAddress(getOldDisk().getId()); } } private void updateLunProperties() { vmDeviceForVm.setScsiReservationUsed(((LunDisk)getNewDisk()).isScsiReservationUsed()); getVmDeviceDao().update(vmDeviceForVm); } }); }</code><technical_language>Do types of disks? if have, this code fail add another type. I check for LUN type update one</technical_language>

Target:
private void performDiskUpdate(final boolean unlockImage) { if (shouldPerformMetadataUpdate()) { updateMetaDataDescription((DiskImage) getNewDisk()); } final Disk disk = getDiskDao().get(getParameters().getDiskId()); applyUserChanges(disk); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getVmStaticDAO().incrementDbGeneration(getVm().getId()); updateDeviceProperties(); getBaseDiskDao().update(disk); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; diskImage.setQuotaId(getQuotaId()); if (unlockImage && diskImage.getImageStatus() == ImageStatus.LOCKED) { diskImage.setImageStatus(ImageStatus.OK); } getImageDao().update(diskImage.getImage()); updateQuota(diskImage); updateDiskProfile(); } if (disk.getDiskStorageType() == DiskStorageType.LUN) { updateLunProperties((LunDisk)getNewDisk()); } reloadDisks(); updateBootOrder(); setSucceeded(true); return null; } private void updateDeviceProperties() { if (updateReadOnlyRequested()) { vmDeviceForVm.setIsReadOnly(getNewDisk().getReadOnly()); getVmDeviceDao().update(vmDeviceForVm); } if (getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface()) { getVmDeviceDao().clearDeviceAddress(getOldDisk().getId()); } } private void updateLunProperties(LunDisk lunDisk) { vmDeviceForVm.setScsiReservationUsed(lunDisk.isUsingScsiReservation()); getVmDeviceDao().update(vmDeviceForVm); } }); }
Source:
<code>public void init() throws MessagingException { String condition = getCondition().trim(); setExceptionClassName(condition); <START> try { <END> Class<?> exceptionClass = Class.forName(exceptionClassName); if (Throwable.class.isAssignableFrom(exceptionClass)) { this.exceptionClass = (Class<? extends Throwable>)exceptionClass; } else { throw new MessagingException("Specified class name is not a throwable."); } } catch (ClassNotFoundException e) { throw new MessagingException("Specified exception class not found."); } }</code><technical_language>some indent issues. enforce a 4 space indentation</technical_language>

Target:
public void init() throws MessagingException { try { String exceptionClassName = getCondition().trim(); this.exceptionClass = castToThrowable(Class.forName(exceptionClassName)); } catch (ClassNotFoundException e) { throw new MessagingException("Specified exception class not found.", e); } }
Source:
<code><START> private void putReportedMetrics(InstanceType instanceType, <END> List<Metric> reportedMetrics) { IndexedSet<Metric> metricSet = mWorkerMetrics; if (instanceType.equals(InstanceType.CLIENT)) { metricSet = mClientMetrics; } for (Metric metric : reportedMetrics) { if (metric.getHostname() == null) { continue; } if (metric.getMetricType() == MetricType.COUNTER) { String metricKeyName = metric.getInstanceType() + "." + metric.getName(); Counter counter = mClusterCounters.get(metricKeyName); if (counter != null) { counter.inc((long) metric.getValue()); continue; } if (instanceType.equals(InstanceType.CLIENT)) { continue; } if (metricKeyName.equals(MetricKey.WORKER_BYTES_READ_UFS.getName())) { incrementUfsRelatedCounters(metric, MetricKey.CLUSTER_BYTES_READ_UFS.getName(), MetricKey.CLUSTER_BYTES_READ_UFS_ALL.getName()); } else if (metricKeyName.equals(MetricKey.WORKER_BYTES_WRITTEN_UFS.getName())) { incrementUfsRelatedCounters(metric, MetricKey.CLUSTER_BYTES_WRITTEN_UFS.getName(), MetricKey.CLUSTER_BYTES_WRITTEN_UFS_ALL.getName()); } } else if (!metricSet.add(metric)) { metricSet.getFirstByField(FULL_NAME_INDEX, metric.getFullMetricName()) .setValue(metric.getValue()); } } }</code><technical_language>line</technical_language>

Target:
private void putReportedMetrics(InstanceType instanceType, List<Metric> reportedMetrics) { IndexedSet<Metric> metricSet = mWorkerMetrics; if (instanceType.equals(InstanceType.CLIENT)) { metricSet = mClientMetrics; } for (Metric metric : reportedMetrics) { if (metric.getHostname() == null) { continue; } if (metric.getMetricType() == MetricType.COUNTER) { ClusterCounterKey key = new ClusterCounterKey(instanceType, metric.getName()); Counter counter = mClusterCounters.get(key); if (counter != null) { counter.inc((long) metric.getValue()); continue; } if (instanceType.equals(InstanceType.CLIENT)) { continue; } if (metric.getName().equals(BYTES_READ_UFS)) { incrementUfsRelatedCounters(metric, MetricKey.CLUSTER_BYTES_READ_UFS.getName(), MetricKey.CLUSTER_BYTES_READ_UFS_ALL.getName()); } else if (metric.getName().equals(BYTES_WRITTEN_UFS)) { incrementUfsRelatedCounters(metric, MetricKey.CLUSTER_BYTES_WRITTEN_UFS.getName(), MetricKey.CLUSTER_BYTES_WRITTEN_UFS_ALL.getName()); } } else if (!metricSet.add(metric)) { metricSet.getFirstByField(FULL_NAME_INDEX, metric.getFullMetricName()) .setValue(metric.getValue()); } } }
Source:
<code>private long getTraceCompletionCount(String tenantId, Criteria criteria, boolean onlyFaulty) { String index = client.getIndex(tenantId); if (!refresh(index)) { return 0; } <START> FilterBuilder filter = FilterBuilders.existsFilter("fault"); <END> BoolQueryBuilder query = buildQuery(criteria, "timestamp", "businessTransaction", CompletionTime.class); SearchRequestBuilder request = getTraceCompletionRequest(index, criteria, query, 0); if (onlyFaulty) { request.setPostFilter(filter); } SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); return 0; } else { return response.getHits().getTotalHits(); } }</code><technical_language>This moved "if (onlyFaulty) {" statement elsewhere</technical_language>

Target:
private long getTraceCompletionCount(String tenantId, Criteria criteria, boolean onlyFaulty) { String index = client.getIndex(tenantId); if (!refresh(index)) { return 0; } BoolQueryBuilder query = buildQuery(criteria, "timestamp", "businessTransaction", CompletionTime.class); SearchRequestBuilder request = getTraceCompletionRequest(index, criteria, query, 0); if (onlyFaulty) { FilterBuilder filter = FilterBuilders.existsFilter("fault"); request.setPostFilter(filter); } SearchResponse response = request.execute().actionGet(); if (response.isTimedOut()) { msgLog.warnQueryTimedOut(); return 0; } else { return response.getHits().getTotalHits(); } }
Source:
<code>public void ignoreRegion(int start, int end) { for (int i = start; i <= end; i++) { <START> this.ignoredLineNumbers.add(i); <END> } }</code><technical_language>I store ignoredRegions instead of ignoredLineNumbers. Single lines need stored <LineNum, LineNum></technical_language>

Target:
public void ignoreRegion(int start, int end) { this.ignoredRegions.add(new Pair<>(start, end)); }
Source:
<code>private String getAttributeGroupNameImpl() { try { String readGroupName; if (isAligned) { readGroupName = getCurrentAlignment().getReadGroup(); } else { readGroupName = getCurrentUnalignedRead().getReadGroup(); } if (!readGroupName.equals("")) { return readGroupName; } <START> return "_"; <END> } catch (ErrorMsg e) { throw new RuntimeException(e); } }</code><technical_language>_ is a standard represent a missing attribute in htsjdk. If RG attribute is missing left unset</technical_language>

Target:
private String getAttributeGroupNameImpl() { try { String readGroupName; if (isAligned) { readGroupName = getCurrentAlignment().getReadGroup(); } else { readGroupName = getCurrentUnalignedRead().getReadGroup(); } if (!readGroupName.isEmpty()) { return readGroupName; } return getReadCollection().getName(); } catch (ErrorMsg e) { throw new RuntimeException(e); } }
Source:
<code>private int getLength(boolean pt, boolean seq, boolean ts, boolean ssrc) { if (!pt && !seq && !ts && !ssrc) return 0; else if (pt && !seq && !ts && !ssrc) return 1; else if (!pt && seq && !ts && !ssrc) return 2; else if (!pt && !seq && ts && !ssrc) return 4; else if (!pt && !seq && !ts && ssrc) return 5; else if (pt && seq && !ts && !ssrc) return 3; else if (pt && !seq && ts && !ssrc) return 5; else if (pt && !seq && !ts && ssrc) return 5; else if (!pt && seq && ts && !ssrc) return 6; else if (!pt && seq && !ts && ssrc) return 7; else if (!pt && !seq && ts && ssrc) return 8; else if (pt && seq && ts && !ssrc) return 7; else if (pt && seq && !ts && ssrc) return 7; else if (pt && !seq && ts && ssrc) return 9; else if (!pt && seq && ts && ssrc) return 10; else if (pt && seq && ts && ssrc) return 11; <START> return -1; <END> }</code><technical_language>throw here</technical_language>

Target:
private int getLength(boolean pt, boolean seq, boolean ts, boolean ssrc) { if (!pt && !seq && !ts && !ssrc) return 0; else if (pt && !seq && !ts && !ssrc) return 1; else if (!pt && seq && !ts && !ssrc) return 2; else if (!pt && !seq && ts && !ssrc) return 4; else if (!pt && !seq && !ts && ssrc) return 5; else if (pt && seq && !ts && !ssrc) return 3; else if (pt && !seq && ts && !ssrc) return 5; else if (pt && !seq && !ts && ssrc) return 5; else if (!pt && seq && ts && !ssrc) return 6; else if (!pt && seq && !ts && ssrc) return 7; else if (!pt && !seq && ts && ssrc) return 8; else if (pt && seq && ts && !ssrc) return 7; else if (pt && seq && !ts && ssrc) return 7; else if (pt && !seq && ts && ssrc) return 9; else if (!pt && seq && ts && ssrc) return 10; else if (pt && seq && ts && ssrc) return 11; throw new IllegalStateException(); }
Source:
<code>private Runnable upToChange(final boolean openReplyBox) { return new Runnable() { public void run() { <START> saveAllDrafts(); <END> String b = base != null ? String.valueOf(base.get()) : null; String rev = String.valueOf(revision.get()); Gerrit.display( PageLinks.toChange(changeId, rev), new ChangeScreen2(changeId, b, rev, openReplyBox)); } }; }</code><technical_language>This is timing race David mentioned. I modify this pass a CallbackGroup saveAllDrafts, pass DraftBox.save(). If unsaved is non-empty add final callback jumps change page. This allows wait proper time required for unsaved drafts save</technical_language>

Target:
private Runnable upToChange(final boolean openReplyBox) { return new Runnable() { public void run() { if (unsaved.isEmpty()) { goUpToChange(openReplyBox); } else { CallbackGroup group = new CallbackGroup(); saveAllDrafts(group); group.addFinal(new GerritCallback<Void>() { @Override public void onSuccess(Void result) { goUpToChange(openReplyBox); } }).onSuccess(null); } } }; }
Source:
<code>public static void main(String[] args) throws Exception { Injector injector = Guice.createInjector(new UpdateHelperModule(), new CheckHelperAuditModule(), new LdapModule()); HostUpdateHelper hostUpdateHelper = injector.getInstance(HostUpdateHelper.class); try { LOG.info("Host names update started."); String hostChangesFile = args[0]; if (hostChangesFile == null || hostChangesFile.isEmpty()) { throw new AmbariException("Path to file with host names changes is empty or null."); } hostUpdateHelper.setHostChangesFile(hostChangesFile); hostUpdateHelper.initHostChangesFileMap(); hostUpdateHelper.startPersistenceService(); hostUpdateHelper.validateHostChanges(); hostUpdateHelper.checkForSecurity(); hostUpdateHelper.updateHostsInDB(); hostUpdateHelper.updateHostsForTopologyRequests(); hostUpdateHelper.updateHostsForAlertsInDB(); hostUpdateHelper.updateHostsInConfigurations(); LOG.info("Host names update completed successfully."); } catch (AmbariException e) { LOG.error("Exception occurred during host names update, failed", e); throw e; <START> } catch (Throwable e){ <END> LOG.error("Unexpected error, host names update failed", e); throw new Exception("Unexpected error, host names update failed", e); } finally { hostUpdateHelper.stopPersistenceService(); } }</code><technical_language>reason catching Throwable converting exception? This catch errors OutOfMemoryError too</technical_language>

Target:
public static void main(String[] args) throws Exception { Injector injector = Guice.createInjector(new UpdateHelperModule(), new CheckHelperAuditModule(), new LdapModule()); HostUpdateHelper hostUpdateHelper = injector.getInstance(HostUpdateHelper.class); try { LOG.info("Host names update started."); String hostChangesFile = args[0]; if (hostChangesFile == null || hostChangesFile.isEmpty()) { throw new AmbariException("Path to file with host names changes is empty or null."); } hostUpdateHelper.setHostChangesFile(hostChangesFile); hostUpdateHelper.initHostChangesFileMap(); hostUpdateHelper.startPersistenceService(); hostUpdateHelper.validateHostChanges(); hostUpdateHelper.checkForSecurity(); hostUpdateHelper.updateHostsInDB(); hostUpdateHelper.updateHostsForTopologyRequests(); hostUpdateHelper.updateHostsForAlertsInDB(); hostUpdateHelper.updateHostsInConfigurations(); LOG.info("Host names update completed successfully."); } catch (AmbariException e) { LOG.error("Exception occurred during host names update, failed", e); throw e; } finally { hostUpdateHelper.stopPersistenceService(); } }
Source:
<code><START> public long createSession(Session session, boolean reserve) { <END> long sid = random.nextLong(); synchronized (session) { session.state = reserve ? State.RESERVED : State.UNRESERVED; session.startTime = session.lastAccessTime = System.currentTimeMillis(); } while (sessions.putIfAbsent(sid, session) != null) { sid = random.nextLong(); } return sid; }</code><technical_language>nice initial state for Sessions check is in state here</technical_language>

Target:
public long createSession(Session session, boolean reserve) { long sid = random.nextLong(); synchronized (session) { Preconditions.checkArgument(session.state == State.NEW); session.state = reserve ? State.RESERVED : State.UNRESERVED; session.startTime = session.lastAccessTime = System.currentTimeMillis(); } while (sessions.putIfAbsent(sid, session) != null) { sid = random.nextLong(); } return sid; }
Source:
<code>protected Case getElement(int recordId, QueryContext context) { if (context == null) { return super.getElement(recordId, context); } CaseGroupResultCache caseGroupCache = context.getQueryCacheOrNull(CaseGroupResultCache.class); CaseObjectCache caseObjectCache = getCaseObjectCacheIfRelevant(context); if (caseObjectCache != null && (caseObjectCache.isLoaded(recordId) || canLoadCaseFromGroup(caseGroupCache, recordId))) { <START> if (!caseObjectCache.isLoaded(recordId)) { <END> Pair<String, LinkedHashSet<Integer>> tranche = caseGroupCache.getTranche(recordId); EvaluationTrace loadTrace = new EvaluationTrace(String.format("Bulk Case Load [%s]", tranche.first)); SqlStorage<ACase> sqlStorage = ((SqlStorage<ACase>)storage); LinkedHashSet<Integer> body = tranche.second; sqlStorage.bulkRead(body, caseObjectCache.getLoadedCaseMap()); loadTrace.setOutcome("Loaded: " + body.size()); context.reportTrace(loadTrace); } return caseObjectCache.getLoadedCase(recordId); } return super.getElement(recordId, context); }</code><technical_language>I this simplified adding this if statement</technical_language>

Target:
protected Case getElement(int recordId, QueryContext context) { if (context == null) { return super.getElement(recordId, context); } CaseSetResultCache caseSetCache = context.getQueryCacheOrNull(CaseSetResultCache.class); CaseObjectCache caseObjectCache = getCaseObjectCacheIfRelevant(context); if(caseObjectCache != null) { if (caseObjectCache.isLoaded(recordId)) { return caseObjectCache.getLoadedCase(recordId); } if (canLoadCaseFromGroup(caseSetCache, recordId)) { Pair<String, LinkedHashSet<Integer>> tranche = caseSetCache.getCaseSetForRecord(recordId); EvaluationTrace loadTrace = new EvaluationTrace(String.format("Bulk Case Load [%s]", tranche.first)); SqlStorage<ACase> sqlStorage = ((SqlStorage<ACase>)storage); LinkedHashSet<Integer> body = tranche.second; sqlStorage.bulkRead(body, caseObjectCache.getLoadedCaseMap()); loadTrace.setOutcome("Loaded: " + body.size()); context.reportTrace(loadTrace); return caseObjectCache.getLoadedCase(recordId); } } return super.getElement(recordId, context); }
Source:
<code>protected void initInternal(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { super.initInternal(filterConfig); setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null)); log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl); setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false"))); log.trace("Loaded renew parameter: " + this.renew); setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false"))); log.trace("Loaded gateway parameter: " + this.gateway); String[] excludeUrls = parseExcludePatterns(getPropertyFromInitParams(filterConfig, EXCLUDE_PARAMETERS_INIT_PARAM, "false")); setExcludePatterns(excludeUrls); <START> log.trace("exclude patterns: " + excludePatterns); <END> final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null); if (gatewayStorageClass != null) { try { this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance(); } catch (final Exception e) { log.error(e,e); throw new ServletException(e); } } } }</code><technical_language>"Exclude patterns:" stay consistent rest of messages</technical_language>

Target:
protected void initInternal(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { super.initInternal(filterConfig); setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null)); log.trace("Loaded CasServerLoginUrl parameter: " + this.casServerLoginUrl); setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false"))); log.trace("Loaded renew parameter: " + this.renew); setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false"))); log.trace("Loaded gateway parameter: " + this.gateway); Pattern[] excludeUrls = parseExcludePatterns(getPropertyFromInitParams(filterConfig, EXCLUDE_PARAMETERS_INIT_PARAM, "false")); setExcludePatterns(excludeUrls); log.trace("Exclude patterns: " + excludePatterns); final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null); if (gatewayStorageClass != null) { try { this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance(); } catch (final Exception e) { log.error(e,e); throw new ServletException(e); } } } }
Source:
<code>public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { <START> AddressEntry entry = new AddressEntry(wallet.freshReceiveKey(), context, offerId, true); <END> addressEntryList.addAddressEntry(entry); return entry; } } }</code><technical_language>Is called a trade protocol entry? e.g. for multisig</technical_language>

Target:
public AddressEntry getOrCreateAddressEntry(String offerId, AddressEntry.Context context) { Optional<AddressEntry> addressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> offerId.equals(e.getOfferId())) .filter(e -> context == e.getContext()) .findAny(); if (addressEntry.isPresent()) { return addressEntry.get(); } else { Optional<AddressEntry> emptyAvailableAddressEntry = getAddressEntryListAsImmutableList().stream() .filter(e -> AddressEntry.Context.AVAILABLE == e.getContext()) .filter(e -> isAddressUnused(e.getAddress())) .filter(e -> Script.ScriptType.P2PKH.equals(e.getAddress().getOutputScriptType())) .findAny(); if (emptyAvailableAddressEntry.isPresent()) { return addressEntryList.swapAvailableToAddressEntryWithOfferId(emptyAvailableAddressEntry.get(), context, offerId); } else { DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(wallet.freshReceiveAddress(Script.ScriptType.P2PKH)); AddressEntry entry = new AddressEntry(key, context, offerId, false); addressEntryList.addAddressEntry(entry); return entry; } } }
Source:
<code>private void checkShutdown() { if (completedOrFailedEvalCount.incrementAndGet() == <START> initServerCount + addedServerContextCount.get() + initWorkerCount + addedWorkerContextCount.get()) { <END> for (final ActiveContext serverContext : serverContexts) { serverContext.close(); } for (final ActiveContext workerContext : workerContextsToClose) { workerContext.close(); } isComplete = true; } }</code><technical_language>L558 replaced runningWorkerContextCount.get() + runningServerContextCount.get()</technical_language>

Target:
private void checkShutdown() { if (completedOrFailedEvalCount.incrementAndGet() == initServerCount + addedServerContextCount.get() + initWorkerCount + addedWorkerContextCount.get()) { if (isJobFinished.compareAndSet(false, true)) { Executors.newSingleThreadExecutor().submit(new Runnable() { @Override public void run() { while (optimizationOrchestrator.isPlanExecuting()) { try { LOG.log(Level.INFO, "It's time to shutdown active contexts, but wait for completion of plan execution"); Thread.sleep(SHUTDOWN_TRIAL_INTERVAL_MS); } catch (final InterruptedException e) { LOG.log(Level.FINEST, "Interrupted while waiting for plan finish", e); } } for (final ActiveContext serverContext : serverContexts) { serverContext.close(); } for (final ActiveContext workerContext : workerContextsToClose) { workerContext.close(); } } }); } } }
Source:
<code>public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { <START> for (Order stock : position) { <END> if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } return null; }</code><technical_language>loop position symbol parameters null</technical_language>

Target:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { if(position != null && symbol != null){ for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } } return null; }
Source:
<code>public void enterFieldkey(ABCMusicParser.FieldkeyContext ctx) { Letter letter = Letter.fromChar(ctx.key().keynote().basenote() .getText().charAt(0)); SingleAccidental accidental = SingleAccidental.NATURAL; boolean major = true; if (ctx.key().keynote().keyaccidental().size() != 0) { <START> if (ctx.key().keynote().keyaccidental().get(0).getText().hashCode() == "b" <END> .hashCode()) { accidental = SingleAccidental.FLAT; } else if (ctx.key().keynote().keyaccidental().get(0).getText() .hashCode() == "#".hashCode()) { accidental = SingleAccidental.SHARP; } } if (ctx.key().modeminor().size() != 0 && ctx.key().modeminor().get(0).getText().hashCode() == "m" .hashCode()) { major = false; } KeySignature keySignature = new KeySignature(letter, accidental, major); System.out.println("Key: Accidental = " + accidental.name() + "; Letter = " + letter.name() + "; Major = " + major); }</code><technical_language>curious -- compare hashcodes</technical_language>

Target:
public void enterFieldkey(ABCMusicParser.FieldkeyContext ctx) { Letter letter = Letter.fromChar(ctx.key().keynote().basenote() .getText().charAt(0)); SingleAccidental accidental = SingleAccidental.NATURAL; boolean major = true; System.out.println("ACCIDENTAL: " + ctx.key().keynote().keyaccidental().get(0).getText()); if (ctx.key().keynote().keyaccidental().size() != 0) { if (ctx.key().keynote().keyaccidental().get(0).getText() .equals("b")) { accidental = SingleAccidental.FLAT; } else if (ctx.key().keynote().keyaccidental().get(0).getText() .equals("#")) { accidental = SingleAccidental.SHARP; } } if (ctx.key().modeminor().size() != 0 && ctx.key().modeminor().get(0).getText().equals("m")) { major = false; } KeySignature keySignature = new KeySignature(letter, accidental, major); System.out.println("Key: Accidental = " + accidental.name() + "; Letter = " + letter.name() + "; Major = " + major); }
Source:
<code>private Iterable<? extends AttributeQuery<?>> parseListQuery(HttpServletRequest request) throws QueryParseException { ImmutableSet.Builder<AttributeQuery<?>> operands = ImmutableSet.builder(); for (Entry<String, String[]> param : getParameterMap(request).entrySet()) { Optional<Attribute<?>> optionalAttribute = attributesLookup.attributeFor(param.getKey()); if (optionalAttribute.isPresent()) { Attribute<?> attribute = optionalAttribute.get(); QueryAtomParser<?> parser = parsers.get(attribute); for (String paramString : param.getValue()) { Iterable<String> values; if (attribute.isCollectionOfValues()) { values = splitVals(paramString); } else { <START> values = Collections.singletonList(paramString); <END> } operands.add(parser.parse(param.getKey(), values)); } } } return operands.build(); }</code><technical_language>this effectively verify a single parameter, treat parameter single</technical_language>

Target:
private Iterable<? extends AttributeQuery<?>> parseListQuery(HttpServletRequest request) throws QueryParseException { ImmutableSet.Builder<AttributeQuery<?>> operands = ImmutableSet.builder(); for (Entry<String, String[]> param : getParameterMap(request).entrySet()) { Optional<Attribute<?>> attribute = attributesLookup.attributeFor(param.getKey()); if (attribute.isPresent()) { QueryAtomParser<?> parser = parsers.get(attribute.get()); for (String paramString : param.getValue()) { Iterable<String> rawValues; if (param.getKey().equals(Attributes.Q.externalName())) { rawValues = Collections.singletonList(paramString); } else { rawValues = splitVals(paramString); } operands.add(parser.parse(param.getKey(), rawValues)); } } } return operands.build(); }
Source:
<code>public Optional<SchedulePeriod> getFinalStub() { SchedulePeriod lastPeriod = getLastPeriod(); <START> if (!isTerm() && !lastPeriod.isRegular(frequency, rollConvention)) { <END> return Optional.of(lastPeriod); } else { return Optional.empty(); } }</code><technical_language>clearer if reversed read "if term, if period is regular, final stub"</technical_language>

Target:
public Optional<SchedulePeriod> getFinalStub() { return (isFinalStub() ? Optional.of(getLastPeriod()) : Optional.empty()); }
Source:
<code>public CustomField getCustomFieldById(int customFieldId) { <START> if(customFields == null) return null; <END> for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }</code><technical_language>need in null check here, a matter of personal preference</technical_language>

Target:
public CustomField getCustomFieldById(int customFieldId) { for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }
Source:
<code>public BatchItem( final String rawEvent, final boolean strictParsing, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = new JSONObject(rawEvent); if (strictParsing) { try { final JSONObject shadowEvent = StrictJsonParser.parseObject(rawEvent); <START> if (!shadowEvent.toString().equals(this.event.toString())) { <END> LOG.debug("[STRICT_JSON_DIFF] Strict parser produced different output for event: {}", rawEvent); } } catch (final Exception e) { LOG.debug("[STRICT_JSON_DIFF] Failed to parse event with strict parser: {}", rawEvent); } } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }</code><technical_language>I approach in unit test. I thought is safe :)</technical_language>

Target:
public BatchItem( final String rawEvent, final boolean strictParsing, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = new JSONObject(rawEvent); if (strictParsing) { try { final JSONObject shadowEvent = StrictJsonParser.parseObject(rawEvent); final String shadowOutput = shadowEvent.toString(); final String usualOutput = this.event.toString(); if (!shadowOutput.equals(usualOutput)) { LOG.debug("[STRICT_JSON_DIFF] Strict parser produced different output for event: " + "Strict parser output: Old parser output: {}", rawEvent, shadowOutput, usualOutput); } } catch (final Exception e) { LOG.debug("[STRICT_JSON_DIFF] Failed to parse event with strict parser: Error message: {}", rawEvent, e.getMessage()); } } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }
Source:
<code>private void handleCluster(HttpGetCommand command) { Node node = textCommandService.getNode(); NetworkingService ns = node.getNetworkingService(); EndpointManager cem = ns.getEndpointManager(CLIENT); AggregateEndpointManager aem = ns.getAggregateEndpointManager(); ClusterServiceImpl clusterService = node.getClusterService(); JsonArray membersArray = new JsonArray(); clusterService.getMembers() .stream() .map(m -> new JsonObject() .add("address", m.getAddress().toString()) .add("liteMember", m.isLiteMember()) .add("localMember", m.localMember()) .add("uuid", m.getUuid().toString()) .add("memberVersion", m.getVersion().toString())) .forEach(membersArray::add); JsonObject response = new JsonObject() <START> .add("memberList", clusterService.getMemberListString()) <END> .add("members", membersArray) .add("connectionCount", cem.getActiveConnections().size()) .add("allConnectionCount", aem.getActiveConnections().size()); prepareResponse(command, response); }</code><technical_language>is some reason string version, consider removing memberList all</technical_language>

Target:
private void handleCluster(HttpGetCommand command) { Node node = textCommandService.getNode(); NetworkingService ns = node.getNetworkingService(); EndpointManager cem = ns.getEndpointManager(CLIENT); AggregateEndpointManager aem = ns.getAggregateEndpointManager(); ClusterServiceImpl clusterService = node.getClusterService(); JsonArray membersArray = new JsonArray(); clusterService.getMembers() .stream() .map(m -> new JsonObject() .add("address", m.getAddress().toString()) .add("liteMember", m.isLiteMember()) .add("localMember", m.localMember()) .add("uuid", m.getUuid().toString()) .add("memberVersion", m.getVersion().toString())) .forEach(membersArray::add); JsonObject response = new JsonObject() .add("members", membersArray) .add("connectionCount", cem.getActiveConnections().size()) .add("allConnectionCount", aem.getActiveConnections().size()); prepareResponse(command, response); }
Source:
<code>public boolean canHandle(Object object) { <START> return DanglingStereotypeApplicationMergeViewerItem.class.isInstance(object); <END> }</code><technical_language>Please object instanceof Dangling..</technical_language>

Target:
public boolean canHandle(Object object) { return object instanceof DanglingStereotypeApplicationMergeViewerItem; }
Source:
<code>public void initialize(int kfactor) throws JSONException, KeeperException, InterruptedException, ExecutionException { final long maxWaitTime = TimeUnit.MINUTES.toSeconds(60); long remainingWaitTime = maxWaitTime; final long retryInterval = 10; while(remainingWaitTime > 0) { VoltZK.createCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker); if (m_messenger.getZK().exists(VoltZK.uacActiveBlocker, false) == null) { return; } VoltZK.removeCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker, REJOINLOG); <START> REJOINLOG.info(String.format("Rejoin node is waiting %d seconds for @UpdateApplicationCatalog to finish", <END> retryInterval)); try { Thread.sleep(TimeUnit.SECONDS.toMillis(retryInterval)); } catch (InterruptedException ignoreIt) { } remainingWaitTime -= retryInterval; } VoltDB.crashLocalVoltDB("Rejoin node is timed out " + maxWaitTime + " seconds waiting for @UpdateApplicationCatalog, " + "please retry node rejoin later manually."); }</code><technical_language>is waiting --> wait</technical_language>

Target:
public void initialize(int kfactor) throws JSONException, KeeperException, InterruptedException, ExecutionException { final long maxWaitTime = TimeUnit.MINUTES.toSeconds(60); long remainingWaitTime = maxWaitTime; final long retryInterval = 10; while(remainingWaitTime > 0) { VoltZK.createCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker); if (m_messenger.getZK().exists(VoltZK.uacActiveBlocker, false) == null) { return; } VoltZK.removeCatalogUpdateBlocker(m_messenger.getZK(), VoltZK.rejoinActiveBlocker, REJOINLOG); REJOINLOG.info(String.format("Rejoin node will wait %d seconds for @UpdateApplicationCatalog to finish", retryInterval)); try { Thread.sleep(TimeUnit.SECONDS.toMillis(retryInterval)); } catch (InterruptedException ignoreIt) { } remainingWaitTime -= retryInterval; } VoltDB.crashLocalVoltDB("Rejoin node is timed out " + maxWaitTime + " seconds waiting for @UpdateApplicationCatalog, " + "please retry node rejoin later manually."); }
Source:
<code>List<LogSegmentMetadata> getLogSegments() throws IOException; CompletableFuture<List<LogSegmentMetadata>> getLogSegmentsAsync(); void registerListener(LogSegmentListener listener) throws IOException; void unregisterListener(LogSegmentListener listener); CompletableFuture<AsyncLogWriter> openAsyncLogWriter(); default CompletableFuture<AsyncLogWriter> openAsyncLogWriter(LedgerMetadata ledgerMetadata) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>Return a failed future</technical_language>

Target:
List<LogSegmentMetadata> getLogSegments() throws IOException; CompletableFuture<List<LogSegmentMetadata>> getLogSegmentsAsync(); void registerListener(LogSegmentListener listener) throws IOException; void unregisterListener(LogSegmentListener listener); CompletableFuture<AsyncLogWriter> openAsyncLogWriter(); default CompletableFuture<AsyncLogWriter> openAsyncLogWriter(LedgerMetadata ledgerMetadata) { return FutureUtils.exception(new UnsupportedOperationException()); }
Source:
<code>public void one_awake_notification() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.triggerRegistrationUpdate(); <START> queueModeHelper.waitForUpdate(1); <END> queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); }</code><technical_language>reset latch</technical_language>

Target:
public void one_awake_notification() { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); queueModeHelper.waitForAwakeTime(awaketime * 1010); queueModeHelper.ensureClientSleeping(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureClientAwake(); queueModeHelper.resetAwakeLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.client.triggerRegistrationUpdate(); queueModeHelper.waitForUpdate(1); queueModeHelper.resetLatch(); queueModeHelper.ensureOneAwakeNotification(); }
Source:
<code>private static boolean checkIfEmptyRow(List<String> rowData) { if (rowData.isEmpty()) { return true; } return rowData.stream() .anyMatch(r -> r.isEmpty()); <START> } <END></code><technical_language>another this one. new code is previous</technical_language>

Target:
private static boolean checkIfEmptyRow(List<String> rowData) { return rowData.stream() .allMatch(r -> r.isEmpty()); }
Source:
<code><START> public final int getLifetime() { <END> return lifetime; }</code><technical_language>Ideally time entries units. a resort, clear units are. getters/setters/variables lifetimeInSeconds</technical_language>

Target:
int getLifetime() { return lifetime; }
Source:
<code>public void testConnectionsGetCycled() throws IOException{ TestCloudbigtableConnectionPool pool = new TestCloudbigtableConnectionPool(); Configuration config = new Configuration(); PoolEntry entry1 = pool.getConnection(config, "key"); PoolEntry entry2 = pool.getConnection(config, "key"); <START> pool.returnConnection(entry1); <END> pool.returnConnection(entry2); for (int i = 0; i < 100; i++) { PoolEntry newEntry = pool.getConnection(config, "key"); assertSame(i % 2 == 0 ? entry1 : entry2, newEntry); pool.returnConnection(newEntry); } }</code><technical_language>assert entry1 entry2 same</technical_language>

Target:
public void testConnectionsGetCycled() throws IOException{ TestCloudbigtableConnectionPool pool = new TestCloudbigtableConnectionPool(); PoolEntry entry1 = pool.getConnection(config, "key"); PoolEntry entry2 = pool.getConnection(config, "key"); assertNotSame(entry1, entry2); pool.returnConnection(entry1); pool.returnConnection(entry2); for (int i = 0; i < 100; i++) { PoolEntry newEntry = pool.getConnection(config, "key"); assertSame(i % 2 == 0 ? entry1 : entry2, newEntry); pool.returnConnection(newEntry); } }
Source:
<code>static ResourceKey of(final String namespace, final String value) { <START> return builder().namespace(namespace).value(value).build(); <END> }</code><technical_language>Prefix static methods class name, if is class</technical_language>

Target:
static ResourceKey of(final String namespace, final String value) { return ResourceKey.builder().namespace(namespace).value(value).build(); }
Source:
<code>public void storeContentToBinaryStorage(Document currentDocument, EntityKey entityKey, OptionsService optionService, Tuple tuple) { <START> Class entityClass = TableEntityTypeMappingInfo.getEntityClass( entityKey.getTable() ); <END> if ( currentDocument == null ) { return; } for ( String fieldName : currentDocument.keySet() ) { if ( fieldName.equals( "$set" ) ) { Document queryFields = (Document) currentDocument.get( fieldName ); for ( String queryField : queryFields.keySet() ) { storeContentFromFieldToBinaryStorage( queryFields, entityClass, queryField, optionService, tuple ); } } else { storeContentFromFieldToBinaryStorage( currentDocument, entityClass, fieldName, optionService, tuple ); } } }</code><technical_language>TableEntityTypeMappingInfo a static utility class, needs bound factory is working with</technical_language>

Target:
public void storeContentToBinaryStorage(Document currentDocument, EntityKey entityKey, OptionsService optionService, Tuple tuple) { Class entityClass = provider.getTableEntityTypeMapping().get( entityKey.getTable() ); if ( currentDocument == null ) { return; } for ( String fieldName : currentDocument.keySet() ) { if ( fieldName.equals( "$set" ) ) { Document queryFields = (Document) currentDocument.get( fieldName ); for ( String queryField : queryFields.keySet() ) { storeContentFromFieldToBinaryStorage( queryFields, entityClass, queryField, optionService, tuple ); } } else { storeContentFromFieldToBinaryStorage( currentDocument, entityClass, fieldName, optionService, tuple ); } } }
Source:
<code>protected void configure(HttpSecurity http) throws Exception { HeadersConfigurer<HttpSecurity> config = http.antMatcher("**").headers().frameOptions().sameOrigin(); config.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler()) .and().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/auth/welcome") .successHandler(authSuccessHandler).failureUrl("/loginfailed").and().authorizeRequests() .antMatchers("/signin/**", "/connect/**", "/signup/**", "/user/register/**", "/resources/**", "/register*", "/login*", "/logout*", "/createaccount*", "/sites/**", "/public/**", "/search/**", "/home/**", "/sociallogin*", "/forbidden") .permitAll() .antMatchers("/users/**", "/admin/**").hasRole("QUADRIGA_USER_ADMIN") .antMatchers("/", "/auth/welcome**", "/auth/home**", "/auth/about**", "/auth/profile/**", <START> "/rest/**", "/forbidden") <END> .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/auth/workbench/**", "/auth/rest/**", "/auth/conceptcollections/**", "/auth/conceptdetails/**", "/auth/transformation/**", "/auth/searchitems/**", "/auth/dictionaries/**", "/auth/editing/**", "/auth/networks/**") .hasAnyRole("QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/users/**", "/admin/**", "/auth/users/**", "/checks/**") .hasRole("QUADRIGA_USER_ADMIN").anyRequest() .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/**").denyAll() .and().apply(new SpringSocialConfigurer()); }</code><technical_language>/forbidden is permitAll</technical_language>

Target:
protected void configure(HttpSecurity http) throws Exception { HeadersConfigurer<HttpSecurity> config = http.antMatcher("**").headers().frameOptions().sameOrigin(); config.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler()) .and().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/auth/welcome") .successHandler(authSuccessHandler).failureUrl("/loginfailed").and().authorizeRequests() .antMatchers("/signin/**", "/connect/**", "/signup/**", "/user/register/**", "/resources/**", "/register*", "/login*", "/logout*", "/createaccount*", "/sites/**", "/public/**", "/search/**", "/home/**", "/sociallogin*", "/forbidden") .permitAll() .antMatchers("/users/**", "/admin/**").hasRole("QUADRIGA_USER_ADMIN") .antMatchers("/", "/auth/welcome**", "/auth/home**", "/auth/about**", "/auth/profile/**", "/rest/**") .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/auth/workbench/**", "/auth/rest/**", "/auth/conceptcollections/**", "/auth/conceptdetails/**", "/auth/transformation/**", "/auth/searchitems/**", "/auth/dictionaries/**", "/auth/editing/**", "/auth/networks/**") .hasAnyRole("QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/users/**", "/admin/**", "/auth/users/**", "/checks/**") .hasRole("QUADRIGA_USER_ADMIN").anyRequest() .hasAnyRole("QUADRIGA_USER_ADMIN", "QUADRIGA_USER_STANDARD", "QUADRIGA_USER_COLLABORATOR") .antMatchers("/**").denyAll() .and().apply(new SpringSocialConfigurer()); }
Source:
<code>public String toString() { <START> StringBuffer buffer <END> = new StringBuffer(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); } return buffer.toString(); }</code><technical_language>If Lars it, cry. StringBuffer in 21 century? (I know, copy/paste)</technical_language>

Target:
public String toString() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); } return buffer.toString(); }
Source:
<code>public void processEvent(Event event) { <START> if (!event.getDetails().getType().equalsIgnoreCase(DockerEvent.TYPE)) { <END> return; } DockerEvent dockerEvent = objectMapper.convertValue(event, DockerEvent.class); Observable.just(dockerEvent) .doOnNext(this::onEchoResponse) .subscribe(triggerEachMatchFrom(pipelineCache.getPipelines())); }</code><technical_language>getDetails() return null here</technical_language>

Target:
public void processEvent(Event event) { super.validateEvent(event); if (!event.getDetails().getType().equalsIgnoreCase(DockerEvent.TYPE)) { return; } DockerEvent dockerEvent = objectMapper.convertValue(event, DockerEvent.class); Observable.just(dockerEvent) .doOnNext(this::onEchoResponse) .subscribe(triggerEachMatchFrom(pipelineCache.getPipelines())); }