auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void commitEntries() { context.checkThread(); long globalMatchIndex = context.getCluster().getMembers().stream().mapToLong(MemberState::getMatchIndex).min().orElse(context.getLog().lastIndex()); <START> context.setGlobalIndex(Math.min(globalMatchIndex - 1, 0)); <END> List<MemberState> members = context.getCluster().getActiveMembers((m1, m2) -> Long.compare(m2.getMatchIndex() != 0 ? m2.getMatchIndex() : 0l, m1.getMatchIndex() != 0 ? m1.getMatchIndex() : 0l)); if (members.isEmpty()) { context.setCommitIndex(context.getLog().lastIndex()); for (Map.Entry<Long, CompletableFuture<Long>> entry : commitFutures.entrySet()) { entry.getValue().complete(entry.getKey()); } commitFutures.clear(); return; } long commitIndex = members.get(quorumIndex()).getMatchIndex(); if (commitIndex > 0 && commitIndex > context.getCommitIndex() && (leaderIndex > 0 && commitIndex >= leaderIndex)) { context.setCommitIndex(commitIndex); SortedMap<Long, CompletableFuture<Long>> futures = commitFutures.headMap(commitIndex, true); for (Map.Entry<Long, CompletableFuture<Long>> entry : futures.entrySet()) { entry.getValue().complete(entry.getKey()); } futures.clear(); } }</code><technical_language>This max right? If matchIndex for server is 0 (it received entries) globalMatchIndex 0 get -1 fail validation somewhere</technical_language>

Target:
private void commitEntries() { context.checkThread(); long globalMatchIndex = context.getCluster().getMembers().stream().mapToLong(MemberState::getMatchIndex).min().orElse(context.getLog().lastIndex()); context.setGlobalIndex(Math.max(globalMatchIndex - 1, 0)); List<MemberState> members = context.getCluster().getActiveMembers((m1, m2) -> Long.compare(m2.getMatchIndex() != 0 ? m2.getMatchIndex() : 0l, m1.getMatchIndex() != 0 ? m1.getMatchIndex() : 0l)); if (members.isEmpty()) { context.setCommitIndex(context.getLog().lastIndex()); for (Map.Entry<Long, CompletableFuture<Long>> entry : commitFutures.entrySet()) { entry.getValue().complete(entry.getKey()); } commitFutures.clear(); return; } long commitIndex = members.get(quorumIndex()).getMatchIndex(); if (commitIndex > 0 && commitIndex > context.getCommitIndex() && (leaderIndex > 0 && commitIndex >= leaderIndex)) { context.setCommitIndex(commitIndex); SortedMap<Long, CompletableFuture<Long>> futures = commitFutures.headMap(commitIndex, true); for (Map.Entry<Long, CompletableFuture<Long>> entry : futures.entrySet()) { entry.getValue().complete(entry.getKey()); } futures.clear(); } }
Source:
<code>public DefaultUrlSanitizer(Collection<String> protocols) { <START> this.protocols = protocols; <END> }</code><technical_language>a defensive copy of passed in Collection new HashSet<String>(protocols)</technical_language>

Target:
public DefaultUrlSanitizer(Collection<String> protocols) { this.protocols = new HashSet<>(protocols); }
Source:
<code>public File createCompressedSegmentDataFile(final File indexFilesDir) throws IOException { <START> final File zipOutFile = File.createTempFile(TEMP_DIR, AzureStorageDruidModule.INDEX_ZIP_FILE_NAME); <END> CompressionUtils.zip(indexFilesDir, zipOutFile); return zipOutFile; }</code><technical_language>File. createTempFile takes prefix / suffix, dir / Filename. this confusing glance</technical_language>

Target:
public File createCompressedSegmentDataFile(final File indexFilesDir) throws IOException { final File zipOutFile = File.createTempFile("index", ".zip"); CompressionUtils.zip(indexFilesDir, zipOutFile); return zipOutFile; }
Source:
<code>private void handleNextRun() { if (m_state != SchedulerWrapperState.RUNNING) { return; } SchedulerResult result; try { result = m_scheduler.nextRun(m_procedure); } catch (RuntimeException e) { errorOccurred("Scheduler encountered unexpected error", e); return; } if (result == null) { errorOccurred("Scheduler returned a null result"); return; } synchronized (this) { if (m_state != SchedulerWrapperState.RUNNING) { return; } Runnable runnable; switch (result.getStatus()) { case EXIT: exitRequested(result.getMessage()); return; <START> case ERROR: <END> if (result.hasMessage()) { log.warn(generateLogMessage(result.getMessage())); } errorOccurred(null); return; case RERUN: runnable = this::handleNextRun; break; case PROCEDURE: runnable = this::executeProcedure; break; default: throw new IllegalStateException("Unknown status: " + result.getStatus()); } m_procedure = result.getScheduledProcedure(); try { m_scheduledFuture = addExceptionListener( m_wrapperExecutor.schedule(runnable, calculateDelay(), TimeUnit.NANOSECONDS)); m_procedure.scheduled(); } catch (RejectedExecutionException e) { if (log.isDebugEnabled()) { log.debug(generateLogMessage( "Could not schedule next procedure scheduler shutdown: " + m_procedure.getProcedure())); } } } }</code><technical_language>put this file concrete handlers wrappers? package-private limit access it</technical_language>

