auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Object doWork() { final CopyNumberTriStateHiddenMarkovModel model = modelArguments.createModel(); final TargetCollection<Target> targets = targetArguments.readTargetCollection(false); final ReadCountCollection inputCounts = readAndSortCountsByTargetCoordinates(targets); checkForMissingTargetsInInputCounts(targets, inputCounts); final Map<String, List<CopyNumberTriStateSegment>> allSegments = calculateBestPathSegments(model, inputCounts); final Iterator<CopyNumberTriStateSegmentRecord> allSegmentsSorted = composeATargetSortedSegmentRecordIterator(targets, allSegments); writeSegmentsInOutputFile(allSegmentsSorted); return "SUCCESS"; }

Target:
protected Object doWork() { final CopyNumberTriStateHiddenMarkovModel model = modelArguments.createModel(); final TargetCollection<Target> targets = targetArguments.readTargetCollection(false); final ReadCountCollection inputCounts = readAndSortCountsByTargetCoordinates(targets); checkForMissingTargetsInInputCounts(targets, inputCounts); final Map<String, List<CopyNumberTriStateSegment>> allSegmentsBySampleName = calculateBestPathSegments(model, inputCounts); final Iterator<CopyNumberTriStateSegmentRecord> allSegmentRecordsSortedByCoordinates = composeATargetSortedSegmentRecordIterator(targets, allSegmentsBySampleName); writeSegmentsInOutputFile(allSegmentRecordsSortedByCoordinates); return "SUCCESS"; }
Source:
public void addOperation(final String key, final Operation o) { MemcachedNode placeIn=null; MemcachedNode primary = locator.getPrimary(key); if(primary.isActive() || failureMode == FailureMode.Retry) { placeIn=primary; } else if(failureMode == FailureMode.Cancel) { o.setHandlingNode(primary); o.cancel("node is not active"); } else { for(Iterator<MemcachedNode> i=locator.getSequence(key); placeIn == null && i.hasNext(); ) { MemcachedNode n=i.next(); if(n.isActive()) { placeIn=n; } } if(placeIn == null) { placeIn = primary; } } assert o.isCancelled() || placeIn != null : "No node found for key " + key; if(placeIn != null) { addOperation(placeIn, o); } else { assert o.isCancelled() : "No not found for " + key + " (and not immediately cancelled)"; } }

Target:
public void addOperation(final String key, final Operation o) { MemcachedNode placeIn=null; MemcachedNode primary = locator.getPrimary(key); if(primary.isActive() || failureMode == FailureMode.Retry) { placeIn=primary; } else if(failureMode == FailureMode.Cancel) { o.setHandlingNode(primary); o.cancel("inactive node"); } else { for(Iterator<MemcachedNode> i=locator.getSequence(key); placeIn == null && i.hasNext(); ) { MemcachedNode n=i.next(); if(n.isActive()) { placeIn=n; } } if(placeIn == null) { placeIn = primary; } } assert o.isCancelled() || placeIn != null : "No node found for key " + key; if(placeIn != null) { addOperation(placeIn, o); } else { assert o.isCancelled() : "No not found for " + key + " (and not immediately cancelled)"; } }
Source:
public void shouldFailureReturnNotNull() { Try<Object> _try = failure(new Error("error")); assertThat(_try).isNotNull(); assertThat(_try.isFailure()).isTrue(); }

Target:
public void shouldFailureReturnNotNull() { final Try<?> t = Failure(new Error()); assertThat(t).isNotNull(); assertThat(t.isFailure()).isTrue(); }
Source:
public Responses getResponsesObject() { return responsesObject; }

Target:
public Responses getResponsesObject() { if (responses == null && responsesObject != null) { responses = new LinkedHashMap<String, Response>(); for (String key : this.responsesObject.keySet()) { responses.put(key, responsesObject.get(key)); } } return responsesObject; }
Source:
public static List<Symbol> extractAll(RowExpression expression) { ImmutableList.Builder<Symbol> builder = ImmutableList.builder(); expression.accept(new VariableBuilderVisitor(), builder); return builder.build(); }

Target:
public static List<VariableReferenceExpression> extractAll(RowExpression expression) { ImmutableList.Builder<VariableReferenceExpression> builder = ImmutableList.builder(); expression.accept(new VariableBuilderVisitor(), builder); return builder.build(); }
Source:
public EntityTraversal<Vertex, User> fold() { return __.<Vertex, Object>project("id", "uuid", "password", "enabled", "roles", "securityTokenKey", "lastUpdated", "sourceId") .by(__.id()) .by(__.enrichPropertyValue("uuid")) .by(__.enrichPropertyValue("password")) .by(__.enrichPropertyValue("enabled")) .by(__.enrichPropertyValue("roles")) .by(__.enrichPropertyValue("securityTokenKey")) .by(__.enrichPropertyValue("lastUpdated")) .by(__.enrichPropertyValue("sourceId")) .map(this::map); }

Target:
public EntityTraversal<Vertex, User> fold() { return __.<Vertex, Object>project("id", "uuid", "password", "enabled", "roles", "securityTokenKey", "lastUpdated", "sourceId") .by(__.id()) .by(__.enrichPropertyValue("uuid")) .by(__.enrichPropertyValue("password")) .by(__.enrichPropertyValue("enabled")) .by(__.outE(Edges.USER_HAS_SECURITY_ROLES) .inV() .map(securityRoleAdapter.fold()) .map(EntityTraversalUtils::castToObject) .fold()) .by(__.enrichPropertyValue("securityTokenKey")) .by(__.enrichPropertyValue("lastUpdated")) .by(__.enrichPropertyValue("sourceId")) .map(this::map); }
Source:
public void onInfoWindowClick(Marker marker) { Intent i = new Intent(EntityMapActivity.this.getIntent()); TreeReference ref = markerReferences.get(marker); SerializationUtil.serializeToIntent(i, EntityDetailActivity.CONTEXT_REFERENCE, ref); setResult(RESULT_OK, i); EntityMapActivity.this.finish(); }

