auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testHappyPath() { DataSize maxResponseSize = new DataSize(10, MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize); URI location = URI.create("http://localhost:8080"); processor.addPage(location, createPage(1)); processor.addPage(location, createPage(2)); processor.addPage(location, createPage(3)); processor.setComplete(location); @SuppressWarnings("resource") ExchangeClient exchangeClient = new ExchangeClient( new DataSize(32, MEGABYTE), maxResponseSize, 1, new Duration(1, MINUTES), true, 0.2, new TestingHttpClient(processor, scheduler), (context, header) -> null, scheduler, new SimpleLocalMemoryContext(newSimpleAggregatedMemoryContext(), "test"), pageBufferClientCallbackExecutor); exchangeClient.addLocation(location, TaskId.valueOf("queryid.0.0.0")); exchangeClient.noMoreLocations(); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(1)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(2)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(3)); assertNull(getNextPage(exchangeClient)); assertEquals(exchangeClient.isClosed(), true); ExchangeClientStatus status = exchangeClient.getStatus(); assertEquals(status.getBufferedPages(), 0); assertEquals(status.getBufferedBytes(), 0); assertStatus(status.getPageBufferClientStatuses().get(0), location, "closed", 3, 3, 3, "not scheduled"); }

Target:
public void testHappyPath() { DataSize maxResponseSize = new DataSize(10, MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize); URI location = URI.create("http://localhost:8080"); processor.addPage(location, createPage(1)); processor.addPage(location, createPage(2)); processor.addPage(location, createPage(3)); processor.setComplete(location); @SuppressWarnings("resource") ExchangeClient exchangeClient = new ExchangeClient( new DataSize(32, MEGABYTE), maxResponseSize, 1, new Duration(1, MINUTES), true, 0.2, new TestingHttpClient(processor, scheduler), new TestingDriftClient<>(), scheduler, new SimpleLocalMemoryContext(newSimpleAggregatedMemoryContext(), "test"), pageBufferClientCallbackExecutor); exchangeClient.addLocation(location, TaskId.valueOf("queryid.0.0.0")); exchangeClient.noMoreLocations(); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(1)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(2)); assertFalse(exchangeClient.isClosed()); assertPageEquals(getNextPage(exchangeClient), createPage(3)); assertNull(getNextPage(exchangeClient)); assertEquals(exchangeClient.isClosed(), true); ExchangeClientStatus status = exchangeClient.getStatus(); assertEquals(status.getBufferedPages(), 0); assertEquals(status.getBufferedBytes(), 0); assertStatus(status.getPageBufferClientStatuses().get(0), location, "closed", 3, 3, 3, "not scheduled"); }
Source:
public Object getValue(final Object element, final String property) { if (IV_NAME.equals(property)) { return ((VarDeclaration) element).getName(); } else if (IV_TYPE.equals(property)) { int i = 0; for(String item : typeDropDown.getItems()){ if(item.equals(((VarDeclaration) element).getType().getName())){ return i; } i++; } return 0; } else if (IV_COMMENT.equals(property)) { return ((VarDeclaration) element).getComment(); } else if (IV_ARRAY.equals(property)) { return Integer.toString(((VarDeclaration) element).getArraySize()); } else{ return ((VarDeclaration) element).getValue().getValue(); } }

Target:
public Object getValue(final Object element, final String property) { VarDeclaration var = (VarDeclaration) element; switch(property) { case IV_NAME: return var.getName(); case IV_TYPE: for(int i = 0; i < typeDropDown.getItems().length; i++) { if(typeDropDown.getItems()[i].equals(var.getType().getName())){ return i; } } return 0; case IV_COMMENT: return var.getComment(); case IV_ARRAY: return Integer.toString(var.getArraySize()); default: return var.getValue().getValue(); } }
Source:
public void clientSupplierInvokedOnStreamsBuilderFactoryBean() { Assert.assertTrue("StreamsBuilderFactoryBean#setClientSupplier(KafkaClientSupplier) not called", bean.isClientSupplierInvoked()); }

Target:
public void clientSupplierInvokedOnStreamsBuilderFactoryBean() { then(streamsBuilderFactoryBean.clientSupplierInvoked).isTrue(); }
Source:
private VisitableSampledSpectrum signal(final double throughput) { final VisitableSampledSpectrum signal = (VisitableSampledSpectrum) sourceFlux.clone(); final int lastPixel = lastCcdPixel(signal.getLength()); Log.fine("Calculating signal with " + throughput + " throughput on detector pixels " + firstCcdPixel + " - " + lastPixel); for (int i = 0; i < firstCcdPixel; ++i) { signal.setY(i, 0); } for (int i = firstCcdPixel; i <= lastPixel; ++i) { signal.setY(i, totalFlux(sourceFlux.getY(i), throughput)); } for (int i = lastPixel+1; i < signal.getLength(); ++i) { signal.setY(i, 0); } return signal; }

Target:
private VisitableSampledSpectrum signal(final double throughput) { final VisitableSampledSpectrum signal = (VisitableSampledSpectrum) sourceFlux.clone(); final int lastPixel = lastCcdPixel(signal.getLength()); Log.fine("Calculating signal with " + throughput + " throughput on detector pixels " + firstCcdPixel + " - " + lastPixel); for (int i = 0; i < signal.getLength(); ++i) { signal.setY(i, 0); } for (int i = firstCcdPixel; i <= lastPixel; ++i) { signal.setY(i, totalFlux(sourceFlux.getY(i), throughput)); } return signal; }
Source:
public void shouldNotRaiseAlertIfRequestParamValuesNotUsedInJsEvent() throws URIException, NullPointerException { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><img src=\"x.jpg\" onerror=alert(\"Error\")></img></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(0)); }

Target:
public void shouldNotRaiseAlertIfRequestParamValuesNotUsedInJsEvent() throws Exception { HttpMessage msg = createMessage(); msg.getRequestHeader().setURI(new URI("<LINK_0>", false)); msg.setResponseBody("<html><img src=\"x.jpg\" onerror=alert(\"Error\")></img></html>"); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), equalTo(0)); }
Source:
public double getPopulationMean() { if (populationCount == 0) { return Double.NaN; } return populationSum.divide(new BigDecimal(populationCount), 8, RoundingMode.HALF_UP).doubleValue(); }

