auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public PopupMenuExportResponse() { super(Constant.messages.getString("history.export.response.popup")); this.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.size() == 0) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.select.warning")); return; } File file = getOutputFile(); if (file == null) { return; } boolean isAppend = true; if (file.exists()) { int rc = extension.getView().showYesNoCancelDialog(Constant.messages.getString("file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { isAppend = false; } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(file, isAppend)); for (HistoryReference href : hrefs) { HttpMessage msg = null; msg = href.getHttpMessage(); exportHistory(msg, bos); } } catch (Exception e1) { extension.getView().showWarningDialog(Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); log.warn(e1.getMessage(), e1); } finally { <START> try { <END> if (bos != null) { bos.close(); } } catch (Exception e2) { log.warn(e2.getMessage(), e2); } } } }); }</code><technical_language>try-with-resource statement instead</technical_language>

Target:
public PopupMenuExportResponse() { super(Constant.messages.getString("history.export.response.popup")); this.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { List<HistoryReference> hrefs = extension.getSelectedHistoryReferences(); if (hrefs.size() == 0) { extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.select.warning")); return; } File file = getOutputFile(); if (file == null) { return; } boolean isAppend = true; if (file.exists()) { int rc = extension.getView().showYesNoCancelDialog(Constant.messages.getString("file.overwrite.warning")); if (rc == JOptionPane.CANCEL_OPTION) { return; } else if (rc == JOptionPane.YES_OPTION) { isAppend = false; } } try (BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file, isAppend));) { for (HistoryReference href : hrefs) { HttpMessage msg = null; msg = href.getHttpMessage(); exportHistory(msg, bos); } } catch (Exception e1) { extension.getView().showWarningDialog(Constant.messages.getString("file.save.error") + file.getAbsolutePath() + "."); log.warn(e1.getMessage(), e1); } } }); }
Source:
<code>private void generateTheStackTrace(Throwable exception, ITestNGMethod method, String title, StringBuilder contentBuffer) { logger.entering(new Object[] { exception, method, title, contentBuffer }); contentBuffer.append(" <div class='stContainer' >" + exception.getClass() + ":" + title <START> + "<a class='exceptionlnk' herf='#'>(+)</a>"); <END> contentBuffer.append("<div class='exception' style='display:none'>"); StackTraceElement[] s1 = exception.getStackTrace(); Throwable t2 = exception.getCause(); if ((t2 != null) && (t2.equals(exception))) { t2 = null; } for (int x = 0; x < s1.length; x++) { contentBuffer.append((x > 0 ? "<br/>at " : "") + escape(s1[x].toString())); } if (t2 != null) { generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage(), contentBuffer); } contentBuffer.append("</div></div>"); logger.exiting(); }</code><technical_language>typo</technical_language>

Target:
private void generateTheStackTrace(Throwable exception, ITestNGMethod method, String title, StringBuilder contentBuffer) { logger.entering(new Object[] { exception, method, title, contentBuffer }); contentBuffer.append(" <div class='stContainer' >" + exception.getClass() + ":" + title + "<a class='exceptionlnk' href='#'>(+)</a>"); contentBuffer.append("<div class='exception' style='display:none'>"); StackTraceElement[] s1 = exception.getStackTrace(); Throwable t2 = exception.getCause(); if ((t2 != null) && (t2.equals(exception))) { t2 = null; } for (int x = 0; x < s1.length; x++) { contentBuffer.append((x > 0 ? "<br/>at " : "") + escape(s1[x].toString())); } if (t2 != null) { generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage(), contentBuffer); } contentBuffer.append("</div></div>"); logger.exiting(); }
Source:
<code>public <D extends EntityDriver> D build(DriverDependentEntity<D> entity, Location location){ Class<D> driverInterface = entity.getDriverInterface(); Class<? extends D> driverClass; if (driverInterface.isInterface()) { String driverClassName = inferClassName(driverInterface, location); try { <START> System.out.println("Loading "+driverInterface.getName()); <END> entity.getClass().getClassLoader().loadClass(driverInterface.getName()); } catch (ClassNotFoundException e) { throw Throwables.propagate(e); } try { System.out.println("Loading "+driverClassName); driverClass = (Class<? extends D>) entity.getClass().getClassLoader().loadClass(driverClassName); } catch (ClassNotFoundException e) { throw Throwables.propagate(e); } } else { driverClass = driverInterface; } Constructor constructor = getConstructor(driverClass); try { constructor.setAccessible(true); return (D) constructor.newInstance(entity, location); } catch (InstantiationException e) { throw Throwables.propagate(e); } catch (IllegalAccessException e) { throw Throwables.propagate(e); } catch (InvocationTargetException e) { throw Throwables.propagate(e); } }</code><technical_language>log</technical_language>

Target:
public <D extends EntityDriver> D build(DriverDependentEntity<D> entity, Location location){ Class<D> driverInterface = entity.getDriverInterface(); Class<? extends D> driverClass; if (driverInterface.isInterface()) { String driverClassName = inferClassName(driverInterface, location); try { driverClass = (Class<? extends D>) entity.getClass().getClassLoader().loadClass(driverClassName); } catch (ClassNotFoundException e) { throw Throwables.propagate(e); } } else { driverClass = driverInterface; } Constructor<? extends D> constructor = getConstructor(driverClass); try { constructor.setAccessible(true); return constructor.newInstance(entity, location); } catch (InstantiationException e) { throw Throwables.propagate(e); } catch (IllegalAccessException e) { throw Throwables.propagate(e); } catch (InvocationTargetException e) { throw Throwables.propagate(e); } }
Source:
<code>public void testGetAllDatabases() throws Exception { final String[] dbsToCreate = {"db_1", "db_2", "db_3"}; final WebTarget dbTarget = target().path("metastore").path("databases"); for (String name : dbsToCreate) { dbTarget.queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.xml(name)); } StringList allDbs = target().path("metastore").path("databases") .queryParam("sessionid", lensSessionId).request(mediaType) .get(StringList.class); System.out.println("ALL DBs:" + allDbs.getElements()); assertEquals(allDbs.getElements().size(), 6); List<String> expected = new ArrayList<String>(Arrays.asList(dbsToCreate)); <START> expected.add("default");expected.add("lensstats");expected.add("test_set_db"); <END> assertEquals(allDbs.getElements(), expected); for (String name : dbsToCreate) { dbTarget.path(name).queryParam("cascade", "true").queryParam("sessionid", lensSessionId).request().delete(); } }</code><technical_language>is this change required</technical_language>

