auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void readMobilePolicy(Context context) { if (context != null) { final SharedPreferences sp = context.getSharedPreferences(MOBILE_POLICY_PREF, Context.MODE_PRIVATE); if (!sp.contains(KEY_TIMEOUT) || !sp.contains(KEY_PASSCODE_LENGTH)) { timeoutMs = 0; passcodeLength = MIN_PASSCODE_LENGTH; passcodeChangeRequired = false; biometricAllowed = true; biometricEnrollmentShown = false; biometricEnabled = false; storeMobilePolicy(context); return; } timeoutMs = sp.getInt(KEY_TIMEOUT, 0); passcodeLength = sp.getInt(KEY_PASSCODE_LENGTH, MIN_PASSCODE_LENGTH); passcodeLengthKnown = sp.getBoolean(KEY_PASSCODE_LENGTH_KNOWN, false); passcodeChangeRequired = sp.getBoolean(KEY_PASSCODE_CHANGE_REQUIRED, false); <START> biometricAllowed = sp.getBoolean(KEY_BIOMETRIC_ALLOWED, false); <END> biometricEnrollmentShown = sp.getBoolean(KEY_BIOMETRIC_ENROLLMENT, true); biometricEnabled = sp.getBoolean(KEY_BIOMETRIC_ENABLED, false); } }</code><technical_language>biometricAllowed true default? match default assignment of line 262 above</technical_language>

Target:
private void readMobilePolicy(Context context) { if (context != null) { final SharedPreferences sp = context.getSharedPreferences(MOBILE_POLICY_PREF, Context.MODE_PRIVATE); if (!sp.contains(KEY_TIMEOUT) || !sp.contains(KEY_PASSCODE_LENGTH)) { timeoutMs = 0; passcodeLength = MIN_PASSCODE_LENGTH; passcodeChangeRequired = false; biometricAllowed = true; biometricEnrollmentShown = false; biometricEnabled = false; storeMobilePolicy(context); return; } timeoutMs = sp.getInt(KEY_TIMEOUT, 0); passcodeLength = sp.getInt(KEY_PASSCODE_LENGTH, MIN_PASSCODE_LENGTH); passcodeLengthKnown = sp.getBoolean(KEY_PASSCODE_LENGTH_KNOWN, false); passcodeChangeRequired = sp.getBoolean(KEY_PASSCODE_CHANGE_REQUIRED, false); biometricAllowed = sp.getBoolean(KEY_BIOMETRIC_ALLOWED, true); biometricEnrollmentShown = sp.getBoolean(KEY_BIOMETRIC_ENROLLMENT, false); biometricEnabled = sp.getBoolean(KEY_BIOMETRIC_ENABLED, false); } }
Source:
<code>private void postSuccess(final T result) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { <START> callback.onResult(Result.withResult(result)); <END> } }); } }</code><technical_language>Result.success is result non-null? case returning null in a couple of callbacks ..</technical_language>

Target:
private void postSuccess(final T result) { if (callback != null) { handler.post(new Runnable() { @Override public void run() { callback.onResult((result == null) ? Result.success() : Result.withResult(result)); } }); } }
Source:
<code>public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("isConnected", connected); root.add("totalPublishLatencies", totalPublishLatency); root.add("totalPublishedEventCount", totalPublishedEventCount); root.add("outboundQueueSize", outboundQueueSize); <START> root.add("paused", isPaused()); <END> root.add("stopped", isStopped()); return root; }</code><technical_language>public, changed. need compatible for minor version. If this is released 3.9.4-c1, MC 3.9.x MC 3.10.x needs able work this. add extra fields in upcoming MC 3.10.x release. Removing field needs delayed HZ 3.11 adjust codebase expect field</technical_language>

Target:
public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("isConnected", connected); root.add("totalPublishLatencies", totalPublishLatency); root.add("totalPublishedEventCount", totalPublishedEventCount); root.add("outboundQueueSize", outboundQueueSize); root.add("paused", !state.isReplicateEnqueuedEvents()); root.add("stopped", !state.isEnqueueNewEvents()); return root; }
Source:
<code><START> public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client, TemplateDetails details, TestClass testClass) throws Exception { <END> if (testClass == null) { return; } if (details == null) { log.warning(String.format("No environment for %s", testClass.getName())); return; } try { for (List<? extends OpenShiftResource> resources : details.getResources()) { delay(client, resources); } } catch (Throwable t) { throw new DeploymentException("Error waiting for template resources to deploy: " + testClass.getName(), t); } }</code><technical_language>space</technical_language>

Target:
public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client, TemplateDetails details, TestClass testClass) throws Exception { if (testClass == null) { return; } if (details == null) { log.warning(String.format("No environment for %s", testClass.getName())); return; } log.info(String.format("Waiting for environment for %s", testClass.getName())); try { for (List<? extends OpenShiftResource> resources : details.getResources()) { delay(client, resources); } } catch (Throwable t) { throw new DeploymentException("Error waiting for template resources to deploy: " + testClass.getName(), t); } }
Source:
<code>public Set<UnitSupportAttachment> getSupportRules() { if (supportRules == null) { supportRules = UnitSupportAttachment.get(getData()) <START> .parallelStream() <END> .filter(usa -> (usa.getRoll() || usa.getStrength())) .collect(Collectors.toSet()); } return supportRules; }</code><technical_language>happen measure if is a performance boost of parallel stream instead of stream? parallel stream is oddly slower stream</technical_language>

Target:
public Set<UnitSupportAttachment> getSupportRules() { if (supportRules == null) { supportRules = UnitSupportAttachment.get(getData()).stream() .filter(usa -> (usa.getRoll() || usa.getStrength())) .collect(Collectors.toSet()); } return supportRules; }
Source:
<code>private Map<String, Object> buildKuraMessageProperties(final WireRecord wireRecord) { Map<String, TypedValue<?>> wireRecordProps = wireRecord.getProperties(); final Map<String, Object> properties = new HashMap<>(); List<String> l = new ArrayList<>(wireRecordProps.keySet()); <START> for(String s:l) { <END> logger.info("IN buildKuraMessageProperties avec props = {}", s); properties.put(s, wireRecordProps.get(s).getValue()); } return properties; }</code><technical_language>please apply formatting</technical_language>