Target:
public void onInfoWindowClick(Marker marker) { Intent i = new Intent(getIntent()); TreeReference ref = markerReferences.get(marker); SerializationUtil.serializeToIntent(i, EntityDetailActivity.CONTEXT_REFERENCE, ref); setResult(RESULT_OK, i); finish(); }
Source:
public void clear() { fieldBinding.clear(); if(dataBindingEditor != null) { FormsElementWrapperWidgetUtil.clear(this); } formRenderer.unBind(); modal.clear(); }

Target:
public void clear() { fieldBinding.clear(); if (dataBindingEditor != null) { wrapperWidgetUtil.clear(this); } formRenderer.unBind(); modal.clear(); }
Source:
private void runUpdateStatisticsTool(String fullTableName) { UpdateStatisticsTool tool = new UpdateStatisticsTool(); tool.setConf(utility.getConfiguration()); String randomDir = getUtility().getRandomDir().toString(); final String[] cmdArgs = getArgValues(fullTableName, randomDir); try { int status = tool.run(cmdArgs); assertEquals(0, status); HBaseAdmin hBaseAdmin = utility.getHBaseAdmin(); assertEquals(0, hBaseAdmin.listSnapshots(tool.getSnapshotName()).size()); } catch (Exception e) { fail("Exception when running UpdateStatisticsTool for " + tableName + " Exception: " + e); } finally { Job job = tool.getJob(); assertEquals(job.getConfiguration().get(MAPREDUCE_JOB_TYPE), UPDATE_STATS.name()); } }

Target:
private void runUpdateStatisticsTool(String fullTableName) { UpdateStatisticsTool tool = new UpdateStatisticsTool(); tool.setConf(utility.getConfiguration()); String randomDir = getUtility().getRandomDir().toString(); final String[] cmdArgs = getArgValues(fullTableName, randomDir); try { int status = tool.run(cmdArgs); assertEquals("MR Job should complete successfully", 0, status); HBaseAdmin hBaseAdmin = utility.getHBaseAdmin(); assertEquals("Snapshot should be automatically deleted when UpdateStatisticsTool has completed", 0, hBaseAdmin.listSnapshots(tool.getSnapshotName()).size()); } catch (Exception e) { fail("Exception when running UpdateStatisticsTool for " + tableName + " Exception: " + e); } finally { Job job = tool.getJob(); assertEquals("MR Job should have been configured with UPDATE_STATS job type", job.getConfiguration().get(MAPREDUCE_JOB_TYPE), UPDATE_STATS.name()); } }
Source:
private static Collection<Unit> getCanCarry( final Unit carrier, final Collection<Unit> selectFrom, final GamePlayer playerWhoIsDoingTheMovement, final GameData data) { final UnitAttachment ua = UnitAttachment.get(carrier.getType()); final Collection<Unit> canCarry = new ArrayList<>(); int available = ua.getCarrierCapacity(); for (final Unit plane : selectFrom) { final UnitAttachment planeAttachment = UnitAttachment.get(plane.getType()); final int cost = planeAttachment.getCarrierCost(); if (available >= cost && ((carrier.getAlreadyMoved().compareTo(plane.getAlreadyMoved()) == 0) || (Matches.unitHasNotMoved().test(plane) && Matches.unitHasNotMoved().test(carrier)) || (Matches.unitIsOwnedBy(playerWhoIsDoingTheMovement).negate().test(plane) && Matches.alliedUnit(playerWhoIsDoingTheMovement, data).test(plane)))) { available -= cost; canCarry.add(plane); } if (available == 0) { break; } } return canCarry; }

Target:
private static Collection<Unit> getCanCarry( final Unit carrier, final Collection<Unit> selectFrom, final GamePlayer playerWhoIsDoingTheMovement, final GameData data) { final UnitAttachment ua = UnitAttachment.get(carrier.getType()); final Collection<Unit> canCarry = new ArrayList<>(); int available = ua.getCarrierCapacity(); for (final Unit plane : selectFrom) { final UnitAttachment planeAttachment = UnitAttachment.get(plane.getType()); final int cost = planeAttachment.getCarrierCost(); if (available >= cost) { if ((carrier.getAlreadyMoved().compareTo(plane.getAlreadyMoved()) == 0) || (Matches.unitHasNotMoved().test(plane) && Matches.unitHasNotMoved().test(carrier)) || (Matches.unitIsOwnedBy(playerWhoIsDoingTheMovement).negate().test(plane) && Matches.alliedUnit(playerWhoIsDoingTheMovement, data).test(plane))) { available -= cost; canCarry.add(plane); } } if (available == 0) { break; } } return canCarry; }
Source:
public void onNext(CRUDEvent event) { Collection<LifeCycleHook> hooks = dictionary.getTriggers( event.getResource().getResourceClass(), this.annotation, event.getFieldName()); if (!event.getFieldName().isEmpty()) { hooks.addAll(dictionary.getTriggers(event.getResource().getResourceClass(), this.annotation)); } hooks.forEach((hook) -> { hook.execute( event.getResource().getObject(), event.getResource().getRequestScope(), event.getChanges()); }); }

Target:
public void onNext(CRUDEvent event) { ArrayList<LifeCycleHook> hooks = new ArrayList<>(); hooks.addAll(dictionary.getTriggers( event.getResource().getResourceClass(), this.annotation, event.getFieldName())); if (!event.getFieldName().isEmpty()) { hooks.addAll(dictionary.getTriggers(event.getResource().getResourceClass(), this.annotation)); } try { hooks.forEach((hook) -> { hook.execute( event.getResource().getObject(), event.getResource().getRequestScope(), event.getChanges()); }); } catch (RuntimeException e) { exception = Optional.of(e); if (throwsExceptions) { throw e; } } }
Source:
private void onHighPriority(MenuItem item) { if (isHighPriority) { item.setTitle(getString(R.string.priority_urgent)); this.isHighPriority = false; setTitle(getTitle().toString().split(",")[0]); } else { item.setTitle(getString(R.string.priority_normal)); this.isHighPriority = true; setTitle(getTitle()+","+getString(R.string.priority_urgent)); } }

