auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testSendFromExecuteBlocking() throws Exception { String expectedBody = TestUtils.randomAlphaString(20); CountDownLatch receivedLatch = new CountDownLatch(1); startNodes(2); vertices[1].eventBus().<String>consumer(ADDRESS1, msg -> { assertEquals(expectedBody, msg.body()); receivedLatch.countDown(); }).completionHandler(ar -> { assertTrue(ar.succeeded()); vertices[0].deployVerticle(new AbstractVerticle() { @Override public void start() throws Exception { vertx().executeBlocking(fut -> { vertices[0].eventBus().send(ADDRESS1, expectedBody); try { awaitLatch(receivedLatch); } catch (InterruptedException e) { Thread.interrupted(); fut.fail(e); } fut.complete(); }, ar -> { if (ar.succeeded()) { testComplete(); } else { fail(ar.cause()); } }); } }); }); await(); }

Target:
public void testSendFromExecuteBlocking() throws Exception { String expectedBody = TestUtils.randomAlphaString(20); CountDownLatch receivedLatch = new CountDownLatch(1); startNodes(2); vertices[1].eventBus().<String>consumer(ADDRESS1, msg -> { assertEquals(expectedBody, msg.body()); receivedLatch.countDown(); }).completionHandler(ar -> { assertTrue(ar.succeeded()); vertices[0].executeBlocking(fut -> { vertices[0].eventBus().send(ADDRESS1, expectedBody); try { awaitLatch(receivedLatch); } catch (InterruptedException e) { Thread.interrupted(); fut.fail(e); } fut.complete(); }, ar2 -> { if (ar2.succeeded()) { testComplete(); } else { fail(ar2.cause()); } }); }); await(); }
Source:
default int compareToSequence( SequenceValue other, Comparator<AnyValue> comparator ) { int i = 0; int x = 0; int length = Math.min( length(), other.length() ); while ( x == 0 && i < length ) { x = comparator.compare( value( i ), other.value( i ) ); i++; } if ( x == 0 ) { x = length() - other.length(); } return x; }

Target:
default int compareToSequence( SequenceValue other, Comparator<AnyValue> comparator ) { IterationPreference pref = iterationPreference(); IterationPreference otherPref = other.iterationPreference(); if ( pref == RANDOM_ACCESS && otherPref == RANDOM_ACCESS ) { return compareUsingRandomAccess( this, other, comparator ); } else { return compareUsingIterators( this, other, comparator ); } }
Source:
private boolean canScrollUp(View view, float x, float y) { if (view instanceof ViewGroup) { ViewGroup vg = (ViewGroup) view; for (int i = 0; i < vg.getChildCount(); i++) { View child = vg.getChildAt(i); int childLeft = child.getLeft() - view.getScrollX(); int childTop = child.getTop() - view.getScrollY(); int childRight = child.getRight() - view.getScrollX(); int childBottom = child.getBottom() - view.getScrollY(); boolean intersects = childLeft < x && x < childRight && childTop < y && y < childBottom; if (intersects && canScrollUp(child, x - childLeft, y - childTop)) { return true; } } } return view.canScrollVertically(-1); }

Target:
private boolean canScrollUp(View view, float x, float y) { if (view instanceof ViewGroup) { ViewGroup vg = (ViewGroup) view; for (int i = 0; i < vg.getChildCount(); i++) { View child = vg.getChildAt(i); int childLeft = child.getLeft() - view.getScrollX(); int childTop = child.getTop() - view.getScrollY(); int childRight = child.getRight() - view.getScrollX(); int childBottom = child.getBottom() - view.getScrollY(); boolean intersects = x > childLeft && x < childRight && y > childTop && y < childBottom; if (intersects && canScrollUp(child, x - childLeft, y - childTop)) { return true; } } } return view.canScrollVertically(-1); }
Source:
public void shouldParseVepOutputWithExtraFields() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(VEP_VERSION, VEP_CACHE_VERSION); Annotation annotation = lineMapper.mapLine(VepOutputContent.vepOutputContentWithExtraFieldsSingleAnnotation, 0); Set<ConsequenceType> consequenceTypes = annotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertEquals(1, consequenceTypes.size()); ConsequenceType consequenceType = consequenceTypes.iterator().next(); Score polyphen = consequenceType.getPolyphen(); Score sifts = consequenceType.getSift(); assertNotNull(polyphen); assertNotNull(sifts); Score expectedSift = new Score(0.07, "tolerated"); Score expectedPolyphen = new Score(0.859, "possibly_damaging"); assertEquals(sifts, expectedSift); assertEquals(polyphen, expectedPolyphen); }

Target:
public void shouldParseVepOutputWithExtraFields() { AnnotationLineMapper lineMapper = new AnnotationLineMapper(VEP_VERSION, VEP_CACHE_VERSION); Annotation annotation = lineMapper.mapLine(VepOutputContent.vepOutputContentWithExtraFieldsSingleAnnotation, 0); Set<ConsequenceType> consequenceTypes = annotation.getConsequenceTypes(); assertNotNull(consequenceTypes); assertEquals(1, consequenceTypes.size()); ConsequenceType consequenceType = consequenceTypes.iterator().next(); Score polyphen = consequenceType.getPolyphen(); Score sifts = consequenceType.getSift(); assertNotNull(polyphen); assertNotNull(sifts); Score expectedSift = new Score(0.07, "tolerated"); Score expectedPolyphen = new Score(0.859, "possibly_damaging"); assertEquals(expectedSift, sifts); assertEquals(expectedPolyphen, polyphen); }
Source:
private void checkUploadRequirements(BlobProperties blobProperties) throws RestServiceException { if (RestUtils.isChunkUpload(restRequest.getArgs())) { RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.SESSION, true); long maxChunkSize = RestUtils.getLongHeader(restRequest.getArgs(), RestUtils.Headers.MAX_UPLOAD_SIZE, true); if (maxChunkSize > chunkUploadMaxChunkSize) { throw new RestServiceException("Invalid max chunk size: " + maxChunkSize, RestServiceErrorCode.InvalidArgs); } long chunkTtl = blobProperties.getTimeToLiveInSeconds(); if (chunkTtl <= 0 || chunkTtl > frontendConfig.chunkUploadInitialChunkTtlSecs) { throw new RestServiceException("Invalid chunk upload TTL: " + chunkTtl, RestServiceErrorCode.InvalidArgs); } } }