Target:
public double getPopulationMean() { if (populationCount == 0) { return Double.NaN; } BigDecimal popCount = BigDecimal.valueOf(populationCount); return populationSum.divide(popCount, populationSum.scale() + popCount.precision(), RoundingMode.HALF_UP).doubleValue(); }
Source:
public void testSameFieldMultipleConverts() throws Exception { ProjectionTransform.ProjectionTransformConfig config = new ProjectionTransform .ProjectionTransformConfig(null, null, "x:int,x:long", null); Transform<StructuredRecord, StructuredRecord> transform = new ProjectionTransform(config); TransformContext transformContext = new MockTransformContext(); String caughtException = ""; try { transform.initialize(transformContext); } catch (Exception e) { caughtException = e.getMessage(); } Assert.assertEquals(validationExceptionMessage, caughtException); FailureCollector collector = transformContext.getFailureCollector(); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, convert); expectedCause.addAttribute(stage, mockStage); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }

Target:
public void testSameFieldMultipleConverts() throws Exception { ProjectionTransform.ProjectionTransformConfig config = new ProjectionTransform .ProjectionTransformConfig(null, null, "x:int,x:long", null); Transform<StructuredRecord, StructuredRecord> transform = new ProjectionTransform(config); TransformContext transformContext = new MockTransformContext(); try { transform.initialize(transformContext); Assert.fail(); } catch (ValidationException e) { Assert.assertEquals(1, e.getFailures().size()); Assert.assertEquals(1, e.getFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, ProjectionTransform.ProjectionTransformConfig.CONVERT); expectedCause.addAttribute(STAGE, MOCK_STAGE); Assert.assertEquals(expectedCause, e.getFailures().get(0).getCauses().get(0)); } }
Source:
private static ConcurStandardAccountingExtractDetailLine buildConcurStandardAccountingExtractDetailLine(String debitCredit, KualiDecimal amount) { ConcurStandardAccountingExtractDetailLine line = new ConcurStandardAccountingExtractDetailLine(); line.setJounalDebitCredit(debitCredit); line.setJournalAmount(amount); line.setEmployeeGroupId("CORNELL"); return line; }

Target:
private static ConcurStandardAccountingExtractDetailLine buildConcurStandardAccountingExtractDetailLine(String debitCredit, KualiDecimal amount) { ConcurStandardAccountingExtractDetailLine line = new ConcurStandardAccountingExtractDetailLine(); line.setJounalDebitCredit(debitCredit); line.setJournalAmount(amount); line.setEmployeeGroupId(EMPLOYEE_GROUP_ID); return line; }
Source:
public void testNoRecursiveNesting() { System.out.println("No Recursive Nesting"); FieldProcessor<TestClassM> instance = new FieldProcessor(TestClassM.class); TestClassE nested = new TestClassE("10"); TestClassM testClass = new TestClassM("20", nested); instance.processLinks(testClass, mockUriInfo, mockRmc); assertEquals("widgets/20", testClass.thelink); assertEquals(null, testClass.nested.link); }

Target:
public void testNoRecursiveNesting() { LOG.info("No Recursive Nesting"); FieldProcessor<TestClassM> instance = new FieldProcessor(TestClassM.class); TestClassE nested = new TestClassE("10"); TestClassE transientNested = new TestClassE("30"); TestClassM testClass = new TestClassM("20", nested, transientNested); instance.processLinks(testClass, mockUriInfo, mockRmc); assertEquals("widgets/20", testClass.thelink); assertEquals(null, testClass.nested.link); assertEquals(null, testClass.transientNested.link); }
Source:
public void killTask(ExecutorDriver driver, TaskID taskId) { String taskIdString = taskId.getValue(); LOGGER.debug("killTask received for taskId: " + taskIdString); TaskStatus status; if (!taskIdString.contains(MyriadExecutorAuxService.YARN_CONTAINER_TASK_ID_PREFIX)) { synchronized (containerIds) { for (String containerId : containerIds) { Protos.TaskID containerTaskId = Protos.TaskID.newBuilder().setValue( MyriadExecutorAuxService.YARN_CONTAINER_TASK_ID_PREFIX + containerId).build(); status = TaskStatus.newBuilder().setTaskId(containerTaskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); } } status = TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); LOGGER.info("NodeManager shutdown after receiving" + " KillTask for taskId " + taskId.getValue()); Runtime.getRuntime().exit(0); } else { status = TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); synchronized (containerIds) { if (containerIds.remove(taskIdString.substring(MyriadExecutorAuxService.YARN_CONTAINER_FULL_PREFIX.length(), taskIdString.length()))) { LOGGER.debug("Removed task from containerIds"); } } LOGGER.debug("Killing " + taskId); } }

Target:
public void killTask(ExecutorDriver driver, TaskID taskId) { String taskIdString = taskId.toString(); LOGGER.debug("killTask received for taskId: " + taskIdString); TaskStatus status; if (!taskIdString.contains(MyriadExecutorAuxService.YARN_CONTAINER_TASK_ID_PREFIX)) { synchronized (containerIds) { for (String containerId : containerIds) { Protos.TaskID containerTaskId = Protos.TaskID.newBuilder().setValue( MyriadExecutorAuxService.YARN_CONTAINER_TASK_ID_PREFIX + containerId).build(); status = TaskStatus.newBuilder().setTaskId(containerTaskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); } } status = TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); LOGGER.info("NodeManager shutdown after receiving KILL_TASK for taskId {}", taskIdString); Runtime.getRuntime().exit(0); } else { status = TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_KILLED).build(); driver.sendStatusUpdate(status); synchronized (containerIds) { if (containerIds.remove(taskIdString.substring(MyriadExecutorAuxService.YARN_CONTAINER_FULL_PREFIX.length(), taskIdString.length()))) { LOGGER.debug("Removed taskId from containerIds", taskIdString); } } LOGGER.debug("Killing " + taskId); } }
Source:
private <K extends Exception> void handleException(int numTries, InetSocketAddress host, Exception ex) throws K { if (isRetriableException(ex) || isRetriableWithBackoffException(ex)) { if (numTries >= MAX_TRIES_TOTAL) { if (ex instanceof TTransportException && ex.getCause() != null && (ex.getCause().getClass() == SocketException.class)) { log.error(CONNECTION_FAILURE_MSG, numTries, ex); String errorMsg = MessageFormatter.format(CONNECTION_FAILURE_MSG, numTries).getMessage(); throw (K) new TTransportException(((TTransportException) ex).getType(), errorMsg, ex); } else { log.error("Tried to connect to cassandra times.", SafeArg.of("numTries", numTries), ex); throw (K) ex; } } else { log.warn("Error occurred talking to cassandra. Attempt of {}. Exception message was: : {}", SafeArg.of("numTries", numTries), SafeArg.of("maxTotalTries", MAX_TRIES_TOTAL), SafeArg.of("exceptionClass", ex.getClass().getTypeName()), ex.getMessage()); if (isConnectionException(ex) && numTries >= MAX_TRIES_SAME_HOST) { addToBlacklist(host); } } } else { throw (K) ex; } }

