auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void MessageWall_008_blockedUserPostsOnHisWall() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialBlockListPageObject blockListPage = base.openSpecialBlockListPage(wikiURL); boolean ifUserBlocked = blockListPage.ifUserIsBlocked(credentials.userNameBlockedAccount); if (!ifUserBlocked) { base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialBlockPageObject blockPage = base.openSpecialBlockPage(wikiURL); blockPage.typeInUserName(credentials.userNameBlockedAccount); blockPage.typeExpiration("10 year"); blockPage.typeReason("block QATestsBlockedUser"); blockPage.clickBlockButton(); } base.logInCookie(credentials.userNameBlockedAccount, credentials.passwordBlockedAccount, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userNameBlockedAccount, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.messageWallMessagePrefix + wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix+ wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); <START> wall.verifyMessageText(title, message, credentials.userName); <END> MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.messageWallQuotePrefix + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply);; wall.submitQuote(); wall.verifyQuote(reply); }</code><technical_language>Check for credentials.userNameBlockedAccount instead of credentials.userName</technical_language>

Target:
public void MessageWall_008_blockedUserPostsOnHisWall() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialBlockListPageObject blockListPage = base.openSpecialBlockListPage(wikiURL); boolean isUserBlocked = blockListPage.isUserBlocked(credentials.userNameBlockedAccount); if (!isUserBlocked) { base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialBlockPageObject blockPage = base.openSpecialBlockPage(wikiURL); blockPage.typeInUserName(credentials.userNameBlockedAccount); blockPage.typeExpiration("10 year"); blockPage.typeReason("block QATestsBlockedUser"); blockPage.clickBlockButton(); } base.logInCookie(credentials.userNameBlockedAccount, credentials.passwordBlockedAccount, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userNameBlockedAccount, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.messageWallMessagePrefix + wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix+ wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userNameBlockedAccount); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.messageWallQuotePrefix + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply); wall.submitQuote(); wall.verifyQuote(reply); }
Source:
<code>public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { <START> try { <END> return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } } }</code><technical_language>unnecessary nested try block</technical_language>

Target:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } }
Source:
<code>private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); List<Page> outputPages = new ArrayList<>(); boolean unblocked = false; <START> while (System.nanoTime() < endTime) { <END> if (operator.isFinished()) { break; } if (operator.isBlocked().isDone()) { unblocked = true; break; } else { Thread.sleep(10); } } assertTrue(unblocked); while (operator.isBlocked().isDone() && System.nanoTime() < endTime) { assertEquals(operator.needsInput(), false); if (operator.isFinished()) { break; } Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertEquals(operator.needsInput(), false); assertNull(operator.getOutput()); return outputPages; }</code><technical_language>simple: assertFalse(operator.isFinished()); assertOperatorIsUnblocked(operator); enough</technical_language>

Target:
private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(1); List<Page> outputPages = new ArrayList<>(); assertOperatorIsUnblocked(operator); while (operator.isBlocked().isDone() && System.nanoTime() < endTime) { assertEquals(operator.needsInput(), false); if (operator.isFinished()) { break; } Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertEquals(operator.needsInput(), false, "Operator still wants input"); assertNull(operator.getOutput(), "Not finished pulling pages"); return outputPages; }
Source:
<code>public void set(@NonNull final MainPageCard card) { setTitle(String.format(getString(R.string.view_main_page_card_title), WikipediaApp.getInstance().getAppLanguageLocalizedName(card.site().languageCode()))); setSubtitle(String.format(getString(R.string.view_main_page_card_subtitle), DateFormat.getDateInstance().format(new Date()))); setIcon(R.drawable.icon_feed_today); <START> setOnClickListener(new OnClickListener() { <END> @Override public void onClick(View view) { if (callback != null) { callback.onSelectPage(new PageTitle(MainPageNameData .valueFor(app.getAppOrSystemLanguageCode()), app.getSite())); } } }); }</code><technical_language>Feel free ignore: consider breaking out adapter portion a private subclass. public void set(@NonNull MainPageCard card) { ... setOnClickListener(new CallbackAdapter(callback)); ... } ... private static class CallbackAdapter implements OnClickListener { @Nullable private final Callback callback; CallbackAdapter(@Nullable Callback callback) { this.callback = callback; } @Override public void onClick(View view) { if (callback != null) { callback.onSelectPage(...); } } }</technical_language>

Target:
public void set(@NonNull final MainPageCard card) { setTitle(String.format(getString(R.string.view_main_page_card_title), WikipediaApp.getInstance().getAppLanguageLocalizedName(card.site().languageCode()))); setSubtitle(String.format(getString(R.string.view_main_page_card_subtitle), DateFormat.getDateInstance().format(new Date()))); setIcon(R.drawable.icon_today_48_x_48_dp); setOnClickListener(new CallbackAdapter(callback)); }
Source:
<code>public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { <START> if (event.character == SWT.ESC) <END> cancelPressed(); } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }</code><technical_language>style nit: add braces if block</technical_language>

