auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void advanceIterator() { if (this.currentIterator != null) { this.currentIterator.close(); } if (!this.iterators.hasNext()) { this.currentIterator = null; return; } final Interval currInterval = this.intervals[this.currentIntervalIndex]; final Interval prevInterval = this.currentIntervalIndex == 0 ? null : this.intervals[this.currentIntervalIndex - 1]; final SamRecordFilter filter = new SamRecordFilter() { @Override public boolean filterOut(final SAMRecord record) { <START> return record.getReadUnmappedFlag() && record.getAlignmentStart() != SAMRecord.NO_ALIGNMENT_START <END> ? !this.acceptUnmappedRecord(record) : !this.acceptRecord(record); } @Override public boolean filterOut(final SAMRecord first, final SAMRecord second) { throw new UnsupportedOperationException(); } private boolean acceptRecord(final SAMRecord rec) { return BAMQueryChainingIterator.this.contained ? currInterval.contains(rec) && (prevInterval == null || !prevInterval.contains(rec)) : currInterval.overlaps(rec) && (prevInterval == null || !prevInterval.overlaps(rec)); } private boolean acceptUnmappedRecord(final SAMRecord rec) { final int start = rec.getStart(); final boolean matchesCurrInterval = rec.contigsMatch(currInterval) && CoordMath.encloses(currInterval.getStart(), currInterval.getEnd(), start, start); final boolean matchesPrevInterval = prevInterval != null && rec.contigsMatch(prevInterval) && CoordMath.encloses(prevInterval.getStart(), prevInterval.getEnd(), start, start); return matchesCurrInterval && !matchesPrevInterval; } }; this.currentIterator = new FilteringSamIterator(this.iterators.next().get(), filter, false); this.currentIntervalIndex++; }</code><technical_language>I this anonymous class a named static class explicitly pass current/previous intervals contained constructor parameters. Currently read carefully in order understand if state, interacts class, etc. A static class is easier ignore internals of</technical_language>

Target:
private void advanceIterator() { if (this.currentIterator != null) { this.currentIterator.close(); } if (!this.iterators.hasNext()) { this.currentIterator = null; return; } final Locatable currInterval = this.intervals.get(this.currentIntervalIndex); final Locatable prevInterval = this.currentIntervalIndex == 0 ? null : this.intervals.get(this.currentIntervalIndex - 1); this.currentIterator = new FilteringSamIterator( this.iterators.next().get(), new ConsecutiveDuplicateRecordFilter(currInterval, prevInterval, contained)); this.currentIntervalIndex++; }
Source:
<code>public PartitionedPageWriter() { checkArgument(temporalColumnIndex.isPresent() == temporalColumnType.isPresent(), "temporalColumnIndex and temporalColumnType must be both present or absent"); List<Type> bucketTypes = Arrays.stream(bucketFields) .mapToObj(columnTypes::get) .collect(toList()); this.bucketFunction = bucketCount.isPresent() ? Optional.of(new RaptorBucketFunction(bucketCount.getAsInt(), bucketTypes)) : Optional.empty(); <START> this.temporalFunction = temporalColumnType.map(type -> temporalFunctionFactory.getTemporalFunction(type)); <END> }</code><technical_language>I this a method reference</technical_language>

Target:
public PartitionedPageWriter() { checkArgument(temporalColumnIndex.isPresent() == temporalColumnType.isPresent(), "temporalColumnIndex and temporalColumnType must be both present or absent"); List<Type> bucketTypes = Arrays.stream(bucketFields) .mapToObj(columnTypes::get) .collect(toList()); this.bucketFunction = bucketCount.isPresent() ? Optional.of(new RaptorBucketFunction(bucketCount.getAsInt(), bucketTypes)) : Optional.empty(); }
Source:
<code>public static URI createUri(final String jobId, final String path) throws URISyntaxException { <START> final String encodedJobId = Base64.encodeBase64URLSafeString(jobId.getBytes()); <END> return new URIBuilder() .setScheme(URI_SCHEME) .setHost(encodedJobId) .setPath(path) .build(); }</code><technical_language>encoding ID missing decoding somewhere? I</technical_language>

Target:
public static URI createUri(final String jobId, final String path) throws URISyntaxException { final String encodedJobId = Base64.encodeBase64URLSafeString(jobId.getBytes(Charset.defaultCharset())); return new URIBuilder() .setScheme(URI_SCHEME) .setHost(encodedJobId) .setPath(path) .build(); }
Source:
<code>private Map<Guid, SubchainInfo> getDomainsToSnapshotsMap(List<SubchainInfo> snapshots) { Map<Guid, SubchainInfo> domainsToPairMap = new HashMap<>(); for (SubchainInfo subchain: snapshots) { Guid storageId = <START> subchain.getBaseImage().getStorageIds().get(0); <END> domainsToPairMap.put(storageId, subchain); } return domainsToPairMap; }</code><technical_language>subchain.getStorageDomainId</technical_language>

