auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ProjectImportWizard(IDialogSettings dialogSettings, PublishedGradleVersionsWrapper publishedGradleVersions) { <START> super(); <END> setDialogSettings(dialogSettings); this.controller = new ProjectImportWizardController(this); final ProjectImportConfiguration configuration = this.controller.getConfiguration(); WelcomePageConfigurator welcomePageConfiguratorImpl = WelcomePageConfiguratorFactory .createImportWizardWelcomePageConfigurator(PREF_SHOW_WELCOME_PAGE); this.welcomeWizardPage = new GradleWelcomeWizardPage(configuration, welcomePageConfiguratorImpl); this.gradleProjectPage = new GradleProjectWizardPage(configuration); this.gradleOptionsPage = new GradleOptionsWizardPage(configuration, publishedGradleVersions); this.projectPreviewPage = new ProjectPreviewWizardPage(this.controller.getConfiguration(), new ProjectPreviewWizardPage.ProjectPreviewLoader() { @Override public Job loadPreview( FutureCallback<Pair<OmniBuildEnvironment, OmniGradleBuildStructure>> resultHandler, List<ProgressListener> listeners) { ProjectPreviewJob projectPreviewJob = new ProjectPreviewJob(configuration, listeners, AsyncHandler.NO_OP, resultHandler); projectPreviewJob.schedule(); return projectPreviewJob; } }); }</code><technical_language>redundant</technical_language>

Target:
public ProjectImportWizard(IDialogSettings dialogSettings, PublishedGradleVersionsWrapper publishedGradleVersions) { super(PREF_SHOW_WELCOME_PAGE); setDialogSettings(dialogSettings); this.controller = new ProjectImportWizardController(this); final ProjectImportConfiguration configuration = this.controller.getConfiguration(); WelcomePageContent welcomePageConfiguratorImpl = WelcomePageContentFactory .createImportWizardWelcomePageConfigurator(); this.welcomeWizardPage = new GradleWelcomeWizardPage(configuration, welcomePageConfiguratorImpl); this.gradleProjectPage = new GradleProjectWizardPage(configuration); this.gradleOptionsPage = new GradleOptionsWizardPage(configuration, publishedGradleVersions); this.projectPreviewPage = new ProjectPreviewWizardPage(this.controller.getConfiguration(), new ProjectPreviewWizardPage.ProjectPreviewLoader() { @Override public Job loadPreview( FutureCallback<Pair<OmniBuildEnvironment, OmniGradleBuildStructure>> resultHandler, List<ProgressListener> listeners) { ProjectPreviewJob projectPreviewJob = new ProjectPreviewJob(configuration, listeners, AsyncHandler.NO_OP, resultHandler); projectPreviewJob.schedule(); return projectPreviewJob; } }); }
Source:
<code>public void onlyApprovedCode() { <START> onlyApprovedCode(true); <END> }</code><technical_language>this false here</technical_language>

Target:
public void onlyApprovedCode() { onlyApprovedCode(false); }
Source:
<code>public String getMetadata(String key) { <START> return metadata.get(key).toString(); <END> }</code><technical_language>cast string instead of toString()</technical_language>

Target:
public String getMetadata(String key) { return (String)metadata.get(key); }
Source:
<code>private static int calculatePageCount( MemoryAllocator memoryAllocator, int cachePageSize ) { long memoryPerPage = cachePageSize + PageList.META_DATA_BYTES_PER_PAGE; long maxPages = memoryAllocator.availableMemory() / memoryPerPage; int minimumPageCount = 2; if ( maxPages < minimumPageCount ) { throw new IllegalArgumentException( String.format( "Page cache must have at least %s pages (%s bytes of memory), but was given %s pages.", minimumPageCount, minimumPageCount * memoryPerPage, maxPages ) ); } if ( maxPages > Integer.MAX_VALUE ) { <START> return Integer.MAX_VALUE; <END> } return Math.toIntExact( maxPages ); }</code><technical_language>this fetched page cache meta data</technical_language>

Target:
private static int calculatePageCount( MemoryAllocator memoryAllocator, int cachePageSize ) { long memoryPerPage = cachePageSize + PageList.META_DATA_BYTES_PER_PAGE; long maxPages = memoryAllocator.availableMemory() / memoryPerPage; int minimumPageCount = 2; if ( maxPages < minimumPageCount ) { throw new IllegalArgumentException( String.format( "Page cache must have at least %s pages (%s bytes of memory), but was given %s pages.", minimumPageCount, minimumPageCount * memoryPerPage, maxPages ) ); } maxPages = Math.min( maxPages, PageList.MAX_PAGES ); return Math.toIntExact( maxPages ); }
Source:
<code>public Map<String, String> getPathParametersEncoded(String uri) { Map<String, String> map = Maps.newHashMap(); Matcher m = regex.matcher(uri); if (m.matches()) { <START> if (this.parameters != null) { <END> Iterator<String> it = this.parameters.keySet().iterator(); for (int i = 1; i < m.groupCount() + 1; i++) { String parameterName = it.next(); map.put(parameterName, m.group(i)); } } } return map; }</code><technical_language>Another idea. returning empty LinkedList RouteParameter.parse(uri) instead returning null? need null checks... test is cool stuff works of course... 100% RouteParameter.parse(uri) is called building Route, a performance impact of that..</technical_language>

Target:
public Map<String, String> getPathParametersEncoded(String uri) { Map<String, String> map = Maps.newHashMap(); Matcher m = regex.matcher(uri); if (m.matches()) { Iterator<String> it = this.parameters.keySet().iterator(); for (int i = 1; i < m.groupCount() + 1; i++) { String parameterName = it.next(); map.put(parameterName, m.group(i)); } } return map; }
Source:
<code>public void testHorizontalScrollbar() { SWTBotView viewBot = openView(); List<? extends @NonNull Slider> <START> scrollers = <END> viewBot.bot().widgets(WidgetOfType.widgetOfType(Slider.class)); assertTrue("The view has " + scrollers.size() + " sliders", scrollers.size() >= 2); SWTBotScroller hScroller = new SWTBotScroller(scrollers.get(HORIZONTAL_SCROLLBAR_INDEX)); Rectangle scrollerRect = hScroller.getBounds(); SWTBotTimeGraph tgBot = new SWTBotTimeGraph(viewBot.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class))); Rectangle timegraphRect = tgBot.getBounds(); assertEquals("Incorrect horizontal scroller start position", timegraphRect.width - scrollerRect.width, scrollerRect.x); }</code><technical_language>sliders</technical_language>

