auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testNegativeWeight() { String error = ""; try { assertAggregation( precisionRecallFunction, 0.0, createLongsBlock(Long.valueOf(200)), createBooleansBlock(Boolean.valueOf(true)), createDoublesBlock(Double.valueOf(0.2)), createDoublesBlock(Double.valueOf(-0.2))); } catch (PrestoException e) { error = e.getMessage(); } assertTrue(error.toLowerCase(Locale.ENGLISH).contains("weight")); assertTrue(error.toLowerCase(Locale.ENGLISH).contains("negative")); }

Target:
public void testNegativeWeight() { try { assertAggregation( precisionRecallFunction, 0.0, createLongsBlock(Long.valueOf(200)), createBooleansBlock(Boolean.valueOf(true)), createDoublesBlock(Double.valueOf(0.2)), createDoublesBlock(Double.valueOf(-0.2))); fail("Expected PrestoException"); } catch (PrestoException e) { assertTrue(e.getMessage().toLowerCase(Locale.ENGLISH).contains("weight")); assertTrue(e.getMessage().toLowerCase(Locale.ENGLISH).contains("negative")); } }
Source:
public static void getAllGroups(final CanvasCallback<Group[]> callback){ if(APIHelpers.paramIsNull(callback)) return; CanvasCallback<Group[]> bridge = new ExhaustiveBridgeCallback<>(callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() { @Override public void performApiCallWithExhaustiveCallback(CanvasCallback callback, String nextURL) { getNextPageGroups(nextURL, callback); } @Override public Class classType() { return Group.class; } }); bridge.readFromCache(getAllGroupsCacheFilename()); getFirstPageGroups(callback); }

Target:
public static void getAllGroups(final CanvasCallback<Group[]> callback){ if(APIHelpers.paramIsNull(callback)) return; CanvasCallback<Group[]> bridge = new ExhaustiveBridgeCallback<>(callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() { @Override public void performApiCallWithExhaustiveCallback(CanvasCallback callback, String nextURL) { getNextPageGroups(nextURL, callback); } @Override public Class classType() { return Group.class; } }); callback.readFromCache(getAllGroupsCacheFilename()); getFirstPageGroups(bridge); }
Source:
private void handleFinalizingSuccess(final StateContext context) { log.info("Finalizing successful transfer for {}", getTransferDescription()); if (stopImageTransferSession(context.entity)) { if (getParameters().getTransferType() == TransferType.Download) { unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); return; } Guid transferingVdsId = context.entity.getVdsId(); if (verifyImage(transferingVdsId)) { setVolumeLegalityInStorage(LEGAL_IMAGE); if (getImage().getVolumeFormat().equals(VolumeFormat.COW)) { setQcowCompat(getImage().getImage(), getStoragePool().getId(), getImage().getImage().getDiskId(), getImage().getImageId(), getStorageDomainId(), transferingVdsId); imageDao.update(getImage().getImage()); } unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); } else { setImageStatus(ImageStatus.ILLEGAL); updateEntityPhase(ImageTransferPhase.FINALIZING_FAILURE); } tearDownImage(context.entity.getVdsId()); } }

Target:
private void handleFinalizingSuccess(final StateContext context) { log.info("Finalizing successful transfer for {}", getTransferDescription()); if (stopImageTransferSession(context.entity)) { Guid transferingVdsId = context.entity.getVdsId(); if (getParameters().getTransferType() == TransferType.Download) { unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); } else if (verifyImage(transferingVdsId)) { setVolumeLegalityInStorage(LEGAL_IMAGE); if (getImage().getVolumeFormat().equals(VolumeFormat.COW)) { setQcowCompat(getImage().getImage(), getStoragePool().getId(), getImage().getImage().getDiskId(), getImage().getImageId(), getStorageDomainId(), transferingVdsId); imageDao.update(getImage().getImage()); } unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); } else { setImageStatus(ImageStatus.ILLEGAL); updateEntityPhase(ImageTransferPhase.FINALIZING_FAILURE); } tearDownImage(context.entity.getVdsId()); } }
Source:
public void labelOverUnboundSubject() throws QueryEvaluationException { TupleQueryResult result = lookupLabel(null, "en", "?s", "rdfs:label"); BlazegraphAssertions.assertThat(result.next()).doesNotBinds("sLabel"); assertFalse(result.hasNext()); }

Target:
public void labelOverUnboundSubject() throws QueryEvaluationException { TupleQueryResult result = lookupLabel(null, "en", "?s", "rdfs:label"); BlazegraphAssertions.assertThat(result.next()).doesNotBind("sLabel"); assertFalse(result.hasNext()); }
Source:
public CodeWriter unindent(int levels) { checkState(indentLevel - levels >= 0); indentLevel -= levels; return this; }

Target:
public CodeWriter unindent(int levels) { checkArgument(indentLevel - levels >= 0); indentLevel -= levels; return this; }
Source:
public Matrix get(final int[] indices) { if (indices == null) { throw new RuntimeException("Array of indices cannot be null"); } int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (final int index : indices) { if (index < min) { min = index; } if (index > max) { max = index; } } final FloatPointer hostPtr = new FloatPointer(max - min + 1); if (!JavaCuda.d2hMemcpy(hostPtr, devPtr.position(FLOAT_SIZE * min), FLOAT_SIZE * (max - min + 1))) { devPtr.position(0); throw new RuntimeException("Failed to copy memory from GPU."); } devPtr.position(0); final MatrixCudaImpl newMatrix = new MatrixCudaImpl(indices.length, 1); for (int i = 0; i < indices.length; i++) { newMatrix.put(i, hostPtr.get(indices[i] - min)); } return newMatrix; }

Target:
public Matrix get(final int[] indices) { if (indices == null || indices.length == 0) { throw new IllegalArgumentException("Array of indices cannot be null or zero-size"); } final MatrixCudaImpl newMatrix = new MatrixCudaImpl(indices.length, 1); for (int i = 0; i < indices.length; i++) { if (!JavaCuda.d2dMemcpy(newMatrix.devPtr.position(i * FLOAT_SIZE), devPtr.position(FLOAT_SIZE * indices[i]), FLOAT_SIZE)) { devPtr.position(0); newMatrix.free(); throw new RuntimeException("Failed to copy memory from GPU."); } } newMatrix.devPtr.position(0); devPtr.position(0); return newMatrix; }
Source:
private OAuthAuthenticator getAuthenticator(String oauthProviderName) { OAuthAuthenticator oauth = providers.getAuthenticator(oauthProviderName); if (oauth == null) { LOG.error("Unsupported OAuth provider ", oauthProviderName); throw new WebApplicationException(Response.status(400).entity("Unsupported OAuth provider " + oauthProviderName).type(MediaType.TEXT_PLAIN) .build()); } return oauth; }

