auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkWhereArguments(WhereClauses whereClauses, List<byte[]> expectedArgs) { List<Object> actualArgs = whereClauses.getArguments(); for (int i = 0; i < actualArgs.size(); i++) { assertThat((byte[]) actualArgs.get(i)).isEqualTo(expectedArgs.get(i)); } assertThat(actualArgs.size()).isEqualTo(expectedArgs.size()); }

Target:
private void checkWhereArguments(WhereClauses whereClauses, List<byte[]> expectedArgs) { List<Object> actualArgs = whereClauses.getArguments(); for (int i = 0; i < actualArgs.size(); i++) { assertThat((byte[]) actualArgs.get(i)).isEqualTo(expectedArgs.get(i)); } assertThat(actualArgs).hasSameSizeAs(expectedArgs); }
Source:
public static boolean isTCCPacket(ByteArrayBuffer baf) { int rc = RTCPHeaderUtils.getReportCount(baf); return isRTPFBPacket(baf) && rc == FMT; }

Target:
public static boolean isTCCPacket(ByteArrayBuffer baf) { int rc = RTCPHeaderUtils.getReportCount(baf); return rc == FMT && isRTPFBPacket(baf); }
Source:
private static boolean shouldShowChooserDialog(long siteId, String serviceId, JSONObject jsonObject) { JSONArray jsonConnectionList = jsonObject.optJSONArray("connections"); if (jsonConnectionList == null || jsonConnectionList.length() <= 1) { return false; } int totalAccounts = 0; int totalExternalAccounts = 0; try { for (int i = 0; i < jsonConnectionList.length(); i++) { JSONObject connectionObject = jsonConnectionList.getJSONObject(i); PublicizeConnection publicizeConnection = PublicizeConnection.fromJson(connectionObject); if (publicizeConnection.getService().equals(serviceId) && !publicizeConnection.isInSite(siteId)) { totalAccounts++; JSONArray externalJsonArray = connectionObject.getJSONArray("additional_external_users"); for (int j = 0; j < externalJsonArray.length(); j++) { totalExternalAccounts++; } } } if (PublicizeTable.onlyExternalConnections(serviceId)) { return totalAccounts > 0; } else { return totalAccounts > 0 || totalExternalAccounts > 0; } } catch (JSONException e) { return false; } }

Target:
private static boolean shouldShowChooserDialog(long siteId, String serviceId, JSONObject jsonObject) { JSONArray jsonConnectionList = jsonObject.optJSONArray("connections"); if (jsonConnectionList == null || jsonConnectionList.length() <= 1) { return false; } int totalAccounts = 0; int totalExternalAccounts = 0; try { for (int i = 0; i < jsonConnectionList.length(); i++) { JSONObject connectionObject = jsonConnectionList.getJSONObject(i); PublicizeConnection publicizeConnection = PublicizeConnection.fromJson(connectionObject); if (publicizeConnection.getService().equals(serviceId) && !publicizeConnection.isInSite(siteId)) { totalAccounts++; JSONArray externalJsonArray = connectionObject.getJSONArray("additional_external_users"); for (int j = 0; j < externalJsonArray.length(); j++) { totalExternalAccounts++; } } } if (PublicizeTable.onlyExternalConnections(serviceId)) { return totalExternalAccounts > 0; } else { return totalAccounts > 0 || totalExternalAccounts > 0; } } catch (JSONException e) { return false; } }
Source:
void seal() throws IOException, StoreException { if (sealed.compareAndSet(false, true)) { if (!config.storeKeepIndexInMemory) { map(); } persistBloomFilter(); } }

Target:
void seal() throws IOException, StoreException { sealed.set(true); if (!config.storeKeepIndexInMemory) { mmap(); } persistBloomFilter(); }
Source:
protected boolean validate() { List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); DiskValidator diskValidator = new DiskValidator(getDiskImage()); if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup() == true) { return false; } } return true; }

Target:
protected boolean validate() { List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); DiskValidator diskValidator = new DiskValidator(getDiskImage()); if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup()) { new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_RUNNING_VM_DISK_CANNOT_MOVE_TO_BACKUP_DOMAIN); return false; } } return true; }
Source:
public SurfaceGenerator() { super( new LakePopulator(), new DesertPopulator(), new TreePopulator(), new MushroomPopulator(), new SnowPopulator(), new FlowerPopulator(), new DungeonPopulator(), new OrePopulator() ); }

Target:
public SurfaceGenerator() { super( new LakePopulator(), new DesertPopulator(), new TreePopulator(), new MushroomPopulator(), new SnowPopulator(), new FlowerPopulator(), new BiomePopulator(), new DungeonPopulator(), new OrePopulator() ); }
Source:
private void prepare(ControlWidget screen) { InjectionHelper.inject(screen); translator.updateWidget(screen); screen.onOpened(); }

Target:
private void prepare(ControlWidget screen) { InjectionHelper.inject(screen); screen.onOpened(); }
Source:
public boolean doPostAddIdP(IdentityProvider identityProvider, String tenantDomain) throws IdentityProviderManagementException { if (isEnable()) { audit.info(String.format(AUDIT_MESSAGE, getUser(), "add", UserCoreUtil.addTenantDomainToEntry(identityProvider .getDisplayName(), tenantDomain), identityProvider.getIdentityProviderName(), SUCCESS)); } return true; }

