auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shutdown() { try { logger.info("shutdown started"); if (jmxServer != null) jmxServer.stop(); if (jvmMetrics != null) jvmMetrics.stop(); if (reporters != null) for (Map.Entry<String, MetricsReporter> reporterEntry : reporters.entrySet()) reporterEntry.getValue().stop(); if(networkServer != null) networkServer.shutdown(); if(requestHandlerPool != null) requestHandlerPool.shutdown(); if (scheduler != null) { scheduler.shutdown(); } if (storeManager != null) { storeManager.shutdown(); } <START> shutdownLatch.countDown(); <END> logger.info("shutdown completed"); } catch (Exception e) { logger.error("Error while shutting down server {}", e); } }</code><technical_language>is intentional suthdownLatch.countDown in a final clause? Current behavior is for server running in face of error for awaitShutdown() continue blocking (i think). if this is intended behaviro not</technical_language>

Target:
public void shutdown() { try { logger.info("shutdown started"); if (jmxServer != null) jmxServer.stop(); if (jvmMetrics != null) jvmMetrics.stop(); if (reporters != null) for (Map.Entry<String, MetricsReporter> reporterEntry : reporters.entrySet()) reporterEntry.getValue().stop(); if(networkServer != null) networkServer.shutdown(); if(requestHandlerPool != null) requestHandlerPool.shutdown(); if (scheduler != null) { scheduler.shutdown(); } if (storeManager != null) { storeManager.shutdown(); } logger.info("shutdown completed"); } catch (Exception e) { logger.error("Error while shutting down server {}", e); } finally { shutdownLatch.countDown(); } }
Source:
<code>public boolean isMiscellaneous() { <START> return miscellaneous; <END> }</code><technical_language>this., for remaining methods</technical_language>

Target:
public boolean isMiscellaneous() { return this.miscellaneous; }
Source:
<code>public MicrometerMetricsCaptor(MeterRegistry meterRegistry) { <START> Assert.notNull(meterRegistry, "meterRgistry cannot be null"); <END> this.meterRegistry = meterRegistry; }</code><technical_language>Wrong indention for ctor name</technical_language>

Target:
public MicrometerMetricsCaptor(MeterRegistry meterRegistry) { Assert.notNull(meterRegistry, "meterRegistry cannot be null"); this.meterRegistry = meterRegistry; }
Source:
<code>public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = ++lastScenarioId; s.setId(id); } else { id = s.getId(); } m.addScenario(s); scenarios.put(id, s); <START> addReport(String.format("New scenario '%s' will occur on %s.", <END> s.getName(), MekHQ.getMekHQOptions().getDisplayFormattedDate(s.getDate()))); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }</code><technical_language>Localize</technical_language>

Target:
public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = ++lastScenarioId; s.setId(id); } else { id = s.getId(); } m.addScenario(s); scenarios.put(id, s); addReport(MessageFormat.format( resources.getString("newAtBMission.format"), s.getName(), MekHQ.getMekHQOptions().getDisplayFormattedDate(s.getDate()))); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }
Source:
<code>public void testClientIsInstrumentedWithTracer() throws InterruptedException { server.enqueue(new MockResponse().setBody("\"server\"")); String parentSpanId = Tracer.startSpan("").getSpanId(); String traceId = Tracer.getTraceId(); List<String> spanIds = Lists.newArrayList(); List<Span> spans = Lists.newArrayList(); Tracer.subscribe(TracerTest.class.getName(), span -> { spanIds.add(span.getSpanId()); spans.add(span); }); service.param("somevalue"); Tracer.unsubscribe(TracerTest.class.getName()); assertThat(spans).containsExactly( span(spans.get(0), traceId, spanIds.get(2), SpanType.LOCAL, "OkHttp: limiter-enqueue"), <START> span(spans.get(1), traceId, spanIds.get(2), SpanType.LOCAL, "OkHttp: limiter-run"), <END> span(spans.get(2), traceId, parentSpanId, SpanType.LOCAL, "OkHttp: enqueue"), span(spans.get(3), traceId, spanIds.get(4), SpanType.CLIENT_OUTGOING, "OkHttp: GET /{param}"), span(spans.get(4), traceId, spanIds.get(1), SpanType.LOCAL, "OkHttp: dispatcher")); RecordedRequest request = server.takeRequest(); assertThat(request.getHeader(TraceHttpHeaders.TRACE_ID)).isEqualTo(traceId); assertThat(request.getHeader(TraceHttpHeaders.SPAN_ID)).isNotEqualTo(parentSpanId); }</code><technical_language>prefer remove/deprecate AsyncTracer in favor of proper APIs support want measure. <LINK_0></technical_language>

Target:
public void testClientIsInstrumentedWithTracer() throws InterruptedException { server.enqueue(new MockResponse().setBody("\"server\"")); String parentSpanId = Tracer.startSpan("").getSpanId(); String traceId = Tracer.getTraceId(); List<String> spanIds = Lists.newArrayList(); List<Span> spans = Lists.newArrayList(); Tracer.subscribe(TracerTest.class.getName(), span -> { spanIds.add(span.getSpanId()); spans.add(span); }); service.param("somevalue"); Tracer.unsubscribe(TracerTest.class.getName()); assertThat(spans).containsExactly( span(spans.get(0), traceId, spanIds.get(2), SpanType.LOCAL, "OkHttp: limiter-enqueue"), span(spans.get(1), traceId, spanIds.get(2), SpanType.LOCAL, "OkHttp: limiter-run"), span(spans.get(2), traceId, parentSpanId, SpanType.LOCAL, "OkHttp: enqueue"), span(spans.get(3), traceId, spanIds.get(4), SpanType.CLIENT_OUTGOING, "OkHttp: GET /{param}"), span(spans.get(4), traceId, spanIds.get(2), SpanType.LOCAL, "OkHttp: dispatcher")); RecordedRequest request = server.takeRequest(); assertThat(request.getHeader(TraceHttpHeaders.TRACE_ID)).isEqualTo(traceId); assertThat(request.getHeader(TraceHttpHeaders.SPAN_ID)).isNotEqualTo(parentSpanId); }
Source:
<code>private com.jcabi.http.Request request(final Request req, final String dest) throws IOException { final String method = new RqMethod.Base(req).method(); com.jcabi.http.Request proxied = new JdkRequest(dest) .method(method); final RqHeaders.Base headers = new RqHeaders.Base(req); for (final String name : headers.names()) { if ("content-length".equals(name.toLowerCase(Locale.ENGLISH))) { continue; } if (isHost(name)) { proxied = proxied.header(name, this.host); continue; } for (final String value : headers.header(name)) { proxied = proxied.header(name, value); } } <START> if (Arrays.asList("POST", "PUT").contains(method)) { <END> final ByteArrayOutputStream output = new ByteArrayOutputStream(); new RqPrint(new RqLengthAware(req)).printBody(output); proxied = proxied.body().set(output.toByteArray()).back(); } return proxied; }</code><technical_language>@bdragan them? PATCH, for example? I do this filtering-out all. of a body</technical_language>

