auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) { List<CustomerDto> customers = new ArrayList<>(); CustomerDto customerOne = new CustomerDto("1", "Kelly", "Brown"); CustomerDto customerTwo = new CustomerDto("2", "Alfonso", "Bass"); customers.add(customerOne); customers.add(customerTwo); <START> CustomerResource customerResource = new CustomerResource(customers); <END> System.out.println("All customers:-"); List<CustomerDto> allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); System.out.println("----------------------------------------------------------"); System.out.println("Deleting customer with id {1}"); customerResource.delete(customerOne.getId()); allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); System.out.println("----------------------------------------------------------"); System.out.println("Adding customer three}"); CustomerDto customerThree = new CustomerDto("3", "Lynda", "Blair"); customerResource.save(customerThree); allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); }</code><technical_language>This is customer server data initialization, right? move static block in CustomerResource class</technical_language>

Target:
public static void main(String[] args) { List<CustomerDto> customers = new ArrayList<>(); CustomerDto customerOne = new CustomerDto("1", "Kelly", "Brown"); CustomerDto customerTwo = new CustomerDto("2", "Alfonso", "Bass"); customers.add(customerOne); customers.add(customerTwo); CustomerResource customerResource = new CustomerResource(customers); LOGGER.info("All customers:-"); List<CustomerDto> allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); LOGGER.info("----------------------------------------------------------"); LOGGER.info("Deleting customer with id {1}"); customerResource.delete(customerOne.getId()); allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); LOGGER.info("----------------------------------------------------------"); LOGGER.info("Adding customer three}"); CustomerDto customerThree = new CustomerDto("3", "Lynda", "Blair"); customerResource.save(customerThree); allCustomers = customerResource.getAllCustomers(); printCustomerDetails(allCustomers); }
Source:
<code>public String getGender() { <START> return gender.name(); <END> }</code><technical_language>Getters generally a simple return. return type Gender? is prescription return type needs String</technical_language>

Target:
public Gender getGender() { return gender; }
Source:
<code>public MqttBrokerConnection(String host, @Nullable Integer port, boolean secure, @Nullable String clientId) { this.host = host; this.secure = secure; if (clientId == null) { clientId = MqttClient.generateClientId(); <START> assert clientId != null; <END> } else if (clientId.length() > 23) { throw new IllegalArgumentException("Client ID cannot be longer than 23 characters"); } if (port != null && (port <= 0 || port > 65535)) { throw new IllegalArgumentException("Port is not within a valid range"); } this.port = port != null ? port : (secure ? 8883 : 1883); this.clientId = clientId; setReconnectStrategy(new PeriodicReconnectStrategy()); }</code><technical_language>please remove refactor</technical_language>

Target:
public MqttBrokerConnection(String host, @Nullable Integer port, boolean secure, @Nullable String clientId) { this.host = host; this.secure = secure; String newClientID = clientId; if (newClientID == null) { newClientID = MqttClient.generateClientId(); } else if (newClientID.length() > 23) { throw new IllegalArgumentException("Client ID cannot be longer than 23 characters"); } if (port != null && (port <= 0 || port > 65535)) { throw new IllegalArgumentException("Port is not within a valid range"); } this.port = port != null ? port : (secure ? 8883 : 1883); this.clientId = newClientID; setReconnectStrategy(new PeriodicReconnectStrategy()); }
Source:
<code>public void shouldCreateEntry() throws OperationException { String entryId = "test_entry"; assertEquals("vocabulary", directoryService.getDirectorySchema(vocabularyName)); Session vocabularySession = directoryService.open(vocabularyName); <START> assertTrue(!vocabularySession.hasEntry(entryId)); <END> OperationContext context = new OperationContext(session); OperationChain chain = new OperationChain("shouldCreateEntry"); chain.add(CreateVocabularyEntry.ID).set("name", vocabularyName).set("id", entryId); service.run(context, chain); assertTrue(vocabularySession.hasEntry(entryId)); }</code><technical_language>assertFalse</technical_language>

Target:
public void shouldCreateEntry() throws OperationException { String entryId = "test_entry"; assertEquals("vocabulary", directoryService.getDirectorySchema(vocabularyName)); Session vocabularySession = directoryService.open(vocabularyName); assertFalse(vocabularySession.hasEntry(entryId)); OperationContext context = new OperationContext(session); OperationChain chain = new OperationChain("shouldCreateEntry"); chain.add(CreateVocabularyEntry.ID).set("name", vocabularyName).set("id", entryId); service.run(context, chain); assertTrue(vocabularySession.hasEntry(entryId)); }
Source:
<code>InterfaceTypeDefinition createInterface(Map<String, Object> input) { assertTrue(input.get("kind").equals("INTERFACE"), "wrong input"); InterfaceTypeDefinition.Builder interfaceTypeDefinition = InterfaceTypeDefinition.newInterfaceTypeDefinition().name((String) input.get("name")); interfaceTypeDefinition.description(toDescription(input)); if (input.containsKey("interfaces") && input.get("interfaces") != null) { interfaceTypeDefinition.implementz( <START> ((List<Map<String, Object>>) input.get("interfaces")).stream() <END> .map(this::createTypeIndirection) .collect(Collectors.toList()) ); } List<Map<String, Object>> fields = (List<Map<String, Object>>) input.get("fields"); interfaceTypeDefinition.definitions(createFields(fields)); return interfaceTypeDefinition.build(); }</code><technical_language>please map static function instead of streams</technical_language>