Target:
private Map<String, Object> buildKuraMessageProperties(final WireRecord wireRecord) { Map<String, TypedValue<?>> wireRecordProps = wireRecord.getProperties(); final Map<String, Object> properties = new HashMap<>(); List<String> l = new ArrayList<>(wireRecordProps.keySet()); for (String s : l) { properties.put(s, wireRecordProps.get(s).getValue()); } return properties; }
Source:
<code>public void statusUpdate(SchedulerDriver driver, TaskStatus status) { TaskID taskId = status.getTaskId(); LOGGER.info("Status update: task " + taskId + " is in state " + status.getState()); if (!results.containsKey(taskId)) { throw new IllegalStateException("Unknown taskId: " + taskId); } Result result = results.get(taskId); boolean cleanupTask = false; switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: break; case TASK_RUNNING: result.result.running(result.slave); break; case TASK_FINISHED: result.result.finished(result.slave); cleanupTask = true; break; case TASK_FAILED: case TASK_KILLED: case TASK_LOST: result.result.failed(result.slave); cleanupTask = true; break; default: throw new IllegalStateException("Invalid State: " + status.getState()); } <START> if (cleanupTask) { <END> results.remove(taskId); } if (mesosCloud.isOnDemandRegistration()) { SchedularSupervisor.supervise(); } }</code><technical_language>I this is a fix for unbounded results map mentioned earlier. split this fix review? s/cleanupTask/terminalState/</technical_language>

Target:
public void statusUpdate(SchedulerDriver driver, TaskStatus status) { TaskID taskId = status.getTaskId(); LOGGER.info("Status update: task " + taskId + " is in state " + status.getState()); if (!results.containsKey(taskId)) { throw new IllegalStateException("Unknown taskId: " + taskId); } Result result = results.get(taskId); switch (status.getState()) { case TASK_STAGING: case TASK_STARTING: break; case TASK_RUNNING: result.result.running(result.slave); break; case TASK_FINISHED: result.result.finished(result.slave); break; case TASK_FAILED: case TASK_KILLED: case TASK_LOST: result.result.failed(result.slave); break; default: throw new IllegalStateException("Invalid State: " + status.getState()); } if (mesosCloud.isOnDemandRegistration()) { supervise(); } }
Source:
<code>private Path getSysfsDevicePath(Path ttyFile) { try { return ttyFile.toRealPath(); } catch (IOException e) { <START> logger.warn("Could not find the device path for in the sysfs; message: {}", ttyFile, e.getMessage()); <END> return null; } }</code><technical_language>..the sysfs ~~; message~~ : {}</technical_language>

Target:
private Path getSysfsDevicePath(Path ttyFile) { try { return ttyFile.toRealPath(); } catch (IOException e) { logger.warn("Could not find the device path for in the sysfs: {}", ttyFile, e.getMessage()); return null; } }
Source:
<code>private static AddModuleWizard selectFileAndCreateWizard() { FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, true, true, false, false) { FileChooserDescriptor myDelegate = new OpenProjectFileChooserDescriptor(true); @Override public Icon getIcon(VirtualFile file) { Icon icon = myDelegate.getIcon(file); return icon == null ? super.getIcon(file) : icon; } }; descriptor.setHideIgnored(false); <START> descriptor.setTitle("Select File or Directory to Import"); <END> String description = "Select a Gradle build script (*.gradle)"; descriptor.setDescription(description); return selectFileAndCreateWizard(descriptor); }</code><technical_language>Select Gradle Project Import</technical_language>

Target:
private static AddModuleWizard selectFileAndCreateWizard() { FileChooserDescriptor descriptor = new FileChooserDescriptor(true, true, true, true, false, false) { FileChooserDescriptor myDelegate = new OpenProjectFileChooserDescriptor(true); @Override public Icon getIcon(VirtualFile file) { Icon icon = myDelegate.getIcon(file); return icon == null ? super.getIcon(file) : icon; } }; descriptor.setHideIgnored(false); descriptor.setTitle("Select Gradle Project Import"); String description = "Select build.gradle or settings.gradle"; descriptor.setDescription(description); return selectFileAndCreateWizard(descriptor); }
Source:
<code>public static void smite(final Player player) { <START> Command_smite.smite(player, reason); <END> }</code><technical_language>please leave this smite(player, reason</technical_language>

Target:
public static void smite(final Player player) { String reason = null; smite(player, reason); }
Source:
<code>private String insertNewWinnerRevision(SQLDatabase db,DocumentBody newWinner, BasicDocumentRevision oldWinner, boolean copyAttachments) throws AttachmentException { String newRevisionId = CouchUtils.generateNextRevisionId(oldWinner.getRevision()); InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = oldWinner.getInternalNumericId(); options.revId = newRevisionId; options.parentSequence = oldWinner.getSequence(); options.deleted = false; options.current = true; options.data = newWinner.asBytes(); options.available = true; options.copyAttachments = copyAttachments; try { this.insertRevision(db,options); } catch (AttachmentException e){ if(copyAttachments){ throw e; }else { <START> throw new RuntimeException("Attachments should not have been copied",e); <END> } } return newRevisionId; }</code><technical_language>This mystery error again</technical_language>

Target:
private String insertNewWinnerRevision(SQLDatabase db,DocumentBody newWinner, BasicDocumentRevision oldWinner, boolean copyAttachments) throws AttachmentException, DatastoreException { String newRevisionId = CouchUtils.generateNextRevisionId(oldWinner.getRevision()); InsertRevisionOptions options = new InsertRevisionOptions(); options.docNumericId = oldWinner.getInternalNumericId(); options.revId = newRevisionId; options.parentSequence = oldWinner.getSequence(); options.deleted = false; options.current = true; options.data = newWinner.asBytes(); options.available = true; if( copyAttachments){ this.insertRevisionAndCopyAttachments(db,options); } else { this.insertRevision(db, options); } return newRevisionId; }
Source:
<code>public void saveOrUpdateShouldDeleteOldestPasswordWhenPasswordHistoryLongerThanLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT + 1); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); given(this.passwordHistoryRepository.findOldestPassword(USER_ID)).willReturn(passwordHistoryEntityList.get(0)); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); <START> then(this.passwordHistoryRepository).should().delete(passwordHistoryEntityList.get(0)); <END> }</code><technical_language>worth check invocations of mock objects</technical_language>