Target:
private void handleNextRun() { Scheduler scheduler; synchronized (this) { if (m_state != SchedulerWrapperState.RUNNING) { return; } scheduler = m_scheduler; } long startTime = System.nanoTime(); long waitTime = startTime - m_expectedExecutionTime; SchedulerResult result; try { result = scheduler.nextRun(m_procedure); } catch (RuntimeException e) { errorOccurred("Scheduler encountered unexpected error", e); return; } finally { m_stats.addSchedulerCall(System.nanoTime() - startTime, waitTime); } if (result == null) { errorOccurred("Scheduler returned a null result"); return; } synchronized (this) { if (m_state != SchedulerWrapperState.RUNNING) { return; } Runnable runnable; switch (result.getStatus()) { case EXIT: exitRequested(result.getMessage()); return; case ERROR: if (result.hasMessage()) { log.warn(generateLogMessage(result.getMessage())); } errorOccurred(null); return; case RERUN: runnable = this::handleNextRun; break; case PROCEDURE: runnable = this::executeProcedure; break; default: throw new IllegalStateException("Unknown status: " + result.getStatus()); } m_procedure = result.getScheduledProcedure(); try { long delay = calculateDelay(); m_expectedExecutionTime = System.nanoTime() + delay; m_procedure.expectedExecutionTime(m_expectedExecutionTime); m_scheduledFuture = addExceptionListener( m_wrapperExecutor.schedule(runnable, delay, TimeUnit.NANOSECONDS)); } catch (RejectedExecutionException e) { if (log.isDebugEnabled()) { log.debug(generateLogMessage( "Could not schedule next procedure scheduler shutdown: " + m_procedure.getProcedure())); } } } }
Source:
<code>public void selectField(Long id, String username, String fieldName) { Entity entity = getEntity(id); UserPreferences userPreferences = allUserPreferences.retrieveByClassNameAndUsername(entity.getClassName(), username); userPreferences = checkPreferences(userPreferences, entity, username); Field field = entity.getField(fieldName); assertField(field); List<Field> fields = userPreferences.getVisibleFields(); fields.add(field); <START> userPreferences.setVisibleFields(fields); <END> allUserPreferences.update(userPreferences); }</code><technical_language>set is required manipulating orignal collection (maybe add addField method UserPreferences though)</technical_language>

Target:
public void selectField(Long id, String username, String fieldName) { Entity entity = getEntity(id); UserPreferences userPreferences = allUserPreferences.retrieveByClassNameAndUsername(entity.getClassName(), username); userPreferences = checkPreferences(userPreferences, entity, username); Field field = entity.getField(fieldName); assertField(field); userPreferences.selectField(field); allUserPreferences.update(userPreferences); }
Source:
<code>public FenceOperationResult <START> fence(FenceActionType <END> action, FenceAgent agent) { FenceOperationResult result; VDS proxyHost = getProxyLocator().findProxyHost(isRetryEnabled(action)); if (proxyHost == null) { return new FenceOperationResult( Status.ERROR, HostPowerStatus.UNKNOWN, String.format( "Failed to run Power Management command on Host '%s', no proxy was found", fencedHost.getHostName())); } try { result = runFenceAction(action, agent, proxyHost); if (result.getStatus() == Status.ERROR) { log.warn( "Fence operation failed with proxy host '{}', trying another proxy", proxyHost.getHostName()); VDS alternativeProxy = getProxyLocator().findProxyHost( isRetryEnabled(action), proxyHost.getId()); if (alternativeProxy != null) { result = runFenceAction(action, agent, alternativeProxy); } else { log.warn( "Failed to find another proxy to re-run failed fence operation, " + "retrying with the same proxy '{}'", proxyHost.getHostName()); result = runFenceAction(action, agent, proxyHost); } } } catch (VdcBLLException e) { log.debug("Exception", e); result = new FenceOperationResult( FenceOperationResult.Status.ERROR, HostPowerStatus.UNKNOWN, e.getMessage()); } return result; }</code><technical_language>FenceExecutor a method exact signature. exist</technical_language>

Target:
public FenceOperationResult fence(FenceActionType action, FenceAgent agent) { FenceOperationResult result; VDS proxyHost = getProxyLocator().findProxyHost(isRetryEnabled(action)); if (proxyHost == null) { return new FenceOperationResult( Status.ERROR, PowerStatus.UNKNOWN, String.format( "Failed to run Power Management command on Host '%s', no proxy was found", fencedHost.getHostName())); } try { result = runFenceAction(action, agent, proxyHost); if (result.getStatus() == Status.ERROR) { log.warn( "Fence operation failed with proxy host '{}', trying another proxy", proxyHost.getHostName()); VDS alternativeProxy = getProxyLocator().findProxyHost( isRetryEnabled(action), proxyHost.getId()); if (alternativeProxy != null) { result = runFenceAction(action, agent, alternativeProxy); } else { log.warn( "Failed to find another proxy to re-run failed fence operation, " + "retrying with the same proxy '{}'", proxyHost.getHostName()); result = runFenceAction(action, agent, proxyHost); } } } catch (VdcBLLException e) { log.debug("Exception", e); result = new FenceOperationResult( FenceOperationResult.Status.ERROR, PowerStatus.UNKNOWN, e.getMessage()); } return result; }
Source:
<code>static <T> Try.CheckedSupplier<T> decorateCheckedSupplier(Timer timer, Try.CheckedSupplier<T> supplier){ return () -> { <START> Timer.Context context = timer.time(); <END> try { return supplier.get(); } finally{ context.stop(); } }; }</code><technical_language>try-with-resources java try (Timer.Context context = timer.time()) { return supplier.get(); }</technical_language>

Target:
static <T> Try.CheckedSupplier<T> decorateCheckedSupplier(Timer timer, Try.CheckedSupplier<T> supplier){ return () -> { try (Timer.Context context = timer.time()) { return supplier.get(); } }; }
Source:
<code>private void setActionIconBackground(int color) { <START> GradientDrawable shape = new GradientDrawable(); <END> shape.setCornerRadius(actionBackground.getResources() .getDimensionPixelSize(R.dimen.list_feed_action_icon_corner_radius)); shape.setColor(color); actionBackground.setBackground(shape); }</code><technical_language>rect rounded corners? why? shape fits in this situation</technical_language>