Target:
InterfaceTypeDefinition createInterface(Map<String, Object> input) { assertTrue(input.get("kind").equals("INTERFACE"), () -> "wrong input"); InterfaceTypeDefinition.Builder interfaceTypeDefinition = InterfaceTypeDefinition.newInterfaceTypeDefinition().name((String) input.get("name")); interfaceTypeDefinition.description(toDescription(input)); if (input.containsKey("interfaces") && input.get("interfaces") != null) { interfaceTypeDefinition.implementz( FpKit.map( (List<Map<String, Object>>) input.get("interfaces"), this::createTypeIndirection ) ); } List<Map<String, Object>> fields = (List<Map<String, Object>>) input.get("fields"); interfaceTypeDefinition.definitions(createFields(fields)); return interfaceTypeDefinition.build(); }
Source:
<code>private void setCompletedStatus(boolean completed) { mButton.setEnabled(!completed); <START> mButton.setText(getString(completed ? R.string.completed : R.string.complete_this_guide)); <END> }</code><technical_language>[TextView.setText()](<LINK_0> a resId getString() call removed</technical_language>

Target:
private void setCompletedStatus(boolean completed) { mButton.setEnabled(!completed); mButton.setText(completed ? R.string.completed : (App.get().getSite().isIfixit() ? R.string.i_did_it_success : R.string.complete_this_guide)); }
Source:
<code>public void getSupportFiles(OutputStream output, OrcsApi orcsApi) throws IOException { final ZipOutputStream zout = new ZipOutputStream(output); IResourceRegistry registry = orcsApi.getResourceRegistry(); ResourceToken tokens[] = {AtsRestTemplateTokens.BuiltEditorCss, AtsRestTemplateTokens.BuiltEditorJs}; for (ResourceToken token : tokens) { zout.putNextEntry(new ZipEntry(token.getName())); Lib.inputStreamToOutputStream(registry.getResource(token.getGuid()), zout); zout.closeEntry(); } <START> zout.close(); <END> }</code><technical_language>this in a finally clause in case of exception</technical_language>

Target:
public void getSupportFiles(OutputStream output, OrcsApi orcsApi) throws IOException { ZipOutputStream zout = null; try { zout = new ZipOutputStream(output); IResourceRegistry registry = orcsApi.getResourceRegistry(); ResourceToken tokens[] = {OseeTemplateTokens.BuiltEditorCss, OseeTemplateTokens.BuiltEditorJs}; for (ResourceToken token : tokens) { zout.putNextEntry(new ZipEntry(token.getName())); Lib.inputStreamToOutputStream(registry.getResource(token.getGuid()), zout); zout.closeEntry(); } } finally { Lib.close(zout); } }
Source:
<code>private void checkProxy(List<? extends Proxy> proxies, Attribution attribution, Map<String, List<String>> creatorMap) { if (!proxies.isEmpty()) { for (Proxy proxy : proxies) { <START> if (creatorMap.size() == 0 && isNotBlank(proxy.getDcCreator())) { <END> creatorMap.putAll(createCreatorMap(proxy.getDcCreator())); } if (attribution.getTitle().size() == 0 && isNotBlank(proxy.getDcTitle())) { attribution.setTitle(concatLangawareMap(proxy.getDcTitle())); } if (attribution.getDate().size() == 0 && isNotBlank(proxy.getYear())) { attribution.setDate(concatLangawareMap(proxy.getYear())); } } } }</code><technical_language>consider {Map}.isEmpty() instead of {Map}.size() == 0</technical_language>

Target:
private void checkProxy(List<? extends Proxy> proxies, Attribution attribution, Map<String, List<String>> creatorMap) { if (! proxies.isEmpty()) { for (Proxy proxy : proxies) { if (creatorMap.isEmpty() && isNotBlank(proxy.getDcCreator())) { creatorMap.putAll(createCreatorMap(proxy.getDcCreator())); } if (attribution.getTitle().isEmpty() && isNotBlank(proxy.getDcTitle())) { attribution.setTitle(concatLangawareMap(proxy.getDcTitle())); } if (attribution.getDate().isEmpty() && isNotBlank(proxy.getYear())) { attribution.setDate(concatLangawareMap(proxy.getYear())); } } } }
Source:
<code>protected JsonObject getBuild(String buildId, CloseableHttpClient httpclient, String authorization) throws IOException { String buildURL = getBuildsUrl(httpclient) + "?build_id=" + URLEncoder.encode(buildId, StandardCharsets.UTF_8.name()); HttpGet httpget = new HttpGet(buildURL); <START> httpget.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); <END> httpget.addHeader("Authorization", authorization); JsonObject response = StreamsRestUtils.getGsonResponse(httpclient, httpget); JsonObject build = null; JsonArray builds = array(response, "builds"); for (JsonElement iterBuildElem : builds) { JsonObject iterBuild = iterBuildElem.getAsJsonObject(); if (jstring(iterBuild, "id").equals(buildId)) build = iterBuild; } return build; }</code><technical_language>a nit, I this code is redundant. APPLICATION_JSON MIME type in getGsonResponse method. other places this happens</technical_language>

Target:
protected JsonObject getBuild(String buildId, CloseableHttpClient httpclient, String authorization) throws IOException { String buildURL = getBuildsUrl(httpclient) + "?build_id=" + URLEncoder.encode(buildId, StandardCharsets.UTF_8.name()); HttpGet httpget = new HttpGet(buildURL); httpget.addHeader("Authorization", authorization); JsonObject response = StreamsRestUtils.getGsonResponse(httpclient, httpget); JsonObject build = null; JsonArray builds = array(response, "builds"); for (JsonElement iterBuildElem : builds) { JsonObject iterBuild = iterBuildElem.getAsJsonObject(); if (jstring(iterBuild, "id").equals(buildId)) build = iterBuild; } return build; }
Source:
<code><START> @Bean @Qualifier("YouviewQueryExecutor") KnownTypeQueryExecutor youviewQueryExecutor() { <END> MongoLookupEntryStore lookupStore = new MongoLookupEntryStore(mongo.collection("lookup"), new NoLoggingPersistenceAuditLog(), readPreference); KnownTypeContentResolver mongoContentResolver = new MongoContentResolver(mongo, lookupStore); KnownTypeContentResolver cassandraContentResolver = new CassandraKnownTypeContentResolver(cassandra); AllFromPublishersEquivalentContentResolver allFromPublishersEquivalentContentResolver = new AllFromPublishersEquivalentContentResolver( mongoContentResolver, lookupStore ); KnownTypeQueryExecutor queryExecutor = new LookupResolvingQueryExecutor( cassandraContentResolver, allFromPublishersEquivalentContentResolver, lookupStore, cassandraEnabled ); queryExecutor = new UriFetchingQueryExecutor(localOrRemoteFetcher, queryExecutor, equivUpdater, ImmutableSet.of(FACEBOOK)); queryExecutor = new CurieResolvingQueryExecutor(queryExecutor); queryExecutor = new FilterActivelyPublishedOnlyQueryExecutor(queryExecutor); queryExecutor = new MergeOnOutputQueryExecutor(queryExecutor); queryExecutor = new FilterScheduleOnlyQueryExecutor(queryExecutor); return Boolean.parseBoolean(applicationsEnabled) ? new ApplicationConfigurationQueryExecutor(queryExecutor) : queryExecutor; }</code><technical_language>this bean in atlas feeds if place used</technical_language>