Target:
private void onHighPriority(MenuItem item) { if (isHighPriority) { item.setTitle(getString(R.string.priority_high)); setTitle(getString(R.string.compose_title_compose)); this.isHighPriority = false; } else { item.setTitle(getString(R.string.priority_normal)); setTitle(getString(R.string.compose_title_compose)+","+getString(R.string.priority_high)); this.isHighPriority = true; } }
Source:
public static void dropTable(Connection c, String storageKey) { String sqlStatement = "DROP TABLE IF EXISTS " + storageKey; try { PreparedStatement preparedStatement = c.prepareStatement(sqlStatement); preparedStatement.execute(); } catch (SQLException e) { System.out.println("didn't drop table"); } }

Target:
public static void dropTable(Connection c, String storageKey) { String sqlStatement = "DROP TABLE IF EXISTS " + storageKey; PreparedStatement preparedStatement = null; try { preparedStatement = c.prepareStatement(sqlStatement); preparedStatement.execute(); } catch (SQLException e) { Logger.log("E", "Could not drop table: " + e.getMessage()); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
Source:
public void testRecomputePictureViews() throws Exception { DocumentModel doc = session.createDocumentModel("/", "pictureDoc", "Picture"); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/test.jpg"), "image/jpeg", StandardCharsets.UTF_8.name(), "test.jpg"); doc.setPropertyValue("file:content", (Serializable) blob); doc = session.createDocument(doc); txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); List<Serializable> pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertFalse(pictureViews.isEmpty()); doc.setPropertyValue("picture:views", new ArrayList<>()); session.saveDocument(doc); txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertTrue(pictureViews.isEmpty()); Map<String, String> parameters = Collections.singletonMap("query", "SELECT * FROM Document WHERE ecm:mixinType = 'Picture'"); try (OperationContext ctx = new OperationContext(session)) { automationService.run(ctx, RecomputePictureViews.ID, parameters); } bulkService.await(Duration.ofSeconds(60)); txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertFalse(pictureViews.isEmpty()); }

Target:
public void testRecomputePictureViews() throws Exception { DocumentModel doc = session.createDocumentModel("/", "pictureDoc", "Picture"); Blob blob = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/test.jpg"), "image/jpeg", StandardCharsets.UTF_8.name(), "test.jpg"); doc.setPropertyValue("file:content", (Serializable) blob); doc = session.createDocument(doc); txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); List<Serializable> pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertFalse(pictureViews.isEmpty()); doc.setPropertyValue("picture:views", new ArrayList<>()); session.saveDocument(doc); txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertTrue(pictureViews.isEmpty()); Map<String, String> parameters = Collections.singletonMap("query", "SELECT * FROM Document WHERE ecm:mixinType = 'Picture'"); try (OperationContext ctx = new OperationContext(session)) { automationService.run(ctx, RecomputePictureViews.ID, parameters); } txFeature.nextTransaction(); doc = session.getDocument(doc.getRef()); pictureViews = (List<Serializable>) doc.getPropertyValue("picture:views"); assertNotNull(pictureViews); assertFalse(pictureViews.isEmpty()); }
Source:
private Owner setupOwner(Principal principal, String ownerKey) { if (ownerKey == null && (principal instanceof UserPrincipal)) { List<String> ownerKeys = ((UserPrincipal) principal).getOwnerKeys(); if (ownerKeys.size() != 1) { throw new BadRequestException(i18n.tr("You must specify an organization for new units.")); } ownerKey = ownerKeys.get(0); } createOwnerIfNeeded(principal); Owner owner = ownerCurator.getByKey(ownerKey); if (owner == null) { throw new BadRequestException(i18n.tr("Organization {0} does not exist.", ownerKey)); } if ((principal instanceof UserPrincipal) && !principal.canAccess(owner, SubResource.CONSUMERS, Access.CREATE)) { log.warn("User does not have access to create consumers in org {}", principal.getPrincipalName(), owner.getKey()); throw new ForbiddenException(i18n.tr("{0} is not authorized to register with " + "organization {1}", principal.getName(), owner.getKey())); } return owner; }

Target:
private Owner setupOwner(Principal principal, String ownerKey) { if (ownerKey == null && (principal instanceof UserPrincipal)) { List<String> ownerKeys = ((UserPrincipal) principal).getOwnerKeys(); if (ownerKeys.size() != 1) { throw new BadRequestException(i18n.tr("You must specify an organization for new units.")); } ownerKey = ownerKeys.get(0); } createOwnerIfNeeded(principal); Owner owner = ownerCurator.getByKey(ownerKey); if (owner == null) { throw new BadRequestException(i18n.tr("Organization {0} does not exist.", ownerKey)); } if ((principal instanceof UserPrincipal) && !principal.canAccess(owner, SubResource.CONSUMERS, Access.CREATE)) { log.warn("User does not have access to create consumers in org {}", principal.getPrincipalName(), owner.getKey()); List<Owner> owners = ((UserPrincipal) principal).getOwners(); boolean isOwnerContained = owners != null && owners.stream() .anyMatch(t -> t != null && t.getOwnerId().equals(owner.getOwnerId())); if (isOwnerContained) { throw new ForbiddenException(i18n.tr("{0} is not authorized to register with " + "organization {1}", principal.getName(), owner.getKey())); } throw new NotFoundException(i18n.tr("owner with key: {0} was not found.", owner.getKey())); } return owner; }
Source:
private void init() { setTitle(ConstantsManager.getInstance().getConstants().editLogicalNetworkTitle()); setHelpTag(HelpTag.edit_logical_network); setHashName("edit_logical_network"); getName().setEntity(getNetwork().getName()); getDescription().setEntity(getNetwork().getDescription()); getComment().setEntity(getNetwork().getComment()); getIsStpEnabled().setEntity(getNetwork().getStp()); getHasVLanTag().setEntity(getNetwork().getVlanId() != null); getVLanTag().setEntity(getNetwork().getVlanId()); initMtu(); initIsVm(); getExternal().setEntity(getNetwork().isExternal()); getExternal().setIsChangeable(false); getExternalProviders().setIsChangeable(false); getPhysicalNetwork().setEntity(isConnectedToPhysicalNetwork()); getPhysicalNetwork().setIsChangeable(false); if (isConnectedToPhysicalNetwork()) { getPhysicalNetworkDatacenter().setEntity(getNetwork().getProvidedBy().isSetPhysicalNetworkId()); } getPhysicalNetworkDatacenterRB().setIsChangeable(false); getPhysicalNetworkCustomRB().setIsChangeable(false); getDatacenterPhysicalNetwork().setIsChangeable(false); if (getNetwork().isExternal() && isConnectedToPhysicalNetwork()) { getNeutronPhysicalNetwork().setEntity(getNetwork().getLabel()); } else { getNetworkLabel().setSelectedItem(getNetwork().getLabel()); } toggleProfilesAvailability(); }

Target:
private void init() { setTitle(ConstantsManager.getInstance().getConstants().editLogicalNetworkTitle()); setHelpTag(HelpTag.edit_logical_network); setHashName("edit_logical_network"); getName().setEntity(getNetwork().getName()); getDescription().setEntity(getNetwork().getDescription()); getComment().setEntity(getNetwork().getComment()); getIsStpEnabled().setEntity(getNetwork().getStp()); getHasVLanTag().setEntity(getNetwork().getVlanId() != null); getVLanTag().setEntity(getNetwork().getVlanId()); initMtu(); initIsVm(); getExternal().setEntity(getNetwork().isExternal()); getExternal().setIsChangeable(false); getExternalProviders().setIsChangeable(false); getPhysicalNetwork().setEntity(isConnectedToPhysicalNetwork()); getPhysicalNetwork().setIsChangeable(false); getPhysicalNetworkDatacenterRB().setIsChangeable(false); getPhysicalNetworkCustomRB().setIsChangeable(false); getDatacenterPhysicalNetwork().setIsChangeable(false); if (isConnectedToPhysicalNetwork()) { if (getNetwork().getProvidedBy().isSetPhysicalNetworkId()) { getPhysicalNetworkDatacenter().setEntity(true); } else { getPhysicalNetworkDatacenter().setEntity(false); getNeutronPhysicalNetwork().setEntity(getNetwork().getLabel()); } } else { getNetworkLabel().setSelectedItem(getNetwork().getLabel()); } toggleProfilesAvailability(); }
Source:
public void disconnect() { if (sock.isConnected()) { sock.disconnect(); } }

Target:
public void disconnect() { if (sock.isConnected()) sock.disconnect(); }
Source:
private List<SchemaTableConfigBean> expandListOfSchemas() { List<SchemaTableConfigBean> expandedSchemas = new ArrayList<>(); configBean.baseConfigBean.schemaTableConfigs .stream() .map(baseConfig -> Arrays.stream(baseConfig.schema.split(",")) .map(copyBean(baseConfig)) .collect(Collectors.toList())) .forEach(expandedSchemas::addAll); return expandedSchemas; }

Target:
private List<SchemaTableConfigBean> expandListOfSchemas() { List<SchemaTableConfigBean> expandedSchemas = new ArrayList<>(); for (SchemaTableConfigBean baseConfig : configBean.baseConfigBean.schemaTableConfigs) { for(String s: Splitter.on(COMMA_SPLIT_PATTERN).split(baseConfig.schema)){ SchemaTableConfigBean schemaTableConfigBean = copyBean(baseConfig,s.replaceAll("^\"|\"$", "")); expandedSchemas.add(schemaTableConfigBean); } } return expandedSchemas; }
Source:
public void requestWhenAuthorizedClientFoundThenMethodArgumentResolved() throws Exception { String clientRegistrationId = "client1"; String principalName = "user1"; TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password"); ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class); OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); when(authorizedClientRepository.loadAuthorizedClient( eq(clientRegistrationId), eq(authentication), any(HttpServletRequest.class))) .thenReturn(authorizedClient); OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class); when(authorizedClient.getAccessToken()).thenReturn(accessToken); OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository; OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository; OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient; this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire(); this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))) .andExpect(status().isOk()) .andExpect(content().string("resolved")); verify(accessTokenResponseClient, times(0)).getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)); }

Target:
public void requestWhenAuthorizedClientFoundThenMethodArgumentResolved() throws Exception { String clientRegistrationId = "client1"; String principalName = "user1"; TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password"); ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class); OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); when(authorizedClientRepository.loadAuthorizedClient( eq(clientRegistrationId), eq(authentication), any(HttpServletRequest.class))) .thenReturn(authorizedClient); OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class); when(authorizedClient.getAccessToken()).thenReturn(accessToken); OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository; OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository; OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient; this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire(); this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))) .andExpect(status().isOk()) .andExpect(content().string("resolved")); verifyZeroInteractions(accessTokenResponseClient); }
Source:
private void bindToBrokerAccountService(final Context context, final Callback<BrokerAccountServiceConnection> callback, final BrokerEvent brokerEvent) { Logger.v(TAG, "Binding to BrokerAccountService for caller uid: " + android.os.Process.myUid()); final Intent brokerAccountServiceToBind = getIntentForBrokerAccountService(context); final BrokerAccountServiceConnection connection = new BrokerAccountServiceConnection(); BindServiceTimeoutRunnable timeoutRunnable = new BindServiceTimeoutRunnable(context, connection, callback); connection.setBindServiceTimeoutCallback(timeoutRunnable); if (brokerEvent != null) { connection.setTelemetryEvent(brokerEvent); brokerEvent.setBrokerAccountServerStartsBinding(); } final CallbackExecutor<BrokerAccountServiceConnection> callbackExecutor = new CallbackExecutor<>(callback); mPendingConnections.put(connection, callbackExecutor); final boolean serviceBound = context.bindService(brokerAccountServiceToBind, connection, Context.BIND_AUTO_CREATE); Logger.v(TAG, "The status for brokerAccountService bindService call is: " + Boolean.valueOf(serviceBound)); if (brokerEvent != null) { brokerEvent.setBrokerAccountServiceBindingSucceed(serviceBound); } if (!serviceBound) { connection.unBindService(context); callback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED)); } else { mUiHandler.postDelayed(timeoutRunnable, BIND_SERVICE_TIMEOUT_THRESHOLD); } }

Target:
private void bindToBrokerAccountService(final Context context, final Callback<BrokerAccountServiceConnection> callback, final BrokerEvent brokerEvent) { Logger.v(TAG, "Binding to BrokerAccountService for caller uid: " + android.os.Process.myUid()); final Intent brokerAccountServiceToBind = getIntentForBrokerAccountService(context); final BrokerAccountServiceConnection connection = new BrokerAccountServiceConnection(); final BindServiceTimeoutRunnable timeoutRunnable = new BindServiceTimeoutRunnable(context, connection, callback); connection.setBindServiceTimeoutCallback(timeoutRunnable); if (brokerEvent != null) { connection.setTelemetryEvent(brokerEvent); brokerEvent.setBrokerAccountServerStartsBinding(); } final CallbackExecutor<BrokerAccountServiceConnection> callbackExecutor = new CallbackExecutor<>(callback); mPendingConnections.put(connection, callbackExecutor); final boolean serviceBound = context.bindService(brokerAccountServiceToBind, connection, Context.BIND_AUTO_CREATE); Logger.v(TAG, "The status for brokerAccountService bindService call is: " + Boolean.valueOf(serviceBound)); if (brokerEvent != null) { brokerEvent.setBrokerAccountServiceBindingSucceed(serviceBound); } if (!serviceBound) { connection.unBindService(context); callback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED, "'bindService' returned 'false'")); } else { mUiHandler.postDelayed(timeoutRunnable, BIND_SERVICE_TIMEOUT_THRESHOLD); } }
Source:
public boolean canSyncNics(List<? extends NetworkInterface> currentDbNics, List<? extends NetworkInterface> snapshotedNics) { CountMacUsageDifference macUsageDifference = new CountMacUsageDifference(vmNicsToMacAddresses(currentDbNics), vmNicsToMacAddresses(snapshotedNics), macsInSnapshotAreExpectedToBeAlreadyAllocated); List<String> macs = macUsageDifference.getMissingMacs(); if (macs.isEmpty()) { return true; } boolean canReallocateMacs = true; List<String> macsCopy = new ArrayList<>(macs); for (NetworkInterface vmInterface : snapshotedNics) { String originalMacAddress = vmInterface.getMacAddress(); if (macsCopy.contains(originalMacAddress)) { canReallocateMacs &= macPool.canAllocateNewMac(); } } return canReallocateMacs; }

Target:
public boolean canSyncNics(List<? extends NetworkInterface> currentDbNics, List<? extends NetworkInterface> snapshotedNics) { CountMacUsageDifference macUsageDifference = new CountMacUsageDifference(vmNicsToMacAddresses(currentDbNics), vmNicsToMacAddresses(snapshotedNics), macsInSnapshotAreExpectedToBeAlreadyAllocated); List<String> macsToBeAdded = macUsageDifference.getMissingMacs(); if (macsToBeAdded.isEmpty()) { return true; } List<String> macsToBeRemoved = macUsageDifference.getExtraMacs(); int numOfMacsToAdd = macsToBeAdded.size() - macsToBeRemoved.size(); return numOfMacsToAdd > 0 ? macPool.canAllocateMacAddresses(numOfMacsToAdd) : true; }
Source:
private List<CoordinatorDuty> makeCompactSegmentsDuty() { List<CoordinatorDuty> duties = new ArrayList<>(); duties.add(compactSegments); return ImmutableList.copyOf(duties); }

Target:
private List<CoordinatorDuty> makeCompactSegmentsDuty() { return ImmutableList.of(compactSegments); }
Source:
public void testCompletion() throws Exception { Set<Shell> beforeShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells())); editor.selectAndReveal(3, 0); ContentAssistAction action = (ContentAssistAction) editor.getAction(ITextEditorActionConstants.CONTENT_ASSIST); action.update(); action.run(); Set<Shell> afterShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells())); afterShell.removeAll(beforeShell); Assert.assertEquals("No completion", 1, afterShell.size()); Shell completionShell= afterShell.iterator().next(); Table completionProposalList = findCompletionSelectionControl(completionShell); Assert.assertEquals(1, completionProposalList.getItemCount()); TableItem completionProposalItem = completionProposalList.getItem(0); Assert.assertEquals("s are good for a beer.", ((ICompletionProposal)completionProposalItem.getData()).getDisplayString()); completionShell.close(); }

