auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
int foo(int y) { MathOperation addition = (x) -> x + x; MathOperation addition2 = (x) -> { return x + x; }; MathOperation addition3 = x -> x + x; MathOperation2 addition4 = (a, b) -> a + b; return y; }

Target:
int foo(int y) { MathOperation case1 = (x) -> x + x; MathOperation case2 = (x) -> { return x + x; }; MathOperation case3 = (int x) -> x + x; MathOperation case4 = x -> x + x; MathOperation2 case5 = (a, b) -> a + b; MathOperation2 case6 = (int a, int b) -> a + b; MathOperation2 case7 = (int a, int b) -> { return a + b; }; Objects.requireNonNull(null, () -> "message"); call((x) -> x + x); new HashSet<Integer>().stream().filter((filter) -> filter > 0); return y; }
Source:
void runBenchmark() { try { long start, time; start = JVM.monotonicTimeMillis(); String privateDir = System.getProperty("fileconn.dir.private"); Random random = new Random(); String filename = new javax.bluetooth.UUID(java.lang.Math.abs(random.nextInt())).toString(); FileConnection file = (FileConnection)Connector.open(privateDir + filename); System.out.println("Writing to file " + privateDir + filename); file.create(); SecureRandom rnd = SecureRandom.getInstance(SecureRandom.ALG_SECURE_RANDOM); OutputStream out = file.openOutputStream(); byte[] b = new byte[1024]; for (int i = 0; i < 1000; i++) { rnd.nextBytes(b, 0, 1024); out.write(b); } out.close(); time = JVM.monotonicTimeMillis() - start; System.out.println("FileConnection.write time: " + time); } catch (Exception e) { System.out.println("Unexpected exception: " + e); e.printStackTrace(); } }

Target:
void runBenchmark() { try { long start; String privateDir = System.getProperty("fileconn.dir.private"); String filename = String.valueOf(System.currentTimeMillis()); start = JVM.monotonicTimeMillis(); FileConnection file = (FileConnection)Connector.open(privateDir + filename); System.out.println("Writing to file " + privateDir + filename); file.create(); System.out.println("FileConnection.open/create time: " + (JVM.monotonicTimeMillis() - start)); start = JVM.monotonicTimeMillis(); OutputStream out = file.openOutputStream(); System.out.println("FileConnection.openOutputStream time: " + (JVM.monotonicTimeMillis() - start)); start = JVM.monotonicTimeMillis(); for (int i = 0; i < 1000; i++) { out.write(b); } System.out.println("OutputStream.write time: " + (JVM.monotonicTimeMillis() - start)); out.close(); file.close(); } catch (Exception e) { System.out.println("Unexpected exception: " + e); e.printStackTrace(); } }
Source:
public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Ds3Element)) { return false; } final Ds3Element element = (Ds3Element) obj; if (this.getName().equals(element.getName()) && this.getType().equals(element.getType()) && this.getComponentType().equals(element.getComponentType())) { return true; } return false; }

Target:
public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Ds3Element)) { return false; } final Ds3Element element = (Ds3Element) obj; return this.getName().equals(element.getName()) && this.getType().equals(element.getType()) && this.getComponentType().equals(element.getComponentType()); }
Source:
public String getUsername(URI uri) throws ClientConfigException { final CallbackHandler callbackHandler = AUTH_CONTEXT_CLIENT.getCallbackHandler(AUTH_CONTEXT_CLIENT.getAuthenticationConfiguration(uri, authenticationContext)); NameCallback nameCallback = new NameCallback("user name"); try { callbackHandler.handle(new Callback[]{nameCallback}); return nameCallback.getName(); } catch (IOException | UnsupportedCallbackException e) { throw new ClientConfigException("Name callback handling was unsuccessful"); } }

Target:
public String getUsername(URI uri) throws ClientConfigException { final CallbackHandler callbackHandler = AUTH_CONTEXT_CLIENT.getCallbackHandler(AUTH_CONTEXT_CLIENT.getAuthenticationConfiguration(uri, AuthenticationContext.captureCurrent())); NameCallback nameCallback = new NameCallback("user name"); try { callbackHandler.handle(new Callback[]{nameCallback}); return nameCallback.getName(); } catch (IOException | UnsupportedCallbackException e) { throw new ClientConfigException(ElytronMessages.log.nameCallbackHandlingWasUnsuccessful()); } }
Source:
private boolean validateSurl(String surlString) { TSURL surl; if(!SurlValidator.valid(surlString)){ validationResponse = Response.status(400).entity("Invalid surl\n\n").build(); return false; } try { surl = TSURL.makeFromStringValidate(surlString); } catch (InvalidTSURLAttributesException e) { validationResponse = Response.status(400).build(); return false; } try { stori = NamespaceDirector.getNamespace().resolveStoRIbySURL(surl); } catch (UnapprochableSurlException e) { log.warn("Unable to build a stori for surl " + surl + " UnapprochableSurlException: " + e.getMessage()); return false; } return true; }

Target:
private boolean validateSurl(String surlString) { TSURL surl; if(!SurlValidator.valid(surlString)){ validationResponse = Response.status(400).entity("Invalid surl: " + surlString + "\n\n").build(); return false; } try { surl = TSURL.makeFromStringValidate(surlString); } catch (InvalidTSURLAttributesException e) { validationResponse = Response.status(400).build(); return false; } try { stori = NamespaceDirector.getNamespace().resolveStoRIbySURL(surl); } catch (UnapprochableSurlException e) { log.warn("Unable to build a stori for surl " + surl + " UnapprochableSurlException: " + e.getMessage()); return false; } return true; }
Source:
protected void startScan() { removeOlderResults(getTimestampOfLastScan(), null); logger.trace("Starting Discovery"); List<String> networkIPs = getScannableIPs(); scannedIPcount = 0; networkIPs.add(0, "127.0.0.1"); final int totalScans = networkIPs.size() * 2; MqttBrokerConnection o[]; try { o = createTestConnections(networkIPs); } catch (ConfigurationException e) { logger.debug("Could not create MqttBrokerConnection object", e); stopScan(); return; } for (MqttBrokerConnection c : o) { scheduler.execute(() -> { Thread.currentThread().setName("Discovery thread " + c.getHost() + ":" + String.valueOf(c.getPort())); try { scanTarget(c); } catch (ConfigurationException | MqttException | InterruptedException e) { logger.trace("Scan of failed", c.getHost() + ":" + String.valueOf(c.getPort())); } stopScanIfAllScanned(totalScans); }); } }

