auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void createControl(Composite parent) { final Composite composite = getCompositeProvider().createUI(parent); if (getCompositeProvider().getViewer() instanceof TreeViewer) { final TreeViewer tv = (TreeViewer) getCompositeProvider().getViewer(); tv.expandToLevel(2); } getCompositeProvider().getViewer().addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updatePageStatus(); } }); getCompositeProvider().getViewer().addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { if (isPageComplete() && performFinish()) { ((WizardDialog) getContainer()).close(); } } }); <START> setPageComplete(false); <END> updatePageStatus(); setControl(composite); }</code><technical_language>removed this is done in updatepagestatus</technical_language>

Target:
public void createControl(Composite parent) { final Composite composite = getCompositeProvider().createUI(parent); if (getCompositeProvider().getViewer() instanceof TreeViewer) { final TreeViewer tv = (TreeViewer) getCompositeProvider().getViewer(); tv.expandToLevel(2); } getCompositeProvider().getViewer().addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updatePageStatus(); } }); getCompositeProvider().getViewer().addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { if (isPageComplete() && performFinish()) { ((WizardDialog) getContainer()).close(); } } }); updatePageStatus(); setControl(composite); }
Source:
<code>public <F> void testEmptyTemporaryFileSuffixCannotBeNull() throws Exception { SessionFactory<F> sf = mock(SessionFactory.class); Session<F> session = mock(Session.class); when(sf.getSession()).thenReturn(session); <START> ExpressionParser parser = new SpelExpressionParser(); <END> FileTransferringMessageHandler<F> handler = new FileTransferringMessageHandler<F>(sf); handler.setBeanFactory(mock(BeanFactory.class)); handler.setRemoteDirectoryExpressionString("headers['path']"); handler.setTemporaryFileSuffix(null); handler.onInit(); }</code><technical_language>delete; unused now</technical_language>

Target:
public <F> void testEmptyTemporaryFileSuffixCannotBeNull() throws Exception { SessionFactory<F> sf = mock(SessionFactory.class); Session<F> session = mock(Session.class); when(sf.getSession()).thenReturn(session); FileTransferringMessageHandler<F> handler = new FileTransferringMessageHandler<F>(sf); handler.setBeanFactory(mock(BeanFactory.class)); handler.setRemoteDirectoryExpressionString("headers['path']"); handler.setTemporaryFileSuffix(null); handler.onInit(); }
Source:
<code><START> public JobId submit(File workflowFile, Map<String, String> variables) throws NotConnectedRestException, <END> PermissionRestException, SubmissionClosedRestException, JobCreationRestException { try { Job job = createJobObject(workflowFile, variables); JobId jobId = scheduler.submit(job); File visualizationFile = new File(PortalConfiguration.jobIdToPath(jobId.value()) + ".html"); Files.deleteIfExists(visualizationFile.toPath()); FileUtils.write(new File(visualizationFile.getAbsolutePath()), job.getVisualization(), StandardCharsets.UTF_8); return jobId; } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } catch (Exception e) { logger.warn("Unexpected error when submitting job", e); throw new JobCreationRestException(e); } }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public JobId submit(File workflowFile, Map<String, String> variables) throws NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, JobCreationRestException { try { Job job = createJobObject(workflowFile, variables); JobId jobId = scheduler.submit(job); String visualization = job.getVisualization(); if (visualization != null && !visualization.isEmpty()) { File visualizationFile = new File(PortalConfiguration.jobIdToPath(jobId.value()) + ".html"); Files.deleteIfExists(visualizationFile.toPath()); FileUtils.write(new File(visualizationFile.getAbsolutePath()), job.getVisualization(), Charset.forName(FILE_ENCODING)); } return jobId; } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } catch (Exception e) { logger.warn("Unexpected error when submitting job", e); throw new JobCreationRestException(e); } }
Source:
<code>public void visitNode(Tree tree) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); <START> if (symbol.owner().isTypeSymbol() && symbol.isStatic()) { <END> addIssue(tree, "Remove this redundant \"static\" qualifier."); } }</code><technical_language>This check rely semantic !!</technical_language>

Target:
public void visitNode(Tree tree) { if (isStatic((ClassTree) tree)) { addIssue(tree, "Remove this redundant \"static\" qualifier."); } }
Source:
<code>public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != null) { for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { <START> features.getClusterFeatures().add(addLinks(ClusterFeaturesMapper.map(entity.getFeature(), <END> null))); } } } return features; }</code><technical_language>"map" here</technical_language>

Target:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != null) { for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { features.getClusterFeatures().add(addLinks(map(entity.getFeature(), null))); } } } return features; }
Source:
<code>protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context) { val token = credentials.getPassword(); LOGGER.trace("Received refresh token for authentication", token); val refreshToken = getTicketRegistry().getTicket(token, OAuth20RefreshToken.class); if (refreshToken == null || refreshToken.isExpired() || !StringUtils.equals(refreshToken.getClientId(), credentials.getUsername())) { <START> LOGGER.error("Provided refresh token is either not found in the ticket registry or has expired or not related with the client provided"); <END> throw new CredentialsException("Invalid token: " + token); } }</code><technical_language>suggestion LOGGER.error("Provided refresh token is in ticket registry, expired is related client provided");</technical_language>