Target:
private void checkUploadRequirements(BlobProperties blobProperties) throws RestServiceException { if (RestUtils.isChunkUpload(restRequest.getArgs())) { RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.SESSION, true); RestUtils.getLongHeader(restRequest.getArgs(), RestUtils.Headers.MAX_UPLOAD_SIZE, true); long chunkTtl = blobProperties.getTimeToLiveInSeconds(); if (chunkTtl <= 0 || chunkTtl > frontendConfig.chunkUploadInitialChunkTtlSecs) { throw new RestServiceException("Invalid chunk upload TTL: " + chunkTtl, RestServiceErrorCode.InvalidArgs); } } }
Source:
public void testMultipleEventBasedStartEventsTimerDifferentPaths() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-MultipleStartEventProcessDifferentPaths.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); final List<Long> list = new ArrayList<Long>(); ksession.addEventListener(new DefaultProcessEventListener() { public void afterProcessStarted(ProcessStartedEvent event) { list.add(event.getProcessInstance().getId()); } }); assertEquals(0, list.size()); Thread.sleep(2100); assertEquals(2, list.size()); List<WorkItem> workItems = workItemHandler.getWorkItems(); for (WorkItem workItem : workItems) { long processInstanceId = ((WorkItemImpl) workItem).getProcessInstanceId(); ProcessInstance processInstance = ksession .getProcessInstance(processInstanceId); ksession = restoreSession(ksession, true); assertNotNull(workItem); assertEquals("john", workItem.getParameter("ActorId")); ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null); assertProcessInstanceFinished(processInstance, ksession); assertNodeTriggered(processInstanceId, "StartTimer", "Script 2", "User task", "End"); } }

Target:
public void testMultipleEventBasedStartEventsTimerDifferentPaths() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-MultipleStartEventProcessDifferentPaths.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); final List<Long> list = new ArrayList<Long>(); ksession.addEventListener(new DefaultProcessEventListener() { public void afterProcessStarted(ProcessStartedEvent event) { list.add(event.getProcessInstance().getId()); } }); assertEquals(0, list.size()); Thread.sleep(2000 + EXTRA_SLEEP_TIME); assertEquals(2, list.size()); List<WorkItem> workItems = workItemHandler.getWorkItems(); for (WorkItem workItem : workItems) { long processInstanceId = ((WorkItemImpl) workItem).getProcessInstanceId(); ProcessInstance processInstance = ksession .getProcessInstance(processInstanceId); ksession = restoreSession(ksession, true); assertNotNull(workItem); assertEquals("john", workItem.getParameter("ActorId")); ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null); assertProcessInstanceFinished(processInstance, ksession); assertNodeTriggered(processInstanceId, "StartTimer", "Script 2", "User task", "End"); } }
Source:
public void testExecuteQueryCommand() { Guid spId = Guid.NewGuid(); when(getQueryParameters().getStoragePoolId()).thenReturn(spId); when(getQueryParameters().isLocalFsOnly()).thenReturn(false); VDS vds = new VDS(); vds.setStoragePoolId(spId); List<VDS> result = Collections.singletonList(vds); VdsDAO vdsDAOMock = mock(VdsDAO.class); when(vdsDAOMock.getSpmCandidates(spId, getQueryParameters().isLocalFsOnly())).thenReturn(result); when(getDbFacadeMockInstance().getVdsDao()).thenReturn(vdsDAOMock); getQuery().executeQueryCommand(); assertEquals("Wrong roles returned", result, getQuery().getQueryReturnValue().getReturnValue()); }

Target:
public void testExecuteQueryCommand() { Guid spId = Guid.NewGuid(); when(getQueryParameters().getStoragePoolId()).thenReturn(spId); when(getQueryParameters().isLocalFsOnly()).thenReturn(false); VDS vds = new VDS(); vds.setStoragePoolId(spId); List<VDS> result = Collections.singletonList(vds); VdsDAO vdsDAOMock = mock(VdsDAO.class); when(vdsDAOMock.getSpmCandidates(spId, getQueryParameters().isLocalFsOnly())).thenReturn(result); when(getDbFacadeMockInstance().getVdsDao()).thenReturn(vdsDAOMock); getQuery().executeQueryCommand(); assertEquals("Wrong Vds returned", result, getQuery().getQueryReturnValue().getReturnValue()); }
Source:
public String docs() { return "mixed {ivar | key[, namespace, ...]} This function imports a value from the global value" + " register. In the first mode, it looks for an ivariable with the specified" + " name, and stores the value in the variable, and returns void. In the" + " second mode, it looks for a value stored with the specified key, and" + " returns that value. Items can be stored with the export function. If" + " the specified ivar doesn't exist, the ivar will be assigned an empty" + " string, and if the specified string key doesn't exist, null is returned." + " See the documentation on [[CommandHelper/import-export|imports/exports]]" + " for more information."; }

Target:
public String docs() { return "mixed {ivar | key[, namespace, ...,]} This function imports a value from the global value" + " register. In the first mode, it looks for an ivariable with the specified" + " name, and stores the value in the variable, and returns void. In the" + " second mode, it looks for a value stored with the specified key, and" + " returns that value. Items can be stored with the export function. If" + " the specified ivar doesn't exist, the ivar will be assigned an empty" + " string, and if the specified string key doesn't exist, null is returned." + " See the documentation on [[CommandHelper/import-export|imports/exports]]" + " for more information."; }
Source:
public synchronized static HDF5Library getLibrary() { if (global == null) { global = new HDF5Library(); } return global; }