Target:
private void setActionIconBackground(int color) { GradientDrawable shape = new GradientDrawable(); shape.setShape(GradientDrawable.OVAL); shape.setColor(color); actionIcon.setBackground(shape); }
Source:
<code>private void execute(UnmodifiableTestPlan unmodifiableTestPlan, TestExecutionListener[] listeners) { Root root = unmodifiableTestPlan.getRoot(); ConfigurationParameters configurationParameters = root.getConfigurationParameters(); TestExecutionListenerRegistry listenerRegistry = buildListenerRegistryForExecution(listeners); withInterceptedStreams(configurationParameters, listenerRegistry, testExecutionListener -> { <START> TestPlan testPlan = unmodifiableTestPlan.getDelegate(); <END> testExecutionListener.testPlanExecutionStarted(testPlan); ExecutionListenerAdapter engineExecutionListener = new ExecutionListenerAdapter(testPlan, testExecutionListener); for (TestEngine testEngine : root.getTestEngines()) { TestDescriptor testDescriptor = root.getTestDescriptorFor(testEngine); execute(testEngine, new ExecutionRequest(testDescriptor, engineExecutionListener, configurationParameters)); } testExecutionListener.testPlanExecutionFinished(testPlan); }); }</code><technical_language>Is necessary work "modifiable" TestPlan this point on, suffice work UnmodifiableTestPlan execution phase? I about, reasonable disallow modification of TestPlan a registered TestExecutionListener</technical_language>

Target:
private void execute(UnmodifiableTestPlan unmodifiableTestPlan, TestExecutionListener[] listeners) { Root root = unmodifiableTestPlan.getRoot(); ConfigurationParameters configurationParameters = root.getConfigurationParameters(); TestExecutionListenerRegistry listenerRegistry = buildListenerRegistryForExecution(listeners); withInterceptedStreams(configurationParameters, listenerRegistry, testExecutionListener -> { TestPlan testPlan = unmodifiableTestPlan.getDelegate(); testExecutionListener.testPlanExecutionStarted(unmodifiableTestPlan); ExecutionListenerAdapter engineExecutionListener = new ExecutionListenerAdapter(testPlan, testExecutionListener); for (TestEngine testEngine : root.getTestEngines()) { TestDescriptor testDescriptor = root.getTestDescriptorFor(testEngine); execute(testEngine, new ExecutionRequest(testDescriptor, engineExecutionListener, configurationParameters)); } testExecutionListener.testPlanExecutionFinished(unmodifiableTestPlan); }); }
Source:
<code>public void afterDelivery() throws ApplicationServerInternalException, UnavailableException { switch (state) { case RELEASED: throw new IllegalStateException("Message endpoint factory has been released"); case NONE: throw new IllegalStateException("afterDelivery may only be called if message delivery began with a beforeDelivery call"); } boolean exceptionThrown = false; try { container.afterDelivery(instance); } catch (final SystemException se) { exceptionThrown = true; final Throwable throwable = se.getRootCause() != null ? se.getRootCause() : se; <START> throwable.printStackTrace(); <END> throw new ApplicationServerInternalException(throwable); } finally { if (state == State.SYSTEM_EXCEPTION) { recreateInstance(exceptionThrown); } state = State.NONE; } }</code><technical_language>logging instead</technical_language>

Target:
public void afterDelivery() throws ApplicationServerInternalException, UnavailableException { switch (state) { case RELEASED: throw new IllegalStateException("Message endpoint factory has been released"); case NONE: throw new IllegalStateException("afterDelivery may only be called if message delivery began with a beforeDelivery call"); } boolean exceptionThrown = false; try { container.afterDelivery(instance); } catch (final SystemException se) { exceptionThrown = true; final Throwable throwable = se.getRootCause() != null ? se.getRootCause() : se; throw new ApplicationServerInternalException(throwable); } finally { if (state == State.SYSTEM_EXCEPTION) { recreateInstance(exceptionThrown); } state = State.NONE; } }
Source:
<code>private Composite createDirectionGroup(Composite parent) { Composite panel = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginWidth = 0; layout.marginHeight = 0; panel.setLayout(layout); Group group = new Group(panel, SWT.SHADOW_ETCHED_IN); <START> group.setText("Direction"); <END> GridLayout groupLayout = new GridLayout(); group.setLayout(groupLayout); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); SelectionListener selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; fForwardRadioButton = new Button(group, SWT.RADIO | SWT.LEFT); fForwardRadioButton.setText("F&orward"); setGridData(fForwardRadioButton, SWT.LEFT, false, SWT.CENTER, false); fForwardRadioButton.addSelectionListener(selectionListener); storeButtonWithMnemonicInMap(fForwardRadioButton); Button backwardRadioButton = new Button(group, SWT.RADIO | SWT.LEFT); backwardRadioButton.setText("&Backward"); setGridData(backwardRadioButton, SWT.LEFT, false, SWT.CENTER, false); backwardRadioButton.addSelectionListener(selectionListener); storeButtonWithMnemonicInMap(backwardRadioButton); backwardRadioButton.setSelection(!fForwardInit); fForwardRadioButton.setSelection(fForwardInit); return panel; }</code><technical_language>externalize user facing strings</technical_language>