Target:
public void testCompletion() throws Exception { Set<Shell> beforeShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells())); editor.selectAndReveal(3, 0); ContentAssistAction action = (ContentAssistAction) editor.getAction(ITextEditorActionConstants.CONTENT_ASSIST); action.update(); action.run(); Set<Shell> afterShell = new HashSet<>(Arrays.asList(Display.getDefault().getShells())); afterShell.removeAll(beforeShell); assertEquals("No completion", 1, afterShell.size()); Shell completionShell= afterShell.iterator().next(); Table completionProposalList = findCompletionSelectionControl(completionShell); assertEquals(1, completionProposalList.getItemCount()); TableItem completionProposalItem = completionProposalList.getItem(0); assertEquals("s are good for a beer.", ((ICompletionProposal)completionProposalItem.getData()).getDisplayString()); completionShell.close(); }
Source:
public DetailedSampleBuilder(User user) { if (user != null) { securityProfile = new SecurityProfile(user); getSecurityProfile().getProfileId(); } }

Target:
public DetailedSampleBuilder(User user) { if (user != null) { securityProfile = new SecurityProfile(user); } }
Source:
private Mono<Address> addressLookup(ServiceMessage request) { return Mono.fromCallable(() -> router.route(serviceRegistry, request) .map(ServiceReference::address) .orElseThrow(() -> noReachableMemberException(request))) .doOnError( t -> { Optional<Object> dataOptional = Optional.ofNullable(request.data()); dataOptional.ifPresent(ReferenceCountUtil::safestRelease); }); }