Target:
public void saveOrUpdateShouldDeleteOldestPasswordWhenPasswordHistoryLongerThanLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT + 1); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); given(this.passwordHistoryRepository.findOldestPassword(USER_ID)).willReturn(passwordHistoryEntityList.get(0)); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); then(this.passwordHistoryRepository).should().delete(passwordHistoryEntityList.get(0)); then(this.userRepository).should().findOne(USER_ID); then(this.passwordHistoryRepository).should().save(passwordHistoryEntityWithUserEntity); then(this.passwordHistoryRepository).should().findByUserEntity(userEntityWithId); then(this.passwordHistoryRepository).should().findOldestPassword(USER_ID); }
Source:
<code>static String getMapPrefix(final URL[] resourcePaths) { for (val url : resourcePaths) { <START> try (val zip = new ZipFile(new File(url.toURI()))) { <END> val e = zip.stream().filter($ -> $.getName().endsWith(REQUIRED_ASSET_FOLDER)).findAny(); if (e.isPresent()) { val path = e.get().getName(); return path.substring(0, path.length() - REQUIRED_ASSET_FOLDER.length()); } } catch (IOException | URISyntaxException e) { } } return ""; }</code><technical_language>checked performance of this method? - tested for case map is a directory a zip</technical_language>

Target:
static String getMapPrefix(final URL[] resourcePaths) { for (final URL url : resourcePaths) { try (ZipFile zip = new ZipFile(new File(url.toURI()))) { final Optional<? extends ZipEntry> baseTilesEntry = zip.stream().filter(entry -> entry.getName().endsWith(REQUIRED_ASSET_EXAMPLE_FOLDER)).findAny(); if (baseTilesEntry.isPresent()) { final String path = baseTilesEntry.get().getName(); return path.substring(0, path.length() - REQUIRED_ASSET_EXAMPLE_FOLDER.length()); } } catch (final IOException | URISyntaxException e) { } } return ""; }
Source:
<code>private List<VocabularyTerm> sortTermsByLevel(Collection<VocabularyTerm> terms) { List<VocabularyTerm> sortedTerms = new LinkedList<>(); Map<Long, VocabularyTerm> levelMap = new HashMap<>(); for (VocabularyTerm term : terms) { <START> levelMap.put(term.getDistanceTo(this.getRootTerm()), term); <END> } Set<Long> keys = levelMap.keySet(); List<Long> sortedKeys = new LinkedList<>(); for (Long key : keys) { sortedKeys.add(key); } Collections.sort(sortedKeys); Collections.reverse(sortedKeys); for (Long key : sortedKeys) { sortedTerms.add(levelMap.get(key)); } return sortedTerms; }</code><technical_language>this code simplified a comparator</technical_language>

