auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public List<org.kie.server.controller.api.model.runtime.Container> startScanner(ServerTemplate serverTemplate, final ContainerSpec containerSpec, final long interval) { <END> return callRemoteKieServerOperation(serverTemplate, containerSpec, new RemoteKieServerOperation<Void>(){ @Override public Void doOperation(KieServicesClient client, Container container) { KieScannerResource scannerResource = new KieScannerResource(); scannerResource.setPollInterval(interval); scannerResource.setStatus(KieScannerStatus.STARTED); ServiceResponse<KieScannerResource> response = client.updateScanner(containerSpec.getId(), scannerResource); if (!response.getType().equals(ServiceResponse.ResponseType.SUCCESS)) { logger.debug("Scanner failed to start on server instance due to {}", container.getUrl(), response.getMsg()); } collectContainerInfo(containerSpec, client, container); return null; } }); }</code><technical_language>FQCN is some places? Is purpose</technical_language>

Target:
public List<Container> startScanner(ServerTemplate serverTemplate, final ContainerSpec containerSpec, final long interval) { return callRemoteKieServerOperation(serverTemplate, containerSpec, new RemoteKieServerOperation<Void>(){ @Override public Void doOperation(KieServicesClient client, Container container) { KieScannerResource scannerResource = new KieScannerResource(); scannerResource.setPollInterval(interval); scannerResource.setStatus(KieScannerStatus.STARTED); ServiceResponse<KieScannerResource> response = client.updateScanner(containerSpec.getId(), scannerResource); if (!response.getType().equals(ServiceResponse.ResponseType.SUCCESS)) { logger.debug("Scanner failed to start on server instance due to {}", container.getUrl(), response.getMsg()); } collectContainerInfo(containerSpec, client, container); return null; } }); }
Source:
<code>public void run() { reader = new BufferedReader(new InputStreamReader(in)); <START> <END> String line; String responseText = ""; while (!interrupted) { try { line = reader.readLine(); if (line == null) { throw new EOFException("lost connection"); } else { Matcher m = EVENT_PATTERN.matcher(line); logger.trace("Received message: {}", line); if (m.matches()) { String code = m.group(1); String repeatsHex = m.group(2); String button = m.group(3); String remote = m.group(4); int repeats = Integer.parseInt(repeatsHex, 16); LIRCButtonEvent buttonMessage = new LIRCButtonEvent(remote, button, repeats, code); connector.sendButtonToListeners(buttonMessage); } else { if ("BEGIN".equals(line)) { responseText = ""; } else if ("END".equals(line)) { processResponse(responseText); responseText = null; } else { responseText += line + "\n"; } } } } catch (InterruptedIOException e) { Thread.currentThread().interrupt(); logger.error("Interrupted via InterruptedIOException"); } catch (EOFException e) { logger.error("Lost connection to LIRC server", e); connector.sendErrorToListeners(e.getMessage()); this.interrupt(); } catch (IOException e) { if (!interrupted) { logger.error("Reading from socket failed", e); connector.sendErrorToListeners(e.getMessage()); } } catch (LIRCResponseException e) { logger.error("Invalid message received", e); } } IOUtils.closeQuietly(reader); }</code><technical_language>blank lines in here</technical_language>

Target:
public void run() { reader = new BufferedReader(new InputStreamReader(in)); String line; String responseText = ""; while (!interrupted) { try { line = reader.readLine(); if (line == null) { throw new EOFException("lost connection"); } else { logger.trace("Received message: {}", line); Matcher m = EVENT_PATTERN.matcher(line); if (m.matches()) { String code = m.group(1); String repeatsHex = m.group(2); String button = m.group(3); String remote = m.group(4); int repeats = Integer.parseInt(repeatsHex, 16); LIRCButtonEvent buttonMessage = new LIRCButtonEvent(remote, button, repeats, code); connector.sendButtonToListeners(buttonMessage); } else { if ("BEGIN".equals(line)) { responseText = ""; } else if ("END".equals(line)) { processResponse(responseText); responseText = null; } else { responseText += line + "\n"; } } } } catch (InterruptedIOException e) { Thread.currentThread().interrupt(); logger.error("Interrupted via InterruptedIOException"); } catch (EOFException e) { logger.error("Lost connection to LIRC server", e); connector.sendErrorToListeners(e.getMessage()); this.interrupt(); } catch (IOException e) { if (!interrupted) { logger.error("Reading from socket failed", e); connector.sendErrorToListeners(e.getMessage()); } } catch (LIRCResponseException e) { logger.error("Invalid message received", e); } } IOUtils.closeQuietly(reader); }
Source:
<code>private void addTestResultException(XMLStringBuffer xmlBuffer, ITestResult testResult) { Throwable exception = testResult.getThrowable(); if (exception != null) { Properties exceptionAttrs = new Properties(); exceptionAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, exception.getClass().getName()); xmlBuffer.push(XMLReporterConfig.TAG_EXCEPTION, exceptionAttrs); if (!Utils.isStringEmpty(exception.getMessage())) { xmlBuffer.push(XMLReporterConfig.TAG_MESSAGE); xmlBuffer.addCDATA(exception.getMessage()); xmlBuffer.pop(); } String[] stackTraces = Utils.stackTrace(exception, false); int level = calculateStackTraceLevels(testResult); switch (level) { case XMLReporterConfig.STACKTRACE_SHORT: xmlBuffer.push(XMLReporterConfig.TAG_SHORT_STACKTRACE); <START> xmlBuffer.addCDATA(stackTraces[0]); <END> xmlBuffer.pop(); break; case XMLReporterConfig.STACKTRACE_FULL: xmlBuffer.push(XMLReporterConfig.TAG_FULL_STACKTRACE); xmlBuffer.addCDATA(stackTraces[1]); xmlBuffer.pop(); break; default: } xmlBuffer.pop(); } }</code><technical_language>stackTraces[0] (and [1]) frame of stack trace? I understand short full..</technical_language>