Target:
protected void startScan() { removeOlderResults(getTimestampOfLastScan(), null); logger.trace("Starting Discovery"); List<String> networkIPs = getScannableIPs(); scannedIPcount = 0; networkIPs.add(0, "127.0.0.1"); final int totalScans = networkIPs.size() * 2; MqttBrokerConnection o[]; try { o = createTestConnections(networkIPs); } catch (ConfigurationException e) { logger.debug("Could not create MqttBrokerConnection object", e); stopScan(); return; } for (MqttBrokerConnection c : o) { scheduler.execute(() -> { try { scanTarget(c); } catch (ConfigurationException | MqttException | InterruptedException e) { logger.trace("Scan of {}:{} failed", c.getHost(), String.valueOf(c.getPort())); } stopScanIfAllScanned(totalScans); }); } }
Source:
public void setupLibraryBreadCrumbsForImportProjects(final String repositoryUrl) { breadcrumbs.clearBreadcrumbs(LibraryPlaces.LIBRARY_PERSPECTIVE); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, translationUtils.getOrganizationalUnitAliasInPlural(), () -> goToOrganizationalUnits()); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, projectContext.getActiveOrganizationalUnit() .orElseThrow(() -> new IllegalStateException("Cannot create library breadcrumb without active organizational unit.")) .getName(), () -> goToLibrary()); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, ts.getTranslation(LibraryConstants.ImportProjects), () -> goToImportProjects(repositoryUrl)); }

Target:
public void setupLibraryBreadCrumbsForImportProjects(final String repositoryUrl) { breadcrumbs.clearBreadcrumbs(LibraryPlaces.LIBRARY_PERSPECTIVE); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, translationUtils.getOrganizationalUnitAliasInPlural(), () -> goToOrganizationalUnits()); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, projectContext.getActiveOrganizationalUnit() .orElseThrow(() -> new IllegalStateException("Cannot create library breadcrumb without active space.")) .getName(), () -> goToLibrary()); breadcrumbs.addBreadCrumb(LibraryPlaces.LIBRARY_PERSPECTIVE, ts.getTranslation(LibraryConstants.ImportProjects), () -> goToImportProjects(repositoryUrl)); }
Source:
public String getAdvertiseNonce() { return CAPABILITY_PUSH_CERT + "=" + nonceGenerator.createNonce(seed, dirPath, TimeUnit.MILLISECONDS .toSeconds(System.currentTimeMillis())); }

Target:
public String getAdvertiseNonce() { sentNonce = nonceGenerator.createNonce(seed, db, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); return CAPABILITY_PUSH_CERT + "=" + sentNonce; }
Source:
public Iterable<ProjectState> parents() { return new Iterable<ProjectState>() { @Override public Iterator<ProjectState> iterator() { Iterator<ProjectState> i = tree().iterator(); Preconditions.checkState( i.hasNext() && i.next() == ProjectState.this, "skip starting ProjectState"); return i; } }; }

Target:
public Iterable<ProjectState> parents() { return Iterables.skip(tree(), 1); }
Source:
public void managementClientWithProxy() throws InterruptedException, ServiceBusException { String proxyHostName = "127.0.0.1"; int proxyPort = 8888; final ProxySelector systemDefaultSelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (uri != null && uri.getHost() != null ) { List<Proxy> proxies = new LinkedList<>(); proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort))); return proxies; } return systemDefaultSelector.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe){ if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } systemDefaultSelector.connectFailed(uri, sa, ioe); } }); URI namespaceEndpointURI = TestUtils.getNamespaceEndpointURI(); ClientSettings managementClientSettings = TestUtils.getManagementClientSettings(); ManagementClient managementClient = new ManagementClient(namespaceEndpointURI, managementClientSettings); String queueName = "proxy" + UUID.randomUUID().toString().substring(0, 8); QueueDescription q = new QueueDescription(queueName); QueueDescription qCreated = managementClient.createQueue(q); Assert.assertEquals(q, qCreated); }

Target:
public void managementClientWithProxy() throws Exception { String proxyHostName = "127.0.0.1"; int proxyPort = 8888; final ProxySelector systemDefaultSelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { if (uri != null && uri.getHost() != null ) { List<Proxy> proxies = new LinkedList<>(); proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort))); return proxies; } return systemDefaultSelector.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe){ if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } systemDefaultSelector.connectFailed(uri, sa, ioe); } }); URI namespaceEndpointURI = TestUtils.getNamespaceEndpointURI(); ClientSettings managementClientSettings = TestUtils.getManagementClientSettings(); ManagementClient managementClient = new ManagementClient(namespaceEndpointURI, managementClientSettings); String queueName = "test" + UUID.randomUUID().toString().substring(0, 8); QueueDescription q = new QueueDescription(queueName); QueueDescription qCreated = managementClient.createQueue(q); Assert.assertEquals(q, qCreated); String connectionString = TestUtils.getNamespaceConnectionString(); ConnectionStringBuilder connStrBuilder = new ConnectionStringBuilder(connectionString, queueName); connStrBuilder.setTransportType(TransportType.AMQP_WEB_SOCKETS); QueueClient sendClient = new QueueClient(connStrBuilder, ReceiveMode.PEEKLOCK); Message message = new Message("hello"); sendClient.sendAsync(message).thenRunAsync(() -> sendClient.closeAsync()); waitForEnter(10); }
Source:
private static Authorizer getAuthorizer(TimelockAuthConfiguration authConfiguration) { Map<AuthenticatedClient, Privileges> privilegesMap = authConfiguration.privileges().stream() .collect(Collectors.toMap(p -> AuthenticatedClient.create(p.id()), PrivilegesConfiguration::privileges)); return SimpleAuthorizer.of(privilegesMap, AuthRequirement.PRIVILEGE_BASED); }