Target:
private com.jcabi.http.Request request(final Request req, final String dest) throws IOException { final String method = new RqMethod.Base(req).method(); com.jcabi.http.Request proxied = new JdkRequest(dest) .method(method); final RqHeaders.Base headers = new RqHeaders.Base(req); for (final String name : headers.names()) { if ("content-length".equals(name.toLowerCase(Locale.ENGLISH))) { continue; } if (isHost(name)) { proxied = proxied.header(name, this.host); continue; } for (final String value : headers.header(name)) { proxied = proxied.header(name, value); } } if (headers.header("Content-Length").iterator().hasNext() || headers.header("Transfer-Encoding").iterator().hasNext()) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); new RqPrint(new RqLengthAware(req)).printBody(output); proxied = proxied.body().set(output.toByteArray()).back(); } return proxied; }
Source:
<code>void roundtripWithArticleMonths() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/articleWithMonths.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences, fileMonitor).parse(Importer.getReader(testBibtexFile, encoding)); when(preferences.getEncoding()).thenReturn(encoding); when(preferences.isSaveInOriginalOrder()).thenReturn(true); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData(), new Defaults(BibDatabaseMode.BIBTEX)); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); <START> assertEquals(Files.asCharSource(testBibtexFile.toFile(), Charsets.UTF_8).read(), stringWriter.toString()); <END> }</code><technical_language>This is in java: Files.readString</technical_language>