Target:
private <K extends Exception> void handleException(int numTries, InetSocketAddress host, Exception ex) throws K { if (isRetriableException(ex) || isRetriableWithBackoffException(ex)) { if (numTries >= MAX_TRIES_TOTAL) { if (ex instanceof TTransportException && ex.getCause() != null && (ex.getCause().getClass() == SocketException.class)) { log.error(CONNECTION_FAILURE_MSG, numTries, ex); String errorMsg = MessageFormatter.format(CONNECTION_FAILURE_MSG, numTries).getMessage(); throw (K) new TTransportException(((TTransportException) ex).getType(), errorMsg, ex); } else { log.error("Tried to connect to cassandra times.", SafeArg.of("numTries", numTries), ex); throw (K) ex; } } else { if (numTries > 1) { log.warn("Error occurred talking to cassandra. Attempt of {}. Exception message was: : {}", SafeArg.of("numTries", numTries), SafeArg.of("maxTotalTries", MAX_TRIES_TOTAL), SafeArg.of("exceptionClass", ex.getClass().getTypeName()), UnsafeArg.of("exceptionMessage", ex.getMessage())); } else { log.warn("Error occurred talking to cassandra. Attempt of {}.", SafeArg.of("numTries", numTries), SafeArg.of("maxTotalTries", MAX_TRIES_TOTAL), ex); } if (isConnectionException(ex) && numTries >= MAX_TRIES_SAME_HOST) { addToBlacklist(host); } } } else { throw (K) ex; } }
Source:
public Object clone() { final RetryOptions cloned = (RetryOptions) getRetryOptions().clone(); return new ExponentialRetryPolicy(cloned); }

Target:
public RetryPolicy clone() { final RetryOptions cloned = getRetryOptions().clone(); return new ExponentialRetryPolicy(cloned); }
Source:
private MainJava() { throw new AssertionError("Instantiating utility class"); }

Target:
private MainJava() { }
Source:
public void onButtonClicked(JogPanelButtonEnum button) { switch (button) { case BUTTON_XNEG: jogService.adjustManualLocationXY(-1, 0); break; case BUTTON_XPOS: jogService.adjustManualLocationXY(1, 0); break; case BUTTON_YNEG: jogService.adjustManualLocationXY(0, -1); break; case BUTTON_YPOS: jogService.adjustManualLocationXY(0, 1); break; case BUTTON_DIAG_XNEG_YNEG: jogService.adjustManualLocationXY(-1, -1); break; case BUTTON_DIAG_XNEG_YPOS: jogService.adjustManualLocationXY(-1, 1); break; case BUTTON_DIAG_XPOS_YNEG: jogService.adjustManualLocationXY(1, -1); break; case BUTTON_DIAG_XPOS_YPOS: jogService.adjustManualLocationXY(1, 1); break; case BUTTON_ZNEG: jogService.adjustManualLocationZ(-1); break; case BUTTON_ZPOS: jogService.adjustManualLocationZ(1); break; case BUTTON_TOGGLE_UNIT: if (jogService.getUnits() == UnitUtils.Units.MM) { jogService.setUnits(UnitUtils.Units.INCH); } else { jogService.setUnits(UnitUtils.Units.MM); } break; case BUTTON_LARGER_STEP: jogService.setStepSizeXY(jogService.getStepSizeXY() * 10); jogService.setStepSizeZ(jogService.getStepSizeZ() * 5); break; case BUTTON_SMALLER_STEP: jogService.setStepSizeXY(jogService.getStepSizeXY() / 10); jogService.setStepSizeZ(jogService.getStepSizeZ() / 5); break; default: } }

Target:
public void onButtonClicked(JogPanelButtonEnum button) { switch (button) { case BUTTON_XNEG: jogService.adjustManualLocationXY(-1, 0); break; case BUTTON_XPOS: jogService.adjustManualLocationXY(1, 0); break; case BUTTON_YNEG: jogService.adjustManualLocationXY(0, -1); break; case BUTTON_YPOS: jogService.adjustManualLocationXY(0, 1); break; case BUTTON_DIAG_XNEG_YNEG: jogService.adjustManualLocationXY(-1, -1); break; case BUTTON_DIAG_XNEG_YPOS: jogService.adjustManualLocationXY(-1, 1); break; case BUTTON_DIAG_XPOS_YNEG: jogService.adjustManualLocationXY(1, -1); break; case BUTTON_DIAG_XPOS_YPOS: jogService.adjustManualLocationXY(1, 1); break; case BUTTON_ZNEG: jogService.adjustManualLocationZ(-1); break; case BUTTON_ZPOS: jogService.adjustManualLocationZ(1); break; case BUTTON_TOGGLE_UNIT: if (jogService.getUnits() == UnitUtils.Units.MM) { jogService.setUnits(UnitUtils.Units.INCH); } else { jogService.setUnits(UnitUtils.Units.MM); } break; case BUTTON_LARGER_STEP: jogService.multiplyXYStepSize(); jogService.multiplyZStepSize(); break; case BUTTON_SMALLER_STEP: jogService.divideXYStepSize(); jogService.divideZStepSize(); break; default: } }
Source:
protected void onPostExecute(SiteList[] updatedSiteLists) { if (updatedSiteLists != null) { mAllSites = updatedSiteLists[0]; mSites = updatedSiteLists[1]; notifyDataSetChanged(); } mIsTaskRunning = false; if (mDataLoadedListener != null) { mDataLoadedListener.onAfterLoad(); } }

Target:
protected void onPostExecute(SiteList[] updatedSiteLists) { if (updatedSiteLists != null) { mAllSites = updatedSiteLists[0]; mSites = updatedSiteLists[1]; notifyDataSetChanged(); } if (mDataLoadedListener != null) { mDataLoadedListener.onAfterLoad(); } }
Source:
public boolean isPartitionedOn(Collection<Symbol> columns, Set<Symbol> knownConstants) { return arguments.stream() .filter(ArgumentBinding::isCoalesce) .count() == 0 && arguments.stream() .filter(ArgumentBinding::isVariable) .map(ArgumentBinding::getColumn) .filter(symbol -> !knownConstants.contains(symbol)) .allMatch(columns::contains); }