Target:
private static Authorizer getAuthorizer(TimelockAuthConfiguration authConfiguration) { Map<ClientId, Privileges> privilegesMap = authConfiguration.privileges().stream() .collect(Collectors.toMap(PrivilegesConfiguration::clientId, PrivilegesConfiguration::privileges)); return SimpleAuthorizer.of(privilegesMap, AUTH_REQUIREMENT); }
Source:
private void propagatePartitionErrorToPrestoException(String databaseName, String tableName, List<PartitionError> partitionErrors) { if (partitionErrors != null && !partitionErrors.isEmpty()) { ErrorDetail errorDetail = partitionErrors.get(0).getErrorDetail(); String glueExceptionCode = errorDetail.getErrorCode(); switch (glueExceptionCode) { case "AlreadyExistsException": throw new PrestoException(StandardErrorCode.ALREADY_EXISTS, errorDetail.getErrorMessage()); case "EntityNotFoundException": throw new TableNotFoundException(new SchemaTableName(databaseName, tableName), errorDetail.getErrorMessage()); default: throw new PrestoException(HIVE_METASTORE_ERROR, errorDetail.getErrorCode() + ": " + errorDetail.getErrorMessage()); } } }

Target:
private void propagatePartitionErrorToPrestoException(String databaseName, String tableName, List<PartitionError> partitionErrors) { if (partitionErrors != null && !partitionErrors.isEmpty()) { ErrorDetail errorDetail = partitionErrors.get(0).getErrorDetail(); String glueExceptionCode = errorDetail.getErrorCode(); switch (glueExceptionCode) { case "AlreadyExistsException": throw new PrestoException(ALREADY_EXISTS, errorDetail.getErrorMessage()); case "EntityNotFoundException": throw new TableNotFoundException(new SchemaTableName(databaseName, tableName), errorDetail.getErrorMessage()); default: throw new PrestoException(HIVE_METASTORE_ERROR, errorDetail.getErrorCode() + ": " + errorDetail.getErrorMessage()); } } }
Source:
public String getBranchPath(ServiceProvider context) { if (branchPath == null) { CodeSystemVersionSearchRequestBuilder versionSearch = CodeSystemRequests.prepareSearchCodeSystemVersion() .one() .filterByCodeSystemShortName(codeSystem.getShortName()); if (uri.isHead()) { branchPath = codeSystem.getBranchPath(); } else { if (uri.isLatest()) { versionSearch.sortBy(SearchResourceRequest.SortField.descending(CodeSystemVersionEntry.Fields.EFFECTIVE_DATE)); } else { versionSearch.filterByVersionId(uri.getPath()); } branchPath = versionSearch .build(codeSystem.getRepositoryUuid()) .getRequest() .execute(context) .stream() .findFirst() .map(CodeSystemVersionEntry::getPath) .orElse(codeSystem.getRelativeBranchPath(uri.getPath())); } } return branchPath; }

Target:
public String getBranchPath(ServiceProvider context) { if (branchPath == null) { if (uri.isHead()) { branchPath = codeSystem.getBranchPath(); } else { CodeSystemVersionSearchRequestBuilder versionSearch = CodeSystemRequests.prepareSearchCodeSystemVersion() .one() .filterByCodeSystemShortName(codeSystem.getShortName()); if (uri.isLatest()) { versionSearch.sortBy(SearchResourceRequest.SortField.descending(CodeSystemVersionEntry.Fields.EFFECTIVE_DATE)); } else { versionSearch.filterByVersionId(uri.getPath()); } branchPath = versionSearch .build(codeSystem.getRepositoryUuid()) .getRequest() .execute(context) .stream() .findFirst() .map(CodeSystemVersionEntry::getPath) .orElse(codeSystem.getRelativeBranchPath(uri.getPath())); } } return branchPath; }
Source:
public void savePlannedVisitDates(String subjectId, LocalDate primeVaccinationDate) { Subject subject = subjectDataService.findSubjectBySubjectId(subjectId); validateDate(subjectId, primeVaccinationDate); if (subject == null) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s not found", subjectId)); } if (subject.getVisits() == null || subject.getVisits().isEmpty()) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s has no Visits", subjectId)); } if (subject.getPrimerVaccinationDate() != null) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s has been vaccinated", subjectId)); } visitBookingDetailsService.createOrUpdate(calculatePlannedDates(subject.getVisits(), primeVaccinationDate).values()); }

Target:
public void savePlannedVisitDates(String subjectId, LocalDate primeVaccinationDate) { Subject subject = subjectDataService.findSubjectBySubjectId(subjectId); if (subject == null) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s not found", subjectId)); } if (subject.getVisits() == null || subject.getVisits().isEmpty()) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s has no Visits", subjectId)); } if (subject.getPrimerVaccinationDate() != null) { throw new VisitScheduleException(String.format("Cannot save Planned Dates, because Participant with Id: %s has been vaccinated", subjectId)); } visitBookingDetailsService.createOrUpdate(calculatePlannedDates(subject.getVisits(), primeVaccinationDate).values()); }
Source:
private SQLException receiveErrorResponse() throws IOException { int elen = pgStream.receiveInteger4(); EncodingPredictor.DecodeResult totalMessage = pgStream.receiveErrorString(elen - 4); ServerErrorMessage errorMsg = new ServerErrorMessage(totalMessage); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " <=BE ErrorMessage({0})", errorMsg.toString()); } PSQLException error; if (errorMsg.getMessage() != null && errorMsg.getMessage().endsWith(COPY_ERROR_MESSAGE)) { error = new CopyNotSupportedException(errorMsg); } else { error = new PSQLException(errorMsg); } if (transactionFailCause == null) { transactionFailCause = error; } else { error.initCause(transactionFailCause); } return error; }