Target:
public void testHorizontalScrollbar() { SWTBotView viewBot = openView(); List<? extends @NonNull Slider> sliders = viewBot.bot().widgets(WidgetOfType.widgetOfType(Slider.class)); assertTrue("The view has " + sliders.size() + " sliders", sliders.size() >= 2); SWTBotScroller hSlider = new SWTBotScroller(sliders.get(HORIZONTAL_SCROLLBAR_INDEX)); Rectangle scrollerRect = hSlider.getBounds(); SWTBotTimeGraph tgBot = new SWTBotTimeGraph(viewBot.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class))); Rectangle timegraphRect = tgBot.getBounds(); assertEquals("Incorrect horizontal scroller start position", timegraphRect.x + tgBot.getNameSpace(), scrollerRect.x); }
Source:
<code>public Matcher<Document> hasNodes(final String xPath, final Matcher<? extends Iterable<Node>> matcher) { return new BaseMatcher<Document>() { @Override public boolean matches(Object item) { XpathEngine engine = XMLUnit.newXpathEngine(); engine.setNamespaceContext(namespaceContext); try { List<Node> nodes = nodeCollection(engine.getMatchingNodes(xPath, (Document) item)); return matcher.matches(nodes); } catch (XpathException e) { return false; } } @Override public void describeTo(Description description) { description.appendText("Document where the list of nodes matching ") .appendValue(xPath).appendText(" is ").appendDescriptionOf(matcher); } @Override public void describeMismatch(Object item, Description description) { XpathEngine engine = XMLUnit.newXpathEngine(); engine.setNamespaceContext(namespaceContext); try { List<Node> nodes = nodeCollection(engine.getMatchingNodes(xPath, (Document) item)); matcher.describeMismatch(nodes, description); if(showXML != null) { <START> printDom((Document) item, System.out); <END> } } catch (XpathException e) { description.appendText("exception occured: ").appendText(e.getMessage()); } } }; }</code><technical_language>this print showXML, System.out</technical_language>

Target:
public Matcher<Document> hasNodes(final String xPath, final Matcher<? extends Iterable<Node>> matcher) { return new BaseMatcher<Document>() { @Override public boolean matches(Object item) { XpathEngine engine = XMLUnit.newXpathEngine(); engine.setNamespaceContext(namespaceContext); try { List<Node> nodes = nodeCollection(engine.getMatchingNodes(xPath, (Document) item)); return matcher.matches(nodes); } catch (XpathException e) { return false; } } @Override public void describeTo(Description description) { description.appendText("Document where the list of nodes matching ") .appendValue(xPath).appendText(" is ").appendDescriptionOf(matcher); } @Override public void describeMismatch(Object item, Description description) { XpathEngine engine = XMLUnit.newXpathEngine(); engine.setNamespaceContext(namespaceContext); try { List<Node> nodes = nodeCollection(engine.getMatchingNodes(xPath, (Document) item)); matcher.describeMismatch(nodes, description); if(showXML != null) { printDom((Document) item, showXML); } } catch (XpathException e) { description.appendText("exception occured: ").appendText(e.getMessage()); } } }; }
Source:
<code>private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); List<Page> outputPages = new ArrayList<>(); assertOperatorIsUnblocked(operator); while (!operator.isFinished() && System.nanoTime() - endTime < 0) { <START> assertEquals(operator.needsInput(), false); <END> Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertEquals(operator.needsInput(), false, "Operator still wants input"); assertTrue(operator.isFinished(), "Expected operator to be finished"); return outputPages; }</code><technical_language>assertFalse</technical_language>

Target:
private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); List<Page> outputPages = new ArrayList<>(); assertOperatorIsUnblocked(operator); while (!operator.isFinished() && System.nanoTime() - endTime < 0) { assertFalse(operator.needsInput()); Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertFalse(operator.needsInput(), "Operator still wants input"); assertTrue(operator.isFinished(), "Expected operator to be finished"); return outputPages; }
Source:
<code><START> public void elasticsearchVersion() throws IOException { <END> container = new ElasticsearchContainer(); Properties props = new Properties(); props.load(ElasticsearchContainerTest.class.getResourceAsStream("elasticsearch-version.properties")); String version = props.getProperty("version"); container.withVersion(version); container.start(); Response response = getClient(container).performRequest("GET", "/"); assertThat(response.getStatusLine().getStatusCode(), is(200)); String responseAsString = EntityUtils.toString(response.getEntity()); assertThat(responseAsString, containsString(version)); }</code><technical_language>this effectively elasticsearchDefaultTest, fallback default version</technical_language>

Target:
public void elasticsearchVersion() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:5.6.12")) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); String responseAsString = EntityUtils.toString(response.getEntity()); assertThat(responseAsString, containsString("5.6.12")); } }
Source:
<code>public void addConfigurations(PluginInfo pluginInfo, List<ConfigurationProperty> configurationProperties) { settingsMap.clear(); if (pluginInfo != null) { ConfigurationPropertyBuilder builder = new ConfigurationPropertyBuilder(); for (ConfigurationProperty property : configurationProperties) { final PluginConfiguration configuration = configPropertyFor(property.getConfigKeyName(), pluginInfo); if (configuration != null) { settingsMap.add(builder.create(property.getConfigKeyName(), property.getConfigValue(), property.getEncryptedValue(), configuration.isSecure())); } } <START> } <END> }</code><technical_language>ignoring a property a configuration in pluginInfo. Instead ignoring leave plugin validate it</technical_language>