Target:
private Map<Guid, SubchainInfo> getDomainsToSnapshotsMap(List<SubchainInfo> snapshots) { Map<Guid, SubchainInfo> domainsToPairMap = new HashMap<>(); for (SubchainInfo subchain: snapshots) { Guid storageId = subchain.getStorageDomainId(); domainsToPairMap.put(storageId, subchain); } return domainsToPairMap; }
Source:
<code>public void testHashSaltedPassword() throws Exception { String password = "test-password"; String salt = pwGenerator.generateSalt(); int hashIterations = 1024; String hash1 = pwGenerator.hashPassword(password, salt, hashIterations); String hash2 = pwGenerator.hashPassword(password, salt, hashIterations); <START> Assert.assertEquals(hash1, hash2); <END> String salt2 = pwGenerator.generateSalt(); String hash3 = pwGenerator.hashPassword(password, salt2, hashIterations); Assert.assertFalse(hash1.equals(hash3)); String hash4 = pwGenerator.hashPassword(password, salt, 1); Assert.assertFalse(hash1.equals(hash4)); }</code><technical_language>Recommend new tests hamcrest matchers, ex: assertThat(hash2, is(hash1)); produce more descriptive messages assertion fails</technical_language>

Target:
public void testHashSaltedPassword() throws Exception { String password = "test-password"; String salt = pwGenerator.generateSalt(); int hashIterations = 1024; String hash1 = pwGenerator.hashPassword(password, salt, hashIterations); String hash2 = pwGenerator.hashPassword(password, salt, hashIterations); assertThat(hash2, is(hash1)); String salt2 = pwGenerator.generateSalt(); String hash3 = pwGenerator.hashPassword(password, salt2, hashIterations); assertThat(hash3, not(hash1)); String hash4 = pwGenerator.hashPassword(password, salt, 1); assertThat(hash4, not(hash1)); }
Source:
<code>private Ds3ClientHelpers.Job innerStartReadJob(final String bucket, final Iterable<Ds3Object> objectsToRead, final ReadJobOptions options) throws SignatureException, IOException, XmlProcessingException { final List<Ds3Object> objects = Lists.newArrayList(objectsToRead); final BulkGetResponse prime = this.client.bulkGet(new BulkGetRequest(bucket, objects) .withChunkOrdering(ChunkClientProcessingOrderGuarantee.NONE) .withPriority(options.getPriority())); final ImmutableMultimap<String, Range> partialRanges = PartialObjectHelpers.getPartialObjectsRanges(objects); final MasterObjectList mob = prime.getResult(); <START> final ImmutableMultimap<BulkObject, Range> blobtoRanges = PartialObjectHelpers.mapRangesToBlob(mob.getObjects(), partialRanges); <END> return new ReadJobImpl(this.client, mob, blobtoRanges); }</code><technical_language>capitalize "To" in blobtoRange</technical_language>