Target:
private Composite createDirectionGroup(Composite parent) { Composite panel = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginWidth = 0; layout.marginHeight = 0; panel.setLayout(layout); Group group = new Group(panel, SWT.SHADOW_ETCHED_IN); group.setText(Messages.TimeGraphFindDialog_Direction); GridLayout groupLayout = new GridLayout(); group.setLayout(groupLayout); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); SelectionListener selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; fForwardRadioButton = new Button(group, SWT.RADIO | SWT.LEFT); fForwardRadioButton.setText(Messages.TimeGraphFindDialog_ForwardRadioButton_label); setGridData(fForwardRadioButton, SWT.LEFT, false, SWT.CENTER, false); fForwardRadioButton.addSelectionListener(selectionListener); storeButtonWithMnemonicInMap(fForwardRadioButton); Button backwardRadioButton = new Button(group, SWT.RADIO | SWT.LEFT); backwardRadioButton.setText(Messages.TimeGraphFindDialog_BackwardRadioButton_label); setGridData(backwardRadioButton, SWT.LEFT, false, SWT.CENTER, false); backwardRadioButton.addSelectionListener(selectionListener); storeButtonWithMnemonicInMap(backwardRadioButton); backwardRadioButton.setSelection(!fForwardInit); fForwardRadioButton.setSelection(fForwardInit); return panel; }
Source:
<code>public void init(String host, int port) throws Exception { <START> if(host.contains("0.0.0.0")) { <END> uri = new URI("http://" + host + ":" + port + "/"); } else { uri = new URI("http://" + "localhost" + ":" + port + "/"); } openBrowser(); }</code><technical_language>contains string equality here? For instance 140.0.0.0 contains 0.0.0.0 I want rewrite localhost. Also, marginally cleaner set a variable storing cleaned host in if block, build URI based cleaned host</technical_language>

Target:
public void init(String host, int port) throws Exception { String cleanedHost = host; if("0.0.0.0".equals(host)) { cleanedHost = "localhost"; } uri = new URI("http://" + cleanedHost + ":" + port + "/"); openBrowser(); }
Source:
<code>public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_new_tab: providerListener.onNewTabRequested(); return true; case R.id.menu_close_all_tabs: AlertDialog.Builder alert = new AlertDialog.Builder(fragment.getContext()); alert.setMessage(R.string.close_all_tabs_confirm); alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { <START> dialog.dismiss(); <END> providerListener.onCloseAllTabs(); } }); alert.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alert.create().show(); return true; default: return false; } }</code><technical_language>need call dialog.dismiss() here. This is done implicitly</technical_language>

Target:
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_new_tab: providerListener.onNewTabRequested(); return true; case R.id.menu_close_all_tabs: AlertDialog.Builder alert = new AlertDialog.Builder(fragment.getContext()); alert.setMessage(R.string.close_all_tabs_confirm); alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { providerListener.onCloseAllTabs(); } }); alert.setNegativeButton(R.string.no, null); alert.create().show(); return true; default: return false; } }
Source:
<code>public double approximatedForwardAccumulation() { double accumulatedInterest = 0.0d; int nbPeriodNotCutOff = nbPeriods - cutoffOffset + 1; if (fixedPeriod < nbPeriodNotCutOff) { LocalDate startDateApprox = onRatePeriodEffectiveDates.get(fixedPeriod); LocalDate endDateApprox = onRatePeriodMaturityDates.get(nbPeriodNotCutOff - 1); <START> accumulatedInterest = approximatedInterest(env, index, startDateApprox, endDateApprox); <END> } return accumulatedInterest; }</code><technical_language>return</technical_language>

Target:
public double approximatedForwardAccumulation() { int nbPeriodNotCutOff = nbPeriods - cutoffOffset + 1; if (fixedPeriod < nbPeriodNotCutOff) { LocalDate startDateApprox = onRatePeriodEffectiveDates.get(fixedPeriod); LocalDate endDateApprox = onRatePeriodMaturityDates.get(nbPeriodNotCutOff - 1); return approximatedInterest(env, index, startDateApprox, endDateApprox); } return 0.0d; }
Source:
<code>void collectExpectedIssues(String comment, int line) { if (NONCOMPLIANT_COMMENT.matcher(comment).find()) { IssueAndFlows issueAndFlows = parseIssue(comment, line); <START> if (issueAndFlows.parsed()) { <END> issues.put(LINE.get(issueAndFlows.issue), issueAndFlows.issue); issueAndFlows.flows.forEach(f -> flows.put(f.id, f)); } else { LOG.warn("Comment on line not parsed", comment, line); } } if (FLOW_COMMENT.matcher(comment).find()) { parseFlows(comment, line).forEach(f -> flows.put(f.id, f)); } }</code><technical_language>- constant IssueAndFlow.NULL is declared - IssueAndFlow class is implementing equals hashcode I this condition false I is tested. I for suggestion remove completely</technical_language>

Target:
void collectExpectedIssues(String comment, int line) { if (NONCOMPLIANT_COMMENT.matcher(comment).find()) { ParsedComment parsedComment = parseIssue(comment, line); issues.put(LINE.get(parsedComment.issue), parsedComment.issue); parsedComment.flows.forEach(f -> flows.put(f.id, f)); } if (FLOW_COMMENT.matcher(comment).find()) { parseFlows(comment, line).forEach(f -> flows.put(f.id, f)); } }
Source:
<code>public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); context.record( <START> TransformLineageRecorderUtils.oneToOneIn(TransformLineageRecorderUtils.getFields(outSchema), <END> "compress", "Use the specified algorithm to compress the field.")); }</code><technical_language>This transform method ignores fields in input schema is in output schema, perform similar logic add drop operations for fields do get emitted output record</technical_language>

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); parseConfiguration(config.compressor, context.getFailureCollector()); List<String> inFields = TransformLineageRecorderUtils.getFields(context.getInputSchema()); List<String> outFields = TransformLineageRecorderUtils.getFields(context.getOutputSchema()); List<String> identityFields = outFields.stream() .filter(field -> !compMap.containsKey(field) || compMap.get(field) == CompressorType.NONE) .collect(Collectors.toList()); List<String> processedFields = new ArrayList<>(outFields); processedFields.removeAll(identityFields); List<String> droppedFields = new ArrayList<>(inFields); droppedFields.removeAll(outFields); List<FieldOperation> output = new ArrayList<>(); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(processedFields, "compress", "Used the specified algorithm to compress the field.")); output.addAll(TransformLineageRecorderUtils.generateDrops(droppedFields)); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(identityFields, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); context.record(output); }
Source:
<code><START> Map<String, List<PipelineTemplate>> list( <END> @RequestParam(required = false, value = "scopes") List<String> scopes) { PipelineTemplateDAO pipelineTemplateDAO = getPipelineTemplateDAO(); Collection<PipelineTemplate> pipelineTemplates = pipelineTemplateDAO.getPipelineTemplatesByScope(scopes).stream() .filter(pt -> pt.getOrDefault("schema", "").equals("v2")) .collect(Collectors.toList()); return pipelineTemplateDAO.groupPipelineTemplatesById(pipelineTemplates); }</code><technical_language>In general, I encourage changing API's contract this. means upgrade front50, gate, deck, spin time. If of out of sync, get 500 errors, callers receive a map, try read a list (or vice versa). add a new API in front50 gate, change deck spin call new API remove API. level of safety care Netflix upgrades separately</technical_language>