Target:
private SQLException receiveErrorResponse() throws IOException { int elen = pgStream.receiveInteger4(); assert elen > 4 : "Error response length must be greater than 4"; EncodingPredictor.DecodeResult totalMessage = pgStream.receiveErrorString(elen - 4); ServerErrorMessage errorMsg = new ServerErrorMessage(totalMessage); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " <=BE ErrorMessage({0})", errorMsg.toString()); } PSQLException error = new PSQLException(errorMsg); if (transactionFailCause == null) { transactionFailCause = error; } else { error.initCause(transactionFailCause); } return error; }
Source:
public String getLoginFromSessionId(@PathParam("sessionId") String sessionId) throws SchedulerRestException, LoginException, NotConnectedRestException { if (sessionId != null && sessionStore.exists(sessionId)) { return sessionStore.get(sessionId).getUserName(); } return ""; }

Target:
public String getLoginFromSessionId(@PathParam("sessionId") String sessionId) throws SchedulerRestException, LoginException, NotConnectedRestException { if (sessionId != null && sessionStore.exists(sessionId)) { return sessionStore.get(sessionId).getUserName(); } throw new NotFoundException("login cannot be found with the session id " + sessionId); }
Source:
public AbstractRecordAndOffset(final SAMRecord record, final int offset, int length, int refPos) { validateIndex(offset, record.getBaseQualities()); if (length > record.getReadLength()) { throw new IllegalArgumentException("Block length cannot be larger than whole read length"); } this.offset = offset; this.record = record; this.length = length; this.refPos = refPos; }

Target:
public AbstractRecordAndOffset(final SAMRecord record, final int offset, int length, int refPos) { this(record, offset); }
Source:
public static boolean isNetworkInSync(VdsNetworkInterface iface, Network network, NetworkQoS qos) { return (network.getMtu() == 0 || iface.getMtu() == network.getMtu()) && Objects.equals(iface.getVlanId(), network.getVlanId()) && iface.isBridged() == network.isVmNetwork() && (Objects.equals(iface.getQos(), qos) || iface.isQosOverridden()); }

Target:
public static boolean isNetworkInSync(VdsNetworkInterface iface, Network network, NetworkQoS qos) { return (network.getMtu() == 0 || iface.getMtu() == network.getMtu()) && Objects.equals(iface.getVlanId(), network.getVlanId()) && iface.isBridged() == network.isVmNetwork() && (isQosInSync(iface, qos) || iface.isQosOverridden()); }
Source:
private void doTaskEnd() { if((this.listenerFailed || this.started) && !this.finished) { this.taskExecution.setEndTime(new Date()); if(this.exitCodeEvent != null) { this.taskExecution.setExitCode(this.exitCodeEvent.getExitCode()); } else if(this.listenerFailed || this.applicationFailedEvent != null){ this.taskExecution.setExitCode(1); } else{ this.taskExecution.setExitCode(0); } if(this.applicationFailedEvent != null) { this.taskExecution.setErrorMessage(stackTraceToString(this.applicationFailedEvent.getException())); } if(this.listenerException != null) { String errorMessage = this.stackTraceToString(this.listenerException); if (StringUtils.hasText(this.taskExecution.getErrorMessage())) { errorMessage = String.format("%s :Task Also threw this Exception: %s", errorMessage, this.taskExecution.getErrorMessage()); } this.taskExecution.setErrorMessage(errorMessage); } if(this.listenerFailed && this.taskExecution.getExitCode() != 0) { setMessages(invokeOnTaskError(this.taskExecution, this.listenerException)); } else if (this.applicationFailedEvent != null && this.taskExecution.getExitCode() != 0) { setMessages(invokeOnTaskError(this.taskExecution, this.applicationFailedEvent.getException())); } setMessages(invokeOnTaskEnd(this.taskExecution)); if(this.listenerFailed) { this.taskExecution.setExitCode(1); } this.taskRepository.completeTaskExecution(this.taskExecution.getExecutionId(), this.taskExecution.getExitCode(), this.taskExecution.getEndTime(), this.taskExecution.getExitMessage(), this.taskExecution.getErrorMessage()); this.finished = true; if(this.taskProperties.getClosecontextEnabled() && this.context.isActive()) { this.context.close(); } } else if(!this.started){ logger.error("An event to end a task has been received for a task that has " + "not yet started."); } }

Target:
private void doTaskEnd() { if((this.listenerFailed || this.started) && !this.finished) { this.taskExecution.setEndTime(new Date()); if(this.applicationFailedEvent != null) { this.taskExecution.setErrorMessage(stackTraceToString(this.applicationFailedEvent.getException())); } this.taskExecution.setExitCode(calcExitStatus()); if (this.applicationFailedEvent != null) { setExitMessage(invokeOnTaskError(this.taskExecution, this.applicationFailedEvent.getException())); } setExitMessage(invokeOnTaskEnd(this.taskExecution)); this.taskRepository.completeTaskExecution(this.taskExecution.getExecutionId(), this.taskExecution.getExitCode(), this.taskExecution.getEndTime(), this.taskExecution.getExitMessage(), this.taskExecution.getErrorMessage()); this.finished = true; if(this.taskProperties.getClosecontextEnabled() && this.context.isActive()) { this.context.close(); } } else if(!this.started){ logger.error("An event to end a task has been received for a task that has " + "not yet started."); } }
Source:
public void shouldRemoveExistingElements() { final Seq<Integer> seq = of(1, 2, 3); assertThat(seq.reject(i -> i == 1)).isEqualTo(of(2, 3)); assertThat(seq.reject(i -> i == 2)).isEqualTo(of(1, 3)); assertThat(seq.reject(i -> i == 3)).isEqualTo(of(1, 2)); assertThat(seq.reject(ignore -> true)).isEmpty(); assertThat(seq.reject(ignore -> false)).isSameAs(seq); }