Target:
private Ds3ClientHelpers.Job innerStartReadJob(final String bucket, final Iterable<Ds3Object> objectsToRead, final ReadJobOptions options) throws SignatureException, IOException, XmlProcessingException { final List<Ds3Object> objects = Lists.newArrayList(objectsToRead); final BulkGetResponse prime = this.client.bulkGet(new BulkGetRequest(bucket, objects) .withChunkOrdering(ChunkClientProcessingOrderGuarantee.NONE) .withPriority(options.getPriority())); final ImmutableMultimap<String, Range> partialRanges = PartialObjectHelpers.getPartialObjectsRanges(objects); return new ReadJobImpl(this.client, prime.getResult(), partialRanges); }
Source:
<code>protected void showPackageFilter() { final Collection<String> packages; if (getCollector() instanceof TargetPlatformClassContributionCollector) { packages = TargetPlatformClassContributionCollector.getInstance().getPackages(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { packages = TargetPlatformIconContributionCollector.getInstance().getPackages(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(packages); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the package to filter on."); setTitle("Package Filter"); getShell().setText("Package Filter"); <START> setTitleImage(new Image(getShell().getDisplay(), getClass().getResourceAsStream("/icons/full/wizban/package_wiz.png"))); <END> return ret; } }; if (dlg.open() == Dialog.OK) { setFilterPackages((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }</code><technical_language>anonymous "new Image()" is a resource leak. Please some kind of resourcepool</technical_language>

Target:
protected void showPackageFilter() { final Collection<String> packages; if (getCollector() instanceof TargetPlatformClassContributionCollector) { packages = TargetPlatformClassContributionCollector.getInstance().getPackages(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { packages = TargetPlatformIconContributionCollector.getInstance().getPackages(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(packages); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the package to filter on."); setTitle("Package Filter"); getShell().setText("Package Filter"); setTitleImage(imageCache.create("/icons/full/wizban/package_wiz.png")); return ret; } }; if (dlg.open() == Dialog.OK) { setFilterPackages((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }
Source:
<code>public Collection<RepositoryMapping> find(IProgressMonitor m, boolean searchLinkedFolders) throws CoreException { <START> IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; <END> find(monitor, proj, searchLinkedFolders); return results; }</code><technical_language>Delete pass m</technical_language>

Target:
public List<RepositoryMapping> find(IProgressMonitor m, boolean searchLinkedFolders) throws CoreException { find(m, proj, searchLinkedFolders); return results; }
Source:
<code>public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBBegin"); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); diagramEditor.click("refToBBegin"); <START> SWTBotUtils.waitAllUiEvents(); <END> IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); diagramEditor.dragWithKey(part.getFigure().getBounds().x, part.getFigure().getBounds().y, part.getFigure().getBounds().x - 10, part.getFigure().getBounds().y - 10, SWT.None); SWTBotUtils.waitAllUiEvents(); assertEquals(172, part.getFigure().getBounds().x); assertEquals(94, part.getFigure().getBounds().y); }</code><technical_language>more reliable wait for CheckSelectedCondition instead of waitAllUIEvent (especially gerrit Jenkins)</technical_language>

Target:
public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBBegin"); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); int originalX = part.getFigure().getBounds().x; int originalY = part.getFigure().getBounds().y; CheckEditPartMoved checkEditPartMoved = new CheckEditPartMoved(editPart); diagramEditor.dragWithKey(part.getFigure().getBounds().x, part.getFigure().getBounds().y, part.getFigure().getBounds().x - 10, part.getFigure().getBounds().y - 10, SWT.None); bot.waitUntil(checkEditPartMoved); assertEquals(originalX - 10, part.getFigure().getBounds().x); assertEquals(originalY - 10, part.getFigure().getBounds().y); }
Source:
<code>public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); setHasOptionsMenu(true); View rootView = inflater.inflate(R.layout.pager_fragment, container, false); viewPager = rootView.findViewById(R.id.viewpager); toolbar = rootView.findViewById(R.id.toolbar); viewPager.setAdapter(new StatisticsPagerAdapter(this)); tabLayout = rootView.findViewById(R.id.sliding_tabs); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> { switch (position) { case POS_LISTENED_HOURS: tab.setText(R.string.playback_statistics_label); break; case POS_SPACE_TAKEN: tab.setText(R.string.download_statistics_label); break; default: break; } }).attach(); if (getActivity().getClass() == PreferenceActivity.class) { rootView.findViewById(R.id.toolbar).setVisibility(View.GONE); } else { <START> toolbar.setTitle(getString(R.string.statistics_label)); <END> } return rootView; }</code><technical_language>Adding arrow button work: toolbar.setNavigationOnClickListener(v -> getParentFragmentManager().popBackStack());</technical_language>

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); setHasOptionsMenu(true); View rootView = inflater.inflate(R.layout.pager_fragment, container, false); viewPager = rootView.findViewById(R.id.viewpager); toolbar = rootView.findViewById(R.id.toolbar); viewPager.setAdapter(new StatisticsPagerAdapter(this)); tabLayout = rootView.findViewById(R.id.sliding_tabs); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> { switch (position) { case POS_LISTENED_HOURS: tab.setText(R.string.playback_statistics_label); break; case POS_SPACE_TAKEN: tab.setText(R.string.download_statistics_label); break; default: break; } }).attach(); if (getActivity().getClass() == PreferenceActivity.class) { rootView.findViewById(R.id.toolbar).setVisibility(View.GONE); } else { toolbar.setTitle(getString(R.string.statistics_label)); toolbar.setNavigationOnClickListener(v -> getParentFragmentManager().popBackStack()); } return rootView; }
Source:
<code>public void testLeftJoinMissingStats() { PlanNodeStatsEstimate leftStats = planNodeStats( 0, <START> new SymbolStatistics(LEFT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), <END> new SymbolStatistics(LEFT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); PlanNodeStatsEstimate rightStats = planNodeStats( 0, new SymbolStatistics(RIGHT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(RIGHT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); assertJoinStats(LEFT, leftStats, rightStats, leftStats); }</code><technical_language>nit: I old, more concise UNKNOWN_STATS</technical_language>

Target:
public void testLeftJoinMissingStats() { PlanNodeStatsEstimate leftStats = planNodeStats( 0, new SymbolStatistics(LEFT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(LEFT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); PlanNodeStatsEstimate rightStats = planNodeStats( 0, new SymbolStatistics(RIGHT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(RIGHT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); assertJoinStats(LEFT, leftStats, rightStats, PlanNodeStatsEstimate.unknown()); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) { String dir = data.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR); File path; if (dir != null) { path = new File(dir); } else { path = getActivity().getExternalFilesDir(null); } String message = null; final Context context = getActivity().getApplicationContext(); if (!path.exists()) { message = String.format(context.getString(R.string.folder_does_not_exist_error), dir); } else if (!path.canRead()) { message = String.format(context.getString(R.string.folder_not_readable_error), dir); } else if (!path.canWrite()) { message = String.format(context.getString(R.string.folder_not_writable_error), dir); } if (message == null) { Log.d(TAG, "Setting data folder: " + dir); UserPreferences.setDataFolder(dir); setDataFolderText(); } else { AlertDialog.Builder ab = new AlertDialog.Builder(getActivity()); ab.setMessage(message); ab.setPositiveButton(android.R.string.ok, null); ab.show(); } } if (resultCode == Activity.RESULT_OK && <START> requestCode == CHOOSE_OPML_EXPORT_PATH) { <END> Uri uri = data.getData(); export(new OpmlWriter(), uri); } }</code><technical_language>line need wrapped. short enough fit in a single line</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) { String dir = data.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR); File path; if (dir != null) { path = new File(dir); } else { path = getActivity().getExternalFilesDir(null); } String message = null; final Context context = getActivity().getApplicationContext(); if (!path.exists()) { message = String.format(context.getString(R.string.folder_does_not_exist_error), dir); } else if (!path.canRead()) { message = String.format(context.getString(R.string.folder_not_readable_error), dir); } else if (!path.canWrite()) { message = String.format(context.getString(R.string.folder_not_writable_error), dir); } if (message == null) { Log.d(TAG, "Setting data folder: " + dir); UserPreferences.setDataFolder(dir); setDataFolderText(); } else { AlertDialog.Builder ab = new AlertDialog.Builder(getActivity()); ab.setMessage(message); ab.setPositiveButton(android.R.string.ok, null); ab.show(); } } if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_OPML_EXPORT_PATH) { Uri uri = data.getData(); export(new OpmlWriter(), uri); } if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_HTML_EXPORT_PATH) { Uri uri = data.getData(); export(new HtmlWriter(), uri); } }
Source:
<code>public <T> Iterator<List<T>> split(Iterator<T> inputIterator, Function<T, InputFileAttribute> inputAttributeExtractor) { return new Iterator<List<T>>() { private T peeking; @Override public boolean hasNext() { return peeking != null || inputIterator.hasNext(); } @Override public List<T> next() { final List<T> current = new ArrayList<>(); long splitSize = 0; while (splitSize < maxSplitSize && (peeking != null || inputIterator.hasNext())) { if (peeking == null) { peeking = inputIterator.next(); } final long size = inputAttributeExtractor.apply(peeking).getSize(); if (current.isEmpty()) { current.add(peeking); splitSize += size; peeking = null; <START> } else if (splitSize + size < maxSplitSize) { <END> current.add(peeking); splitSize += size; peeking = null; } else { break; } } assert !current.isEmpty(); return current; } }; }</code><technical_language>splitSize + size < maxSplitSize current.isEmpty() block combined</technical_language>

Target:
public <T> Iterator<List<T>> split(Iterator<T> inputIterator, Function<T, InputFileAttribute> inputAttributeExtractor) { return new Iterator<List<T>>() { private T peeking; @Override public boolean hasNext() { return peeking != null || inputIterator.hasNext(); } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } final List<T> current = new ArrayList<>(); long splitSize = 0; while (splitSize < maxSplitSize && (peeking != null || inputIterator.hasNext())) { if (peeking == null) { peeking = inputIterator.next(); } final long size = inputAttributeExtractor.apply(peeking).getSize(); if (current.isEmpty() || splitSize + size < maxSplitSize) { current.add(peeking); splitSize += size; peeking = null; } else { break; } } assert !current.isEmpty(); return current; } }; }
Source:
<code>public EquipmentDefinition(int id, int index, boolean twoHanded, boolean fullBody, boolean fullHelmet, Requirement[] requirements, int[] bonuses) { this.id = id; this.index = index; this.twoHanded = twoHanded; this.fullBody = fullBody; this.fullHelmet = fullHelmet; this.requirements = List.of(requirements); <START> this.bonuses = bonuses.clone(); <END> }</code><technical_language>clone() a badly designed portion of Java API, Arrays.copyOf</technical_language>

Target:
public EquipmentDefinition(int id, int index, boolean twoHanded, boolean fullBody, boolean fullHelmet, Requirement[] requirements, int[] bonuses) { this.id = id; this.index = index; this.twoHanded = twoHanded; this.fullBody = fullBody; this.fullHelmet = fullHelmet; this.requirements = ImmutableList.copyOf(requirements); this.bonuses = Arrays.copyOf(bonuses, bonuses.length); }
Source:
<code>private <START> static String <END> expandIpv6String(String ipv6Addr) { List<String> list = Stream.of(ipv6Addr.split(COLON, -1)) .collect(Collectors.toList()); int emptyIndex = list.indexOf(EMPTY_STRING); if (emptyIndex >= 0) { list = list.stream() .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); int expandCount = 8 - list.size(); for (int i = 0; i < expandCount; i++) { list.add(emptyIndex, ZERO_STRING); } } return list.stream() .map(IPAddressConverter::prependZeroes) .collect(Collectors.joining()); }</code><technical_language>static</technical_language>

Target:
private String expandIpv6String(String ipv6Addr) { List<String> list = Stream.of(ipv6Addr.split(COLON, -1)) .collect(Collectors.toList()); int emptyIndex = list.indexOf(EMPTY_STRING); if (emptyIndex >= 0) { list = list.stream() .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); int expandCount = 8 - list.size(); for (int i = 0; i < expandCount; i++) { list.add(emptyIndex, ZERO_STRING); } } return list.stream() .map(this::prependZeroes) .collect(Collectors.joining()); }
Source:
<code>public DocumentModel run(DocumentModel doc) throws OperationException, IOException { if (index != null) { Property complexProperty = doc.getProperty(xpath); ListType ltype = (ListType) complexProperty.getField().getType(); if (!ltype.getFieldType().isComplexType() && !ltype.isListType()) { throw new OperationException("Property type is not supported by this operation"); } ListProperty listProperty = (ListProperty) complexProperty; <START> ArrayList propertiesValues = (ArrayList) listProperty.getValue(); <END> propertiesValues.remove(index.intValue()); listProperty.clear(); listProperty.setValue(propertiesValues); } else { Property complexProperty = doc.getProperty(xpath); ListType ltype = (ListType) complexProperty.getField().getType(); if (!ltype.getFieldType().isComplexType() && !ltype.isListType()) { throw new OperationException("Property type is not supported by this operation"); } ListProperty listProperty = (ListProperty) complexProperty; listProperty.clear(); } doc = session.saveDocument(doc); if (save) { session.save(); } return doc; }</code><technical_language>List</technical_language>