Target:
public static HDF5Library getLibrary() { if (global == null) { global = new HDF5Library(); } return global; }
Source:
public FileServiceSasQueryParameters generateSasQueryParameters( StorageSharedKeyCredential storageSharedKeyCredentials) { Utility.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); final String resource; if (ImplUtils.isNullOrEmpty(filePath)) { resource = Constants.UrlConstants.SAS_SHARE_CONSTANT; if (permissions != null) { permissions = ShareSasPermission.parse(permissions).toString(); } } else { resource = Constants.UrlConstants.SAS_FILE_CONSTANT; if (permissions != null) { permissions = FileSasPermission.parse(permissions).toString(); } } if (ImplUtils.isNullOrEmpty(version)) { version = FileServiceVersion.getLatest().getVersion(); } String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName(), shareName, filePath); String stringToSign = stringToSign(canonicalName); String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return new FileServiceSasQueryParameters(this.version, this.protocol, this.startTime, this.expiryTime, this.sasIpRange, this.identifier, resource, this.permissions, signature, this.cacheControl, this.contentDisposition, this.contentEncoding, this.contentLanguage, this.contentType); }

Target:
public FileServiceSasQueryParameters generateSasQueryParameters( StorageSharedKeyCredential storageSharedKeyCredentials) { Utility.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); final String resource; if (ImplUtils.isNullOrEmpty(filePath)) { resource = SAS_SHARE_CONSTANT; if (permissions != null) { permissions = ShareSasPermission.parse(permissions).toString(); } } else { resource = SAS_FILE_CONSTANT; if (permissions != null) { permissions = FileSasPermission.parse(permissions).toString(); } } if (ImplUtils.isNullOrEmpty(version)) { version = FileServiceVersion.getLatest().getVersion(); } String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName(), shareName, filePath); String stringToSign = stringToSign(canonicalName); String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return new FileServiceSasQueryParameters(this.version, this.protocol, this.startTime, this.expiryTime, this.sasIpRange, this.identifier, resource, this.permissions, signature, this.cacheControl, this.contentDisposition, this.contentEncoding, this.contentLanguage, this.contentType); }
Source:
public void testNativeFilterWithLargeAggSetInSlicer() { propSaver.set( MondrianProperties.instance() .AlertNativeEvaluationUnsupported, "ERROR"); final String query = "with member customers.agg as " + "'Aggregate(Except(Customers.[Name].members, " + "{[Customers].[USA].[OR].[Corvallis].[Judy Doolittle]} ))' " + " select filter(gender.gender.members, measures.[unit sales] >131500)" + " on 0 from sales " + " where customers.agg"; final String message = "The results of native and non-native evaluations should be equal"; verifySameNativeAndNot(query, message, getTestContext()); }

Target:
public void testNativeFilterWithLargeAggSetInSlicer() { final String query = "with member customers.agg as " + "'Aggregate(Except(Customers.[Name].members, " + "{[Customers].[USA].[OR].[Corvallis].[Judy Doolittle]} ))' " + " select filter(gender.gender.members, measures.[unit sales] >131500)" + " on 0 from sales " + " where customers.agg"; final String message = "The results of native and non-native evaluations should be equal"; verifySameNativeAndNot(query, message, getTestContext()); propSaver.set( MondrianProperties.instance() .AlertNativeEvaluationUnsupported, "ERROR"); propSaver.set(propSaver.properties.EnableNativeFilter, true); Appender appenderMock = mock(Appender.class); try { final Logger logger = Logger.getLogger(RolapUtil.class); logger.addAppender(appenderMock); executeQuery(query); } catch (NativeEvaluationUnsupportedException e) { verify(appenderMock) .doAppend(argThat( new ArgumentMatcher<LoggingEvent>() { @Override public boolean matches(Object item) { String message = "Unable to use native SQL evaluation for 'Filter'; reason: " + MondrianResource.instance() .MembersQuantityExceedsMaxConstraints.str("10280"); return message.equals( ((LoggingEvent) item).getMessage().toString()); } })); return; } fail("NativeEvaluationUnsupportedException was expected"); }
Source:
protected I[] getBuckets() { return (I[]) buckets; }

Target:
protected I[] getBuckets() { return buckets; }
Source:
public void start() { synchronized (started) { if (!started.get()) { exec.scheduleAtFixedRate( new ConsumerRunnable(), influxdbEmitterConfig.getFlushDelay(), influxdbEmitterConfig.getFlushPeriod(), TimeUnit.MILLISECONDS ); started.set(true); } } }

Target:
public void start() { synchronized (started) { if (!started.get()) { exec.scheduleAtFixedRate( () -> transformAndSendToInfluxdb(eventsQueue), influxdbEmitterConfig.getFlushDelay(), influxdbEmitterConfig.getFlushPeriod(), TimeUnit.MILLISECONDS ); started.set(true); } } }
Source:
public static String tr(String text, Object o1, Object o2, Object o3) { return text == null ? "" : getI18n().tr(text, o1, o2, o3); }

Target:
public static String tr(String text, Object o1, Object o2, Object o3) { return text == null ? null : getI18n().tr(text, o1, o2, o3); }
Source:
public List<Item> getApproximateItemsQuickly() { return getItemsAsList(); }

Target:
public List<Item> getApproximateItemsQuickly() { return Arrays.asList(getItems()); }
Source:
private void initChangeActions(ChangeInfo info, boolean hasUser) { NativeMap<ActionInfo> actions = info.has_actions() ? info.actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (hasUser) { a2b(actions, "abandon", abandon); a2b(actions, "/", deleteDraftChange); a2b(actions, "restore", restore); a2b(actions, "revert", revert); for (String id : filterNonCore(actions)) { add(new ActionButton(info, actions.get(id))); } } }