Target:
protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context) { val token = credentials.getPassword(); LOGGER.trace("Received refresh token for authentication", token); val refreshToken = getTicketRegistry().getTicket(token, OAuth20RefreshToken.class); val clientId = credentials.getUsername(); if (refreshToken == null || refreshToken.isExpired() || !StringUtils.equals(refreshToken.getClientId(), clientId)) { LOGGER.error("Provided refresh token is either not found in the ticket registry, has expired or is not related to the client [{}]", token, clientId); throw new CredentialsException("Invalid token: " + token); } }
Source:
<code>private void persistBloomFilter() throws StoreException { try { CrcOutputStream crcStream = new CrcOutputStream(new FileOutputStream(bloomFile)); DataOutputStream stream = new DataOutputStream(crcStream); FilterFactory.serialize(bloomFilter, stream); long crcValue = crcStream.getValue(); stream.writeLong(crcValue); stream.close(); } catch (IOException e) { <START> if (e.getClass() == IOException.class && e.getMessage().equals(StoreException.IO_ERROR_STR)) { <END> throw new StoreException("IO error while trying to persist bloom filter", e, StoreErrorCodes.IOError); } else { throw new StoreException("Unknown error while trying to persist bloom filter", e, StoreErrorCodes.Unknown_Error); } } }</code><technical_language>condition true</technical_language>