Target:
public DocumentModel run(DocumentModel doc) throws OperationException, IOException { if (index != null) { Property complexProperty = doc.getProperty(xpath); ListType listType = (ListType) complexProperty.getField().getType(); if (!listType.getFieldType().isComplexType() && !listType.isListType()) { throw new OperationException("Property type is not supported by this operation"); } ListProperty listProperty = (ListProperty) complexProperty; List<?> propertiesValues = (List<?>) listProperty.getValue(); propertiesValues.remove(index.intValue()); listProperty.clear(); listProperty.setValue(propertiesValues); } else { Property complexProperty = doc.getProperty(xpath); ListType listType = (ListType) complexProperty.getField().getType(); if (!listType.getFieldType().isComplexType() && !listType.isListType()) { throw new OperationException("Property type is not supported by this operation"); } ListProperty listProperty = (ListProperty) complexProperty; listProperty.clear(); } doc = session.saveDocument(doc); if (save) { session.save(); } return doc; }
Source:
<code>public void tenantId() { FhirContext ctx = FhirContext.forR4(); IGenericClient genericClient = ctx.newRestfulGenericClient("http://localhost:9999/fhir"); UrlTenantSelectionInterceptor tenantSelection = new UrlTenantSelectionInterceptor(); genericClient.registerInterceptor(tenantSelection); tenantSelection.setTenantId("TENANT-A"); Patient patientA = genericClient.read().resource(Patient.class).withId("123").execute(); tenantSelection.setTenantId("TENANT-B"); <START> Patient patientB = genericClient.read().resource(Patient.class).withId("123").execute(); <END> END SNIPPET: tenantId }</code><technical_language>suggestion Patient patientB = genericClient.read().resource(Patient.class).withId("456").execute(); worried people get impression id in partitions</technical_language>