Target:
KnownTypeQueryExecutor youviewQueryExecutor() { MongoLookupEntryStore lookupStore = new MongoLookupEntryStore( mongo.collection("lookup"), new NoLoggingPersistenceAuditLog(), readPreference ); KnownTypeContentResolver mongoContentResolver = new MongoContentResolver(mongo, lookupStore); KnownTypeContentResolver cassandraContentResolver = new CassandraKnownTypeContentResolver(cassandra); AllFromPublishersEquivalentContentResolver allFromPublishersEquivalentContentResolver = new AllFromPublishersEquivalentContentResolver(mongoContentResolver, lookupStore); KnownTypeQueryExecutor queryExecutor = new LookupResolvingQueryExecutor( cassandraContentResolver, allFromPublishersEquivalentContentResolver, lookupStore, cassandraEnabled ); queryExecutor = new UriFetchingQueryExecutor (localOrRemoteFetcher, queryExecutor, equivUpdater, ImmutableSet.of(FACEBOOK)); queryExecutor = new CurieResolvingQueryExecutor(queryExecutor); queryExecutor = new FilterActivelyPublishedOnlyQueryExecutor(queryExecutor); queryExecutor = new MergeOnOutputQueryExecutor(queryExecutor); queryExecutor = new FilterScheduleOnlyQueryExecutor(queryExecutor); return Boolean.parseBoolean(applicationsEnabled) ? new ApplicationConfigurationQueryExecutor(queryExecutor) : queryExecutor; }
Source:
<code>public void onPositiveClick(CompileDialog dialog) { List<ChapterCard> toCompile = new ArrayList<>(); for (int i : dialog.getChapterInicies()) { toCompile.add(mChapterCardList.get(i)); mChapterCardList.get(i).destroyAudioPlayer(); } <START> mChaptersCompiled = dialog.getChapterInicies(); <END> CompileChapterTask task = new CompileChapterTask(COMPILE_CHAPTER_TASK, toCompile); mTaskFragment.executeRunnable(task, "Compiling Chapter", "Please wait...", false); }</code><technical_language>Typo dialog.getChapterIndicies()</technical_language>

Target:
public void onPositiveClick(CompileDialog dialog) { List<ChapterCard> toCompile = new ArrayList<>(); for (int i : dialog.getChapterIndicies()) { toCompile.add(mChapterCardList.get(i)); mChapterCardList.get(i).destroyAudioPlayer(); } mChaptersCompiled = dialog.getChapterIndicies(); CompileChapterTask task = new CompileChapterTask(COMPILE_CHAPTER_TASK, toCompile); mTaskFragment.executeRunnable(task, "Compiling Chapter", "Please wait...", false); }
Source:
<code>protected void onInitialize() { super.onInitialize(); getForm().add(new EqualPasswordInputValidator(password, confirmPassword)); IModel<String> labelModel = getLabel(); password.add(new AttributeModifier("placeholder", new StringResourceModel("password.placeholder.enter", labelModel))); password.setLabel(labelModel); confirmPassword.add(new AttributeModifier("placeholder", new StringResourceModel("password.placeholder.confirm", labelModel))); confirmPassword.setLabel(new StringResourceModel("password.confirm.label", labelModel)); <START> confirmPassword.add(AttributeModifier.append("style", "margin-top: 5px;")); <END> }</code><technical_language>AttributeModifier needed here? update PasswordsPanel.html</technical_language>

Target:
protected void onInitialize() { super.onInitialize(); getForm().add(new EqualPasswordInputValidator(password, confirmPassword)); IModel<String> labelModel = getLabel(); password.add(new AttributeModifier("placeholder", new StringResourceModel("password.placeholder.enter", labelModel))); password.setLabel(labelModel); confirmPassword.add(new AttributeModifier("placeholder", new StringResourceModel("password.placeholder.confirm", labelModel))); confirmPassword.setLabel(new StringResourceModel("password.confirm.label", labelModel)); }
Source:
<code>public BaseComponent[] transform(ProxiedPlayer player, BaseComponent... component) { <START> if ( component == null || component.length < 1 || component[0] == null ) <END> { return new BaseComponent[] { new TextComponent( "" ) }; } for ( BaseComponent root : component ) { if ( root.getExtra() != null && !root.getExtra().isEmpty() ) { List<BaseComponent> list = Lists.newArrayList( transform( player, root.getExtra().toArray( new BaseComponent[ root.getExtra().size() ] ) ) ); root.setExtra( list ); } if ( root instanceof ScoreComponent ) { transformScoreComponent( player, (ScoreComponent) root ); } } return component; }</code><technical_language>I code be: component == null || component.length < 1 || ( component.length == 1 && component[0] == null ) this validation in this method ideal, this allow like: transform(player, null, <component> accidentally valid</technical_language>

Target:
public BaseComponent[] transform(ProxiedPlayer player, BaseComponent... component) { if ( component == null || component.length < 1 || ( component.length == 1 && component[0] == null ) ) { return new BaseComponent[] { new TextComponent( "" ) }; } for ( BaseComponent root : component ) { if ( root.getExtra() != null && !root.getExtra().isEmpty() ) { List<BaseComponent> list = Lists.newArrayList( transform( player, root.getExtra().toArray( new BaseComponent[ root.getExtra().size() ] ) ) ); root.setExtra( list ); } if ( root instanceof ScoreComponent ) { transformScoreComponent( player, (ScoreComponent) root ); } } return component; }
Source:
<code>private long getCowVirtualSize(String id) throws IOException { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(id).execute(); try { int bytesRead = downloadImage.getInputStream().read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new RuntimeException("Unable to read image header: " + bytesRead); } } finally { downloadImage.getInputStream().close(); } ByteBuffer b = ByteBuffer.wrap(imgContent); <START> if (b.getInt() == 0x514649fb && b.getInt() == 2) { END> b.position(24); return b.getLong(); } throw new RuntimeException("Unable to recognize QCOW2 format"); }</code><technical_language>please extract constants</technical_language>