Target:
private void persistBloomFilter() throws StoreException { try { CrcOutputStream crcStream = new CrcOutputStream(new FileOutputStream(bloomFile)); DataOutputStream stream = new DataOutputStream(crcStream); FilterFactory.serialize(bloomFilter, stream); long crcValue = crcStream.getValue(); stream.writeLong(crcValue); stream.close(); } catch (IOException e) { StoreErrorCodes errorCode = e.getMessage().equals(StoreException.IO_ERROR_STR) ? StoreErrorCodes.IOError : StoreErrorCodes.Unknown_Error; throw new StoreException(errorCode.toString() + " while trying to persist bloom filter", e, errorCode); } }
Source:
<code>Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if(!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly set"); sendMessageToRoom("Transcriber is not properly configured. " + "Contact the host and let him now! I will now leave"); <START> jvbConference.stop(); <END> } jvbConferenceCall.setConference(new MediaAwareCallConference() { @Override public MediaDevice getDefaultDevice(MediaType mediaType, MediaUseCase useCase) { if(MediaType.AUDIO.equals(mediaType)) { return transcriber.getMediaDevice(); } return super.getDefaultDevice(mediaType, useCase); } }); addInitialMembers(); transcriber.start(); sendMessageToRoom("Started transcription!"); logger.debug("TranscriptionGatewaySession started transcribing"); return null; }</code><technical_language>return here, add members start transcriber? changing chat message "Contact service administrators know"</technical_language>

Target:
Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if(!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly configured"); sendMessageToRoom("Transcriber is not properly " + "configured. Contact the service administrators and let them " + "know! I will now leave."); jvbConference.stop(); return null; } jvbConferenceCall.setConference(new MediaAwareCallConference() { @Override public MediaDevice getDefaultDevice(MediaType mediaType, MediaUseCase useCase) { if(MediaType.AUDIO.equals(mediaType)) { return transcriber.getMediaDevice(); } return super.getDefaultDevice(mediaType, useCase); } }); addInitialMembers(); transcriber.start(); sendMessageToRoom("Started transcription!"); logger.debug("TranscriptionGatewaySession started transcribing"); return null; }
Source:
<code><START> private boolean saveVendorMaintenanceDocument(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { <END> GlobalVariables.getMessageMap().clearErrorMessages(); LOG.info("saveVendorMaintenanceDocument: vendorMaintenceDoc validate save business rules."); boolean documentSaved = false; try { getDocumentService().saveDocument(vendorMaintenceDoc); LOG.info("saveVendorMaintenanceDocument: vendorMaintenceDoc saved."); documentSaved = true; } catch (WorkflowException we) { List<String> edocCreateErrors = getPaymentWorksBatchUtilityService().convertReportDataValidationErrors(GlobalVariables.getMessageMap().getErrorMessages()); captureKfsProcessingErrorsForVendor(pmwVendor, reportData, edocCreateErrors); LOG.error("saveVendorMaintenanceDocument: eDoc saving error(s): " + edocCreateErrors.toString()); LOG.error("saveVendorMaintenanceDocument: eDoc saving exception caught: " + we.getMessage()); } finally { GlobalVariables.getMessageMap().clearErrorMessages(); } return documentSaved; }</code><technical_language>Another case nice minimize duplication save route variants, if practical</technical_language>

Target:
private boolean saveVendorMaintenanceDocument(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { return kfsVendorMaintenceDocumentActionProcessed(vendorMaintenceDoc, reportData, pmwVendor, DocumentAction.SAVE); }
Source:
<code>public MqttClient getMqttSinkClient(final String brokerURI) throws MqttException, IOException { this.publisherLock.lock(); final List<MqttClient> mqttClientList = mqttPublisherMap.get(brokerURI); if (mqttClientList == null) { <START> mqttPublisherMap.putIfAbsent(brokerURI, new ArrayList<>()); <END> final MqttClient client = new MqttClient(brokerURI, MQTT_PUBLISHER_ID_PREFIX + brokerURI + "_0"); final MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setMaxInflight(maxInflightMqttEventNum); client.connect(connectOptions); mqttPublisherMap.get(brokerURI).add(client); publisherSinkNumMap.put(client, 1); this.publisherLock.unlock(); return client; } else { final MqttClient clientCandidate = mqttClientList.get(mqttClientList.size() - 1); final int sinkNum = publisherSinkNumMap.get(clientCandidate); if (sinkNum < maxMqttSinkNumPerClient) { publisherSinkNumMap.replace(clientCandidate, sinkNum + 1); this.publisherLock.unlock(); return clientCandidate; } else { final MqttClient newClientCandidate = new MqttClient(brokerURI, MQTTSharedResource.MQTT_PUBLISHER_ID_PREFIX + brokerURI + "_" + mqttClientList.size()); final MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setMaxInflight(maxInflightMqttEventNum); newClientCandidate.connect(connectOptions); mqttClientList.add(newClientCandidate); publisherSinkNumMap.put(newClientCandidate, 1); this.publisherLock.unlock(); return newClientCandidate; } } }</code><technical_language>putIfAbsent -> put</technical_language>

Target:
public MqttClient getMqttSinkClient(final String brokerURI) throws MqttException, IOException { this.publisherLock.lock(); final List<MqttClient> mqttClientList = mqttPublisherMap.get(brokerURI); if (mqttClientList == null) { mqttPublisherMap.put(brokerURI, new ArrayList<>()); final MqttClient client = createSinkClient(brokerURI, mqttPublisherMap.get(brokerURI)); this.publisherLock.unlock(); return client; } else { final MqttClient clientCandidate = mqttClientList.get(mqttClientList.size() - 1); final int sinkNum = publisherSinkNumMap.get(clientCandidate); if (sinkNum < maxMqttSinkNumPerClient) { publisherSinkNumMap.replace(clientCandidate, sinkNum + 1); this.publisherLock.unlock(); return clientCandidate; } else { final MqttClient newClientCandidate = createSinkClient(brokerURI, mqttClientList); this.publisherLock.unlock(); return newClientCandidate; } } }
Source:
<code>Map<String, String> parseGroupingKey(final String groupingKeyConfig) { if (!groupingKeyConfig.isEmpty()) { Map<String, String> groupingKey = new HashMap<>(); String[] kvs = groupingKeyConfig.split(";"); for (String kv : kvs) { int idx = kv.indexOf("="); if (idx < 0) { <START> LOG.warn("Invalid prometheusPushGateway groupingKey:" + kv + ", will be ignored"); <END> continue; } String labelKey = kv.substring(0, idx); String labelValue = kv.substring(idx + 1); if (StringUtils.isEmpty(labelKey) || StringUtils.isEmpty(labelValue)) { LOG.warn("Invalid groupingKey labelKey:" + labelKey + ", labelValue:" + labelValue + " must not be empty"); continue; } groupingKey.put(labelKey, labelValue); } return groupingKey; } return Collections.emptyMap(); }</code><technical_language>slf4j lets for expansion</technical_language>

Target:
Map<String, String> parseGroupingKey(final String groupingKeyConfig) { if (!groupingKeyConfig.isEmpty()) { Map<String, String> groupingKey = new HashMap<>(); String[] kvs = groupingKeyConfig.split(";"); for (String kv : kvs) { int idx = kv.indexOf("="); if (idx < 0) { LOG.warn("Invalid prometheusPushGateway groupingKey:{}, will be ignored", kv); continue; } String labelKey = kv.substring(0, idx); String labelValue = kv.substring(idx + 1); if (StringUtils.isEmpty(labelKey) || StringUtils.isEmpty(labelValue)) { LOG.warn("Invalid groupingKey labelKey:{}, labelValue:{} must not be empty", labelKey, labelValue); continue; } groupingKey.put(labelKey, labelValue); } return groupingKey; } return Collections.emptyMap(); }
Source:
<code>private void writeData(PartitionIterable partitions) throws SemanticException { try { if (tableSpec.tableHandle.isPartitioned()) { if (partitions == null) { throw new IllegalStateException("partitions cannot be null for partitionTable :" + tableSpec.getTableName().getTable()); } new PartitionExport(paths, partitions, distCpDoAsUser, conf, mmCtx).write(replicationSpec); } else { List<Path> dataPathList = Utils.getDataPathList(tableSpec.tableHandle.getDataLocation(), replicationSpec, conf); <START> if (!replicationSpec.isLazy()) { <END> new FileOperations(dataPathList, paths.dataExportDir(), distCpDoAsUser, conf, mmCtx).export(); } } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }</code><technical_language>Is check needed</technical_language>

Target:
private void writeData(PartitionIterable partitions) throws SemanticException { try { if (tableSpec.tableHandle.isPartitioned()) { if (partitions == null) { throw new IllegalStateException("partitions cannot be null for partitionTable :" + tableSpec.getTableName().getTable()); } new PartitionExport(paths, partitions, distCpDoAsUser, conf, mmCtx).write(replicationSpec); } else { List<Path> dataPathList = Utils.getDataPathList(tableSpec.tableHandle.getDataLocation(), replicationSpec, conf); new FileOperations(dataPathList, paths.dataExportDir(), distCpDoAsUser, conf, mmCtx) .export(replicationSpec); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }
Source:
<code>public void testTextWrapBoundariesUpdatesOnSetSize() { tested.setSize(10, 10); <START> verify(textDecorator).setTextBoundaries(any()); <END> }</code><technical_language>verify text boundaries correct? Verifying simply set boundaries text decorator is ascertain values set</technical_language>

Target:
public void testTextWrapBoundariesUpdatesOnSetSize() { tested.setSize(10, 10); verify(textDecorator).setTextBoundaries(PATH.getBoundingBox()); }
Source:
<code>private SampleIdentity createParentIdentity(DetailedSample sample) throws IOException, MisoNamingException, SQLException { log.debug("Creating a new Identity to use as a parent."); List<SampleClass> identityClasses = sampleClassService.listByCategory(SampleIdentity.CATEGORY_NAME); if (identityClasses.size() != 1) { throw new IllegalStateException("Found more or less than one SampleClass of category " + SampleIdentity.CATEGORY_NAME + ". Cannot choose which to use as root sample class."); } SampleClass rootSampleClass = identityClasses.get(0); <START> String internalName = sample.getProject().getShortName() + "_"; <END> String number = sampleNumberPerProjectService.nextNumber(sample.getProject(), internalName); internalName += number; if (sample.getProject().getShortName() == null) { throw new NullPointerException("Project shortname required to generate Identity alias"); } SampleIdentity shellParent = (SampleIdentity) sample.getParent(); confirmExternalNameUniqueForProjectIfRequired(shellParent.getExternalName(), sample); Sample identitySample = new IdentityBuilder().project(sample.getProject()) .sampleType(sample.getSampleType()).scientificName(sample.getScientificName()).name(generateTemporaryName()) .alias(internalName).rootSampleClass(rootSampleClass).volume(0D).externalName(shellParent.getExternalName()) .donorSex(shellParent.getDonorSex()).build(); setChangeDetails(identitySample); return (SampleIdentity) save(identitySample, true); }</code><technical_language>need move this null check line 462</technical_language>

Target:
private SampleIdentity createParentIdentity(DetailedSample sample) throws IOException, MisoNamingException, SQLException { log.debug("Creating a new Identity to use as a parent."); List<SampleClass> identityClasses = sampleClassService.listByCategory(SampleIdentity.CATEGORY_NAME); if (identityClasses.size() != 1) { throw new IllegalStateException("Found more or less than one SampleClass of category " + SampleIdentity.CATEGORY_NAME + ". Cannot choose which to use as root sample class."); } SampleClass rootSampleClass = identityClasses.get(0); if (sample.getProject().getShortName() == null) { throw new NullPointerException("Project shortname required to generate Identity alias"); } String internalName = sample.getProject().getShortName() + "_"; String number = sampleNumberPerProjectService.nextNumber(sample.getProject(), internalName); internalName += number; SampleIdentity shellParent = (SampleIdentity) sample.getParent(); confirmExternalNameUniqueForProjectIfRequired(shellParent.getExternalName(), sample); Sample identitySample = new IdentityBuilder().project(sample.getProject()) .sampleType(sample.getSampleType()).scientificName(sample.getScientificName()).name(generateTemporaryName()) .alias(internalName).rootSampleClass(rootSampleClass).volume(0D).externalName(shellParent.getExternalName()) .donorSex(shellParent.getDonorSex()).build(); setChangeDetails(identitySample); return (SampleIdentity) save(identitySample, true); }
Source:
<code>protected void commonInitialize() { super.commonInitialize(); getModel().getIsStateless().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (getModel().getTemplateWithVersion() == null || getModel().getTemplateWithVersion().getItems() == null || getModel().getTemplateWithVersion().getSelectedItem() == null) { return; } List<VmTemplate> baseTemplates = new ArrayList<>(); for (TemplateWithVersion templateWithVersion : getModel().getTemplateWithVersion().getItems()) { if (templateWithVersion.isLatest()) { continue; } <START> baseTemplates.add(templateWithVersion.getBaseTemplate()); <END> } TemplateWithVersion selectedItemTemplateWithVersion = getModel().getTemplateWithVersion().getSelectedItem(); VmTemplate selectedTemplateWithVersion = selectedItemTemplateWithVersion.getTemplateVersion(); if (selectedTemplateWithVersion == null) { return; } Guid selectedId = selectedTemplateWithVersion.getId(); updateStatelessFlag = false; initTemplateWithVersion(baseTemplates, selectedId, selectedItemTemplateWithVersion.isLatest(), getModel().getIsStateless().getEntity()); } }); }</code><technical_language>IIUIC baseTemplates list base-templates multiple times. baseTemplates is parameter of initTemplateWithVersion() expects templates (not base-ones). .getTemplateVersion()</technical_language>

Target:
protected void commonInitialize() { super.commonInitialize(); getModel().getIsStateless().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (getModel().getTemplateWithVersion() == null || getModel().getTemplateWithVersion().getItems() == null || getModel().getTemplateWithVersion().getSelectedItem() == null) { return; } List<VmTemplate> baseTemplates = new ArrayList<>(); for (TemplateWithVersion templateWithVersion : getModel().getTemplateWithVersion().getItems()) { if (templateWithVersion.isLatest() || templateWithVersion.getTemplateVersion() == null) { continue; } baseTemplates.add(templateWithVersion.getTemplateVersion()); } TemplateWithVersion selectedItemTemplateWithVersion = getModel().getTemplateWithVersion().getSelectedItem(); VmTemplate selectedTemplateWithVersion = selectedItemTemplateWithVersion.getTemplateVersion(); if (selectedTemplateWithVersion == null) { return; } Guid selectedId = selectedTemplateWithVersion.getId(); updateStatelessFlag = false; initTemplateWithVersion(baseTemplates, selectedId, selectedItemTemplateWithVersion.isLatest(), getModel().getIsStateless().getEntity()); } }); }
Source:
<code>private void addTakeToDb() { ProjectDatabaseHelper db = new ProjectDatabaseHelper(this); ProjectPatternMatcher ppm = mProject.getPatternMatcher(); ppm.match(mNewRecording.getFile()); db.addTake( ppm.getTakeInfo(), mNewRecording.getFile().getName(), mNewRecording.getMetadata().getModeSlug(), mNewRecording.getFile().lastModified(), 0, mUser.getId() ); if(chunkPlugin != null) { ProjectProgress pp = new ProjectProgress(mProject, db, chunkPlugin.getChapters()); pp.updateProjectProgress(); } <START> db.close(); <END> }</code><technical_language>good close this if instance for activity</technical_language>

Target:
private void addTakeToDb() { ProjectPatternMatcher ppm = mProject.getPatternMatcher(); ppm.match(mNewRecording.getFile()); db.addTake( ppm.getTakeInfo(), mNewRecording.getFile().getName(), mNewRecording.getMetadata().getModeSlug(), mNewRecording.getFile().lastModified(), 0, mUser.getId() ); if(projectProgress != null) { projectProgress.updateProjectProgress(); } }
Source:
<code>private static void createTables(SchemaDao dao) { dao.createTableDistributions(); dao.createTableTables(); dao.createTableColumns(); dao.createTableViews(); dao.createTableNodes(); dao.createTableShards(); dao.createTableShardNodes(); dao.createTableExternalBatches(); dao.createTableTransactions(); dao.createTableCreatedShards(); dao.createTableDeletedShards(); dao.createTableBuckets(); dao.createTableShardOrganizerJobs(); try { dao.alterTableTables(); <START> dao.alterTableShards(); <END> } catch (Exception e) { log.info("alter table failed: s%", e); } }</code><technical_language>If previous statement throws, this executed</technical_language>

Target:
private static void createTables(SchemaDao dao) { dao.createTableDistributions(); dao.createTableTables(); dao.createTableColumns(); dao.createTableViews(); dao.createTableNodes(); dao.createTableShards(); dao.createTableShardNodes(); dao.createTableExternalBatches(); dao.createTableTransactions(); dao.createTableCreatedShards(); dao.createTableDeletedShards(); dao.createTableBuckets(); dao.createTableShardOrganizerJobs(); alterTable(dao::alterTableTablesWithDeltaDelete); alterTable(dao::alterTableTablesWithDeltaCount); alterTable(dao::alterTableShardsWithIsDelta); alterTable(dao::alterTableShardsWithDeltaUuid); }
Source:
<code>private synchronized void writeCurrentBufferToService() throws IOException { <START> outputStreamStatistics.writeCurrentBuffer(); <END> if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; outputStreamStatistics.bytesToUpload(bytesLength); buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { long start = System.currentTimeMillis(); waitForTaskToComplete(); outputStreamStatistics.timeSpentTaskWait(start, System.currentTimeMillis()); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); if (job.isCancelled()) { outputStreamStatistics.uploadFailed(bytesLength); } else { outputStreamStatistics.uploadSuccessful(bytesLength); } writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }</code><technical_language>if clause</technical_language>

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } outputStreamStatistics.writeCurrentBuffer(); final byte[] bytes = buffer; final int bytesLength = bufferIndex; outputStreamStatistics.bytesToUpload(bytesLength); buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { long start = System.currentTimeMillis(); waitForTaskToComplete(); outputStreamStatistics.timeSpentTaskWait(start, System.currentTimeMillis()); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); if (job.isCancelled()) { outputStreamStatistics.uploadFailed(bytesLength); } else { outputStreamStatistics.uploadSuccessful(bytesLength); } writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
<code><START> public void calculateAgeAdjustedRawValue(Context context){ <END> double adjust_for = AGE_ADJUSTMENT_TIME - time_since_sensor_started; if (adjust_for > 0 && !CollectionServiceStarter.isLimitter(context)) { age_adjusted_raw_value = ((AGE_ADJUSTMENT_FACTOR * (adjust_for / AGE_ADJUSTMENT_TIME)) * raw_data) + raw_data; Log.i(TAG, "calculateAgeAdjustedRawValue: RAW VALUE ADJUSTMENT FROM:" + raw_data + " TO: " + age_adjusted_raw_value); } else { age_adjusted_raw_value = raw_data; } }</code><technical_language>please start function with: if(CollectionServiceStarter.isLimitter(context)) { age_adjusted_raw_value = raw_data; return; } readable</technical_language>