Target:
public boolean doPostAddIdP(IdentityProvider identityProvider, String tenantDomain) throws IdentityProviderManagementException { String displayName = "Undefined"; String IDPName = "Undefined"; if (identityProvider != null) { displayName = identityProvider.getDisplayName(); IDPName = identityProvider.getIdentityProviderName(); } audit.info(String.format(AUDIT_MESSAGE, getUser(), "add", UserCoreUtil.addTenantDomainToEntry(displayName, tenantDomain), IDPName, SUCCESS)); return true; }
Source:
public void setUp() throws URIException, HttpMalformedHeaderException { Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.OFF); FrontEndScannerAPI api = mock(FrontEndScannerAPI.class); FrontEndScannerOptions options = mock(FrontEndScannerOptions.class); when(options.isEnabled()).thenReturn(true); HistoryReference ref = mock(HistoryReference.class); when(ref.getHistoryId()).thenReturn(42); frontEndScannerProxyListener = new FrontEndScannerProxyListener(api, options); msg = new HttpMessage(new URI("https", HOSTNAME, "/", "")); msg.getResponseHeader().setHeader(HttpResponseHeader.CONTENT_TYPE, "text/html"); msg.setHistoryRef(ref); }

Target:
public void setUp() throws URIException, HttpMalformedHeaderException { FrontEndScannerAPI api = mock(FrontEndScannerAPI.class); options = mock(FrontEndScannerOptions.class); HistoryReference ref = mock(HistoryReference.class, withSettings().lenient()); when(ref.getHistoryId()).thenReturn(42); frontEndScannerProxyListener = new FrontEndScannerProxyListener(api, options); msg = new HttpMessage(new URI("https", HOSTNAME, "/", "")); msg.getResponseHeader().setHeader(HttpResponseHeader.CONTENT_TYPE, "text/html"); msg.setHistoryRef(ref); }
Source:
public void shouldCreateOrderWithGivenParameters() { Location location = new Location(); location.setName("testLocation"); Patient patient = new Patient(); patient.setUuid("10"); Provider provider = new Provider(); provider.setUuid("20"); Visit visit = new Visit(); visit.setUuid("40"); Encounter encounter = new Encounter(); encounter.setUuid("50"); Concept concept = createTestConcept("testConcept"); Order order = new Order("testType", encounter, provider, patient, concept, Order.CareSetting.INPATIENT); openMRSActionProxyService.createOrder(CONFIG_NAME, "testType", encounter.getUuid(), patient.getUuid(), concept.getUuid(), provider.getUuid(), Order.CareSetting.INPATIENT.toString()); verify(orderService).createOrder(eq(CONFIG_NAME), orderCaptor.capture()); assertEquals(order, orderCaptor.getValue()); }

Target:
public void shouldCreateOrderWithGivenParameters() { Patient patient = new Patient(); patient.setUuid("10"); Provider provider = new Provider(); provider.setUuid("20"); Encounter encounter = new Encounter(); encounter.setUuid("50"); Concept concept = createTestConcept("60"); Order order = new Order("order", encounter, provider, patient, concept, Order.CareSetting.INPATIENT); doReturn(order).when(orderService).createOrder(eq(CONFIG_NAME), eq(order)); Order orderCreated = openMRSActionProxyService.createOrder(CONFIG_NAME, "order", encounter.getUuid(), patient.getUuid(), concept.getUuid(), provider.getUuid(), Order.CareSetting.INPATIENT.toString()); assertEquals(order, orderCreated); }
Source:
public List<ResourceGroupSelector> getSelectors() { if (lastRefresh.get() == 0) { throw new PrestoException(CONFIGURATION_UNAVAILABLE, "Selectors could not be fetched from database"); } if (this.selectors.get().isEmpty()) { throw new PrestoException(CONFIGURATION_INVALID, "No selectors are configured"); } return this.selectors.get(); }

Target:
public List<ResourceGroupSelector> getSelectors() { if (lastRefresh.get() == 0) { throw new PrestoException(CONFIGURATION_UNAVAILABLE, "Selectors cannot be fetched from database"); } if (this.selectors.get().isEmpty()) { throw new PrestoException(CONFIGURATION_INVALID, "No selectors are configured"); } return this.selectors.get(); }
Source:
public void run() { File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { String[] javaVersion = System.getProperty("java.version").split("\\."); if (Integer.parseInt(javaVersion[0]) >= 9) { ClassPathAgent.addJarFile(new JarFile(file)); } else { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL()); } } catch (ReflectiveOperationException | IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }

Target:
public void run() { File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { String[] javaVersion = System.getProperty("java.version").split("-")[0].split("\\."); if (Integer.parseInt(javaVersion[0]) >= 9) { ClassPathAgent.addJarFile(new JarFile(file)); } else { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL()); } } catch (ReflectiveOperationException | IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }
Source:
protected IContributionItem[] getContributionItems() { Set<Pair<String, String>> selectedTraceTypes = new HashSet<>(getParam()); Pair<String, String> launchConfiguration = getLaunchConfigurationParam(); if (launchConfiguration != null) { selectedTraceTypes.add(launchConfiguration); } List<IContributionItem> list = new LinkedList<>(); for (Pair<String, String> item : selectedTraceTypes) { Map<String, String> params = new HashMap<>(); params.put(TYPE_PARAMETER, item.getFirst()); params.put(MODE_PARAMETER, getLaunchMode()); CommandContributionItemParameter param = new CommandContributionItemParameter( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), "my.parameterid", getContributionItemCommandId(), CommandContributionItem.STYLE_PUSH ); param.parameters = params; param.label = item.getSecond(); param.visibleEnabled = true; list.add(new CommandContributionItem(param)); } Collections.sort(list, ITEM_COMPARATOR); return list.toArray(new IContributionItem[list.size()]); }