Target:
private long getCowVirtualSize(String id) throws IOException { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(id).execute(); try { int bytesRead = downloadImage.getInputStream().read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new RuntimeException("Unable to read image header: " + bytesRead); } } finally { downloadImage.getInputStream().close(); } ByteBuffer b = ByteBuffer.wrap(imgContent); if (b.getInt() == QCOW2_SIGNATURE && b.getInt() == QCOW2_VERSION) { b.position(QCOW2_SIZE_OFFSET); return b.getLong(); } throw new RuntimeException("Unable to recognize QCOW2 format"); }
Source:
<code>public void testQuestionFormattingChanges() throws IOException { String fileContent = "one,two" + Const.EOL + "Question 1," + Sanitizer.sanitizeForCsv("Hi What do you think about Calculus, Differential Classes ?"); XlsxFileDownloadResult download = new XlsxFileDownloadResult( "/page/instructorFeedbackResultsDownload", null, null, "Normal name", fileContent, Const.FeedbackSessionResultsDownloadTypes.XLSX); assertEquals(2, download.getWorkBook().getSheetAt(0).getLastRowNum()); <START> assertEquals(2, download.getWorkBook().getSheetAt(0).getRow(1).getLastCellNum()); <END> assertEquals(2, download.getWorkBook().getSheetAt(0).getRow(2).getLastCellNum()); assertTrue(download.getWorkBook().getSheetAt(0).getRow(2).getRowStyle().getFont().getBold()); assertEquals(15, download.getWorkBook().getSheetAt(0).getRow(2).getRowStyle().getFont().getFontHeightInPoints()); }</code><technical_language>For @Test method, extract repeated download.getWorkBook().getSheetAt(0) a local variable improve readability</technical_language>

Target:
public void testQuestionFormattingChanges() throws IOException { String fileContent = "one,two" + Const.EOL + "Question 1," + Sanitizer.sanitizeForCsv("Hi What do you think about Calculus, Differential Classes ?"); XlsxFileDownloadResult download = new XlsxFileDownloadResult( "/page/instructorFeedbackResultsDownload", null, null, "Normal name", fileContent, Const.FeedbackSessionResultsDownloadTypes.XLSX); XSSFSheet firstSheet = download.getWorkBook().getSheetAt(0); assertEquals(2, firstSheet.getLastRowNum()); assertEquals(2, firstSheet.getRow(1).getLastCellNum()); XSSFRow questionRow = firstSheet.getRow(2); assertEquals(2, questionRow.getLastCellNum()); assertTrue(questionRow.getRowStyle().getFont().getBold()); assertEquals(15, questionRow.getRowStyle().getFont().getFontHeightInPoints()); }
Source:
<code>public void loadTwoNewItems_withOneItemPreexistsInDatabase_addsTwoRowsInEntryAndOnlyOneRowInItemTable() { String item1 = "{\"register\":\"register1\",\"text\":\"Register1 Text\", \"phase\":\"alpha\"}"; Response r = send(item1); assertThat(r.getStatus(), equalTo(204)); String item2 = "{\"register\":\"register2\",\"text\":\"Register2 Text\", \"phase\":\"alpha\"}"; r = send(item1 + "\n" + item2); assertThat(r.getStatus(), equalTo(204)); String canonicalItem1 = new String(canonicalJsonMapper.writeToBytes(canonicalJsonMapper.readFromBytes(item1.getBytes()))); String canonicalItem2 = new String(canonicalJsonMapper.writeToBytes(canonicalJsonMapper.readFromBytes(item2.getBytes()))); List<String> entries = testEntryDAO.getAllHex(); assertThat(entries.size(), equalTo(3)); assertThat(entries.get(0), equalTo(DigestUtils.sha256Hex(canonicalItem1))); assertThat(entries.get(1), equalTo(DigestUtils.sha256Hex(canonicalItem1))); <START> assertThat(entries.get(2), equalTo(DigestUtils.sha256Hex(canonicalItem2))); <END> List<TestDBItem> items = testItemDAO.getItems(); assertThat(items.size(), equalTo(2)); assertThat(items.get(0).sha256hex, equalTo(DigestUtils.sha256Hex(canonicalItem1))); assertThat(items.get(0).contents, equalTo(canonicalItem1.getBytes())); assertThat(items.get(1).sha256hex, equalTo(DigestUtils.sha256Hex(canonicalItem2))); assertThat(items.get(1).contents, equalTo(canonicalItem2.getBytes())); }</code><technical_language>(badly-named) contains() matcher for this</technical_language>