Target:
public void tenantId() { FhirContext ctx = FhirContext.forR4(); IGenericClient genericClient = ctx.newRestfulGenericClient("http://localhost:9999/fhir"); UrlTenantSelectionInterceptor tenantSelection = new UrlTenantSelectionInterceptor(); genericClient.registerInterceptor(tenantSelection); tenantSelection.setTenantId("TENANT-A"); Patient patientA = genericClient.read().resource(Patient.class).withId("123").execute(); tenantSelection.setTenantId("TENANT-B"); Patient patientB = genericClient.read().resource(Patient.class).withId("456").execute(); END SNIPPET: tenantId }
Source:
<code>public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { <START> entry = client.files().upload(localPath); <END> } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } }</code><technical_language>dropboxPath</technical_language>

Target:
public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { entry = client.files().upload(dropboxPath); } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } }
Source:
<code>protected HttpConsumer resolve(HttpServletRequest request) { String path = request.getPathInfo(); log.trace("Request path is: {}", path); String endpointName = getEndpointNameFromPath(path); log.trace("Looking up consumer for endpoint: {}", endpointName); HttpConsumer answer = consumers.get(endpointName); if (answer == null) { if (LOGGER.isDebugEnabled()) { <START> log.debug("Consumer Keys: {}", Arrays.toString(consumers.keySet().toArray())); <END> } for (Entry<String, HttpConsumer> entry : consumers.entrySet()) { if (entry.getValue().getEndpoint().isMatchOnUriPrefix() && path.startsWith(entry.getKey())) { answer = consumers.get(entry.getKey()); break; } } } return answer; }</code><technical_language>Is Arrays.toString(consumers.keySet().toArray())); necessary? I consumers.keySet().toString() print a comma separated list of keys</technical_language>

Target:
protected HttpConsumer resolve(HttpServletRequest request) { String path = request.getPathInfo(); log.trace("Request path is: {}", path); String endpointName = getEndpointNameFromPath(path); log.trace("Looking up consumer for endpoint: {}", endpointName); HttpConsumer answer = consumers.get(endpointName); if (answer == null) { if (LOGGER.isDebugEnabled()) { log.debug("Consumer Keys: {}", consumers.keySet()); } for (Entry<String, HttpConsumer> entry : consumers.entrySet()) { if (entry.getValue().getEndpoint().isMatchOnUriPrefix() && path.startsWith(entry.getKey())) { answer = consumers.get(entry.getKey()); break; } } } return answer; }
Source:
<code>public CollectionDetail get(HttpServletRequest request, HttpServletResponse response) throws IOException, ZebedeeException { <START> com.github.onsdigital.zebedee.model.Collection collection = Collections <END> .getCollection(request); if (collection == null) { response.setStatus(HttpStatus.NOT_FOUND_404); return null; } Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canView(session.getEmail(), collection.getDescription())) { response.setStatus(HttpStatus.UNAUTHORIZED_401); return null; } CollectionDetail result = new CollectionDetail(); result.setId(collection.getDescription().getId()); result.setName(collection.getDescription().getName()); result.setType(collection.getDescription().getType()); result.setPublishDate(collection.getDescription().getPublishDate()); result.setReleaseUri(collection.getDescription().getReleaseUri()); result.approvalStatus = collection.getDescription().approvalStatus; return result; }</code><technical_language>Is a reason importing this statements top of file</technical_language>