Target:
void roundtripWithArticleMonths() throws Exception { Path testBibtexFile = Paths.get("src/test/resources/testbib/articleWithMonths.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences, fileMonitor).parse(Importer.getReader(testBibtexFile, encoding)); when(preferences.getEncoding()).thenReturn(encoding); when(preferences.isSaveInOriginalOrder()).thenReturn(true); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData(), new Defaults(BibDatabaseMode.BIBTEX)); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); }
Source:
<code>protected void endVmCommand() { initializeObjectState(); if (getParameters().getTaskGroupSuccess()) { getSnapshotDao().remove(getParameters().getSnapshotId()); } else { List<String> failedToRemoveDisks = new ArrayList<>(); for (VdcActionParametersBase parametersBase : getParameters().getImagesParameters()) { <START> ImagesContainterParametersBase imagesParams = (ImagesContainterParametersBase) parametersBase; <END> if (imagesParams.getTaskGroupSuccess()) { Snapshot snapshotWithoutImage = ImagesHandler.prepareSnapshotConfigWithoutImageSingleImage( getParameters().getSnapshotId(), imagesParams.getImageId()); getSnapshotDao().update(snapshotWithoutImage); } else { log.errorFormat("Could not delete image {0} from snapshot {1}", getParameters().getSnapshotId(), imagesParams.getImageId()); DiskImage diskImage = getDiskImageDao().getSnapshotById(imagesParams.getImageId()); failedToRemoveDisks.add(diskImage.getDiskAlias()); } } if (!failedToRemoveDisks.isEmpty()) { addCustomValue("DiskAliases", StringUtils.join(failedToRemoveDisks, ", ")); AuditLogDirector.log(this, AuditLogType.USER_REMOVE_SNAPSHOT_FINISHED_FAILURE_PARTIAL_SNAPSHOT); } getSnapshotDao().updateStatus(getParameters().getSnapshotId(), SnapshotStatus.OK); } super.endVmCommand(); }</code><technical_language>in case of snapshot memory, get other type of parameters fail casting</technical_language>

Target:
protected void endVmCommand() { initializeObjectState(); if (getParameters().getTaskGroupSuccess()) { getSnapshotDao().remove(getParameters().getSnapshotId()); } else { List<String> failedToRemoveDisks = new ArrayList<>(); Snapshot snapshot = getSnapshotDao().get(getParameters().getSnapshotId()); for (VdcActionParametersBase parameters : getParameters().getImagesParameters()) { ImagesContainterParametersBase imagesParams = (parameters instanceof ImagesContainterParametersBase ? (ImagesContainterParametersBase) parameters : null); if (imagesParams == null) { continue; } if (imagesParams.getTaskGroupSuccess()) { snapshot = ImagesHandler.prepareSnapshotConfigWithoutImageSingleImage( snapshot, imagesParams.getImageId()); } else { log.errorFormat("Could not delete image {0} from snapshot {1}", imagesParams.getImageId(), getParameters().getSnapshotId()); DiskImage diskImage = getDiskImageDao().getSnapshotById(imagesParams.getImageId()); failedToRemoveDisks.add(diskImage.getDiskAlias()); } } snapshot.setMemoryVolume(""); getSnapshotDao().update(snapshot); if (!failedToRemoveDisks.isEmpty()) { addCustomValue("DiskAliases", StringUtils.join(failedToRemoveDisks, ", ")); AuditLogDirector.log(this, AuditLogType.USER_REMOVE_SNAPSHOT_FINISHED_FAILURE_PARTIAL_SNAPSHOT); } getSnapshotDao().updateStatus(getParameters().getSnapshotId(), SnapshotStatus.OK); } super.endVmCommand(); }
Source:
<code>public Map<String, Object> getPropertiesAndTypeValues(String nodeId, Alien4CloudApplication toscaApplication, String requirementId, String computeName) { Optional<RelationshipTemplate> optionalRelationshipTemplate = findRelationshipRequirement(nodeId, toscaApplication, requirementId); if (optionalRelationshipTemplate.isPresent()) { RelationshipTemplate relationshipTemplate = optionalRelationshipTemplate.get(); <START> if (relationshipTemplate.getType().equals("tosca.relationships.Configure")) { <END> Map<String, Object> relationProperties = getRelationProperties(nodeId, computeName, toscaApplication, relationshipTemplate); return getPropertiesAndTypedValues(relationshipTemplate, relationProperties, computeName); } } return Collections.emptyMap(); }</code><technical_language>Switch this update relationship.yaml tomcat-mysql-on-one-compute.yaml brooklyn.relationships.Configure instead</technical_language>

Target:
public Map<String, Object> getPropertiesAndTypeValues(String nodeId, Alien4CloudApplication toscaApplication, String requirementId, String computeName) { Optional<RelationshipTemplate> optionalRelationshipTemplate = findRelationshipRequirement(nodeId, toscaApplication, requirementId); if (optionalRelationshipTemplate.isPresent()) { RelationshipTemplate relationshipTemplate = optionalRelationshipTemplate.get(); if (relationshipTemplate.getType().equals("brooklyn.relationships.Configure")) { Map<String, Object> relationProperties = getRelationProperties(nodeId, computeName, toscaApplication, relationshipTemplate); return getPropertiesAndTypedValues(relationshipTemplate, relationProperties, computeName); } } return Collections.emptyMap(); }
Source:
<code>@Override public void onNegativeClicked(@NonNull String instanceTag) { switch (instanceTag) { case ASYNC_PROMO_DIALOG_TAG: PromoDialog promoDialog = (PromoDialog) getSupportFragmentManager().findFragmentByTag(instanceTag); <START> if (promoDialog != null) { <END> promoDialog.dismiss(); } break; case TAG_PUBLISH_CONFIRMATION_DIALOG: case TAG_REMOVE_FAILED_UPLOADS_DIALOG: BasicYesNoFragmentDialog basicDialog = (BasicYesNoFragmentDialog) getSupportFragmentManager() .findFragmentByTag(instanceTag); if (basicDialog != null) { basicDialog.dismiss(); } break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }</code><technical_language>consider adding dismiss call PromoDialog class. I of scenario in dialog shown user clicks of buttons. WDYT</technical_language>

Target:
@Override public void onNegativeClicked(@NonNull String instanceTag) { switch (instanceTag) { case ASYNC_PROMO_DIALOG_TAG: case TAG_PUBLISH_CONFIRMATION_DIALOG: case TAG_REMOVE_FAILED_UPLOADS_DIALOG: break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }
Source:
<code>protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException { final String attrName = operation.require(ModelDescriptionConstants.NAME).asString(); ProtocolServerMetrics metric = ProtocolServerMetrics.getStat(attrName); if (metric == null) { context.getFailureDescription().set(String.format("Unknown metric %s", attrName)); } else { final ServiceController<?> controller = context.getServiceRegistry(false) .getService(EndpointUtils.getServiceName(operation, name)); ProtocolServerService service = (ProtocolServerService) controller.getService(); ModelNode result = new ModelNode(); switch (metric) { case BYTES_READ: result.set(service.getTransport().getTotalBytesRead()); break; case BYTES_WRITTEN: <START> result.set(service.getTransport().getTotalBytesWritten()); <END> break; case TRANSPORT_RUNNING: result.set(((AbstractProtocolServer)service.getValue()).getTransportStatus() == ComponentStatus.RUNNING); break; } context.getResult().set(result); } context.stepCompleted(); }</code><technical_language>need get Transport AbstractProtocolServer. service, instance instantiated endpoint</technical_language>

Target:
protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException { final String attrName = operation.require(ModelDescriptionConstants.NAME).asString(); ProtocolServerMetrics metric = ProtocolServerMetrics.getStat(attrName); if (metric == null) { context.getFailureDescription().set(String.format("Unknown metric %s", attrName)); } else { final ServiceController<?> controller = context.getServiceRegistry(false) .getService(EndpointUtils.getServiceName(operation, name)); ProtocolServerService service = (ProtocolServerService) controller.getService(); AbstractProtocolServer server = (AbstractProtocolServer) service.getValue(); ModelNode result = new ModelNode(); switch (metric) { case BYTES_READ: result.set(server.getTransport().getTotalBytesRead()); break; case BYTES_WRITTEN: result.set(server.getTransport().getTotalBytesWritten()); break; case TRANSPORT_RUNNING: result.set(server.getTransportStatus() == ComponentStatus.RUNNING); break; } context.getResult().set(result); } context.stepCompleted(); }
Source:
<code>private void addViewerToSelectionProvider() { IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider instanceof CompareEditorSelectionProvider) { EMFCompareEditorSelectionProviderWrapper compareProvider = new EMFCompareEditorSelectionProviderWrapper( (CompareEditorSelectionProvider)provider); part.getSite().setSelectionProvider(compareProvider); <START> compareProvider.addViewers(Arrays.asList((Viewer)getViewer()), getViewer()); <END> } }</code><technical_language>Please declare method addViewers(List<? extends Viewer>...) remove cast (Viewer) here</technical_language>

Target:
private void addViewerToSelectionProvider() { IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider instanceof CompareEditorSelectionProvider) { EMFCompareEditorSelectionProviderWrapper compareProvider = new EMFCompareEditorSelectionProviderWrapper( (CompareEditorSelectionProvider)provider); part.getSite().setSelectionProvider(compareProvider); compareProvider.addViewers(Arrays.asList(getViewer()), getViewer()); } }
Source:
<code>protected ISeries addSeries(String seriesName) { if (seriesName == null) { return null; } ISeriesSet seriesSet = getSwtChart().getSeriesSet(); int seriesCount = seriesSet.getSeries().length; ICommonXAxisModel currentModel = getModel(); IYSeries ySeries = currentModel.findSeries(seriesName); if (ySeries == null) { setSeries(seriesName, new double[currentModel.getXAxis().length]); currentModel = getModel(); ySeries = currentModel.findSeries(seriesName); } if (ySeries == null) { return null; } <START> String colorTxt = ySeries.getColor(); Color color = getColor(seriesName, colorTxt); switch (ySeries.getSeriesType()) { case IYSeries.BAR: IBarSeries barSeries = (IBarSeries) seriesSet.createSeries(SeriesType.BAR, seriesName); barSeries.enableStack(true); barSeries.setBarColor(color); barSeries.setBarPadding(0); barSeries.setVisible(true); return barSeries; default: ILineSeries lineSeries = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, seriesName); boolean isScatter = IYSeries.SCATTER.equals(ySeries.getSeriesType()); lineSeries.enableArea(IYSeries.AREA.equals(ySeries.getSeriesType())); lineSeries.setLineStyle(!isScatter ? LINE_STYLES.get(getLineStyle(ySeries.getSeriesType(), seriesCount)) : LineStyle.NONE); lineSeries.setSymbolType(isScatter ? PlotSymbolType.DIAMOND : PlotSymbolType.NONE); lineSeries.setLineColor(color); lineSeries.setVisible(true); return lineSeries; } <END> }</code><technical_language>please if-statement instead a chages other patch depends this</technical_language>

Target:
protected ISeries addSeries(String seriesName) { if (seriesName == null) { return null; } ISeriesSet seriesSet = getSwtChart().getSeriesSet(); int seriesCount = seriesSet.getSeries().length; ICommonXAxisModel currentModel = getModel(); IYSeries ySeries = currentModel.findSeries(seriesName); if (ySeries == null) { setSeries(seriesName, new double[currentModel.getXAxis().length]); currentModel = getModel(); ySeries = currentModel.findSeries(seriesName); } if (ySeries == null) { return null; } String colorTxt = ySeries.getColor(); Color color = getColor(seriesName, colorTxt); if (ySeries.getSeriesType() == IYSeries.BAR) { IBarSeries barSeries = (IBarSeries) seriesSet.createSeries(SeriesType.BAR, seriesName); barSeries.enableStack(true); barSeries.setBarColor(color); barSeries.setBarPadding(0); barSeries.setVisible(true); return barSeries; } ILineSeries lineSeries = (ILineSeries) seriesSet.createSeries(SeriesType.LINE, seriesName); boolean isScatter = IYSeries.SCATTER.equals(ySeries.getSeriesType()); lineSeries.enableArea(IYSeries.AREA.equals(ySeries.getSeriesType())); lineSeries.setLineStyle(!isScatter ? LINE_STYLES.get(getLineStyle(ySeries.getSeriesType(), seriesCount)) : LineStyle.NONE); lineSeries.setSymbolType(isScatter ? PlotSymbolType.DIAMOND : PlotSymbolType.NONE); lineSeries.setLineColor(color); lineSeries.setVisible(true); return lineSeries; }
Source:
<code>private VideoBlockModel getVideoUnit() { EnrolledCoursesResponse courseData; try { courseData = executeStrict(courseAPI.getEnrolledCourses()).get(0); } catch (Exception e) { throw new RuntimeException(e); } String courseId = courseData.getCourse().getId(); CourseStructureV1Model model; CourseComponent courseComponent; try { model = executeStrict(courseAPI.getCourseStructure(courseId)); courseComponent = (CourseComponent) CourseAPI.normalizeCourseStructure(model, courseId); } catch (Exception e) { throw new RuntimeException(e); } <START> return (VideoBlockModel) courseComponent.getVideos().get(0); <END> }</code><technical_language>Redundant type casting</technical_language>

Target:
private VideoBlockModel getVideoUnit() { EnrolledCoursesResponse courseData; try { courseData = executeStrict(courseAPI.getEnrolledCourses()).get(0); } catch (Exception e) { throw new RuntimeException(e); } String courseId = courseData.getCourse().getId(); CourseStructureV1Model model; CourseComponent courseComponent; try { model = executeStrict(courseAPI.getCourseStructure(config.getApiUrlVersionConfig().getBlocksApiVersion(), courseId)); courseComponent = (CourseComponent) CourseAPI.normalizeCourseStructure(model, courseId); } catch (Exception e) { throw new RuntimeException(e); } return courseComponent.getVideos().get(0); }
Source:
<code>public void addItem(CatalogItem<?> item) { log.debug("Adding manual catalog item to "+mgmt+": "+item); <START> Preconditions.checkNotNull(item); <END> if (manualAdditionsCatalog==null) loadManualAdditionsCatalog(); manualAdditionsCatalog.addEntry(getAbstractCatalogItem(item)); }</code><technical_language>I nice do checkNotNull(item, "item") NPE message null. source code line check causing NPE</technical_language>

Target:
public void addItem(CatalogItem<?> item) { log.debug("Adding manual catalog item to "+mgmt+": "+item); Preconditions.checkNotNull(item, "item"); if (manualAdditionsCatalog==null) loadManualAdditionsCatalog(); manualAdditionsCatalog.addEntry(getAbstractCatalogItem(item)); }
Source:
<code>public void submoduleWithNoHead() throws Exception { Git git = new Git(db); writeTrashFile("file.txt", "content"); git.add().addFilepattern("file.txt").call(); final RevCommit id = git.commit().setMessage("create file").call(); final String path = "sub"; DirCache cache = db.lockDirCache(); DirCacheEditor editor = cache.editor(); editor.add(new PathEdit(path) { public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(id); } }); editor.commit(); assertNotNull(Git.init().setDirectory(new File(db.getWorkTree(), path)) .call().getRepository()); TreeWalk walk = new TreeWalk(db); DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache()); FileTreeIterator workTreeIter = new FileTreeIterator(db); walk.addTree(indexIter); walk.addTree(workTreeIter); walk.setFilter(PathFilter.create(path)); assertTrue(walk.next()); <START> assertFalse(indexIter.idEqual(workTreeIter)); <END> }</code><technical_language>assert workTreeIter zeroid</technical_language>