Target:
public void shouldRemoveExistingElements() { final Seq<Integer> seq = of(1, 2, 3); assertThat(seq.removeAll(i -> i == 1)).isEqualTo(of(2, 3)); assertThat(seq.removeAll(i -> i == 2)).isEqualTo(of(1, 3)); assertThat(seq.removeAll(i -> i == 3)).isEqualTo(of(1, 2)); assertThat(seq.removeAll(ignore -> true)).isEmpty(); assertThat(seq.removeAll(ignore -> false)).isSameAs(seq); }
Source:
private void minimumSleep(long millis) { long nanos = TimeUnit.MILLISECONDS.toNanos(millis); long start = System.nanoTime(); while (true) { long nanosLeft = nanos - (System.nanoTime() - start); if (nanosLeft <= 0) { break; } try { Thread.sleep(TimeUnit.NANOSECONDS.toMillis(nanosLeft)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } }

Target:
private void minimumSleep(long millis) { long nanos = TimeUnit.MILLISECONDS.toNanos(millis); long start = System.nanoTime(); while (true) { long nanosLeft = nanos - (System.nanoTime() - start); if (nanosLeft <= 0) { break; } try { TimeUnit.NANOSECONDS.sleep(nanosLeft); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } }
Source:
public void test_capabilities_exposed() throws Exception { Capability[] capabilities = consumer.getValueForNode(consumerId, new String[]{"management", "clients", clientIdentifier, "registry", "capabilities"}, Capability[].class); assertThat(capabilities.length, equalTo(5)); assertThat(capabilities[0].getName(), equalTo("ActionsCapability")); assertThat(capabilities[1].getName(), equalTo("StatisticsCapability")); assertThat(capabilities[2].getName(), equalTo("StatisticCollectorCapability")); assertThat(capabilities[3].getName(), equalTo("SettingsCapability")); assertThat(capabilities[4].getName(), equalTo("ManagementAgentService")); assertThat(capabilities[0].getDescriptors(), hasSize(4)); Collection<Descriptor> descriptors = capabilities[1].getDescriptors(); Collection<Descriptor> allDescriptors = new ArrayList<Descriptor>(); allDescriptors.addAll(StatsUtil.CACHE_DESCRIPTORS); allDescriptors.addAll(StatsUtil.ONHEAP_DESCRIPTORS); allDescriptors.addAll(StatsUtil.OFFHEAP_DESCRIPTORS); allDescriptors.addAll(StatsUtil.CLUSTERED_DESCRIPTORS); assertThat(descriptors, hasSize(allDescriptors.size())); assertThat(descriptors, containsInAnyOrder(allDescriptors.toArray())); assertThat(capabilities[1].getDescriptors(), hasSize(allDescriptors.size())); }

Target:
public void test_capabilities_exposed() throws Exception { Capability[] capabilities = consumer.getValueForNode(consumerId, new String[]{"management", "clients", clientIdentifier, "registry", "capabilities"}, Capability[].class); assertThat(capabilities.length, equalTo(5)); assertThat(capabilities[0].getName(), equalTo("ActionsCapability")); assertThat(capabilities[1].getName(), equalTo("StatisticsCapability")); assertThat(capabilities[2].getName(), equalTo("StatisticCollectorCapability")); assertThat(capabilities[3].getName(), equalTo("SettingsCapability")); assertThat(capabilities[4].getName(), equalTo("ManagementAgentService")); assertThat(capabilities[0].getDescriptors(), hasSize(4)); Collection<Descriptor> descriptors = capabilities[1].getDescriptors(); Collection<Descriptor> allDescriptors = new ArrayList<Descriptor>(); allDescriptors.addAll(CACHE_DESCRIPTORS); allDescriptors.addAll(ONHEAP_DESCRIPTORS); allDescriptors.addAll(OFFHEAP_DESCRIPTORS); allDescriptors.addAll(CLUSTERED_DESCRIPTORS); assertThat(descriptors, containsInAnyOrder(allDescriptors.toArray())); assertThat(descriptors, hasSize(allDescriptors.size())); }
Source:
private List<Entity> getEntities(String extensionName, String jobName, InputStream configStream, String extensionType, String extensionBuildLocation) { List<Entity> entities = null; if (!extensionType.equals(ExtensionType.CUSTOM.name())) { try { entities = ExtensionHandler.loadAndPrepare(extensionName, jobName, configStream, extensionBuildLocation); } catch (Exception e) { LOG.error("Error in building the extension. Cause: ", e); throw new FalconCLIException("Error in building the extension:" + e.getMessage(), e); } if (entities == null || entities.isEmpty()) { throw new FalconCLIException("No entities got built for the given extension"); } } return entities; }

Target:
private List<Entity> getEntities(String extensionName, String jobName, InputStream configStream, String extensionType, String extensionBuildLocation) { List<Entity> entities = null; if (!extensionType.equals(ExtensionType.CUSTOM.name())) { try { entities = ExtensionHandler.loadAndPrepare(extensionName, jobName, configStream, extensionBuildLocation); } catch (Exception e) { LOG.error("Error in building the extension. Cause: ", e); OUT.get().println("Error in building the extension:" + ExceptionUtils.getFullStackTrace(e)); throw new FalconCLIException("Error in building the extension:" + e.getMessage(), e); } if (entities == null || entities.isEmpty()) { throw new FalconCLIException("No entities got built for the given extension"); } } return entities; }
Source:
public void run() { MessageReceiver receiver = new MessageReceiver(mmHandler); while (true) { try { mmReader.readAvailable(receiver); } catch (IOException e) { e.printStackTrace(); break; } catch (Throwable t) { t.printStackTrace(); break; } } stopWriteThread(); disconnect(); }

Target:
public void run() { MessageReceiver receiver = new MessageReceiver(this.handler); boolean running = true; while (running) { try { this.reader.readAvailable(receiver); } catch (IOException e) { e.printStackTrace(); } finally { running = false; stopWriteThread(); disconnect(); } } }
Source:
public void shouldExecute() throws Exception { Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(54689))); Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(54693))); }