Target:
List<PipelineTemplate> list( @RequestParam(required = false, value = "scopes") List<String> scopes) { return (List<PipelineTemplate>) getPipelineTemplateDAO().getPipelineTemplatesByScope(scopes); }
Source:
<code>public void lock() throws InterruptedException, TimeoutException { Exception exception = null; ExceptionType exceptionType = ExceptionType.NONE; for (ExtendedLockPromise lockPromise : lockPromiseList) { try { lockPromise.lock(); } catch (InterruptedException e) { if (exception == null) { exception = e; exceptionType = ExceptionType.INTERRUPTED; } } catch (TimeoutException e) { if (exception == null) { exception = e; exceptionType = ExceptionType.TIMEOUT; } } catch (DeadlockDetectedException e) { if (exception == null) { exception = e; exceptionType = ExceptionType.DEADLOCK; } } catch (RuntimeException e) { if (exception == null) { exception = e; exceptionType = ExceptionType.RUNTIME; } } } if (exception != null) { switch (exceptionType) { <START> case INTERRUPTED: <END> throw (InterruptedException) exception; case TIMEOUT: throw (TimeoutException) exception; case RUNTIME: throw (RuntimeException) exception; case DEADLOCK: throw (DeadlockDetectedException) exception; default: break; } } }</code><technical_language>I exception instanceof InterruptedException work... I want some kind of exception hierarchy, e.g. InterruptedException trumps else, in case a separate variable for exception type better. Also, I try preserve exceptions more of them, addSuppressed()</technical_language>

Target:
public void lock() throws InterruptedException, TimeoutException { InterruptedException interruptedException = null; TimeoutException timeoutException = null; DeadlockDetectedException deadlockException = null; RuntimeException runtimeException = null; for (ExtendedLockPromise lockPromise : lockPromiseList) { try { lockPromise.lock(); } catch (InterruptedException e) { interruptedException = e; } catch (TimeoutException e) { timeoutException = e; } catch (DeadlockDetectedException e) { deadlockException = e; } catch (RuntimeException e) { runtimeException = e; } } if (interruptedException != null) { throw interruptedException; } else if (timeoutException != null) { throw timeoutException; } else if (deadlockException != null) { throw deadlockException; } else if (runtimeException != null) { throw runtimeException; } }
Source:
<code>public void testAfterApplicationName() throws Exception { String baseDS = ".credentials/talend-googledrive"; String appName = ""; assertThat(properties.datastorePath.getValue(), endsWith(baseDS)); appName = "GoogleDriveTests"; properties.applicationName.setValue(appName); properties.afterApplicationName(); <START> assertThat(properties.datastorePath.getValue(), endsWith(baseDS + "/" + appName)); <END> }</code><technical_language>work windows '\'</technical_language>

Target:
public void testAfterApplicationName() throws Exception { String baseDS = ".credentials" + File.separator + "talend-googledrive"; String appName = ""; assertThat(properties.datastorePath.getValue(), endsWith(baseDS)); appName = "GoogleDriveTests"; properties.applicationName.setValue(appName); properties.afterApplicationName(); assertThat(properties.datastorePath.getValue(), endsWith(baseDS + File.separator + appName)); }
Source:
<code>public MetricsMode toggle() { do { currentMode = modeIterator.next(); } while (!getCurrentMode().isAvailable()); return this.getCurrentMode(); <START> } <END></code><technical_language>I concerned this method. exception generated if next() is called set is empty? Also, I infinite loop if of MetricsMode.isAvailable() methods return true. I if a compact easier read method work: public MetricsMode toggle() { MetricsMode startingMode = getCurrentMode(); while(modeIterator.hasNext()) { currentMode = modeIterator.next(); if(currentMode == startingMode || currentMode.isAvailable()) { break; } } return currentMode; }</technical_language>

Target:
public MetricsMode toggle() { do { cursor = (cursor + 1) % modes.size(); currentMode = modes.get(cursor); } while (!currentMode.isAvailable()); return currentMode; }
Source:
<code>public void checkFullyInitialized() throws IllegalStateException { if (fullyInitialized) { return; } if (!initialized) { throw new IllegalStateException("Metadata not yet initialized"); } <START> fullyInitialized = true; END> try { for (Field field : fields) { if (field instanceof StructField) { ((StructField) field).getMetadata().checkFullyInitialized(); } } } catch (RuntimeException e) { fullyInitialized = false; throw e; } }</code><technical_language>Scares this is volatile in this manner. This threadsafe moment a checking thread erroneously validate fully initialized if sees trueness set other thread</technical_language>

Target:
public void checkFullyInitialized() throws IllegalStateException { if (initializationFullyChecked || Boolean.TRUE.equals(checkingForFullInitialization.get())) { return; } if (!initialized) { throw new IllegalStateException("Metadata not yet initialized"); } checkingForFullInitialization.set(Boolean.TRUE); try { for (Field field : fields) { if (field instanceof StructField) { ((StructField) field).getMetadata().checkFullyInitialized(); } } initializationFullyChecked = true; } finally { checkingForFullInitialization.remove(); } }
Source:
<code>public SpongeCommandData setLastOutput(Text message) { if (message.isEmpty()) { <START> this.lastOutput = null; <END> } else { this.lastOutput = message; } return this; }</code><technical_language>checkNotNull</technical_language>