Target:
public boolean isPartitionedOn(Collection<Symbol> columns, Set<Symbol> knownConstants) { for (ArgumentBinding argument : arguments) { if (argument.isConstant()) { continue; } if (!argument.isVariable()) { return false; } if (!knownConstants.contains(argument.getColumn()) && !columns.contains(argument.getColumn())) { return false; } } return true; }
Source:
public static boolean isEmptyDRId (long drId) { return ((drId >>> 63) == 1L) && !(drId == -1); }

Target:
public static boolean isEmptyDRId (long drId) { return ((drId >>> 63) == 1L) && (drId != -1); }
Source:
public void takeLeadership(CuratorFramework client) throws Exception { setState(State.PRIMARY); if (client.checkExists().forPath(mLeaderFolder + mName) != null) { LOG.info("Deleting zk path: {}{}", mLeaderFolder, mName); client.delete().forPath(mLeaderFolder + mName); } LOG.info("Creating zk path: {}{}", mLeaderFolder, mName); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL) .forPath(mLeaderFolder + mName); LOG.info("{} is now the leader.", mName); try { mLeaderZkSessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); waitForState(State.SECONDARY); } finally { LOG.warn("{} relinquishing leadership.", mName); LOG.info("The current leader is {}", mLeaderSelector.getLeader().getId()); LOG.info("All participants: {}", mLeaderSelector.getParticipants()); client.delete().forPath(mLeaderFolder + mName); mLeaderZkSessionId = -1; } }

Target:
public void takeLeadership(CuratorFramework client) throws Exception { setState(State.PRIMARY); if (client.checkExists().forPath(mLeaderFolder + mName) != null) { LOG.info("Deleting zk path: {}{}", mLeaderFolder, mName); client.delete().forPath(mLeaderFolder + mName); } LOG.info("Creating zk path: {}{}", mLeaderFolder, mName); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL) .forPath(mLeaderFolder + mName); LOG.info("{} is now the leader.", mName); try { mLeaderZkSessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); LOG.info(String.format("Taken leadership under session Id: %x", mLeaderZkSessionId)); waitForState(State.SECONDARY); } finally { LOG.warn("{} relinquishing leadership.", mName); LOG.info("The current leader is {}", mLeaderSelector.getLeader().getId()); LOG.info("All participants: {}", mLeaderSelector.getParticipants()); client.delete().forPath(mLeaderFolder + mName); mLeaderZkSessionId = NOT_A_LEADER; } }
Source:
public void checkSymmetry(Iterator<SymmetryCheckerMessage> msgIterator) { while (msgIterator.hasNext()) { SymmetryCheckerMessage incomingMsg = msgIterator.next(); EDGETYPE neighborToMe = EDGETYPE.fromByte(incomingMsg.getFlag()); boolean exist = getVertexValue().getEdges(neighborToMe).contains(incomingMsg.getSourceVertexId()); if (!exist) { getVertexValue().setState(State.ERROR_NODE); return; } boolean edgesAreSame = true; for (VKmer kmer : incomingMsg.getEdges()) { if (!getVertexValue().getEdges(neighborToMe).contains(kmer)) { edgesAreSame = false; break; } } if (!edgesAreSame) getVertexValue().setState(State.ERROR_NODE); } }