Target:
protected IContributionItem[] getContributionItems() { Set<Pair<String, String>> availableShortcuts = new HashSet<>(getParam()); Pair<String, String> launchConfiguration = getLaunchConfigurationParam(); if (launchConfiguration != null) { availableShortcuts.add(launchConfiguration); } List<IContributionItem> list = new LinkedList<>(); for (Pair<String, String> item : availableShortcuts) { Map<String, String> params = new HashMap<>(); params.put(TYPE_PARAMETER, item.getFirst()); params.put(MODE_PARAMETER, getLaunchMode()); CommandContributionItemParameter param = new CommandContributionItemParameter( PlatformUI.getWorkbench().getActiveWorkbenchWindow(), LAUNCH_COMMAND_CONTRIBUTION_ITEM_ID, getContributionItemCommandId(), CommandContributionItem.STYLE_PUSH ); param.parameters = params; param.label = item.getSecond(); param.visibleEnabled = true; list.add(new CommandContributionItem(param)); } Collections.sort(list, ITEM_COMPARATOR); return list.toArray(new IContributionItem[list.size()]); }
Source:
public void project_level() { assertThat(getProjectMeasureAsInt(NCLOC)).isEqualTo(1); assertThat(getProjectMeasureAsInt(LINES)).isEqualTo(6); assertThat(getProjectMeasureAsInt(FILES)).isEqualTo(1); assertThat(getProjectMeasureAsInt(STATEMENTS)).isEqualTo(1); assertThat(getProjectMeasureAsInt(FUNCTIONS)).isEqualTo(1); assertThat(getProjectMeasureAsInt(CLASSES)).isEqualTo(0); assertThat(getProjectMeasureAsInt(COMMENT_LINES)).isEqualTo(1); assertThat(getProjectMeasureAsDouble(COMMENT_LINES_DENSITY)).isEqualTo(50.0); assertThat(getProjectMeasureAsDouble(COMPLEXITY)).isEqualTo(2.0); assertThat(getProjectMeasureAsDouble(COGNITIVE_COMPLEXITY)).isEqualTo(1.0); assertThat(getProjectMeasureAsDouble(FUNCTION_COMPLEXITY)).isNull(); assertThat(getProjectMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION).getValue()).isEqualTo("1=0;2=1;4=0;6=0;8=0;10=0;12=0;20=0;30=0"); assertThat(getProjectMeasureAsDouble(FILE_COMPLEXITY)).isEqualTo(2.0); assertThat(getProjectMeasure(FILE_COMPLEXITY_DISTRIBUTION).getValue()).isEqualTo("0=1;5=0;10=0;20=0;30=0;60=0;90=0"); assertThat(getProjectMeasureAsDouble(DUPLICATED_LINES)).isZero(); assertThat(getProjectMeasureAsDouble(DUPLICATED_BLOCKS)).isZero(); assertThat(getProjectMeasureAsDouble(DUPLICATED_FILES)).isZero(); assertThat(getProjectMeasureAsDouble(DUPLICATED_LINES_DENSITY)).isZero(); assertThat(getProjectMeasureAsDouble(VIOLATIONS)).isZero(); assertThat(getProjectMeasureAsInt(TESTS)).isNull(); assertThat(getProjectMeasureAsDouble(COVERAGE)).isZero(); }

Target:
public void project_level() { assertThat(getProjectMeasureAsInt(NCLOC)).isEqualTo(6); assertThat(getProjectMeasureAsInt(LINES)).isEqualTo(13); assertThat(getProjectMeasureAsInt(FILES)).isEqualTo(2); assertThat(getProjectMeasureAsInt(STATEMENTS)).isEqualTo(5); assertThat(getProjectMeasureAsInt(FUNCTIONS)).isEqualTo(1); assertThat(getProjectMeasureAsInt(CLASSES)).isEqualTo(0); assertThat(getProjectMeasureAsInt(COMMENT_LINES)).isEqualTo(1); assertThat(getProjectMeasureAsDouble(COMMENT_LINES_DENSITY)).isEqualTo(14.3, OFFSET); assertThat(getProjectMeasureAsDouble(COMPLEXITY)).isEqualTo(3.0, OFFSET); assertThat(getProjectMeasureAsDouble(COGNITIVE_COMPLEXITY)).isEqualTo(3.0, OFFSET); assertThat(getProjectMeasureAsDouble(FUNCTION_COMPLEXITY)).isNull(); assertThat(getProjectMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION).getValue()).isEqualTo("1=0;2=1;4=0;6=0;8=0;10=0;12=0;20=0;30=0"); assertThat(getProjectMeasureAsDouble(FILE_COMPLEXITY)).isEqualTo(1.5, OFFSET); assertThat(getProjectMeasure(FILE_COMPLEXITY_DISTRIBUTION).getValue()).isEqualTo("0=2;5=0;10=0;20=0;30=0;60=0;90=0"); assertThat(getProjectMeasureAsDouble(DUPLICATED_LINES)).isEqualTo(0.0, OFFSET); assertThat(getProjectMeasureAsDouble(DUPLICATED_BLOCKS)).isEqualTo(0.0, OFFSET); assertThat(getProjectMeasureAsDouble(DUPLICATED_FILES)).isEqualTo(0.0, OFFSET); assertThat(getProjectMeasureAsDouble(DUPLICATED_LINES_DENSITY)).isEqualTo(0.0, OFFSET); assertThat(getProjectMeasureAsDouble(VIOLATIONS)).isEqualTo(0.0, OFFSET); assertThat(getProjectMeasureAsInt(TESTS)).isNull(); assertThat(getProjectMeasureAsDouble(COVERAGE)).isEqualTo(0.0, OFFSET); }
Source:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); return ALLOWED_ANNOTATIONS.contains( annotationType ) || Arrays.stream( annotationType.getDeclaredAnnotations() ) .anyMatch( annotation -> isAnnotationAllowed( annotation, processedAnnotations ) ); }