Target:
private void addTestResultException(XMLStringBuffer xmlBuffer, ITestResult testResult) { Throwable exception = testResult.getThrowable(); if (exception != null) { Properties exceptionAttrs = new Properties(); exceptionAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, exception.getClass().getName()); xmlBuffer.push(XMLReporterConfig.TAG_EXCEPTION, exceptionAttrs); if (!Utils.isStringEmpty(exception.getMessage())) { xmlBuffer.push(XMLReporterConfig.TAG_MESSAGE); xmlBuffer.addCDATA(exception.getMessage()); xmlBuffer.pop(); } XMLReporterConfig.StackTraceLevels level = calculateStackTraceLevels(testResult); switch (level) { case SHORT: xmlBuffer.push(XMLReporterConfig.TAG_SHORT_STACKTRACE); xmlBuffer.addCDATA(Utils.shortStackTrace(exception, false)); xmlBuffer.pop(); break; case FULL: xmlBuffer.push(XMLReporterConfig.TAG_FULL_STACKTRACE); xmlBuffer.addCDATA(Utils.longStackTrace(exception, false)); xmlBuffer.pop(); break; default: } xmlBuffer.pop(); } }
Source:
<code>public ButtonRs() { this( new ButtonRs.BuildInfoRetriever() { @Override public TestResponse info(final UriBuilder builder, final String stnd) { return RestTester.start( builder.path(stnd).build() ) .header( <START> "Accept", MediaType.APPLICATION_XML_UTF_8.toString() <END> ) .get("retrieve stand"); } } ); }</code><technical_language>HttpHeaders.ACCEPT constant</technical_language>

Target:
public ButtonRs() { this(ButtonRs.DEFAULT_BUILD); }
Source:
<code>void doPrefetch(long relativeOffset, long size) throws IOException { long sizeToRead = Math.min(size, getMessageInfo().getSize() - relativeOffset); prefetchedData = ByteBuffer.allocate((int) sizeToRead); <START> getChannel().position(offset.getOffset() + relativeOffset); <END> getChannel().read(prefetchedData); prefetchedDataRelativeOffset = relativeOffset; }</code><technical_language>this work in a concurrent environment. this a shared channel? instead [this](<LINK_0></technical_language>

Target:
void doPrefetch(long relativeOffset, long size) throws IOException { long sizeToRead = Math.min(size, getMessageInfo().getSize() - relativeOffset); prefetchedData = ByteBuffer.allocate((int) sizeToRead); getChannel().read(prefetchedData, offset.getOffset() + relativeOffset); prefetchedDataRelativeOffset = relativeOffset; }
Source:
<code>public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); context.setResponseStatusCode(status); if (entity != null) { context.setResponseDataStream(entity); } <START> boolean isOriginResponseGzipped = false; <END> if (headers.containsKey(CONTENT_ENCODING)) { List<String> collection = headers.get(CONTENT_ENCODING); for (String header : collection) { if (HTTPRequestUtils.getInstance().isGzipped(header)) { isOriginResponseGzipped = true; break; } } } context.setResponseGZipped(isOriginResponseGzipped); for (Entry<String, List<String>> header : headers.entrySet()) { String name = header.getKey(); for (String value : header.getValue()) { context.addOriginResponseHeader(name, value); if (name.equalsIgnoreCase(CONTENT_LENGTH)) { context.setOriginContentLength(value); } if (isIncludedHeader(name)) { context.addZuulResponseHeader(name, value); } } } }</code><technical_language>explain removed this other simplify</technical_language>

Target:
public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); context.setResponseStatusCode(status); if (entity != null) { context.setResponseDataStream(entity); } boolean isOriginResponseGzipped = false; for (Entry<String, List<String>> header : headers.entrySet()) { String name = header.getKey(); for (String value : header.getValue()) { if (name.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING) && HTTPRequestUtils.getInstance().isGzipped(value)) { isOriginResponseGzipped = true; } if (name.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { context.setOriginContentLength(value); } if (isIncludedHeader(name)) { context.addZuulResponseHeader(name, value); } } } context.setResponseGZipped(isOriginResponseGzipped); }
Source:
<code>public List<AuthorizationAttribute> getAll() { return Stream.of( Optional.ofNullable(readers).orElse(new ArrayList<>()), <START> Optional.ofNullable(admins).orElse(new ArrayList<>())) <END> .flatMap(Collection::stream).collect(Collectors.toList()); }</code><technical_language>I sense check for null is marked @Nullable In Nakadi not-nullable-by-default practice allows code clean unnecessary null checks</technical_language>

Target:
public List<AuthorizationAttribute> getAll() { return Stream.of(readers, admins) .flatMap(Collection::stream).collect(Collectors.toList()); }
Source:
<code>private ArrayList<MediaOption> initOtherMediaFileOptions() { ArrayList<MediaOption> otherMediaOptions = new ArrayList<>(); Bundle arguments = getArguments(); FragmentActivity activity = getActivity(); if (activity == null || arguments == null) { AppLog.e(T.EDITOR, "Failed to initialize other media options because the activity or getArguments() is null"); return otherMediaOptions; } String packageName = activity.getApplication().getPackageName(); <START> int stockMediaResourceId = <END> getResources().getIdentifier("photo_picker_choose_file", "string", packageName); otherMediaOptions.add(new MediaOption(MEDIA_SOURCE_FILE, getString(stockMediaResourceId))); return otherMediaOptions; }</code><technical_language>do renaming this suggestion int chooseFileResourceId = for more clarity</technical_language>