Target:
private List<VocabularyTerm> sortTermsByLevel(Collection<VocabularyTerm> terms) { List<VocabularyTerm> sortedTerms = new LinkedList<>(); final Map<VocabularyTerm, Long> levelMap = new HashMap<>(); for (VocabularyTerm term : terms) { levelMap.put(term, term.getDistanceTo(this.getRootTerm())); sortedTerms.add(term); } Collections.sort(sortedTerms, (new Comparator<VocabularyTerm>() { @Override public int compare(VocabularyTerm o1, VocabularyTerm o2) { if (levelMap.get(o1) > levelMap.get(o2)) { return -1; } else { return 1; } } })); return sortedTerms; }
Source:
<code>private void doUpdateWithBody(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { log.trace("Processing merging update"); final ServletFileUpload upload = new ServletFileUpload(factory); FileItem insertStatements = null; FileItem valueSet = null; FileItem refSet = null; try { final List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { insertStatements = checkFileItem(item, insertStatements, "insertStatements"); valueSet = checkFileItem(item, valueSet, "valueSet"); refSet = checkFileItem(item, refSet, "refSet"); } } catch (FileUploadException ex) { throw new IOException(ex); } final String baseURI = req.getRequestURL().toString(); final String namespace = getNamespace(req); try { submitApiTask( new MergingUpdateWithBodyTask(req, resp, namespace, ITx.UNISOLATED, baseURI, insertStatements, valueSet, refSet, UrisSchemeFactory.getURISystem() )).get(); <START> insertStatements.delete(); valueSet.delete(); refSet.delete(); <END> } catch (DatasetNotFoundException | InterruptedException | ExecutionException | TimeoutException t) { launderThrowable( t, resp, getErrorMessage(insertStatements, baseURI)); } }</code><technical_language>Cleanup done in a finally block. Guava's Closer abused manage multiple resources, of some wrapper (see Update class for example)</technical_language>

Target:
private void doUpdateWithBody(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { log.trace("Processing merging update"); final ServletFileUpload upload = new ServletFileUpload(factory); FileItem insertStatements = null; FileItem valueSet = null; FileItem refSet = null; final List<FileItem> items; try { items = upload.parseRequest(req); } catch (FileUploadException ex) { throw new IOException(ex); } try { for (FileItem item : items) { insertStatements = checkFileItem(item, insertStatements, "insertStatements"); valueSet = checkFileItem(item, valueSet, "valueSet"); refSet = checkFileItem(item, refSet, "refSet"); } final String baseURI = req.getRequestURL().toString(); final String namespace = getNamespace(req); try { submitApiTask( new MergingUpdateWithBodyTask(req, resp, namespace, ITx.UNISOLATED, baseURI, insertStatements, valueSet, refSet, UrisSchemeFactory.getURISystem() )).get(); } catch (DatasetNotFoundException | InterruptedException | ExecutionException | TimeoutException t) { launderThrowable( t, resp, getErrorMessage(insertStatements, baseURI)); } } finally { for (FileItem item: items) { item.delete(); } } }
Source:
<code>public void setPrimaryView(@Nonnull View v) { <START> if (hasPermission(ADMINISTER)) { <END> this.primaryView = v.getViewName(); } }</code><technical_language>is this CONFIGURE</technical_language>

Target:
public void setPrimaryView(@Nonnull View v) { checkPermission(Jenkins.ADMINISTER); this.primaryView = v.getViewName(); }
Source:
<code>protected CapturesToolWindowFixture(@NotNull Project project, @NotNull Robot robot) { super(CapturesToolWindowFactory.TOOL_WINDOW_ID, project, robot); show(); myTreeFixture = new JTreeFixture(robot, getTree()); <START> pause(new Condition("Wait for tree to load.") { @Override public boolean test() { TreeNode root = (TreeNode)myTreeFixture.target().getModel().getRoot(); return root != null && root.getChildCount() > 0 && !(root instanceof LoadingNode); } }, SHORT_TIMEOUT); <END> }</code><technical_language>This pause is needed exposes of internals</technical_language>

Target:
protected CapturesToolWindowFixture(@NotNull Project project, @NotNull Robot robot) { super(CapturesToolWindowFactory.TOOL_WINDOW_ID, project, robot); show(); myTreeFixture = new JTreeFixture(robot, getTree()); }
Source:
<code>public Integer createGermplasmListFolder(final String cropName, final String programUUID, final String folderName, final String parentId) { errors = new MapBindingResult(new HashMap<String, String>(), String.class.getName()); <START> if (StringUtils.isEmpty(folderName)) { <END> this.errors.reject("list.folder.empty", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } this.validateProgram(cropName, programUUID); this.validateNodeId(parentId, programUUID, ListNodeType.PARENT); final Integer parent = this.getFolderIdAsInteger(parentId); this.validateNotSameFolderNameInParent(folderName, parent, programUUID); final WorkbenchUser createdBy = this.securityService.getCurrentlyLoggedInUser(); return this.germplasmListService.createGermplasmListFolder(createdBy.getUserid(), folderName, parent, programUUID); }</code><technical_language>create functions repeated validations</technical_language>

Target:
public Integer createGermplasmListFolder(final String cropName, final String programUUID, final String folderName, final String parentId) { errors = new MapBindingResult(new HashMap<String, String>(), String.class.getName()); if (parentId.equals(CROP_LISTS)) { this.errors.reject("list.parent.id.invalid", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } this.validateFolderName(folderName); this.validateProgram(cropName, programUUID); this.validateNodeId(parentId, programUUID, ListNodeType.PARENT); final Integer parent = this.getFolderIdAsInteger(parentId); this.validateNotSameFolderNameInParent(folderName, parent, programUUID); final WorkbenchUser createdBy = this.securityService.getCurrentlyLoggedInUser(); return this.germplasmListService.createGermplasmListFolder(createdBy.getUserid(), folderName, parent, programUUID); }
Source:
<code>public void read_failure_ifObjectWasModifiedDuringRead() throws IOException { String bucketName = sharedBucketName1; String object = "generation-strict-" + UUID.randomUUID(); String message1 = "Hello world!\n"; String message2 = "Sayonara world!\n"; gcsiHelper.writeTextFile(bucketName, object, message1); int offset = 5; GoogleCloudStorageReadOptions readOptions = GoogleCloudStorageReadOptions.builder() .setFadvise(Fadvise.RANDOM) .setMinRangeRequestSize(0) .build(); try (SeekableByteChannel readChannel = gcsiHelper.open(bucketName, object, readOptions)) { String read1 = gcsiHelper.readText(readChannel, 0, offset, false); assertWithMessage("partial read mismatch") .that(read1) .isEqualTo(message1.substring(0, offset)); gcsiHelper.writeTextFileOverwriting(bucketName, object, message2); FileNotFoundException expected = assertThrows( FileNotFoundException.class, () -> gcsiHelper.readText(readChannel, offset, message1.length() - offset, true)); assertThat(expected) .hasMessageThat() .contains( "Note, it is possible that the live version is still available" + " but the requested generation is deleted."); <START> assertThat(expected).hasMessageThat().contains("generation"); <END> } }</code><technical_language>this check deleted now</technical_language>

Target:
public void read_failure_ifObjectWasModifiedDuringRead() throws IOException { String bucketName = sharedBucketName1; String object = "generation-strict-" + UUID.randomUUID(); String message1 = "Hello world!\n"; String message2 = "Sayonara world!\n"; gcsiHelper.writeTextFile(bucketName, object, message1); int offset = 5; GoogleCloudStorageReadOptions readOptions = GoogleCloudStorageReadOptions.builder() .setFadvise(Fadvise.RANDOM) .setMinRangeRequestSize(0) .build(); try (SeekableByteChannel readChannel = gcsiHelper.open(bucketName, object, readOptions)) { String read1 = gcsiHelper.readText(readChannel, 0, offset, false); assertWithMessage("partial read mismatch") .that(read1) .isEqualTo(message1.substring(0, offset)); gcsiHelper.writeTextFileOverwriting(bucketName, object, message2); FileNotFoundException expected = assertThrows( FileNotFoundException.class, () -> gcsiHelper.readText(readChannel, offset, message1.length() - offset, true)); assertThat(expected) .hasMessageThat() .contains( "Note, it is possible that the live version is still available" + " but the requested generation is deleted."); } }
Source:
<code>public GlusterBricks list() { <START> try { <END> VdcQueryReturnValue returnValue = runQuery(VdcQueryType.GetGlusterVolumeBricks, new IdQueryParameters(asGuid(getVolumeId()))); if (!returnValue.getSucceeded()) { throw new BackendFailureException(localize(returnValue.getExceptionString())); } List<GlusterBrickEntity> bricks = (List<GlusterBrickEntity>) returnValue.getReturnValue(); return mapCollection(bricks); } catch (Exception e) { return handleError(e, false); } }</code><technical_language>please getBackendCollection() instead of this code</technical_language>

Target:
public GlusterBricks list() { List<GlusterBrickEntity> bricks = getBackendCollection(VdcQueryType.GetGlusterVolumeBricks, new IdQueryParameters(asGuid(getVolumeId()))); return mapCollection(bricks); }
Source:
<code>protected LamiGraphRange getRange(List<LamiTableEntryAspect> aspects, boolean clampToZero) { BigDecimal min = new BigDecimal(Long.MAX_VALUE); BigDecimal max = new BigDecimal(Long.MIN_VALUE); for (LamiTableEntryAspect lamiTableEntryAspect : aspects) { for (LamiTableEntry entry : getResultTable().getEntries()) { @Nullable Number number = lamiTableEntryAspect.resolveNumber(entry); if (number != null) { BigDecimal current = new BigDecimal(number.toString()); min = current.min(min); max = current.max(max); } } } if (clampToZero) { min.min(BigDecimal.ZERO); } if (max.equals(min)) { <START> max = min.add(new BigDecimal(1)); <END> } return new LamiGraphRange(checkNotNull(min), checkNotNull(max)); }</code><technical_language>a BigDecimal.ONE ! if wasn't, extracted a constant</technical_language>

Target:
protected LamiGraphRange getRange(List<LamiTableEntryAspect> aspects, boolean clampToZero) { BigDecimal min = new BigDecimal(Long.MAX_VALUE); BigDecimal max = new BigDecimal(Long.MIN_VALUE); for (LamiTableEntryAspect lamiTableEntryAspect : aspects) { for (LamiTableEntry entry : getResultTable().getEntries()) { @Nullable Number number = lamiTableEntryAspect.resolveNumber(entry); if (number != null) { BigDecimal current = new BigDecimal(number.toString()); min = current.min(min); max = current.max(max); } } } if (clampToZero) { min.min(BigDecimal.ZERO); } if (max.equals(min)) { max = min.add(BigDecimal.ONE); } return new LamiGraphRange(checkNotNull(min), checkNotNull(max)); }
Source:
<code>public void testRecycleCurrentBufferOnFailure() throws Exception { final ResultPartition resultPartition = createPartition(ResultPartitionType.BLOCKING, fileChannelManager); final BoundedBlockingSubpartition subpartition = new BoundedBlockingSubpartition( 0, resultPartition, new FailingBoundedData(), !sslEnabled && type == BoundedBlockingSubpartitionType.FILE); final BufferConsumer consumer = BufferBuilderTestUtils.createFilledFinishedBufferConsumer(100); try { try { subpartition.add(consumer); subpartition.createReadView(new NoOpBufferAvailablityListener()); fail("should fail with an exception"); } catch (Exception ignored) { } assertNotNull(subpartition.getCurrentBuffer()); assertFalse(subpartition.getCurrentBuffer().isRecycled()); } finally { subpartition.release(); <START> assertNull(subpartition.getCurrentBuffer()); <END> } }</code><technical_language>code is testing if buffer is recycled. assertTrue(consumer.isRecycled())</technical_language>

Target:
public void testRecycleCurrentBufferOnFailure() throws Exception { final ResultPartition resultPartition = createPartition(ResultPartitionType.BLOCKING, fileChannelManager); final BoundedBlockingSubpartition subpartition = new BoundedBlockingSubpartition( 0, resultPartition, new FailingBoundedData(), !sslEnabled && type == BoundedBlockingSubpartitionType.FILE); final BufferConsumer consumer = BufferBuilderTestUtils.createFilledFinishedBufferConsumer(100); try { try { subpartition.add(consumer); subpartition.createReadView(new NoOpBufferAvailablityListener()); fail("should fail with an exception"); } catch (Exception ignored) { } assertFalse(consumer.isRecycled()); assertNotNull(subpartition.getCurrentBuffer()); assertFalse(subpartition.getCurrentBuffer().isRecycled()); } finally { subpartition.release(); assertTrue(consumer.isRecycled()); assertNull(subpartition.getCurrentBuffer()); } }
Source:
<code>public Collection<TopicPartition> onPartitionsAssigned(Collection<TopicPartition> partitions) { <START> return new HashSet<>(); <END> }</code><technical_language>nit: create static variable for this empty set return static variable</technical_language>

Target:
public Collection<TopicPartition> onPartitionsAssigned(Collection<TopicPartition> partitions) { return _emptyPartitions; }
Source:
<code>public final void addSystemEnvironment() { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); for ( String key : systemEnvVars.stringPropertyNames() ) { <START> if ( !addedEnvironmentVariables.contains( key ) && !excludedEnvironmentVariables.contains( key ) ) <END> { super.addEnvironment( key, systemEnvVars.getProperty( key ) ); } } }</code><technical_language>yes, this is I mean. LGTM</technical_language>

Target:
public final void addSystemEnvironment() { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); for ( String key : systemEnvVars.stringPropertyNames() ) { if ( !addedEnvironmentVariables.contains( key ) && !excludedEnvironmentVariables.contains( key ) ) { addEnvironment( key, systemEnvVars.getProperty( key ) ); } } }
Source:
<code>public void testFileHandlesLeak() throws Exception { final EnvInjectPasswordWrapper passwordWrapper = new EnvInjectPasswordWrapper(); passwordWrapper.setPasswordEntries(new EnvInjectPasswordEntry[]{ new EnvInjectPasswordEntry(PWD_KEY, PWD_VALUE) }); final FileLeakBuildWrapper fileLeakDetector = new FileLeakBuildWrapper(); project.getBuildWrappersList().add(fileLeakDetector); project.getBuildWrappersList().add(passwordWrapper); @SuppressWarnings("deprecation") FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause()).get(); <START> Assert.assertEquals(Result.SUCCESS, build.getResult()); <END> Assert.assertTrue("Nested output stream has not been closed", fileLeakDetector.getLastOutputStream().isClosed()); }</code><technical_language>Tip: java buildAndAssertSuccess(project); intermediate steps, omit Cause, assertBuildStatusSuccess, etc</technical_language>

Target:
public void testFileHandlesLeak() throws Exception { final EnvInjectPasswordWrapper passwordWrapper = new EnvInjectPasswordWrapper(); passwordWrapper.setPasswordEntries(new EnvInjectPasswordEntry[]{ new EnvInjectPasswordEntry(PWD_KEY, PWD_VALUE) }); final FileLeakBuildWrapper fileLeakDetector = new FileLeakBuildWrapper(); project.getBuildWrappersList().add(fileLeakDetector); project.getBuildWrappersList().add(passwordWrapper); @SuppressWarnings("deprecation") FreeStyleBuild build = project.scheduleBuild2(0).get(); assertBuildStatusSuccess(build); Assert.assertTrue("Nested output stream has not been closed", fileLeakDetector.getLastOutputStream().isClosed()); }
Source:
<code>private SenderClient(Builder builder) { this.setServerURL(builder.rootServerURL); this.proxyHost = builder.proxyHost; this.proxyPort = builder.proxyPort; this.proxyUser = builder.proxyUser; this.proxyPassword = builder.proxyPassword; <START> this.proxyType = builder.proxyType; <END> this.trustStorePath = builder.trustStorePath; this.trustStorePassword = builder.trustStorePassword; this.trustStoreType = builder.trustStoreType; }</code><technical_language>Tolis, mind move code another class</technical_language>

Target:
private SenderClient(Builder builder) { this.setServerURL(builder.rootServerURL); this.proxy = builder.proxy; this.customTrustStore = builder.customTrustStore; }
Source:
<code>public StoreFileStream acquire( String destination, int requiredAlignment ) throws IOException { File fileName = new File( storeDir, destination ); fs.mkdirs( fileName.getParentFile() ); fileCopyMonitor.copyFile( fileName ); <START> if ( StoreType.shouldBeManagedByPageCache( destination ) ) <END> { int filePageSize = pageCache.pageSize() - pageCache.pageSize() % requiredAlignment; PagedFile pagedFile = pageCache.map( fileName, filePageSize, StandardOpenOption.CREATE ); return new StreamToDisk( pagedFile.openWritableByteChannel(), pagedFile ); } else { return new StreamToDisk( Channels.newChannel( fs.openAsOutputStream( fileName, false ) ) ); } }</code><technical_language>This needs brought speed changes in #11231</technical_language>

Target:
public StoreFileStream acquire( String destination, int requiredAlignment ) throws IOException { File fileName = new File( storeDir, destination ); fs.mkdirs( fileName.getParentFile() ); fileCopyMonitor.copyFile( fileName ); if ( !pageCache.fileSystemSupportsFileOperations() && StoreType.canBeManagedByPageCache( destination ) ) { int filePageSize = pageCache.pageSize() - pageCache.pageSize() % requiredAlignment; PagedFile pagedFile = pageCache.map( fileName, filePageSize, StandardOpenOption.CREATE ); return StreamToDisk.fromPagedFile( pagedFile ); } else { return StreamToDisk.fromFile( fs, fileName ); } }
Source:
<code>private void parseAdapterList(final EList<AdapterDeclaration> adpaterList, String adpaterListName, boolean isInput) throws TypeImportException, XMLStreamException { processChildren(adpaterListName, name -> { if <START> (name.equals(LibraryElementTags.ADAPTER_DECLARATION_ELEMENT)) { <END> AdapterDeclaration a = parseAdapterDeclaration(); a.setIsInput(isInput); adapters.put(a.getName(), a); adpaterList.add(a); if (null != a.getType() && null != a.getType().getInterfaceList()) { if (isInput) { addAdapterEventInputs(a.getType().getInterfaceList().getEventOutputs(), a); addAdapterEventOutputs(a.getType().getInterfaceList().getEventInputs(), a); } else { addAdapterEventInputs(a.getType().getInterfaceList().getEventInputs(), a); addAdapterEventOutputs(a.getType().getInterfaceList().getEventOutputs(), a); } } return true; } return false; }); }</code><technical_language>call equal constant</technical_language>

Target:
private void parseAdapterList(final EList<AdapterDeclaration> adpaterList, String adpaterListName, boolean isInput) throws TypeImportException, XMLStreamException { processChildren(adpaterListName, name -> { if (LibraryElementTags.ADAPTER_DECLARATION_ELEMENT.equals(name)) { AdapterDeclaration a = parseAdapterDeclaration(); a.setIsInput(isInput); adapters.put(a.getName(), a); adpaterList.add(a); if ((null != a.getType()) && (null != a.getType().getInterfaceList())) { if (isInput) { addAdapterEventInputs(a.getType().getInterfaceList().getEventOutputs(), a); addAdapterEventOutputs(a.getType().getInterfaceList().getEventInputs(), a); } else { addAdapterEventInputs(a.getType().getInterfaceList().getEventInputs(), a); addAdapterEventOutputs(a.getType().getInterfaceList().getEventOutputs(), a); } } return true; } return false; }); }
Source:
<code>public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { PrintWriter p = toPrintWriter(out); parseCommandLine(); if (!suggestParent) { if (projectName == null) { p.println("fatal: Option \"--name (-n)\" is required"); p.flush(); return; } try { createProject(); } catch (Exception e) { p.print("Error when trying to create project: " + e.getMessage() + "\n"); p.flush(); } } else { List<Project.NameKey> parentCandidates = retrieveParentCandidates.getParentCandidates(); <START> p.println("Parent Suggestions:"); <END> for (Project.NameKey parent : parentCandidates) { p.println(parent.get()); } p.flush(); } } }); }</code><technical_language>asked for parent suggestions, do need this header line</technical_language>