Target:
private OAuthAuthenticator getAuthenticator(String oauthProviderName) throws BadRequestException { OAuthAuthenticator oauth = providers.getAuthenticator(oauthProviderName); if (oauth == null) { LOG.warn(format(UNSUPPORTED_OAUTH_PROVIDER_ERROR, oauthProviderName)); throw new BadRequestException(format(UNSUPPORTED_OAUTH_PROVIDER_ERROR, oauthProviderName)); } return oauth; }
Source:
public Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags() { final Map<String, Map<Integer, LagInfo>> localStorePartitionLags = new TreeMap<>(); final Collection<TopicPartition> allPartitions = new LinkedList<>(); final Map<TopicPartition, Long> allChangelogPositions = new HashMap<>(); for (final StreamThread streamThread : threads) { for (final Task task : streamThread.allTasks().values()) { allPartitions.addAll(task.changelogPartitions()); allChangelogPositions.putAll(task.changelogOffsets()); } } log.debug("Current changelog positions: {}", allChangelogPositions); final Map<TopicPartition, ListOffsetsResultInfo> allEndOffsets = fetchEndOffsets( allPartitions, adminClient, getAdminDefaultApiTimeoutMs(config) ); log.debug("Current end offsets :{}", allEndOffsets); for (final Map.Entry<TopicPartition, ListOffsetsResultInfo> entry : allEndOffsets.entrySet()) { final long earliestOffset = 0L; final long changelogPosition = allChangelogPositions.getOrDefault(entry.getKey(), earliestOffset); final long latestOffset = entry.getValue().offset(); final LagInfo lagInfo = new LagInfo(changelogPosition == Task.LATEST_OFFSET ? latestOffset : changelogPosition, latestOffset); final String storeName = streamsMetadataState.getStoreForChangelogTopic(entry.getKey().topic()); localStorePartitionLags.computeIfAbsent(storeName, ignored -> new TreeMap<>()) .put(entry.getKey().partition(), lagInfo); } return Collections.unmodifiableMap(localStorePartitionLags); }