Target:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { if (event.character == SWT.ESC) { cancelPressed(); } } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }
Source:
<code>public void start(Map<String, String> props) { logger.info("Starting"); try { apiName = props.get("apiName"); apiObj = IOTestUtil.readApi(apiName); scriptPath = IOTestUtil.getScriptPath(apiObj); apiPath = IOTestUtil.getApiPath(scriptPath); IOTestUtil.load(apiName, apiObj, scriptPath, apiPath); String forestName = props.get("forestName"); String endpointState = "{\"next\":"+1+"}"; String workUnit = "{\"limit\":"+100+"}"+"{\"forestName\":"+forestName+"}"; bulkCaller = OutputEndpoint.on(IOTestUtil.db, new JacksonHandle(apiObj)).bulkCaller(); <START> bulkCaller.setEndpointState(new ByteArrayInputStream(endpointState.getBytes())); <END> bulkCaller.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes())); sourceOffset = 0; } catch (Exception ex) { ex.printStackTrace(); } }</code><technical_language>simpler alternative StringHandle need get bytes strings</technical_language>

Target:
public void start(Map<String, String> props) { logger.info("*******************Starting******************"); try { apiName = props.get("apiName"); apiObj = IOTestUtil.readApi(apiName); scriptPath = IOTestUtil.getScriptPath(apiObj); apiPath = IOTestUtil.getApiPath(scriptPath); IOTestUtil.load(apiName, apiObj, scriptPath, apiPath); String forestName = props.get("forestName"); String endpointState = "{\"next\":"+1+"}"; String workUnit = "{\"limit\":"+100+"}"+"{\"forestName\":"+forestName+"}"; bulkCaller = OutputEndpoint.on(IOTestUtil.db, new JacksonHandle(apiObj)).bulkCaller(); bulkCaller.setEndpointState(new ByteArrayInputStream(endpointState.getBytes())); bulkCaller.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes())); sourceOffset = 0; } catch (Exception ex) { ex.printStackTrace(); } }
Source:
<code><START> public static CodedValueType createCodeValueType(String code, String codeSys, String codeSysName, String dispName) { <END> CodedValueType codeValueType = new CodedValueType(); if (NullChecker.isNotNullish(code)) { codeValueType.setCode(code); } if (NullChecker.isNotNullish(codeSys)) { codeValueType.setCodeSystem(codeSys); } if (NullChecker.isNotNullish(codeSysName)) { codeValueType.setCodeSystemName(codeSysName); } if (NullChecker.isNotNullish(dispName)) { codeValueType.setDisplayName(dispName); } return codeValueType; }</code><technical_language>this method private? Is class</technical_language>

Target:
private static CodedValueType createCodeValueType(String code, String codeSys, String codeSysName, String dispName) { CodedValueType codeValueType = new CodedValueType(); if (NullChecker.isNotNullish(code)) { codeValueType.setCode(code); } if (NullChecker.isNotNullish(codeSys)) { codeValueType.setCodeSystem(codeSys); } if (NullChecker.isNotNullish(codeSysName)) { codeValueType.setCodeSystemName(codeSysName); } if (NullChecker.isNotNullish(dispName)) { codeValueType.setDisplayName(dispName); } return codeValueType; }
Source:
<code>void validateBonds(VdsNetworkInterface nicWithUnmanagedNetwork, List<Bond> newOrModifiedBonds, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap) throws ValidationException{ <START> for(Bond newOrModifiedBond:newOrModifiedBonds){ <END> VdsNetworkInterface existingInterface = existingInterfacesMap.get(newOrModifiedBond.getName()); boolean doesInterfaceExist = existingInterface != null; if (doesInterfaceExist){ Bond existingBond = (Bond) existingInterface; Collection<String> addedSlaves = computeAddedSlaves(newOrModifiedBond.getSlaves(), existingBond.getSlaves()); checkIfSlaveWithUnmanagedNetworkIsAddedToBond(nicWithUnmanagedNetwork, newOrModifiedBond, addedSlaves); checkIfSlaveIsAddedToBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond, existingBond, addedSlaves); }else{ checkNewBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond); } } }</code><technical_language>Please add spaces - " : "</technical_language>