Target:
public void loadTwoNewItems_withOneItemPreexistsInDatabase_addsTwoRowsInEntryAndOnlyOneRowInItemTable() { String item1 = "{\"register\":\"register1\",\"text\":\"Register1 Text\", \"phase\":\"alpha\"}"; Response r = send(item1); assertThat(r.getStatus(), equalTo(204)); String item2 = "{\"register\":\"register2\",\"text\":\"Register2 Text\", \"phase\":\"alpha\"}"; r = send(item1 + "\n" + item2); assertThat(r.getStatus(), equalTo(204)); byte[] canonicalItem1 = canonicalJsonMapper.writeToBytes(canonicalJsonMapper.readFromBytes(item1.getBytes())); byte[] canonicalItem2 = canonicalJsonMapper.writeToBytes(canonicalJsonMapper.readFromBytes(item2.getBytes())); List<Entry> entries = testEntryDAO.getAllEntries(); assertThat(entries, contains( new Entry(1, DigestUtils.sha256Hex(canonicalItem1)), new Entry(2, DigestUtils.sha256Hex(canonicalItem1)), new Entry(3, DigestUtils.sha256Hex(canonicalItem2)) ) ); List<TestDBItem> items = testItemDAO.getItems(); assertThat(items, contains( new TestDBItem(canonicalItem1), new TestDBItem(canonicalItem2) ) ); }
Source:
<code>protected boolean updateSelection(IStructuredSelection selection) { addAll(selectedDifferences, getSelectedDifferences(selection)); <START> Iterable<Diff> terminalStateDiffs = filter(selectedDifferences, new Predicate<Diff>() { <END> public boolean apply(Diff input) { return isInTerminalState(input); } }); if (!Iterables.isEmpty(terminalStateDiffs)) { return false; } if (this.adapterFactory != null) { contextualizeTooltip(); } return selection.toList().size() == selectedDifferences.size(); }</code><technical_language>Please hasState(MERGED, DISCARDED) instead of a new anonymous predicate. a static import of EMFComparePredicates of DifferenceState.*</technical_language>

Target:
protected boolean updateSelection(IStructuredSelection selection) { addAll(selectedDifferences, getSelectedDifferences(selection)); Iterable<Diff> terminalStateDiffs = filter(selectedDifferences, EMFComparePredicates.hasState(DifferenceState.MERGED, DifferenceState.DISCARDED)); if (!Iterables.isEmpty(terminalStateDiffs)) { return false; } if (this.adapterFactory != null) { contextualizeTooltip(); } return selection.toList().size() == selectedDifferences.size(); }
Source:
<code>private String customizeCompilationMessage(String text) { try { <START> int lineStart = text.indexOf(":") + ":".length(), lineEnd = text.indexOf(":", lineStart), <END> columnStart = lineEnd + ":".length(), columnEnd = text.indexOf(":", columnStart); String fileName = text.substring(0, text.indexOf(":")).trim(); int lineNumber = Integer.valueOf(text.substring(lineStart, lineEnd).trim()), columnNumber = Integer.valueOf(text.substring(columnStart, columnEnd).trim()); String customText = "<a href='javascript:openCM(\"" + fileName + "\"," + lineNumber + "," + columnNumber + ");'>"; customText += text.substring(0, columnEnd); customText += "</a>"; customText += text.substring(columnEnd); text = customText; } catch (IndexOutOfBoundsException ex) { } catch (NumberFormatException ex) { } return text; }</code><technical_language>declare variable a new line increase readability, currently is merging statement is assigned lineStart. lease put new line commas for variable declaration</technical_language>

Target:
private String customizeCompilationMessage(String text) { try { int lineStart = text.indexOf(":") + ":".length(); int lineEnd = text.indexOf(":", lineStart); int columnStart = lineEnd + ":".length(); int columnEnd = text.indexOf(":", columnStart); String fileName = text.substring(0, text.indexOf(":")).trim(); int lineNumber = Integer.valueOf(text.substring(lineStart, lineEnd).trim()); int columnNumber = Integer.valueOf(text.substring(columnStart, columnEnd).trim()); String customText = "<a href='javascript:openCM(\"" + fileName + "\"," + lineNumber + "," + columnNumber + ");'>"; customText += text.substring(0, columnEnd); customText += "</a>"; customText += text.substring(columnEnd); text = customText; } catch (IndexOutOfBoundsException ex) { } catch (NumberFormatException ex) { } return text; }
Source:
<code>protected void refreshServiceTaskList(ServiceTaskSummary serviceTaskSummary) { serviceTaskService.call((String serviceTaskName) -> { <START> notificationEvent.fire(new NotificationEvent(getRemoveTaskSuccess() + serviceTaskName)); <END> refreshData(); }).removeServiceTask(serviceTaskSummary); }</code><technical_language>suggestion notificationEvent.fire(new NotificationEvent(constants.RemoveTaskSuccess(serviceTaskName)));</technical_language>

Target:
protected void refreshServiceTaskList(ServiceTaskSummary serviceTaskSummary) { serviceTaskService.call((String serviceTaskName) -> { notificationEvent.fire(new NotificationEvent(getRemoveTaskSuccess(serviceTaskName))); refreshData(); }).removeServiceTask(serviceTaskSummary); }
Source:
<code>private boolean isHealthCheckDeactivated() { <START> if (!healthCheckDeactivated) { healthCheckDeactivated = Duration.between(timeCreated, Instant.now()).compareTo(HEALTH_CHECK_DEACTIVATION_PERIOD) < 0; } <END> return healthCheckDeactivated; }</code><technical_language>do java healthCheckDeactivated = healthCheckDeactivated || Duration.between(...).compareTo(...) < 0;</technical_language>

Target:
private boolean isHealthCheckDeactivated() { if (!healthCheckDeactivated) { return false; } boolean shouldBeDeactivated = healthCheckDeactivated && isWithinDeactivationWindow(); healthCheckDeactivated = shouldBeDeactivated; return shouldBeDeactivated; }
Source:
<code>public int getVisibility(IBinding member) { if (member instanceof ICPPSpecialization) { return getSpecializedBinding().getVisibility(((ICPPSpecialization)member).getSpecializedBinding()); } try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); <START> return v_public; END> } }</code><technical_language>return v_private this is default for classes getKey returns k_class in case of a CoreException</technical_language>