Target:
public Map<String, Map<Integer, LagInfo>> allLocalStorePartitionLags() { final Map<String, Map<Integer, LagInfo>> localStorePartitionLags = new TreeMap<>(); final Collection<TopicPartition> allPartitions = new LinkedList<>(); final Map<TopicPartition, Long> allChangelogPositions = new HashMap<>(); for (final StreamThread streamThread : threads) { for (final Task task : streamThread.allTasks().values()) { allPartitions.addAll(task.changelogPartitions()); allChangelogPositions.putAll(task.changelogOffsets()); } } log.debug("Current changelog positions: {}", allChangelogPositions); final Map<TopicPartition, ListOffsetsResultInfo> allEndOffsets = fetchEndOffsets(allPartitions, adminClient); log.debug("Current end offsets :{}", allEndOffsets); for (final Map.Entry<TopicPartition, ListOffsetsResultInfo> entry : allEndOffsets.entrySet()) { final long earliestOffset = 0L; final long changelogPosition = allChangelogPositions.getOrDefault(entry.getKey(), earliestOffset); final long latestOffset = entry.getValue().offset(); final LagInfo lagInfo = new LagInfo(changelogPosition == Task.LATEST_OFFSET ? latestOffset : changelogPosition, latestOffset); final String storeName = streamsMetadataState.getStoreForChangelogTopic(entry.getKey().topic()); localStorePartitionLags.computeIfAbsent(storeName, ignored -> new TreeMap<>()) .put(entry.getKey().partition(), lagInfo); } return Collections.unmodifiableMap(localStorePartitionLags); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { boolean retval = true; switch (item.getItemId()) { case R.id.action_create_dir: CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile); dialog.show( getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT); break; case android.R.id.home: if ((mParents.size() > 1)) { onBackPressed(); } break; case R.id.action_sort_descending: item.setChecked(!item.isChecked()); boolean isAscending = !item.isChecked(); com.owncloud.android.db.PreferenceManager.setSortAscending(isAscending,this,FileStorageUtils.FILE_DISPLAY_SORT); switch(com.owncloud.android.db.PreferenceManager.getSortOrder(this,FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: sortByName(isAscending); break; case FileStorageUtils.SORT_SIZE: sortBySize(isAscending); break; case FileStorageUtils.SORT_DATE: sortByDate(isAscending); break; } break; case R.id.action_sort_by_name: item.setChecked(true); sortByName(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case R.id.action_sort_by_size: item.setChecked(true); sortBySize(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case R.id.action_sort_by_date: item.setChecked(true); sortByDate(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; default: retval = super.onOptionsItemSelected(item); } return retval; }

Target:
public boolean onOptionsItemSelected(MenuItem item) { boolean retval = true; switch (item.getItemId()) { case R.id.action_create_dir: CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile); dialog.show( getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT); break; case android.R.id.home: if ((mParents.size() > 1)) { onBackPressed(); } break; case R.id.action_sort_descending: item.setChecked(!item.isChecked()); boolean isAscending = !item.isChecked(); PreferenceManager.setSortAscending(isAscending, this, FileStorageUtils.FILE_DISPLAY_SORT); switch (PreferenceManager.getSortOrder(this, FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: sortByName(isAscending); break; case FileStorageUtils.SORT_SIZE: sortBySize(isAscending); break; case FileStorageUtils.SORT_DATE: sortByDate(isAscending); break; } break; case R.id.action_sort_by_name: item.setChecked(true); sortByName(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case R.id.action_sort_by_size: item.setChecked(true); sortBySize(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case R.id.action_sort_by_date: item.setChecked(true); sortByDate(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; default: retval = super.onOptionsItemSelected(item); } return retval; }
Source:
public Object call(Properties bindings, Object[] args) { if (args.length == 2) { Object s1 = args[0]; Object s2 = args[1]; if (s1 != null && s2 != null && s1 instanceof String && (s2 instanceof String || s2 instanceof Pattern)) { String s = (String) s1; Pattern pattern = (s2 instanceof String) ? Pattern.compile((String) s2) : (Pattern) s2; Matcher matcher = pattern.matcher(s); if (matcher.find()) { return true; }else return false; } } return null; }

Target:
public Object call(Properties bindings, Object[] args) { if (args.length == 2) { Object s1 = args[0]; Object s2 = args[1]; if (s1 != null && s2 != null && s1 instanceof String && s2 instanceof String) { return ((String) s1).indexOf((String) s2) > -1; } else if (s1 != null && s2 != null && s1 instanceof String && s2 instanceof Pattern){ String s = (String) s1; Pattern pattern = (Pattern) s2; Matcher matcher = pattern.matcher(s); if (matcher.find()) { return true; }else return false; } } return null; }
Source:
public void simpleTestAES192() throws Exception { KeyPair caPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); X509Certificate ca = X509Certificates.createEphemeral( new X500Principal("CN=CA"), caPair); KeyPair clientPair = KeyPairGenerator.getInstance("RSA") .generateKeyPair(); X509Certificate client = X509Certificates.createEphemeral( new X500Principal("CN=Client"), clientPair); PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(ca, "AES_192"); PkiMessageEncoder encoder = new PkiMessageEncoder( clientPair.getPrivate(), client, envEncoder); PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(ca, caPair.getPrivate()); PkiMessageDecoder decoder = new PkiMessageDecoder(client, envDecoder); PkiMessage<?> actual = decoder.decode(encoder.encode(message)); assertEquals(message, actual); }

Target:
public void simpleTestAES192() throws Exception { PkiMessage<?> actual = encodeAndDecodeEnvelope("AES_192"); assertEquals(message, actual); }
Source:
public HSearchEntityContext(IndexedTypeIdentifier entityType, ExtendedSearchIntegrator factory) { indexBoundType = getIndexBoundType( entityType, factory ); if ( indexBoundType == null ) { IndexedTypesSet configuredSubTypes = factory.getConfiguredTypesPolymorphic( new Class<?>[] { entityType.getPojoType() } ); if ( configuredSubTypes.isEmpty() ) { throw log.cantQueryUnconfiguredType( entityType.getName() ); } else { throw log.cantQueryUnindexedType( entityType.getName()); } } originalAnalyzerReference = factory.getAnalyzerReference( indexBoundType.getPojoType() ); queryAnalyzerReferenceBuilder = factory.getAnalyzerReference( indexBoundType.getPojoType() ).startCopy(); IndexManagerType indexManagerType = factory.getIndexBinding( indexBoundType.getPojoType() ).getIndexManagerType(); analyzerRegistry = factory.getIntegration( indexManagerType ).getAnalyzerRegistry(); }

Target:
public HSearchEntityContext(IndexedTypeIdentifier entityType, ExtendedSearchIntegrator factory) { indexBoundType = getIndexBoundType( entityType, factory ); if ( indexBoundType == null ) { IndexedTypeSet configuredSubTypes = factory.getConfiguredTypesPolymorphic( entityType.asTypeSet() ); if ( configuredSubTypes.isEmpty() ) { throw log.cantQueryUnconfiguredType( entityType.getName() ); } else { throw log.cantQueryUnindexedType( entityType.getName() ); } } originalAnalyzerReference = factory.getAnalyzerReference( indexBoundType ); queryAnalyzerReferenceBuilder = factory.getAnalyzerReference( indexBoundType ).startCopy(); IndexManagerType indexManagerType = factory.getIndexBinding( indexBoundType ).getIndexManagerType(); analyzerRegistry = factory.getIntegration( indexManagerType ).getAnalyzerRegistry(); }
Source:
public AccessTokenResponse getAccessTokenResponse() throws OAuthException, IOException, OAuthError { checkNotNull(handle, "handle must not be null"); AccessTokenResponse lastAccessToken = storeHandler.loadAccessTokenResponse(handle); if (lastAccessToken == null) { return null; } if (lastAccessToken.isExpired(new Date(), tokenExpiresIn_Buffer) && lastAccessToken.getRefreshToken() != null) { return refreshToken(); } return lastAccessToken; }

Target:
public @Nullable AccessTokenResponse getAccessTokenResponse() throws OAuthException, IOException, OAuthResponseException { if (isClosed()) { throw new OAuthException(EXCEPTION_MESSAGE_CLOSED); } AccessTokenResponse lastAccessToken; try { lastAccessToken = storeHandler.loadAccessTokenResponse(handle); } catch (GeneralSecurityException e) { throw new OAuthException("Cannot decrypt access token from store", e); } if (lastAccessToken == null) { return null; } if (lastAccessToken.isExpired(LocalDateTime.now(), tokenExpiresInBuffer) && lastAccessToken.getRefreshToken() != null) { return refreshToken(); } return lastAccessToken; }
Source:
static void checkForMerge(String tableId, Iterator<KeyExtent> lmi, TabletIterFactory tabletIterFactory) throws Exception { KeyExtent currRange = lmi.next(); Text startRow = currRange.getPrevEndRow(); Iterator<KeyExtent> tabletIter = tabletIterFactory.newTabletIter(startRow); KeyExtent currTablet = tabletIter.next(); if (!tabletIter.hasNext() && equals(KeyExtent::getPrevEndRow, currTablet, currRange) && equals(KeyExtent::getEndRow, currTablet, currRange)) currRange = null; while (tabletIter.hasNext()) { if (currRange == null) { if (!lmi.hasNext()) { break; } currRange = lmi.next(); } while (!equals(KeyExtent::getPrevEndRow, currTablet, currRange) && tabletIter.hasNext()) { currTablet = tabletIter.next(); } boolean matchedPrevRow = equals(KeyExtent::getPrevEndRow, currTablet, currRange); while (!equals(KeyExtent::getEndRow, currTablet, currRange) && tabletIter.hasNext()) { currTablet = tabletIter.next(); } if (!matchedPrevRow || !equals(KeyExtent::getEndRow, currTablet, currRange)) { break; } currRange = null; } if (currRange != null || lmi.hasNext()) { throw new AcceptableThriftTableOperationException(tableId, null, TableOperation.BULK_IMPORT, TableOperationExceptionType.OTHER, Constants.BULK_CONCURRENT_MERGE_MSG); } }

Target:
static void checkForMerge(String tableId, Iterator<KeyExtent> lmi, TabletIterFactory tabletIterFactory) throws Exception { KeyExtent currRange = lmi.next(); Text startRow = currRange.getPrevEndRow(); Iterator<KeyExtent> tabletIter = tabletIterFactory.newTabletIter(startRow); KeyExtent currTablet = tabletIter.next(); if (!tabletIter.hasNext() && equals(KeyExtent::getPrevEndRow, currTablet, currRange) && equals(KeyExtent::getEndRow, currTablet, currRange)) currRange = null; while (tabletIter.hasNext()) { if (currRange == null) { if (!lmi.hasNext()) { break; } currRange = lmi.next(); } while (!equals(KeyExtent::getPrevEndRow, currTablet, currRange) && tabletIter.hasNext()) { currTablet = tabletIter.next(); } boolean matchedPrevRow = equals(KeyExtent::getPrevEndRow, currTablet, currRange); while (!equals(KeyExtent::getEndRow, currTablet, currRange) && tabletIter.hasNext()) { currTablet = tabletIter.next(); } if (!matchedPrevRow || !equals(KeyExtent::getEndRow, currTablet, currRange)) { break; } currRange = null; } if (currRange != null || lmi.hasNext()) { throw new AcceptableThriftTableOperationException(tableId, null, TableOperation.BULK_IMPORT, TableOperationExceptionType.BULK_CONCURRENT_MERGE, "Concurrent merge happened"); } }
Source:
public synchronized void removeSegmentDir(File segmentDir, DataSegment segment) { if (files.remove(segmentDir)) { currSize -= segment.getSize(); } else { log.warn("SegmentDir[%s] is not found under this location[%s]", segmentDir, path); } }

Target:
public synchronized void removeSegmentDir(File segmentDir, DataSegment segment) { if (files.remove(segmentDir)) { currSizeBytes -= segment.getSize(); } else { log.warn("SegmentDir[%s] is not found under this location[%s]", segmentDir, path); } }
Source:
public List<CourseComponentSession> getComponentSessions() { if (componentSessions == null) { componentSessions = new ArrayList<CourseComponentSession>(); for(CourseComponentSessionDAO session: dao.getComponentSessions()) { componentSessions.add(new CourseComponentSessionImpl(session)); } } Collections.sort(componentSessions, new Comparator<CourseComponentSession>() { public int compare(CourseComponentSession c1,CourseComponentSession c2) { if (null != c1.getSessionStart() && null != c2.getSessionStart()) { return c1.getSessionStart().compareTo(c2.getSessionStart()); } return c1.getSessionId().compareTo(c2.getSessionId()); } }); return componentSessions; }

Target:
public List<CourseComponentSession> getComponentSessions() { if (componentSessions == null) { componentSessions = new ArrayList<CourseComponentSession>(); for(CourseComponentSessionDAO session: dao.getComponentSessions()) { componentSessions.add(new CourseComponentSessionImpl(session)); } } Collections.sort(componentSessions); return componentSessions; }
Source:
public void shouldPublishAndConsumeMessageWithTraceAndSpanHeaders() { String message = "{\"id\": 101}"; String traceId = UUID.randomUUID().toString(); String spanId = UUID.randomUUID().toString(); String parentSpanId = UUID.randomUUID().toString(); String sampled = "1"; String reported = "0"; Topic topic = operations.buildTopic("traceSendAndReceiveGroup", "topic"); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(message); WebTarget client = ClientBuilder.newClient().target(FRONTEND_URL).path("topics").path(topic.getQualifiedName()); Response response = client .request() .header("Trace-Id", traceId) .header("Span-Id", spanId) .header("Parent-Span-Id", parentSpanId) .header("Trace-Sampled", sampled) .header("Trace-Reported", reported) .post(Entity.entity(message, MediaType.APPLICATION_JSON)); assertThat(response).hasStatus(Response.Status.CREATED); LoggedRequest lastRequest = remoteService.waitAndGetLastRequest(); assertThat(lastRequest).hasHeaderValue("Trace-Id", traceId); assertThat(lastRequest).hasHeaderValue("Span-Id", spanId); assertThat(lastRequest).hasHeaderValue("Parent-Span-Id", parentSpanId); assertThat(lastRequest).hasHeaderValue("Trace-Sampled", sampled); assertThat(lastRequest).hasHeaderValue("Trace-Reported", reported); }

Target:
public void shouldPublishAndConsumeMessageWithTraceAndSpanHeaders() { String message = "{\"id\": 101}"; TraceContext trace = TraceContext.random(); Topic topic = operations.buildTopic("traceSendAndReceiveGroup", "topic"); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(message); Invocation.Builder request = createRequestWithTraceHeaders(FRONTEND_URL, topic.getQualifiedName(), trace); Response response = request.post(Entity.entity(message, MediaType.APPLICATION_JSON)); assertThat(response).hasStatus(Response.Status.CREATED); assertThat(remoteService.waitAndGetLastRequest()).containsAllHeaders(trace.asMap()); }
Source:
public Collection<BodyPart> getAll() { return ImmutableList.copyOf(this.bodyPartMap.values()); }

Target:
public Collection<BodyPart> getAll() { return ImmutableSet.copyOf(this.bodyPartMap.values()); }
Source:
public void afterActionPerformed(AnAction anAction, DataContext dataContext, AnActionEvent anActionEvent) { if (anAction instanceof StepIntoAction || anAction instanceof ForceStepIntoAction) { eventManager.addEvent(new DebugEventBase(EventType.STEP_INTO, new Date())); } else if (anAction instanceof StepOverAction || anAction instanceof ForceStepOverAction) { eventManager.addEvent(new DebugEventBase(EventType.STEP_OVER, new Date())); } else if (anAction instanceof StepOutAction) { eventManager.addEvent(new DebugEventBase(EventType.STEP_OUT, new Date())); } else if (anAction instanceof XInspectAction) { eventManager.addEvent(new DebugEventBase(EventType.INSPECT_VARIABLE, new Date())); } else if (anAction.getClass().getSimpleName().equals("XAddToWatchesAction")) { eventManager.addEvent(new DebugEventBase(EventType.DEFINE_WATCH, new Date())); } else if (anAction.getClass().getSimpleName().equals("EvaluateAction")) { eventManager.addEvent(new DebugEventBase(EventType.EVALUATE_EXPRESSION, new Date())); } else if (anAction instanceof XSetValueAction) { eventManager.addEvent(new DebugEventBase(EventType.MODIFY_VARIABLE_VALUE, new Date())); } }

Target:
public void afterActionPerformed(AnAction anAction, DataContext dataContext, AnActionEvent anActionEvent) { if (anAction instanceof StepIntoAction || anAction instanceof ForceStepIntoAction) { createEvent(DebugEventType.STEP_INTO); } else if (anAction instanceof StepOverAction || anAction instanceof ForceStepOverAction) { createEvent(DebugEventType.STEP_OVER); } else if (anAction instanceof StepOutAction) { createEvent(DebugEventType.STEP_OUT); } else if (anAction instanceof XInspectAction) { createEvent(DebugEventType.INSPECT_VARIABLE); } else if (anAction.getClass().getSimpleName().equals("XAddToWatchesAction")) { createEvent(DebugEventType.DEFINE_WATCH); } else if (anAction.getClass().getSimpleName().equals("EvaluateAction")) { createEvent(DebugEventType.EVALUATE_EXPRESSION); } else if (anAction instanceof XSetValueAction) { createEvent(DebugEventType.MODIFY_VARIABLE_VALUE); } }
Source:
public BinaryResult apply(ChangeResource rsrc) throws AuthException, IOException, InvalidChangeOperationException, OrmException, NoSuchChangeException { Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange()); String m = edit.isPresent() ? edit.get().getEditCommit().getFullMessage() : changeUtil.getMessage(rsrc.getChange()); return BinaryResult.create(m).base64(); }

Target:
public BinaryResult apply(ChangeResource rsrc) throws AuthException, IOException, OrmException, NoSuchChangeException { Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange()); String m = edit.isPresent() ? edit.get().getEditCommit().getFullMessage() : changeUtil.getMessage(rsrc.getChange()); return BinaryResult.create(m).base64(); }
Source:
public void queryFrozenRealmAcrossThreads() throws InterruptedException { final Realm frozenRealm = createDataForFrozenRealm(DATA_SIZE); Thread t = new Thread(() -> { RealmResults<AllTypes> results = frozenRealm.where(AllTypes.class).findAll(); assertEquals(DATA_SIZE, results.size()); }); t.start(); t.join(); frozenRealm.close(); }

Target:
public void queryFrozenRealmAcrossThreads() throws InterruptedException { final Realm frozenRealm = createDataForFrozenRealm(DATA_SIZE); Thread t = new Thread(() -> { RealmResults<AllTypes> results = frozenRealm.where(AllTypes.class).findAll(); assertEquals(DATA_SIZE, results.size()); }); t.start(); t.join(); }
Source:
public ResponseEntity<?> commitCursors(@PathVariable("subscriptionId") final String subscriptionId, @RequestBody final List<Cursor> cursors, final NativeWebRequest request) { if (!featureToggleService.isFeatureEnabled("high_level_api")) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } try { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); final String eventType = subscription.getEventTypes().iterator().next(); topicRepository.validateCommitCursors(eventType, cursors); boolean allCommitted = true; for (final Cursor cursor : cursors) { allCommitted = allCommitted && cursorsCommitService.commitCursor(subscriptionId, eventType, cursor); } return allCommitted ? ok().build() : noContent().build(); } catch (final NoSuchSubscriptionException | ServiceUnavailableException e) { return create(e.asProblem(), request); } catch (InvalidCursorException e) { return create(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage()), request); } }

Target:
public ResponseEntity<?> commitCursors(@PathVariable("subscriptionId") final String subscriptionId, @RequestBody final List<Cursor> cursors, final NativeWebRequest request) { if (!featureToggleService.isFeatureEnabled(FEATURE_HIGH_LEVEL_API)) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } try { boolean allCommitted = cursorsCommitService.commitCursors(subscriptionId, cursors); return allCommitted ? ok().build() : noContent().build(); } catch (final NoSuchSubscriptionException | ServiceUnavailableException e) { return create(e.asProblem(), request); } catch (InvalidCursorException e) { return create(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage()), request); } }
Source:
public static void setUp() throws Exception { client = ManagementClientProvider.createOnlineManagementClient(); client.apply(snapshotBackup.backup()); administration.reloadIfRequired(); }