Target:
public void submoduleWithNoHead() throws Exception { Git git = new Git(db); writeTrashFile("file.txt", "content"); git.add().addFilepattern("file.txt").call(); final RevCommit id = git.commit().setMessage("create file").call(); final String path = "sub"; DirCache cache = db.lockDirCache(); DirCacheEditor editor = cache.editor(); editor.add(new PathEdit(path) { public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(id); } }); editor.commit(); assertNotNull(Git.init().setDirectory(new File(db.getWorkTree(), path)) .call().getRepository()); TreeWalk walk = new TreeWalk(db); DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache()); FileTreeIterator workTreeIter = new FileTreeIterator(db); walk.addTree(indexIter); walk.addTree(workTreeIter); walk.setFilter(PathFilter.create(path)); assertTrue(walk.next()); assertFalse(indexIter.idEqual(workTreeIter)); assertEquals(ObjectId.zeroId(), workTreeIter.getEntryObjectId()); }
Source:
<code>public int getPartitionId(final long dataId) { <START> final long partitionSize = Long.MAX_VALUE / numPartitions; <END> return (int) (dataId / partitionSize); }</code><technical_language>calculate in constructor once, adding partitionSize a class field variable</technical_language>

Target:
public int getPartitionId(final long dataId) { return (int) (dataId / partitionSize); }
Source:
<code>public Collection<Class> getServices() { <START> return Arrays.asList(new Class[] { MagicThingActionsService.class }); <END> }</code><technical_language>suggestion return Collections.singletonList(MagicThingActionsService.class);</technical_language>