Target:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); if ( ALLOWED_ANNOTATIONS.contains( annotationType ) ) { return true; } for ( Annotation annotation : annotationType.getDeclaredAnnotations() ) { if ( isAnnotationAllowed( annotation, processedAnnotations ) ) { return true; } } return false; }
Source:
public String getCanonicalName() { return getPackage() + "." + getSimpleName().replaceAll("$", "\\."); }

Target:
public String getCanonicalName() { return getPackage() + "." + getSimpleName().replace("$", "\\."); }
Source:
public QueryDetail explain(EntityProjection projection, RequestScope scope) { Class<?> entityClass = projection.getType(); String modelName = entityClass.getName(); List<String> queryTextList = getQueryText(); this.queryText = new ArrayList<>(); return new QueryDetail(modelName, queryTextList); }

Target:
public QueryDetail explain(EntityProjection projection, RequestScope scope) { Class<?> entityClass = projection.getType(); Pagination pagination = projection.getPagination(); FilterExpression filterExpression = projection.getFilterExpression(); Sorting sorting = projection.getSorting(); List<String> queryTextList = new ArrayList<>(); if (pagination != null && pagination.returnPageTotals()) { pagination.setPageTotals(getTotalRecords(entityClass, Optional.ofNullable(filterExpression), scope.getDictionary())); queryTextList.add(explainTotalRecords(projection, scope)); } RootCollectionFetchQueryBuilder queryBuilder = new RootCollectionFetchQueryBuilder(entityClass, scope.getDictionary(), sessionWrapper); queryBuilder .withPossibleFilterExpression(Optional.ofNullable(filterExpression)) .withPossibleSorting(Optional.ofNullable(sorting)) .withPossiblePagination(Optional.ofNullable(pagination)) .build(); queryTextList.add(queryBuilder.getQueryString()); return new QueryDetail(entityClass.getName(), queryTextList); }
Source:
public boolean filterRow(Project project, int rowIndex, Row row) { Cell cell = _cellIndex < 0 ? null : row.getCell(_cellIndex); Properties bindings = ExpressionUtils.createBindings(project); ExpressionUtils.bind(bindings, row, rowIndex, _columnName, cell); Boolean invert = _invert; Object value = _evaluable.evaluate(bindings); if (value != null) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { if (checkValue(v instanceof String ? ((String) v) : v.toString())) { return (invert) ? false : true; } } } else if (value instanceof Collection<?>) { for (Object v : ExpressionUtils.toObjectCollection(value)) { if (checkValue(v.toString())) { return (invert) ? false : true; } } return (invert) ? true : false; } else if (value instanceof JSONArray) { JSONArray a = (JSONArray) value; int l = a.length(); for (int i = 0; i < l; i++) { try { if (checkValue(a.get(i).toString())) { return (invert) ? false : true; } } catch (JSONException e) { } } return (invert) ? true : false; } else { if (checkValue(value instanceof String ? ((String) value) : value.toString())) { return (invert) ? false : true; } } } return (invert) ? true : false; }

Target:
public boolean filterRow(Project project, int rowIndex, Row row) { Cell cell = _cellIndex < 0 ? null : row.getCell(_cellIndex); Properties bindings = ExpressionUtils.createBindings(project); ExpressionUtils.bind(bindings, row, rowIndex, _columnName, cell); Boolean invert = _invert; Object value = _evaluable.evaluate(bindings); if (value != null) { if (value.getClass().isArray()) { Object[] a = (Object[]) value; for (Object v : a) { if (checkValue(v instanceof String ? ((String) v) : v.toString())) { return !invert; } } } else if (value instanceof Collection<?>) { for (Object v : ExpressionUtils.toObjectCollection(value)) { if (checkValue(v.toString())) { return !invert; } } return invert; } else if (value instanceof JSONArray) { JSONArray a = (JSONArray) value; int l = a.length(); for (int i = 0; i < l; i++) { try { if (checkValue(a.get(i).toString())) { return !invert; } } catch (JSONException e) { } } return invert; } else { if (checkValue(value instanceof String ? ((String) value) : value.toString())) { return !invert; } } } return invert; }
Source:
public void merge() throws MergeException { try { schema = mArguments.schemaFactory.open(); openRepository(); submitted = schema.changes().submitted(destBranch).toList(); preMerge(); updateBranch(); updateChangeStatus(); } catch (OrmException e) { throw new MergeException("Cannot open database", e); } finally { if (rw != null) { rw.release(); } if (db != null) { db.close(); } schema.close(); schema = null; } }

Target:
public final void merge() throws MergeException { try { schema = mArguments.schemaFactory.open(); openRepository(); submitted = schema.changes().submitted(destBranch).toList(); preMerge(); updateBranch(); updateChangeStatus(); } catch (OrmException e) { throw new MergeException("Cannot open database", e); } finally { if (rw != null) { rw.release(); } if (db != null) { db.close(); } schema.close(); schema = null; } }
Source:
public void saveOrderType_shouldAddNewOrderTypeToTheDatabase() { OrderService orderService = Context.getOrderService(); OrderType orderType = new OrderType(); orderType.setName("New Order"); orderType.setJavaClassName("org.openmrs.NewTestOrder"); orderType.setDescription("New order type for testing"); orderType.setRetired(false); orderType = orderService.saveOrderType(orderType); assertNotNull(orderType); assertEquals("New Order", orderType.getName()); }