Target:
public CollectionDetail get(HttpServletRequest request, HttpServletResponse response) throws IOException, ZebedeeException { Collection collection = zebedeeCmsService.getCollection(request); if (collection == null) { throw new CollectionNotFoundException("collection not found"); } Session session = zebedeeCmsService.getSession(request); if (session == null || !zebedeeCmsService.getPermissions().canView(session.getEmail(), collection.getDescription())) { throw new UnauthorizedException("unauthorised call to get publishing queue collection details"); } CollectionDetail result = new CollectionDetail(); result.setId(collection.getDescription().getId()); result.setName(collection.getDescription().getName()); result.setType(collection.getDescription().getType()); result.setPublishDate(collection.getDescription().getPublishDate()); result.setReleaseUri(collection.getDescription().getReleaseUri()); result.approvalStatus = collection.getDescription().approvalStatus; return result; }
Source:
<code>public void asNormal() { Flowable<Object> flow = normal.completable.as(new CompletableConverter<Flowable<Object>>() { @Override public Flowable<Object> apply(Completable c) { return c.toFlowable(); } }); <START> flow.blockingForEach(new Consumer<Object>() { <END> @Override public void accept(Object e) { } }); }</code><technical_language>this assertion is this wanted</technical_language>

Target:
public void asNormal() { normal.completable .as(new CompletableConverter<Flowable<Object>>() { @Override public Flowable<Object> apply(Completable c) { return c.toFlowable(); } }) .test() .assertComplete() .assertNoValues(); }
Source:
<code>public String getTimeZone() { <START> String tz = timeZoneComboBox.getSelectedItem().toString(); <END> return tz.substring(tz.indexOf(")") + 2).trim(); }</code><technical_language>this method need public</technical_language>

Target:
String getTimeZone() { String tz = timeZoneComboBox.getSelectedItem().toString(); return tz.substring(tz.indexOf(")") + 2).trim(); }
Source:
<code>public CachingInputStream open(FileSystem fileSystem, Path path, Optional<byte[]> extraFileInfo) throws IOException { <START> checkArgument(fileSystem instanceof CachingFileSystem, "fileSystem should be of CachingFileSystem type."); <END> CachingFileSystem cachingFileSystem = (CachingFileSystem) fileSystem; FSDataInputStream fsDataInputStream = fileOpener.open(cachingFileSystem.getDataTier(), path, extraFileInfo); return new CachingInputStream(fsDataInputStream, cacheManager, path, cachingFileSystem.isCacheValidationEnabled()); }</code><technical_language>nit: of time add dot end of error message, I strong opinion this</technical_language>

Target:
public CachingInputStream open(FileSystem fileSystem, Path path, Optional<byte[]> extraFileInfo) throws IOException { checkArgument(fileSystem instanceof CachingFileSystem, "fileSystem should be of CachingFileSystem type"); CachingFileSystem cachingFileSystem = (CachingFileSystem) fileSystem; FSDataInputStream inputStream = fileOpener.open(cachingFileSystem.getDataTier(), path, extraFileInfo); return new CachingInputStream(inputStream, cacheManager, path, cachingFileSystem.isCacheValidationEnabled()); }
Source:
<code>protected File getEmptyJarDestinationFolder() throws IOException { <START> File destinationFolder = new File("/tmp/expandedJar"); <END> if (destinationFolder.exists()) { FileUtils.cleanDirectory(destinationFolder); } else { destinationFolder.mkdirs(); } return destinationFolder; }</code><technical_language>path work windows? :)</technical_language>

Target:
protected File getEmptyJarDestinationFolder() throws IOException { File destinationFolder = new File(System.getProperty("java.io.tmpdir"), "expandedJar"); if (destinationFolder.exists()) { FileUtils.cleanDirectory(destinationFolder); } else { destinationFolder.mkdirs(); } return destinationFolder; }
Source:
<code>public boolean contains(String entityName, Object object) { <START> checkTransactionSynchStatus(); <END> if ( object == null ) { return false; } try { if ( !HibernateProxy.class.isInstance( object ) && persistenceContext.getEntry( object ) == null ) { try { getSessionFactory().getMetamodel().entityPersister( entityName ); } catch (HibernateException e) { throw new IllegalArgumentException( "Not an entity [" + entityName + "] : " + object ); } } if ( object instanceof HibernateProxy ) { checkOpen(); LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { return li.getSession() == this; } else { object = li.getImplementation(); } } EntityEntry entry = persistenceContext.getEntry( object ); delayedAfterCompletion(); return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE; } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } catch (RuntimeException e) { throw exceptionConverter.convert( e ); } }</code><technical_language>changing checkOpenOrWaitingForAutoClose()</technical_language>