Target:
public void addConfigurations(PluginInfo pluginInfo, List<ConfigurationProperty> configurationProperties) { settingsMap.clear(); if (pluginInfo != null) { ConfigurationPropertyBuilder builder = new ConfigurationPropertyBuilder(); for (ConfigurationProperty property : configurationProperties) { final PluginConfiguration configuration = configPropertyFor(property.getConfigKeyName(), pluginInfo); if (configuration != null) { settingsMap.add(builder.create(property.getConfigKeyName(), property.getConfigValue(), property.getEncryptedValue(), configuration.isSecure())); } else { settingsMap.add(property); } } } }
Source:
<code>public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) { <START> this.result = wizard.getCommand(); <END> editingDomain.getCommandStack().execute(result); } }</code><technical_language>Command cmd = getPatternCreationCommand(editingDomain.getResourcSet(), selectedViewpoint Eventually, Wizard a getSelectedPattern (and configured of course) write: IPatternProvider selectedPattern = wizard.getSelectedPattern(); editingDomain.getCommandStack().execute(selectedPattern.getCreationCommand(resourceSet, selectedViewpoint));</technical_language>

Target:
public void run() { InitializerWizard wizard = new InitializerWizard(); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) { editingDomain.getCommandStack().execute(wizard.getCommand(this.editingDomain.getResourceSet(), this.viewpoint)); } }
Source:
<code>public void testWbFromDMNWhenDMNIsNotNull() { final String id = "id"; final Id expectedId = new Id(id); final String qNameNamespaceURI = "qName namespaceURI"; final String qNameLocalPart = "qName local part"; <START> final String qNamePrefix = "qName local part"; <END> final QName expectedTypeRef = new QName(qNameNamespaceURI, qNameLocalPart, qNamePrefix); final javax.xml.namespace.QName qName = mock(javax.xml.namespace.QName.class); final org.kie.dmn.model.api.InformationItem dmn = mock(org.kie.dmn.model.api.InformationItem.class); when(dmn.getId()).thenReturn(id); when(dmn.getTypeRef()).thenReturn(qName); when(qName.getNamespaceURI()).thenReturn(qNameNamespaceURI); when(qName.getLocalPart()).thenReturn(qNameLocalPart); when(qName.getPrefix()).thenReturn(qNamePrefix); final InformationItemPrimary informationItemPrimary = InformationItemPrimaryPropertyConverter.wbFromDMN(dmn); final Id actualId = informationItemPrimary.getId(); final QName actualTypeRef = informationItemPrimary.getTypeRef(); assertEquals(expectedId, actualId); assertEquals(expectedTypeRef, actualTypeRef); }</code><technical_language>Please do for qNameLocalPart qNamePrefix. for example "qName prefix" of qNamePrefix variable</technical_language>

Target:
public void testWbFromDMNWhenDMNIsNotNull() { final String id = "id"; final Id expectedId = new Id(id); final String qNameNamespaceURI = "qName namespaceURI"; final String qNameLocalPart = "qName local part"; final String qNamePrefix = "qName prefix"; final QName expectedTypeRef = new QName(qNameNamespaceURI, qNameLocalPart, qNamePrefix); final javax.xml.namespace.QName qName = mock(javax.xml.namespace.QName.class); final org.kie.dmn.model.api.InformationItem dmn = mock(org.kie.dmn.model.api.InformationItem.class); when(dmn.getId()).thenReturn(id); when(dmn.getTypeRef()).thenReturn(qName); when(qName.getNamespaceURI()).thenReturn(qNameNamespaceURI); when(qName.getLocalPart()).thenReturn(qNameLocalPart); when(qName.getPrefix()).thenReturn(qNamePrefix); final InformationItemPrimary informationItemPrimary = InformationItemPrimaryPropertyConverter.wbFromDMN(dmn, dmn); final Id actualId = informationItemPrimary.getId(); final QName actualTypeRef = informationItemPrimary.getTypeRef(); assertEquals(expectedId, actualId); assertEquals(expectedTypeRef, actualTypeRef); }
Source:
<code>public Map<String, Object> asMap() throws JWTDecodeException { ObjectMapper mapper = new ObjectMapper(); try { TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() { }; <START> return mapper.treeAsTokens(data).readValueAs(mapType); <END> } catch (IOException e) { throw new JWTDecodeException("Couldn't map the Claim value to Map", e); } }</code><technical_language>this PR, ObjectMapper (even static) instead of creating a new time? TypeReference</technical_language>

Target:
public Map<String, Object> asMap() throws JWTDecodeException { if (!data.isObject()) { return null; } ObjectMapper mapper = new ObjectMapper(); try { TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() { }; return mapper.treeAsTokens(data).readValueAs(mapType); } catch (IOException e) { throw new JWTDecodeException("Couldn't map the Claim value to Map", e); } }
Source:
<code>public void close() { log.debug("Closing queue"); tailers.stream().filter(Objects::nonNull).forEach(tailer -> { try { tailer.close(); <START> } catch (Exception e) { <END> log.error("Failed to close tailer: " + tailer); } }); tailers.clear(); queues.stream().filter(Objects::nonNull).forEach(ChronicleQueue::close); queues.clear(); closed = true; }</code><technical_language>catch Exception</technical_language>