Target:
public void checkSymmetry(Iterator<SymmetryCheckerMessage> msgIterator) { while (msgIterator.hasNext()) { SymmetryCheckerMessage incomingMsg = msgIterator.next(); EDGETYPE neighborToMe = EDGETYPE.fromByte(incomingMsg.getFlag()); boolean exist = getVertexValue().getEdges(neighborToMe).contains(incomingMsg.getSourceVertexId()); if (!exist) { getVertexValue().setState(State.ERROR_NODE); return; } boolean edgesAreSame = true; for (VKmer kmer : incomingMsg.getEdges()) { if (!getVertexValue().getEdges(neighborToMe).contains(kmer)) { edgesAreSame = false; break; } } for (VKmer kmer : getVertexValue().getEdges(neighborToMe)) { if (!incomingMsg.getEdges().contains(kmer)) { edgesAreSame = false; break; } } if (!edgesAreSame) getVertexValue().setState(State.ERROR_NODE); } }
Source:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { SchemaWrite schemaWrite = schemaWriteInNewTransaction(); try { schemaWrite.indexCreate( forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { } }

Target:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { SchemaWrite schemaWrite = schemaWriteInNewTransaction(); try { creator.create( schemaWrite, forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { } }
Source:
public void processClientSettingsEvent(C15PacketClientSettings packet, CallbackInfo ci) { PlayerChangeClientSettingsEvent event = SpongeEventFactory.createPlayerChangeClientSettingsEvent(Cause.of(NamedCause.source(this)), (ChatVisibility) (Object) this.chatVisibility, this.skinParts, this.getLocale(), this, this.chatColours, this.viewDistance); SpongeImpl.postEvent(event); }

Target:
public void processClientSettingsEvent(C15PacketClientSettings packet, CallbackInfo ci) { PlayerChangeClientSettingsEvent event = SpongeEventFactory.createPlayerChangeClientSettingsEvent(Cause.of(NamedCause.source(this)), (ChatVisibility) (Object) packet.getChatVisibility(), SkinUtil.fromFlags(packet.getModelPartFlags()), LanguageUtil.LOCALE_CACHE.getUnchecked(packet.getLang()), this, packet.isColorsEnabled(), packet.view); SpongeImpl.postEvent(event); }
Source:
protected ResultMetadata convert(RequestStatusMetaData requestStatusMetaData) { if (requestStatusMetaData == null) { return null; } if (!DeleteStatusMetaData.class.isInstance(requestStatusMetaData)) { throw new IllegalArgumentException("RequestStatusDetails is not of type DeleteStatusDetails. requestStatusMetaData.getClass= " + requestStatusMetaData.getClass()); } DeleteStatusMetaData statusDetails = (DeleteStatusMetaData) requestStatusMetaData; DeleteResultMetadata resultDetails = new DeleteResultMetadata(); resultDetails.addDeletedKeys(statusDetails.getDeletedKeys()); resultDetails.addExceptions(statusDetails.getExceptionForKeys()); return resultDetails; }

Target:
protected ResultMetadata convert(RequestStatusMetaData requestStatusMetaData) { if (requestStatusMetaData == null) { return null; } if (!(requestStatusMetaData instanceof DeleteStatusMetaData)) { throw new IllegalArgumentException( String.format("Wrong status details class received - expecting: %s; actual: %s", DeleteStatusMetaData.class, requestStatusMetaData.getClass())); } DeleteStatusMetaData statusDetails = (DeleteStatusMetaData) requestStatusMetaData; DeleteResultMetadata resultDetails = new DeleteResultMetadata(); resultDetails.addDeletedKeys(statusDetails.getDeletedKeys()); resultDetails.addExceptions(statusDetails.getExceptionForKeys()); return resultDetails; }
Source:
private String addCachePrefix(String content) { return CACHE_PREFIX + content; }

Target:
private static String addCachePrefix(String content) { return CACHE_PREFIX + content; }
Source:
public Collection<ActivityEvent> getEvents(ActivityScope scope) { Assert.isNotNull(scope, "Task scope should not be null."); events.addAll(new ReviewTaskProvider().getReviews(((TaskActivityScope) scope).getTask().getTaskId())); return events; }

Target:
public Collection<ActivityEvent> getEvents(ActivityScope scope) { return events; }
Source:
public List<CorrelationIdentifier> findCorrelationIds(Scope... scope) { List<CorrelationIdentifier> ret = null; for (int i=0; i < correlationIds.size(); i++) { CorrelationIdentifier cid = correlationIds.get(i); for (int j=0; j < scope.length; j++) { if (cid.getScope() == scope[j]) { if (ret == null) { ret = new ArrayList<CorrelationIdentifier>(); } ret.add(cid); } } } return ret == null ? Collections.emptyList() : ret; }

Target:
public List<CorrelationIdentifier> findCorrelationIds(Scope... scope) { List<CorrelationIdentifier> ret = null; for (int i=0; i < correlationIds.size(); i++) { CorrelationIdentifier cid = correlationIds.get(i); for (int j=0; j < scope.length; j++) { if (cid.getScope() == scope[j]) { if (ret == null) { ret = new ArrayList<CorrelationIdentifier>(); } if (!ret.contains(cid)) { ret.add(cid); } } } } return ret == null ? Collections.emptyList() : ret; }
Source:
public static Collection<FunctionDesc> loadHiveUDFs(TajoConf conf) { ArrayList<FunctionDesc> funcList = new ArrayList<>(); String udfdir = conf.getVar(TajoConf.ConfVars.HIVE_UDF_DIR); try { FileSystem localFS = FileSystem.getLocal(conf); Path udfPath = new Path(udfdir); if (!localFS.isDirectory(udfPath)) { return null; } for (FileStatus fstatus : localFS.listStatus(udfPath, (Path path) -> path.getName().endsWith(".jar"))) { URL[] urls = new URL[]{new URL("jar:" + fstatus.getPath().toUri().toURL() + "!/")}; Set<Class<? extends UDF>> udfClasses = getSubclassesFromJarEntry(urls, UDF.class); if (udfClasses != null) { buildFunctionsFromUDF(udfClasses, funcList, "jar:"+urls[0].getPath()); } } } catch (IOException e) { throw new TajoInternalError(e); } return funcList; }

Target:
public static Optional<List<FunctionDesc>> loadHiveUDFs(TajoConf conf) { ArrayList<FunctionDesc> funcList = new ArrayList<>(); String udfdir = conf.getVar(TajoConf.ConfVars.HIVE_UDF_DIR); try { FileSystem fs = FileSystem.getLocal(conf); Path udfPath = new Path(udfdir); if (!fs.isDirectory(udfPath)) { LOG.warn("Hive UDF directory doesn't exist : "+udfdir); return Optional.empty(); } URL urls = Arrays.stream(fs.listStatus(udfPath, (Path path) -> path.getName().endsWith(".jar"))) .map(fstatus -> { try { return new URL("jar:" + fstatus.getPath().toUri().toURL() + "!/"); } catch (MalformedURLException e) { e.printStackTrace(); } return null; }) .toArray(URL[]::new); Set<Class<? extends UDF>> udfClasses = getSubclassesFromJarEntry(urls, UDF.class); buildFunctionsFromUDF(udfClasses, funcList, "jar:"+urls[0].getPath()); } catch (IOException e) { throw new TajoInternalError(e); } return Optional.of(funcList); }
Source:
synchronized public static Number nativeCreate() { long nativePtr = nextNativePtr++; NATIVE_PTR_TO_PARCEL.put(nextNativePtr, new ByteBuffer()); return castNativePtr(nextNativePtr); }

Target:
synchronized public static Number nativeCreate() { long nativePtr = nextNativePtr++; NATIVE_PTR_TO_PARCEL.put(nativePtr, new ByteBuffer()); return castNativePtr(nativePtr); }
Source:
private boolean processAnnotations(RoundEnvironment roundEnv) { for (Element classElement : roundEnv.getElementsAnnotatedWith(RealmClass.class)) { if (!Utils.isImplementingMarkerInterface(classElement)) { Utils.error("A RealmClass annotated object must implement RealmModel or derive from RealmObject.", classElement); } if (!classElement.getKind().equals(ElementKind.CLASS)) { Utils.error("The RealmClass annotation can only be applied to classes.", classElement); return false; } ClassMetaData metadata = new ClassMetaData(processingEnv, (TypeElement) classElement); if (!metadata.isModelClass()) { continue; } Utils.note("Processing class " + metadata.getSimpleClassName()); if (!metadata.generate()) { return false; } classesToValidate.add(metadata); backlinksToValidate.addAll(metadata.getBacklinkFields()); RealmProxyInterfaceGenerator interfaceGenerator = new RealmProxyInterfaceGenerator(processingEnv, metadata); try { interfaceGenerator.generate(); } catch (IOException e) { Utils.error(e.getMessage(), classElement); } RealmProxyClassGenerator sourceCodeGenerator = new RealmProxyClassGenerator(processingEnv, metadata); try { sourceCodeGenerator.generate(); } catch (IOException e) { Utils.error(e.getMessage(), classElement); } catch (UnsupportedOperationException e) { Utils.error(e.getMessage(), classElement); } } return true; }

Target:
private boolean processAnnotations(RoundEnvironment roundEnv) { for (Element classElement : roundEnv.getElementsAnnotatedWith(RealmClass.class)) { if (!Utils.isImplementingMarkerInterface(classElement)) { Utils.error("A RealmClass annotated object must implement RealmModel or derive from RealmObject.", classElement); return false; } if (!classElement.getKind().equals(ElementKind.CLASS)) { Utils.error("The RealmClass annotation can only be applied to classes.", classElement); return false; } ClassMetaData metadata = new ClassMetaData(processingEnv, (TypeElement) classElement); if (!metadata.isModelClass()) { continue; } Utils.note("Processing class " + metadata.getSimpleClassName()); if (!metadata.generate()) { return false; } classesToValidate.add(metadata); backlinksToValidate.addAll(metadata.getBacklinkFields()); RealmProxyInterfaceGenerator interfaceGenerator = new RealmProxyInterfaceGenerator(processingEnv, metadata); try { interfaceGenerator.generate(); } catch (IOException e) { Utils.error(e.getMessage(), classElement); } RealmProxyClassGenerator sourceCodeGenerator = new RealmProxyClassGenerator(processingEnv, metadata); try { sourceCodeGenerator.generate(); } catch (IOException e) { Utils.error(e.getMessage(), classElement); } catch (UnsupportedOperationException e) { Utils.error(e.getMessage(), classElement); } } return true; }
Source:
public List<? extends MetadataInterface> getMetadataInclDefaultDisplay(DocStructInterface inStruct, String inLanguage, boolean inIsPerson, Process inProzess) { List<MetadataTypeInterface> displayMetadataTypes = inStruct.getDisplayMetadataTypes(); if (displayMetadataTypes != null) { for (MetadataTypeInterface mdt : displayMetadataTypes) { if (!(inStruct.getAllMetadataByType(mdt) != null && inStruct.getAllMetadataByType(mdt).size() != 0)) { try { if (mdt.isPerson()) { PersonInterface p = UghImplementation.INSTANCE.createPerson(mdt); p.setRole(mdt.getName()); inStruct.addPerson(p); } else { MetadataInterface md = UghImplementation.INSTANCE.createMetadata(mdt); inStruct.addMetadata(md); } } catch (DocStructHasNoTypeException | MetadataTypeNotAllowedException e) { logger.error(e); } } } } if (inIsPerson) { List<PersonInterface> personInterfaces = inStruct.getAllPersons(); if (personInterfaces != null && !inProzess.getRuleset().isOrderMetadataByRuleset()) { Collections.sort(personInterfaces, new MetadataComparator(inLanguage)); } return personInterfaces; } else { List<MetadataInterface> metadataInterface = inStruct.getAllMetadata(); if (metadataInterface != null && !inProzess.getRuleset().isOrderMetadataByRuleset()) { Collections.sort(metadataInterface, new MetadataComparator(inLanguage)); } return getAllVisibleMetadataHack(inStruct); } }

Target:
public List<? extends MetadataInterface> getMetadataInclDefaultDisplay(DocStructInterface inStruct, String inLanguage, boolean inIsPerson, Process inProzess) { List<MetadataTypeInterface> displayMetadataTypes = inStruct.getDisplayMetadataTypes(); if (displayMetadataTypes != null) { for (MetadataTypeInterface mdt : displayMetadataTypes) { if (!(inStruct.getAllMetadataByType(mdt) != null && inStruct.getAllMetadataByType(mdt).size() != 0)) { try { if (mdt.isPerson()) { PersonInterface p = UghImplementation.INSTANCE.createPerson(mdt); p.setRole(mdt.getName()); inStruct.addPerson(p); } else { MetadataInterface md = UghImplementation.INSTANCE.createMetadata(mdt); inStruct.addMetadata(md); } } catch (DocStructHasNoTypeException | MetadataTypeNotAllowedException e) { logger.error(e); } } } } if (inIsPerson) { List<PersonInterface> person = inStruct.getAllPersons(); if (person != null && !inProzess.getRuleset().isOrderMetadataByRuleset()) { Collections.sort(person, new MetadataComparator(inLanguage)); } return person; } else { List<MetadataInterface> metadata = inStruct.getAllMetadata(); if (metadata != null && !inProzess.getRuleset().isOrderMetadataByRuleset()) { Collections.sort(metadata, new MetadataComparator(inLanguage)); } return getAllVisibleMetadataHack(inStruct); } }
Source:
private byte[] generateSecureRandomBytesWithLength(int length) { byte[] randBytes = new byte[length]; new SecureRandom().nextBytes(randBytes); return randBytes; }

Target:
private byte[] generateSecureRandomBytesWithLength(int length) { byte[] randBytes = new byte[length]; secureRandom.nextBytes(randBytes); return randBytes; }
Source:
private void bindToBrokerAccountService(final Context context, final Callback<BrokerAccountServiceConnection> callback, final BrokerEvent brokerEvent) { Logger.v(TAG, "Binding to BrokerAccountService for caller uid: " + android.os.Process.myUid()); final Intent brokerAccountServiceToBind = getIntentForBrokerAccountService(context); final BrokerAccountServiceConnection connection = new BrokerAccountServiceConnection(); if (brokerEvent != null) { connection.setTelemetryEvent(brokerEvent); brokerEvent.setBrokerAccountServerStartsBinding(); } final CallbackExecutor<BrokerAccountServiceConnection> callbackExecutor = new CallbackExecutor<>(callback); mPendingConnections.put(connection, callbackExecutor); final boolean serviceBound = context.bindService(brokerAccountServiceToBind, connection, Context.BIND_AUTO_CREATE); Logger.v(TAG, "The status for brokerAccountService bindService call is: " + Boolean.valueOf(serviceBound)); if (brokerEvent != null) { brokerEvent.setBrokerAccountServiceBindingSucceed(serviceBound); } if (!serviceBound) { connection.unBindService(context); callback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED)); } }

Target:
private void bindToBrokerAccountService(final Context context, final Callback<BrokerAccountServiceConnection> callback, final BrokerEvent brokerEvent) { Logger.v(TAG, "Binding to BrokerAccountService for caller uid: " + android.os.Process.myUid()); final Intent brokerAccountServiceToBind = getIntentForBrokerAccountService(context); final BrokerAccountServiceConnection connection = new BrokerAccountServiceConnection(); if (brokerEvent != null) { connection.setTelemetryEvent(brokerEvent); brokerEvent.setBrokerAccountServerStartsBinding(); } final CallbackExecutor<BrokerAccountServiceConnection> callbackExecutor = new CallbackExecutor<>(callback); mPendingConnections.put(connection, callbackExecutor); final boolean serviceBound = context.bindService(brokerAccountServiceToBind, connection, Context.BIND_AUTO_CREATE); Logger.v(TAG, "The status for brokerAccountService bindService call is: " + Boolean.valueOf(serviceBound)); if (brokerEvent != null) { brokerEvent.setBrokerAccountServiceBindingSucceed(serviceBound); } if (!serviceBound) { connection.unBindService(context); Logger.e(TAG, "Failed to bind service to broker app", "'bindService' returned false", ADALError.BROKER_BIND_SERVICE_FAILED); callback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED)); } }
Source:
protected void executeVdsBrokerCommand() { vmListReturn = getBroker().getExternalVmList(getParameters().getUrl(), getParameters().getUsername(), getParameters().getPassword(), getParameters().getNamesOfVms()); proceedProxyReturnValue(); List<VM> vms = new ArrayList<>(); List<VM> notDownVms = new ArrayList<>(); for (Map<String, Object> map : vmListReturn.vmList) { VM vm = VdsBrokerObjectsBuilder.buildVmsDataFromExternalProvider(map); if (vm != null) { vm.setOrigin(getParameters().getOriginType()); if (vm.getOrigin() == OriginType.KVM && VmDeviceCommonUtils.isVirtIoScsiDiskInterfaceExists(vm.getStaticData())) { VmDeviceCommonUtils.addVirtIoScsiDevice(vm.getStaticData()); } vms.add(vm); if (!vm.isDown()) { notDownVms.add(vm); } } } logNonDownVms(notDownVms); setReturnValue(vms); }