Target:
public void saveOrderType_shouldAddNewOrderTypeToTheDatabase() { OrderService orderService = Context.getOrderService(); int orderTypeCount = orderService.getOrderTypes(true).size(); OrderType orderType = new OrderType(); orderType.setName("New Order"); orderType.setJavaClassName("org.openmrs.NewTestOrder"); orderType.setDescription("New order type for testing"); orderType.setRetired(false); orderType = orderService.saveOrderType(orderType); assertNotNull(orderType); assertEquals("New Order", orderType.getName()); assertNotNull(orderType.getId()); assertEquals((orderTypeCount + 1), orderService.getOrderTypes(true).size()); }
Source:
public boolean hasNext() { if (throwable != null) throw throwable; try { if (nextElement != null && nextElement != terminator) { return true; } else if(nextElement == terminator) return false; nextElement = buffer.take(); if (nextElement == terminator) return false; return true; } catch (Exception e) { log.error("Premature end of loop!"); return false; } }

Target:
public boolean hasNext() { if (throwable != null) throw throwable; try { if (nextElement != null && nextElement != terminator) { return true; } else if(nextElement == terminator) return false; nextElement = buffer.take(); if (nextElement == terminator) return false; return true; } catch (Exception e) { log.error("Premature end of loop!"); throw new RuntimeException(e); } }
Source:
public void sessionClosed(IoSession session) throws Exception { if (sync && !messageReceived) { LOG.debug("Session closed but no message received from address: {}", address); countDown(); } closeLatch.countDown(); }

Target:
public void sessionClosed(IoSession session) throws Exception { if (sync && !messageReceived) { LOG.debug("Session closed but no message received from address: {}", address); notifyResultAvailable(); } notifySessionClosed(); }
Source:
public void addPages() { setWindowTitle("Run SWT Recorder"); firstPage = new SWTRecorderWizardPage(); addPage(firstPage); }

Target:
public void addPages() { setWindowTitle(Messages.recorderDialogTitle); firstPage = new SWTRecorderWizardPage(); addPage(firstPage); }
Source:
public void onUserSetScaleDenominator(PropertyChangeEvent pce) throws PropertyVetoException { long newScale = (Long)pce.getNewValue(); if(newScale<1) { throw new PropertyVetoException(I18N.tr("The value of the scale denominator must be equal or greater than 1"),pce); } mapControl.getMapTransform().setScaleDenominator((double)newScale); }