Target:
private Mono<Address> addressLookup(ServiceMessage request) { Callable<Address> callable = () -> router .route(serviceRegistry, request) .map(ServiceReference::address) .orElseThrow(() -> noReachableMemberException(request)); return Mono.fromCallable(callable) .doOnError( t -> { Optional<Object> dataOptional = Optional.ofNullable(request.data()); dataOptional.ifPresent(ReferenceCountUtil::safestRelease); }); }
Source:
@Override public SVMLinearBinaryClassificationModel fit(DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, double[]> featureExtractor, IgniteBiFunction<K, V, Double> lbExtractor, int cols) { assert datasetBuilder != null; PartitionDataBuilder<K, V, SVMPartitionContext, LabeledDataset<Double, LabeledVector>> partDataBuilder = new SVMPartitionDataBuilderOnHeap<>( featureExtractor, lbExtractor, cols ); this.dataset = datasetBuilder.build( (upstream, upstreamSize) -> new SVMPartitionContext(), partDataBuilder ); final int weightVectorSizeWithIntercept = cols + 1; Vector weights = initializeWeightsWithZeros(weightVectorSizeWithIntercept); for (int i = 0; i < this.getAmountOfIterations(); i++) { Vector deltaWeights = calculateUpdates(weights); weights = weights.plus(deltaWeights); } return new SVMLinearBinaryClassificationModel(weights.viewPart(1, weights.size() - 1), weights.get(0)); }