Target:
public void calculateAgeAdjustedRawValue(Context context){ double adjust_for = AGE_ADJUSTMENT_TIME - time_since_sensor_started; if (adjust_for <= 0 || CollectionServiceStarter.isLimitter(context)) { age_adjusted_raw_value = raw_data; } else { age_adjusted_raw_value = ((AGE_ADJUSTMENT_FACTOR * (adjust_for / AGE_ADJUSTMENT_TIME)) * raw_data) + raw_data; Log.i(TAG, "calculateAgeAdjustedRawValue: RAW VALUE ADJUSTMENT FROM:" + raw_data + " TO: " + age_adjusted_raw_value); } }
Source:
<code>public void shouldStoreAndLoadStrings() throws Exception { try ( StringCollisionValues values = new StringCollisionValues( factory, 100_000 ); ) { long[] offsets = new long[100]; String[] strings = new String[offsets.length]; for ( int i = 0; i < offsets.length; i++ ) { <START> String string = random.string(); <END> offsets[i] = values.add( string ); strings[i] = string; } for ( int i = 0; i < offsets.length; i++ ) { assertEquals( strings[i], values.get( offsets[i] ) ); } } }</code><technical_language>default, maximum length of string this produce is 20 characters. I misses a lot of important edge cases</technical_language>