Target:
private ArrayList<MediaOption> initOtherMediaFileOptions() { ArrayList<MediaOption> otherMediaOptions = new ArrayList<>(); FragmentActivity activity = getActivity(); if (activity == null) { AppLog.e(T.EDITOR, "Failed to initialize other media options because the activity is null"); return otherMediaOptions; } String packageName = activity.getApplication().getPackageName(); int chooseFileResourceId = getResources().getIdentifier("photo_picker_choose_file", "string", packageName); otherMediaOptions.add(new MediaOption(MEDIA_SOURCE_FILE, getString(chooseFileResourceId))); return otherMediaOptions; }
Source:
<code>public void waitContextMenuJavaDocText(String expectedText) { waitJavaDocPopupSrcAttributeIsNotEmpty(); loadPageDriverWait.until( <START> new ExpectedCondition<Boolean>() { <END> @Override public Boolean apply(WebDriver driver) { String javaDocPopupHtmlText = ""; try { javaDocPopupHtmlText = getJavaDocPopupText(); } catch (IOException e) { LOG.error("Can not get java doc HTML text from autocomplete context menu in editor"); } return verifyJavaDoc(javaDocPopupHtmlText, expectedText); } }); }</code><technical_language>Please, rewrite lambda</technical_language>

Target:
public void waitContextMenuJavaDocText(String expectedText) { waitJavaDocPopupSrcAttributeIsNotEmpty(); loadPageDriverWait.until( (ExpectedCondition<Boolean>) driver -> { String javaDocPopupHtmlText = ""; try { javaDocPopupHtmlText = getJavaDocPopupText(); } catch (IOException e) { LOG.error( "Can not get java doc HTML text from autocomplete context menu in editor"); } return verifyJavaDoc(javaDocPopupHtmlText, expectedText); }); }
Source:
<code>public List<BakedQuad> getFaceQuads(EnumFacing side) { <START> ArrayList<BakedQuad> ret = new ArrayList(base.getFaceQuads(side)); <END> for (IFlexibleBakedModel bakedPart : parts) ret.addAll(bakedPart.getFaceQuads(side)); return ret; }</code><technical_language>This cached, especially if parts array immutable</technical_language>

Target:
public List<BakedQuad> getFaceQuads(EnumFacing side) { return faces.get(side); }
Source:
<code>public int hashCode() { <START> int result = super.hashCode(); <END> result = 31 * result + getLibraryId(); result = 31 * result + getReadGroup(); return result; }</code><technical_language>I start practice of Objects.hash() instead of computing hashes hand, e.g. replace this code return Objects.hash(super.hashCode(), getLibraryId(), getReadGroup());</technical_language>

Target:
public int hashCode() { int result = getLibraryId(); result = 31 * result + getReadGroup(); result = 31 * result + getTile(); result = 31 * result + getY(); result = 31 * result + getX(); return result; }
Source:
<code>public void updateEndpointRegistry(String registryId, String registryName, String registryType, EndpointRegistryInfo endpointRegistryInfo) throws EndpointRegistryException { String tenantDomain = MultitenantUtils .getTenantDomain(APIUtil.replaceEmailDomainBack(endpointRegistryInfo.getOwner())); int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); if (!registryType.equals(endpointRegistryInfo.getType()) && registryDAO.isEndpointRegistryTypeExists(endpointRegistryInfo.getType(), tenantId)) { <START> EndpointRegistryUtil.handleResourceAlreadyExistsException("Endpoint Registry of type '" <END> + endpointRegistryInfo.getType() + "' already exists"); } else if (!registryName.equals(endpointRegistryInfo.getName()) && registryDAO.isEndpointRegistryNameExists(endpointRegistryInfo.getName(), tenantId)) { EndpointRegistryUtil.handleResourceAlreadyExistsException("Endpoint Registry with name '" + endpointRegistryInfo.getName() + "' already exists"); } registryDAO.updateEndpointRegistry(registryId, endpointRegistryInfo, username); } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while updating " + "endpoint registry with id :" + registryId, e); } }</code><technical_language>this is throwing Exception raiseException instead of handleException</technical_language>

Target:
public void updateEndpointRegistry(String registryId, String registryName, String registryType, EndpointRegistryInfo endpointRegistryInfo) throws EndpointRegistryException { String tenantDomain = MultitenantUtils .getTenantDomain(APIUtil.replaceEmailDomainBack(endpointRegistryInfo.getOwner())); int tenantId; try { tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); if (!registryType.equals(endpointRegistryInfo.getType()) && registryDAO.isEndpointRegistryTypeExists(endpointRegistryInfo.getType(), tenantId)) { EndpointRegistryUtil.raiseResourceAlreadyExistsException("Endpoint Registry of type '" + endpointRegistryInfo.getType() + "' already exists"); } else if (!registryName.equals(endpointRegistryInfo.getName()) && registryDAO.isEndpointRegistryNameExists(endpointRegistryInfo.getName(), tenantId)) { EndpointRegistryUtil.raiseResourceAlreadyExistsException("Endpoint Registry with name '" + endpointRegistryInfo.getName() + "' already exists"); } registryDAO.updateEndpointRegistry(registryId, endpointRegistryInfo, username); } catch (UserStoreException e) { String msg = "Error while retrieving tenant information"; log.error(msg, e); throw new EndpointRegistryException("Error in retrieving Tenant Information while updating " + "endpoint registry with id :" + registryId, e); } }
Source:
<code>public void addTransactionHandler(Coordinator coordinator, Receiver receiver) { ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI); <START> coordinator.setCapabilities(Symbol.getSymbol("[\"amqp:local-transactions\",\"amqp:multi-txns-per-ssn\",\"amqp:multi-ssns-per-txn\"]")); <END> receiver.setContext(transactionHandler); receiver.open(); receiver.flow(100); }</code><technical_language>I Capabilities array of symbols applicable individual capability values, a CSV encoding of them</technical_language>