Target:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { PrintWriter p = toPrintWriter(out); parseCommandLine(); if (!suggestParent) { if (projectName == null) { p.println("fatal: Option \"--name (-n)\" is required"); p.flush(); return; } try { createProject(); } catch (Exception e) { p.print("Error when trying to create project: " + e.getMessage() + "\n"); p.flush(); } } else { List<Project.NameKey> parentCandidates = retrieveParentCandidates.getParentCandidates(); for (Project.NameKey parent : parentCandidates) { p.print(parent.get() + "\n"); } p.flush(); } } }); }
Source:
<code>public void customize() { newScript(CUSTOMIZING). body.append("echo copying creation script"). execute(); copyDatabaseCreationScript(); newScript(CUSTOMIZING). updateTaskAndFailOnNonZeroResultCode(). body.append( "touch mymysql.cnf", "chmod 600 mymysql.cnf", <START> "cat > mymysql.cnf << END_MYSQL_CONF_"+entity.getId()+"\n"+ <END> getDatabaseConfigScript()+ "\nEND_MYSQL_CONF_"+entity.getId()+"\n", getBasedir()+"/scripts/mysql_install_db "+ "--basedir="+getBasedir()+" --datadir="+getDatadir()+" "+ "--defaults-file=mymysql.cnf", getBasedir()+"/bin/mysqld --defaults-file=mymysql.cnf --user=`whoami` &", "export MYSQL_PID=$!", "sleep 20", "echo launching mysqladmin", getBasedir()+"/bin/mysqladmin --defaults-file=mymysql.cnf --password= password "+getPassword(), "sleep 20", "echo launching mysql creation script", getBasedir()+"/bin/mysql --defaults-file=mymysql.cnf < creation-script.cnf", "echo terminating mysql on customization complete", "kill $MYSQL_PID" ).execute(); }</code><technical_language>Instead of cat > mysql.cnf ..., getMachine().copyTo(...)? cat is giving else here</technical_language>