Target:
public SpongeCommandData setLastOutput(Text message) { if (checkNotNull(message, "message").isEmpty()) { this.lastOutput = null; } else { this.lastOutput = message; } return this; }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { <START> if (args.length != 2) <END> { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } smite(player); return true; }</code><technical_language>Reason optional</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length != 1) { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } smite(player); return true; }
Source:
<code>protected void setAuthentication(final Builder builder) { if (tokenManager != null) { String accessToken = tokenManager.getToken(); <START> builder.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); <END> } else if (getApiKey() == null) { if (skipAuthentication) { return; } throw new IllegalArgumentException("apiKey or username and password were not specified"); } else { builder.addHeader(HttpHeaders.AUTHORIZATION, apiKey.startsWith(BASIC) ? apiKey : BASIC + apiKey); } }</code><technical_language>"Bearer " a constant</technical_language>

Target:
protected void setAuthentication(final Builder builder) { if (tokenManager != null) { String accessToken = tokenManager.getToken(); builder.addHeader(HttpHeaders.AUTHORIZATION, BEARER + accessToken); } else if (getApiKey() == null) { if (skipAuthentication) { return; } throw new IllegalArgumentException("apiKey or username and password were not specified"); } else { builder.addHeader(HttpHeaders.AUTHORIZATION, apiKey.startsWith(BASIC) ? apiKey : BASIC + apiKey); } }
Source:
<code>private MessageFormatInputStream getPutMessage(StoreKey key, BlobProperties blobProperties, byte[] usermetadata, byte[] blob, int blobSize, short blobVersion, BlobType blobType) throws MessageFormatException { <START> switch (blobVersion) { <END> case MessageFormatRecord.Blob_Version_V1: return new PutMessageFormatBlobV1InputStream(key, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize, blobType); case MessageFormatRecord.Blob_Version_V2: return new PutMessageFormatInputStream(key, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize, blobType); default: throw new IllegalStateException("Unsupported Blob version " + blobVersion); } }</code><technical_language>this consistent rest of tests. switch-case preferably, you</technical_language>

Target:
private MessageFormatInputStream getPutMessage(StoreKey key, BlobProperties blobProperties, byte[] usermetadata, byte[] blob, int blobSize, short blobVersion, BlobType blobType) throws MessageFormatException { if (blobVersion == MessageFormatRecord.Blob_Version_V2) { return new PutMessageFormatInputStream(key, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize, blobType); } else { return new PutMessageFormatBlobV1InputStream(key, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize, blobType); } }
Source:
<code>private VmPayload getPayloadModel() { VmPayload payload = new VmPayload(); payload.setType(VmDeviceType.CDROM); <START> payload.getFiles().put("payloadFile", PAYLOAD_COMTENT); <END> return payload; }</code><technical_language>this change is correct for other content Payload is used, Base64 encoding</technical_language>

Target:
private VmPayload getPayloadModel() { VmPayload payload = new VmPayload(); payload.setType(VmDeviceType.CDROM); payload.getFiles().put("payloadFile", new String(Base64.decodeBase64(PAYLOAD_COMTENT))); return payload; }
Source:
<code>int writeBytes(InputStream input, int bytesToRead) throws IOException; static ChannelStateByteBuffer wrap(Buffer buffer) { return new ChannelStateByteBuffer() { private ByteBuf byteBuf = buffer.asByteBuf(); @Override public boolean isWritable() { return byteBuf.isWritable(); } @Override public int writableBytes() { return byteBuf.writableBytes(); } <START> <END> @Override public int writeBytes(InputStream input, int bytesToRead) throws IOException { return byteBuf.writeBytes(input, Math.min(bytesToRead, byteBuf.writableBytes())); } }; }</code><technical_language>TBH I of creating temporary byte array for buffer level, friendly for GC. brings additional copy while reading. i thought of a option now. at-least reuse buf for wrap</technical_language>

Target:
int writeBytes(InputStream input, int bytesToRead) throws IOException; static ChannelStateByteBuffer wrap(Buffer buffer) { return new ChannelStateByteBuffer() { private final ByteBuf byteBuf = buffer.asByteBuf(); @Override public boolean isWritable() { return byteBuf.isWritable(); } @Override public int writeBytes(InputStream input, int bytesToRead) throws IOException { return byteBuf.writeBytes(input, Math.min(bytesToRead, byteBuf.writableBytes())); } }; }
Source:
<code>void handlePendingNotices() { if (stateRef.get().pendingNotices.isEmpty()) { return; } LookupUpdateState swappedState = atomicallyUpdateStateRef( oldState -> { <START> return new LookupUpdateState(oldState.lookupMap, ImmutableList.of(), oldState.pendingNotices); <END> } ); Map<String, LookupExtractorFactoryContainer> lookupMap = new HashMap<>(swappedState.lookupMap); for (Notice notice : swappedState.noticesBeingHandled) { try { notice.handle(lookupMap); } catch (Exception ex) { LOG.error(ex, "Exception occured while handling lookup notice [%s].", notice); LOG.makeAlert("Exception occured while handling lookup notice, with message [%s].", ex.getMessage()).emit(); } } takeSnapshot(lookupMap); ImmutableMap<String, LookupExtractorFactoryContainer> immutableLookupMap = ImmutableMap.copyOf(lookupMap); atomicallyUpdateStateRef( oldState -> { return new LookupUpdateState(immutableLookupMap, oldState.pendingNotices, ImmutableList.of()); } ); }</code><technical_language>return keyword braces needed (and in places below)</technical_language>