Target:
public void addTransactionHandler(Coordinator coordinator, Receiver receiver) { ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI); coordinator.setCapabilities(Symbol.getSymbol("amqp:local-transactions"), Symbol.getSymbol("amqp:multi-txns-per-ssn"), Symbol.getSymbol("amqp:multi-ssns-per-txn")); receiver.setContext(transactionHandler); receiver.open(); receiver.flow(100); }
Source:
<code>public void elementTextShouldNotBe(String locator, String text, String...params) { String message = robot.getParamsValue(params, 0, ""); List<WebElement> elements = elementFind(locator, true, true); Boolean ignoreCase = robot.getParamsValue(params, 1, Boolean.FALSE); String actual = elements.get(0).getText(); String textToCompare = text; if (ignoreCase) { actual = actual.toLowerCase(); textToCompare = textToCompare.toLowerCase(); } if (textToCompare.equals(actual)) { <START> if (StringUtils.isNotBlank(message)) { <END> message = String.format("The text of element '%s' should have been '%s', but it was '%s'.", locator, text, actual); } throw new SeleniumLibraryNonFatalException(message); } }</code><technical_language>Technically, this a incompatible change isNotBlank isNotEmpty</technical_language>

Target:
public void elementTextShouldNotBe(String locator, String text, String...params) { String message = robot.getParamsValue(params, 0, ""); List<WebElement> elements = elementFind(locator, true, true); Boolean ignoreCase = robot.getParamsValue(params, 1, Boolean.FALSE); String actual = elements.get(0).getText(); if (textIs(actual, text, ignoreCase)) { if (StringUtils.isEmpty(message)) { message = String.format("The text of element '%s' should have been '%s', but it was '%s'.", locator, text, actual); } throw new SeleniumLibraryNonFatalException(message); } }
Source:
<code>public boolean acquireLockPatiently(KeyType key, int maxWaitMillis) { final long startTime = System.currentTimeMillis(); boolean acquiredLock; while (!(acquiredLock = acquireLock(key)) && System.currentTimeMillis() - startTime < maxWaitMillis) { try { TimeUnit.MILLISECONDS.sleep(250L); } catch(InterruptedException ie) { <START> log.info("{}: interrupted acquiring lock", cacheName, ie); <END> } } if (!acquiredLock) { log.warn("{}: failed to acquire lock within milliseconds", cacheName, maxWaitMillis); } return acquiredLock; }</code><technical_language>swallowing interrupt is a bad idea, consider calling Thread.currentThread().interrupt() handled elsewhere</technical_language>

Target:
public boolean acquireLockPatiently(KeyType key, int maxWaitMillis) { final long startTime = System.currentTimeMillis(); boolean acquiredLock; while (!(acquiredLock = acquireLock(key)) && System.currentTimeMillis() - startTime < maxWaitMillis) { try { TimeUnit.MILLISECONDS.sleep(250L); } catch(InterruptedException ie) { log.info("{}: interrupted acquiring lock", cacheName, ie); Thread.currentThread().interrupt(); } } if (!acquiredLock) { log.warn("{}: failed to acquire lock within milliseconds", cacheName, maxWaitMillis); } return acquiredLock; }
Source:
<code>public void afterScenario(Scenario scenario) { if (scenario.isFailed()) { container.afterTest(new TestDescription() { @Override public String getTestId() { return scenario.getId(); } @Override public String getFilesystemFriendlyName() { return scenario.getName(); } <START> }, Optional.of(RuntimeException.class)); <END> } container.stop(); }</code><technical_language>this Optional<Throwable> Optional<Class></technical_language>

Target:
public void afterScenario(Scenario scenario) { container.afterTest(new TestDescription() { @Override public String getTestId() { return scenario.getId(); } @Override public String getFilesystemFriendlyName() { return scenario.getName(); } }, Optional.of(scenario).filter(Scenario::isFailed).map(__ -> new RuntimeException())); }
Source:
<code>Request build() throws UnsupportedEncodingException { if (multipartBody != null && multipartBody.getPartCount() == 0) { throw new IllegalStateException("Multipart requests must contain at least one part."); } String apiUrl = this.apiUrl; StringBuilder url = new StringBuilder(apiUrl); if (apiUrl.endsWith("/")) { url.deleteCharAt(url.length() - 1); } url.append(relativeUrl); StringBuilder queryParams = this.queryParams; if (queryParams != null) { url.append(queryParams); } TypedOutput body = this.body; if (body != null) { <START> boolean hasContentType = false; <END> if (headers != null) { for (Header header : headers) { if ("Content-Type".equalsIgnoreCase(header.getName())) { hasContentType = true; break; } } } if (!hasContentType) { addHeader("Content-Type", body.mimeType()); } long length = body.length(); if (length != -1) { addHeader("Content-Length", String.valueOf(length)); } } return new Request(requestMethod, url.toString(), headers, body); }</code><technical_language>Suggestion: Move this block a memoized method RestMethodInfo, cached</technical_language>

Target:
Request build() throws UnsupportedEncodingException { if (multipartBody != null && multipartBody.getPartCount() == 0) { throw new IllegalStateException("Multipart requests must contain at least one part."); } String apiUrl = this.apiUrl; StringBuilder url = new StringBuilder(apiUrl); if (apiUrl.endsWith("/")) { url.deleteCharAt(url.length() - 1); } url.append(relativeUrl); StringBuilder queryParams = this.queryParams; if (queryParams != null) { url.append(queryParams); } TypedOutput body = this.body; if (body != null) { if (!hasContentTypeHeader) { addHeader("Content-Type", body.mimeType()); } long length = body.length(); if (length != -1) { addHeader("Content-Length", String.valueOf(length)); } } return new Request(requestMethod, url.toString(), headers, body); }
Source:
<code>void processRuntimes(String rtLocations, String installLocation, String installerBase, int step) throws IOException { String jarLocation = P2DirectorStarterListener.findPathJar(Unpacker.class); String[] rtl = rtLocations.split(","); handler.nextStep("Processing Supplemental Runtimes", step + 1, 1); installLocation += java.io.File.separator + "runtimes" + java.io.File.separator; Path zipPath = null; java.util.jar.JarFile jar = new java.util.jar.JarFile(jarLocation); JarEntry runtimeEntry = null; for (int i = 0; i < rtl.length; i++) { runtimeEntry = jar.getJarEntry(rtl[i]); if (runtimeEntry != null) { handler.progress(i + 1, "Runtime " + runtimeEntry.getName()); <START> String separator = java.io.File.separator; <END> if (separator.equals("\\")) separator = "/"; String[] rtlComponents = rtl[i].split(separator); File entryFile = new File(installLocation, rtlComponents[0]); entryFile.setLastModified(runtimeEntry.getTime()); entryFile.getParentFile().mkdirs(); InputStream in = new BufferedInputStream(jar.getInputStream(runtimeEntry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile)); byte[] buffer = new byte[BUFFER_SIZE]; for (;;) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); out.close(); in.close(); zipPath = Paths.get(entryFile.getAbsolutePath()); inflateZip(zipPath.toString(), installLocation); Files.delete(zipPath); } } jar.close(); }</code><technical_language>This java String[] rtlComponents = rtl[i].split("/");</technical_language>