Target:
public void close() { log.debug("Closing queue"); tailers.stream().filter(Objects::nonNull).forEach(ChronicleLogTailer::close); tailers.clear(); queues.stream().filter(Objects::nonNull).forEach(ChronicleQueue::close); queues.clear(); closed = true; }
Source:
<code>public void testExtensionHandlerNotRemovedByFailureWritePromise() { when(mainHandshakerMock.handshakeExtension(webSocketExtensionDataMatcher("main"))) .thenReturn(mainExtensionMock); WebSocketServerExtensionHandler extensionHandler = new WebSocketServerExtensionHandler(mainHandshakerMock); EmbeddedChannel ch = new EmbeddedChannel(extensionHandler); HttpRequest req = newUpgradeRequest("unknown, unknown2"); ch.writeInbound(req); HttpResponse res = newUpgradeResponse(null); ChannelPromise failurePromise = ch.newPromise(); ch.writeOneOutbound(res, failurePromise); failurePromise.setFailure(new IOException("Cannot write response")); assertNull(ch.readOutbound()); assertNotNull(ch.pipeline().context(extensionHandler)); <START> } <END></code><technical_language>call ch.finish() assert return value</technical_language>

Target:
public void testExtensionHandlerNotRemovedByFailureWritePromise() { when(mainHandshakerMock.handshakeExtension(webSocketExtensionDataMatcher("main"))) .thenReturn(mainExtensionMock); when(mainExtensionMock.newReponseData()).thenReturn( new WebSocketExtensionData("main", Collections.<String, String>emptyMap())); WebSocketServerExtensionHandler extensionHandler = new WebSocketServerExtensionHandler(mainHandshakerMock); EmbeddedChannel ch = new EmbeddedChannel(extensionHandler); HttpRequest req = newUpgradeRequest("main"); ch.writeInbound(req); HttpResponse res = newUpgradeResponse(null); ChannelPromise failurePromise = ch.newPromise(); ch.writeOneOutbound(res, failurePromise); failurePromise.setFailure(new IOException("Cannot write response")); assertNull(ch.readOutbound()); assertNotNull(ch.pipeline().context(extensionHandler)); assertTrue(ch.finish()); }
Source:
<code>public Verification withIssuer(String... issuer) { <START> requireClaim(PublicClaims.ISSUER, Arrays.asList(issuer)); <END> return this; }</code><technical_language>need call Arrays.asList all. If varargs instead of a String, instance of Array considered a "list". Similarly, if fix withAudience method calling Arrays.asList well. (same reason). Feel free do in a separate PR if desired</technical_language>

Target:
public Verification withIssuer(String... issuer) { requireClaim(PublicClaims.ISSUER, issuer == null ? null : Arrays.asList(issuer)); return this; }
Source:
<code>private void writeLine(String line, TestingOutput.LineType lineType) { try { consumer.consume(DtoFactory.cloneDto(new TestingOutputImpl(line, lineType))); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>LOG.error</technical_language>

Target:
private void writeLine(String line, TestingOutput.LineType lineType) { try { consumer.consume(DtoFactory.cloneDto(new TestingOutputImpl(line, lineType))); } catch (IOException e) { LOG.error(consumeErrorMessage, e); } }
Source:
<code>public void testChangeTypePrivate() throws InterruptedException { getActivity(); onView(withText(R.string.changeGroupType)).perform(click()); onView(withText(" Private")).perform(click()); onView(withText("Ok")).perform(click()); onView(withText("Group type changed to : private")).inRoot(withDecorView(not(is(getActivity(). getWindow().getDecorView())))).check(matches(isDisplayed())); assertEquals(Group.GroupVisibility.PRIVATE, YieldsApplication.getGroup().getVisibility()); <START> Thread.sleep(2000); <END> }</code><technical_language>Sleep end</technical_language>

Target:
public void testChangeTypePrivate() throws InterruptedException { getActivity(); onView(withText(R.string.changeGroupType)).perform(click()); onView(withText(" Private")).perform(click()); onView(withText("Ok")).perform(click()); onView(withText("Group type changed to : private")).inRoot(withDecorView(not(is(getActivity(). getWindow().getDecorView())))).check(matches(isDisplayed())); assertEquals(Group.GroupVisibility.PRIVATE, YieldsApplication.getGroup().getVisibility()); }
Source:
<code>protected void updateValue() { <START> if ("".equals(property.getValue())) { <END> dropDownButton.setCaption("All"); dropDownButton.setWidth(""); } else { dropDownButton.setCaption("Toolkit Defined"); } }</code><technical_language>Consider making this property.getValue() == null || property.getValue().isEmpty()</technical_language>

Target:
protected void updateValue() { if (StringUtils.isNullOrEmpty(property.getValue())) { dropDownButton.setCaption("All"); dropDownButton.setWidth(""); } else { dropDownButton.setCaption("Toolkit Defined"); } }
Source:
<code>public void shouldLogErrorOn_9_2_24() { Logger log = Mockito.mock(Logger.class); thrown.expect(AssertionError.class); <START> thrown.expectMessage("The minimum supported version is "); <END> PostgresVersionCheck.checkDatabaseVersion("9.2.24", log); Mockito.verify(log).error(contains("The minimum supported version is {}"), Mockito.anyObject(), Mockito.eq(PostgresVersionCheck.MIN_POSTGRES_VERSION)); Mockito.verifyNoMoreInteractions(log); }</code><technical_language>this test right anymore. Lines 37-40 dead code, right</technical_language>

Target:
public void shouldLogErrorOn_9_2_24() { Logger log = Mockito.mock(Logger.class); String expectedMessage = "The minimum supported version is " + PostgresVersionCheck.MIN_POSTGRES_VERSION; try { PostgresVersionCheck.checkDatabaseVersion("9.2.24", log); Assert.fail("Expected an AssertionError"); } catch (AssertionError error) { Assert.assertTrue("Error did not contain expected message. Actual error: " + error, error.getMessage().contains(expectedMessage)); } Mockito.verify(log).error( eq("Assertion with exception "), contains(expectedMessage), Mockito.any(Exception.class)); Mockito.verifyNoMoreInteractions(log); }
Source:
<code>public void before() { IndexInitializer.init(elasticsearchTemplate, Product.class); repository.saveAll(Arrays.asList( Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false).sortName("sort5") .build(), <START> Product.builder().id("2").name("Sugar").text("Cane sugar").price(1.2f).available(true).sortName("sort4") <END> .build(), Product.builder().id("3").name("Sugar").text("Beet sugar").price(1.1f).available(true).sortName("sort3") .build(), Product.builder().id("4").name("Salt").text("Rock salt").price(1.9f).available(true).sortName("sort2").build(), Product.builder().id("5").name("Salt").text("Sea salt").price(2.1f).available(false).sortName("sort1") .build())); elasticsearchTemplate.refresh(Product.class); }</code><technical_language>Nit: Extract product objects for readability variables</technical_language>

Target:
public void before() { IndexInitializer.init(elasticsearchTemplate, Product.class); Product product1 = Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false) .sortName("sort5").build(); Product product2 = Product.builder().id("2").name("Sugar").text("Cane sugar").price(1.2f).available(true) .sortName("sort4").build(); Product product3 = Product.builder().id("3").name("Sugar").text("Beet sugar").price(1.1f).available(true) .sortName("sort3").build(); Product product4 = Product.builder().id("4").name("Salt").text("Rock salt").price(1.9f).available(true) .sortName("sort2").build(); Product product5 = Product.builder().id("5").name("Salt").text("Sea salt").price(2.1f).available(false) .sortName("sort1").build(); repository.saveAll(Arrays.asList(product1, product2, product3, product4, product5)); elasticsearchTemplate.refresh(Product.class); }
Source:
<code>int determineRealLabelWidth(FormItem item, Integer labelWidth) { List<Integer> sizesList = formSizeMap.get(item); int valueWidth; if (labelWidth != null) { sizesList.set(1, labelWidth); <START> valueWidth = labelWidth; <END> } else { valueWidth = sizesList.get(1); } return valueWidth; }</code><technical_language>Alternatively, this a bit shorter: if (labelWidth != null) { sizesList.set(1, labelWidth); } valueWidth = sizesList.get(1);</technical_language>