Target:
public void customize() { copyDatabaseCreationScript(); copyDatabaseConfigScript(); newScript(CUSTOMIZING). updateTaskAndFailOnNonZeroResultCode(). body.append( "chmod 600 mymysql.cnf", getBasedir()+"/scripts/mysql_install_db "+ "--basedir="+getBasedir()+" --datadir="+getDatadir()+" "+ "--defaults-file=mymysql.cnf", getBasedir()+"/bin/mysqld --defaults-file=mymysql.cnf --user=`whoami` &", "export MYSQL_PID=$!", "sleep 20", "echo launching mysqladmin", getBasedir()+"/bin/mysqladmin --defaults-file=mymysql.cnf --password= password "+getPassword(), "sleep 20", "echo launching mysql creation script", getBasedir()+"/bin/mysql --defaults-file=mymysql.cnf < creation-script.cnf", "echo terminating mysql on customization complete", "kill $MYSQL_PID" ).execute(); }
Source:
<code>protected void initWidgets() { catBox = new ListBox(); catBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(final ChangeEvent event) { updateCategorySelection(); } }); nameTxt = new HintTextBox(); nameSug = new SuggestBox(new AccountGroupSuggestOracle(), nameTxt); nameTxt.setVisibleLength(50); nameTxt.setHintText(Util.C.defaultAccountGroupName()); <START> nameTxt.setHintStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); <END> referenceTxt = new HintTextBox(); referenceTxt.setVisibleLength(50); referenceTxt.setText(""); referenceTxt.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewRight(); } } }); topBox = new ListBox(); botBox = new ListBox(); addBut = new Button(Util.C.buttonAddProjectRight()); addBut.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewRight(); } }); clearBut = new Button(Util.C.buttonClearProjectRight()); clearBut.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { clear(); } }); }</code><technical_language>this assumed HintTextBox</technical_language>