Target:
ValidationResult validateBonds(VdsNetworkInterface nicWithUnmanagedNetwork, List<Bond> newOrModifiedBonds, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap) { for(Bond newOrModifiedBond : newOrModifiedBonds){ VdsNetworkInterface existingInterface = existingInterfacesMap.get(newOrModifiedBond.getName()); boolean doesInterfaceExist = existingInterface != null; if (doesInterfaceExist){ Bond existingBond = (Bond) existingInterface; Collection<String> addedSlaves = computeAddedSlaves(newOrModifiedBond.getSlaves(), existingBond.getSlaves()); ValidationResult result = checkIfSlaveWithUnmanagedNetworkIsAddedToBond(nicWithUnmanagedNetwork, newOrModifiedBond, addedSlaves); if (!result.isValid()) { return result; } result = checkIfSlaveIsAddedToBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond, existingBond, addedSlaves); if (!result.isValid()) { return result; } } else { ValidationResult result = checkNewBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond); if (!result.isValid()) { return result; } } } return ValidationResult.VALID; }
Source:
<code>public void start(BundleContext context) throws Exception { final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); try { <START> Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); <END> System.out.println("Starting activator " + this + " in bundle " + context.getBundle() + " ..."); ServiceReference serviceRef = context.getServiceReference(HazelcastOSGiService.class.getName()); if (serviceRef == null) { throw new IllegalStateException("There is no registered `HazelcastOSGiService`!"); } HazelcastOSGiService hazelcastOsgiService = (HazelcastOSGiService) context.getService(serviceRef); HazelcastOSGiInstance defaultInstance = hazelcastOsgiService.getDefaultHazelcastInstance(); HazelcastOSGiInstance newInstance1 = hazelcastOsgiService.newHazelcastInstance(); Config config = new Config(); config.setInstanceName("OSGI-Instance"); HazelcastOSGiInstance newInstance2 = hazelcastOsgiService.newHazelcastInstance(config); HazelcastOSGiInstance instance = hazelcastOsgiService.getHazelcastInstanceByName("OSGI-Instance"); hazelcastOsgiService.shutdownHazelcastInstance(instance); for (HazelcastOSGiInstance osgiInstance : hazelcastOsgiService.getAllHazelcastInstances()) { System.out.println(osgiInstance); } hazelcastOsgiService.shutdownAll(); } finally { Thread.currentThread().setContextClassLoader(currentContextClassLoader); } }</code><technical_language>clear need swap classLoader. user of service need swap classloaders able create instances</technical_language>

Target:
public void start(BundleContext context) throws Exception { System.out.println("Starting activator " + this + " in bundle " + context.getBundle() + " ..."); ServiceReference serviceRef = context.getServiceReference(HazelcastOSGiService.class.getName()); if (serviceRef == null) { throw new IllegalStateException("There is no registered `HazelcastOSGiService`!"); } HazelcastOSGiService hazelcastOsgiService = (HazelcastOSGiService) context.getService(serviceRef); HazelcastOSGiInstance defaultInstance = hazelcastOsgiService.getDefaultHazelcastInstance(); HazelcastOSGiInstance newInstance1 = hazelcastOsgiService.newHazelcastInstance(); Config config = new Config(); config.setInstanceName("OSGI-Instance"); HazelcastOSGiInstance newInstance2 = hazelcastOsgiService.newHazelcastInstance(config); HazelcastOSGiInstance instance = hazelcastOsgiService.getHazelcastInstanceByName("OSGI-Instance"); hazelcastOsgiService.shutdownHazelcastInstance(instance); for (HazelcastOSGiInstance osgiInstance : hazelcastOsgiService.getAllHazelcastInstances()) { System.out.println(osgiInstance); } hazelcastOsgiService.shutdownAll(); }
Source:
<code>private <T> CloseableIterator<T> decorateShutdownTimeout( ScheduledExecutorService exec, CloseableIterator<T> delegateIterator ) { final Closer closer = Closer.create(); closer.register(delegateIterator); closer.register(exec::shutdownNow); final CloseableIterator<T> wrappingIterator = new CloseableIterator<T>() { volatile boolean closed; @Override public boolean hasNext() { return !closed && delegateIterator.hasNext(); } @Override public T next() { if (!hasNext()) { <START> throw new NoSuchElementException(); <END> } return delegateIterator.next(); } @Override public void close() throws IOException { closed = true; closer.close(); } }; exec.schedule( () -> { LOG.info("Closing delegate inputSource."); try { wrappingIterator.close(); } catch (IOException e) { LOG.warn(e, "Failed to close delegate inputSource, ignoring."); } }, shutoffTime.getMillis() - System.currentTimeMillis(), TimeUnit.MILLISECONDS ); return wrappingIterator; }</code><technical_language>This kind of ugly if transforming reader wrapping this iterator sampler calls hasNext this iterator is closed calls next. In practice _I think_ this ok handled ExceptionThrowingIterator of CloseableIterator, I if is a more graceful, exception throwing handle this</technical_language>

Target:
private <T> CloseableIterator<T> decorateShutdownTimeout( ScheduledExecutorService exec, CloseableIterator<T> delegateIterator ) { final Closer closer = Closer.create(); closer.register(delegateIterator); closer.register(exec::shutdownNow); final CloseableIterator<T> wrappingIterator = new CloseableIterator<T>() { volatile boolean closed; T next = null; @Override public boolean hasNext() { if (next != null) { return true; } if (!closed && delegateIterator.hasNext()) { next = delegateIterator.next(); return true; } else { return false; } } @Override public T next() { if (next != null) { final T returnValue = next; next = null; return returnValue; } else { throw new NoSuchElementException(); } } @Override public void close() throws IOException { closed = true; closer.close(); } }; exec.schedule( () -> { LOG.info("Closing delegate inputSource."); try { wrappingIterator.close(); } catch (IOException e) { LOG.warn(e, "Failed to close delegate inputSource, ignoring."); } }, shutoffTime.getMillis() - System.currentTimeMillis(), TimeUnit.MILLISECONDS ); return wrappingIterator; }
Source:
<code>public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory,projectName); configuration.setBuildNumber(buildNumber); configuration.setStatusFlags(skippedFails,pendingFails,undefinedFails,missingFails); configuration.setParallelTesting(parallelTesting); <START> configuration.setRunWithJenkins(false); <END> ReportBuilder reportBuilder = new ReportBuilder(list,configuration); getLog().info("About to generate Cucumber report."); reportBuilder.generateReports(); if (checkBuildResult) { boolean buildResult = reportBuilder.hasBuildPassed(); if (!buildResult) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }</code><technical_language>needed, this is default</technical_language>