Target:
@Override public SVMLinearBinaryClassificationModel fit(DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, double[]> featureExtractor, IgniteBiFunction<K, V, Double> lbExtractor, int cols) { assert datasetBuilder != null; PartitionDataBuilder<K, V, SVMPartitionContext, LabeledDataset<Double, LabeledVector>> partDataBuilder = new SVMPartitionDataBuilderOnHeap<>( featureExtractor, lbExtractor, cols ); Vector weights; try(Dataset<SVMPartitionContext, LabeledDataset<Double, LabeledVector>> dataset = datasetBuilder.build( (upstream, upstreamSize) -> new SVMPartitionContext(), partDataBuilder )) { final int weightVectorSizeWithIntercept = cols + 1; weights = initializeWeightsWithZeros(weightVectorSizeWithIntercept); for (int i = 0; i < this.getAmountOfIterations(); i++) { Vector deltaWeights = calculateUpdates(weights, dataset); weights = weights.plus(deltaWeights); } } catch (Exception e) { throw new RuntimeException(e); } return new SVMLinearBinaryClassificationModel(weights.viewPart(1, weights.size() - 1), weights.get(0)); }
Source:
public String apply(final String password) { final String hashed = hashPasswordWithSalt(password); return BCrypt.with(LongPasswordStrategies.none()).hashToString(10, hashed.toCharArray()); }

Target:
public String apply(final String password) { final String hashed = hashPasswordWithSalt(password); return hashPassword(hashed); }
Source:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton<T>) f; } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }

Target:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton) f; } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }
Source:
public APIResult submitExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { InputStream configStream = getServletInputStream(configPath); try { List<Entity> entities = getEntities(extensionName, jobName, configStream); List<Feed> feeds = new ArrayList<>(); List<Process> processes = new ArrayList<>(); for (Entity entity : entities) { if (EntityType.FEED.equals(entity.getEntityType())) { feeds.add((Feed)entity); } else if (EntityType.PROCESS.equals(entity.getEntityType())) { processes.add((Process)entity); } } return localExtensionManager.submitExtensionJob(extensionName, jobName, configStream, feeds, processes); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }

Target:
public APIResult submitExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { InputStream configStream = getServletInputStream(configPath); try { Map<EntityType, List<Entity>> entityMap = getEntityTypeListMap(extensionName, jobName, configStream); return localExtensionManager.submitExtensionJob(extensionName, jobName, configStream, entityMap); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }
Source:
protected boolean downloadAsset(final SwrveAssetsQueueItem assetItem, final String cdnRoot) { boolean success = false; String url = cdnRoot + assetItem.getName(); InputStream inputStream = null; try { URLConnection openConnection = new URL(url).openConnection(); inputStream = new SwrveFilterInputStream(openConnection.getInputStream()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { stream.write(buffer, 0, bytesRead); } byte[] fileContents = stream.toByteArray(); String sha1File = SwrveHelper.sha1(stream.toByteArray()); if (assetItem.getDigest().equals(sha1File)) { FileOutputStream fileStream = new FileOutputStream(new File(storageDir, assetItem.getName())); fileStream.write(fileContents); fileStream.close(); success = true; } else { SwrveLogger.e(LOG_TAG, "Error downloading asset:" + assetItem + ". Did not match sha:" + sha1File); } } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error downloading asset:" + assetItem, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error closing assets stream.", e); } } } return success; }