Target:
public void onUserSetScaleDenominator(PropertyChangeEvent pce) throws PropertyVetoException { long newScale = (Long)pce.getNewValue(); if(newScale<1) { throw new PropertyVetoException(I18N.tr("The value of the scale denominator must be equal or greater than 1"),pce); } mapControl.getMapTransform().setScaleDenominator(newScale); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 47.495052, -121.786863, 12); mMapView.setMap(map); mFab = findViewById(R.id.floatingActionButton); mFab.setOnClickListener(v -> Snackbar.make(v, "Button responds to attribution bar", Snackbar.LENGTH_LONG) .setAction("Action", null).show()); mMapView.addAttributionViewLayoutChangeListener( (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { int heightDelta = oldBottom - bottom; mFab.animate().translationYBy(heightDelta); Toast.makeText(MainActivity.this, "new bounds [" + left + "," + top + "," + right + "," + bottom + "]" + " old bounds [" + oldLeft + "," + oldTop + "," + oldRight + "," + oldBottom + "]", Toast.LENGTH_SHORT) .show(); }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 47.495052, -121.786863, 12); mMapView.setMap(map); FloatingActionButton mFab = findViewById(R.id.floatingActionButton); mFab.setOnClickListener(v -> Snackbar.make(v, "Button responds to attribution bar", Snackbar.LENGTH_LONG) .setAction("Action", null).show()); mMapView.addAttributionViewLayoutChangeListener( (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { int heightDelta = oldBottom - bottom; mFab.animate().translationYBy(heightDelta); Toast.makeText(MainActivity.this, "new bounds [" + left + ',' + top + ',' + right + ',' + bottom + ']' + " old bounds [" + oldLeft + ',' + oldTop + ',' + oldRight + ',' + oldBottom + ']', Toast.LENGTH_SHORT) .show(); }); }
Source:
public boolean getDataConsistentOnStandby() { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setKey( ReplicationStatusKey.Status.IS_DATA_CONSISTENT).build(); CorfuRecord record = corfuStore.query(NAMESPACE).getRecord(REPLICATION_STATUS_TABLE, key); if (record == null) { return false; } ReplicationStatusVal val = (ReplicationStatusVal)record.getPayload(); return val.getDataConsistent(); }

Target:
public Map<String, ReplicationStatusVal> getDataConsistentOnStandby() { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setClusterId(localClusterId).build(); CorfuRecord record = corfuStore.query(NAMESPACE).getRecord(REPLICATION_STATUS_TABLE, key); ReplicationStatusVal statusVal; if (record == null) { log.warn("No Key for Data Consistent found. DataConsistent Status is not set."); statusVal = ReplicationStatusVal.newBuilder().setDataConsistent(false).build(); } else { statusVal = (ReplicationStatusVal)record.getPayload(); } Map<String, ReplicationStatusVal> dataConsistentMap = new HashMap<>(); dataConsistentMap.put(localClusterId, statusVal); return dataConsistentMap; }
Source:
public boolean getUserHasPermissions(String userName, String domain) throws SQLException { Connection connection = null; PreparedStatement prepareStatement = null; ResultSet resultSet = null; try { log.info("getPermissionsForUser username: " + userName + " domain: " + domain); connection = ds.getConnection(); prepareStatement = connection.prepareStatement(selectQuery); prepareStatement.setString(1, userName); prepareStatement.setString(2, domain); resultSet = prepareStatement.executeQuery(); if (resultSet.next()) { return true; } } finally { if (resultSet != null) { resultSet.close(); } if (prepareStatement != null) { prepareStatement.close(); } if (connection != null) { connection.close(); } } return false; }

Target:
public boolean getUserHasPermissions(String userName, String domain) throws SQLException { Connection connection = null; PreparedStatement prepareStatement = null; ResultSet resultSet = null; try { log.info("getPermissionsForUser username: " + userName + " domain: " + domain); connection = ds.getConnection(); prepareStatement = connection.prepareStatement(selectQuery); prepareStatement.setString(1, userName); prepareStatement.setString(2, domain); resultSet = prepareStatement.executeQuery(); if (resultSet.next()) { return true; } } finally { DbUtils.closeQuietly(resultSet, prepareStatement, connection); } return false; }
Source:
private void postInstalledEvent(String extensionId) { if (eventPublisher != null) { Event event = ExtensionEventFactory.createExtensionInstalledEvent(extensionId); eventPublisher.post(event); } }

Target:
private void postInstalledEvent(String extensionId) { Event event = ExtensionEventFactory.createExtensionInstalledEvent(extensionId); eventPublisher.post(event); }
Source:
private OutputStream decorate(OutputStream os) { for (ConsoleLogFilter f : ConsoleLogFilter.all()) { try { os = f.decorateLogger(this,os); } catch (IOException|InterruptedException e) { logger.log(Level.WARNING, "Failed to filter log with "+f, e); } } return os; }

Target:
private OutputStream decorate(OutputStream os) { for (ConsoleLogFilter f : ConsoleLogFilter.all()) { try { os = f.decorateLogger(this,os); } catch (IOException|InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to filter log with "+f, e); } } return os; }
Source:
public boolean isRecord() throws JavaModelException { IBinaryType info = (IBinaryType) getElementInfo(); if( TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL) { return CharOperation.equals(info.getSuperclassName(), RecordDeclaration.super_class); } return false; }

Target:
public boolean isRecord() throws JavaModelException { IBinaryType info = (IBinaryType) getElementInfo(); if( TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL) { return CharOperation.equals(info.getSuperclassName(), TypeConstants.CharArray_JAVA_LANG_RECORD); } return false; }
Source:
public long saveProjectOverview(ProjectOverview overview) throws IOException { if (projectStore != null) { if (overview.getId() != ProjectOverview.UNSAVED_ID) { ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); original.setLastUpdated(new Date()); overview = original; } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); } else { throw new IOException("No projectStore available. Check that it has been declared in the Spring config."); } }

Target:
public long saveProjectOverview(ProjectOverview overview) throws IOException { if (projectStore != null) { if (overview.getId() != ProjectOverview.UNSAVED_ID) { ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); overview = original; } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); } else { throw new IOException("No projectStore available. Check that it has been declared in the Spring config."); } }
Source:
public void populateAvatar(ChatChannelUser chatChannelUser) { if (chatChannelUser.isDisplayed()) { if (chatChannelUser.getAvatar().isEmpty()) { chatChannelUser.getPlayer() .ifPresent(player -> { Image avatar; if (!Strings.isNullOrEmpty(player.getAvatarUrl())) { avatar = avatarService.loadAvatar(player.getAvatarUrl()); } else { avatar = null; } Platform.runLater(() -> { chatChannelUser.setAvatar(avatar); }); }); } } else { chatChannelUser.setAvatar(null); } }

Target:
public void populateAvatar(ChatChannelUser chatChannelUser) { if (chatChannelUser.isDisplayed()) { if (!chatChannelUser.getAvatar().isEmpty()) { return; } chatChannelUser.getPlayer() .ifPresent(player -> { Image avatar; if (!Strings.isNullOrEmpty(player.getAvatarUrl())) { avatar = avatarService.loadAvatar(player.getAvatarUrl()); } else { avatar = null; } Platform.runLater(() -> { chatChannelUser.setAvatar(avatar); }); }); } else { chatChannelUser.setAvatar(null); } }
Source:
private void handleBlockchainStateNotification(BlockchainState blockchainState) { final Intent broadcast = new Intent(ACTION_BLOCKCHAIN_STATE); broadcast.setPackage(getPackageName()); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && blockchainState != null && blockchainState.getBestChainDate() != null) { boolean syncing = blockchainState.getBestChainDate().getTime() < (Utils.currentTimeMillis() - DateUtils.HOUR_IN_MILLIS); if (!syncing && blockchainState.getBestChainHeight() == config.getBestChainHeightEver()) { stopForeground(true); nm.cancel(Constants.NOTIFICATION_ID_BLOCKCHAIN_SYNC); } else if (blockchainState.getReplaying() || syncing) { Notification notification = createNetworkSyncNotification(); nm.notify(Constants.NOTIFICATION_ID_BLOCKCHAIN_SYNC, notification); } } }

Target:
private void handleBlockchainStateNotification(BlockchainState blockchainState) { final Intent broadcast = new Intent(ACTION_BLOCKCHAIN_STATE); broadcast.setPackage(getPackageName()); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && blockchainState != null && blockchainState.getBestChainDate() != null) { boolean syncing = blockchainState.getBestChainDate().getTime() < (Utils.currentTimeMillis() - DateUtils.HOUR_IN_MILLIS); if (!syncing && blockchainState.getBestChainHeight() == config.getBestChainHeightEver()) { stopForeground(true); nm.cancel(Constants.NOTIFICATION_ID_BLOCKCHAIN_SYNC); } else if (blockchainState.getReplaying() || syncing) { Notification notification = createNetworkSyncNotification(blockchainState); nm.notify(Constants.NOTIFICATION_ID_BLOCKCHAIN_SYNC, notification); } } }
Source:
private void setDisplayHeight() { displayDensity = DimenUtil.getDensityScalar(); displayHeight = (int) (DimenUtil.getDisplayMetrics().heightPixels / displayDensity); }