Target:
protected void executeVdsBrokerCommand() { vmListReturn = getBroker().getExternalVmList(getParameters().getUrl(), getParameters().getUsername(), getParameters().getPassword(), getParameters().getNamesOfVms()); proceedProxyReturnValue(); List<VM> vms = new ArrayList<>(); List<VM> notDownVms = new ArrayList<>(); for (Map<String, Object> map : vmListReturn.vmList) { VM vm = VdsBrokerObjectsBuilder.buildVmsDataFromExternalProvider(map); if (vm != null) { vm.setOrigin(getParameters().getOriginType()); if (vm.getOrigin() == OriginType.KVM) { if (VmDeviceCommonUtils.isVirtIoScsiDiskInterfaceExists(vm.getStaticData())) { VmDeviceCommonUtils.addVirtIoScsiDevice(vm.getStaticData()); } } vms.add(vm); if (!vm.isDown()) { notDownVms.add(vm); } } } logNonDownVms(notDownVms); setReturnValue(vms); }
Source:
SetSaslClientFactoryAuthenticationConfiguration(final AuthenticationConfiguration parent, final Supplier<SaslClientFactory> saslClientFactorySupplier) { super(parent.without(SetSaslClientFactoryAuthenticationConfiguration.class)); this.saslClientFactorySupplier = saslClientFactorySupplier; }