Target:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } if (list.isEmpty()) { getLog().warn(cucumberOutput.getAbsolutePath() + " does not exist."); return; } try { Configuration configuration = new Configuration(outputDirectory,projectName); configuration.setBuildNumber(buildNumber); configuration.setStatusFlags(skippedFails,pendingFails,undefinedFails,missingFails); configuration.setParallelTesting(parallelTesting); ReportBuilder reportBuilder = new ReportBuilder(list,configuration); getLog().info("About to generate Cucumber report."); reportBuilder.generateReports(); if (checkBuildResult) { boolean buildResult = reportBuilder.hasBuildPassed(); if (!buildResult) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }
Source:
<code>protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) { if (this.callback != null) { this.callback.changeThingType(getThing(), thingTypeUID, configuration); } else { <START> throw new IllegalStateException("Could change thing type because callback is missing"); <END> } }</code><technical_language>is a "not" missing</technical_language>

Target:
protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) { if (this.callback != null) { this.callback.changeThingType(getThing(), thingTypeUID, configuration); } else { throw new IllegalStateException("Could not change thing type because callback is missing"); } }
Source:
<code>public void testNullBinding() throws Exception { Map<String, Object> args = Collections.singletonMap("foo", null); new MapArguments(args, ctx).find("foo").get().apply(3, stmt, null); <START> verify(stmt).setNull(3, ((NullArgument)new Arguments().getUntypedNullArgument()).getSqlType()); <END> }</code><technical_language>Meh.. Types.OTHER is safe here</technical_language>

Target:
public void testNullBinding() throws Exception { Map<String, Object> args = Collections.singletonMap("foo", null); new MapArguments(args, ctx).find("foo").get().apply(3, stmt, null); verify(stmt).setNull(3, Types.OTHER); }
Source:
<code><START> public boolean isExpired() { <END> if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } else { return TokenCacheItem.isTokenExpired(getExpiresOn()); } }</code><technical_language>I understand check. do if outgage mode is turned in AuthenticationResult class iteself? If turned on, checking extended expires on</technical_language>

Target:
public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } return TokenCacheItem.isTokenExpired(getExpiresOn()); }
Source:
<code>private static IBlockState asBlockState(crafttweaker.api.block.IBlockState blockstate) { Object internal = blockstate.getInternal(); if (!(internal instanceof IBlockState)) { CraftTweakerAPI.logError("Not a valid blockstate: " + blockstate); } <START> return (IBlockState) internal; <END> }</code><technical_language>this throw a ClassCastException if condition for logError is met? return null in instanceof Check</technical_language>

Target:
private static IBlockState asBlockState(crafttweaker.api.block.IBlockState blockstate) { Object internal = blockstate.getInternal(); if (!(internal instanceof IBlockState)) { CraftTweakerAPI.logError("Not a valid blockstate: " + blockstate); return null; } return (IBlockState) internal; }
Source:
<code>public void writeConfiguration(String host) throws IOException { Lock readLock = configLock.readLock(); try { readLock.lock(); Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("configuration") .queryParam("reindex", true) .request() <START> .put(Entity.xml(configuration.getXMLRepresentationAsString())); <END> if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException(r.toString()); } } finally { readLock.unlock(); } }</code><technical_language>Is neccessary lock api call a non-trivial amount of time while needs lock is this configuration.getXMLRepresentationAsString()</technical_language>

Target:
public void writeConfiguration(String host) throws IOException { String configXML; try { configLock.readLock().lock(); configXML = configuration.getXMLRepresentationAsString(); } finally { configLock.readLock().unlock(); } Response r = ClientBuilder.newClient() .target(host) .path("api") .path("v1") .path("configuration") .queryParam("reindex", true) .request() .put(Entity.xml(configXML)); if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException(r.toString()); } }
Source:
<code>private ReflectionMappers(ReflectionMappers that) { <START> columnNameMatchers.addAll(that.columnNameMatchers); <END> strictMatching = that.strictMatching; }</code><technical_language>CopyOnWriteArrayList(Collection) copy constructor, reuses underlying array if collection is another CopyOnWriteArrayList. get copy-on-write benefit</technical_language>