Target:
private void setDisplayHeight() { displayDensity = DimenUtil.getDensityScalar(); displayHeight = DimenUtil.getDisplayHeight( parentFragment.getActivity().getWindowManager().getDefaultDisplay(), displayDensity); }
Source:
public boolean addPassenger(Entity passenger) { Preconditions.checkArgument(passenger != this, "Entity cannot ride itself."); if (passenger == null || passengers.contains(passenger)) return false; if (!(passenger instanceof GlowEntity)) { return false; } GlowEntity glowPassenger = (GlowEntity) passenger; if (glowPassenger.vehicle != null) { glowPassenger.vehicle.removePassenger(passenger); } EntityMountEvent event = new EntityMountEvent(passenger, this); EventFactory.callEvent(event); if (event.isCancelled()) { return false; } this.passengers.add(passenger); glowPassenger.vehicle = this; this.passengerChanged = true; Location onTopOfVehicle = this.location.clone().add(0, this.getHeight(), 0); glowPassenger.teleport(onTopOfVehicle); return true; }

Target:
public boolean addPassenger(Entity passenger) { Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); if (passenger == null || passengers.contains(passenger)) return false; if (!(passenger instanceof GlowEntity)) { return false; } GlowEntity glowPassenger = (GlowEntity) passenger; if (glowPassenger.vehicle != null) { glowPassenger.vehicle.removePassenger(passenger); } EntityMountEvent event = new EntityMountEvent(passenger, this); EventFactory.callEvent(event); if (event.isCancelled()) { return false; } passengerChanged = true; glowPassenger.vehicle = this; glowPassenger.teleport(getMountLocation()); return this.passengers.add(passenger); }
Source:
public void saveUserLocation_shouldSaveAUserLocation() throws Exception { MohCoreService cservice = Context.getService(MohCoreService.class); User sysUser = new User(); sysUser.setUserId(2); Location userLoc = new Location(); userLoc.setLocationId(3); UserLocation userlocation = new UserLocation(); userlocation.setUserLocationId(3); userlocation.setSysUser(sysUser); userlocation.setUserLoc(userLoc); cservice.saveUserLocation(userlocation); }

Target:
public void saveUserLocation_shouldSaveAUserLocation() throws Exception { MohCoreService cservice = Context.getService(MohCoreService.class); User sysUser = new User(); sysUser.setUserId(501); Location userLoc = new Location(); userLoc.setLocationId(1); UserLocation userlocation = new UserLocation(); userlocation.setSysUser(sysUser); userlocation.setUserLoc(userLoc); Assert.assertNull(userlocation.getUserLocationId()); UserLocation uloc=cservice.saveUserLocation(userlocation); Assert.assertNotNull(uloc.getUserLocationId()); }
Source:
private void createProgressBar(Composite parent) { progressBarComposite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.TOP, true, true); progressBarComposite.setLayoutData(gd); GridLayout layout = new GridLayout(); progressBarComposite.setLayout(layout); progressBarComposite.setVisible(false); Label progressBarLabel = new Label(progressBarComposite, SWT.NONE); progressBarLabel.setText(ProvUIMessages.AvailableIUsPage_Fetching); gd = new GridData(SWT.LEFT, SWT.CENTER, true, true); progressBarLabel.setLayoutData(gd); ProgressBar progressBar = new ProgressBar(progressBarComposite, SWT.INDETERMINATE); gd = new GridData(SWT.FILL, SWT.FILL, true, true); progressBar.setLayoutData(gd); IContentProvider contentProvider = availableIUGroup.getCheckboxTreeViewer().getContentProvider(); if (contentProvider instanceof DeferredQueryContentProvider) { ((DeferredQueryContentProvider) contentProvider).addOnFetchingActionListener(new IDeferredQueryTreeListener() { @Override public void finishedFetchingDeferredChildren(Object parent, Object placeHolder) { if (parent instanceof QueriedElement) { if (((QueriedElement) parent).getCachedChildren().length > 0) { setProgressBarVisibility(false); } } } @Override public void fetchingDeferredChildren(Object parent, Object placeHolder) { setProgressBarVisibility(true); } }); } }

Target:
private Composite createProgressBar(Composite parent) { final Composite progressBarComposite = new Composite(parent, SWT.NONE); Label progressBarLabel = new Label(progressBarComposite, SWT.NONE); progressBarLabel.setText(ProvUIMessages.AvailableIUsPage_Fetching); ProgressBar progressBar = new ProgressBar(progressBarComposite, SWT.INDETERMINATE); IContentProvider contentProvider = availableIUGroup.getCheckboxTreeViewer().getContentProvider(); if (contentProvider instanceof DeferredQueryContentProvider) { ((DeferredQueryContentProvider) contentProvider).addOnFetchingActionListener(new IDeferredQueryTreeListener() { @Override public void finishedFetchingDeferredChildren(Object parent, Object placeHolder) { if (parent instanceof QueriedElement) { if (((QueriedElement) parent).getCachedChildren().length > 0) { if (progressBarRefCount > 0) { progressBarRefCount--; } } } changeProgressBarVisibility(progressBarComposite); } @Override public void fetchingDeferredChildren(Object parent, Object placeHolder) { progressBarRefCount++; changeProgressBarVisibility(progressBarComposite); } }); } GridLayoutFactory.fillDefaults().generateLayout(progressBarComposite); return progressBarComposite; }
Source:
private void abortL1UpdateOrWait(Object key) throws InterruptedException { L1WriteSynchronizer sync = concurrentWrites.remove(key); if (sync != null) { if (sync.trySkipL1Update()) { log.tracef("Aborted possible L1 update due to concurrent invalidation for key %s", key); } else { log.tracef("L1 invalidation found a pending update from a read for key %s - need to wait for it to " + "complete to guarantee consistency", key); try { sync.get(); } catch (ExecutionException e) { } log.tracef("Pending L1 update completed - L1 invalidation can occur for key %s", key); } } }