Target:
public void shouldExecute() throws Exception { Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(71500))); Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(71510))); }
Source:
public boolean isVolumeEmpty(String volume) throws IOException { String volumePrefix = getVolumeKey(volume + OM_KEY_PREFIX); if (bucketTable instanceof TypedTable) { Iterator<Map.Entry<CacheKey<String>, CacheValue<OmBucketInfo>>> iterator = ((TypedTable< String, OmBucketInfo>) bucketTable).cacheIterator(); while (iterator.hasNext()) { Map.Entry< CacheKey< String >, CacheValue< OmBucketInfo > > entry = iterator.next(); String key = entry.getKey().getKey(); OmBucketInfo omBucketInfo = entry.getValue().getValue(); if (key.startsWith(volumePrefix) && omBucketInfo != null) { return false; } } } try (TableIterator<String, ? extends KeyValue<String, OmBucketInfo>> bucketIter = bucketTable.iterator()) { KeyValue<String, OmBucketInfo> kv = bucketIter.seek(volumePrefix); if (kv != null && kv.getKey().startsWith(volumePrefix)) { return false; } } return true; }

Target:
public boolean isVolumeEmpty(String volume) throws IOException { String volumePrefix = getVolumeKey(volume + OM_KEY_PREFIX); Iterator<Map.Entry<CacheKey<String>, CacheValue<OmBucketInfo>>> iterator = ((TypedTable< String, OmBucketInfo>) bucketTable).cacheIterator(); while (iterator.hasNext()) { Map.Entry< CacheKey< String >, CacheValue< OmBucketInfo > > entry = iterator.next(); String key = entry.getKey().getCacheKey(); OmBucketInfo omBucketInfo = entry.getValue().getCacheValue(); if (key.startsWith(volumePrefix) && omBucketInfo != null) { return false; } } try (TableIterator<String, ? extends KeyValue<String, OmBucketInfo>> bucketIter = bucketTable.iterator()) { KeyValue<String, OmBucketInfo> kv = bucketIter.seek(volumePrefix); if (kv != null && kv.getKey().startsWith(volumePrefix) && bucketTable.get(kv.getKey()) != null) { return false; } } return true; }
Source:
private void backUpCompactionPolicyInfo(String dataDir, CompactionPolicySwitchInfo compactionPolicySwitchInfo) { if (dataDir != null && !dataDir.isEmpty()) { File tempFile = new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH).toString()); try { tempFile.createNewFile(); objectMapper.defaultPrettyPrintingWriter().writeValue(tempFile, compactionPolicySwitchInfo); } catch (IOException e) { logger.error("Exception while store compaction policy info for local report. Output file path - {}", tempFile.getAbsolutePath(), e); } } }

Target:
private void backUpCompactionPolicyInfo(String dataDir, CompactionPolicySwitchInfo compactionPolicySwitchInfo) { if (dataDir != null && !dataDir.isEmpty()) { File tempFile = new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH + ".temp").toString()); try { tempFile.createNewFile(); objectMapper.defaultPrettyPrintingWriter().writeValue(tempFile, compactionPolicySwitchInfo); tempFile.renameTo(new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH).toString())); } catch (IOException e) { logger.error("Exception while store compaction policy info for local report. Output file path - {}", tempFile.getAbsolutePath(), e); } } }
Source:
protected DiskProfiles mapCollection(List<org.ovirt.engine.core.common.businessentities.profiles.DiskProfile> entities) { DiskProfiles collection = new DiskProfiles(); Map<Guid, List<Qos>> qosMap = new HashMap<>(); for (org.ovirt.engine.core.common.businessentities.profiles.DiskProfile entity : entities) { DiskProfile profile = populate(map(entity), entity); collection.getDiskProfiles().add(profile); if (entity.getQosId() != null) { List<Qos> qosList = qosMap.get(entity.getQosId()); if (qosList == null) { qosList = new ArrayList<>(); qosMap.put(entity.getQosId(), qosList); } qosList.add(profile.getQos()); } } handleQosDataCenterLinks(qosMap); for (DiskProfile diskProfile : collection.getDiskProfiles()) { addLinks(diskProfile); } return collection; }

Target:
protected DiskProfiles mapCollection(List<org.ovirt.engine.core.common.businessentities.profiles.DiskProfile> entities) { DiskProfiles collection = new DiskProfiles(); Map<Guid, List<Qos>> qosMap = new HashMap<>(); for (org.ovirt.engine.core.common.businessentities.profiles.DiskProfile entity : entities) { DiskProfile profile = populate(map(entity), entity); collection.getDiskProfiles().add(profile); if (entity.getQosId() != null) { List<Qos> qosList = qosMap.computeIfAbsent(entity.getQosId(), id -> new ArrayList<>()); qosList.add(profile.getQos()); } } handleQosDataCenterLinks(qosMap); for (DiskProfile diskProfile : collection.getDiskProfiles()) { addLinks(diskProfile); } return collection; }
Source:
public byte[] getBinary(int ordinal) { BytesColumnVector.Bytes byteArray = getByteArray(ordinal); if (byteArray.len == byteArray.data.length) { return byteArray.data; } else { byte[] ret = new byte[byteArray.len]; System.arraycopy(byteArray.data, byteArray.offset, ret, 0, byteArray.len); return ret; } }

Target:
public byte[] getBinary(int ordinal) { BytesColumnVector.Bytes byteArray = getByteArray(ordinal); if (byteArray.len == byteArray.data.length) { return byteArray.data; } else { return Arrays.copyOfRange(byteArray.data, byteArray.offset, byteArray.len); } }
Source:
public void testQueryNameDisplayable() { String test = "select * from employee e (where e.id <> 0 and e.name ='foo' and e.other != 'other'"; long start = System.currentTimeMillis(); for ( int looper = 0; looper < 500000; looper ++) { QueryName name = new QueryName(test); } long end = System.currentTimeMillis(); long duration = (end - start); Assert.assertTrue("Duration of QueryName.displayable called in a 500000 loop must be lower than 3000 milliseconds, but was " + duration, duration < 3000); }