Target:
private ReflectionMappers(ReflectionMappers that) { columnNameMatchers = new ArrayList<>(that.columnNameMatchers); strictMatching = that.strictMatching; }
Source:
<code>public void onAssignmentChange(List<DatastreamTask> tasks) { HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); <START> for (DatastreamTask task : toCancel) { <END> KafkaConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { if (_runningTasks.containsKey(task)) { continue; } LOG.info("creating task for {}.", task); KafkaConnectorTask connectorTask = new KafkaConnectorTask(task); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }</code><technical_language>In general, I start tasks need started, stop tasks supposed stopped. other potentially introduce latency</technical_language>

Target:
public void onAssignmentChange(List<DatastreamTask> tasks) { HashSet<DatastreamTask> toCancel = new HashSet<>(_runningTasks.keySet()); toCancel.removeAll(tasks); for (DatastreamTask task : toCancel) { KafkaConnectorTask connectorTask = _runningTasks.remove(task); connectorTask.stop(); } for (DatastreamTask task : tasks) { if (_runningTasks.containsKey(task)) { continue; } LOG.info("creating task for {}.", task); KafkaConnectorTask connectorTask = new KafkaConnectorTask(task, 100); _runningTasks.put(task, connectorTask); _executor.submit(connectorTask); } }
Source:
<code>public boolean equals(Object column) { <START> if (column == null) { <END> return false; } else if (column instanceof Column) { Column col = (Column)column; return (getType() == col.getType()); } else { return false; } }</code><technical_language>This is good. Thanks</technical_language>

Target:
public boolean equals(Object column) { if (!(column instanceof Column)) { return false; } Column col = (Column)column; return (getType() == col.getType()); }
Source:
<code>public void break_outside_loop() { cfgForBlock("" + <START> " break 2;"); <END> }</code><technical_language>nitpick indent for this break</technical_language>

Target:
public void break_outside_loop() { cfgForBlock("break 2;"); }
Source:
<code>public static long toMillisFromJavaEpoch(int year, int month, int day, TimeZone currentTimeZone) { int daysFromMinDay = countDaysFromMinDay(year, month, day); long millisFromMinDay = daysFromMinDay * UniversalDate.MILLIS_IN_DAY; int timezoneOffsetFromGMT = currentTimeZone.getOffset(millisFromMinDay); <START> return millisFromMinDay + MIN_MILLIS_FROM_JAVA_EPOCH - timezoneOffsetFromGMT; <END> }</code><technical_language>this completely, explain want subtracting timezoneOffsetFromGMT</technical_language>

Target:
public static long toMillisFromJavaEpoch(int year, int month, int day, TimeZone currentTimeZone) { int daysFromMinDay = countDaysFromMinDay(year, month, day); long millisFromMinDay = daysFromMinDay * UniversalDate.MILLIS_IN_DAY; int timezoneOffsetFromUTC = currentTimeZone.getOffset(millisFromMinDay); long millisNormalizedToUTC = millisFromMinDay - timezoneOffsetFromUTC; return millisNormalizedToUTC + MIN_MILLIS_FROM_JAVA_EPOCH; }
Source:
<code>public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object <START> name : <END> c) changed |= remove(name); return changed; }</code><technical_language>rename 'element'</technical_language>

Target:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object element : c) changed |= remove(element); return changed; }
Source:
<code>private BigInteger evaluateExpression(IDMContext ctx, String expression) throws Throwable { final IExpressionDMContext expressionDMC = SyncUtil.createExpression(ctx, expression); final FormattedValueDMContext formattedValueDMC = SyncUtil.getFormattedValue(fExpressionService, expressionDMC, IFormattedValues.DECIMAL_FORMAT); Query<FormattedValueDMData> query = new <START> Query<IFormattedValues.FormattedValueDMData>() <END> { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpressionService.getFormattedExpressionValue(formattedValueDMC, rm); } }; fExpressionService.getExecutor().submit(query); FormattedValueDMData result = query.get(); return new BigInteger(result.getFormattedValue()); }</code><technical_language>Please remove redundant IFormattedValues</technical_language>

Target:
private BigInteger evaluateExpression(IDMContext ctx, String expression) throws Throwable { final IExpressionDMContext expressionDMC = SyncUtil.createExpression(ctx, expression); final FormattedValueDMContext formattedValueDMC = SyncUtil.getFormattedValue(fExpressionService, expressionDMC, IFormattedValues.DECIMAL_FORMAT); Query<FormattedValueDMData> query = new Query<FormattedValueDMData>() { @Override protected void execute(DataRequestMonitor<FormattedValueDMData> rm) { fExpressionService.getFormattedExpressionValue(formattedValueDMC, rm); } }; fExpressionService.getExecutor().submit(query); FormattedValueDMData result = query.get(TestsPlugin.massageTimeout(2000), TimeUnit.MILLISECONDS); return new BigInteger(result.getFormattedValue()); }
Source:
<code>public synchronized Optional<ILauncher> getLauncher() { <START> return model.getLauncher().map(launcher -> launcher); <END> }</code><technical_language>Erm, need map launcher suggestion return model.getLauncher();</technical_language>

Target:
public synchronized Optional<? extends ILauncher> getLauncher() { return model.getLauncher(); }
Source:
<code>private static boolean isUnaryValid(CallExpression callExpression) { <START> return callExpression.getChildren().size() == 1 && callExpression.getChildren().get(0) instanceof FieldReferenceExpression; <END> }</code><technical_language>a isRef(Expression) isLit(Expr)</technical_language>

Target:
private static boolean isUnaryValid(CallExpression callExpression) { return callExpression.getChildren().size() == 1 && isRef(callExpression.getChildren().get(0)); }
Source:
<code>public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { <START> System.out.println("## Error :: "+e.getMessage()); <END> return null; } }</code><technical_language>Please log exception. Do print it. Log this: logger.error("Some message..." + e);</technical_language>