Target:
private void initChangeActions(ChangeInfo info, boolean hasUser) { NativeMap<ActionInfo> actions = info.has_actions() ? info.actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (hasUser) { a2b(actions, "/", deleteChange); a2b(actions, "abandon", abandon); a2b(actions, "restore", restore); a2b(actions, "revert", revert); for (String id : filterNonCore(actions)) { add(new ActionButton(info, actions.get(id))); } } }
Source:
public boolean isSaplingAt(World world, BlockPos pos, BlockState blockState) { return ArboricultureBlocks.SAPLING_GE.getBlock() == blockState.getBlock(); }

Target:
public boolean isSaplingAt(World world, BlockPos pos, BlockState blockState) { return ArboricultureBlocks.SAPLING_GE.blockEqual(blockState); }
Source:
public ElementName[] getValidMorphElements() { final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (!canMorphElement(currentElement)) { return new ElementName[0]; } final IValidator validator = document.getValidator(); final IElement parent = currentElement.getParentElement(); final List<QualifiedName> candidates = createCandidatesList(validator, parent, IValidator.PCDATA, currentElement.getQualifiedName()); if (candidates.isEmpty()) { return new ElementName[0]; } final List<QualifiedName> content = Node.getNodeNames(currentElement.children()); for (final Iterator<QualifiedName> iter = candidates.iterator(); iter.hasNext();) { if (!canContainContent(validator, iter.next(), content)) { iter.remove(); } } Collections.sort(candidates, new QualifiedNameComparator()); return toElementNames(parent, candidates); }

Target:
public ElementName[] getValidMorphElements() { final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (!canMorphElement(currentElement)) { return new ElementName[0]; } final IValidator validator = document.getValidator(); final IElement parent = currentElement.getParentElement(); final List<QualifiedName> candidates = createCandidatesList(validator, parent, IValidator.PCDATA, currentElement.getQualifiedName()); if (candidates.isEmpty()) { return new ElementName[0]; } final List<QualifiedName> content = Node.getNodeNames(currentElement.children()); final List<QualifiedName> nodesBefore = Node.getNodeNames(parent.children().before(currentElement.getStartOffset())); final List<QualifiedName> nodesAfter = Node.getNodeNames(parent.children().after(currentElement.getEndOffset())); for (final Iterator<QualifiedName> iter = candidates.iterator(); iter.hasNext();) { final QualifiedName candidate = iter.next(); if (!canContainContent(validator, candidate, content)) { iter.remove(); } else if (!isValidChild(validator, parent.getQualifiedName(), candidate, nodesBefore, nodesAfter)) { iter.remove(); } } Collections.sort(candidates, new QualifiedNameComparator()); return toElementNames(parent, candidates); }
Source:
public void testRequestTimeout() throws Exception { conf = new Configuration(); conf.setInt(REQUEST_TIMEOUT, 10); fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); AmazonS3 s3 = fs.getAmazonS3ClientForTesting("Request timeout"); assertNotNull(s3); ClientConfiguration awsConf = getField(s3, ClientConfiguration.class, "clientConfiguration"); assertEquals(10, awsConf.getRequestTimeout()); }

Target:
public void testRequestTimeout() throws Exception { conf = new Configuration(); conf.set(REQUEST_TIMEOUT, "120"); fs = S3ATestUtils.createTestFileSystem(conf); AmazonS3 s3 = fs.getAmazonS3ClientForTesting("Request timeout (ms)"); ClientConfiguration awsConf = getField(s3, ClientConfiguration.class, "clientConfiguration"); assertEquals("Configured " + REQUEST_TIMEOUT + " is different than what AWS sdk configuration uses internally", 120000, awsConf.getRequestTimeout()); }
Source:
public Array getArray(int columnIndex) throws SQLException { checkCursorState(); ColumnProjector projector = rowProjector.getColumnProjector(columnIndex-1); int arrayIndex = projector.getArrayIndex(); PDataType type = projector.getExpression().getDataType(); Object value = null; if (arrayIndex != -1) { value = projector.getValue(currentRow, type, ptr, arrayIndex); } else { value = projector.getValue(currentRow, type, ptr); } if (wasNull = (value == null)) { return null; } return (Array)value; }

Target:
public Array getArray(int columnIndex) throws SQLException { checkCursorState(); ColumnProjector projector = rowProjector.getColumnProjector(columnIndex-1); Array value = (Array)projector.getValue(currentRow, projector.getExpression().getDataType(), ptr); wasNull = (value == null); return value; }
Source:
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http://" + authority + "/path").getPort() != -1; }

Target:
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http://" + authority).getPort() != -1; }
Source:
public void setTabSelected(int position) { mSelectedTabIndex = position; final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = i == position; child.setSelected(isSelected); if (isSelected) { animateToTab(position); } } if (isCollapsed()) { mTabSpinner.setSelection(position); } }