Target:
public void shouldStoreAndLoadStrings() throws Exception { try ( StringCollisionValues values = new StringCollisionValues( factory, 10_000 ); ) { long[] offsets = new long[100]; String[] strings = new String[offsets.length]; for ( int i = 0; i < offsets.length; i++ ) { String string = random.string(); offsets[i] = values.add( string ); strings[i] = string; } for ( int i = 0; i < offsets.length; i++ ) { assertEquals( strings[i], values.get( offsets[i] ) ); } } }
Source:
<code>public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); } AbstractEEFWidgetLifecycleManager.this.setLabelFontStyle(); } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, <START> "No description available")); <END> } } }); }</code><technical_language>externalized in Messages class</technical_language>

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); } AbstractEEFWidgetLifecycleManager.this.setLabelFontStyle(); } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, Messages.AbstractEEFWidgetLifecycleManager_noDescriptionAvailable)); } } }); }
Source:
<code>private FunctionCheckedException<CassandraClient, Void, TException> truncationFunction( Collection<TableReference> tablesToTruncate) { return new FunctionCheckedException<CassandraClient, Void, TException>() { @Override public Void apply(CassandraClient client) throws TException { for (TableReference tableRef : tablesToTruncate) { queryRunner.run(client, tableRef, () -> { client.truncate(CassandraKeyValueServiceImpl.internalTableName(tableRef)); return true; }); } return null; } @Override public String toString() { <START> return "truncateTables(" + tablesToTruncate.size() + " tables)"; <END> } }; }</code><technical_language>nit: if (but if) tables C* safe, this table names</technical_language>