Target:
void processRuntimes(String rtLocations, String installLocation, String installerBase, int step) throws IOException { String jarLocation = P2DirectorStarterListener.findPathJar(Unpacker.class); String[] rtl = rtLocations.split(","); handler.nextStep("Processing Supplemental Runtimes", step + 1, 1); installLocation += java.io.File.separator + "runtimes" + java.io.File.separator; Path zipPath = null; java.util.jar.JarFile jar = new java.util.jar.JarFile(jarLocation); JarEntry runtimeEntry = null; for (int i = 0; i < rtl.length; i++) { runtimeEntry = jar.getJarEntry(rtl[i]); if (runtimeEntry != null) { handler.progress(i + 1, "Runtime " + runtimeEntry.getName()); String[] rtlComponents = rtl[i].split("/"); File entryFile = new File(installLocation, rtlComponents[0]); entryFile.setLastModified(runtimeEntry.getTime()); entryFile.getParentFile().mkdirs(); InputStream in = new BufferedInputStream(jar.getInputStream(runtimeEntry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile)); byte[] buffer = new byte[BUFFER_SIZE]; for (;;) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); out.close(); in.close(); zipPath = Paths.get(entryFile.getAbsolutePath()); inflateZip(zipPath.toString(), installLocation); Files.delete(zipPath); } } jar.close(); }
Source:
<code>private String findPdpFromEmailAddress() { <START> return parameterService.getParameterValueAsString(KFSConstants.ParameterNamespaces.PDP, KfsParameterConstants.BATCH_COMPONENT, KFSConstants.FROM_EMAIL_ADDRESS_PARM_NM); <END> }</code><technical_language>This is KFSContstants.ParameterNamespaces.PDP</technical_language>

Target:
private String findPdpFromEmailAddress() { return parameterService.getParameterValueAsString(KFSConstants.CoreModuleNamespaces.PDP, KfsParameterConstants.BATCH_COMPONENT, KFSConstants.FROM_EMAIL_ADDRESS_PARM_NM); }
Source:
<code>private ConsumerRecords<K, V> pollKafkaBroker(PollablePartitionsInfo pollablePartitionsInfo) { doSeekRetriableTopicPartitions(pollablePartitionsInfo.pollableEarliestRetriableOffsets); Set<TopicPartition> pausedPartitions = new HashSet<>(kafkaConsumer.assignment()); pausedPartitions.removeIf(pollablePartitionsInfo.pollablePartitions::contains); try { kafkaConsumer.pause(pausedPartitions); final ConsumerRecords<K, V> consumerRecords = kafkaConsumer.poll(kafkaSpoutConfig.getPollTimeoutMs()); ackRetriableOffsetsIfCompactedAway(pollablePartitionsInfo.pollableEarliestRetriableOffsets, consumerRecords); final int numPolledRecords = consumerRecords.count(); LOG.debug("Polled records from Kafka", numPolledRecords); if (kafkaSpoutConfig.getProcessingGuarantee() == KafkaSpoutConfig.ProcessingGuarantee.AT_MOST_ONCE) { Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = createOffsetsToCommitForConsumedOffsets(kafkaConsumer.assignment()); <START> kafkaConsumer.commitSync(offsetsToCommit); <END> LOG.debug("Committed offsets to Kafka", offsetsToCommit); } return consumerRecords; } finally { kafkaConsumer.resume(pausedPartitions); } }</code><technical_language>createFetchedOffsetsMetadata</technical_language>

Target:
private ConsumerRecords<K, V> pollKafkaBroker(PollablePartitionsInfo pollablePartitionsInfo) { doSeekRetriableTopicPartitions(pollablePartitionsInfo.pollableEarliestRetriableOffsets); Set<TopicPartition> pausedPartitions = new HashSet<>(kafkaConsumer.assignment()); pausedPartitions.removeIf(pollablePartitionsInfo.pollablePartitions::contains); try { kafkaConsumer.pause(pausedPartitions); final ConsumerRecords<K, V> consumerRecords = kafkaConsumer.poll(kafkaSpoutConfig.getPollTimeoutMs()); ackRetriableOffsetsIfCompactedAway(pollablePartitionsInfo.pollableEarliestRetriableOffsets, consumerRecords); final int numPolledRecords = consumerRecords.count(); LOG.debug("Polled records from Kafka", numPolledRecords); if (kafkaSpoutConfig.getProcessingGuarantee() == KafkaSpoutConfig.ProcessingGuarantee.AT_MOST_ONCE) { Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = createFetchedOffsetsMetadata(kafkaConsumer.assignment()); kafkaConsumer.commitSync(offsetsToCommit); LOG.debug("Committed offsets to Kafka", offsetsToCommit); } return consumerRecords; } finally { kafkaConsumer.resume(pausedPartitions); } }
Source:
<code>public void testWhenAnyResultFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override <START> public Task<?> call() throws Exception { <END> final ArrayList<Task<Void>> tasks = new ArrayList<Task<Void>>(); final Task<Void> firstToCompleteSuccess = Task.callInBackground(new Callable<Void>() { @Override public Void call() throws Exception { Thread.sleep(50); return null; } }); tasks.addAll(launchTasksWithRandomCompletions(10)); tasks.add(firstToCompleteSuccess); return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Void>, Object>() { @Override public Object then(Task<Task<Void>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(task.getResult(), firstToCompleteSuccess); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertFalse(task.getResult().isFaulted()); return null; } }); } }); }</code><technical_language>a non-wildcard result whenAnyResult</technical_language>