Target:
public void setTabSelected(int position) { mSelectedTabIndex = position; if (isCollapsed()) { mTabSpinner.setSelection(position); } else { setTabHostSelection(position); } }
Source:
public ValidationResult validate() { Collection<NetworkAttachment> attachmentsToConfigure = getAttachmentsToConfigure(); ValidationResult vr = ValidationResult.VALID; vr = skipValidation(vr) ? vr : new NicLabelValidator(params, existingInterfacesMap, bondsMap, hostSetupNetworksValidatorHelper).validate(); vr = skipValidation(vr) ? vr : validNewOrModifiedNetworkAttachments(); vr = skipValidation(vr) ? vr : validRemovedNetworkAttachments(); vr = skipValidation(vr) ? vr : validNewOrModifiedBonds(); vr = skipValidation(vr) ? vr : validRemovedBonds(attachmentsToConfigure); vr = skipValidation(vr) ? vr : attachmentsDontReferenceSameNetworkDuplicately(attachmentsToConfigure); vr = skipValidation(vr) ? vr : networksUniquelyConfiguredOnHost(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateNetworkExclusiveOnNics(attachmentsToConfigure); vr = skipValidation(vr) ? vr : new NetworkMtuValidator(networkBusinessEntityMap).validateMtu( attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateCustomProperties(); vr = skipValidation(vr) ? vr : validateQos(attachmentsToConfigure); vr = skipValidation(vr) ? vr : createUnmanagedNetworkValidator().validate(params, existingInterfaces, existingInterfacesMap); return vr; }

Target:
public ValidationResult validate() { Collection<NetworkAttachment> attachmentsToConfigure = getAttachmentsToConfigure(); ValidationResult vr = ValidationResult.VALID; vr = skipValidation(vr) ? vr : new NicLabelValidator(params, existingInterfacesMap, bondsMap, hostSetupNetworksValidatorHelper).validate(); vr = skipValidation(vr) ? vr : validNewOrModifiedNetworkAttachments(); vr = skipValidation(vr) ? vr : validRemovedNetworkAttachments(); vr = skipValidation(vr) ? vr : validNewOrModifiedBonds(); vr = skipValidation(vr) ? vr : validRemovedBonds(attachmentsToConfigure); vr = skipValidation(vr) ? vr : attachmentsDontReferenceSameNetworkDuplicately(attachmentsToConfigure); vr = skipValidation(vr) ? vr : networksUniquelyConfiguredOnHost(attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateNetworkExclusiveOnNics(attachmentsToConfigure); vr = skipValidation(vr) ? vr : new NetworkMtuValidator(networkBusinessEntityMap).validateMtu( attachmentsToConfigure); vr = skipValidation(vr) ? vr : validateCustomProperties(); vr = skipValidation(vr) ? vr : validateQos(attachmentsToConfigure); vr = skipValidation(vr) ? vr : unmanagedNetworkValidator.validate(params, existingInterfaces, existingInterfacesMap); return vr; }
Source:
public static EnrichedFlow buildEnrichedFlow(FlowDocument flowDocument) { EnrichedFlow enrichedFlow = new EnrichedFlow(flowDocument.getFlow()); enrichedFlow.setApplication(flowDocument.getApplication()); enrichedFlow.setHost(flowDocument.getHost()); enrichedFlow.setLocation(flowDocument.getLocation()); enrichedFlow.setDstLocality(matchLocality(flowDocument.getDstLocality())); enrichedFlow.setSrcLocality(matchLocality(flowDocument.getSrcLocality())); enrichedFlow.setFlowLocality(matchLocality(flowDocument.getFlowLocality())); enrichedFlow.setSrcNodeInfo(buildNodeInfo(flowDocument.getNodeSrc())); enrichedFlow.setDstNodeInfo(buildNodeInfo(flowDocument.getNodeDst())); enrichedFlow.setExporterNodeInfo(buildNodeInfo(flowDocument.getNodeExporter())); return enrichedFlow; }

Target:
public static EnrichedFlow buildEnrichedFlow(FlowDocument flowDocument) { EnrichedFlow enrichedFlow = new EnrichedFlow(flowDocument.getFlow()); enrichedFlow.setApplication(flowDocument.getApplication()); enrichedFlow.setHost(flowDocument.getHost()); enrichedFlow.setLocation(flowDocument.getLocation()); enrichedFlow.setDstLocality(matchLocality(flowDocument.getDstLocality())); enrichedFlow.setSrcLocality(matchLocality(flowDocument.getSrcLocality())); enrichedFlow.setFlowLocality(matchLocality(flowDocument.getFlowLocality())); enrichedFlow.setSrcNodeInfo(buildNodeInfo(flowDocument.getNodeSrc())); enrichedFlow.setDstNodeInfo(buildNodeInfo(flowDocument.getNodeDst())); enrichedFlow.setExporterNodeInfo(buildNodeInfo(flowDocument.getNodeExporter())); enrichedFlow.setConvoKey(flowDocument.getConvoKey()); return enrichedFlow; }
Source:
public BigDecimal getMovementCostIgnoreEnd(final Unit unit) { BigDecimal movementCost = BigDecimal.ZERO; final List<Territory> territories = steps.size() > 0 ? steps.subList(0, steps.size() - 1) : steps; for (final Territory t : territories) { movementCost = movementCost.add(TerritoryEffectHelper.getMovementCost(t, unit)); } return movementCost; }

Target:
public BigDecimal getMovementCostIgnoreEnd(final Unit unit) { final List<Territory> territories = steps.size() > 0 ? steps.subList(0, steps.size() - 1) : steps; return findMovementCost(unit, territories); }
Source:
public boolean canRestoreVmConfigurationFromSnapshot(VM vm, Snapshot snapshot, VmInterfaceManager vmInterfaceManager) { if (snapshot.getVmConfiguration() == null) { return false; } VM tempVM = new VM(); if (vm.getDynamicData() != null) { tempVM.setDynamicData(vm.getDynamicData()); } List<VmNetworkInterface> interfaces = new ArrayList<>(); try { ovfManager.importVm(snapshot.getVmConfiguration(), tempVM, new ArrayList<>(), Collections.EMPTY_LIST, interfaces); } catch (OvfReaderException e) { log.error("Failed to import VM from the configuration '{}': {}", snapshot.getVmConfiguration(), e.getMessage()); log.debug("Exception", e); return false; } boolean macsInSnapshotAreExpectedToBeAlreadyAllocated = SnapshotType.STATELESS.equals(snapshot.getType()); return canSynchronizeNics(vm, vmInterfaceManager, interfaces, macsInSnapshotAreExpectedToBeAlreadyAllocated); }

Target:
public boolean canRestoreVmConfigurationFromSnapshot(VM vm, Snapshot snapshot, VmInterfaceManager vmInterfaceManager) { if (snapshot.getVmConfiguration() == null) { return false; } VM tempVM = new VM(); if (vm.getDynamicData() != null) { tempVM.setDynamicData(vm.getDynamicData()); } List<VmNetworkInterface> interfaces = new ArrayList<>(); try { ovfManager.importVm(snapshot.getVmConfiguration(), tempVM, Collections.emptyList(), Collections.emptyList(), interfaces); } catch (OvfReaderException e) { log.error("Failed to import VM from the configuration '{}': {}", snapshot.getVmConfiguration(), e.getMessage()); log.debug("Exception", e); return false; } boolean macsInSnapshotAreExpectedToBeAlreadyAllocated = SnapshotType.STATELESS.equals(snapshot.getType()); return canSynchronizeNics(vm, vmInterfaceManager, interfaces, macsInSnapshotAreExpectedToBeAlreadyAllocated); }
Source:
public Result<ItemsWrapper<List<SubscriptionEventTypeStats>>> getSubscriptionStat(final String subscriptionId) { try { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); final List<SubscriptionEventTypeStats> subscriptionStat = createSubscriptionStat(subscription); return new Result.Success<>(new ItemsWrapper(subscriptionStat)); } catch (final NoSuchSubscriptionException e) { LOG.debug("Failed to find subscription: {}", subscriptionId, e); return Result.problem(e.asProblem()); } catch (final ServiceUnavailableException e) { LOG.error("Error occurred when trying to get subscription stat: {}" + subscriptionId, e); return Result.problem(e.asProblem()); } }

Target:
public Result<ItemsWrapper<SubscriptionEventTypeStats>> getSubscriptionStat(final String subscriptionId) { try { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); final List<SubscriptionEventTypeStats> subscriptionStat = createSubscriptionStat(subscription); return new Result.Success<>(new ItemsWrapper<>(subscriptionStat)); } catch (final NoSuchSubscriptionException e) { LOG.debug("Failed to find subscription: {}", subscriptionId, e); return Result.problem(e.asProblem()); } catch (final ServiceUnavailableException e) { LOG.error("Error occurred when trying to get subscription stat: {}" + subscriptionId, e); return Result.problem(e.asProblem()); } }
Source:
public void testRemoveListenerAfterStopAndRestart() { final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache(); final EventLogListener<Integer> eventListener1 = new EventLogListener<>(rcache); rcache.addClientListener(eventListener1); Set<Object> listeners = rcache.getListeners(); assertEquals(1, listeners.size()); assertEquals(eventListener1, listeners.iterator().next()); listeners = rcache.getListeners(); assertEquals(1, listeners.size()); assertTrue(listeners.contains(eventListener1)); int port = this.hotrodServer.getPort(); HotRodClientTestingUtil.killServers(this.hotrodServer); listeners = rcache.getListeners(); assertEquals(1, listeners.size()); hotrodServer = HotRodClientTestingUtil.startHotRodServer(this.cacheManager, port, new HotRodServerConfigurationBuilder()); rcache.removeClientListener(eventListener1); listeners = rcache.getListeners(); assertEquals(0, listeners.size()); }

Target:
public void testRemoveListenerAfterStopAndRestart() { remoteCacheManager.start(); final RemoteCache<Integer, String> rcache = remoteCacheManager.getCache(); final EventLogListener<Integer> eventListener1 = new EventLogListener<>(rcache); rcache.addClientListener(eventListener1); Set<Object> listeners = rcache.getListeners(); assertEquals(1, listeners.size()); assertTrue(listeners.contains(eventListener1)); int port = this.hotrodServer.getPort(); HotRodClientTestingUtil.killServers(this.hotrodServer); listeners = rcache.getListeners(); assertEquals(1, listeners.size()); hotrodServer = HotRodClientTestingUtil.startHotRodServer(this.cacheManager, port, new HotRodServerConfigurationBuilder()); rcache.removeClientListener(eventListener1); listeners = rcache.getListeners(); assertEquals(0, listeners.size()); }
Source:
public void readProp(final Element elem) { final String attAction = elem.getAttribute(ELEMENT_NAME_ACTION); Action action; switch (attAction) { case "include": action = Action.INCLUDE; break; case "exclude": action = Action.EXCLUDE; break; case "passthrough": action = Action.PASSTHROUGH; break; case "flag": action = readFlag(elem); break; default: logger.error(MessageUtils.getMessage("DOTJ077F", attAction).toString()); throw new IllegalArgumentException("Invalid DITAVAL."); } if (action != null) { final QName attName; if (elem.getTagName().equals(ELEMENT_NAME_REVPROP)) { attName = REV; } else { final String attValue = getValue(elem, ATTRIBUTE_NAME_ATT); if (attValue != null) { if (attValue.contains(":")) { final String[] parts = attValue.split(":"); final String uri; if (parts[0].equals(XML_NS_PREFIX)) { uri = XML_NS_URI; } else { uri = elem.lookupNamespaceURI(parts[0]); } attName = new QName(uri, parts[1], parts[0]); } else { attName = QName.valueOf(attValue); } } else { attName = null; } if (attName != null && attName.equals(REV) && !filterAttributes.isEmpty() && !filterAttributes.contains(REV)) { logger.warn(MessageUtils.getMessage("DOTJ074W").toString()); return; } } final String attValue = getValue(elem, ATTRIBUTE_NAME_VAL); final FilterKey key = attName != null ? new FilterKey(attName, attValue) : DEFAULT; insertAction(action, key); } }

Target:
public void readProp(final Element elem) { final String attAction = elem.getAttribute(ELEMENT_NAME_ACTION); Action action; switch (attAction) { case "include": action = Action.INCLUDE; break; case "exclude": action = Action.EXCLUDE; break; case "passthrough": action = Action.PASSTHROUGH; break; case "flag": action = readFlag(elem); break; default: throw new IllegalArgumentException(MessageUtils.getMessage("DOTJ077F", attAction).toString()); } if (action != null) { final QName attName; if (elem.getTagName().equals(ELEMENT_NAME_REVPROP)) { attName = REV; } else { final String attValue = getValue(elem, ATTRIBUTE_NAME_ATT); if (attValue != null) { if (attValue.contains(":")) { final String[] parts = attValue.split(":"); final String uri; if (parts[0].equals(XML_NS_PREFIX)) { uri = XML_NS_URI; } else { uri = elem.lookupNamespaceURI(parts[0]); } attName = new QName(uri, parts[1], parts[0]); } else { attName = QName.valueOf(attValue); } } else { attName = null; } if (attName != null && attName.equals(REV) && !filterAttributes.isEmpty() && !filterAttributes.contains(REV)) { logger.warn(MessageUtils.getMessage("DOTJ074W").toString()); return; } } final String attValue = getValue(elem, ATTRIBUTE_NAME_VAL); final FilterKey key = attName != null ? new FilterKey(attName, attValue) : DEFAULT; insertAction(action, key); } }
Source:
private String getSourceSurveyId(Long surveyId) { QuestionDao questionDao = new QuestionDao(); List<Question> qList = questionDao.listQuestionsBySurvey(surveyId); if(qList != null && !qList.isEmpty()) { Question q = qList.get(0); Long sourceQuestionId = q.getSourceId(); if (sourceQuestionId != null && questionDao.getByKey(sourceQuestionId) != null) { return questionDao.getByKey(sourceQuestionId).getSurveyId().toString(); } } return null; }

Target:
private String getSourceSurveyId(Long surveyId) { QuestionDao questionDao = new QuestionDao(); List<Question> qList = questionDao.listQuestionsBySurvey(surveyId); if(!qList.isEmpty()) { Question sourceQuestion = questionDao.getByKey(qList.get(0).getSourceId()); if (sourceQuestion != null) { return sourceQuestion.getSurveyId().toString(); } } return null; }
Source:
public void run() { try { DiagnosticsStreamMessage diagnosticsStreamMessage = new DiagnosticsStreamMessage(jobName, jobId, "samza-container-" + containerId, executionEnvContainerId, taskClassVersion, samzaVersion, hostname, System.currentTimeMillis(), resetTime.toEpochMilli()); if (!jobParamsEmitted) { diagnosticsStreamMessage.addContainerMb(containerMemoryMb); diagnosticsStreamMessage.addContainerNumCores(containerNumCores); diagnosticsStreamMessage.addNumStoresWithChangelog(numStoresWithChangelog); diagnosticsStreamMessage.addContainerModels(containerModels); } diagnosticsStreamMessage.addProcessorStopEvents(new ArrayList(processorStopEvents)); diagnosticsStreamMessage.addDiagnosticsExceptionEvents(exceptions.getValues()); if (!diagnosticsStreamMessage.isEmpty()) { systemProducer.send(DiagnosticsManager.class.getName(), new OutgoingMessageEnvelope(diagnosticSystemStream, hostname, null, new MetricsSnapshotSerdeV2().toBytes(diagnosticsStreamMessage.convertToMetricsSnapshot()))); systemProducer.flush(DiagnosticsManager.class.getName()); if (diagnosticsStreamMessage.getProcessorStopEvents() != null) { processorStopEvents.removeAll(diagnosticsStreamMessage.getProcessorStopEvents()); } exceptions.remove(diagnosticsStreamMessage.getExceptionEvents()); jobParamsEmitted = true; } } catch (Exception e) { LOG.error("Exception when flushing diagnosticsStreamMessage", e); } }

Target:
public void run() { try { DiagnosticsStreamMessage diagnosticsStreamMessage = new DiagnosticsStreamMessage(jobName, jobId, "samza-container-" + containerId, executionEnvContainerId, taskClassVersion, samzaVersion, hostname, System.currentTimeMillis(), resetTime.toEpochMilli()); if (!jobParamsEmitted) { diagnosticsStreamMessage.addContainerMb(containerMemoryMb); diagnosticsStreamMessage.addContainerNumCores(containerNumCores); diagnosticsStreamMessage.addNumStoresWithChangelog(numStoresWithChangelog); diagnosticsStreamMessage.addContainerModels(containerModels); } diagnosticsStreamMessage.addProcessorStopEvents(new ArrayList(processorStopEvents)); diagnosticsStreamMessage.addDiagnosticsExceptionEvents(exceptions.getValues()); if (!diagnosticsStreamMessage.isEmpty()) { systemProducer.send(DiagnosticsManager.class.getName(), new OutgoingMessageEnvelope(diagnosticSystemStream, hostname, null, new MetricsSnapshotSerdeV2().toBytes(diagnosticsStreamMessage.convertToMetricsSnapshot()))); systemProducer.flush(DiagnosticsManager.class.getName()); if (diagnosticsStreamMessage.getProcessorStopEvents() != null) { processorStopEvents.removeAll(diagnosticsStreamMessage.getProcessorStopEvents()); } if (diagnosticsStreamMessage.getExceptionEvents() != null) { exceptions.remove(diagnosticsStreamMessage.getExceptionEvents()); } jobParamsEmitted = true; } } catch (Exception e) { LOG.error("Exception when flushing diagnosticsStreamMessage", e); } }
Source:
private long countMapWithMapStoreEnabled(Node node) { return maps.stream().filter(distributedObject -> { MapStoreConfig config = node.getConfig().getMapConfig(distributedObject.getName()).getMapStoreConfig(); if (config != null) { return config.isEnabled(); } return false; }).count(); }

Target:
private long countMapWithMapStoreEnabled(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { return config.getMapStoreConfig().isEnabled(); } return false; }).count(); }
Source:
public void setup(Context context) { setOutputDirs(context); if (context.getConfiguration().get(HBASE_ENCODING) != null) { encoding = context.getConfiguration().get(HBASE_ENCODING); } mergeBodyWithUpdates = context.getConfiguration().get(IMPORT_MERGE_BODY_WITH_UPDATES) != null ? Boolean.valueOf(context.getConfiguration().get(IMPORT_MERGE_BODY_WITH_UPDATES)) : false; DataInfoBasedApprover dataInfoBasedApprover = buildApprover(context); this.resultApprover = dataInfoBasedApprover; docMetaConverter = new DocumentMetadataConverter(this.resultApprover, dataInfoBasedApprover); deduplicationMappingConverter = new DeduplicationMappingConverter(); docProjectConverter = new DocumentToProjectConverter(); personConverter = new PersonConverter(); projectConverter = new ProjectConverter(); organizationConverter = new OrganizationConverter(); projectOrganizationConverter = new ProjectToOrganizationConverter(); }