Target:
public String doPost(String api, HashMap<String, String> mapHeaders, String body, HashMap<String, String> queries) { try { HttpHeaders headers = new HttpHeaders(); for (String i : mapHeaders.keySet()) { headers.add(i, mapHeaders.get(i).toString()); } HttpEntity<String> request; if (body != null) { request = new HttpEntity<>(body, headers); } else { request = new HttpEntity<String>(headers); } RestTemplate rest = new RestTemplate(); ResponseEntity<String> response; if (queries != null) { response = rest.postForEntity(api, request, String.class, queries); } else { response = rest.postForEntity(api, request, String.class); } return response.getBody(); } catch (Exception e) { logger.error("Error sending request : ", e); return null; } }
Source:
<code>protected void printCalendar(Calendar value, CSVPrinter printer) throws IOException { if (value != null) { <START> printer.print(format.format(ZonedDateTime.ofInstant(value.toInstant(), value.getTimeZone().toZoneId()))); <END> } else { printer.print(null); } }</code><technical_language>simpler is ((GregorianCalendar) value).toZonedDateTime()</technical_language>

Target:
protected void printCalendar(Calendar value, CSVPrinter printer) throws IOException { if (value != null) { printer.print(((GregorianCalendar) value).toZonedDateTime()); } else { printer.print(null); } }
Source:
<code>public static void main(String[] args) throws Exception { PatentReaderJobParameters params = new PatentReaderJobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); <START> SparkSession session = SparkSessionFactory.withConfAndKryo(new SparkConf()); <END> try { JavaSparkContext sc = JavaSparkContext.fromSparkContext(session.sparkContext()); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); JavaRDD<ImportedPatent> results = session.read() .option("sep", "\t") .option("header","true") .csv(params.inputTsvLocation) .toJavaRDD() .map(PatentReaderJob::buildEntry); storeInOutput(results, generateReportEntries(sc, results), params.outputPath, params.outputReportPath); } finally { if (Objects.nonNull(session)) { session.stop(); } } }</code><technical_language>Create SparkSession try-with-resources, finally block needed</technical_language>

Target:
public static void main(String[] args) throws Exception { PatentReaderJobParameters params = new PatentReaderJobParameters(); JCommander jcommander = new JCommander(params); jcommander.parse(args); try (SparkSession session = SparkSessionFactory.withConfAndKryo(new SparkConf())) { JavaSparkContext sc = JavaSparkContext.fromSparkContext(session.sparkContext()); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputPath); HdfsUtils.remove(sc.hadoopConfiguration(), params.outputReportPath); JavaRDD<ImportedPatent> results = session.read() .option("sep", "\t") .option("header","true") .csv(params.inputTsvLocation) .toJavaRDD() .map(PatentReaderJob::buildEntry); storeInOutput(results, generateReportEntries(sc, results), params.outputPath, params.outputReportPath); } }
Source:
<code>public Resource parse() throws InvalidStructureException, IOException, XmlPullParserException { checkNode("resource"); String id = parser.getAttributeValue(null, "id"); int version = parseInt(parser.getAttributeValue(null, "version")); String descriptor = parser.getAttributeValue(null, "descriptor"); String lazy = parser.getAttributeValue(null, "lazy"); Vector<ResourceLocation> locations = new Vector<>(); while (nextTagInBlock("resource")) { String sAuthority = parser.getAttributeValue(null, "authority"); String location = parser.nextText(); int authority = Resource.RESOURCE_AUTHORITY_REMOTE; if (sAuthority.toLowerCase().equals("local")) { authority = Resource.RESOURCE_AUTHORITY_LOCAL; } else if (sAuthority.toLowerCase().equals("remote")) { authority = Resource.RESOURCE_AUTHORITY_REMOTE; } if (authority >= maximumAuthority) { locations.addElement(new ResourceLocation(authority, location)); } } <START> return new Resource(version, id, locations, descriptor, lazy != null && lazy.contentEquals("true")); <END> }</code><technical_language>"true".contentEquals(lazy) avoid null checks</technical_language>