Target:
public void testQueryNameDisplayable() { String test = "select * from employee e (where e.id <> 0 and e.name ='foo' and e.other != 'other'"; long start = System.currentTimeMillis(); for ( int looper = 0; looper < 500000; looper ++) { QueryName name = new QueryName(test); } long end = System.currentTimeMillis(); long duration = (end - start); Assert.assertTrue("Duration of QueryName.displayable called in a 500000 loop must be lower than 3000 milliseconds, but was " + duration, duration < TIMEOUT); }
Source:
public void Export_SerializerConfig() { exporter.setTargetFolder(new File("target/gen7")); exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); exporter.export(Cat.class.getPackage()); }

Target:
public void Export_SerializerConfig() { exporter.setTargetFolder(new File("target/gen7")); exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); exporter.export(getClass().getPackage()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEmbeddable.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEmbedded.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEntity.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEntityInterface.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleSupertype.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/sub/QExampleEntity2.java").exists()); }
Source:
public DruidServerMetadata getMetadata(@Self DruidNode node, DruidServerConfig config) { return new DruidServerMetadata( node.getHost(), node.getHost(), config.getMaxSize(), config.getType(), config.getTier() ); }

Target:
public DruidServerMetadata getMetadata(@Self DruidNode node, DruidServerConfig config) { return new DruidServerMetadata( node.getHost(), node.getHost(), config.getMaxSize(), nodeType, config.getTier() ); }
Source:
public void onConnected(Session session) { Log.d(TAG, "onConnected: Connected to session " + session.getSessionId()); CustomVideoCapturer capturer = new CustomVideoCapturer(MainActivity.this, Publisher.CameraCaptureResolution.MEDIUM, Publisher.CameraCaptureFrameRate.FPS_30); capturer.setCustomVideoCapturerDataSource(new CustomVideoCapturer.CustomVideoCapturerDataSource() { @Override public byte[] retrieveMetadata() { return getCurrentTimeStamp().getBytes(); } }); InvertedColorsVideoRenderer renderer = new InvertedColorsVideoRenderer(MainActivity.this); renderer.setInvertedColorsVideoRendererMetadataListener(new InvertedColorsVideoRenderer.InvertedColorsVideoRendererMetadataListener() { @Override public void onMetadataReady(byte[] metadata) { String timestamp = null; try { timestamp = new String(metadata, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(timestamp); } }); mPublisher = new Publisher.Builder(MainActivity.this) .name("publisher") .capturer(capturer) .renderer(renderer).build(); mPublisher.setPublisherListener(this); mPublisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); if (mPublisher.getView() instanceof GLSurfaceView) { ((GLSurfaceView)(mPublisher.getView())).setZOrderOnTop(true); } mSession.publish(mPublisher); }

Target:
public void onConnected(Session session) { Log.d(TAG, "onConnected: Connected to session " + session.getSessionId()); CustomVideoCapturer capturer; capturer = new CustomVideoCapturer(MainActivity.this, Publisher.CameraCaptureResolution.MEDIUM, Publisher.CameraCaptureFrameRate.FPS_30); capturer.setCustomVideoCapturerDataSource(new CustomVideoCapturer.CustomVideoCapturerDataSource() { @Override public byte[] retrieveMetadata() { return getCurrentTimeStamp().getBytes(); } }); InvertedColorsVideoRenderer renderer = new InvertedColorsVideoRenderer(MainActivity.this); renderer.setInvertedColorsVideoRendererMetadataListener(new InvertedColorsVideoRenderer.InvertedColorsVideoRendererMetadataListener() { @Override public void onMetadataReady(byte[] metadata) { String timestamp = null; try { timestamp = new String(metadata, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(timestamp); } }); mPublisher = new Publisher.Builder(MainActivity.this) .name("publisher") .capturer(capturer) .renderer(renderer).build(); mPublisher.setPublisherListener(this); mPublisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); if (mPublisher.getView() instanceof GLSurfaceView) { ((GLSurfaceView)(mPublisher.getView())).setZOrderOnTop(true); } mSession.publish(mPublisher); }
Source:
protected String doIt() throws Exception { final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus); for (final ArchiveId logId : getSelectedDocOutboundLogIds()) { ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, logId); } return MSG_OK; }

Target:
protected String doIt() throws Exception { final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus); for (final DocOutboundLogId logId : getSelectedDocOutboundLogIds()) { ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, logId); } return MSG_OK; }
Source:
public void testEquals() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("a", "aval"); map.put("b", "bval"); IotasEvent event1 = new IotasEventImpl(map); IotasEvent event2 = new IotasEventImpl(map, event1.getId()); assertEquals(event1, event2); }

Target:
public void testEquals() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("a", "aval"); map.put("b", "bval"); IotasEvent event1 = new IotasEventImpl(map, StringUtils.EMPTY); IotasEvent event2 = new IotasEventImpl(map, StringUtils.EMPTY, event1.getId()); assertEquals(event1, event2); }
Source:
protected String getProbeSetName() { if (BAIT_SET_NAME != null) { return BAIT_SET_NAME; } if (BAIT_INTERVALS.size() == 1) { return CollectTargetedMetrics.renderProbeNameFromFilename(BAIT_INTERVALS.get(0)); } else { throw new PicardException("Cannot infer BAIT_SET_NAME because there is not exactly one BAIT_INTERVALS provided."); } }