Target:
public void testGetAllDatabases() throws Exception { final String[] dbsToCreate = {"db_1", "db_2", "db_3"}; final WebTarget dbTarget = target().path("metastore").path("databases"); for (String name : dbsToCreate) { dbTarget.queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.xml(name)); } StringList allDbs = target().path("metastore").path("databases") .queryParam("sessionid", lensSessionId).request(mediaType) .get(StringList.class); System.out.println("ALL DBs:" + allDbs.getElements()); assertEquals(allDbs.getElements().size(), 4); List<String> expected = new ArrayList<String>(Arrays.asList(dbsToCreate)); expected.add("default"); assertEquals(allDbs.getElements(), expected); for (String name : dbsToCreate) { dbTarget.path(name).queryParam("cascade", "true").queryParam("sessionid", lensSessionId).request().delete(); } }
Source:
<code>private BulkWriteResult executeAndLogBulkErrors(BulkWriteOperation bwo) { BulkWriteResult result = null; try { if (writeConcern == null) { LOGGER.debug("Bulk updating docs"); result = bwo.execute(); } else { LOGGER.debug("Bulk deleting docs with writeConcern={} from execution", writeConcern); result = bwo.execute(writeConcern); } } catch (BulkWriteException e) { BulkWriteException bwe = e; result = bwe.getWriteResult(); LOGGER.warn("Bulk update operation contains errors", bwe); docUpdateErrors.addAll(bwe.getWriteErrors()); } catch (Exception e) { <START> throw e; <END> } return result; }</code><technical_language>log it, catch</technical_language>

Target:
private BulkWriteResult executeAndLogBulkErrors(BulkWriteOperation bwo) { BulkWriteResult result = null; try { if (writeConcern == null) { LOGGER.debug("Bulk updating docs"); result = bwo.execute(); } else { LOGGER.debug("Bulk deleting docs with writeConcern={} from execution", writeConcern); result = bwo.execute(writeConcern); } } catch (BulkWriteException e) { BulkWriteException bwe = e; result = bwe.getWriteResult(); LOGGER.warn("Bulk update operation contains errors", bwe); docUpdateErrors.addAll(bwe.getWriteErrors()); } return result; }
Source:
<code>public void after() { for (IBean<?> bean : m_replacedBeans) { <START> BeanTestingHelper.get().unregisterBean(bean); <END> } m_replacedBeans.clear(); }</code><technical_language>unregisterBeans(m_replacedBeans)</technical_language>

Target:
public void after() { BeanTestingHelper.get().unregisterBeans(m_replacedBeans); m_replacedBeans.clear(); }
Source:
<code>public void testCheckTaskStatus() throws ProductInstallatorException, OpenStackException { TaskService taskService = mock (TaskService.class); com.telefonica.euro_iaas.sdc.model.Task task = new Task (); task.setStatus(TaskStates.SUCCESS); when(taskService.load(anyString(),anyString(), anyString())).thenReturn(task); when(openStackRegion.getDefaultRegion(anyString())).thenReturn("region"); when(openStackRegion.getSdcEndPoint(anyString(), anyString())).thenReturn("http"); when(sDCClient.getTaskService(anyString(),anyString())).thenReturn(taskService); sdcUtilImpl.checkTaskStatus(task, "token", "vdc"); <START> <END> }</code><technical_language>verify asserts</technical_language>

Target:
public void testCheckTaskStatus() throws ProductInstallatorException, OpenStackException { TaskService taskService = mock (TaskService.class); com.telefonica.euro_iaas.sdc.model.Task task = new Task (); task.setStatus(TaskStates.SUCCESS); when(taskService.load(anyString(),anyString(), anyString())).thenReturn(task); when(openStackRegion.getDefaultRegion(anyString())).thenReturn("region"); when(openStackRegion.getSdcEndPoint(anyString(), anyString())).thenReturn("http"); when(sDCClient.getTaskService(anyString(),anyString())).thenReturn(taskService); sdcUtilImpl.checkTaskStatus(task, "token", "vdc"); verify (sDCClient).getTaskService(anyString(),anyString()); }
Source:
<code>protected boolean containsExpectedPageContents() { if (isElementPresent(By.className("modal-content"))) { waitForConfirmationModalAndClickOk(); } <START> reloadPageIfStuckLoading(); <END> return getPageTitle().contains("Submit Feedback"); }</code><technical_language>I this is right place put reload. admittedly drawing a blank for put it</technical_language>