Target:
public Resource parse() throws InvalidStructureException, IOException, XmlPullParserException { checkNode("resource"); String id = parser.getAttributeValue(null, "id"); int version = parseInt(parser.getAttributeValue(null, "version")); String descriptor = parser.getAttributeValue(null, "descriptor"); String lazy = parser.getAttributeValue(null, "lazy"); Vector<ResourceLocation> locations = new Vector<>(); while (nextTagInBlock("resource")) { String sAuthority = parser.getAttributeValue(null, "authority"); String location = parser.nextText(); int authority = Resource.RESOURCE_AUTHORITY_REMOTE; if (sAuthority.toLowerCase().equals("local")) { authority = Resource.RESOURCE_AUTHORITY_LOCAL; } else if (sAuthority.toLowerCase().equals("remote")) { authority = Resource.RESOURCE_AUTHORITY_REMOTE; } if (authority >= maximumAuthority) { locations.addElement(new ResourceLocation(authority, location)); } } return new Resource(version, id, locations, descriptor, lazy == null ? LAZY_VAL_FALSE : lazy); }
Source:
<code>public void testVariablesAvailableInView() throws CoreException, IOException { <START> new ProjectExplorer().getProject("nodejs-ex").getProjectItem("server.js").open(); <END> new WaitUntil(new EditorWithTitleIsActive("server.js")); TextEditor editor = new TextEditor("server.js"); setLineBreakpoint(editor, BREAKPOINT_LINE); triggerDebugSession(); TreeItem var_db = getVariable(VAR_db); TreeItem var_initDb = getVariable(VAR_initDb); TreeItem var_require = getVariable(VAR_require); assertTrue("Variable '" + VAR_db + "' not found in view!", var_db != null); assertThat(var_db.getCell(0), is(VAR_db)); assertThat(var_db.getCell(1), containsString(VAR_VALUE_db)); assertTrue("Variable '" + VAR_initDb + "' not found in view!", var_initDb != null); assertThat(var_initDb.getCell(0), is(VAR_initDb)); assertThat(var_initDb.getCell(1), containsString(VAR_VALUE_initDb)); assertTrue("Variable '" + VAR_require + "' not found in view!", var_require != null); assertThat(var_require.getCell(0), is(VAR_require)); assertThat(var_require.getCell(1), containsString(VAR_VALUE_require)); }</code><technical_language>ProjectExplorer is open</technical_language>

Target:
public void testVariablesAvailableInView() throws CoreException, IOException { ProjectExplorer pe = new ProjectExplorer(); pe.open(); pe.getProject(OpenShiftResources.NODEJS_GIT_NAME).getProjectItem("server.js").open(); new WaitUntil(new EditorWithTitleIsActive("server.js")); TextEditor editor = new TextEditor("server.js"); setLineBreakpoint(editor, BREAKPOINT_LINE); triggerDebugSession(); TreeItem var_db = getVariable(VAR_db); TreeItem var_initDb = getVariable(VAR_initDb); TreeItem var_require = getVariable(VAR_require); assertTrue("Variable '" + VAR_db + "' not found in view!", var_db != null); assertThat(var_db.getCell(0), is(VAR_db)); assertThat(var_db.getCell(1), containsString(VAR_VALUE_db)); assertTrue("Variable '" + VAR_initDb + "' not found in view!", var_initDb != null); assertThat(var_initDb.getCell(0), is(VAR_initDb)); assertThat(var_initDb.getCell(1), containsString(VAR_VALUE_initDb)); assertTrue("Variable '" + VAR_require + "' not found in view!", var_require != null); assertThat(var_require.getCell(0), is(VAR_require)); assertThat(var_require.getCell(1), containsString(VAR_VALUE_require)); }
Source:
<code>public void should_mark_regular_node_down_when_no_more_connections() { <START> simulacronRegularNode.rejectConnections(0, RejectScope.UNBIND); <END> simulacronRegularNode.closeConnections(CloseType.DISCONNECT); ConditionChecker.checkThat(() -> metadataRegularNode.getState() == NodeState.DOWN) .as("Node going down") .before(10, TimeUnit.SECONDS) .becomesTrue(); assertThat(metadataRegularNode).hasState(NodeState.DOWN).hasOpenConnections(0).isReconnecting(); expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode)); }</code><technical_language>simulacronRegularNode.stop() a shortcut for 2 methods</technical_language>

Target:
public void should_mark_regular_node_down_when_no_more_connections() { simulacronRegularNode.stop(); ConditionChecker.checkThat( () -> assertThat(metadataRegularNode).isDown().hasOpenConnections(0).isReconnecting()) .as("Node going down") .before(10, TimeUnit.SECONDS) .becomesTrue(); expect(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, metadataRegularNode)); }
Source:
<code>public static void main(final String[] args) throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(512)); final String channel = new String("udp://localhost:40123"); final int streamId = 10; System.out.println("Publishing to " + channel + " on stream Id " + streamId); final Aeron.Context ctx = new Aeron.Context(); Publication publication = null; Aeron aeron = null; <START> try <END> { aeron = Aeron.connect(ctx); publication = aeron.addPublication(channel, streamId); final String message = "Hello World! "; buffer.putBytes(0, message.getBytes()); final long result = publication.offer(buffer, 0, message.getBytes().length); if (result < 0L) { if (result == Publication.BACK_PRESSURE) { System.out.println(" Offer failed due to back pressure"); } else if (result == Publication.NOT_CONNECTED) { System.out.println(" Offer failed because publisher is not yet connected to subscriber"); } else { System.out.println(" Offer failed due to unknown reason"); } } else { System.out.println(" yay !!"); } System.out.println("Done sending."); } finally { publication.close(); aeron.close(); } }</code><technical_language>try resources</technical_language>