Target:
public int getVisibility(IBinding member) { if (member instanceof ICPPSpecialization) { return getSpecializedBinding().getVisibility(((ICPPSpecialization)member).getSpecializedBinding()); } try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); return v_private; } }
Source:
<code>public EventProcessorClient createEventProcessor() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder() .consumerGroup("consumer-group") .checkpointStore(new InMemoryCheckpointStore()) .processEvent(eventContext -> { <START> System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and " <END> + "sequence number of event = " + eventContext.getEventData().getSequenceNumber()); }) .processError(errorContext -> { System.out.printf("Error occurred in partition processor for partition {}, {}", errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable()); }) .connectionString(connectionString) .buildEventProcessorClient(); return eventProcessorClient; }</code><technical_language>nit: " sequence number of event = " +</technical_language>

Target:
public EventProcessorClient createEventProcessor() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder() .consumerGroup("consumer-group") .checkpointStore(new InMemoryCheckpointStore()) .processEvent(eventContext -> { System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + "and sequence number of event = " + eventContext.getEventData().getSequenceNumber()); }) .processError(errorContext -> { System.out.printf("Error occurred in partition processor for partition {}, {}", errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable()); }) .connectionString(connectionString) .buildEventProcessorClient(); return eventProcessorClient; }
Source:
<code>public void shouldGetAllDistinctStages() throws Exception { PipelineConfig pipelineCfgOne = configFileHelper.addPipeline("pipeline-one", "stage"); PipelineConfig pipelineCfgTwo = configFileHelper.addPipeline("pipeline-two", "stage"); Pipeline p1Run1 = dbHelper.schedulePipeline(pipelineCfgOne, new TimeProvider()); dbHelper.passStage(p1Run1.findStage("stage")); Pipeline p1Run2 = dbHelper.schedulePipeline(pipelineCfgOne, new TimeProvider()); dbHelper.passStage(p1Run2.findStage("stage")); Pipeline p2Run1 = dbHelper.schedulePipeline(pipelineCfgTwo, new TimeProvider()); dbHelper.passStage(p2Run1.findStage("stage")); Pipeline p2Run2 = dbHelper.schedulePipeline(pipelineCfgTwo, new TimeProvider()); dbHelper.passStage(p2Run2.findStage("stage")); List<StageConfigIdentifier> stages = stageService.getAllDistinctStages(); assertThat(stages.size(), is(3)); <START> assertStageWithPipeline(stages.get(0), "dev", "mingle"); <END> assertStageWithPipeline(stages.get(1), "stage", "pipeline-one"); assertStageWithPipeline(stages.get(2), "stage", "pipeline-two"); }</code><technical_language>constants PIPELINE_NAME STAGE_NAME instead of "mingle" "dev"</technical_language>

Target:
public void shouldGetAllDistinctStages() throws Exception { PipelineConfig pipelineCfgOne = configFileHelper.addPipeline("pipeline-one", "stage"); PipelineConfig pipelineCfgTwo = configFileHelper.addPipeline("pipeline-two", "stage"); Pipeline p1Run1 = dbHelper.schedulePipeline(pipelineCfgOne, new TimeProvider()); dbHelper.passStage(p1Run1.findStage("stage")); Pipeline p1Run2 = dbHelper.schedulePipeline(pipelineCfgOne, new TimeProvider()); dbHelper.passStage(p1Run2.findStage("stage")); Pipeline p2Run1 = dbHelper.schedulePipeline(pipelineCfgTwo, new TimeProvider()); dbHelper.passStage(p2Run1.findStage("stage")); Pipeline p2Run2 = dbHelper.schedulePipeline(pipelineCfgTwo, new TimeProvider()); dbHelper.passStage(p2Run2.findStage("stage")); List<StageConfigIdentifier> stages = stageService.getAllDistinctStages(); assertThat(stages.size(), is(3)); assertStageWithPipeline(stages.get(0), STAGE_NAME, PIPELINE_NAME); assertStageWithPipeline(stages.get(1), "stage", "pipeline-one"); assertStageWithPipeline(stages.get(2), "stage", "pipeline-two"); }
Source:
<code>private void doPutAssets(final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload, final String[] resources) { this.findAssets(); final String assetPid = resources[1]; final String channelName = resources[2]; final Asset asset = this.assets.get(assetPid); final AssetConfiguration configuration = asset.getAssetConfiguration(); final Map<String, Channel> assetConfiguredChannels = configuration.getAssetChannels(); if (assetConfiguredChannels != null) { final String userValue = (String) reqPayload.getMetric("value"); final String userType = (String) reqPayload.getMetric("type"); <START> ChannelRecord ChannelRecord = null; <END> boolean flag = true; try { ChannelRecord = this.createWriteRecord(channelName, userValue, userType); } catch (final IllegalArgumentException e) { flag = false; ChannelRecord.setChannelStatus( new ChannelStatus(ChannelFlag.FAILURE, message.valueTypeConversionError(), e)); ChannelRecord.setTimestamp(System.currentTimeMillis()); } List<ChannelRecord> ChannelRecords = Arrays.asList(ChannelRecord); try { if (flag) { asset.write(ChannelRecords); } } catch (final KuraException e) { respPayload.addMetric(message.errorMessage(), message.connectionException()); } this.prepareResponse(respPayload, ChannelRecords); } }</code><technical_language>advisable start variable names case</technical_language>