Target:
protected boolean containsExpectedPageContents() { if (isElementPresent(By.className("modal-content"))) { waitForConfirmationModalAndClickOk(); } return getPageTitle().contains("Submit Feedback"); }
Source:
<code>private List<SubscriptionAssignment> readExistingAssignments() { <START> return subscriptionsCache.listActiveSubscriptionNames().stream().flatMap(subscriptionName -> { <END> String path = pathSerializer.serialize(subscriptionName); List<String> children = new ArrayList<>(); try { children.addAll(curator.getChildren().forPath(path)); } catch (Exception e) { } return children.stream().map(node -> new SubscriptionAssignment(node, subscriptionName)); }).collect(Collectors.toList()); }</code><technical_language>i simple for-each more readable this stream magic wit this long functions</technical_language>

Target:
private List<SubscriptionAssignment> readExistingAssignments() { List<SubscriptionAssignment> existingAssignments = new ArrayList<>(); for (SubscriptionName subscriptionName : subscriptionsCache.listActiveSubscriptionNames()) { try { String path = pathSerializer.serialize(subscriptionName); List<String> nodes = curator.getChildren().forPath(path); for (String node : nodes) { String fullPath = path + "/" + node; existingAssignments.add(pathSerializer.deserialize(fullPath, curator.getData().forPath(fullPath))); } } catch (Exception e) { logger.info("Exception occurred when initializing cache with subscription {}", subscriptionName, e); } } return existingAssignments; }
Source:
<code>public ZAddArgs gt() { <START> this.gt = true; <END> return this; }</code><technical_language>ideally, set lt false a state lt gt set true if calls lt().gt()</technical_language>

Target:
public ZAddArgs gt() { this.gt = true; this.lt = false; return this; }
Source:
<code>private VmNetworkInterface getIfaceWithNetworkName(List<VmNetworkInterface> interfaces) { <START> if (getNetworkName() == null) { <END> return null; } else { return LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface vmNetworkInterface) { return getNetworkName().equals(vmNetworkInterface.getName()); } }); } }</code><technical_language>I agree Moti. Changing order is enough. (getNetworkName().equals(vmNetworkInterface.getName()) instead of vmNetworkInterface.getName().equals(getNetworkName()) ). is need check cluster network is null, null</technical_language>

Target:
private VmNetworkInterface getIfaceWithNetworkName(List<VmNetworkInterface> interfaces) { return LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface vmNetworkInterface) { return getNetworkName().equals(vmNetworkInterface.getName()); } }); }
Source:
<code>public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; <START> for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) <END> if (nameSpecifier instanceof IASTName) result[idx++] = (IASTName) nameSpecifier; else throw new UnsupportedOperationException("Can't use getNames() on a " + "qualified name that includes a decltype-specifier. Use " + "getQualifier() and getLastName() instead"); if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }</code><technical_language>Please curly braces in 'for' statements</technical_language>

Target:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) { if (nameSpecifier instanceof IASTName) { result[idx++] = (IASTName) nameSpecifier; } else { throw new UnsupportedOperationException("Can't use getNames() on a " + "qualified name that includes a decltype-specifier. Use " + "getQualifier() and getLastName() instead"); } } if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }
Source:
<code>public NotificationAssert hasGroup(String group) { isNotNull(); assertThat(actual.getGroup()) <START> .overridingErrorMessage("Expected group <%s> but was <%s>.", group, actual.getGroup()) <END> .isEqualTo(group); return this; }</code><technical_language>convention pulling this a local variable isNotNull named actualFoo Foo is parameter (e.g., actualGroup)</technical_language>

Target:
public NotificationAssert hasGroup(String group) { isNotNull(); String actualGroup = actual.getGroup(); assertThat(actual.getGroup()) .overridingErrorMessage("Expected group <%s> but was <%s>.", group, actualGroup) .isEqualTo(group); return this; }
Source:
<code>private InstructorFeedbackResultsPage loginToInstructorFeedbackResultsPage(String instructorName, String fsName) { AppUrl resultsUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_PAGE) .withUserId(testData.instructors.get(instructorName).googleId) .withCourseId(testData.feedbackSessions.get(fsName).getCourseId()) .withSessionName(testData.feedbackSessions.get(fsName).getFeedbackSessionName()); Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); InstructorFeedbackResultsPage resultsPage = loginAdminToPage(resultsUrl, InstructorFeedbackResultsPage.class); <START> log.info("Time taken: " + stopwatch.getTimeElapsedInSeconds()); <END> return resultsPage; }</code><technical_language>This time meaningful anymore loading ajax implemented (less a for cases). need expand panels include in time taken</technical_language>

Target:
private InstructorFeedbackResultsPage loginToInstructorFeedbackResultsPage(String instructorName, String fsName) { AppUrl resultsUrl = createUrl(Const.ActionURIs.INSTRUCTOR_FEEDBACK_RESULTS_PAGE) .withUserId(testData.instructors.get(instructorName).googleId) .withCourseId(testData.feedbackSessions.get(fsName).getCourseId()) .withSessionName(testData.feedbackSessions.get(fsName).getFeedbackSessionName()); Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); InstructorFeedbackResultsPage resultsPage = loginAdminToPage(resultsUrl, InstructorFeedbackResultsPage.class); resultsPage.expandPanels(); log.info("Time taken: " + stopwatch.getTimeElapsedInSeconds()); return resultsPage; }
Source:
<code>public String allowedPattern(Type type) { <START> return Converter.ANY_MULTI_LINE; <END> }</code><technical_language>proper regexp match port/[udp|tcp] (btw. I parentheses means optional part)</technical_language>