Target:
public static void setUp() throws Exception { client.apply(snapshotBackup.backup()); administration.reloadIfRequired(); }
Source:
public SqlScript(ExpressionRuntime expressionRuntime, ScriptEngine<SqlEngine> scriptEngine, ValuesConverter<StreamlineEvent> valuesConverter) { super(expressionRuntime.asString(), scriptEngine); this.valuesConverter = valuesConverter; stormSqlFields = ((StormSqlExpression) expressionRuntime).getStormSqlFields(); if (stormSqlFields.isEmpty()) { ((StormSqlExpression) expressionRuntime).addStormSqlField(DUMMY_FIELD); stormSqlFields.add(DUMMY_FIELD); } if (!stormSqlFields.isEmpty()) { SqlEngine sqlEngine = (SqlEngine) scriptEngine; sqlEngine.compileQuery(createQuery((StormSqlExpression) expressionRuntime)); } projectedFields = ((StormSqlExpression) expressionRuntime).getProjectedFields(); outputFields = ((StormSqlExpression) expressionRuntime).getOutputFields(); }

Target:
public SqlScript(ExpressionRuntime expressionRuntime, ScriptEngine<SqlEngine> scriptEngine, ValuesConverter<StreamlineEvent> valuesConverter) { super(expressionRuntime.asString(), scriptEngine); this.valuesConverter = valuesConverter; stormSqlFields = ((StormSqlExpression) expressionRuntime).getStormSqlFields(); if (stormSqlFields.isEmpty()) { ((StormSqlExpression) expressionRuntime).addStormSqlField(DUMMY_FIELD); stormSqlFields.add(DUMMY_FIELD); } SqlEngine sqlEngine = (SqlEngine) scriptEngine; sqlEngine.compileQuery(createQuery((StormSqlExpression) expressionRuntime)); projectedFields = ((StormSqlExpression) expressionRuntime).getProjectedFields(); outputFields = ((StormSqlExpression) expressionRuntime).getOutputFields(); }
Source:
private void niceSyncthing() { new Thread() { public void run() { Process niceST = null; DataOutputStream niceSTOut = null; int ret = 1; try { Thread.sleep(1000); niceST = Runtime.getRuntime().exec("sh"); niceSTOut = new DataOutputStream(niceST.getOutputStream()); niceSTOut.writeBytes("set `ps |grep libsyncthing.so`\n"); niceSTOut.writeBytes("ionice $2 be 7\n"); niceSTOut.writeBytes("exit\n"); log(niceST.getInputStream(), Log.INFO); log(niceST.getErrorStream(), Log.WARN); niceSTOut.flush(); ret = niceST.waitFor(); Log.i(TAG, "ionice performed on libsyncthing.so"); } catch (IOException | InterruptedException e) { Log.e(TAG, "Failed to execute ionice binary", e); } finally { try { if (niceSTOut != null) { niceSTOut.close(); } } catch (IOException e) { Log.w(TAG, "Failed to close shell stream", e); } if (niceST != null) { niceST.destroy(); } if (ret != 0) { Log.e(TAG_NATIVE, "Failed to set ionice " + Integer.toString(ret)); } } } }.start(); }