Target:
private void doPutAssets(final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload, final String[] resources) { this.findAssets(); final String assetPid = resources[1]; final String channelName = resources[2]; final Asset asset = this.assets.get(assetPid); final AssetConfiguration configuration = asset.getAssetConfiguration(); final Map<String, Channel> assetConfiguredChannels = configuration.getAssetChannels(); if (assetConfiguredChannels != null) { final String userValue = (String) reqPayload.getMetric("value"); final String userType = (String) reqPayload.getMetric("type"); ChannelRecord channelRecord = null; boolean flag = true; try { channelRecord = this.createWriteRecord(channelName, userValue, userType); } catch (final IllegalArgumentException e) { flag = false; channelRecord.setChannelStatus( new ChannelStatus(ChannelFlag.FAILURE, message.valueTypeConversionError(), e)); channelRecord.setTimestamp(System.currentTimeMillis()); } List<ChannelRecord> channelRecords = Arrays.asList(channelRecord); try { if (flag) { asset.write(channelRecords); } } catch (final KuraException e) { respPayload.addMetric(message.errorMessage(), message.connectionException()); } this.prepareResponse(respPayload, channelRecords); } }
Source:
<code>InputFile.Status status(String projectKeyWithBranch, DefaultInputFile inputFile, String hash) { FileData fileDataPerPath = projectRepositories.fileData(projectKeyWithBranch, inputFile.relativePath()); if (fileDataPerPath == null) { return InputFile.Status.ADDED; <START> } <END> String previousHash = fileDataPerPath.hash(); if (StringUtils.equals(hash, previousHash)) { return InputFile.Status.SAME; } if (StringUtils.isEmpty(previousHash)) { return InputFile.Status.ADDED; } if (!scmChangedFiles.verifyChanged(inputFile.path())) { return InputFile.Status.SAME; } return InputFile.Status.CHANGED; }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "relativePath"; is deprecated. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
InputFile.Status status(String projectKeyWithBranch, DefaultInputFile inputFile, String hash) { FileData fileDataPerPath = projectRepositories.fileData(projectKeyWithBranch, inputFile.relativePath()); if (fileDataPerPath == null) { return checkChanged(ADDED, inputFile); } String previousHash = fileDataPerPath.hash(); if (StringUtils.equals(hash, previousHash)) { return SAME; } if (StringUtils.isEmpty(previousHash)) { return checkChanged(ADDED, inputFile); } return checkChanged(CHANGED, inputFile); }
Source:
<code>public boolean onboarded() { <START> return thingIfApi.onboarded(); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public boolean onboarded() { return this.thingIfApi.onboarded(); }
Source:
<code>public static ModelRef modelRef(ResolvedType resolved, ModelContext modelContext, TypeNameExtractor nameExtractor) { if (isContainerType(resolved)) { ResolvedType collectionElementType = collectionElementType(resolved); String elementTypeName = nameExtractor.typeName(fromParent(modelContext, collectionElementType)); AllowableValues allowableValues = ResolvedTypes.allowableValues(resolved); return new ModelRef(containerType(resolved), elementTypeName, allowableValues); } if (isMapType(resolved)) { String elementTypeName = nameExtractor.typeName(fromParent(modelContext, mapValueType(resolved))); return new ModelRef("Map", elementTypeName, true); } if (Void.class.equals(resolved.getErasedType()) || Void.TYPE.equals(resolved.getErasedType())) { return new ModelRef("void"); } AllowableValues allowableValues = ResolvedTypes.allowableValues(resolved); String typeName = nameExtractor.typeName(fromParent(modelContext, resolved)); <START> return new ModelRef(typeName, null, allowableValues); <END> }</code><technical_language>provide a builder for ModelRef... :cry: for null in middle</technical_language>

Target:
public static ModelRef modelRef(ResolvedType resolved, ModelContext modelContext, TypeNameExtractor nameExtractor) { if (isContainerType(resolved)) { ResolvedType collectionElementType = collectionElementType(resolved); String elementTypeName = nameExtractor.typeName(fromParent(modelContext, collectionElementType)); AllowableValues allowableValues = ResolvedTypes.allowableValues(resolved); return new ModelRef(containerType(resolved), elementTypeName, allowableValues); } if (isMapType(resolved)) { String elementTypeName = nameExtractor.typeName(fromParent(modelContext, mapValueType(resolved))); return new ModelRef("Map", elementTypeName, true); } if (Void.class.equals(resolved.getErasedType()) || Void.TYPE.equals(resolved.getErasedType())) { return new ModelRef("void"); } AllowableValues allowableValues = ResolvedTypes.allowableValues(resolved); String typeName = nameExtractor.typeName(fromParent(modelContext, resolved)); return new ModelRef(typeName, allowableValues); }
Source:
<code>private IASTName getLastInQualified(IASTName name) { <START> if (name instanceof ICPPASTQualifiedName) { <END> name= name.getLastName(); } return name; }</code><technical_language>Redundant condition</technical_language>

Target:
private IASTName getLastInQualified(IASTName name) { return name.getLastName(); }
Source:
<code>public GenericPartitioningSpiller( List<Type> types, PartitionFunction partitionFunction, SpillContext spillContext, AggregatedMemoryContext memoryContext, SingleStreamSpillerFactory spillerFactory) { requireNonNull(spillContext, "spillContext is null"); <START> this.types = requireNonNull(types, "types is null"); <END> this.partitionFunction = requireNonNull(partitionFunction, "partitionFunction is null"); requireNonNull(memoryContext, "memoryContext is null"); closer.register(memoryContext::close); Supplier<LocalMemoryContext> childMemoryContextSupplier = synchronizedMemoryContext(memoryContext)::newLocalMemoryContext; int partitionCount = partitionFunction.getPartitionCount(); this.spillers = new SingleStreamSpiller[partitionCount]; this.pageBuilders = new PageBuilder[partitionCount]; for (int partition = 0; partition < partitionCount; partition++) { pageBuilders[partition] = new PageBuilder(types); spillers[partition] = closer.register(spillerFactory.create(types, spillContext, childMemoryContextSupplier.get())); } }</code><technical_language>Defensive copy</technical_language>

Target:
public GenericPartitioningSpiller( List<Type> types, PartitionFunction partitionFunction, SpillContext spillContext, AggregatedMemoryContext memoryContext, SingleStreamSpillerFactory spillerFactory) { requireNonNull(spillContext, "spillContext is null"); this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); this.partitionFunction = requireNonNull(partitionFunction, "partitionFunction is null"); this.spillerFactory = requireNonNull(spillerFactory, "spillerFactory is null"); this.spillContext = closer.register(requireNonNull(spillContext, "spillContext is null")); requireNonNull(memoryContext, "memoryContext is null"); closer.register(memoryContext::close); this.memoryContext = synchronizedMemoryContext(memoryContext); int partitionCount = partitionFunction.getPartitionCount(); this.pageBuilders = new PageBuilder[partitionCount]; this.spillers = new Optional[partitionCount]; for (int partition = 0; partition < partitionCount; partition++) { pageBuilders[partition] = new PageBuilder(types); spillers[partition] = Optional.empty(); } }
Source:
<code>public Card getCard() { _checkDay(); if (!mHaveQueues) { reset(); <START> mNextCard = null; <END> } Card card; if (mNextCard != null) { card = mNextCard; mNextCard = null; } else { card = _getCard(); } if (card != null) { mCol.log(card); mReps += 1; card.startTimer(); } backgroundNextCard(); return card; }</code><technical_language>reset() sets mNextCard null immediately I this line is unnecessary</technical_language>