Target:
private FunctionCheckedException<CassandraClient, Void, TException> truncationFunction( Collection<TableReference> tablesToTruncate) { return new FunctionCheckedException<CassandraClient, Void, TException>() { @Override public Void apply(CassandraClient client) throws TException { for (TableReference tableRef : tablesToTruncate) { queryRunner.run(client, tableRef, () -> { client.truncate(CassandraKeyValueServiceImpl.internalTableName(tableRef)); return true; }); } return null; } @Override public String toString() { return "truncateTables(" + tablesToTruncate + ")"; } }; }
Source:
<code>public void startingAndroidAppWithCapabilitiesOnlyTest(){ File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); AndroidDriver<MobileElement> driver = null; try { driver = new AndroidDriver<>(capabilities); Capabilities caps = driver.getCapabilities(); <START> Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); <END> Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); Assert.assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); } finally { if (driver != null) driver.quit(); } }</code><technical_language>A static import for Assert.* methods this a bit more readable</technical_language>

Target:
public void startingAndroidAppWithCapabilitiesOnlyTest(){ File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); AndroidDriver<MobileElement> driver = new AndroidDriver<>(capabilities);; try { Capabilities caps = driver.getCapabilities(); assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); } finally { driver.quit(); } }
Source:
<code>public static void onBlockRandomTick(World worldIn, BlockPos pos, IBlockState state, Random random) { if(BlockEvent.RandomTickEvent.RandomBlockTickEventRegistry.isEventRegistredForBlock(state.getBlock())) { BlockEvent.RandomTickEvent rte = new BlockEvent.RandomTickEvent(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(rte); if(!rte.isCanceled()) { state.getBlock().randomTick(worldIn, pos, state, random); BlockEvent.RandomTickEvent.Post post = new BlockEvent.RandomTickEvent.Post(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(post); } else { <START> if(!(rte.getState() == state)) <END> { if(!worldIn.isRemote) { worldIn.setBlockState(pos, rte.getState(), 3); } } } } else state.getBlock().randomTick(worldIn, pos, state, random); }</code><technical_language>if(rte.getState() != state) (would a tad bit more readable)</technical_language>

Target:
public static void onBlockRandomTick(World worldIn, BlockPos pos, IBlockState state, Random random) { if(BlockEvent.RandomTickEvent.RandomBlockTickEventRegistry.isBlockRegistred(state.getBlock())) { BlockEvent.RandomTickEvent rte = new BlockEvent.RandomTickEvent(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(rte); if(!rte.isCanceled()) { state.getBlock().randomTick(worldIn, pos, state, random); BlockEvent.RandomTickEvent.Post post = new BlockEvent.RandomTickEvent.Post(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(post); } else { if(rte.getState() != state) { if(!worldIn.isRemote) { worldIn.setBlockState(pos, rte.getState(), 3); } } } } else state.getBlock().randomTick(worldIn, pos, state, random); }
Source:
<code>private void doMediaIdsSelected(ArrayList<Long> mediaIds, @NonNull PhotoPickerMediaSource source) { <START> if (mBrowserType == MediaBrowserType.FEATURED_IMAGE_PICKER && mediaIds != null && mediaIds.size() == 1) { <END> mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, mLocalPostId ); Intent data = new Intent() .putExtra(EXTRA_MEDIA_ID, mediaIds.get(0)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } else { Intent data = new Intent() .putExtra(MediaBrowserActivity.RESULT_IDS, ListUtils.toLongArray(mediaIds)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } }</code><technical_language>This condition a bit misleading. Do want invoke else branch mediaIds.size != 1? checking for mediaIds != null, null app crash in else branch, wdyt? want consider checking if media != null && media.size() > 0 beginning of this method logging exception false. Wdyt</technical_language>

Target:
private void doMediaIdsSelected(ArrayList<Long> mediaIds, @NonNull PhotoPickerMediaSource source) { if (mediaIds != null && mediaIds.size() == 1) { if (mBrowserType == MediaBrowserType.FEATURED_IMAGE_PICKER) { mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, mLocalPostId ); Intent data = new Intent() .putExtra(EXTRA_MEDIA_ID, mediaIds.get(0)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } else { Intent data = new Intent() .putExtra(MediaBrowserActivity.RESULT_IDS, ListUtils.toLongArray(mediaIds)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } } else { throw new IllegalArgumentException("call to doMediaIdsSelected with null or empty mediaIds array"); } }
Source:
<code>public Page getOutput() { if (pageBuilder.isFull()) { Page output = pageBuilder.build(); pageBuilder.reset(); return output; } if (pendingInput != null) { processInput(pendingInput); updateMemoryUsage(); return null; } if (finishing) { if (previousRow != null) { evaluateAggregatesToPageBuilder(previousRow, 0); previousRow = null; } Page output = null; <START> if (!pageBuilder.isEmpty()) { <END> output = pageBuilder.build(); } pageBuilder.reset(); return output; } return null; }</code><technical_language>flush unfinished aggregates in finish() method. If follow suggestion outputPages, this method greatly simplify</technical_language>

Target:
public Page getOutput() { if (!outputPages.isEmpty()) { return outputPages.removeFirst(); } return null; }
Source:
<code>public void testResolveTools() throws Exception { evalRuleContextCode( createRuleContext(" <START> "inputs, input_manifests = ruleContext.resolve_tools(", <END> " tools=ruleContext.attr.tools)"); assertArtifactFilenames( ((SkylarkNestedSet) lookup("inputs")).getSet(Artifact.class), "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); @SuppressWarnings("unchecked") CompositeRunfilesSupplier runfilesSupplier = new CompositeRunfilesSupplier((List<RunfilesSupplier>) lookup("input_manifests")); assertThat(runfilesSupplier.getMappings(ArtifactPathResolver.IDENTITY)).hasSize(1); }</code><technical_language>verify passed ctx.action.run</technical_language>

Target:
public void testResolveTools() throws Exception { SkylarkRuleContext ruleContext = createRuleContext(" evalRuleContextCode( ruleContext, "inputs, input_manifests = ruleContext.resolve_tools(tools=ruleContext.attr.tools)", "ruleContext.actions.run(", " outputs = [ruleContext.actions.declare_file('x.out')],", " inputs = inputs,", " input_manifests = input_manifests,", " executable = 'dummy',", ")"); assertArtifactFilenames( ((SkylarkNestedSet) lookup("inputs")).getSet(Artifact.class), "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); @SuppressWarnings("unchecked") CompositeRunfilesSupplier runfilesSupplier = new CompositeRunfilesSupplier((List<RunfilesSupplier>) lookup("input_manifests")); assertThat(runfilesSupplier.getMappings(ArtifactPathResolver.IDENTITY)).hasSize(1); SpawnAction action = (SpawnAction) Iterables.getOnlyElement( ruleContext.getRuleContext().getAnalysisEnvironment().getRegisteredActions()); assertThat(ActionsTestUtil.baseArtifactNames(action.getInputs())) .containsAllOf( "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); }
Source:
<code>public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { Optional<VehicleData> vehicleData = get(VehicleData.class); if (vehicleData.isPresent()) { manipulators.add(vehicleData.get()); } if (this.fire > 0) { manipulators.add(get(IgniteableData.class).get()); } <START> manipulators.add(new SpongeGravityData()); <END> }</code><technical_language>no, need pass in entity's current gravity state, hasNoGravity</technical_language>

Target:
public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { Optional<VehicleData> vehicleData = get(VehicleData.class); if (vehicleData.isPresent()) { manipulators.add(vehicleData.get()); } if (this.fire > 0) { manipulators.add(get(IgniteableData.class).get()); } manipulators.add(new SpongeGravityData(!this.hasNoGravity())); }
Source:
<code>public void storeLocalMapping(RespondingGatewayPRPAIN201305UV02RequestType request) { LOG.debug("Begin storeLocalMapping"); String hcid = HomeCommunityMap.getLocalHomeCommunityId(); <START> LOG.debug("Begin storeLocalMapping: hcid", hcid); <END> II patId = extractPatientIdFrom201305(request.getPRPAIN201305UV02()); AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); if (patId == null) { LOG.warn("AssigningAuthorityHomeCommunityMappingDAO or Local Patient Id was null. Mapping was not stored."); } else { if (!mappingDao.storeMapping(hcid, patId.getRoot())) { LOG.warn("Failed to store home community - assigning authority mapping"); } } LOG.debug("End storeLocalMapping"); }</code><technical_language>missing log's parameter</technical_language>

Target:
public void storeLocalMapping(RespondingGatewayPRPAIN201305UV02RequestType request) { LOG.debug("Begin storeLocalMapping"); String hcid = HomeCommunityMap.getLocalHomeCommunityId(); LOG.debug("Begin storeLocalMapping hcid : ", hcid); II patId = extractPatientIdFrom201305(request.getPRPAIN201305UV02()); AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); if (patId == null) { LOG.warn("AssigningAuthorityHomeCommunityMappingDAO or Local Patient Id was null. Mapping was not stored."); } else { if (!mappingDao.storeMapping(hcid, patId.getRoot())) { LOG.warn("Failed to store home community - assigning authority mapping"); } } LOG.debug("End storeLocalMapping"); }
Source:
<code>public void testCheckProjectAdminAccessInvalidUserSession() throws AccessControlException { final TestSession sessions = new TestSession(); final ACDAOFacade acDAOFacade = new DAOFacadeMock(); final ESOrgUnitRepository orgUnitRepository = new ESOrgUnitRepositoryImpl(acDAOFacade); final ESOrgUnitProvider orgUnitProvider = new ESOrgUnitProviderImpl(orgUnitRepository); final ESOrgUnitResolver orgUnitResolver = new DefaultESOrgUnitResolverService(); orgUnitResolver.init(orgUnitProvider); final DefaultESAuthorizationService defaultESAuthorizationService = createServiceUnderTest(sessions, orgUnitProvider, orgUnitResolver); final SessionIdImpl sessionId = (SessionIdImpl) ModelFactory.eINSTANCE.createSessionId(); <START> final ProjectIdImpl projectId = (ProjectIdImpl) ModelFactory.eINSTANCE.createProjectId(); <END> try { defaultESAuthorizationService.checkProjectAdminAccess( sessionId.toAPI(), projectId.toAPI(), ESProjectAdminPrivileges.AssignRoleToOrgUnit); } catch (final SessionTimedOutException ex) { assertEquals(Messages.AccessControlImpl_SessionID_Unknown, ex.getMessage()); throw ex; } }</code><technical_language>Setup block for tests. sense extract a method</technical_language>

Target:
public void testCheckProjectAdminAccessInvalidUserSession() throws AccessControlException { final DefaultESAuthorizationService defaultESAuthorizationService = createServiceUnderTest(sessions, orgUnitProvider, orgUnitResolver); try { defaultESAuthorizationService.checkProjectAdminAccess( sessionId.toAPI(), projectId.toAPI(), ESProjectAdminPrivileges.AssignRoleToOrgUnit); } catch (final SessionTimedOutException ex) { assertEquals(Messages.AccessControlImpl_SessionID_Unknown, ex.getMessage()); throw ex; } }
Source:
<code>public boolean isNull(RexNode node) { <START> final Policy policy = MAP.getOrDefault(node.getKind(), Policy.AS_IS); <END> switch (policy) { case NOT_NULL: return false; case ANY: return anyNull(((RexCall) node).getOperands()); default: break; } switch (node.getKind()) { case LITERAL: return ((RexLiteral) node).isNull(); case AND: case OR: case COALESCE: return allNull(((RexCall) node).getOperands()); case NULLIF: return allNull(ImmutableList.of(((RexCall) node).getOperands().get(0))); case INPUT_REF: return isNull((RexInputRef) node); case CASE: final RexCall caseCall = (RexCall) node; final List<RexNode> caseValues = new ArrayList<>(); for (int i = 0; i < caseCall.getOperands().size(); i++) { if (!RexUtil.isCasePredicate(caseCall, i)) { caseValues.add(caseCall.getOperands().get(i)); } } return allNull(caseValues); default: return false; } }</code><technical_language>policy(node.getKind())</technical_language>

Target:
public boolean isNull(RexNode node) { final Policy policy = policy(node.getKind()); switch (policy) { case NOT_NULL: return false; case ANY: return anyNull(((RexCall) node).getOperands()); default: break; } switch (node.getKind()) { case LITERAL: return ((RexLiteral) node).isNull(); case AND: case OR: case COALESCE: return allNull(((RexCall) node).getOperands()); case NULLIF: return allNull(ImmutableList.of(((RexCall) node).getOperands().get(0))); case INPUT_REF: return isNull((RexInputRef) node); case CASE: final RexCall caseCall = (RexCall) node; final List<RexNode> caseValues = new ArrayList<>(); for (int i = 0; i < caseCall.getOperands().size(); i++) { if (!RexUtil.isCasePredicate(caseCall, i)) { caseValues.add(caseCall.getOperands().get(i)); } } return allNull(caseValues); default: return false; } }