Target:
public String allowedPattern(Type type) { return "\\s*([0-9]+/(tcp|udp)\\s*)+"; }
Source:
<code>public void should_SetExpiration_givenKeyTo_StringValueInMilliSeconds() { String key = "key"; <START> String value = "value"; <END> long millisecondsToLive = 20000l; jedis.set(key, value); Long timeToLive = jedis.ttl(key); assertThat(timeToLive).isEqualTo(-1); jedis.pexpire(key, millisecondsToLive); timeToLive = jedis.ttl(key); assertThat(timeToLive).isLessThanOrEqualTo(20); assertThat(timeToLive).isGreaterThanOrEqualTo(15); }</code><technical_language>in this file, worth making line a capital "L" long millisecondsToLive = 20000L</technical_language>

Target:
public void should_SetExpiration_givenKeyTo_StringValueInMilliSeconds() { String key = "key"; String value = "value"; long millisecondsToLive = 20000L; jedis.set(key, value); Long timeToLive = jedis.ttl(key); assertThat(timeToLive).isEqualTo(-1); jedis.pexpire(key, millisecondsToLive); timeToLive = jedis.ttl(key); assertThat(timeToLive).isLessThanOrEqualTo(20); assertThat(timeToLive).isGreaterThanOrEqualTo(15); }
Source:
<code>public boolean quit() { if (stateManager.getAnyTaskRunning().getValue()) { Optional<ButtonType> shouldClose = dialogService.showBackgroundProgressDialogAndWait( Localization.lang("Please wait..."), Localization.lang("Waiting for background tasks to finish. Quit anyway?"), stateManager ); if (!(shouldClose.isPresent() && (shouldClose.get() == ButtonType.YES))) { return false; } } List<String> filenames = new ArrayList<>(); for (int i = 0; i < tabbedPane.getTabs().size(); i++) { BasePanel panel = getBasePanelAt(i); final BibDatabaseContext context = panel.getBibDatabaseContext(); if (panel.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { tabbedPane.getSelectionModel().select(i); if (!confirmClose(panel)) { return false; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); } <START> SaveDatabaseAction.shutDown(context); <END> BackupManager.shutdown(context); context.getDatabasePath().map(Path::toAbsolutePath).map(Path::toString).ifPresent(filenames::add); } WaitForSaveFinishedDialog waitForSaveFinishedDialog = new WaitForSaveFinishedDialog(dialogService); waitForSaveFinishedDialog.showAndWait(getBasePanelList()); tearDownJabRef(filenames); Platform.exit(); return true; }</code><technical_language>shutdown</technical_language>

Target:
public boolean quit() { if (stateManager.getAnyTaskRunning().getValue()) { Optional<ButtonType> shouldClose = dialogService.showBackgroundProgressDialogAndWait( Localization.lang("Please wait..."), Localization.lang("Waiting for background tasks to finish. Quit anyway?"), stateManager ); if (!(shouldClose.isPresent() && (shouldClose.get() == ButtonType.YES))) { return false; } } List<String> filenames = new ArrayList<>(); for (int i = 0; i < tabbedPane.getTabs().size(); i++) { LibraryTab libraryTab = getLibraryTabAt(i); final BibDatabaseContext context = libraryTab.getBibDatabaseContext(); if (libraryTab.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { tabbedPane.getSelectionModel().select(i); if (!confirmClose(libraryTab)) { return false; } } else if (context.getLocation() == DatabaseLocation.SHARED) { context.convertToLocalDatabase(); context.getDBMSSynchronizer().closeSharedDatabase(); context.clearDBMSSynchronizer(); } AutosaveManager.shutdown(context); BackupManager.shutdown(context); context.getDatabasePath().map(Path::toAbsolutePath).map(Path::toString).ifPresent(filenames::add); } WaitForSaveFinishedDialog waitForSaveFinishedDialog = new WaitForSaveFinishedDialog(dialogService); waitForSaveFinishedDialog.showAndWait(getLibraryTabs()); tearDownJabRef(filenames); Platform.exit(); return true; }
Source:
<code>private void waitForPackagesRefreshed() { int count = 0; synchronized (lock) { while (!moduleRefreshed && count < MAX_WAIT_COUNT) { try { lock.wait(WAIT_TIME); } catch (InterruptedException e) { LOGGER.error("Interrupted while waiting", e); } ++count; } <START> if(count >= MAX_WAIT_COUNT) { <END> LOGGER.error("Package has not been refreshed, reached time limit"); } } }</code><technical_language>space if</technical_language>

Target:
private void waitForPackagesRefreshed() { int count = 0; synchronized (lock) { while (!moduleRefreshed && count < MAX_WAIT_COUNT) { try { lock.wait(WAIT_TIME); } catch (InterruptedException e) { LOGGER.error("Interrupted while waiting", e); } ++count; } if (count >= MAX_WAIT_COUNT) { LOGGER.error("Packages have not been refreshed, reached time limit"); } } }
Source:
<code>final Listener wrap(Listener delegate) { <START> return new Listener() { <END> @Override public void onSuccess() { requestsSucceeded.increment(); delegate.onSuccess(); } @Override public void onIgnore() { requestsIgnored.increment(); delegate.onIgnore(); } @Override public void onDropped() { requestsDropped.increment(); delegate.onDropped(); } }; }</code><technical_language>want override toString</technical_language>

Target:
final Listener wrap(Listener delegate) { return new Listener() { @Override public void onSuccess() { requestsSucceeded.increment(); delegate.onSuccess(); } @Override public void onIgnore() { requestsIgnored.increment(); delegate.onIgnore(); } @Override public void onDropped() { requestsDropped.increment(); delegate.onDropped(); } @Override public String toString() { return "LimiterMetrics{" + delegate + "}"; } }; }
Source:
<code>protected int run() throws Exception { boolean errorOccurred = false; try { Jenkins.getActiveInstance().doReload(); } catch (AccessDeniedException e) { stderr.println(e.getMessage()); errorOccurred = true; } catch (Exception e) { <START> final String errorMsg = String.format("Unexpected exception occurred during performing clear-queue command: %s", <END> e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; } return errorOccurred ? 1 : 0; }</code><technical_language>clear-queue instead of reload-configuration I guess copy-paste bitten #1942 ;-). AbstractCLICommand + strategy pattern introduced try factorize common code</technical_language>

Target:
protected int run() throws Exception { Jenkins.getActiveInstance().doReload(); return 0; }
Source:
<code><START> public void setGuestOsNamedVersion() { <END> if (guestOsType == OsType.Linux) { String optional = ""; if (!StringUtils.isEmpty(guestOsCodename)) { optional = messages.guestOSVersionOptional(guestOsCodename); } guestOsNamedVersion = messages.guestOSVersionLinux(guestOsDistribution, guestOsVersion, optional); } else if (guestOsType == OsType.Windows && guestOs.startsWith("Win ")) { if (guestOs.startsWith("Win 20")) { guestOsNamedVersion = messages.guestOSVersionWindowsServer(guestOs.substring(4), guestOsVersion); } else { guestOsNamedVersion = messages.guestOSVersionWindows(guestOs.substring(4), guestOsVersion); } } }</code><technical_language>this private, IMHO supposed</technical_language>

Target:
private void setGuestOsNamedVersion() { if (guestOsType == OsType.Linux) { String optional = ""; if (!StringUtils.isEmpty(guestOsCodename)) { optional = messages.guestOSVersionOptional(guestOsCodename); } guestOsNamedVersion = messages.guestOSVersionLinux(guestOsDistribution, guestOsVersion, optional); } else if (guestOsType == OsType.Windows && guestOs.startsWith("Win ")) { if (guestOs.startsWith("Win 20")) { guestOsNamedVersion = messages.guestOSVersionWindowsServer(guestOs.substring(4), guestOsVersion); } else { guestOsNamedVersion = messages.guestOSVersionWindows(guestOs.substring(4), guestOsVersion); } } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> Timber.i("onCreate"); <END> setContentView(R.layout.activity_arrow); if (!mPreferences.getBoolean(Const.SETTINGS_SIGNED_IN, false)) finish(); arrowPreferences = getSharedPreferences("arrow", MODE_PRIVATE); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { showNoNfc(); mArrowHandler = new BaseArrowHandler(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mArrowHandler = new NfcArrowHandler(); } else { mArrowHandler = new BaseArrowHandler(); } } scanImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(ArrowActivity.this); integrator.initiateScan(); } }); switchToReceive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewFlipper.setDisplayedChild(0); } }); }</code><technical_language>This removed, esp. info level is a bit much. wanted debug a lifecycle bug remove line afterwards</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_arrow); if (!mPreferences.getBoolean(Const.SETTINGS_SIGNED_IN, false)) finish(); arrowPreferences = getSharedPreferences("arrow", MODE_PRIVATE); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { showNoNfc(); mArrowHandler = new BaseArrowHandler(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mArrowHandler = new NfcArrowHandler(); } else { mArrowHandler = new BaseArrowHandler(); } } scanImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(ArrowActivity.this); integrator.initiateScan(); } }); switchToReceive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewFlipper.setDisplayedChild(0); } }); }
Source:
<code>public Credential validate(final Credential credential, final RequestData data) throws WSSecurityException { if (credential == null || credential.getSamlAssertion() == null) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noCredential"); } final SamlAssertionWrapper assertion = credential.getSamlAssertion(); String confirmMethod = null; final List<String> methods = assertion.getConfirmationMethods(); <START> if (!methods.isEmpty()) { <END> confirmMethod = methods.get(0); } checkAssertion(assertion, confirmMethod); checkConditions(assertion); validateAssertion(assertion); checkSignedAssertion(assertion, data); return credential; }</code><technical_language>if List option "isNotEmpty", consider for easy read</technical_language>

Target:
public Credential validate(final Credential credential, final RequestData data) throws WSSecurityException { if (credential == null || credential.getSamlAssertion() == null) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noCredential"); } final SamlAssertionWrapper assertion = credential.getSamlAssertion(); String confirmMethod = null; final List<String> methods = assertion.getConfirmationMethods(); if (CollectionUtils.isNotEmpty(methods)) { confirmMethod = methods.get(0); } checkAssertion(assertion, confirmMethod); checkConditions(assertion); validateAssertion(assertion); checkSignedAssertion(assertion, data); return credential; }
Source:
<code>@Test public void pressKeyCodeTest() throws Exception { <START> final AndroidDriver driver = getAndroidDriver(".fingerprint.FingerprintSettings"); <END> TimeUnit.SECONDS.sleep(2); driver.findElement(By.id("com.android.settings:id/password_entry")).sendKeys("1234\n"); TimeUnit.SECONDS.sleep(2); driver.findElement(By.xpath(" .click(); TimeUnit.SECONDS.sleep(2); driver.fingerPrint(2); driver.findElement(By.id("com.android.settings:id/next_button")).click(); TimeUnit.SECONDS.sleep(2); driver.quit(); }</code><technical_language>@Test(expected = MyException.class) syntax for case</technical_language>

Target:
@Test public void pressKeyCodeTest() throws InterruptedException { final AndroidDriver driver = getAndroidDriver(".fingerprint.FingerprintSettings"); TimeUnit.SECONDS.sleep(2); enterPasswordAndContinue(driver); driver.findElementByXPath(FIRST_IN_LIST_XPATH).click(); TimeUnit.SECONDS.sleep(2); driver.fingerPrint(2); TimeUnit.SECONDS.sleep(2); try { clickNext(driver); } catch (Exception e) { Assert.fail("fingerprint command fail to execute"); } finally { driver.quit(); } }
Source:
<code>DelegatingTimeoutSaslServer(final SaslServer delegate, final ScheduledExecutorService scheduledExecutorService, final long timeout) { super(delegate); timeoutTask = scheduledExecutorService.schedule(() -> { <START> if (! (isComplete() && complete.compareAndSet(false, true))) { <END> dispose(); } return null; }, timeout, TimeUnit.SECONDS); }</code><technical_language>I executor service fire time, a concurrency guard of some sort. "complete" flag suffice checked late in evaluateResponse. simplest solution is synchronized protect access delegate SaslServer "complete" flag "timeoutTask" field, means atomic boolean volatile field simplified plain fields</technical_language>

Target:
DelegatingTimeoutSaslServer(final SaslServer delegate, final ScheduledExecutorService scheduledExecutorService, final long timeout) { super(delegate); timeoutTask = scheduledExecutorService.schedule(() -> { synchronized (this) { if (! (isComplete() && ! complete)) { dispose(); terminated = true; } else { complete = true; } return null; } }, timeout, TimeUnit.SECONDS); }
Source:
<code>public void testRequestSuccessForImage() throws Throwable { <START> enqueueFromFile("gallery_item_image.json"); Callback cb = mock(Callback.class); Call<MwQueryResponse> call = request(cb, false); server().takeRequest(); ArgumentCaptor<HashMap> captor = ArgumentCaptor.forClass(HashMap.class); verify(cb).success(eq(call), captor.capture()); Map<PageTitle, GalleryItem> result = captor.getValue(); Assert.assertTrue(result.size() > 0); GalleryItem galleryItem = (GalleryItem) result.values().toArray()[0]; Assert.assertTrue(galleryItem != null); Assert.assertThat(String.valueOf(galleryItem.getHeight()), is("1489")); Assert.assertThat(String.valueOf(galleryItem.getWidth()), is("2125")); Assert.assertThat(galleryItem.getThumbUrl(), is("<LINK_0>")); Assert.assertThat(galleryItem.getMimeType(), is("image/jpeg")); Assert.assertThat(galleryItem.getUrl(), is("<LINK_1>")); <END> }</code><technical_language>please remove some of spaces code lines here? generally code pretty compact</technical_language>

Target:
public void testRequestSuccessForImage() throws Throwable { enqueueFromFile("gallery_item_image.json"); Callback cb = mock(Callback.class); Call<MwQueryResponse> call = request(cb, false); server().takeRequest(); ArgumentCaptor<GalleryItem> captor = ArgumentCaptor.forClass(GalleryItem.class); verify(cb).success(eq(call), captor.capture()); GalleryItem galleryItem = captor.getValue(); Assert.assertTrue(galleryItem != null); Assert.assertThat(String.valueOf(galleryItem.getHeight()), is("1489")); Assert.assertThat(String.valueOf(galleryItem.getWidth()), is("2125")); Assert.assertThat(galleryItem.getThumbUrl(), is("<LINK_0>")); Assert.assertThat(galleryItem.getMimeType(), is("image/jpeg")); Assert.assertThat(galleryItem.getUrl(), is("<LINK_1>")); }
Source:
<code>protected abstract <K> Object handleWriteManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<K> keys, boolean forwarded) throws Throwable; <START> protected final Throwable cleanLocksAndRethrow(InvocationContext ctx, Throwable te) { <END> lockManager.unlockAll(ctx); return te; }</code><technical_language>related PR, this method is anymore. removed</technical_language>

Target:
protected abstract <K> Object handleWriteManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<K> keys, boolean forwarded) throws Throwable; protected final long getLockTimeoutMillis(FlagAffectedCommand command) { return command.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT) ? 0 : cacheConfiguration.locking().lockAcquisitionTimeout(); }
Source:
<code>public void read(Row row, int ordinal) throws StandardException { if (row.isNullAt(ordinal)) setToNull(); else { isNull = false; byte[] bytes = (byte[]) row.get(ordinal); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); value = in.readObject(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } <START> } <END> } }</code><technical_language>another spot a try-with-resources block simplify a bit. java else { isNull = false; byte[] bytes = (byte[]) row.get(ordinal); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); try (ObjectInput in = new ObjectInputStream(bis)) { = in.readObject(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } Again, throwing RuntimeException instead of StandardException</technical_language>

Target:
public void read(Row row, int ordinal) throws StandardException { if (row.isNullAt(ordinal)) setToNull(); else { isNull = false; Object object = row.get(ordinal); if (object instanceof byte[]) { value = SerializationUtils.deserialize((byte[]) object); } else { value = object; } } }
Source:
<code>protected void verifyResults(Map <String,Integer> result, Map <String,Integer> verifyAgainst) { <START> assert result.size() > 0 : "Results should have at least 1 answer"; <END> for (Entry<String, Integer> e : result.entrySet()) { String key = e.getKey(); Integer count = verifyAgainst.get(key); assert count.equals(e.getValue()): "key " + e.getKey() + " does not have count " + count + " but " + e.getValue(); } }</code><technical_language>Please AssertJUnit methods (in this case assertTrue)</technical_language>

Target:
protected void verifyResults(Map <String,Integer> result, Map <String,Integer> verifyAgainst) { assertTrue("Results should have at least 1 answer", result.size() > 0); for (Entry<String, Integer> e : result.entrySet()) { String key = e.getKey(); Integer count = verifyAgainst.get(key); assertTrue("key " + e.getKey() + " does not have count " + count + " but " + e.getValue(), count.equals(e.getValue())); } }
Source:
<code>private static void validateStreamModifierClauses(String statement, Map<String, String> expectedGroupValues) { Matcher matcher = SQLParser.matchAnyCreateStreamStatementClause(statement); Set<String> matched = new HashSet<>(); int start = 0; while (matcher.find(start)) { start = matcher.end(); <START> for (Map.Entry<String, String> e : expectedGroupValues.entrySet()) { <END> String key = e.getKey(); String parsedValue = matcher.group(key); if (parsedValue == null) { continue; } assertFalse(matched.contains(key)); matched.add(key); assertEquals(expectedGroupValues.get(key), parsedValue); } } assertEquals(matched.size(), expectedGroupValues.keySet().size()); }</code><technical_language>This is checking expected values values parsed there. worth adding a check expected values matcher</technical_language>

Target:
private static void validateStreamModifierClauses(String statement, Map<String, String> expectedGroupValues) { Matcher matcher = SQLParser.matchAnyCreateStreamStatementClause(statement); Set<String> matched = new HashSet<>(); int start = 0; while (matcher.find(start)) { start = matcher.end(); for (String group : s_allStreamModifierGroups) { String parsedValue = matcher.group(group); if (parsedValue == null) { continue; } assertTrue(expectedGroupValues.keySet().contains(group)); assertFalse(matched.contains(group)); matched.add(group); assertEquals(expectedGroupValues.get(group), parsedValue); } } assertEquals(matched.size(), expectedGroupValues.keySet().size()); }
Source:
<code>public Optional<AccessToken> authenticate(String submittedToken) throws AuthenticationException { <START> Optional<AccessToken> token; <END> try { token = tokenStore.getAccessTokenByToken(submittedToken, DateTime.now()); if(!token.isPresent()) { LOGGER.warn("warning=token_not_present token={}", submittedToken); } return token; } catch (MissingRequiredScopeException e) { throw new MissingRequiredScopeAuthenticationException(e); } }</code><technical_language>nit: this final move try</technical_language>

Target:
public Optional<AccessToken> authenticate(String submittedToken) throws AuthenticationException { try { final Optional<AccessToken> token = tokenStore.getAccessTokenByToken(submittedToken, DateTime.now()); if(!token.isPresent()) { LOGGER.warn("warning=token_not_present token={}", submittedToken); } return token; } catch (MissingRequiredScopeException e) { throw new MissingRequiredScopeAuthenticationException(e); } }
Source:
<code>public void safeRun() { while (true) { Versioned<LedgerMetadata> currentMetadata = getVersionedLedgerMetadata(); Version.Occurred occurred = currentMetadata.getVersion().compare(newMetadata.getVersion()); if (Version.Occurred.BEFORE == occurred) { <START> LOG.info("Updated ledger metadata for ledger to {}.", <END> ledgerId, newMetadata.getValue().toSafeString()); synchronized (ReadOnlyLedgerHandle.this) { if (setLedgerMetadata(currentMetadata, newMetadata)) { break; } } } else { break; } } }</code><technical_language>Please add version in logging removed toSafeString</technical_language>

Target:
public void safeRun() { while (true) { Versioned<LedgerMetadata> currentMetadata = getVersionedLedgerMetadata(); Version.Occurred occurred = currentMetadata.getVersion().compare(newMetadata.getVersion()); if (Version.Occurred.BEFORE == occurred) { synchronized (ReadOnlyLedgerHandle.this) { if (setLedgerMetadata(currentMetadata, newMetadata)) { LOG.info("Updated ledger metadata for ledger to {}, version {}.", ledgerId, newMetadata.getValue().toSafeString(), newMetadata.getVersion()); break; } } } else { break; } } }
Source:
<code>public DateTime increment(DateTime time) { <START> return new DateTime(Long.MAX_VALUE / 2); <END> }</code><technical_language>JodaUtils.MAX_INSTANT instead</technical_language>

Target:
public DateTime increment(DateTime time) { return maxDateTime; }
Source:
<code>protected void setup(Binder binder) { httpServerBinder(binder).bindResource("/ui", "router_ui").withWelcomeFile("index.html"); configBinder(binder).bindConfig(RouterConfig.class); binder.bind(ClusterManager.class).in(Scopes.SINGLETON); binder.bind(RemoteInfoFactory.class).in(Scopes.SINGLETON); httpClientBinder(binder).bindHttpClient("query-tracker", ForQueryInfoTracker.class) .withConfigDefaults(config -> { <START> config.setIdleTimeout(new Duration(30, SECONDS)); config.setRequestTimeout(new Duration(10, SECONDS)); <END> }); httpClientBinder(binder).bindHttpClient("query-tracker", ForClusterInfoTracker.class) .withConfigDefaults(config -> { config.setIdleTimeout(new Duration(30, SECONDS)); config.setRequestTimeout(new Duration(10, SECONDS)); }); binder.bind(ClusterStatusTracker.class).in(Scopes.SINGLETON); jaxrsBinder(binder).bind(RouterResource.class); jaxrsBinder(binder).bind(ClusterStatusResource.class); }</code><technical_language>move values (30 10) router config configurable more flexible</technical_language>

Target:
protected void setup(Binder binder) { httpServerBinder(binder).bindResource("/ui", "router_ui").withWelcomeFile("index.html"); configBinder(binder).bindConfig(RouterConfig.class); binder.bind(ClusterManager.class).in(Scopes.SINGLETON); binder.bind(RemoteInfoFactory.class).in(Scopes.SINGLETON); bindHttpClient(binder, QUERY_TRACKER, ForQueryInfoTracker.class); bindHttpClient(binder, QUERY_TRACKER, ForClusterInfoTracker.class); binder.bind(ClusterStatusTracker.class).in(Scopes.SINGLETON); jaxrsBinder(binder).bind(RouterResource.class); jaxrsBinder(binder).bind(ClusterStatusResource.class); }
Source:
<code>private CassandraNodeInfo buildInfo(JmxConnect jmx) throws UnknownHostException { Nodetool nodetool = new Nodetool(jmx); String endpoint = nodetool.getEndpoint(); return CassandraNodeInfo.newBuilder() .setOperationMode(nodetool.getOperationMode()) .setJoined(nodetool.isJoined()) .setGoosipInitialized(nodetool.isGossipInitialized()) .setGossipRunning(nodetool.isGossipRunning()) .setNativeTransportRunning(nodetool.isNativeTransportRunning()) .setRpcServerRunning(nodetool.isRPCServerRunning()) <START> .setUptimeSeconds(nodetool.getUptimeInMillis() / 1000L) <END> .setVersion(nodetool.getVersion()) .setHostId(nodetool.getHostID()) .setEndpoint(endpoint) .setTokenCount(nodetool.getTokenCount()) .setDataCenter(nodetool.getDataCenter(endpoint)) .setRack(nodetool.getRack(endpoint)) .setClusterName(nodetool.getClusterName()) .build(); }</code><technical_language>motivation convert seconds instead of staying in millis</technical_language>

Target:
private CassandraNodeInfo buildInfo(JmxConnect jmx) throws UnknownHostException { Nodetool nodetool = new Nodetool(jmx); String endpoint = nodetool.getEndpoint(); return CassandraNodeInfo.newBuilder() .setOperationMode(nodetool.getOperationMode()) .setJoined(nodetool.isJoined()) .setGossipInitialized(nodetool.isGossipInitialized()) .setGossipRunning(nodetool.isGossipRunning()) .setNativeTransportRunning(nodetool.isNativeTransportRunning()) .setRpcServerRunning(nodetool.isRPCServerRunning()) .setUptimeMillis(nodetool.getUptimeInMillis()) .setVersion(nodetool.getVersion()) .setHostId(nodetool.getHostID()) .setEndpoint(endpoint) .setTokenCount(nodetool.getTokenCount()) .setDataCenter(nodetool.getDataCenter(endpoint)) .setRack(nodetool.getRack(endpoint)) .setClusterName(nodetool.getClusterName()) .build(); }
Source:
<code>public boolean removeAll(Collection<?> c) { try { boolean removed = false; for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null) { <START> fireOnChangeListeners(); <END> } } }</code><technical_language>I do a reason for invoking listeners if removed</technical_language>