Target:
private void niceSyncthing() { new Thread() { public void run() { Process nice = null; DataOutputStream niceOut = null; int ret = 1; try { Thread.sleep(1000); nice = Runtime.getRuntime().exec("sh"); niceOut = new DataOutputStream(nice.getOutputStream()); niceOut.writeBytes("set `ps |grep libsyncthing.so`\n"); niceOut.writeBytes("ionice $2 be 7\n"); niceOut.writeBytes("exit\n"); log(nice.getErrorStream(), Log.WARN); niceOut.flush(); ret = nice.waitFor(); Log.i(TAG_IONICE, "ionice performed on libsyncthing.so"); } catch (IOException | InterruptedException e) { Log.e(TAG_IONICE, "Failed to execute ionice binary", e); } finally { try { if (niceOut != null) { niceOut.close(); } } catch (IOException e) { Log.w(TAG_IONICE, "Failed to close shell stream", e); } if (nice != null) { nice.destroy(); } if (ret != 0) { Log.e(TAG_IONICE, "Failed to set ionice " + Integer.toString(ret)); } } } }.start(); }
Source:
public IpUtil() { trustedProxiesCache = new HashSet<IpAddressMatcher>(); labsSubnetsCache = new HashSet<IpAddressMatcher>(); for (String proxyIp : trustedProxies) { String trimmedProxyIp = proxyIp.trim(); try { IpAddressMatcher matcher = new IpAddressMatcher(trimmedProxyIp); trustedProxiesCache.add(matcher); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalid entry '" + proxyIp + "' " + "found in the default trusted proxies list", e); } } for (String labsSubnet: labsSubnets) { try { IpAddressMatcher matcher = new IpAddressMatcher(labsSubnet); labsSubnetsCache.add(matcher); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalid entry '" + labsSubnet + "' found in the default labs subnet list", e); } } }