Target:
public void testWhenAnyResultFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<Integer>> tasks = new ArrayList<>(); final Task<Integer> firstToCompleteSuccess = Task.callInBackground(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(50); return 10; } }); tasks.addAll(launchTasksWithRandomCompletions(5)); tasks.add(firstToCompleteSuccess); tasks.addAll(launchTasksWithRandomCompletions(5)); return Task.whenAnyResult(tasks).continueWith(new Continuation<Task<Integer>, Void>() { @Override public Void then(Task<Task<Integer>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(firstToCompleteSuccess, task.getResult()); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertFalse(task.getResult().isFaulted()); assertEquals(10, (int)task.getResult().getResult()); return null; } }); } }); }
Source:
<code>protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { <START> from("netty4:udp://localhost:{{port}}?option."+ ChannelOption.RCVBUF_ALLOCATOR.name() +"=#"+ChannelOption.RCVBUF_ALLOCATOR.name()) <END> .to("mock:result"); } }; }</code><technical_language>Please do change existing unit test, create a new test</technical_language>

Target:
protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("netty4:udp://localhost:{{port}}?receiveBufferSizePredictor=2048&sync=false") .to("mock:result"); } }; }
Source:
<code>public void onLoad(String mixinPackage) { boolean isOptifineCoreModLoaded = true; try { <START> Class.forName("optifine.OptiFineForgeTweaker"); <END> } catch (ClassNotFoundException e) { isOptifineCoreModLoaded = false; } modDependencyConditions.defaultReturnValue(true); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderChunk_NoOptifine", !isOptifineCoreModLoaded); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderChunk_OptifineSpecific", isOptifineCoreModLoaded); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobal_BiggerRenderChunk_NoOptifine", !isOptifineCoreModLoaded); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobal_BiggerRenderChunk_OptifineSpecific", isOptifineCoreModLoaded); File folder = new File(".", "config"); folder.mkdirs(); File configFile = new File(folder, "cubicchunks_mixin_config.json"); LOGGER.info("Loading configuration file " + configFile.getAbsolutePath()); try { if (!configFile.exists()) this.writeConfigToJson(configFile); this.readConfigFromJson(configFile); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>is a detect if optifine is loaded. I forge some optifine-detection code works</technical_language>

Target:
public void onLoad(String mixinPackage) { boolean isOptifineCoreModLoaded = true; try { Class.forName("optifine.OptiFineForgeTweaker"); } catch (ClassNotFoundException e) { isOptifineCoreModLoaded = false; } modDependencyConditions.defaultReturnValue(true); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderChunk_NoOptifine", !isOptifineCoreModLoaded); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderChunk_OptifineSpecific", isOptifineCoreModLoaded); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobal_BiggerRenderChunk_OptifineSpecific", isOptifineCoreModLoaded); File folder = new File(".", "config"); folder.mkdirs(); File configFile = new File(folder, "cubicchunks_mixin_config.json"); LOGGER.info("Loading configuration file " + configFile.getAbsolutePath()); try { if (!configFile.exists()) this.writeConfigToJson(configFile); this.readConfigFromJson(configFile); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code><START> private StringBuffer getPathFromDirInternal(@Nonnull CachedParentVDir baseDir, <END> @Nonnull CachedParentVDir currentDir) { if (baseDir == currentDir) { return new StringBuffer(); } CachedParentVDir currentParent = currentDir.getParent(); assert currentParent != null; return getPathFromDirInternal(baseDir, currentParent).append(currentDir.getName()).append('/'); }</code><technical_language>similar DirectFS, share code</technical_language>

Target:
private static StringBuffer getPathFromDirInternal(@Nonnull CachedParentVDir baseDir, @Nonnull CachedParentVDir currentDir) { if (baseDir == currentDir) { return new StringBuffer(); } CachedParentVDir currentParent = currentDir.getParent(); assert currentParent != null; return getPathFromDirInternal(baseDir, currentParent).append(currentDir.getName()).append('/'); }
Source:
<code>private LoginService initLoginService() { if (authenticationControlType == null) { final String[] splittedProperty = ServerConfiguration .getSplittedProperty(ServerConfiguration.AUTHENTICATION_POLICY); authenticationControlType = ESAuthenticationControlType.valueOf(splittedProperty[0]); } final String delayString = ServerConfiguration.getProperties().getProperty( ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS, ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS_DEFAULT); int delay; try { delay = Integer.valueOf(delayString); } catch (final NumberFormatException ex) { ModelUtil.logWarning(MessageFormat.format(Messages.AccessControl_IllegalDelayValueInProperties, ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS), ex); <START> delay = -1; <END> } return new LoginService( authenticationControlType, sessions, orgUnitProvider, getOrgUnitResolverServive(), delay); }</code><technical_language>1 is good here. tage default imho better, throw a FatalServerException</technical_language>

Target:
private LoginService initLoginService() throws FatalESException { if (authenticationControlType == null) { final String[] splittedProperty = ServerConfiguration .getSplittedProperty(ServerConfiguration.AUTHENTICATION_POLICY); authenticationControlType = ESAuthenticationControlType.valueOf(splittedProperty[0]); } final String delayString = ServerConfiguration.getProperties().getProperty( ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS, ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS_DEFAULT); int delay; try { delay = Integer.valueOf(delayString); } catch (final NumberFormatException ex) { throw new FatalESException(MessageFormat.format(Messages.AccessControl_IllegalDelayValueInProperties, ServerConfiguration.AUTHENTICATION_LOGIN_DELAY_FAILED_REQUESTS), ex); } return new LoginService( authenticationControlType, sessions, orgUnitProvider, getOrgUnitResolverServive(), delay); }
Source:
<code>public String encode(CharSequence rawPassword) { <START> return new String(Hex.encode(SCrypt.generate(Utf8.encode(rawPassword), saltBytes, cpuCost, memoryCost, parallelization, saltBytes.length))); <END> }</code><technical_language>Ideally encoding parameters in encoded (along salt mentioned above). This allows for increasing strength computing resources get better</technical_language>

Target:
public String encode(CharSequence rawPassword) { return digest(rawPassword, saltGenerator.generateKey()); }
Source:
<code><START> public void checkSwitchProjectsWhenContributeIsFalse() { <END> openContributeTab(); setStateContributeChecboxAndCloseForm(true); projectExplorer.waitAndSelectItem(FIRST_PROJECT_NAME); pullRequestPanel.waitOpenPanel(); openContributeTab(); setStateContributeChecboxAndCloseForm(false); projectExplorer.waitAndSelectItem(FIRST_PROJECT_NAME); pullRequestPanel.waitRepoUrl(firstProjectUrl); pullRequestPanel.waitProjectName(FIRST_PROJECT_NAME); projectExplorer.waitAndSelectItem(SECOND_PROJECT_NAME); pullRequestPanel.waitRepoUrl(secondProjectUrl); pullRequestPanel.waitProjectName(SECOND_PROJECT_NAME); projectExplorer.waitAndSelectItem(THIRD_PROJECT_NAME); pullRequestPanel.waitTetxNotVcsProject(EXP_TEXT_NOT_VCS); }</code><technical_language>"Contribute is false" mean</technical_language>

Target:
public void checkSwitchProjectsWhenContributeIsFalse() { openContributeTab(); setStateContributeChecboxAndCloseForm(true); projectExplorer.waitAndSelectItem(FIRST_PROJECT_NAME); pullRequestPanel.waitOpenPanel(); openContributeTab(); setStateContributeChecboxAndCloseForm(false); projectExplorer.waitAndSelectItem(FIRST_PROJECT_NAME); pullRequestPanel.waitRepoUrl(firstProjectUrl); pullRequestPanel.waitProjectName(FIRST_PROJECT_NAME); projectExplorer.waitAndSelectItem(SECOND_PROJECT_NAME); pullRequestPanel.waitRepoUrl(secondProjectUrl); pullRequestPanel.waitProjectName(SECOND_PROJECT_NAME); projectExplorer.waitAndSelectItem(THIRD_PROJECT_NAME); pullRequestPanel.waitTextNotVcsProject(EXP_TEXT_NOT_VCS); }
Source:
<code>public void init(Project.NameKey project, ReceivePack rp) { QuotaSection quotaSection = quotaFinder.firstMatching(project); if (quotaSection == null) { return; } Long maxRepoSize = quotaSection.getMaxRepoSize(); if (maxRepoSize == null) { return; } try { long maxPackSize = Math.max(0, maxRepoSize - getDiskUsage(project)); rp.setMaxPackSizeLimit(maxPackSize); } catch (IOException e) { <START> log.warn("Couldn't setMaxPackSizeLimit", e); <END> } }</code><technical_language>include project name warning</technical_language>

Target:
public void init(Project.NameKey project, ReceivePack rp) { QuotaSection quotaSection = quotaFinder.firstMatching(project); if (quotaSection == null) { return; } Long maxRepoSize = quotaSection.getMaxRepoSize(); if (maxRepoSize == null) { return; } try { long maxPackSize = Math.max(0, maxRepoSize - getDiskUsage(project)); rp.setMaxPackSizeLimit(maxPackSize); } catch (IOException e) { log.warn("Couldn't setMaxPackSizeLimit on receive-pack for " + project.get(), e); } }
Source:
<code>public static <T> long count( Iterable<T> iterable, Predicate<T> filter ) { <START> try ( ResourceIterator<T> iterator = Iterators.asResourceIterator( iterable.iterator() ) ) <END> { return Iterators.count( iterator, filter ); } }</code><technical_language>Instead of wrapping in a resource iterator, is potentially unnecessary object instantiation, do usual check of Resource in finally</technical_language>

Target:
public static <T> long count( Iterable<T> iterable, Predicate<T> filter ) { Iterator<T> iterator = iterable.iterator(); try { return Iterators.count( iterator, filter ); } finally { if ( iterator instanceof ResourceIterator ) { ((ResourceIterator) iterator).close(); } } }
Source:
<code>public void validate(PasswordChangeDTO passwordChangeDTO) throws PasswordOldMatchValidationException { Assert.notNull(passwordChangeDTO); Assert.notNull(passwordChangeDTO.getOldPassword()); UserDetails userDetails = null; try { userDetails = authenticationService.getCurrentUserDetails(); } catch (UserNotLoggedInException e) { <START> e.printStackTrace(); <END> throw new PasswordOldMatchValidationException(); } if (!(bCryptPasswordEncoder.matches(passwordChangeDTO.getOldPassword(), userDetails.getPassword()))) { throw new PasswordOldMatchValidationException(); } }</code><technical_language>logger instead of printing System.err</technical_language>

Target:
public void validate(PasswordChangeDTO passwordChangeDTO) throws PasswordOldMatchValidationException { Assert.notNull(passwordChangeDTO); Assert.notNull(passwordChangeDTO.getOldPassword()); UserDetails userDetails; try { userDetails = authenticationService.getCurrentUserDetails(); } catch (UserNotLoggedInException e) { log.error("User is not logged in: ", e); throw new PasswordOldMatchValidationException(); } if (!(bCryptPasswordEncoder.matches(passwordChangeDTO.getOldPassword(), userDetails.getPassword()))) { throw new PasswordOldMatchValidationException(); } }
Source:
<code>public void startServer() throws RemotingException { port = NetUtils.getAvailablePort(); ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Data.class, (channel, msg) -> { <START> for (int i = 0; i < 10000; i++) { <END> System.currentTimeMillis(); } return new StringMessage("hello world"); }); exchangeServer = Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); }</code><technical_language>I this is existing code. thinking purpose for this code? this is necessary for this unit test</technical_language>