Target:
int determineRealLabelWidth(FormItem item, Integer labelWidth) { List<Integer> sizesList = formSizeMap.get(item); if (labelWidth != null) { sizesList.set(1, labelWidth); } return sizesList.get(1); }
Source:
<code>private static <C extends Content> C mergeContents(C current, C extracted) { <START> current.setActivelyPublished(true); <END> current.setAliasUrls(extracted.getAliasUrls()); current.setTitle(extracted.getTitle()); current.setDescription(extracted.getDescription()); current.setImage(extracted.getImage()); current.setYear(extracted.getYear()); current.setGenres(extracted.getGenres()); current.setPeople(extracted.people()); current.setLanguages(extracted.getLanguages()); current.setCertificates(extracted.getCertificates()); current.setMediaType(extracted.getMediaType()); current.setSpecialization(extracted.getSpecialization()); current.setLastUpdated(extracted.getLastUpdated()); return current; }</code><technical_language>this honour actively published flag of extracted content, explicitly set true</technical_language>

Target:
private static <C extends Content> C mergeContents(C current, C extracted) { current.setActivelyPublished(extracted.isActivelyPublished()); current.setAliasUrls(extracted.getAliasUrls()); current.setTitle(extracted.getTitle()); current.setDescription(extracted.getDescription()); current.setImage(extracted.getImage()); current.setYear(extracted.getYear()); current.setGenres(extracted.getGenres()); current.setPeople(extracted.people()); current.setLanguages(extracted.getLanguages()); current.setCertificates(extracted.getCertificates()); current.setMediaType(extracted.getMediaType()); current.setSpecialization(extracted.getSpecialization()); current.setLastUpdated(extracted.getLastUpdated()); return current; }
Source:
<code>public RequiredRolesListItemPresenter setup(final String role, final DeploymentsRequiredRolesPresenter parentPresenter) { <START> singleValueModal.setup(LibraryConstants.AddRequiredRole, LibraryConstants.Role); <END> this.role = role; this.parentPresenter = parentPresenter; view.init(this); view.setRole(role); return this; }</code><technical_language>EditRequiredRole</technical_language>

Target:
public RequiredRolesListItemPresenter setup(final String role, final DeploymentsRequiredRolesPresenter parentPresenter) { singleValueModal.setup(LibraryConstants.EditRequiredRole, LibraryConstants.Role); this.role = role; this.parentPresenter = parentPresenter; view.init(this); view.setRole(role); return this; }
Source:
<code>public boolean userHasRoles(String userId, List<String> roleIds) { if (!UtilMethods.isSet(userId) || roleIds == null || roleIds.size() == 0) { return false; } User user; try { <START> user = APILocator.getUserAPI().loadUserById(userId, APILocator.getUserAPI().getSystemUser(), false); <END> } catch (Exception e) { Logger.error(this, "An error occurred when retrieving information of user ID [" + userId + "]", e); return false; } String currentRoleId = null; for (String roleId : roleIds) { if (UtilMethods.isSet(roleId.trim())) { currentRoleId = roleId; try { if (APILocator.getRoleAPI().doesUserHaveRole(user, roleId)) { return true; } } catch (DotDataException e) { Logger.error(UserAjax.class, "An error occurred when checking role [" + currentRoleId + "] on user ID [" + userId + "]", e); return false; } } } return false; }</code><technical_language>Shoudn't class attribute for UserApi</technical_language>

Target:
public boolean userHasRoles(String userId, List<String> roleIds) { if (!UtilMethods.isSet(userId) || roleIds == null || roleIds.size() == 0) { return false; } User user; try { user = this.userAPI.loadUserById(userId, this.userAPI.getSystemUser(), false); } catch (Exception e) { Logger.error(this, "An error occurred when retrieving information of user ID [" + userId + "]", e); return false; } String currentRoleId = null; for (String roleId : roleIds) { if (UtilMethods.isSet(roleId.trim())) { currentRoleId = roleId; try { if (this.roleAPI.doesUserHaveRole(user, roleId)) { return true; } } catch (DotDataException e) { Logger.error(UserAjax.class, "An error occurred when checking role [" + currentRoleId + "] on user ID [" + userId + "]", e); return false; } } } return false; }
Source:
<code>public Set<ArtifactStore> getAllArtifactStores() throws IndyDataException { Set<ArtifactStore> ret = new HashSet<>(); <START> stores.getCache().forEach( ( k, v ) -> { <END> ArtifactStore store = readValueByJson( v, StoreKey.fromString( k ) ); if ( store != null ) { ret.add( store ); } } ); return ret; }</code><technical_language>nitpick again. :)</technical_language>