Target:
public Collection<Class<? extends ThingHandlerService>> getServices() { return Collections.singletonList(MagicThingActionsService.class); }
Source:
<code>public Object[][] intervalsMultipleContigs(){ <START> List<Locatable> input = Arrays.asList( <END> new Interval("1", 10, 100), new Interval("2", 200, 300) ); List<Locatable> empty = new ArrayList<>(); List<Locatable> contig1 = Arrays.asList( new Interval("1", 10, 100) ); List<Locatable> contig2 = Arrays.asList( new Interval("2", 200, 300) ); return new Object[][]{ new Object[]{input, new Interval("1", 100, 200), contig1}, new Object[]{input, new Interval("1", 1, 5), empty}, new Object[]{input, new Interval("2", 100, 200), contig2}, new Object[]{input, new Interval("3", 100, 200), empty}, }; }</code><technical_language>finals around</technical_language>

Target:
public Object[][] intervalsMultipleContigs(){ final List<Locatable> input = Arrays.asList( new Interval("1", 10, 100), new Interval("2", 200, 300) ); final List<Locatable> empty = new ArrayList<>(); final List<Locatable> contig1 = Arrays.asList( new Interval("1", 10, 100) ); final List<Locatable> contig2 = Arrays.asList( new Interval("2", 200, 300) ); return new Object[][] { new Object[] {input, new Interval("1", 100, 200), contig1}, new Object[] {input, new Interval("1", 1, 5), empty}, new Object[] {input, new Interval("2", 100, 200), contig2}, new Object[] {input, new Interval("3", 100, 200), empty}, }; }
Source:
<code>private JButton createCloseButton() { final JButton closeButton = WidgetFactory.createPrimaryButton("Close", IconUtils.ACTION_SAVE_BRIGHT); closeButton .addActionListener(e -> { dispose(); <START> }); <END> return closeButton; }</code><technical_language>closeButton.addActionListener(e -> dispose()); instead</technical_language>

Target:
private JButton createCloseButton() { final JButton closeButton = WidgetFactory.createPrimaryButton("Close", IconUtils.ACTION_SAVE_BRIGHT); closeButton.addActionListener(e -> { if (isParticularDateSpecified()) { updateWidget(); } dispose(); }); return closeButton; }
Source:
<code>public static Subject fromSecurityIdentity(final SecurityIdentity securityIdentity) { Assert.checkNotNullParam("securityIdentity", securityIdentity); Subject subject = new Subject(); subject.getPrincipals().add(securityIdentity.getPrincipal()); <START> Group rolesGroup = new SimpleGroup("Roles"); <END> for (String role : securityIdentity.getRoles()) { rolesGroup.addMember(new NamePrincipal(role)); } subject.getPrincipals().add(rolesGroup); Group callerPrincipalGroup = new SimpleGroup("CallerPrincipal"); callerPrincipalGroup.addMember(securityIdentity.getPrincipal()); subject.getPrincipals().add(callerPrincipalGroup); IdentityCredentials publicCredentials = securityIdentity.getPublicCredentials(); PublicKeyCredential publicKeyCredential = publicCredentials.getCredential(PublicKeyCredential.class); if (publicKeyCredential != null) { subject.getPublicCredentials().add(publicKeyCredential.getPublicKey()); } return subject; }</code><technical_language>This is super-legacy. Group API</technical_language>