Target:
public void setup(Context context) { setOutputDirs(context); encoding = context.getConfiguration().get(HBASE_ENCODING, HBaseConstants.STATIC_FIELDS_ENCODING_UTF8); mergeBodyWithUpdates = context.getConfiguration().getBoolean(IMPORT_MERGE_BODY_WITH_UPDATES, false); DataInfoBasedApprover dataInfoBasedApprover = buildApprover(context); this.resultApprover = dataInfoBasedApprover; docMetaConverter = new DocumentMetadataConverter(this.resultApprover, dataInfoBasedApprover); deduplicationMappingConverter = new DeduplicationMappingConverter(); docProjectConverter = new DocumentToProjectRelationConverter(); personConverter = new PersonConverter(); projectConverter = new ProjectConverter(); organizationConverter = new OrganizationConverter(); projectOrganizationConverter = new ProjectToOrganizationRelationConverter(); }
Source:
public static Test suite() { TestSuite suite = new TestSuite(RegressionTests.class.getName()); suite.addTestSuite(Bug_303953.class); suite.addTestSuite(Bug_377295.class); return suite; }

Target:
public static Test suite() { TestSuite suite = new TestSuite(RegressionTests.class.getName()); suite.addTestSuite(Bug_303953.class); return suite; }
Source:
public void testCall() { String revision_id = null, change_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !"); gAccess.pushFile(); change_id = gAccess.getChangeId(); revision_id = gAccess.getCommitId(); } catch (Exception e1) { e1.printStackTrace(); } CherryPickRevisionCommand command = fGerrit.cherryPickRevision(change_id, revision_id); CherryPickInput cherryPickInput = new CherryPickInput(); cherryPickInput.setMessage("Implementing Feature X"); cherryPickInput.setDestination("HEAD"); command.setCherryPickInput(cherryPickInput); ChangeInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } catch (ClientProtocolException e) { fail(e.getMessage()); } System.out.println(result); assert (true); }

Target:
public void testCall() { String revision_id = null, change_id = null; try { GitAccess gAccess = new GitAccess(); Git git = gAccess.getGitProject(); gAccess.addFile("EGerritTestReviewFile.java", "Hello reviewers community !"); gAccess.pushFile(); change_id = gAccess.getChangeId(); revision_id = gAccess.getCommitId(); } catch (Exception e1) { e1.printStackTrace(); } CherryPickRevisionCommand command = fGerrit.cherryPickRevision(change_id, revision_id); CherryPickInput cherryPickInput = new CherryPickInput(); cherryPickInput.setMessage("Implementing Feature X"); cherryPickInput.setDestination("HEAD"); command.setCherryPickInput(cherryPickInput); ChangeInfo result = null; try { result = command.call(); } catch (EGerritException e) { fail(e.getMessage()); } catch (ClientProtocolException e) { fail(e.getMessage()); } assert (true); }
Source:
public EngineSettings(ExtendedJSONObject object) throws NumberFormatException { this.syncID = object.getString("syncID"); this.version = object.getIntegerSafely("version").intValue(); }

Target:
public EngineSettings(ExtendedJSONObject object) { try { this.syncID = object.getString("syncID"); this.version = object.getIntegerSafely("version").intValue(); } catch (Exception e ) { throw new IllegalArgumentException(e); } }
Source:
public static void resetConnectionAfterTransaction(Connection con, @Nullable Integer previousIsolationLevel) { Assert.notNull(con, "No Connection specified"); final boolean debugEnabled = logger.isDebugEnabled(); try { if (previousIsolationLevel != null) { if (debugEnabled) { logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to " + previousIsolationLevel); } con.setTransactionIsolation(previousIsolationLevel); } if (con.isReadOnly()) { if (logger.isDebugEnabled()) { logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]"); } con.setReadOnly(false); } } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } }

Target:
public static void resetConnectionAfterTransaction(Connection con, @Nullable Integer previousIsolationLevel) { Assert.notNull(con, "No Connection specified"); try { if (previousIsolationLevel != null) { if (logger.isDebugEnabled()) { logger.debug("Resetting isolation level of JDBC Connection [" + con + "] to " + previousIsolationLevel); } con.setTransactionIsolation(previousIsolationLevel); } if (con.isReadOnly()) { if (logger.isDebugEnabled()) { logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]"); } con.setReadOnly(false); } } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } }
Source:
public void return_mismatch_object_with_int32_values() { final int expected = 0; final int value1 = 1; final int value2 = 2; final ValueMismatch mismatch = Mismatch.of(expected, value1, value2, VERSION); final Int32Value expectedAny = fromAny(mismatch.getExpected()); final Int32Value actual = fromAny(mismatch.getActual()); final Int32Value requested = fromAny(mismatch.getRequested()); assertEquals(expected, expectedAny.getValue()); assertEquals(value1, actual.getValue()); assertEquals(value2, requested.getValue()); }

Target:
public void return_mismatch_object_with_int32_values() { final int expected = 0; final int actual = 1; final int requested = 2; final ValueMismatch mismatch = Mismatch.of(expected, actual, requested, VERSION); final Int32Value expectedWrapper = fromAny(mismatch.getExpected()); final Int32Value actualWrapper = fromAny(mismatch.getActual()); final Int32Value requestedWrapper = fromAny(mismatch.getRequested()); assertEquals(expected, expectedWrapper.getValue()); assertEquals(actual, actualWrapper.getValue()); assertEquals(requested, requestedWrapper.getValue()); }