Target:
public Set<ArtifactStore> getAllArtifactStores() throws IndyDataException { return stores.executeCache( c -> { Set<ArtifactStore> ret = new HashSet<>(); c.forEach( ( k, v ) -> { ArtifactStore store = readValueByJson( v, k ); if ( store != null ) { ret.add( store ); } } ); return ret; } ); }
Source:
<code>public void test2faToken() throws IOException { List<String> asList = Arrays.asList("repo", "gist", "write:packages", "read:packages", "delete:packages", "user", "delete_repo"); String nameOfToken = "Test2faTokenCreate"; GHAuthorization token=gitHub.createToken( asList, nameOfToken, "this is a test token created by a unit test", () -> { String data = "111878"; return data; }); assert token!=null; <START> String p = token.getToken(); <END> assert p!=null; }</code><technical_language>more checks done here? Ensure list passed is in expected values of returned GHAuthorization such</technical_language>

Target:
public void test2faToken() throws IOException { assertFalse("Test only valid when not proxying", mockGitHub.isUseProxy()); List<String> asList = Arrays.asList("repo", "gist", "write:packages", "read:packages", "delete:packages", "user", "delete_repo"); String nameOfToken = "Test2faTokenCreate"; GHAuthorization token=gitHub.createToken( asList, nameOfToken, "this is a test token created by a unit test", () -> { String data = "111878"; return data; }); assert token!=null; for(int i=0;i<asList.size();i++) { assertTrue(token.getScopes().get(i).contentEquals(asList.get(i))); } String p = token.getToken(); assert p!=null; }
Source:
<code>public static UiStringText getCustomStringForAutosaveRevisionDialog(PostModel post) { <START> Context context = WordPress.getContext(); <END> String firstPart = context.getString(R.string.dialog_confirm_autosave_body); String lastModified = TextUtils.isEmpty(post.getDateLocallyChanged()) ? post.getLastModified() : post.getDateLocallyChanged(); String secondPart = String.format(context.getString(R.string.dialog_confirm_autosave_body_2), getFormattedDateForLastModified( context, DateTimeUtils.timestampFromIso8601Millis(lastModified)), getFormattedDateForLastModified( context, DateTimeUtils.timestampFromIso8601Millis(post.getAutoSaveModified()))); return new UiStringText(firstPart + secondPart); }</code><technical_language>I WordPress.getContext(). a global difficult in unit tests</technical_language>

Target:
public static UiStringText getCustomStringForAutosaveRevisionDialog(PostModel post) { Context context = WordPress.getContext(); String firstPart = context.getString(R.string.dialog_confirm_autosave_body_first_part); String lastModified = TextUtils.isEmpty(post.getDateLocallyChanged()) ? post.getLastModified() : post.getDateLocallyChanged(); String secondPart = String.format(context.getString(R.string.dialog_confirm_autosave_body_second_part), getFormattedDateForLastModified( context, DateTimeUtils.timestampFromIso8601Millis(lastModified)), getFormattedDateForLastModified( context, DateTimeUtils.timestampFromIso8601Millis(post.getAutoSaveModified()))); return new UiStringText(firstPart + secondPart); }
Source:
<code>public Map<String, Optional<DatastreamPartitionsMetadata>> getDatastreamPartitions() { Map<String, Optional<DatastreamPartitionsMetadata>> datastreams = new HashMap<>(); _partitionDiscoveryThreadMap.forEach((s, partitionDiscoveryThread) -> { <START> if (partitionDiscoveryThread._initialized) { <END> datastreams.put(s, Optional.of(new DatastreamPartitionsMetadata(s, partitionDiscoveryThread._subscribedPartitions))); } else { datastreams.put(s, Optional.empty()); } }); return datastreams; }</code><technical_language>Java allows this, code readability future refactoring if need, if avoid accessing internal variables outside</technical_language>

Target:
public Map<String, Optional<DatastreamGroupPartitionsMetadata>> getDatastreamPartitions() { Map<String, Optional<DatastreamGroupPartitionsMetadata>> datastreams = new HashMap<>(); _partitionDiscoveryThreadMap.forEach((s, partitionDiscoveryThread) -> { if (partitionDiscoveryThread.isInitialized()) { datastreams.put(s, Optional.of(new DatastreamGroupPartitionsMetadata(partitionDiscoveryThread.getDatastreamGroup(), partitionDiscoveryThread.getSubscribedPartitions()))); } else { datastreams.put(s, Optional.empty()); } }); return datastreams; }
Source:
<code>private ModelNode readAttributeValue(PathAddress address, String attributeName) { final ModelNode readAttributeOp = new ModelNode(); readAttributeOp.get(OP).set(READ_ATTRIBUTE_OPERATION); readAttributeOp.get(OP_ADDR).set(address.toModelNode()); readAttributeOp.get(ModelDescriptionConstants.INCLUDE_UNDEFINED_METRIC_VALUES).set(false); readAttributeOp.get(NAME).set(attributeName); ModelNode response = modelControllerClient.execute(readAttributeOp); String error = getFailureDescription(response); if (error != null) { <START> LOGGER.unableToReadAttribute(attributeName, address, error); <END> } return response.get(RESULT); }</code><technical_language>RBAC failures logged a level</technical_language>