Target:
public IpUtil() { trustedProxiesCache = new HashSet<IpAddressMatcher>(); labsSubnetsCache = new HashSet<IpAddressMatcher>(); for (String proxyIp : trustedProxies) { String trimmedProxyIp = proxyIp.trim(); try { IpAddressMatcher matcher = new IpAddressMatcher(trimmedProxyIp); trustedProxiesCache.add(matcher); } catch (IllegalArgumentException e) { throw new RuntimeException("Invalid entry '" + proxyIp + "' " + "found in the default trusted proxies list", e); } } for (String labsSubnet: labsSubnets) { IpAddressMatcher matcher = new IpAddressMatcher(labsSubnet); labsSubnetsCache.add(matcher); } }
Source:
public void vuapResolvedStateIsNotMute(Page page, String slot, String videoIframeSelector) { AdsBaseObject ads = openPageWithVideoInLocalStorage(page, VuapVideos.PORVATA_VAST, VuapVideos.VAST_VIDEO); final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); ads.refreshPage(); vuap.replay(); vuap.clickOnSoundButton(); VuapAssertions.verifyVideoUnmuteAndMute(vuap); }

Target:
public void vuapResolvedStateIsNotMute(Page page, String slot, String videoIframeSelector) { AdsBaseObject ads = openPageWithVideoInLocalStorage(page); final AutoplayVuap vuap = new AutoplayVuap(driver, slot, videoIframeSelector); ads.refreshPage(); vuap.replay(); vuap.mute(); VuapAssertions.verifyVideoUnmuteAndMute(vuap); }
Source:
public JsonObject asJson() { $lock.readLock().lock(); JsonObject json = new JsonObject(); if (text != null) { json.addProperty("text", text); } if (translate != null) { json.addProperty("translate", translate); JsonArray array = new JsonArray(); with.forEach(array::add); json.add("with", array); } if (scoreUsername != null && scoreObjective != null) { JsonObject score = new JsonObject(); score.addProperty("name", scoreUsername); score.addProperty("objective", scoreObjective); json.add("score", score); } if (selector != null) { json.addProperty("selector", selector); } if (!extra.isEmpty()) { JsonArray extra = new JsonArray(); this.extra.forEach(e -> extra.add(e.asJson())); json.add("extra", extra); } if (bold != null) { json.addProperty("bold", bold.get()); } if (italic != null) { json.addProperty("italic", italic.get()); } if (underlined != null) { json.addProperty("underlined", underlined.get()); } if (strikethrough != null) { json.addProperty("strikethrough", strikethrough.get()); } if (obfuscated != null) { json.addProperty("obfuscated", obfuscated.get()); } if (color != null) { json.addProperty("color", color.name().toLowerCase()); } if (clickEvent != null) { json.add("clickEvent", this.clickEvent.asJson()); } if (hoverEvent != null) { json.add("hoverEvent", this.hoverEvent.asJson()); } if (insertion != null) { json.addProperty("insertion", insertion); } $lock.readLock().unlock(); return json; }