Target:
public void startServer() throws RemotingException { port = NetUtils.getAvailablePort(); ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Data.class, (channel, msg) -> new StringMessage("hello world")); exchangeServer = Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); }
Source:
<code>public MessagePanel(final ChangeMessage msg) { SafeHtml message = new SafeHtmlBuilder().append(msg.getMessage().trim()); <START> message.setFindReplaceList(Gerrit.getConfig().getCommentLinks()); <END> final Widget l = message.wikify().runFindReplaceList().toBlockWidget(); l.setStyleName("gerrit-ChangeMessage-Message"); initWidget(l); }</code><technical_language>MDC[1] $& expands entire matched string. link compute replacement string be: repl = "<a href=\"" + link + "\">$&</a>" [1] <LINK_0> other option is wrap match in parens increment $n reference in link one, $1 anchor for entire expression. do server side of GerritConfigProvider, needs done easier perform full power of Java's String java.util.regex you</technical_language>

Target:
public MessagePanel(final ChangeMessage msg) { final Widget l = new SafeHtmlBuilder().append(msg.getMessage().trim()).wikify() .replaceAll(Gerrit.getConfig().getCommentLinks()).toBlockWidget(); l.setStyleName("gerrit-ChangeMessage-Message"); initWidget(l); }
Source:
<code>private void executeCommand(String command) { ServiceReference ref = hostBundle.getServiceReference( SHELL_SERVICE_REFERENCE); if (ref == null) <START> { <END> LOGGER.error(I18N.tr("No shell service is available.")); return; } ShellService shell = (ShellService) hostBundle.getService(ref); try { try { outputField.getDocument().insertString(outputField.getDocument().getLength(), "-> "+command+"\n", null); } catch(BadLocationException ex) { LOGGER.debug(ex.getLocalizedMessage(), ex); } try { shell.executeCommand(command, new PrintStream(info), new PrintStream(error)); } catch (Exception ex) { LOGGER.error(ex.getLocalizedMessage(),ex); } finally { try { info.flush(); error.flush(); outputField.setCaretPosition(outputField.getDocument().getLength()); } catch(IOException ex) { LOGGER.error(ex.getLocalizedMessage(),ex); } } } finally { hostBundle.ungetService(ref); } }</code><technical_language>Please put brackets line of if. :-)</technical_language>