Target:
public static Subject fromSecurityIdentity(final SecurityIdentity securityIdentity) { Assert.checkNotNullParam("securityIdentity", securityIdentity); Subject subject = new Subject(); subject.getPrincipals().add(securityIdentity.getPrincipal()); Group rolesGroup = new SimpleGroup("Roles"); for (String role : securityIdentity.getRoles()) { rolesGroup.addMember(new NamePrincipal(role)); } subject.getPrincipals().add(rolesGroup); Group callerPrincipalGroup = new SimpleGroup("CallerPrincipal"); callerPrincipalGroup.addMember(securityIdentity.getPrincipal()); subject.getPrincipals().add(callerPrincipalGroup); for (Credential credential : securityIdentity.getPublicCredentials()) { if (credential instanceof PublicKeyCredential) { subject.getPublicCredentials().add(credential.castAs(PublicKeyCredential.class).getPublicKey()); } else if (credential instanceof X509CertificateChainPublicCredential) { subject.getPublicCredentials().add(credential.castAs(X509CertificateChainPublicCredential.class).getCertificateChain()); } else { subject.getPublicCredentials().add(credential); } } for (Credential credential : securityIdentity.getPrivateCredentials()) { if (credential instanceof PasswordCredential) { addPrivateCredential(subject, credential.castAs(PasswordCredential.class).getPassword()); } else if (credential instanceof SecretKeyCredential) { addPrivateCredential(subject, credential.castAs(SecretKeyCredential.class).getSecretKey()); } else if (credential instanceof KeyPairCredential) { addPrivateCredential(subject, credential.castAs(KeyPairCredential.class).getKeyPair()); } else if (credential instanceof X509CertificateChainPrivateCredential) { addPrivateCredential(subject, credential.castAs(X509CertificateChainPrivateCredential.class).getCertificateChain()); } else { addPrivateCredential(subject, credential); } } addPrivateCredential(subject, securityIdentity); return subject; }
Source:
<code>protected T doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { <START> BufferedInputStream is = new BufferedInputStream(response.getResponseEntityAsStream()); <END> InputStreamReader in = new InputStreamReader(is); isRestError(is, in); return parseFromJson(in); }</code><technical_language>this stream closed</technical_language>

Target:
protected T doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, BugzillaRestException { try (BufferedInputStream is = new BufferedInputStream(response.getResponseEntityAsStream())) { InputStreamReader in = new InputStreamReader(is); throwExeptionIfRestError(is, in); return parseFromJson(in); } }
Source:
<code>private void aggreagteJobStats(JobDetails jobDetails, byte[] rowKey, Context context, AggregationConstants.AGGREGATION_TYPE aggType) throws IOException, InterruptedException { byte[] aggStatusCol = null; switch (aggType) { case DAILY: aggStatusCol = AggregationConstants.JOB_DAILY_AGGREGATION_STATUS_COL_BYTES; break; case WEEKLY: aggStatusCol = AggregationConstants.JOB_WEEKLY_AGGREGATION_STATUS_COL_BYTES; break; default: LOG.error("Unknown aggregation type " + aggType); return; } <START> if ((reAggregationFlag == true) <END> || ((aggregationFlag == Boolean.TRUE) && (!rawService.getStatusAgg(rowKey, aggStatusCol)))) { Boolean aggStatus = appSummaryService.aggregateJobDetails(jobDetails, aggType); context.progress(); LOG.debug("Status of aggreagting stats for " + aggType + "=" + aggStatus); if (aggStatus) { Put aggStatusPut = rawService.getAggregatedStatusPut(rowKey, aggStatusCol, aggStatus); context.write(RAW_TABLE, aggStatusPut); } } }</code><technical_language>simply if (reAggregationFlag || (aggregationFlag && !rawService.getStatusAgg(...)))</technical_language>

Target:
private void aggreagteJobStats(JobDetails jobDetails, byte[] rowKey, Context context, AggregationConstants.AGGREGATION_TYPE aggType) throws IOException, InterruptedException { byte[] aggStatusCol = null; switch (aggType) { case DAILY: aggStatusCol = AggregationConstants.JOB_DAILY_AGGREGATION_STATUS_COL_BYTES; break; case WEEKLY: aggStatusCol = AggregationConstants.JOB_WEEKLY_AGGREGATION_STATUS_COL_BYTES; break; default: LOG.error("Unknown aggregation type " + aggType); return; } boolean aggStatus = appSummaryService.aggregateJobDetails(jobDetails, aggType); context.progress(); LOG.debug("Status of aggreagting stats for " + aggType + "=" + aggStatus); if (aggStatus) { Put aggStatusPut = rawService.getAggregatedStatusPut(rowKey, aggStatusCol, aggStatus); context.write(RAW_TABLE, aggStatusPut); } }
Source:
<code>public synchronized void initRoutingTable(final EMRoutingTable routingTable) { if (initLatch.getCount() == 0) { return; } numTotalBlocks = routingTable.getNumTotalBlocks(); storeIdToBlockIds.putAll(routingTable.getStoreIdToBlockIds()); storeIdToEndpointId.putAll(routingTable.getStoreIdToEndpointId()); for (final Map.Entry<Integer, Set<Integer>> entry : storeIdToBlockIds.entrySet()) { final int storeId = entry.getKey(); for (final int blockId : entry.getValue()) { blockIdToStoreId.put(blockId, storeId); } } <START> if (blockIdToStoreId.size() != numTotalBlocks || <END> storeIdToBlockIds.size() != storeIdToEndpointId.size()) { throw new RuntimeException("Init info is invalid"); } initLatch.countDown(); LOG.log(Level.FINE, "Server resolver is initialized"); }</code><technical_language>If condition checked routingTable itself, move this sanity check a lines above, EMRoutingTable is created (e.g., constructor)</technical_language>