Target:
public boolean contains(String entityName, Object object) { checkOpenOrWaitingForAutoClose(); checkTransactionSynchStatus(); if ( object == null ) { return false; } try { if ( !HibernateProxy.class.isInstance( object ) && persistenceContext.getEntry( object ) == null ) { try { getSessionFactory().getMetamodel().entityPersister( entityName ); } catch (HibernateException e) { throw new IllegalArgumentException( "Not an entity [" + entityName + "] : " + object ); } } if ( object instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { return li.getSession() == this; } else { object = li.getImplementation(); } } EntityEntry entry = persistenceContext.getEntry( object ); delayedAfterCompletion(); return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE; } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } catch (RuntimeException e) { throw exceptionConverter.convert( e ); } }
Source:
<code>public static CommandLineBuilder commandLineBuilder( PathFragment windowsSandboxPath, List<String> commandArguments) { return new CommandLineBuilder() .setWindowsSandboxPath(windowsSandboxPath) <START> .setCommandArguments(commandArguments); <END> }</code><technical_language>opt: if windowsSandboxPath commandArguments mandatory, safer set in Builder ctor</technical_language>

Target:
public static CommandLineBuilder commandLineBuilder( PathFragment windowsSandboxPath, List<String> commandArguments) { return new CommandLineBuilder(windowsSandboxPath, commandArguments); }
Source:
<code>public void testNullBucket() { Session session = getSession(); QueryRunner queryRunner = getQueryRunner(); queryRunner.execute("CREATE TABLE table_with_null_buckets WITH (bucket_count=2, bucketed_by = ARRAY['key']) AS " + "SELECT 10 x, CAST(NULL AS INTEGER) AS key UNION ALL SELECT 20 x, 1 key"); try { assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL", "SELECT 1"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key IS NULL", "SELECT 10"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE x = 10", "SELECT NULL"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key = 1", "SELECT 20"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE key IS NULL AND x = 10", "SELECT NULL"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL AND x = 1", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key = 10", "SELECT 0"); <START> assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IN (NULL,1)", "SELECT 1"); <END> } finally { queryRunner.execute("DROP TABLE table_with_null_buckets"); } }</code><technical_language>nits: space comma in NULL,1</technical_language>

Target:
public void testNullBucket() { Session session = getSession(); QueryRunner queryRunner = getQueryRunner(); queryRunner.execute("CREATE TABLE table_with_null_buckets WITH (bucket_count=2, bucketed_by = ARRAY['key']) AS " + "SELECT 10 x, CAST(NULL AS INTEGER) AS key UNION ALL SELECT 20 x, 1 key"); try { assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL", "SELECT 1"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key IS NULL", "SELECT 10"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE x = 10", "SELECT NULL"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key = 1", "SELECT 20"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE key IS NULL AND x = 10", "SELECT NULL"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL AND x = 1", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key = 10", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IN (NULL, 1)", "SELECT 1"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL OR key = 1", "SELECT 2"); } finally { queryRunner.execute("DROP TABLE table_with_null_buckets"); } }
Source:
<code>public BlockState getStateForPlacement(BlockItemUseContext context) { BlockState state = this.getDefaultState(); if(state.has(BlockStateProperties.WATERLOGGED) &&context.getWorld().getFluidState(context.getPos()).getFluid()==Fluids.WATER) { state = state.with(BlockStateProperties.WATERLOGGED, true); <START> } <END> return state; }</code><technical_language>Formatting (extra {})</technical_language>

Target:
public BlockState getStateForPlacement(BlockItemUseContext context) { BlockState state = this.getDefaultState(); if(state.has(BlockStateProperties.WATERLOGGED) &&context.getWorld().getFluidState(context.getPos()).getFluid()==Fluids.WATER) state = state.with(BlockStateProperties.WATERLOGGED, true); return state; }
Source:
<code>default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); optional(clone()); optional(exclusive()); optional(template().name()); <START> optional(configuration()); <END> }</code><technical_language>"registrationConfiguration", name below</technical_language>

Target:
default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); optional(clone()); optional(exclusive()); optional(template().name()); or(optional(storageDomain().id()), optional(storageDomain().name())); optional(vm().diskAttachments()[COLLECTION].id()); }
Source:
<code>public synchronized void saveManagementLayout(Layout layout) { if (layout == null) { log.warn("saveManagementLayout: Attempted to update with null layout"); return; } Layout currentLayout = getManagementLayout(); if (currentLayout == null || layout.getEpoch() > currentLayout.getEpoch()) { dataStore.put(Layout.class, PREFIX_MANAGEMENT, MANAGEMENT_LAYOUT, layout); log.info("saveManagementLayout: Updated to new layout at epoch {}", getManagementLayout().getEpoch()); } else if (layout.getEpoch() < currentLayout.getEpoch()){ log.debug("saveManagementLayout: " <START> + "Ignoring layout because new epoch < old epoch {}", <END> layout.getEpoch(), currentLayout.getEpoch()); } else { log.trace("saveManagementLayout: " + "Ignoring layout because new epoch equal to old epoch {}", layout.getEpoch(), currentLayout.getEpoch()); } }</code><technical_language>I "Ignoring layout ...." statement trace, info level log anytime accept a newer layout</technical_language>