Target:
protected String getProbeSetName() { if (BAIT_SET_NAME != null) { return BAIT_SET_NAME; } else { final SortedSet<String> baitSetNames = new TreeSet<String>(); for (final File file : BAIT_INTERVALS) { baitSetNames.add(CollectTargetedMetrics.renderProbeNameFromFile(file)); } return StringUtil.join(".", baitSetNames); } }
Source:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (DisallowedDisguises.disabled) { msg("Disguises are not enabled."); return true; } FUtil.adminAction(sender.getName(), "Undisguising all non-admins", true); plugin.ldb.undisguiseAll(false); return true; }

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (plugin.ldb.getLibsDisguisesPlugin() == null) { msg("libsDisguises is not enabled."); return true; } if (DisallowedDisguises.disabled) { msg("Disguises are not enabled."); return true; } FUtil.adminAction(sender.getName(), "Undisguising all non-admins", true); plugin.ldb.undisguiseAll(false); return true; }
Source:
public Optional<GradleBuild> getGradleBuild(IProject project) { try { if (GradleProjectNature.isPresentOn(project)) { ProjectConfiguration projectConfiguration = CorePlugin.configurationManager().loadProjectConfiguration(project); BuildConfiguration buildConfig = projectConfiguration.getBuildConfiguration(); return Optional.<GradleBuild>of(new DefaultGradleBuild(buildConfig)); } else { return Optional.absent(); } } catch (RuntimeException e) { CorePlugin.logger().debug("Cannot load configuration for project " + project.getName()); return Optional.absent(); } }

Target:
public Optional<GradleBuild> getGradleBuild(IProject project) { if (GradleProjectNature.isPresentOn(project)) { ProjectConfiguration projectConfiguration = CorePlugin.configurationManager().tryLoadProjectConfiguration(project); if (projectConfiguration != null) { return Optional.<GradleBuild>of(new DefaultGradleBuild(projectConfiguration.getBuildConfiguration())); } else { return Optional.absent(); } } else { return Optional.absent(); } }
Source:
public static String getParameterOrDefaultValue(ParameterCore key) { if (Objects.nonNull(key.getType())) { if (key.getType().equals(String.class)) { return getParameter(key.getName(), (String) key.getDefaultValue()); } throw new ConfigParameterException(key.getName(), "String"); } throw new ConfigParameterException("Type of key is null"); }

Target:
public static String getParameterOrDefaultValue(ParameterCore key) { checkNotNullKeyType(key); if (key.getType().equals(String.class)) { return getParameter(key.getName(), (String) key.getDefaultValue()); } throw new ConfigParameterException(key.getName(), "String"); }
Source:
private void beforeFirstRefreshTreatment(boolean isVdsUpOrGoingToMaintenance) { if (_vdsManager.getbeforeFirstRefresh()) { boolean flagsChanged = false; final AtomicBoolean processHardwareCapsNeededTemp = new AtomicBoolean(); _vdsManager.refreshCapabilities(processHardwareCapsNeededTemp, _vds); flagsChanged = processHardwareCapsNeededTemp.get(); _vdsManager.setbeforeFirstRefresh(false); refreshedCapabilities = true; _saveVdsDynamic = true; processHardwareCapsNeeded = (processHardwareCapsNeeded) ? processHardwareCapsNeeded : flagsChanged; } else if (isVdsUpOrGoingToMaintenance || _vds.getStatus() == VDSStatus.Error) { return; } if (_vds.getStatus() != VDSStatus.Up) { AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.addCustomValue("VdsStatus", _vds.getStatus().toString()); auditLog(logable, AuditLogType.VDS_DETECTED); } }

Target:
private void beforeFirstRefreshTreatment(boolean isVdsUpOrGoingToMaintenance) { if (_vdsManager.getbeforeFirstRefresh()) { boolean flagsChanged = false; final AtomicBoolean processHardwareCapsNeededTemp = new AtomicBoolean(); _vdsManager.refreshCapabilities(processHardwareCapsNeededTemp, _vds); flagsChanged = processHardwareCapsNeededTemp.get(); _vdsManager.setbeforeFirstRefresh(false); refreshedCapabilities = true; _saveVdsDynamic = true; processHardwareCapsNeeded = (processHardwareCapsNeeded) ? processHardwareCapsNeeded : flagsChanged; } else if (isVdsUpOrGoingToMaintenance || _vds.getStatus() == VDSStatus.Error) { return; } if (_vds.getStatus() != VDSStatus.Up) { AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.addCustomValue("HostStatus", _vds.getStatus().toString()); auditLog(logable, AuditLogType.VDS_DETECTED); } }
Source:
public boolean match(Double outputValue, Double correctValue) { try { double a = outputValue; double b = correctValue; if (Double.isNaN(a) && Double.isNaN(b)) { return true; } else if (Double.isInfinite(a) && Double.isInfinite(b) && a * b < 0) { return true; } else if (Math.abs(a - b) < COMPARISON_THRESHOLD * a) { return true; } return false; } catch(NumberFormatException e) { return false; } }

Target:
public boolean match(Double outputValue, Double correctValue) { try { double a = outputValue; double b = correctValue; if (a == b) { return true; } else if (Double.isNaN(a) && Double.isNaN(b)) { return true; } else if (Math.abs(a - b) < COMPARISON_THRESHOLD * b) { return true; } else { return false; } } catch(NumberFormatException e) { return false; } }
Source:
public void testCorrect() throws Exception { final String expected = new String(Files.readAllBytes(Paths.get( getPath("ExpectedSuppressionsStringPrinter.txt"))), StandardCharsets.UTF_8).replaceAll("\\\\r\\\\n", "\\\\n"); final File input = new File(getPath("InputSuppressionsStringPrinter.java")); final String lineAndColumnNumber = "3:1"; final int tabWidth = 2; final String result = SuppressionsStringPrinter.printSuppressions(input, lineAndColumnNumber, tabWidth); Assert.assertEquals("Invalid xpath queries", expected, result); }

Target:
public void testCorrect() throws Exception { final String expected = "/CLASS_DEF[@text='InputSuppressionsStringPrinter']" + EOL + "/CLASS_DEF[@text='InputSuppressionsStringPrinter']/MODIFIERS" + EOL + "/CLASS_DEF[@text='InputSuppressionsStringPrinter']/MODIFIERS/LITERAL_PUBLIC" + EOL; final File input = new File(getPath("InputSuppressionsStringPrinter.java")); final String lineAndColumnNumber = "3:1"; final int tabWidth = 2; final String result = SuppressionsStringPrinter.printSuppressions(input, lineAndColumnNumber, tabWidth); Assert.assertEquals("Invalid xpath queries", expected, result); }