Target:
private ModelNode readAttributeValue(PathAddress address, String attributeName) { final ModelNode readAttributeOp = new ModelNode(); readAttributeOp.get(OP).set(READ_ATTRIBUTE_OPERATION); readAttributeOp.get(OP_ADDR).set(address.toModelNode()); readAttributeOp.get(ModelDescriptionConstants.INCLUDE_UNDEFINED_METRIC_VALUES).set(false); readAttributeOp.get(NAME).set(attributeName); ModelNode response = modelControllerClient.execute(readAttributeOp); String error = getFailureDescription(response); if (error != null) { if (error.contains("WFLYCTL0216")) { LOGGER.debugf("Unable to read attribute %s: %s.", attributeName, error); } else{ LOGGER.unableToReadAttribute(attributeName, address, error); } return new ModelNode(ModelType.UNDEFINED); } return response.get(RESULT); }
Source:
<code>public void saveOrder_shouldSetOrderTypeOfDrugOrderToDrugOrderIfNotSetAndConceptNotMapped() throws Exception { Drug drug = conceptService.getDrug(2); <START> drug.setConcept(conceptService.getConcept(113)); <END> DrugOrder drugOrder = new DrugOrder(); Encounter encounter = encounterService.getEncounter(3); drugOrder.setEncounter(encounter); drugOrder.setPatient(patientService.getPatient(7)); drugOrder.setCareSetting(orderService.getCareSetting(1)); drugOrder.setOrderer(Context.getProviderService().getProvider(1)); drugOrder.setStartDate(encounter.getEncounterDatetime()); drugOrder.setDrug(drug); drugOrder.setDosingType(DrugOrder.DosingType.SIMPLE); drugOrder.setDose(300.0); drugOrder.setDoseUnits(conceptService.getConcept(50)); drugOrder.setQuantity(20.0); drugOrder.setQuantityUnits(conceptService.getConcept(51)); drugOrder.setDuration(20.0); drugOrder.setDurationUnits(conceptService.getConcept(28)); drugOrder.setFrequency(orderService.getOrderFrequency(3)); drugOrder.setRoute(conceptService.getConcept(22)); drugOrder.setNumRefills(10); drugOrder.setOrderType(null); orderService.saveOrder(drugOrder, null); Assert.assertNotNull(drugOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.DRUG_ORDER_TYPE_UUID), drugOrder.getOrderType()); }</code><technical_language>add assertion ensures this concept is mapped, orderService.getOrderTypeByConcept check is null</technical_language>

Target:
public void saveOrder_shouldSetOrderTypeOfDrugOrderToDrugOrderIfNotSetAndConceptNotMapped() throws Exception { Drug drug = conceptService.getDrug(2); Concept unmappedConcept = conceptService.getConcept(113); Assert.assertNull(orderService.getOrderTypeByConcept(unmappedConcept)); drug.setConcept(unmappedConcept); DrugOrder drugOrder = new DrugOrder(); Encounter encounter = encounterService.getEncounter(3); drugOrder.setEncounter(encounter); drugOrder.setPatient(patientService.getPatient(7)); drugOrder.setCareSetting(orderService.getCareSetting(1)); drugOrder.setOrderer(Context.getProviderService().getProvider(1)); drugOrder.setStartDate(encounter.getEncounterDatetime()); drugOrder.setDrug(drug); drugOrder.setDosingType(DrugOrder.DosingType.SIMPLE); drugOrder.setDose(300.0); drugOrder.setDoseUnits(conceptService.getConcept(50)); drugOrder.setQuantity(20.0); drugOrder.setQuantityUnits(conceptService.getConcept(51)); drugOrder.setDuration(20.0); drugOrder.setDurationUnits(conceptService.getConcept(28)); drugOrder.setFrequency(orderService.getOrderFrequency(3)); drugOrder.setRoute(conceptService.getConcept(22)); drugOrder.setNumRefills(10); drugOrder.setOrderType(null); orderService.saveOrder(drugOrder, null); Assert.assertNotNull(drugOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.DRUG_ORDER_TYPE_UUID), drugOrder.getOrderType()); }
Source:
<code>public void close() throws IOException { super.close(); <START> for (Class cl : classCache.values()) { <END> InvokerHelper.removeClass(cl); } }</code><technical_language>+1 for clear cache... especially proper synchronization</technical_language>

Target:
public void close() throws IOException { super.close(); clearCache(); }
Source:
<code>private void refreshCanvas() { MockCanvas mockCanvas = (MockCanvas) getContainer(); if (mockCanvas != null) { <START> mockCanvas.refreshForm(); <END> } }</code><technical_language>is purpose of refreshing form canvas? This more cycles for result</technical_language>

Target:
private void refreshCanvas() { MockCanvas mockCanvas = (MockCanvas) getContainer(); if (mockCanvas != null) { mockCanvas.reorderComponents(this); } }
Source:
<code>public EClassSelectionStrategy create() { return new EClassSelectionStrategy() { @Override public Collection<EClass> collectEClasses(EObject owner, EReference reference, Collection<EClass> eclasses) { return <START> EMFUtils.getSubClasses(EcorePackage.eINSTANCE.getEObject()); <END> } }; }</code><technical_language>I suggest reference.getEReferenceType() here, for pedantic correctness</technical_language>

Target:
public EClassSelectionStrategy create() { return new EClassSelectionStrategy() { @Override public Collection<EClass> collectEClasses(EObject owner, EReference reference, Collection<EClass> eclasses) { return EMFUtils.getSubClasses(reference.getEReferenceType()); } }; }
Source:
<code>public static long clockUrlDownload( URL url, int speedLimit ) throws IOException { long t = System.currentTimeMillis(); HttpClient client = new HttpClient(); GetMethod get = new GetMethod( url.toString() ); int result = client.executeMethod( get ); assertThat( result, ResponseMatchers.isSuccessfulCode() ); InputStream in = get.getResponseBodyAsStream(); byte[] b; if ( speedLimit != -1 ) { b = new byte[speedLimit * 1024]; } else { b = new byte[1024]; } while ( in.read( b ) != -1 ) { if ( speedLimit != -1 ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { } } } in.close(); <START> get.releaseConnection(); <END> return System.currentTimeMillis() - t; }</code><technical_language>put cleanup this in finally block</technical_language>