Target:
SetSaslClientFactoryAuthenticationConfiguration(final AuthenticationConfiguration parent, final Supplier<SaslClientFactory> saslClientFactorySupplier) { super(parent); this.saslClientFactorySupplier = saslClientFactorySupplier; }
Source:
void parseServerAddress(Connection connection, Span span) { try { URI url = URI.create(connection.getMetaData().getURL().substring(5)); String actualServiceName = remoteServiceName; final Matcher matcher = URL_SERVICE_NAME_FINDER.matcher(url.toString()); if(matcher.find() && matcher.groupCount() == 1) { final String parsedServiceName = matcher.group(1); if(parsedServiceName != null && !parsedServiceName.isEmpty()) { actualServiceName = parsedServiceName; } } Endpoint.Builder builder = Endpoint.builder().port(url.getPort()); boolean parsed = builder.parseIp(url.getHost()); if (actualServiceName == null || "".equals(actualServiceName)) { String databaseName = connection.getCatalog(); if (databaseName != null && !databaseName.isEmpty()) { builder.serviceName(databaseName); } else { if (!parsed) return; builder.serviceName(""); } } else { builder.serviceName(actualServiceName); } span.remoteEndpoint(builder.build()); } catch (Exception e) { } }

Target:
void parseServerAddress(Connection connection, Span span) { try { URI url = URI.create(connection.getMetaData().getURL().substring(5)); String defaultRemoteServiceName = remoteServiceName; Matcher matcher = URL_SERVICE_NAME_FINDER.matcher(url.toString()); if (matcher.find() && matcher.groupCount() == 1) { String parsedServiceName = matcher.group(1); if (parsedServiceName != null && !parsedServiceName.isEmpty()) { defaultRemoteServiceName = parsedServiceName; } } Endpoint.Builder builder = Endpoint.builder().port(url.getPort()); boolean parsed = builder.parseIp(url.getHost()); if (defaultRemoteServiceName == null || "".equals(defaultRemoteServiceName)) { String databaseName = connection.getCatalog(); if (databaseName != null && !databaseName.isEmpty()) { builder.serviceName(databaseName); } else { if (!parsed) return; builder.serviceName(""); } } else { builder.serviceName(defaultRemoteServiceName); } span.remoteEndpoint(builder.build()); } catch (Exception e) { } }
Source:
public AuditAssociationQuery<? extends AuditQuery> traverseRelation( String associationName, JoinType joinType, String alias) { if ( !selectEntitiesOnly ) { throw new IllegalStateException( "Audit association queries only permitted while selecting only entities." ); } AbstractAuditAssociationQuery<AuditQueryImplementor> query = associationQueryMap.get( associationName ); if ( query == null ) { query = new RevisionsOfEntityAssociationQuery<>( enversService, versionsReader, this, qb, associationName, joinType, aliasToEntityNameMap, REFERENCED_ENTITY_ALIAS, alias ); addAssociationQuery( associationName, query ); } return query; }

Target:
public AuditAssociationQuery<? extends AuditQuery> traverseRelation( String associationName, JoinType joinType, String alias) { if ( !selectEntitiesOnly ) { throw new IllegalStateException( "Audit association queries are only permitted when the query is created with selectEntitiesOnly: true." ); } return associationQueryMap.computeIfAbsent( associationName, name -> { AbstractAuditAssociationQuery<AuditQueryImplementor> query = new RevisionsOfEntityAssociationQuery<>( enversService, versionsReader, this, qb, name, joinType, aliasToEntityNameMap, REFERENCED_ENTITY_ALIAS, alias); addAssociationQuery( name, query ); return query; } ); }
Source:
private SimpleObject getVisits(RequestContext context, String patientParameter, String includeInactiveParameter, Date minStartDate) { boolean includeAll = Boolean.parseBoolean(context.getParameter("includeAll")); Collection<Patient> patients = patientParameter == null ? null : Arrays.asList(getPatient(patientParameter)); boolean includeInactive = includeInactiveParameter == null ? true : Boolean.parseBoolean(includeInactiveParameter); return new NeedsPaging<Visit>(Context.getVisitService().getVisits(null, patients, null, null, minStartDate, null, null, null, null, includeInactive, includeAll), context).toSimpleObject(this); }