Target:
public synchronized void saveManagementLayout(Layout layout) { if (layout == null) { log.warn("saveManagementLayout: Attempted to update with null layout"); return; } Layout currentLayout = getManagementLayout(); if (currentLayout == null || layout.getEpoch() > currentLayout.getEpoch()) { dataStore.put(Layout.class, PREFIX_MANAGEMENT, MANAGEMENT_LAYOUT, layout); log.info("saveManagementLayout: Updated to new layout at epoch {}", getManagementLayout().getEpoch()); } else { log.trace("saveManagementLayout: " + "Ignoring layout because new epoch <= old epoch {}", layout.getEpoch(), currentLayout.getEpoch()); } }
Source:
<code>private void handleOffsetOutOfRange(FetchPosition fetchPosition, TopicPartition topicPartition, String reason) { if (subscriptions.hasDefaultOffsetResetPolicy()) { log.info("Fetch offset epoch is out of range for partition {}, resetting offset", fetchPosition, topicPartition); subscriptions.requestOffsetReset(topicPartition); } else { Map<TopicPartition, Long> offsetOutOfRangePartitions = Collections.singletonMap(topicPartition, fetchPosition.offset); String errorMessage = String.format("Offsets out of range " + "with no configured reset policy for partitions: %s" + ", for fetch offset: %d, " + "root cause: %s", offsetOutOfRangePartitions, fetchPosition.offset, reason); <START> log.error(errorMessage); <END> throw new OffsetOutOfRangeException(errorMessage, offsetOutOfRangePartitions); } }</code><technical_language>info in cases? If application set a reset policy, expecting handle exception</technical_language>

Target:
private void handleOffsetOutOfRange(FetchPosition fetchPosition, TopicPartition topicPartition, String reason) { if (subscriptions.hasDefaultOffsetResetPolicy()) { log.info("Fetch offset epoch is out of range for partition {}, resetting offset", fetchPosition, topicPartition); subscriptions.requestOffsetReset(topicPartition); } else { Map<TopicPartition, Long> offsetOutOfRangePartitions = Collections.singletonMap(topicPartition, fetchPosition.offset); String errorMessage = String.format("Offsets out of range " + "with no configured reset policy for partitions: %s" + ", for fetch offset: %d, " + "root cause: %s", offsetOutOfRangePartitions, fetchPosition.offset, reason); log.info(errorMessage); throw new OffsetOutOfRangeException(errorMessage, offsetOutOfRangePartitions); } }
Source:
<code>protected synchronized long doPersist(final PreparedStatement ps, final MappedEntity me, final boolean useAutoInc, final int lastBindPosition) throws Exception { ps.execute(); if (useAutoInc) { <START> for (final DbColumn column : me.getEntity().getColumns()) { if ((column.isAutoInc())) { try (final ResultSet generatedKeys = ps.getGeneratedKeys()) { if (generatedKeys.next()) { return generatedKeys.getLong(column.getName()); } } <END> } } } return 0; }</code><technical_language>I performance of a cycle for final DbColumn column = me.getEntity().getColumns().stream().filter(c -> c.isAutoInc()).findFirst().get(); (that a cycle itself). This is important method need try introduce cyclomatic complexity</technical_language>

Target:
protected synchronized long doPersist(final PreparedStatement ps, final MappedEntity me, final boolean useAutoInc, final int lastBindPosition) throws Exception { ps.execute(); final String autoIncColumnName = me.getAutoIncColumn(); if (useAutoInc && autoIncColumnName != null) { try (final ResultSet generatedKeys = ps.getGeneratedKeys()) { if (generatedKeys.next()) { return generatedKeys.getLong(autoIncColumnName); } } } return 0; }
Source:
<code>public void testCounter() throws Exception { BoundedExecutor boundedExecutor = new BoundedExecutor(executorService, 1); int stageTasks = 100_000; int totalTasks = stageTasks * 2; AtomicInteger counter = new AtomicInteger(); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch completeLatch = new CountDownLatch(totalTasks); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { <START> Uninterruptibles.awaitUninterruptibly(startLatch); END> int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } startLatch.countDown(); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES); Assert.assertEquals(counter.get(), totalTasks); }</code><technical_language>wait for "thead count" threads get</technical_language>

Target:
public void testCounter() throws Exception { int maxThreads = 1; BoundedExecutor boundedExecutor = new BoundedExecutor(executorService, maxThreads); int stageTasks = 100_000; int totalTasks = stageTasks * 2; AtomicInteger counter = new AtomicInteger(); CountDownLatch initializeLatch = new CountDownLatch(maxThreads); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch completeLatch = new CountDownLatch(totalTasks); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { initializeLatch.countDown(); Uninterruptibles.awaitUninterruptibly(startLatch); int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES); startLatch.countDown(); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES); Assert.assertEquals(counter.get(), totalTasks); }
Source:
<code>public int updateOwnership(final String dataType, final int blockId, final int storeId) { try { <START> routerLock.writeLock().lock(); <END> final int oldOwnerId = router.updateOwnership(blockId, storeId); return oldOwnerId; } finally { routerLock.writeLock().unlock(); } }</code><technical_language>Typically lock() try</technical_language>

Target:
public int updateOwnership(final String dataType, final int blockId, final int storeId) { routerLock.writeLock().lock(); try { final int oldOwnerId = router.updateOwnership(blockId, storeId); return oldOwnerId; } finally { routerLock.writeLock().unlock(); } }