Target:
protected void initWidgets() { catBox = new ListBox(); catBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(final ChangeEvent event) { updateCategorySelection(); } }); nameTxt = new HintTextBox(); nameSug = new SuggestBox(new AccountGroupSuggestOracle(), nameTxt); nameTxt.setVisibleLength(50); nameTxt.setHintText(Util.C.defaultAccountGroupName()); referenceTxt = new HintTextBox(); referenceTxt.setVisibleLength(50); referenceTxt.setText(""); referenceTxt.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doAddNewRight(); } } }); topBox = new ListBox(); botBox = new ListBox(); addBut = new Button(Util.C.buttonAddProjectRight()); addBut.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewRight(); } }); clearBut = new Button(Util.C.buttonClearProjectRight()); clearBut.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { clear(); } }); }
Source:
<code>private void createSchemaType(ContentType contentType, final Map<String, GraphQLObjectType> graphqlObjectTypes) { if(!contentType.variable().matches(TYPES_AND_FIELDS_VALID_NAME_REGEX)) { return; } final GraphQLObjectType.Builder builder = GraphQLObjectType.newObject().name(contentType.variable()); builder.fields(InterfaceType.CONTENTLET.getType().getFieldDefinitions()); if(InterfaceType.getInterfaceForBaseType(contentType.baseType())!=null) { builder.withInterface(InterfaceType.getInterfaceForBaseType(contentType.baseType())); } final List<Field> fields = contentType.fields(); fields.forEach((field)->{ if(!field.variable().matches(TYPES_AND_FIELDS_VALID_NAME_REGEX) || field instanceof RelationshipsTabField) { return; } if(!(field instanceof RowField) && !(field instanceof ColumnField)) { if (field instanceof RelationshipField) { try { handleRelationshipField(contentType, builder, field, graphqlObjectTypes); <START> } catch(Exception e) { <END> Logger.error(this, "Unable to create relationship field", e); } } else { builder.field(newFieldDefinition() .name(field.variable()) .type(field.required() ? nonNull(getGraphqlTypeForFieldClass(field.type(), field)) : getGraphqlTypeForFieldClass(field.type(), field)) .dataFetcher(getGraphqlDataFetcherForFieldClass(field.type())) ); } } }); builder.withInterface(InterfaceType.CONTENTLET.getType()); final GraphQLObjectType graphQLType = builder.build(); graphqlObjectTypes.put(graphQLType.getName(), graphQLType); }</code><technical_language>do need catch Exception?, catch another more specific exception</technical_language>