Target:
void handlePendingNotices() { if (stateRef.get().pendingNotices.isEmpty()) { return; } LookupUpdateState swappedState = atomicallyUpdateStateRef( oldState -> new LookupUpdateState(oldState.lookupMap, ImmutableList.of(), oldState.pendingNotices) ); Map<String, LookupExtractorFactoryContainer> lookupMap = new HashMap<>(swappedState.lookupMap); for (Notice notice : swappedState.noticesBeingHandled) { try { notice.handle(lookupMap); } catch (Exception ex) { LOG.error(ex, "Exception occured while handling lookup notice [%s].", notice); LOG.makeAlert("Exception occured while handling lookup notice, with message [%s].", ex.getMessage()).emit(); } } takeSnapshot(lookupMap); ImmutableMap<String, LookupExtractorFactoryContainer> immutableLookupMap = ImmutableMap.copyOf(lookupMap); atomicallyUpdateStateRef( oldState -> new LookupUpdateState(immutableLookupMap, oldState.pendingNotices, ImmutableList.of()) ); }
Source:
<code>private Broker findNewLeader(Broker oldLeader) throws InterruptedException { long retryCnt = 0; while (true) { PartitionMetadata metadata = findLeader(); if (metadata != null) { replicaBrokers.clear(); for (Broker replica : metadata.replicas()) { replicaBrokers.add(new KafkaBroker(replica.host(), replica.port())); } log.debug("findNewLeader - metadata[%s], previous leader[%s]", metadata, oldLeader); Broker newLeader = metadata.leader(); if (newLeader != null) { if (oldLeader == null || !isCurrLeader(newLeader) || retryCnt != 0) { return newLeader; } } } <START> Thread.sleep(1000L); <END> retryCnt++; if (retryCnt >= 3 && (retryCnt - 3) % 5 == 0) { log.warn("cannot find leader for [%s] - [%s] after [%s] retries", topic, partitionId, retryCnt); replicaBrokers.clear(); replicaBrokers.addAll(allBrokers); } } }</code><technical_language>define this a constant somewhere</technical_language>

Target:
private Broker findNewLeader(Broker oldLeader) throws InterruptedException { long retryCnt = 0; while (true) { PartitionMetadata metadata = findLeader(); if (metadata != null) { replicaBrokers.clear(); for (Broker replica : metadata.replicas()) { replicaBrokers.add(new KafkaBroker(replica.host(), replica.port())); } log.debug("Got new Kafka leader metadata : [%s], previous leader : [%s]", metadata, oldLeader); Broker newLeader = metadata.leader(); if (newLeader != null) { if (oldLeader == null || isValidNewLeader(newLeader) || retryCnt != 0) { return newLeader; } } } Thread.sleep(RETRY_INTERVAL); retryCnt++; if (retryCnt >= 3 && (retryCnt - 3) % 5 == 0) { log.warn("cannot find leader for [%s] - [%s] after [%s] retries", topic, partitionId, retryCnt); replicaBrokers.clear(); replicaBrokers.addAll(allBrokers); } } }
Source:
<code>private void checkSessionExpiration() { if ( (currentConnectionState == ConnectionState.SUSPENDED) && (startOfSuspendedEpoch != 0) ) { long elapsedMs = System.currentTimeMillis() - startOfSuspendedEpoch; int useSessionTimeoutMs = getUseSessionTimeoutMs(); if ( elapsedMs >= useSessionTimeoutMs ) { startOfSuspendedEpoch = System.currentTimeMillis(); log.warn(String.format("Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d", elapsedMs, useSessionTimeoutMs)); try { client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); } catch ( Exception e ) { log.error("Could not inject session expiration", e); } } } else if ( currentConnectionState == ConnectionState.LOST ) { try { <START> if ( client.getZookeeperClient().isConnected() ) <END> { log.warn("ConnectionState is LOST but isConnected() is true. Resetting connection."); client.getZookeeperClient().reset(); } else { client.getZookeeperClient().getZooKeeper(); } } catch ( Exception e ) { log.error("Could not get ZooKeeper", e); } } }</code><technical_language>right now, checkSessionExpiration is called if sessionExpirationPercent > 0, change that</technical_language>

Target:
private void checkSessionExpiration() { if ( (currentConnectionState == ConnectionState.SUSPENDED) && (startOfSuspendedEpoch != 0) ) { long elapsedMs = System.currentTimeMillis() - startOfSuspendedEpoch; int useSessionTimeoutMs = getUseSessionTimeoutMs(); if ( elapsedMs >= useSessionTimeoutMs ) { startOfSuspendedEpoch = System.currentTimeMillis(); log.warn(String.format("Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d", elapsedMs, useSessionTimeoutMs)); try { client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); } catch ( Exception e ) { log.error("Could not inject session expiration", e); } } } else if ( currentConnectionState == ConnectionState.LOST ) { try { client.getZookeeperClient().getZooKeeper(); } catch ( Exception e ) { log.error("Could not get ZooKeeper", e); } } }
Source:
<code>protected IDialogSettings getPersistentPropertyStore() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(fViewId); if (section == null) { section = settings.addNewSection(fViewId); if (section == null) { throw new IllegalStateException("The persistent property section could not be added"); } } if (fViewName == null) { <START> System.out.println(getClass().getName() + ": name is null"); <END> return section; } IDialogSettings subSection = section.getSection(fViewName); if (subSection == null) { subSection = section.addNewSection(fViewName); if (subSection == null) { throw new IllegalStateException("The persistent property section could not be added"); } } return subSection; }</code><technical_language>remove? logWarning()</technical_language>

Target:
protected IDialogSettings getPersistentPropertyStore() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(fViewId); if (section == null) { section = settings.addNewSection(fViewId); if (section == null) { throw new IllegalStateException("The persistent property section could not be added"); } } return section; }
Source:
<code>public void unsubscribeFrom(final String channelName) { if (channelName == null) { throw new IllegalArgumentException("Cannot unsubscribe from null channel"); } final InternalChannel channel = channelNameToChannelMap.remove(channelName); if (channel == null) { return; } if (connection.getState() == ConnectionState.CONNECTED) { if (channel instanceof PrivateEncryptedChannelImpl) { <START> ((PrivateEncryptedChannelImpl) channel).tearDownChannel(); <END> } sendUnsubscribeMessage(channel); } }</code><technical_language>This class a dependency specific implementation details. handled existing updateState. if tread-safe generally good allow caller's thread access modify channel object... (it a barrier of thread executor queue)</technical_language>