Target:
public static void main(final String[] args) throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(512)); final String channel = "udp://localhost:40123"; final int streamId = 10; System.out.println("Publishing to " + channel + " on stream Id " + streamId); final Aeron.Context ctx = new Aeron.Context(); try (final Aeron aeron = Aeron.connect(ctx); final Publication publication = aeron.addPublication(channel, streamId);) { final String message = "Hello World! "; buffer.putBytes(0, message.getBytes()); final long result = publication.offer(buffer, 0, message.getBytes().length); if (result < 0L) { if (result == Publication.BACK_PRESSURE) { System.out.println(" Offer failed due to back pressure"); } else if (result == Publication.NOT_CONNECTED) { System.out.println(" Offer failed because publisher is not yet connected to subscriber"); } else { System.out.println(" Offer failed due to unknown reason"); } } else { System.out.println(" yay !!"); } System.out.println("Done sending."); } finally { ctx.close(); } }
Source:
<code>protected void run() throws Exception { ResetCommand command = new Git(db).reset(); command.setRef(commit); ResetType mode = null; <START> if(soft) <END> mode = ResetType.SOFT; else if(mixed) mode = ResetType.MIXED; else if(hard) mode = ResetType.HARD; if (mode != null) command.setMode(mode); command.call(); }</code><technical_language>Style-nit: Space if</technical_language>

Target:
protected void run() throws Exception { ResetCommand command = new Git(db).reset(); command.setRef(commit); ResetType mode = null; if (soft) mode = selectMode(mode, ResetType.SOFT); if (mixed) mode = selectMode(mode, ResetType.MIXED); if (hard) mode = selectMode(mode, ResetType.HARD); if (mode == null) throw die("no reset mode set"); command.setMode(mode); command.call(); }
Source:
<code>public String toString() { <START> return "NationalIdentityNumber{" + <END> "value='" + value + '\'' + '}'; }</code><technical_language>Simplify toString</technical_language>

Target:
public String toString() { return "NationalIdentityNumber{" + value + "}"; }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else if(item.getTitle().equals(getString(R.string.comment_reply_send))) { String subreddit = subredditEdit.getText().toString(); String postTitle = titleEdit.getText().toString(); String text = textEdit.getText().toString(); if (subreddit.isEmpty()) { <START> Toast.makeText(this, "Specify subreddit", Toast.LENGTH_SHORT).show(); <END> subredditEdit.requestFocus(); } else if (postTitle.isEmpty()) { Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show(); titleEdit.requestFocus(); } else if ("URL".equals(textEdit.getHint().toString()) && text.isEmpty()) { Toast.makeText(this, "URL cannot be empty", Toast.LENGTH_SHORT).show(); textEdit.requestFocus(); } else { final Intent captchaIntent = new Intent(this, CaptchaActivity.class); captchaIntent.putExtra("username", (String)usernameSpinner.getSelectedItem()); startActivityForResult(captchaIntent, REQUEST_CAPTCHA); } } else if(item.getTitle().equals(getString(R.string.comment_reply_preview))) { MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager(), null); } return true; }</code><technical_language>This string (and line 198 201) declared end of strings.xml (to allow for translation)</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else if(item.getTitle().equals(getString(R.string.comment_reply_send))) { String subreddit = subredditEdit.getText().toString(); String postTitle = titleEdit.getText().toString(); String text = textEdit.getText().toString(); if (subreddit.isEmpty()) { Toast.makeText(this, R.string.submit_post_specify_subreddit, Toast.LENGTH_SHORT).show(); subredditEdit.requestFocus(); } else if (postTitle.isEmpty()) { Toast.makeText(this, R.string.submit_post_title_empty, Toast.LENGTH_SHORT).show(); titleEdit.requestFocus(); } else if (getString(R.string.submit_post_url_hint).equals(textEdit.getHint().toString()) && text.isEmpty()) { Toast.makeText(this, R.string.submit_post_url_empty, Toast.LENGTH_SHORT).show(); textEdit.requestFocus(); } else { final Intent captchaIntent = new Intent(this, CaptchaActivity.class); captchaIntent.putExtra("username", (String)usernameSpinner.getSelectedItem()); startActivityForResult(captchaIntent, REQUEST_CAPTCHA); } } else if(item.getTitle().equals(getString(R.string.comment_reply_preview))) { MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager(), null); } return true; }
Source:
<code>private Method findMethod(Class<?> testClass, String methodName) { if (methodName.contains("[") && methodName.endsWith("]")) { <START> return findMethod(testClass, methodName.substring(0, methodName.indexOf("["))); <END> } List<Method> methods = methodsCache.computeIfAbsent(testClass, clazz -> findMethods(clazz, m -> true)).stream() .filter(where(Method::getName, isEqual(methodName))) .collect(toList()); if (methods.isEmpty()) { return null; } if (methods.size() == 1) { return methods.get(0); } methods = methods.stream().filter(ModifierSupport::isPublic).collect(toList()); if (methods.size() == 1) { return methods.get(0); } return null; }</code><technical_language>perform recursion here? methodName = methodName.substring(0, methodName.indexOf("["));</technical_language>

Target:
private Method findMethod(Class<?> testClass, String methodName) { List<Method> methods = methodsCache.computeIfAbsent(testClass, clazz -> findMethods(clazz, m -> true)).stream() .filter(where(Method::getName, isEqual(methodName))) .collect(toList()); if (methods.isEmpty()) { return null; } if (methods.size() == 1) { return methods.get(0); } methods = methods.stream().filter(ModifierSupport::isPublic).collect(toList()); if (methods.size() == 1) { return methods.get(0); } return null; }