Target:
protected boolean downloadAsset(final SwrveAssetsQueueItem assetItem, final String cdnRoot) { boolean success = false; String url = cdnRoot + assetItem.getName(); InputStream inputStream = null; try { URLConnection openConnection = new URL(url).openConnection(); inputStream = new SwrveFilterInputStream(openConnection.getInputStream()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { stream.write(buffer, 0, bytesRead); } byte[] fileContents = stream.toByteArray(); String sha1File = SwrveHelper.sha1(stream.toByteArray()); if (assetItem.getDigest().equals(sha1File)) { FileOutputStream fileStream = new FileOutputStream(new File(storageDir, assetItem.getName())); fileStream.write(fileContents); fileStream.close(); success = true; } else { SwrveLogger.e(LOG_TAG, "Error downloading assetItem:" + assetItem + ". Did not match digest:" + sha1File); } } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error downloading asset:" + assetItem, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error closing assets stream.", e); } } } return success; }
Source:
public void verify() { if (previousCallHistory == null) { if (currentCallHistory.size() == 0) { return; } throw new AssertionFailedError("unexpected"); } if (ordered) { int numMissingCalls = previousCallHistory.size() - currentCallHistory.size(); if (numMissingCalls > 0) { throw new AssertionFailedError("missing method calls (" + numMissingCalls + ", first is: " + previousCallHistory.get(currentCallHistory.size()) + ")"); } for (int i = 0; i < previousCallHistory.size(); i++) { if (!previousCallHistory.get(i).equals( currentCallHistory.get(i))) { throw new AssertionFailedError( "method call did not match (" + i + " of " + currentCallHistory.size() + ")"); } } } else { for (Iterator<MethodCall> it = previousCallHistory.iterator(); it.hasNext();) { MethodCall methodCall = it.next(); if (!currentCallHistory.contains(methodCall)) { throw new AssertionFailedError("missing method call:" + methodCall.method.getName()); } } } reset(); }

Target:
public void verify() { if (previousCallHistory == null) { if (currentCallHistory.size() == 0) { return; } throw new AssertionFailedError("unexpected"); } if (ordered) { int numMissingCalls = previousCallHistory.size() - currentCallHistory.size(); if (numMissingCalls > 0) { throw new AssertionFailedError("missing method calls (" + numMissingCalls + ", first is: " + previousCallHistory.get(currentCallHistory.size()) + ")"); } for (int i = 0; i < previousCallHistory.size(); i++) { if (!previousCallHistory.get(i).equals( currentCallHistory.get(i))) { throw new AssertionFailedError( "method call did not match (" + i + " of " + currentCallHistory.size() + ")"); } } } else { for (MethodCall methodCall : previousCallHistory) { if (!currentCallHistory.contains(methodCall)) { throw new AssertionFailedError("missing method call:" + methodCall.method.getName()); } } } reset(); }
Source:
public Subscriptions getAccountSubscriptions(final String accountCode, final String status) { return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + Subscriptions.SUBSCRIPTIONS_RESOURCE + "?state=" + status, Subscriptions.class); }

Target:
public Subscriptions getAccountSubscriptions(final String accountCode, final String status) { final QueryParams params = new QueryParams(); if (status != null) params.put("state", status); return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + Subscriptions.SUBSCRIPTIONS_RESOURCE, Subscriptions.class, params); }
Source:
private static void preparePrologue( @Nonnull CandidateInfo candidate, @Nonnull PrologueInfo prologue, @Nonnull TransformationRequest tr) { List<JParameter> params = candidate.target.getParams(); for (int i = 0; i < candidate.callSite.getArgs().size(); i++) { JExpression arg = candidate.callSite.getArgs().get(i); JLocal local = new JLocal( candidate.callSite.getSourceInfo(), ".inline_param_" + params.get(i).getName(), params.get(i).getType(), params.get(i).getModifier() | JModifier.SYNTHETIC, (JMethodBody) candidate.target.getBody()); prologue.parameterMap.put(params.get(i), local); JMethodBody enclosingBody = candidate.callSiteMethodBody; assert enclosingBody != null; tr.append(new AddJLocalInMethodBody(local, enclosingBody)); tr.append( new AppendBefore( candidate.callSiteStmt, new JExpressionStatement( candidate.callSite.getSourceInfo(), new JAsgOperation( candidate.callSite.getSourceInfo(), local.makeRef(candidate.callSite.getSourceInfo()), arg)))); } if (prologue.targetThis != null) { JLocal local = new JLocal( candidate.callSite.getSourceInfo(), ".inline_this", prologue.targetThis.getType(), JModifier.SYNTHETIC, (JMethodBody) candidate.target.getBody()); JMethodBody enclosingBody = candidate.callSiteMethodBody; assert enclosingBody != null; tr.append(new AddJLocalInMethodBody(local, enclosingBody)); tr.append( new AppendBefore( candidate.callSiteStmt, new JExpressionStatement( candidate.callSite.getSourceInfo(), new JAsgOperation( candidate.callSite.getSourceInfo(), local.makeRef(candidate.callSite.getSourceInfo()), prologue.targetThis)))); prologue.targetThisLocal = local; } }