Target:
private void executeCommand(String command) { ServiceReference ref = hostBundle.getServiceReference( SHELL_SERVICE_REFERENCE); if (ref == null) { LOGGER.error(I18N.tr("No shell service is available.")); return; } ShellService shell = (ShellService) hostBundle.getService(ref); try { try { outputField.getDocument().insertString(outputField.getDocument().getLength(), "osgi> "+command+"\n", null); } catch(BadLocationException ex) { LOGGER.debug(ex.getLocalizedMessage(), ex); } try { shell.executeCommand(command, new PrintStream(info), new PrintStream(error)); } catch (Exception ex) { LOGGER.error(ex.getLocalizedMessage(),ex); } finally { try { info.flush(); error.flush(); outputField.setCaretPosition(outputField.getDocument().getLength()); } catch(IOException ex) { LOGGER.error(ex.getLocalizedMessage(),ex); } } } finally { hostBundle.ungetService(ref); } }
Source:
<code>private RexNode simplifyIs2(SqlKind kind, RexNode a, RexUnknownAs unknownAs) { final RexNode simplified; switch (kind) { case IS_NULL: simplified = simplifyIsNull(a); if (simplified != null) { return simplified; } break; case IS_NOT_NULL: simplified = simplifyIsNotNull(a); if (simplified != null) { return simplified; } break; case IS_TRUE: case IS_NOT_FALSE: if (!a.getType().isNullable()) { return simplify(a, unknownAs); } else { RexNode newSub = <START> simplify(a, kind == SqlKind.IS_TRUE ? RexUnknownAs.FALSE : TRUE); <END> if (newSub == a) { return null; } return rexBuilder.makeCall(RexUtil.op(kind), ImmutableList.of(newSub)); } case IS_FALSE: case IS_NOT_TRUE: if (!a.getType().isNullable()) { return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs); } break; } switch (a.getKind()) { case NOT: final SqlOperator notKind = RexUtil.op(kind.negateNullSafe()); final RexNode arg = ((RexCall) a).operands.get(0); return simplify(rexBuilder.makeCall(notKind, arg), UNKNOWN); } final RexNode a2 = simplify(a, UNKNOWN); if (a != a2) { return rexBuilder.makeCall(RexUtil.op(kind), ImmutableList.of(a2)); } return null; }</code><technical_language>RexUnknownAs.TRUE code more readable</technical_language>

Target:
private RexNode simplifyIs2(SqlKind kind, RexNode a, RexUnknownAs unknownAs) { final RexNode simplified; switch (kind) { case IS_NULL: simplified = simplifyIsNull(a); if (simplified != null) { return simplified; } break; case IS_NOT_NULL: simplified = simplifyIsNotNull(a); if (simplified != null) { return simplified; } break; case IS_TRUE: case IS_NOT_FALSE: if (!a.getType().isNullable()) { return simplify(a, unknownAs); } else { RexNode newSub = simplify(a, kind == SqlKind.IS_TRUE ? RexUnknownAs.FALSE : RexUnknownAs.TRUE); if (newSub == a) { return null; } return rexBuilder.makeCall(RexUtil.op(kind), ImmutableList.of(newSub)); } case IS_FALSE: case IS_NOT_TRUE: if (!a.getType().isNullable()) { return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs); } break; } switch (a.getKind()) { case NOT: final SqlOperator notKind = RexUtil.op(kind.negateNullSafe()); final RexNode arg = ((RexCall) a).operands.get(0); return simplify(rexBuilder.makeCall(notKind, arg), UNKNOWN); } final RexNode a2 = simplify(a, UNKNOWN); if (a != a2) { return rexBuilder.makeCall(RexUtil.op(kind), ImmutableList.of(a2)); } return null; }