Target:
public synchronized void initRoutingTable(final EMRoutingTable routingTable) { if (initLatch.getCount() == 0) { return; } numTotalBlocks = routingTable.getNumTotalBlocks(); storeIdToBlockIds.putAll(routingTable.getStoreIdToBlockIds()); storeIdToEndpointId.putAll(routingTable.getStoreIdToEndpointId()); for (final Map.Entry<Integer, Set<Integer>> entry : storeIdToBlockIds.entrySet()) { final int storeId = entry.getKey(); for (final int blockId : entry.getValue()) { blockIdToStoreId.put(blockId, storeId); } } initLatch.countDown(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Server resolver is initialized with NumTotalBlocks: {0}, StoreIdToBlockIds: {1}", new Object[]{numTotalBlocks, storeIdToBlockIds}); } else { LOG.log(Level.INFO, "Server resolver is initialized"); } }
Source:
<code>public ExtensionProxy initialize(String extensionName) { ExtensionEntry entry = loadedEntries.get(extensionName); if (entry == null) { throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found", extensionName)); } try { ExtMap output = entry.extension.invoke( new ExtMap().mput( Base.InvokeKeys.COMMAND, Base.InvokeCommands.INITIALIZE ) ); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.name, ex.getMessage() ) ); if (log.isDebugEnabled()) { log.debug(ex.toString(), ex); } throw new RuntimeException(ex); <START> } <END> entry.initialized = true; initializedEntries.put(extensionName, entry); synchronized (globalContext) { globalContext.<List<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add( new ExtMap().mput( Base.ExtensionRecord.INSTANCE_NAME, entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ).mput( Base.ExtensionRecord.PROVIDES, entry.extension.getContext().get(Base.ContextKeys.PROVIDES) ).mput( Base.ExtensionRecord.EXTENSION, entry.extension.getExtension() ).mput( Base.ExtensionRecord.CONTEXT, entry.extension.getContext() ) ); } dumpConfig(entry.extension); setChanged(); notifyObservers(); return entry != null ? entry.extension : null; }</code><technical_language>try is entire function? critical, a question</technical_language>

Target:
public ExtensionProxy initialize(String extensionName) { ExtensionEntry entry = loadedEntries.get(extensionName); if (entry == null) { throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found", extensionName)); } try { ExtMap output = entry.extension.invoke( new ExtMap().mput( Base.InvokeKeys.COMMAND, Base.InvokeCommands.INITIALIZE ) ); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.name, ex.getMessage() ) ); if (log.isDebugEnabled()) { log.debug(ex.toString(), ex); } throw new RuntimeException(ex); } entry.initialized = true; initializedEntries.put(extensionName, entry); synchronized (globalContext) { globalContext.<List<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add( new ExtMap().mput( Base.ExtensionRecord.INSTANCE_NAME, entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ).mput( Base.ExtensionRecord.PROVIDES, entry.extension.getContext().get(Base.ContextKeys.PROVIDES) ).mput( Base.ExtensionRecord.EXTENSION, entry.extension.getExtension() ).mput( Base.ExtensionRecord.CONTEXT, entry.extension.getContext() ) ); } setChanged(); notifyObservers(); return entry != null ? entry.extension : null; }
Source:
<code>public Backup(String filePath, List<UUID> streamIDs, CorfuRuntime runtime) throws IOException { this.filePath = filePath; this.backupTempDirPath = Files.createTempDirectory(BACKUP_TEMP_DIR_PREFIX).toString(); <START> this.streamIDs = streamIDs; <END> this.runtime = runtime; this.timestamp = runtime.getAddressSpaceView().getLogTail(); }</code><technical_language>add a check if streamIDs is empty, print a warning</technical_language>

Target:
public Backup(String filePath, List<UUID> streamIDs, CorfuRuntime runtime) throws IOException { this.filePath = filePath; this.backupTempDirPath = Files.createTempDirectory(BACKUP_TEMP_DIR_PREFIX).toString(); this.streamIDs = streamIDs; this.runtime = runtime; }
Source:
<code>private void testExceptionCasesProcessResponse(RestMethod restMethod, RestResponseChannel restResponseChannel, BlobInfo blobInfo, RestServiceErrorCode expectedErrorCode) throws Exception { RestRequest restRequest = createRestRequest(restMethod, "/", null); SecurityServiceCallback callback = new SecurityServiceCallback(); securityService.processResponse(restRequest, restResponseChannel, blobInfo, callback); Assert.assertTrue("Callback should have been invoked", callback.callbackLatch.await(1, TimeUnit.SECONDS)); Assert.assertNotNull("Exception should have been thrown", callback.exception); RestServiceException re = (RestServiceException) callback.exception; Assert.assertEquals("Unexpected RestServerErrorCode (Callback)", expectedErrorCode, re.getErrorCode()); <START> } <END></code><technical_language>if change, lets get rid of SecurityServiceCallback</technical_language>

Target:
private void testExceptionCasesProcessResponse(RestMethod restMethod, RestResponseChannel restResponseChannel, BlobInfo blobInfo, RestServiceErrorCode expectedErrorCode) throws Exception { TestUtils.ThrowingConsumer<ExecutionException> errorAction = e -> { Assert.assertTrue("Exception should have been an instance of RestServiceException", e.getCause() instanceof RestServiceException); RestServiceException re = (RestServiceException) e.getCause(); Assert.assertEquals("Unexpected RestServerErrorCode (Future)", expectedErrorCode, re.getErrorCode()); }; RestRequest restRequest = createRestRequest(restMethod, "/", null); TestUtils.assertException(ExecutionException.class, () -> securityService.processResponse(restRequest, restResponseChannel, blobInfo).get(), errorAction); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_us); send = findViewById(R.id.send); name = findViewById(R.id.name); subject = findViewById(R.id.subject); message = findViewById(R.id.message); <START> <END> send.setOnClickListener(v -> { String name_str = name.getText().toString(); String subject_str = subject.getText().toString(); String msg_str = message.getText().toString(); Intent sendMail = new Intent(Intent.ACTION_SEND); sendMail.putExtra(Intent.EXTRA_EMAIL, new String[]{"helpdesk@openmrs.com"}); sendMail.putExtra(Intent.EXTRA_SUBJECT, name_str + " wants to get in touch."); sendMail.putExtra(Intent.EXTRA_TEXT, "Regarding: " + subject_str + "\n" + msg_str); sendMail.setType("message/rfc822"); startActivity(Intent.createChooser(sendMail, "Choose an Email Client")); }); }</code><technical_language>Bind in function **initViews()** maintain architecture of previous code</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_us); initViewFields(); send.setOnClickListener(v -> { String name_str = name.getText().toString(); String subject_str = subject.getText().toString(); String msg_str = message.getText().toString(); Intent sendMail = new Intent(Intent.ACTION_SEND); sendMail.putExtra(Intent.EXTRA_EMAIL, new String[]{"helpdesk@openmrs.com"}); sendMail.putExtra(Intent.EXTRA_SUBJECT, name_str + " wants to get in touch."); sendMail.putExtra(Intent.EXTRA_TEXT, "Regarding: " + subject_str + "\n" + msg_str); sendMail.setType("message/rfc822"); startActivity(Intent.createChooser(sendMail, "Choose an Email Client")); }); }
Source:
<code>public CompressionOutputStream createOutputStream(OutputStream out, Compressor compressor) throws IOException { <START> if (!warned) { <END> LOG.warn(gplLzoCodec + " is deprecated. You should use " + hadoopLzoCodec + " instead to generate LZO compressed data."); warned = true; } return super.createOutputStream(out, compressor); }</code><technical_language>a risk of >1 warning in a multithread env, worried about. AtomicBoolean purist do it</technical_language>

Target:
public CompressionOutputStream createOutputStream(OutputStream out, Compressor compressor) throws IOException { if (warned.compareAndSet(false, true)) { LOG.warn("{} is deprecated. You should use instead to generate LZO compressed data.", gplLzoCodec, hadoopLzoCodec); } return super.createOutputStream(out, compressor); }
Source:
<code>public void shutdown() { isShutdown.set(true); try { <START> shutdownComplete.await(); <END> log.info("Shutdown of AckManager complete"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }</code><technical_language>join() thread</technical_language>

Target:
public void shutdown() { isShutdown.set(true); try { consumerThread.join(); log.info("Shutdown of AckManager complete"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
<code>private static BigInteger factorial(int n) { return Stream.rangeClosed(1, n) .map(BigInteger::valueOf) <START> .fold(BigInteger.ONE, BigInteger::multiply); <END> }</code><technical_language>reduce instead of fold, like: java return Stream.rangeClosed(1, n) .map(BigInteger::valueOf) .reduce(BigInteger::multiply);</technical_language>

Target:
private static BigInteger factorial(int n) { return Stream.rangeClosed(1, n) .map(BigInteger::valueOf) .reduce(BigInteger::multiply); }
Source:
<code>private void handleRequestError(int responseCode) { <START> System.out.println("Request to " + urlCurrentlyRequestingFrom + " had error code response: " + responseCode); <END> repeatRequestOrShowResults(true); }</code><technical_language>this logging instead of Sysout</technical_language>

Target:
private void handleRequestError(int responseCode) { Log.e(TAG, "Request to " + urlCurrentlyRequestingFrom + " in get available apps request " + "had error code response: " + responseCode); repeatRequestOrShowResults(true); }
Source:
<code>private void parseResponseType() { Type returnType = method.getGenericReturnType(); if (returnType == void.class) { throw methodError("Service methods cannot return void."); } for (int i = 0, count = factories.size(); i < count; i++) { CallAdapter.Factory factory = factories.get(i); CallAdapter adapter = factory.get(returnType); if (adapter != null) { this.adapter = adapter; return; } } StringBuilder builder = new StringBuilder() .append("No registered call adapters were able to handle return type ") .append(returnType) .append(". Checked: [ "); <START> for (int i = 0, count = factories.size(); i < count; i++) { <END> if (i > 0) builder.append(", "); builder.append(factories.get(i).getClass().getSimpleName()); } builder.append(" ]"); throw methodError(builder.toString()); }</code><technical_language>list's toString. If for reason configurable factory class, this prevents adding toString debugging. (Especially implement toString() return factory class simplename in built-in implementations.)</technical_language>

Target:
private void parseResponseType() { Type returnType = method.getGenericReturnType(); if (returnType == void.class) { throw methodError("Service methods cannot return void."); } for (int i = 0, count = factories.size(); i < count; i++) { CallAdapter.Factory factory = factories.get(i); CallAdapter adapter = factory.get(returnType); if (adapter != null) { this.adapter = adapter; return; } } throw methodError("No registered call adapters were able to handle return type " + returnType + ". Checked: " + factories); }
Source:
<code>private Event stubEvent() { Event event = Event .newBuilder() .setMessage(AnyPacker.pack( ProjectCreated .newBuilder() .setProjectId(ProjectId.newBuilder() .setId(getClass().getName())) <START> .build())) <END> .build(); return event; }</code><technical_language>Please extract some values this more readable</technical_language>

Target:
private Event stubEvent() { ProjectId project = ProjectId .newBuilder() .setId(getClass().getName()) .build(); ProjectCreated message = ProjectCreated .newBuilder() .setProjectId(project) .build(); Event event = Event .newBuilder() .setMessage(AnyPacker.pack(message)) .build(); return event; }
Source:
<code>public char[] getTextCharacters() { final StackElement stackElement = tokenStack.peek(); if (stackElement == null || stackElement.xmlEvent != XMLEvent.CHARACTERS) { <START> throw new IllegalStateException(); <END> } try { setXmlText(stackElement, jsonParser); return stackElement.value; } catch (IOException e) { throw new IllegalStateException(e); } }</code><technical_language>Please add some exception message</technical_language>

Target:
public char[] getTextCharacters() { final StackElement stackElement = tokenStack.peek(); if (stackElement == null || stackElement.xmlEvent != XMLEvent.CHARACTERS) { throw new IllegalStateException(ERROR_MSG_NOT_IN_CHARACTERS); } try { setXmlText(stackElement, jsonParser); return stackElement.value; } catch (IOException e) { throw new UncheckedIOException(e); } }