Target:
public void unsubscribeFrom(final String channelName) { if (channelName == null) { throw new IllegalArgumentException("Cannot unsubscribe from null channel"); } final InternalChannel channel = channelNameToChannelMap.remove(channelName); if (channel == null) { return; } if (connection.getState() == ConnectionState.CONNECTED) { sendUnsubscribeMessage(channel); } }
Source:
<code>public void setAutoDisable(Boolean autoDisable) { this.autoDisable = autoDisable; <START> this.addServoEventListener(this); <END> log.info("setAutoDisable : " + autoDisable); delayDisable(); broadcastState(); }</code><technical_language>care separate concept of auto-enable auto-disable? i subtly different.. guess is 99.999% of time wan tot autoEnable in conjunction autoDisable..</technical_language>

Target:
public void setAutoDisable(Boolean autoDisable) { this.autoDisable = autoDisable; addServoEventListener(this); log.info("setAutoDisable : " + autoDisable); delayDisable(); broadcastState(); }
Source:
<code>public void testLastValueIgnoreNulls() <START> { <END> String query = "WITH T AS (" + " SELECT" + " p," + " v" + " FROM (" + " VALUES" + " (2, 2)," + " (1, 1)," + " (3, NULL)" + " ) T(p, v)" + ")" + "SELECT" + " LAST_VALUE(v) IGNORE NULLS OVER (" + " PARTITION BY 1" + " ORDER BY" + " p ASC" + " )" + "FROM T"; MaterializedResult actual = computeActual(query); for (MaterializedRow row : actual.getMaterializedRows()) { assertNotEquals(row.getField(0), null); } }</code><technical_language>write similar other tests assertQueryOrdered provide expected results, checking for null (look testValueWindowFunctions)</technical_language>

Target:
public void testLastValueIgnoreNulls() { assertQuery( "WITH T AS (" + " SELECT" + " p," + " v" + " FROM (" + " VALUES" + " (2, 2)," + " (1, 1)," + " (3, NULL)" + " ) T(p, v)" + ")" + "SELECT" + " LAST_VALUE(v) IGNORE NULLS OVER (" + " PARTITION BY 1" + " ORDER BY" + " p ASC" + " )" + "FROM T", "Values 1, 2, 2"); }
Source:
<code>public String toString() { <START> return super.toString() + "!"; <END> }</code><technical_language>specificity of this SV is exception type I add exceptionType in this</technical_language>

Target:
public String toString() { return super.toString() + "_" + exceptionType.fullyQualifiedName() + "!"; }
Source:
<code>public void onBreakBlock(Block block, World worldIn, BlockPos pos) { IMixinWorld spongeWorld = (IMixinWorld) worldIn; final CauseTracker causeTracker = spongeWorld.getCauseTracker(); <START> final boolean isBlockAlready = causeTracker.getPhases().current() != TrackingPhases.BLOCK; <END> if (isBlockAlready) { causeTracker.switchToPhase(TrackingPhases.BLOCK, BlockPhase.State.BLOCK_DECAY); } block.beginLeavesDecay(worldIn, pos); if (isBlockAlready) { causeTracker.pop(); } }</code><technical_language>This is more isNotBlockAlready</technical_language>

Target:
public void onBreakBlock(Block block, World worldIn, BlockPos pos) { IMixinWorldServer spongeWorld = (IMixinWorldServer) worldIn; final CauseTracker causeTracker = spongeWorld.getCauseTracker(); final boolean isBlockAlready = causeTracker.getStack().current() != TrackingPhases.BLOCK; final IBlockState blockState = worldIn.getBlockState(pos); final IBlockState actualState = blockState.getBlock().getActualState(blockState, worldIn, pos); if (isBlockAlready) { causeTracker.switchToPhase(TrackingPhases.BLOCK, BlockPhase.State.BLOCK_DECAY, PhaseContext.start() .add(NamedCause.source(spongeWorld.createSpongeBlockSnapshot(blockState, actualState, pos, 3))) .addCaptures() .complete()); } block.beginLeavesDecay(worldIn, pos); if (isBlockAlready) { causeTracker.completePhase(); } }
Source:
<code>public HiveMetastoreClient createMetastoreClient(String token) throws TException { List<HostAndPort> metastores = new ArrayList<>(addresses); if (isMultipleMetastore) { Collections.shuffle(metastores); } else { Collections.shuffle(metastores.subList(1, metastores.size())); } TException lastException = null; for (HostAndPort metastore : metastores) { try { <START> HiveMetastoreClient client; <END> client = clientFactory.create(metastore, token); if (!isNullOrEmpty(metastoreUsername)) { client.setUGI(metastoreUsername); } return client; } catch (TException e) { lastException = e; } } throw new TException("Failed connecting to Hive metastore: " + addresses, lastException); }</code><technical_language>inline factory instance creation</technical_language>

Target:
public HiveMetastoreClient createMetastoreClient(String token) throws TException { List<HostAndPort> metastores = new ArrayList<>(addresses); if (isMultipleMetastore) { Collections.shuffle(metastores); } else { Collections.shuffle(metastores.subList(1, metastores.size())); } TException lastException = null; for (HostAndPort metastore : metastores) { try { HiveMetastoreClient client = clientFactory.create(metastore, token); if (!isNullOrEmpty(metastoreUsername)) { client.setUGI(metastoreUsername); } return client; } catch (TException e) { lastException = e; } } throw new TException("Failed connecting to Hive metastore: " + addresses, lastException); }