Target:
public JsonObject asJson() { JsonObject json = new JsonObject(); if (text != null) { json.addProperty("text", text); } if (translate != null) { json.addProperty("translate", translate); JsonArray array = new JsonArray(); with.forEach(array::add); json.add("with", array); } if (scoreUsername != null && scoreObjective != null) { JsonObject score = new JsonObject(); score.addProperty("name", scoreUsername); score.addProperty("objective", scoreObjective); json.add("score", score); } if (selector != null) { json.addProperty("selector", selector); } if (!extra.isEmpty()) { JsonArray extra = new JsonArray(); this.extra.forEach(e -> extra.add(e.asJson())); json.add("extra", extra); } if (bold != null) { json.addProperty("bold", bold.get()); } if (italic != null) { json.addProperty("italic", italic.get()); } if (underlined != null) { json.addProperty("underlined", underlined.get()); } if (strikethrough != null) { json.addProperty("strikethrough", strikethrough.get()); } if (obfuscated != null) { json.addProperty("obfuscated", obfuscated.get()); } if (color != null) { json.addProperty("color", color.name().toLowerCase()); } if (clickEvent != null) { json.add("clickEvent", this.clickEvent.asJson()); } if (hoverEvent != null) { json.add("hoverEvent", this.hoverEvent.asJson()); } if (insertion != null) { json.addProperty("insertion", insertion); } return json; }
Source:
public void testPropertyIsEqualToFloat() throws JAXBException, SAXException, IOException { mockProps.add(MOCK_PROPERTY); when(featureMetacardType.getProperties()).thenReturn(mockProps); when(featureMetacardType.isQueryable(MOCK_PROPERTY)).thenReturn(true); WfsFilterDelegate delegate = createDelegate(); FilterType filter = delegate.propertyIsEqualTo(MOCK_PROPERTY, 1.0F); assertXMLEqual(propertyIsEqualToXmlDecimal, marshal(filter)); }

Target:
public void testPropertyIsEqualToFloat() throws JAXBException, SAXException, IOException { WfsFilterDelegate delegate = createSinglePropertyDelegate(); FilterType filter = delegate.propertyIsEqualTo(MOCK_PROPERTY, 1.0F); assertXMLEqual(propertyIsEqualToXmlDecimal, marshal(filter)); }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); ProgressBar progressBar = findViewById(R.id.progressBar); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrapDrawable = DrawableCompat.wrap(progressBar.getIndeterminateDrawable()); DrawableCompat.setTint(wrapDrawable, 0xffffffff); progressBar.setIndeterminateDrawable(DrawableCompat.unwrap(wrapDrawable)); } else { progressBar.getIndeterminateDrawable().setColorFilter(0xffffffff, PorterDuff.Mode.SRC_IN); } Completable.create(subscriber -> { PodDBAdapter.getInstance().open(); PodDBAdapter.getInstance().close(); subscriber.onComplete(); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> { Intent intent = new Intent(SplashActivity.this, MainActivity.class); finish(); startActivity(intent); }); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); ProgressBar progressBar = findViewById(R.id.progressBar); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable wrapDrawable = DrawableCompat.wrap(progressBar.getIndeterminateDrawable()); DrawableCompat.setTint(wrapDrawable, 0xffffffff); progressBar.setIndeterminateDrawable(DrawableCompat.unwrap(wrapDrawable)); } else { progressBar.getIndeterminateDrawable().setColorFilter(0xffffffff, PorterDuff.Mode.SRC_IN); } Completable.create(subscriber -> { PodDBAdapter.getInstance().open(); PodDBAdapter.getInstance().close(); subscriber.onComplete(); }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> { Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); }); }
Source:
public T getEventValue(@NonNull final IEvent event) { Map<String, ?> map = sharedPreferences.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (entry.getKey().equals(event.getTrackingKey())) { return (T) entry.getValue(); } } return null; }

Target:
public T getEventValue(@NonNull final IEvent event) { Map<String, ?> map = sharedPreferences.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (entry.getKey().equals(event.getTrackingKey())) { return (T) entry.getValue(); } } logger.e("No event value for " + event); return null; }
Source:
public static BuildDirLocator create() { String buildTool = ConfigurationHolder.instance().getProperty(CliOption.BUILD_TOOL); if (BuildTool.MAVEN.getName().equals(buildTool)) { return new MavenBuildDirLocator(); } else if (BuildTool.GRADLE.getName().equals(buildTool)) { return new GradleBuildFileLocator(); } throw new GeneralOptionNotSupportedException("Build tool " + buildTool + " not supported"); }

Target:
public static BuildDirLocator create() { String buildTool = ConfigurationHolder.instance().getProperty(GeneralOption.BUILD_TOOL); notBlank(buildTool); switch (BuildTool.valueOf(buildTool.toUpperCase())) { case MAVEN: return new MavenBuildDirLocator(); case GRADLE: return new GradleBuildFileLocator(); default: log.warn("Build tool " + buildTool + " not supported, using maven"); return new MavenBuildDirLocator(); } }
Source:
private static AccountDiffPreference initAccountDiffPreferences( AccountDiffPreference a, DiffPreferencesInfo i, Account.Id id) { if (a == null) { a = AccountDiffPreference.createDefault(id); } int context = i.context == null ? DiffPreferencesInfo.DEFAULT_CONTEXT : i.context; a.setContext((short)context); a.setExpandAllComments(b(i.expandAllComments)); a.setHideLineNumbers(b(i.hideLineNumbers)); a.setHideTopMenu(b(i.hideTopMenu)); a.setIgnoreWhitespace(Whitespace.forCode( PatchListKey.WHITESPACE_TYPES.get(i.ignoreWhitespace))); a.setIntralineDifference(b(i.intralineDifference)); a.setLineLength(i.lineLength == null ? DiffPreferencesInfo.DEFAULT_LINE_LENGTH : i.lineLength); a.setManualReview(i.manualReview); a.setRenderEntireFile(b(i.renderEntireFile)); a.setRetainHeader(b(i.retainHeader)); a.setShowLineEndings(b(i.showLineEndings)); a.setShowTabs(b(i.showTabs)); a.setShowWhitespaceErrors(b(i.showWhitespaceErrors)); a.setSkipDeleted(b(i.skipDeleted)); a.setSkipUncommented(b(i.skipUncommented)); a.setSyntaxHighlighting(b(i.syntaxHighlighting)); a.setTabSize(i.tabSize == null ? DiffPreferencesInfo.DEFAULT_TAB_SIZE : i.tabSize); a.setTheme(i.theme); a.setHideEmptyPane(b(i.hideEmptyPane)); a.setAutoHideDiffTableHeader(b(i.autoHideDiffTableHeader)); return a; }