Target:
private static void preparePrologue( @Nonnull CandidateInfo candidate, @Nonnull PrologueInfo prologue, @Nonnull TransformationRequest tr) { SourceInfo src = candidate.callSite.getSourceInfo(); List<JParameter> params = candidate.target.getParams(); for (int i = 0; i < candidate.callSite.getArgs().size(); i++) { JExpression arg = candidate.callSite.getArgs().get(i); JLocal local = new JLocal( src, ".inline_param_" + params.get(i).getName(), params.get(i).getType(), params.get(i).getModifier() | JModifier.SYNTHETIC, (JMethodBody) candidate.target.getBody()); prologue.parameterMap.put(params.get(i), local); JMethodBody enclosingBody = candidate.callSiteMethodBody; assert enclosingBody != null; tr.append(new AddJLocalInMethodBody(local, enclosingBody)); tr.append( new AppendBefore( candidate.callSiteStmt, new JExpressionStatement( src, new JAsgOperation( src, local.makeRef(src), arg)))); } if (prologue.targetThis != null) { JLocal local = new JLocal( src, ".inline_this", prologue.targetThis.getType(), JModifier.SYNTHETIC, (JMethodBody) candidate.target.getBody()); JMethodBody enclosingBody = candidate.callSiteMethodBody; assert enclosingBody != null; tr.append(new AddJLocalInMethodBody(local, enclosingBody)); tr.append( new AppendBefore( candidate.callSiteStmt, new JExpressionStatement( src, new JAsgOperation( src, local.makeRef(src), prologue.targetThis)))); prologue.targetThisLocal = local; } }
Source:
private void createDeviceDataTable(final SuripuAppConfiguration configuration, final AWSCredentialsProvider awsCredentialsProvider) { final AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentialsProvider); final DynamoDBConfiguration config = configuration.getDeviceDataConfiguration(); final String tableName = config.getTableName(); client.setEndpoint(config.getEndpoint()); final DeviceDataDAODynamoDB deviceDataDAODynamoDB = new DeviceDataDAODynamoDB(client, tableName); final DateTime now = DateTime.now(); for (int i = 0; i < 6; i++) { final DateTime currDateTime = now.plusMonths(i); try { client.describeTable(deviceDataDAODynamoDB.getTableName(currDateTime)); System.out.println(String.format("%s already exists.", deviceDataDAODynamoDB.getTableName(currDateTime))); } catch (AmazonServiceException exception) { final CreateTableResult result = deviceDataDAODynamoDB.createTable(currDateTime); System.out.println(result.getTableDescription().getTableStatus()); } } }

Target:
private void createDeviceDataTable(final SuripuAppConfiguration configuration, final AWSCredentialsProvider awsCredentialsProvider) { final AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentialsProvider); final DynamoDBConfiguration config = configuration.getDeviceDataConfiguration(); final String tablePrefix = config.getTableName(); client.setEndpoint(config.getEndpoint()); final DeviceDataDAODynamoDB deviceDataDAODynamoDB = new DeviceDataDAODynamoDB(client, tablePrefix); final DateTime now = DateTime.now(DateTimeZone.UTC); for (int i = 0; i < 6; i++) { final DateTime currDateTime = now.plusMonths(i); try { client.describeTable(deviceDataDAODynamoDB.getTableName(currDateTime)); System.out.println(String.format("%s already exists.", deviceDataDAODynamoDB.getTableName(currDateTime))); } catch (AmazonServiceException exception) { final String tableName = deviceDataDAODynamoDB.getTableName(currDateTime); final CreateTableResult result = deviceDataDAODynamoDB.createTable(tableName); System.out.println(result.getTableDescription().getTableStatus()); } } }
Source:
public Optional<DecorrelationResult> visitFilter(FilterNode node, Void context) { Expression predicate = node.getPredicate(); if (!SymbolsExtractor.extractUnique(predicate).containsAll(correlation)) { return Optional.empty(); } Map<Boolean, List<Expression>> predicates = ExpressionUtils.extractConjuncts(predicate).stream() .collect(Collectors.partitioningBy(isUsingPredicate(correlation))); List<Expression> correlatedPredicates = ImmutableList.copyOf(predicates.get(true)); List<Expression> uncorrelatedPredicates = ImmutableList.copyOf(predicates.get(false)); FilterNode newFilterNode = new FilterNode( idAllocator.getNextId(), node.getSource(), ExpressionUtils.combineConjuncts(uncorrelatedPredicates)); return Optional.of(new DecorrelationResult( newFilterNode, Sets.difference(SymbolsExtractor.extractUnique(correlatedPredicates), ImmutableSet.copyOf(correlation)), correlatedPredicates)); }

Target:
public Optional<DecorrelationResult> visitFilter(FilterNode node, Void context) { Optional<DecorrelationResult> childDecorrelationResultOptional = Optional.of(new DecorrelationResult( node.getSource(), ImmutableSet.of(), ImmutableList.of(), ImmutableMultimap.of(), false)); if (containsCorrelation(node.getSource(), correlation)) { childDecorrelationResultOptional = lookup.resolve(node.getSource()).accept(this, null); } if (!childDecorrelationResultOptional.isPresent()) { return Optional.empty(); } Expression predicate = node.getPredicate(); Map<Boolean, List<Expression>> predicates = ExpressionUtils.extractConjuncts(predicate).stream() .collect(Collectors.partitioningBy(PlanNodeDecorrelator.DecorrelatingVisitor.this::isCorrelated)); List<Expression> correlatedPredicates = ImmutableList.copyOf(predicates.get(true)); List<Expression> uncorrelatedPredicates = ImmutableList.copyOf(predicates.get(false)); DecorrelationResult childDecorrelationResult = childDecorrelationResultOptional.get(); FilterNode newFilterNode = new FilterNode( idAllocator.getNextId(), childDecorrelationResult.node, ExpressionUtils.combineConjuncts(uncorrelatedPredicates)); Set<Symbol> symbolsToPropagate = Sets.difference(SymbolsExtractor.extractUnique(correlatedPredicates), ImmutableSet.copyOf(correlation)); return Optional.of(new DecorrelationResult( newFilterNode, Sets.union(childDecorrelationResult.symbolsToPropagate, symbolsToPropagate), ImmutableList.<Expression>builder() .addAll(childDecorrelationResult.correlatedPredicates) .addAll(correlatedPredicates) .build(), ImmutableMultimap.<Symbol, Symbol>builder() .putAll(childDecorrelationResult.correlatedSymbolsMapping) .putAll(extractCorrelatedSymbolsMapping(correlatedPredicates)) .build(), childDecorrelationResult.atMostSingleRow)); }