Target:
private SimpleObject getVisits(RequestContext context, String patientParameter, String includeInactiveParameter, Date minStartDate) { Collection<Patient> patients = patientParameter == null ? null : Arrays.asList(getPatient(patientParameter)); boolean includeInactive = includeInactiveParameter == null ? true : Boolean.parseBoolean(includeInactiveParameter); return new NeedsPaging<Visit>(Context.getVisitService().getVisits(null, patients, null, null, minStartDate, null, null, null, null, includeInactive, context.getIncludeAll()), context).toSimpleObject(this); }
Source:
public void testExtractChunkLabel() { String input = "```{r testingChunks, echo=FALSE}"; String result = ChunkContextUi.extractChunkLabel(input); assertTrue(result.equals("testingChunks")); }

Target:
public void testExtractChunkLabel() { List<Pair<String, String>> testList = new ArrayList<>(); testList.add(new Pair<>("```{r echo=FALSE}", "")); testList.add(new Pair<>("```{r testingChunks}", "testingChunks")); testList.add(new Pair<>("```{r testingChunks, echo=FALSE}", "testingChunks")); for (Pair<String, String> td : testList) { String result = ChunkContextUi.extractChunkLabel(td.first); assertTrue(result.equals(td.second)); } }
Source:
public QueryResult<Alert> query(final AlertQuery query) { assertIsOpen(); LOGGER.debug() .setMessage("Querying") .addData("query", query) .log(); final PagedList<models.ebean.Alert> pagedAlerts = _alertQueryGenerator.createAlertQuery(query); final String etag = Long.toHexString(pagedAlerts.getList().stream() .map(alert -> alert.getUpdatedAt().after(alert.getCreatedAt()) ? alert.getUpdatedAt() : alert.getCreatedAt()) .max(Timestamp::compareTo) .orElse(new Timestamp(0)) .getTime()); final List<Alert> values = new ArrayList<>(); pagedAlerts.getList().forEach(ebeanAlert -> { final Alert result = new DefaultAlert.Builder() .setCluster(ebeanAlert.getCluster()) .setContext(ebeanAlert.getContext()) .setId(ebeanAlert.getUuid()) .setMetric(ebeanAlert.getMetric()) .setName(ebeanAlert.getName()) .setOperator(ebeanAlert.getOperator()) .setPeriod(Period.seconds(ebeanAlert.getPeriod())) .setService(ebeanAlert.getService()) .setStatistic(ebeanAlert.getStatistic()) .setValue(new DefaultQuantity.Builder() .setValue(ebeanAlert.getQuantityValue()) .setUnit(ebeanAlert.getQuantityUnit()) .build()) .setExtensions(mergeExtensions(ebeanAlert.getNagiosExtension())) .build(); values.add(result); }); return new DefaultQueryResult<>(values, pagedAlerts.getTotalRowCount(), etag); }

Target:
public QueryResult<Alert> query(final AlertQuery query) { assertIsOpen(); LOGGER.debug() .setMessage("Querying") .addData("query", query) .log(); final PagedList<models.ebean.Alert> pagedAlerts = _alertQueryGenerator.createAlertQuery(query); final Long etag = _alertQueryGenerator.getEtag(); final List<Alert> values = new ArrayList<>(); pagedAlerts.getList().forEach(ebeanAlert -> values.add(convertFromEbeanAlert(ebeanAlert))); return new DefaultQueryResult<>(values, pagedAlerts.getTotalRowCount(), etag.toString()); }
Source:
public void testPartialRead() throws IOException { GoogleCloudStorage rawStorage = createGoogleCloudStorage(); final int segmentSize = 553; final int segmentCount = 5; StorageResourceId resourceId = new StorageResourceId(BUCKET_NAME, "testReadPartialObjects_Object"); byte[] data = writeObject(rawStorage, resourceId, segmentCount * segmentSize); byte[][] readSegments = new byte[segmentCount][segmentSize]; try (SeekableByteChannel readChannel = rawStorage.open(resourceId)) { for (int i = 0; i < segmentCount; i++) { ByteBuffer segmentBuffer = ByteBuffer.wrap(readSegments[i]); int bytesRead = readChannel.read(segmentBuffer); assertThat(bytesRead).isEqualTo(segmentSize); byte[] expectedSegment = Arrays.copyOfRange( data, i * segmentSize, (i * segmentSize) + segmentSize ); assertWithMessage("Unexpected segment data read.") .that(readSegments[i]) .isEqualTo(expectedSegment); } } }

Target:
public void testPartialRead() throws IOException { GoogleCloudStorage rawStorage = createGoogleCloudStorage(); int segmentSize = 553; int segmentCount = 5; StorageResourceId resourceId = new StorageResourceId(BUCKET_NAME, "testReadPartialObjects_Object"); byte[] data = writeObject(rawStorage, resourceId, segmentCount * segmentSize); byte[][] readSegments = new byte[segmentCount][segmentSize]; try (SeekableByteChannel readChannel = rawStorage.open(resourceId)) { for (int i = 0; i < segmentCount; i++) { ByteBuffer segmentBuffer = ByteBuffer.wrap(readSegments[i]); int bytesRead = readChannel.read(segmentBuffer); assertThat(bytesRead).isEqualTo(segmentSize); byte[] expectedSegment = Arrays.copyOfRange( data, i * segmentSize, i * segmentSize + segmentSize); assertWithMessage("Unexpected segment data read.") .that(readSegments[i]) .isEqualTo(expectedSegment); } } }
Source:
public void redirectCarriesQueryAndFragment() throws IOException { MatcherAssert.assertThat( new RsPrint( new TkRedirect("<LINK_0>").act( new RqFake("GET", "/hi?a=1#test") ) ).print(), Matchers.equalTo( Joiner.on(TkRedirectTest.NEWLINE).join( "HTTP/1.1 303 See Other", String.format( TkRedirectTest.LOCATION, "<LINK_0>&a=1#test" ), "", "" ) ) ); }

Target:
public void redirectCarriesQueryAndFragment() throws IOException { MatcherAssert.assertThat( new TkRedirect("<LINK_0>").act( new RqFake("GET", "/hi?a=1#test") ), new HmRsHeader( "Location", "<LINK_0>&a=1#test" ) ); }