Target:
private static AccountDiffPreference initAccountDiffPreferences( AccountDiffPreference a, DiffPreferencesInfo i, Account.Id id) { if (a == null) { a = AccountDiffPreference.createDefault(id); } int context = i.context == null ? DiffPreferencesInfo.DEFAULT_CONTEXT : i.context; a.setContext((short)context); a.setExpandAllComments(b(i.expandAllComments)); a.setHideLineNumbers(b(i.hideLineNumbers)); a.setHideTopMenu(b(i.hideTopMenu)); a.setIgnoreWhitespace(i.ignoreWhitespace == null ? Whitespace.IGNORE_NONE : Whitespace.forCode( PatchListKey.WHITESPACE_TYPES.get(i.ignoreWhitespace))); a.setIntralineDifference(b(i.intralineDifference)); a.setLineLength(i.lineLength == null ? DiffPreferencesInfo.DEFAULT_LINE_LENGTH : i.lineLength); a.setManualReview(b(i.manualReview)); a.setRenderEntireFile(b(i.renderEntireFile)); a.setRetainHeader(b(i.retainHeader)); a.setShowLineEndings(b(i.showLineEndings)); a.setShowTabs(b(i.showTabs)); a.setShowWhitespaceErrors(b(i.showWhitespaceErrors)); a.setSkipDeleted(b(i.skipDeleted)); a.setSkipUncommented(b(i.skipUncommented)); a.setSyntaxHighlighting(b(i.syntaxHighlighting)); a.setTabSize(i.tabSize == null ? DiffPreferencesInfo.DEFAULT_TAB_SIZE : i.tabSize); a.setTheme(i.theme); a.setHideEmptyPane(b(i.hideEmptyPane)); a.setAutoHideDiffTableHeader(b(i.autoHideDiffTableHeader)); return a; }
Source:
private void expectTaskGetTopic(boolean anyTimes) { final Capture<String> connectorCapture = EasyMock.newCapture(); final Capture<String> topicCapture = EasyMock.newCapture(); IExpectationSetters<TopicStatus> expect = EasyMock.expect(statusBackingStore.getTopic( EasyMock.capture(connectorCapture), EasyMock.capture(topicCapture))); if (anyTimes) { expect.andStubAnswer(() -> new TopicStatus( topicCapture.getValue(), new ConnectorTaskId(connectorCapture.getValue(), 0), Time.SYSTEM.milliseconds())); } else { expect.andStubAnswer(() -> new TopicStatus( topicCapture.getValue(), new ConnectorTaskId(connectorCapture.getValue(), 0), Time.SYSTEM.milliseconds())); } if (connectorCapture.hasCaptured() && topicCapture.hasCaptured()) { assertEquals("job", connectorCapture.getValue()); assertEquals(TOPIC, topicCapture.getValue()); } }

Target:
private void expectTaskGetTopic(boolean anyTimes) { final Capture<String> connectorCapture = EasyMock.newCapture(); final Capture<String> topicCapture = EasyMock.newCapture(); IExpectationSetters<TopicStatus> expect = EasyMock.expect(statusBackingStore.getTopic( EasyMock.capture(connectorCapture), EasyMock.capture(topicCapture))); if (anyTimes) { expect.andStubAnswer(() -> new TopicStatus( topicCapture.getValue(), new ConnectorTaskId(connectorCapture.getValue(), 0), Time.SYSTEM.milliseconds())); } else { expect.andAnswer(() -> new TopicStatus( topicCapture.getValue(), new ConnectorTaskId(connectorCapture.getValue(), 0), Time.SYSTEM.milliseconds())); } if (connectorCapture.hasCaptured() && topicCapture.hasCaptured()) { assertEquals("job", connectorCapture.getValue()); assertEquals(TOPIC, topicCapture.getValue()); } }
Source:
public PlanNode visitProject(ProjectNode node, RewriteContext<Expression> context) { Set<Symbol> deterministicSymbols = node.getAssignments().entrySet().stream() .filter(entry -> DeterminismEvaluator.isDeterministic(entry.getValue())) .map(Map.Entry::getKey) .collect(Collectors.toSet()); Predicate<Expression> deterministic = conjunct -> SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(deterministicSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(deterministic)); List<Expression> deterministicConjuncts = conjuncts.get(true); Map<Boolean, List<Expression>> partitionedConjuncts = deterministicConjuncts.stream() .collect(Collectors.partitioningBy(expression -> isInliningCandidate(expression, node))); List<Expression> inlinedDeterministicConjuncts = partitionedConjuncts.get(true).stream() .map(entry -> inlineSymbols(node.getAssignments().getMap(), entry)) .collect(Collectors.toList()); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(inlinedDeterministicConjuncts)); List<Expression> nonInliningConjuncts = partitionedConjuncts.get(false); if (!conjuncts.get(false).isEmpty()) { nonInliningConjuncts.addAll(conjuncts.get(false)); } if (!nonInliningConjuncts.isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(nonInliningConjuncts)); } return rewrittenNode; }

Target:
public PlanNode visitProject(ProjectNode node, RewriteContext<Expression> context) { Set<Symbol> deterministicSymbols = node.getAssignments().entrySet().stream() .filter(entry -> DeterminismEvaluator.isDeterministic(entry.getValue())) .map(Map.Entry::getKey) .collect(Collectors.toSet()); Predicate<Expression> deterministic = conjunct -> SymbolsExtractor.extractUnique(conjunct).stream() .allMatch(deterministicSymbols::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(deterministic)); List<Expression> deterministicConjuncts = conjuncts.get(true); Map<Boolean, List<Expression>> inlineConjuncts = deterministicConjuncts.stream() .collect(Collectors.partitioningBy(expression -> isInliningCandidate(expression, node))); List<Expression> inlinedDeterministicConjuncts = inlineConjuncts.get(true).stream() .map(entry -> inlineSymbols(node.getAssignments().getMap(), entry)) .collect(Collectors.toList()); PlanNode rewrittenNode = context.defaultRewrite(node, combineConjuncts(inlinedDeterministicConjuncts)); List<Expression> nonInliningConjuncts = inlineConjuncts.get(false); nonInliningConjuncts.addAll(conjuncts.get(false)); if (!nonInliningConjuncts.isEmpty()) { rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(nonInliningConjuncts)); } return rewrittenNode; }