Target:
public static long clockUrlDownload( URL url, int speedLimit ) throws IOException { long t = System.currentTimeMillis(); GetMethod get = null; InputStream in = null; try { HttpClient client = new HttpClient(); get = new GetMethod( url.toString() ); int result = client.executeMethod( get ); assertThat( result, ResponseMatchers.isSuccessfulCode() ); in = get.getResponseBodyAsStream(); byte[] b; if ( speedLimit != -1 ) { b = new byte[speedLimit * 1024]; } else { b = new byte[1024]; } while ( in.read( b ) != -1 ) { if ( speedLimit != -1 ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { } } } } finally { IOUtil.close( in ); if ( get != null ) { get.releaseConnection(); } } return System.currentTimeMillis() - t; }
Source:
<code>public void showPayment(BufferedPayment payment) { if (payment.getOfflinePlayer() == null || !payment.getOfflinePlayer().isOnline() || !payment.containsPayment()) return; UUID playerUUID = payment.getOfflinePlayer().getUniqueId(); Boolean ActionBarsDefaultOn = Jobs.getGCManager().ActionBarsMessageByDefault; Boolean show = ToggleBarHandling.getActionBarToggle().getOrDefault(playerUUID.toString(), ActionBarsDefaultOn); Player abp = Bukkit.getPlayer(playerUUID); if (abp != null) { <START> String Message = Jobs.getLanguage().getMessage("command.toggle.output.paid.main"); <END> if (payment.get(CurrencyType.MONEY) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.money", "[amount]", String.format(Jobs.getGCManager().getDecimalPlacesMoney(), payment.get(CurrencyType.MONEY))); } if (payment.get(CurrencyType.POINTS) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.points", "[points]", String.format(Jobs.getGCManager().getDecimalPlacesPoints(), payment.get(CurrencyType.POINTS))); } if (payment.get(CurrencyType.EXP) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.exp", "[exp]", String.format(Jobs.getGCManager().getDecimalPlacesExp(), payment.get(CurrencyType.EXP))); } if (show.booleanValue()) { ActionBarManager.send(abp, Message); } else abp.sendMessage(Message); } }</code><technical_language>here, change this variable name lowercase</technical_language>

Target:
public void showPayment(BufferedPayment payment) { if (payment.getOfflinePlayer() == null || !payment.getOfflinePlayer().isOnline() || !payment.containsPayment()) return; UUID playerUUID = payment.getOfflinePlayer().getUniqueId(); Boolean actionBarsDefaultOn = Jobs.getGCManager().ActionBarsMessageByDefault; Boolean show = ToggleBarHandling.getActionBarToggle().getOrDefault(playerUUID.toString(), ActionBarsDefaultOn); Player abp = Bukkit.getPlayer(playerUUID); if (abp != null) { String Message = Jobs.getLanguage().getMessage("command.toggle.output.paid.main"); if (payment.get(CurrencyType.MONEY) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.money", "[amount]", String.format(Jobs.getGCManager().getDecimalPlacesMoney(), payment.get(CurrencyType.MONEY))); } if (payment.get(CurrencyType.POINTS) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.points", "[points]", String.format(Jobs.getGCManager().getDecimalPlacesPoints(), payment.get(CurrencyType.POINTS))); } if (payment.get(CurrencyType.EXP) != 0D) { Message += " " + Jobs.getLanguage().getMessage("command.toggle.output.paid.exp", "[exp]", String.format(Jobs.getGCManager().getDecimalPlacesExp(), payment.get(CurrencyType.EXP))); } if (show.booleanValue()) { ActionBarManager.send(abp, Message); } else abp.sendMessage(Message); } }
Source:
<code>protected void notifySelect(boolean first) { int stateMask1 = (first) ? SWT.NONE : (SWT.NONE | SWT.CTRL); int stateMask2 = (first) ? SWT.BUTTON1 : (SWT.BUTTON1 | SWT.CTRL); if (first) { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); } <START> notify(SWT.MouseMove); <END> notify(SWT.MouseDown, createMouseEvent(1, stateMask1, 1)); notify(SWT.Selection, createSelectionEvent(stateMask1)); notify(SWT.MouseUp, createMouseEvent(1, stateMask2, 1)); }</code><technical_language>If right coordinates useful ;)</technical_language>

Target:
protected void notifySelect(boolean first) { int stateMask1 = (first) ? SWT.NONE : (SWT.NONE | SWT.CTRL); int stateMask2 = (first) ? SWT.BUTTON1 : (SWT.BUTTON1 | SWT.CTRL); if (first) { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); } notify(SWT.MouseDown, createMouseEvent(1, stateMask1, 1)); notify(SWT.Selection, createSelectionEvent(stateMask1)); notify(SWT.MouseUp, createMouseEvent(1, stateMask2, 1)); }
Source:
<code>public OrderedDistinctMap(String lastHash) { <START> mapper = new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); <END> this.lastHash = lastHash; }</code><technical_language>ObjectMapper instantiation is expensive. a static ObjectMapper instead: OrderedDistinctMap.OBJECT_MAPPER</technical_language>

Target:
public OrderedDistinctMap(String lastHash) { this.lastHash = lastHash; }
Source:
<code><START> protected void initWidget(IsWidget widget) { <END> if (widget == null) { throw new NullPointerException("Widget cannot be null."); } this.widget = widget.asWidget(); asWidget().addAttachHandler(this); }</code><technical_language>If turned initWidget constructor for version 2.0 work better</technical_language>

Target:
protected void initWidget(IsWidget widget) { if (this.widget != null) { throw new IllegalStateException("ViewImpl.initWidget() may only be called once."); } else if (widget == null) { throw new NullPointerException("widget cannot be null"); } this.widget = widget.asWidget(); asWidget().addAttachHandler(this); }