Target:
private void abortL1UpdateOrWait(Object key) throws InterruptedException { L1WriteSynchronizer sync = concurrentWrites.remove(key); if (sync != null) { if (sync.trySkipL1Update()) { if (trace) { log.tracef("Aborted possible L1 update due to concurrent invalidation for key %s", key); } } else { if (trace) { log.tracef("L1 invalidation found a pending update for key %s - need to block until finished", key); } boolean success; try { sync.get(); success = true; } catch (ExecutionException e) { success = false; } if (trace) { log.tracef("Pending L1 update completed successfully: %b - L1 invalidation can occur for key %s", success, key); } } } }
Source:
protected String getStateParameter(final WebContext context) { final String stateParameter; final String stateData = getState(); if (CommonHelper.isNotBlank(stateData)) { stateParameter = stateData; } else { stateParameter = CommonHelper.randomString(10); } return stateParameter; }

Target:
protected String getStateParameter(final WebContext context) { final String stateParameter; if (CommonHelper.isNotBlank(stateData)) { stateParameter = stateData; } else { stateParameter = CommonHelper.randomString(10); } return stateParameter; }
Source:
private DiscoveryResult createDiscoveryResult(StateServiceResponse packet, StateVersionResponse returnedPacket) { MACAddress discoveredAddress = packet.getTarget(); ThingUID thingUID = getUID(discoveredAddress.getAsLabel()); Products product = Products.getProductFromProductID(returnedPacket.getProduct()); String label = ""; if (StringUtils.isBlank(label)) label = product.getName() + " v." + returnedPacket.getVersion() + " [" + discoveredAddress.getAsLabel() + "]"; logger.debug("Discovered a LIFX light : {}", label); return DiscoveryResultBuilder.create(thingUID).withLabel(label) .withProperty(LifxBindingConstants.CONFIG_PROPERTY_DEVICE_ID, discoveredAddress.getAsLabel()).build(); }

Target:
private DiscoveryResult createDiscoveryResult(StateServiceResponse packet, StateVersionResponse returnedPacket) { MACAddress discoveredAddress = packet.getTarget(); try { Products product = Products.getProductFromProductID(returnedPacket.getProduct()); ThingUID thingUID = getUID(discoveredAddress.getAsLabel(), product.isColor()); String label = ""; if (StringUtils.isBlank(label)) { label = product.getName(); } logger.trace("Discovered a LIFX light : {}", label); return DiscoveryResultBuilder.create(thingUID).withLabel(label) .withProperty(LifxBindingConstants.CONFIG_PROPERTY_DEVICE_ID, discoveredAddress.getAsLabel()) .withRepresentationProperty(discoveredAddress.getAsLabel()).build(); } catch (IllegalArgumentException e) { logger.trace("Ignoring packet: {}", e); return null; } }
Source:
public void write(Page page) throws IOException { requireNonNull(page, "page is null"); if (page.getPositionCount() == 0) { return; } checkArgument(page.getChannelCount() == columnWriters.size()); if (validationBuilder != null) { validationBuilder.addPage(page); } int averageLogicalSizePerRow = estimateAverageLogicalSizePerRow(page); int chunkRows = Math.max(1, chunkMaxLogicalBytes / Math.max(1, averageLogicalSizePerRow)); while (page != null) { chunkRows = min(chunkRows, min(rowGroupMaxRowCount - rowGroupRowCount, stripeMaxRowCount - stripeRowCount)); chunkRows = min(page.getPositionCount(), chunkRows); Page chunk = page.getRegion(0, chunkRows); if (chunkRows < page.getPositionCount()) { page = page.getRegion(chunkRows, page.getPositionCount() - chunkRows); } else { page = null; } writeChunk(chunk); } long recordedSizeInBytes = getRetainedBytes(); stats.updateSizeInBytes(recordedSizeInBytes - previouslyRecordedSizeInBytes); previouslyRecordedSizeInBytes = recordedSizeInBytes; }

Target:
public void write(Page page) throws IOException { requireNonNull(page, "page is null"); if (page.getPositionCount() == 0) { return; } checkArgument(page.getChannelCount() == columnWriters.size()); if (validationBuilder != null) { validationBuilder.addPage(page); } int averageLogicalSizePerRow = estimateAverageLogicalSizePerRow(page); int maxChunkRowCount = max(1, chunkMaxLogicalBytes / max(1, averageLogicalSizePerRow)); while (page != null) { int chunkRows = min(maxChunkRowCount, min(rowGroupMaxRowCount - rowGroupRowCount, stripeMaxRowCount - stripeRowCount)); chunkRows = min(page.getPositionCount(), chunkRows); Page chunk = page.getRegion(0, chunkRows); if (chunkRows < page.getPositionCount()) { page = page.getRegion(chunkRows, page.getPositionCount() - chunkRows); } else { page = null; } writeChunk(chunk); } long recordedSizeInBytes = getRetainedBytes(); stats.updateSizeInBytes(recordedSizeInBytes - previouslyRecordedSizeInBytes); previouslyRecordedSizeInBytes = recordedSizeInBytes; }