Target:
public boolean removeAll(Collection<?> c) { boolean removed = false; try { for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null && removed) { fireOnChangeListeners(); } } }
Source:
<code>public CorfuServerNode(@Nonnull ServerContext serverContext, @Nonnull ImmutableMap<Class, AbstractServer> serverMap) { this.serverContext = serverContext; this.serverMap = serverMap; <START> router = new NettyServerRouter(serverMap, serverContext.getServerEpoch()); <END> this.serverContext.setServerRouter(router); this.close = new AtomicBoolean(false); }</code><technical_language>serverContext.getServerEpoch() return 0 if initialized. invalid -1</technical_language>

Target:
public CorfuServerNode(@Nonnull ServerContext serverContext, @Nonnull ImmutableMap<Class, AbstractServer> serverMap) { this.serverContext = serverContext; this.serverMap = serverMap; router = new NettyServerRouter(serverMap.values().asList(), serverContext); this.serverContext.setServerRouter(router); if(serverContext.isSingleNodeSetup() && serverContext.getCurrentLayout() != null){ serverContext.setServerEpoch(serverContext.getCurrentLayout().getEpoch(), router); } this.close = new AtomicBoolean(false); }
Source:
<code>private void processTimeoutForCallRedirection(String serviceType) { mHandler.postDelayed(new Runnable("CRP.pTFC", <START> mTelecomLock) { <END> @Override public void loggedRun() { boolean isCurrentRedirectionPending = serviceType == SERVICE_TYPE_CARRIER ? mIsUserDefinedRedirectionPending : mIsCarrierRedirectionPending; if (isCurrentRedirectionPending) { Log.i(CallRedirectionProcessor.this, serviceType + "call redirection has timed out."); Log.addEvent(mCall, serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? LogUtils.Events.REDIRECTION_TIMED_OUT_USER : LogUtils.Events.REDIRECTION_TIMED_OUT_CARRIER); onCallRedirectionComplete(mCall); } } }.prepare(), mTimeoutsAdapter.getCallRedirectionTimeoutMillis( mContext.getContentResolver(), serviceType)); }</code><technical_language>need this -- calling Telecom in this runnable; another runnable posted in onCallRedirectionComplete</technical_language>

Target:
private void processTimeoutForCallRedirection(String serviceType) { mHandler.postDelayed(new Runnable("CRP.pTFC", mTelecomLock) { @Override public void loggedRun() { boolean isCurrentRedirectionPending = serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? mIsUserDefinedRedirectionPending : mIsCarrierRedirectionPending; if (isCurrentRedirectionPending) { Log.i(CallRedirectionProcessor.this, serviceType + "call redirection has timed out."); Log.addEvent(mCall, serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? LogUtils.Events.REDIRECTION_TIMED_OUT_USER : LogUtils.Events.REDIRECTION_TIMED_OUT_CARRIER); onCallRedirectionComplete(mCall); } } }.prepare(), mTimeoutsAdapter.getCallRedirectionTimeoutMillis( mContext.getContentResolver(), serviceType)); }