Target:
private void createSchemaType(ContentType contentType, final Map<String, GraphQLObjectType> graphqlObjectTypes) { if(!contentType.variable().matches(TYPES_AND_FIELDS_VALID_NAME_REGEX)) { return; } final GraphQLObjectType.Builder builder = GraphQLObjectType.newObject().name(contentType.variable()); builder.fields(InterfaceType.CONTENTLET.getType().getFieldDefinitions()); if(InterfaceType.getInterfaceForBaseType(contentType.baseType())!=null) { builder.withInterface(InterfaceType.getInterfaceForBaseType(contentType.baseType())); } final List<Field> fields = contentType.fields(); fields.forEach((field)->{ if(!field.variable().matches(TYPES_AND_FIELDS_VALID_NAME_REGEX) || field instanceof RelationshipsTabField) { return; } if(!(field instanceof RowField) && !(field instanceof ColumnField)) { if (field instanceof RelationshipField) { try { handleRelationshipField(contentType, builder, field, graphqlObjectTypes); } catch(DotStateException e) { Logger.error(this, "Unable to create relationship field", e); } } else { builder.field(newFieldDefinition() .name(field.variable()) .type(field.required() ? nonNull(getGraphqlTypeForFieldClass(field.type(), field)) : getGraphqlTypeForFieldClass(field.type(), field)) .dataFetcher(getGraphqlDataFetcherForFieldClass(field.type())) ); } } }); builder.withInterface(InterfaceType.CONTENTLET.getType()); final GraphQLObjectType graphQLType = builder.build(); graphqlObjectTypes.put(graphQLType.getName(), graphQLType); }
Source:
<code>public void testDoubleSkip() { Cache<Double, String> cache = getCache(0); int range = 10; IntStream.range(0, range).mapToDouble(value -> value).forEach(i -> cache.put(i, i + "-value")); CacheSet<Double> keySet = cache.keySet(); for (int i = 0; i < range; i++) { List<Double> res = createStream(keySet) <START> .sorted().skip(i).collect(Collectors.toList()); <END> assertEquals(0, IntStream.range(0, range - res.size()).mapToDouble(v -> v).filter(res::contains).count()); } }</code><technical_language>Need add a assertEquals(i, range - res.size()); good</technical_language>

Target:
public void testDoubleSkip() { Cache<Double, String> cache = getCache(0); int range = 10; IntStream.range(0, range).mapToDouble(value -> value).forEach(i -> cache.put(i, i + "-value")); CacheSet<Double> keySet = cache.keySet(); for (int i = 0; i < range; i++) { List<Double> res = createStream(keySet) .sorted().skip(i).collect(Collectors.toList()); assertEquals(range - i, res.size()); assertEquals(0, IntStream.range(0, range - res.size()).mapToDouble(v -> v).filter(res::contains).count()); } }
Source:
<code>public String determineFirstName(Optional<User> user) { <START> return Buddy.determineName(this::getFirstName, user, User::getFirstName, "message.alternative.first.name", getNickname()); <END> }</code><technical_language>Buddy.determineName -> determineName</technical_language>

Target:
public String determineFirstName(Optional<User> user) { return determineName(this::getFirstName, user, User::getFirstName, "message.alternative.first.name", getNickname()); }
Source:
<code>public void testRegenerateConsumerSecret() { String gatewayURL = getGatewayURLNhttp(); String keyManagerURL = getKeyManagerURLHttp(); String dataFileName = "ApplicationRegenerateConsumerSecretTestCase.txt"; <START> String dataFilePath = (new File(System.getProperty("user.dir"))).getParent() + <END> RESTAPITestConstants.PATH_SUBSTRING + dataFileName; boolean testSuccessStatus = new RESTAPITestUtil().testRestAPI(dataFilePath, gatewayURL, keyManagerURL); assertTrue(testSuccessStatus); }</code><technical_language>move "user.dir" a String constant</technical_language>

Target:
public void testRegenerateConsumerSecret() { String gatewayURL = getGatewayURLNhttp(); String keyManagerURL = getKeyManagerURLHttp(); String dataFileName = "ApplicationRegenerateConsumerSecretTestCase.txt"; String dataFilePath = (new File(System.getProperty(RESTAPITestConstants.USER_DIR))).getParent() + RESTAPITestConstants.PATH_SUBSTRING + dataFileName; boolean testSuccessStatus = new RESTAPITestUtil().testRestAPI(dataFilePath, gatewayURL, keyManagerURL); assertTrue(testSuccessStatus); }
Source:
<code>public static Statistics toParquetStatistics( org.apache.parquet.column.statistics.Statistics stats, int truncateLength) { Statistics formatStats = new Statistics(); <START> if (!stats.isEmpty() && stats.isSmallerThan(MAX_STATS_SIZE)) { <END> formatStats.setNull_count(stats.getNumNulls()); if (stats.hasNonNullValue()) { byte[] min; byte[] max; if (stats instanceof BinaryStatistics && truncateLength != Integer.MAX_VALUE) { BinaryTruncator truncator = BinaryTruncator.getTruncator(stats.type()); min = tuncateMin(truncator, truncateLength, stats.getMinBytes()); max = tuncateMax(truncator, truncateLength, stats.getMaxBytes()); } else { min = stats.getMinBytes(); max = stats.getMaxBytes(); } if (sortOrder(stats.type()) == SortOrder.SIGNED || Arrays.equals(min, max)) { formatStats.setMin(min); formatStats.setMax(max); } if (isMinMaxStatsSupported(stats.type()) || Arrays.equals(min, max)) { formatStats.setMin_value(min); formatStats.setMax_value(max); } } } return formatStats; }</code><technical_language>So, truncating if size is large? other around: check size truncate</technical_language>

Target:
public static Statistics toParquetStatistics( org.apache.parquet.column.statistics.Statistics stats, int truncateLength) { Statistics formatStats = new Statistics(); if (!stats.isEmpty() && withinLimit(stats, truncateLength)) { formatStats.setNull_count(stats.getNumNulls()); if (stats.hasNonNullValue()) { byte[] min; byte[] max; if (stats instanceof BinaryStatistics && truncateLength != Integer.MAX_VALUE) { BinaryTruncator truncator = BinaryTruncator.getTruncator(stats.type()); min = tuncateMin(truncator, truncateLength, stats.getMinBytes()); max = tuncateMax(truncator, truncateLength, stats.getMaxBytes()); } else { min = stats.getMinBytes(); max = stats.getMaxBytes(); } if (sortOrder(stats.type()) == SortOrder.SIGNED || Arrays.equals(min, max)) { formatStats.setMin(min); formatStats.setMax(max); } if (isMinMaxStatsSupported(stats.type()) || Arrays.equals(min, max)) { formatStats.setMin_value(min); formatStats.setMax_value(max); } } } return formatStats; }