Target:
public Card getCard() { _checkDay(); if (!mHaveQueues) { reset(); } Card card = loadNextCard(false); mNextCard = null; if (card != null) { mCol.log(card); mReps += 1; decrementCounts(card); card.startTimer(); } CollectionTask.launchCollectionTask(CollectionTask.TASK_TYPE_PRE_LOAD_CARD); return card; }
Source:
<code><START> public Long getPaymentWorksFieldMappingId() { <END> return paymentWorksFieldMappingId; }</code><technical_language>this need Object Long instead of primitive long? issues null</technical_language>

Target:
public long getPaymentWorksFieldMappingId() { return paymentWorksFieldMappingId; }
Source:
<code>public void run() { progressMonitor.setIndeterminate(true); progressMonitor.setProgress(0); Case currentCase = Case.getCurrentCase(); String imageWriterPath = ""; if (imageWriterSettings != null) { imageWriterPath = imageWriterSettings.getPath(); } List<String> errorMessages = new ArrayList<>(); List<Content> newDataSources = new ArrayList<>(); try { currentCase.getSleuthkitCase().acquireSingleUserCaseWriteLock(); synchronized (tskAddImageProcessLock) { if (!tskAddImageProcessStopped) { tskAddImageProcess = currentCase.getSleuthkitCase().makeAddImageProcess(timeZone, true, ignoreFatOrphanFiles, imageWriterPath); } else { return; } } Thread progressUpdateThread = new Thread(new ProgressUpdater(progressMonitor, tskAddImageProcess)); progressUpdateThread.start(); <START> runAddImageProcess(errorMessages); <END> commitOrRevertAddImageProcess(currentCase, errorMessages, newDataSources); progressMonitor.setProgress(100); } finally { currentCase.getSleuthkitCase().releaseSingleUserCaseWriteLock(); DataSourceProcessorCallback.DataSourceProcessorResult result; if (criticalErrorOccurred) { result = DataSourceProcessorResult.CRITICAL_ERRORS; } else if (!errorMessages.isEmpty()) { result = DataSourceProcessorResult.NONCRITICAL_ERRORS; } else { result = DataSourceProcessorResult.NO_ERRORS; } callback.done(result, errorMessages, newDataSources); } }</code><technical_language>this removed? unrelated sector size. broken</technical_language>

Target:
public void run() { progressMonitor.setIndeterminate(true); progressMonitor.setProgress(0); Case currentCase = Case.getCurrentCase(); String imageWriterPath = ""; if (imageWriterSettings != null) { imageWriterPath = imageWriterSettings.getPath(); } List<String> errorMessages = new ArrayList<>(); List<Content> newDataSources = new ArrayList<>(); try { currentCase.getSleuthkitCase().acquireSingleUserCaseWriteLock(); synchronized (tskAddImageProcessLock) { if (!tskAddImageProcessStopped) { tskAddImageProcess = currentCase.getSleuthkitCase().makeAddImageProcess(timeZone, true, ignoreFatOrphanFiles, imageWriterPath); } else { return; } } Thread progressUpdateThread = new Thread(new ProgressUpdater(progressMonitor, tskAddImageProcess)); progressUpdateThread.start(); runAddImageProcess(errorMessages); progressUpdateThread.interrupt(); commitOrRevertAddImageProcess(currentCase, errorMessages, newDataSources); progressMonitor.setProgress(100); } finally { currentCase.getSleuthkitCase().releaseSingleUserCaseWriteLock(); DataSourceProcessorCallback.DataSourceProcessorResult result; if (criticalErrorOccurred) { result = DataSourceProcessorResult.CRITICAL_ERRORS; } else if (!errorMessages.isEmpty()) { result = DataSourceProcessorResult.NONCRITICAL_ERRORS; } else { result = DataSourceProcessorResult.NO_ERRORS; } callback.done(result, errorMessages, newDataSources); } }
Source:
<code>public void startDetection(String container, MessageProcessor<LogMessage> containerLogProcessor) { if (needStartOOMDetector()) { if (cgroupMount == null) { LOG.warn("System doesn't support OOM events"); return; } try { final long memory = dockerConnector.inspectContainer(container).getConfig().getMemory(); final OOMDetector oomDetector = new OOMDetector(container, containerLogProcessor, memory); <START> oomDetectors.put(container, oomDetector); <END> oomDetector.start(); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } } }</code><technical_language>thread safe</technical_language>

Target:
public void startDetection(String container, MessageProcessor<LogMessage> containerLogProcessor) { if (needStartOOMDetector(container)) { if (cgroupMount == null) { LOG.warn("System doesn't support OOM events"); return; } try { final long memory = dockerConnector.inspectContainer(container).getConfig().getMemory(); OOMDetector oomDetector = new OOMDetector(container, containerLogProcessor, memory); oomDetectors.putIfAbsent(container, oomDetector); oomDetector = oomDetectors.get(container); oomDetector.start(); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } } }
Source:
<code>public Response fault() { return Response.status(ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "code", 0, 0)).entity( fault(ParametersHelper.getParameter(httpHeaders, uriInfo, "reason"), <START> ParametersHelper.getParameter(httpHeaders, uriInfo, "detail"))).build(); <END> }</code><technical_language>This line is long, suggest some local variables, helps step step debugging well</technical_language>

Target:
public Response fault() { int code = ParametersHelper.getIntegerParameter(httpHeaders, uriInfo, "code", 0, 0); String reason = ParametersHelper.getParameter(httpHeaders, uriInfo, "reason"); String detail = ParametersHelper.getParameter(httpHeaders, uriInfo, "detail"); return Response.status(code).entity(fault(reason, detail)).build(); }