auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setUp() throws Exception { super.setUp(); if (USE_DOMAIN_SOCKETS) { assertTrue("Native transport not enabled", USE_NATIVE_TRANSPORT); tmp = TestUtils.tmpFile("vertx", ".sock"); testAddress = SocketAddress.domainSocketAddress(tmp.getAbsolutePath()); } else { testAddress = SocketAddress.inetSocketAddress(1234, "localhost"); } testDir = testFolder.newFolder(); }

Target:
public void setUp() throws Exception { super.setUp(); testDir = testFolder.newFolder(); }
Source:
public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String id, @QueryParam("key") String apiKey) { try { Dataset dataset = findDatasetOrDie(id); RoleAssignee assignee = findAssignee(ra.getAssignee()); if (assignee == null) { return error(Response.Status.BAD_REQUEST, "Assignee not found"); } DataverseRole theRole; Dataverse dv = dataset.getOwner(); theRole = null; while ((theRole == null) && (dv != null)) { for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) { if (aRole.getAlias().equals(ra.getRole())) { theRole = aRole; break; } } dv = dv.getOwner(); } if (theRole == null) { return error(Status.BAD_REQUEST, "Can't find role named '" + ra.getRole() + "' in dataverse " + dataset.getOwner()); } String privateUrlToken = null; return ok( json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken)))); } catch (WrappedResponse ex) { logger.log(Level.WARNING, "Can''t create assignment: {0}", ex.getMessage()); return ex.getResponse(); } }

Target:
public Response createAssignment(RoleAssignmentDTO ra, @PathParam("identifier") String id, @QueryParam("key") String apiKey) { try { Dataset dataset = findDatasetOrDie(id); RoleAssignee assignee = findAssignee(ra.getAssignee()); if (assignee == null) { return error(Response.Status.BAD_REQUEST, BundleUtil.getStringFromBundle("datasets.api.grant.role.assignee.not.found.error")); } DataverseRole theRole; Dataverse dv = dataset.getOwner(); theRole = null; while ((theRole == null) && (dv != null)) { for (DataverseRole aRole : rolesSvc.availableRoles(dv.getId())) { if (aRole.getAlias().equals(ra.getRole())) { theRole = aRole; break; } } dv = dv.getOwner(); } if (theRole == null) { List<String> args = Arrays.asList(ra.getRole(), dataset.getOwner().getDisplayName()); return error(Status.BAD_REQUEST, BundleUtil.getStringFromBundle("datasets.api.grant.role.not.found.error", args)); } String privateUrlToken = null; return ok( json(execCommand(new AssignRoleCommand(assignee, theRole, dataset, createDataverseRequest(findUserOrDie()), privateUrlToken)))); } catch (WrappedResponse ex) { List<String> args = Arrays.asList(ex.getMessage()); logger.log(Level.WARNING, BundleUtil.getStringFromBundle("datasets.api.grant.role.cant.create.assignment.error", args)); return ex.getResponse(); } }
Source:
public void run() { try { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); firstMatchSimpleFilter.addFilterEntries( configurationFilters ); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { FilterEntry.createEntry( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } } for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (SQLException se) { distributeDbDownEvent(); throw se; } } catch (Throwable t) { log.error(String.format("Failed to run the service."), t); } }

Target:
public void run() { try { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { new FirstMatchSimpleFilter.FilterEntry( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } } firstMatchSimpleFilter.addFilterEntries( configurationFilters ); for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (SQLException se) { distributeDbDownEvent(); throw se; } } catch (Throwable t) { log.error(String.format("Failed to run the service."), t); } }
Source:
public NutchJob(Configuration conf) throws IOException { super(conf, "NutchJob"); }

Target:
public NutchJob(Configuration conf) { super(conf, NutchJob.class); }
Source:
AttributeMapping(String searchDn, String filter, String ldapName) { Assert.checkNotNullParam("ldapName", ldapName); this.searchDn = searchDn; this.filter = filter; this.ldapName = ldapName.toUpperCase(Locale.ENGLISH); }

Target:
AttributeMapping(String searchDn, String filter, String ldapName) { Assert.checkNotNullParam("ldapName", ldapName); this.searchDn = searchDn; this.filter = filter; this.ldapName = ldapName.toUpperCase(Locale.ROOT); }
Source:
public void getEventsForTransactionsReturnsSnapshotWithOldEvents() { setupInitialState(); eventCache.processGetCommitTimestampsUpdate(COMMIT_UPDATE, SUCCESS); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS_2); verifyStage(); TransactionsLockWatchUpdate results = eventCache.getUpdateForTransactions(TIMESTAMPS_2, Optional.empty()); assertThat(results.clearCache()).isTrue(); assertThat(results.startTsToSequence()).containsExactlyInAnyOrderEntriesOf( ImmutableMap.of(16L, LockWatchVersion.of(LEADER, 7L))); assertThat(results.events()).containsExactly( LockWatchCreatedEvent.builder(ImmutableSet.of(REFERENCE), ImmutableSet.of(DESCRIPTOR, DESCRIPTOR_2)).build(4L), UNLOCK_EVENT, LOCK_EVENT, LOCK_EVENT_2); }

Target:
public void getEventsForTransactionsReturnsSnapshotWithOldEvents() { eventCache = createEventCache(3); setupInitialState(); eventCache.processGetCommitTimestampsUpdate(COMMIT_UPDATE, SUCCESS); eventCache.removeTransactionStateFromCache(START_TS); verifyStage(); eventCache.processStartTransactionsUpdate(TIMESTAMPS_2, SUCCESS_2); verifyStage(); TransactionsLockWatchUpdate results = eventCache.getUpdateForTransactions(TIMESTAMPS_2, Optional.empty()); assertThat(results.clearCache()).isTrue(); assertThat(results.startTsToSequence()).containsExactlyInAnyOrderEntriesOf( ImmutableMap.of(16L, LockWatchVersion.of(LEADER, 7L))); assertThat(results.events()).containsExactly( LockWatchCreatedEvent.builder(ImmutableSet.of(REFERENCE), ImmutableSet.of(DESCRIPTOR, DESCRIPTOR_2)).build(4L), UNLOCK_EVENT, LOCK_EVENT, LOCK_EVENT_2); }
Source:
public synchronized JsonElement callMethod(SonyAudioMethod method) throws IOException { try { method.id = nextMessageId; String message = mapper.toJson(method); commandLatch = new CountDownLatch(1); commandResponse = null; nextMessageId++; sendMessage(message); if (commandLatch.await(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { logger.debug("callMethod returns {}", commandResponse.toString()); return commandResponse.get("result"); } else { logger.error("Timeout during callMethod({}, {})", method.method, message); throw new IOException("Timeout during callMethod"); } } catch (Exception e) { throw new IOException("Error during callMethod", e); } }

Target:
public synchronized JsonElement callMethod(SonyAudioMethod method) throws IOException { try { method.id = nextMessageId; String message = mapper.toJson(method); logger.debug("callMethod send {}", message); commandLatch = new CountDownLatch(1); commandResponse = null; nextMessageId++; sendMessage(message); if (commandLatch.await(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { logger.debug("callMethod returns {}", uri.toString(), commandResponse.toString()); return commandResponse.get("result"); } else { logger.debug("Timeout during callMethod({}, {})", method.method, message); throw new IOException("Timeout during callMethod"); } } catch (InterruptedException e) { throw new IOException("Timeout in callMethod"); } }
Source:
public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name) throws MetaException { try { return getNotNullConstraintsInternal(db_name, tbl_name, true, true); } catch (NoSuchObjectException e) { throw new MetaException(e.getMessage()); } }

Target:
public List<SQLNotNullConstraint> getNotNullConstraints(String db_name, String tbl_name) throws MetaException { try { return getNotNullConstraintsInternal(db_name, tbl_name, true, true); } catch (NoSuchObjectException e) { throw new MetaException(ExceptionUtils.getStackTrace(e)); } }
Source:
public synchronized void dropView(final String view) throws DatabaseEngineException { Statement drop = null; try { drop = conn.createStatement(); final String query = format("DROP VIEW %s", quotize(view, escapeCharacter())); logger.trace(query); drop.executeUpdate(query); } catch (final SQLException ex) { throw new DatabaseEngineException("Error dropping view", ex); } finally { try { if (drop != null) { drop.close(); } } catch (final Exception e) { logger.trace("Error closing statement.", e); } } }

Target:
public synchronized void dropView(final String view) throws DatabaseEngineException { try (final Statement statement = conn.createStatement()) { final String query = format("DROP VIEW %s", quotize(view, escapeCharacter())); logger.trace(query); statement.executeUpdate(query); } catch (final SQLException ex) { throw new DatabaseEngineException("Error dropping view", ex); } }
Source:
public Collection<Class<? extends DataProvider>> getRequiredDataProviders(String identifier) { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(identifier); String visualizationClassName = settings.getVisualizationClassName(); return StreamSupport.stream(ServiceLoader.load(Visualization.Factory.class).spliterator(), false) .filter(factory -> visualizationClassName.equals(factory.getVisualizationClass().getName())) .findFirst().orElseThrow(() -> new RuntimeException("Failed: No Visualization.Factory found for " + identifier + " and " + visualizationClassName) ).getRequiredDataProviders(settings); }

Target:
public Collection<Class<? extends DataProvider>> getRequiredDataProviders(String identifier) { StepEngineSettings.VisualizationSetting settings = visualizationSettingsMap.get(identifier); String visualizationClassName = settings.getVisualizationClassName(); return getVisualizationFactory(identifier, visualizationClassName).getRequiredDataProviders(settings); }
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { UpdatePartitionColumnStatMessage upcsm = deserializer.getUpdatePartitionColumnStatMessage(context.dmd.getPayload()); ColumnStatistics colStats = upcsm.getColumnStatistics(); ColumnStatisticsDesc colStatsDesc = colStats.getStatsDesc(); colStatsDesc.setDbName(context.dbName); if (!context.isTableNameEmpty()) { colStatsDesc.setTableName(context.tableName); } if (!context.isDbNameEmpty()) { updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); } return Collections.singletonList(TaskFactory.get(new ColumnStatsUpdateWork(colStats), context.hiveConf)); }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { UpdatePartitionColumnStatMessage upcsm = deserializer.getUpdatePartitionColumnStatMessage(context.dmd.getPayload()); ColumnStatistics colStats = upcsm.getColumnStatistics(); ColumnStatisticsDesc colStatsDesc = colStats.getStatsDesc(); if (!context.isTableNameEmpty()) { colStatsDesc.setTableName(context.tableName); } if (!context.isDbNameEmpty()) { colStatsDesc.setDbName(context.dbName); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); } return Collections.singletonList(TaskFactory.get(new ColumnStatsUpdateWork(colStats), context.hiveConf)); }
Source:
public ImmutableBoundedValue<Double> walkSpeed() { return new ImmutableSpongeBoundedValue<>(Keys.WALKING_SPEED, this.walkSpeed, 0.1d, doubleComparator(), Double.MIN_VALUE, Double.MAX_VALUE); }

Target:
public ImmutableBoundedValue<Double> walkSpeed() { return walkSpeedValue; }
Source:
public void variables() throws Exception { List<String> arrayList = new ArrayList<>(); arrayList.add("bar"); arrayList.add("zip"); CoreEvent in = eventBuilder(muleContext).message(of(arrayList)).build(); process(simpleForeach, in); assertSimpleProcessedMessages(); assertThat(variables.keySet(), hasSize(2)); assertThat(variables.keySet(), hasItems(DEFAULT_ROOT_MESSAGE_VARIABLE, DEFAULT_COUNTER_VARIABLE)); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getDataType(), is(assignableTo(MULE_MESSAGE))); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getValue(), equalTo(in.getMessage())); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getDataType(), equalTo(DataType.builder().type(Number.class).build())); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getValue(), equalTo(2)); }

Target:
public void variables() throws Exception { List<String> arrayList = new ArrayList<>(); arrayList.add("bar"); arrayList.add("zip"); CoreEvent in = eventBuilder(muleContext).message(of(arrayList)).build(); process(simpleForeach, in); assertSimpleProcessedMessages(); assertThat(variables.keySet(), hasSize(2)); assertThat(variables.keySet(), hasItems(DEFAULT_ROOT_MESSAGE_VARIABLE, DEFAULT_COUNTER_VARIABLE)); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getDataType(), is(assignableTo(MULE_MESSAGE))); assertThat(variables.get(DEFAULT_ROOT_MESSAGE_VARIABLE).getValue(), equalTo(in.getMessage())); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getDataType(), equalTo(NUMBER)); assertThat(variables.get(DEFAULT_COUNTER_VARIABLE).getValue(), equalTo(2)); }
Source:
private void handleSelectorEvents(List<ResponseInfo> responseInfoList) { logger.trace("Handling selector events at " + time.milliseconds()); for (String connId : selector.connected()) { logger.trace("Checking in connection back to connection tracker for connectionId " + connId); connectionTracker.checkInConnection(connId); } for (String connId : selector.disconnected()) { logger.trace( "Connection disconnected for connectionId " + connId + " and hence removing it from connection tracker"); connectionTracker.removeConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); if (requestMetadata != null) { responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), NetworkClientErrorCode.NetworkError, null)); } } for (NetworkReceive recv : selector.completedReceives()) { String connId = recv.getConnectionId(); logger.trace("Receive completed for connectionId " + connId + " and checking in the connection back to connection tracker"); connectionTracker.checkInConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), null, recv.getReceivedBytes().getPayload())); requestMetadata.onResponseReceive(); } }

Target:
private void handleSelectorEvents(List<ResponseInfo> responseInfoList) { for (String connId : selector.connected()) { logger.trace("Checking in connection back to connection tracker for connectionId ", connId); connectionTracker.checkInConnection(connId); } for (String connId : selector.disconnected()) { logger.trace("Connection disconnected for connectionId and hence removing it from connection tracker", connId); connectionTracker.removeConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); if (requestMetadata != null) { responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), NetworkClientErrorCode.NetworkError, null)); } } for (NetworkReceive recv : selector.completedReceives()) { String connId = recv.getConnectionId(); logger.trace("Receive completed for connectionId and checking in the connection back to connection tracker", connId); connectionTracker.checkInConnection(connId); RequestMetadata requestMetadata = connectionIdToRequestInFlight.remove(connId); responseInfoList.add( new ResponseInfo(requestMetadata.requestInfo.getRequest(), null, recv.getReceivedBytes().getPayload())); requestMetadata.onResponseReceive(); } }
Source:
public void doubleClickTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement dbClickButton = iface.getWebDriverElement(new Hook(Strategy.ID, "buttonId")); dbClickButton.doubleClick(); Assert.assertTrue(iface.isDialogVisible()); }

Target:
public void doubleClickTest() throws Exception { iface.go("<LINK_0>"); WebDriverElement dbClickButton = iface.getWebDriverElement(new Hook(Strategy.ID, "buttonId")); dbClickButton.doubleClick(); Assert.assertTrue(iface.isDialogVisible()); iface.acceptDialog(); }
Source:
public RequestBuilder buildRequest(Api api) { return api.action("query") .param("list", "random") .param("rnnamespace", "0") .param("rnlimit", "10"); }

Target:
public RequestBuilder buildRequest(Api api) { return api.action("query") .param("prop","pageprops|pageimages") .param("ppprop","wikibase_item") .param("pithumbsize", "144") .param("pilimit", "10") .param("generator", "random") .param("grnnamespace", "0") .param("grnlimit", "10"); }
Source:
public Optional<List<SingularityMesosArtifact>> getExtraArtifacts() { return extraArtifacts; }

Target:
public List<SingularityMesosArtifact> getExtraArtifacts() { return extraArtifacts; }
Source:
private void setParentOverflow(Element e, Style.Overflow visible) { if (e != null && e != asWidget().getElement()) { e.getParentElement().getStyle().setOverflow(visible); setParentOverflow(e.getParentElement(), visible); } }

Target:
private void setParentOverflow(Element e, Style.Overflow visible) { if (e != null && !e.equals(asWidget().getElement())) { e.getParentElement().getStyle().setOverflow(visible); setParentOverflow(e.getParentElement(), visible); } }
Source:
protected Control createControl(Composite parent) { toolbar = new FindToolbar(parent); toolbar.setBackground(null); toolbar.addKeyListener(keyListener); toolbar.addListener(SWT.FocusIn, mouseListener); toolbar.addListener(SWT.FocusOut, mouseListener); toolbar.addListener(SWT.MouseDown, mouseListener); toolbar.addListener(SWT.MouseUp, mouseListener); toolbar.addListener(SWT.Modify, (e) -> lastText = toolbar.getText()); toolbar.addSelectionListener(selectionListener); toolbar.addStatusListener(this::showStatus); boolean hasInput = provider != null; if (hasInput) { setInput(provider); } if (lastText != null) { if (lastSearchContext != null && lastSearchContext.equals(searchContext)) { toolbar.setPreselect(lastObjectId); } toolbar.setText(lastText, hasInput); } lastSearchContext = null; lastObjectId = null; if (wasVisible) { return toolbar; } wasVisible = true; toolbar.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (toolbar != null && !toolbar.isDisposed()) { graph.getControl().setFocus(); toolbar.setFocus(); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(toolbar); return toolbar; }

Target:
protected FindToolbar createControl(Composite parent) { toolbar = new FindToolbar(parent); toolbar.setBackground(null); toolbar.addListener(SWT.Modify, (e) -> lastText = toolbar.getText()); toolbar.addSelectionListener(selectionListener); toolbar.addStatusListener(this::showStatus); boolean hasInput = provider != null; if (hasInput) { setInput(provider); } if (lastText != null) { if (lastSearchContext != null && lastSearchContext.equals(searchContext)) { toolbar.setPreselect(lastObjectId); } toolbar.setText(lastText, hasInput); } lastSearchContext = null; lastObjectId = null; GridDataFactory.fillDefaults().grab(true, false).applyTo(toolbar); return toolbar; }
Source:
public Notification build() { NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_PLAYING); if (playable != null) { notification.setContentTitle(Html.fromHtml("<b>" + playable.getFeedTitle() + "</b>")); notification.setContentText(playable.getEpisodeTitle()); addActions(notification, mediaSessionToken, playerStatus, isCasting); if (icon != null) { notification.setLargeIcon(icon); } else { notification.setLargeIcon(getDefaultIcon()); } if (Build.VERSION.SDK_INT < 29) { notification.setSubText(position); } } else { notification.setContentTitle(context.getString(R.string.app_name)); notification.setContentText("Loading. If this does not go away, play any episode and contact us."); } notification.setContentIntent(getPlayerActivityPendingIntent()); notification.setWhen(0); notification.setSmallIcon(R.drawable.ic_antenna); notification.setOngoing(false); notification.setOnlyAlertOnce(true); notification.setShowWhen(false); notification.setPriority(UserPreferences.getNotifyPriority()); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setColor(NotificationCompat.COLOR_DEFAULT); return notification.build(); }

Target:
public Notification build() { NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationUtils.CHANNEL_ID_PLAYING); if (playable != null) { notification.setContentTitle(playable.getFeedTitle()); notification.setContentText(playable.getEpisodeTitle()); addActions(notification, mediaSessionToken, playerStatus, isCasting); if (icon != null) { notification.setLargeIcon(icon); } else { notification.setLargeIcon(getDefaultIcon()); } if (Build.VERSION.SDK_INT < 29) { notification.setSubText(position); } } else { notification.setContentTitle(context.getString(R.string.app_name)); notification.setContentText("Loading. If this does not go away, play any episode and contact us."); } notification.setContentIntent(getPlayerActivityPendingIntent()); notification.setWhen(0); notification.setSmallIcon(R.drawable.ic_antenna); notification.setOngoing(false); notification.setOnlyAlertOnce(true); notification.setShowWhen(false); notification.setPriority(UserPreferences.getNotifyPriority()); notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); notification.setColor(NotificationCompat.COLOR_DEFAULT); return notification.build(); }
Source:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewrite(lambdaExpression.getBody(), session, metadata, sqlParser, symbolAllocator)); } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList(), WarningCollector.NOOP); return rewrite(expression, expressionTypes); }

Target:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } return new AnalyzedExpressionRewriter(session, metadata, sqlParser, symbolAllocator.getTypes()).rewriteWith(Visitor::new, expression); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.createImageryWithLabels()); mMapView.setMap(map); requestReadPermission(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Type.DARK_GRAY_CANVAS_VECTOR, 51.960403, 10.029217, 5); mMapView.setMap(map); KmlDataset kmlDataset = new KmlDataset(getString(R.string.kml_url)); kmlDataset.addKmlNetworkLinkMessageReceivedListener(kmlNetworkLinkMessageReceivedEvent -> { String message = "KML Network Link Message: " + kmlNetworkLinkMessageReceivedEvent.getMessage(); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); Log.i(TAG, message); }); KmlLayer kmlLayer = new KmlLayer(kmlDataset); mMapView.getMap().getOperationalLayers().clear(); mMapView.getMap().getOperationalLayers().add(kmlLayer); kmlDataset.addDoneLoadingListener(() -> { if (kmlDataset.getLoadStatus() != LoadStatus.LOADED) { String error = "Failed to load kml layer from URL: " + kmlDataset.getLoadError().getMessage(); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); Log.e(TAG, error); } }); }
Source:
public TaskStatus process() { while (true) { if (stopped) { return TaskStatus.finished(); } CompletableFuture<?> future; taskExecutionLock.readLock().lock(); try { future = loadSplits(); } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); continue; } finally { taskExecutionLock.readLock().unlock(); } invokeNoMoreSplitsIfNecessary(); if (!future.isDone()) { return TaskStatus.continueOn(future); } } }

Target:
public TaskStatus process() { while (true) { if (stopped) { return TaskStatus.finished(); } CompletableFuture<?> future; taskExecutionLock.readLock().lock(); try { future = loadSplits(); } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); return TaskStatus.finished(); } finally { taskExecutionLock.readLock().unlock(); } invokeNoMoreSplitsIfNecessary(); if (!future.isDone()) { return TaskStatus.continueOn(future); } } }
Source:
public SqlIOConfig(String systemName, String streamName, List<String> sourceParts, Config systemConfig, TableDescriptor tableDescriptor) { HashMap<String, String> streamConfigs = new HashMap<>(systemConfig); this.source = getSourceFromSourceParts(sourceParts); this.sourceParts = sourceParts; this.systemStream = new SystemStream(systemName, streamName); this.tableDescriptor = Optional.ofNullable(tableDescriptor); this.streamId = String.format("%s-%s", systemName, streamName); samzaRelConverterName = streamConfigs.get(CFG_SAMZA_REL_CONVERTER); Validate.notEmpty(samzaRelConverterName, String.format("System %s is unknown. %s is not set or empty for this" + " system", systemName, CFG_SAMZA_REL_CONVERTER)); if (isRemoteTable()) { samzaRelTableKeyConverterName = streamConfigs.get(CFG_SAMZA_REL_TABLE_KEY_CONVERTER); Validate.notEmpty(samzaRelTableKeyConverterName, String.format("System %s is unknown. %s is not set or empty for" + " this system", systemName, CFG_SAMZA_REL_CONVERTER)); } else { samzaRelTableKeyConverterName = ""; } relSchemaProviderName = streamConfigs.get(CFG_REL_SCHEMA_PROVIDER); streamConfigs.remove(CFG_SAMZA_REL_CONVERTER); streamConfigs.remove(CFG_REL_SCHEMA_PROVIDER); if (!isRemoteTable()) { streamConfigs.put(String.format(StreamConfig.PHYSICAL_NAME_FOR_STREAM_ID, streamId), streamName); if (tableDescriptor != null) { streamConfigs.put(String.format(StreamConfig.BOOTSTRAP_FOR_STREAM_ID, streamId), "true"); streamConfigs.put(String.format(StreamConfig.CONSUMER_OFFSET_DEFAULT_FOR_STREAM_ID, streamId), "oldest"); } } config = new MapConfig(streamConfigs); }

Target:
public SqlIOConfig(String systemName, String streamName, List<String> sourceParts, Config systemConfig, TableDescriptor tableDescriptor) { HashMap<String, String> streamConfigs = new HashMap<>(systemConfig); this.source = getSourceFromSourceParts(sourceParts); this.sourceParts = sourceParts; this.systemStream = new SystemStream(systemName, streamName); this.tableDescriptor = Optional.ofNullable(tableDescriptor); this.streamId = String.format("%s-%s", systemName, streamName); samzaRelConverterName = streamConfigs.get(CFG_SAMZA_REL_CONVERTER); Validate.notEmpty(samzaRelConverterName, String.format("System %s is not supported." + "Please check if the system name is provided correctly.", systemName)); if (isRemoteTable()) { samzaRelTableKeyConverterName = streamConfigs.get(CFG_SAMZA_REL_TABLE_KEY_CONVERTER); Validate.notEmpty(samzaRelTableKeyConverterName, String.format("System %s is not supported. " + "Please check if the system name is provided correctly.", systemName)); } else { samzaRelTableKeyConverterName = ""; } relSchemaProviderName = streamConfigs.get(CFG_REL_SCHEMA_PROVIDER); streamConfigs.remove(CFG_SAMZA_REL_CONVERTER); streamConfigs.remove(CFG_REL_SCHEMA_PROVIDER); if (!isRemoteTable()) { streamConfigs.put(String.format(StreamConfig.PHYSICAL_NAME_FOR_STREAM_ID, streamId), streamName); if (tableDescriptor != null) { streamConfigs.put(String.format(StreamConfig.BOOTSTRAP_FOR_STREAM_ID, streamId), "true"); streamConfigs.put(String.format(StreamConfig.CONSUMER_OFFSET_DEFAULT_FOR_STREAM_ID, streamId), "oldest"); } } config = new MapConfig(streamConfigs); }
Source:
private void buildPayload( String urlEncodedJson, String enc ) { try { JSONObject jsonVars = new JSONObject( urlEncodedJson ); String actionClass = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONCLASS ), enc ); String actionId = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONID ), enc ); actionUser = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONUSER ), enc ); workItemUid = URLDecoder.decode( jsonVars.getString( ActionUtil.WORK_ITEM_UID ), enc ); action = getActionBean( actionClass, actionId ); String stringActionParams = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONPARAMS ), enc ); ActionParams actionParams = ActionParams.fromJson( stringActionParams ); actionMap = ActionParams.deserialize( action, actionParams ); } catch ( JSONException | IOException | ActionInvocationException e ) { throw new IllegalArgumentException( e ); } }

Target:
private void buildPayload( String urlEncodedJson, String enc ) { try { JSONObject jsonVars = new JSONObject( urlEncodedJson ); String actionClass = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONCLASS ), enc ); String actionId = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONID ), enc ); actionUser = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONUSER ), enc ); action = getActionBean( actionClass, actionId ); String stringActionParams = URLDecoder.decode( jsonVars.getString( ActionUtil.INVOKER_ACTIONPARAMS ), enc ); ActionParams actionParams = ActionParams.fromJson( stringActionParams ); actionMap = ActionParams.deserialize( action, actionParams ); } catch ( JSONException | IOException | ActionInvocationException e ) { throw new IllegalArgumentException( e ); } }
Source:
public Optional<Row> getNextMergedRow() throws IOException { RowMerger builder = null; while (!lastResponseProcessed) { ResultQueueEntry<ReadRowsResponse> queueEntry = getNext(); if (queueEntry.isCompletionMarker()) { lastResponseProcessed = true; break; } ReadRowsResponse partialRow = queueEntry.getResponseOrThrow(); if (builder == null) { builder = new RowMerger(); } builder.addPartialRow(partialRow); if (builder.isRowCommitted()) { return Optional.of(builder.buildRow()); } } Preconditions.checkState( builder == null, "End of stream marker encountered while merging a row."); Preconditions.checkState( lastResponseProcessed, "Should only exit merge loop with by returning a complete Row or hitting end of stream."); return Optional.absent(); }

Target:
public synchronized Row getNextMergedRow() throws IOException { RowMerger builder = null; while (!lastResponseProcessed) { ResultQueueEntry<ReadRowsResponse> queueEntry = getNext(); if (queueEntry.isCompletionMarker()) { lastResponseProcessed = true; break; } ReadRowsResponse partialRow = queueEntry.getResponseOrThrow(); if (builder == null) { builder = new RowMerger(); } builder.addPartialRow(partialRow); if (builder.isRowCommitted()) { return builder.buildRow(); } } Preconditions.checkState( builder == null, "End of stream marker encountered while merging a row."); Preconditions.checkState( lastResponseProcessed, "Should only exit merge loop with by returning a complete Row or hitting end of stream."); return null; }
Source:
public void removeCache(String cacheName) { authzHelper.checkPermission(AuthorizationPermission.ADMIN); if (cacheManagerAdmin != null) cacheManagerAdmin.removeCache(cacheName); else { RemoveCacheCommand.removeCache(this, cacheName); } }

Target:
public void removeCache(String cacheName) { cacheManagerAdmin.removeCache(cacheName); }
Source:
private static void ensureEntry(final String path, final RemoteConfigurationRegistryClient remoteClient) { if (!remoteClient.entryExists(path)) { remoteClient.createEntry(path); } else { List<RemoteConfigurationRegistryClient.EntryACL> entryACLs = remoteClient.getACL(path); for (RemoteConfigurationRegistryClient.EntryACL entryACL : entryACLs) { if ("world".equals(entryACL.getType()) && "anyone".equals(entryACL.getId())) { LOG.suspectWritableRemoteConfigurationEntry(path); if (remoteClient.isAuthenticationConfigured()) { LOG.correctingSuspectWritableRemoteConfigurationEntry(path); if (remoteClient.authenticationType() .equalsIgnoreCase("Kerberos") && !remoteClient .isBackwardsCompatible()) { remoteClient.setACL(path, Collections.singletonList(KERBEROS_KNOX_ALL)); } else { remoteClient.setACL(path, Collections .singletonList(AUTHENTICATED_USERS_ALL)); } } } } } }

Target:
private static void ensureEntry(final String path, final RemoteConfigurationRegistryClient remoteClient) { if (!remoteClient.entryExists(path)) { remoteClient.createEntry(path); } else { List<RemoteConfigurationRegistryClient.EntryACL> entryACLs = remoteClient.getACL(path); for (RemoteConfigurationRegistryClient.EntryACL entryACL : entryACLs) { if ("world".equals(entryACL.getType()) && "anyone".equals(entryACL.getId())) { LOG.suspectWritableRemoteConfigurationEntry(path); if (remoteClient.isAuthenticationConfigured()) { LOG.correctingSuspectWritableRemoteConfigurationEntry(path); if(ZooKeeperClientService.AUTH_TYPE_KERBEROS.equalsIgnoreCase(remoteClient.authenticationType()) && !remoteClient.isBackwardsCompatible()) { remoteClient.setACL(path, Collections.singletonList(KERBEROS_KNOX_ALL)); } else { remoteClient.setACL(path, Collections .singletonList(AUTHENTICATED_USERS_ALL)); } } } } } }
Source:
public static void main(String[] args) throws FileNotFoundException { System.out.println(); System.out.println(">>> Logistic regression model loaded from Spark through serialization over partitioned dataset usage example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteCache<Integer, Object[]> dataCache = TitanicUtils.readPassengers(ignite); IgniteBiFunction<Integer, Object[], Vector> featureExtractor = (k, v) -> { double[] data = new double[] {(double)v[0], (double)v[5], (double)v[6]}; data[0] = Double.isNaN(data[0]) ? 0 : data[0]; data[1] = Double.isNaN(data[1]) ? 0 : data[1]; data[2] = Double.isNaN(data[2]) ? 0 : data[2]; return VectorUtils.of(data); }; IgniteBiFunction<Integer, Object[], Double> lbExtractor = (k, v) -> (double)v[1]; LogisticRegressionModel mdl = (LogisticRegressionModel) SparkModelParser.parse( new Path("examples/src/main/resources/models/spark/serialized/data" + "/part-00000-7551081d-c0a8-4ed7-afe4-a464aabc7f80-c000.snappy.parquet"), SupportedSparkModels.LOG_REGRESSION ); System.out.println(">>> Logistic regression model: " + mdl); double accuracy = BinaryClassificationEvaluator.evaluate( dataCache, mdl, featureExtractor, lbExtractor, new Accuracy<>() ); System.out.println("\n>>> Accuracy " + accuracy); System.out.println("\n>>> Test Error " + (1 - accuracy)); } }

Target:
public static void main(String[] args) throws FileNotFoundException { System.out.println(); System.out.println(">>> Logistic regression model loaded from Spark through serialization over partitioned dataset usage example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteCache<Integer, Object[]> dataCache = TitanicUtils.readPassengers(ignite); IgniteBiFunction<Integer, Object[], Vector> featureExtractor = (k, v) -> { double[] data = new double[] {(double)v[0], (double)v[5], (double)v[6]}; data[0] = Double.isNaN(data[0]) ? 0 : data[0]; data[1] = Double.isNaN(data[1]) ? 0 : data[1]; data[2] = Double.isNaN(data[2]) ? 0 : data[2]; return VectorUtils.of(data); }; IgniteBiFunction<Integer, Object[], Double> lbExtractor = (k, v) -> (double)v[1]; LogisticRegressionModel mdl = (LogisticRegressionModel) SparkModelParser.parse( SPARK_LOG_REG_MDL_PATH, SupportedSparkModels.LOG_REGRESSION ); System.out.println(">>> Logistic regression model: " + mdl); double accuracy = BinaryClassificationEvaluator.evaluate( dataCache, mdl, featureExtractor, lbExtractor, new Accuracy<>() ); System.out.println("\n>>> Accuracy " + accuracy); System.out.println("\n>>> Test Error " + (1 - accuracy)); } }
Source:
public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; if (defaultValue instanceof ConfigEnum) { for (T t : all) { if (((ConfigEnum) t).matchConfigValue(value)) return t; } } String n = value.replace(' ', '_'); n = n.replace('-', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().enumValueNotSupported3, section, subsection, name, value)); else throw new IllegalArgumentException( MessageFormat.format(JGitText.get().enumValueNotSupported2, section, name, value)); }

Target:
public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; if (all[0] instanceof ConfigEnum) { for (T t : all) { if (((ConfigEnum) t).matchConfigValue(value)) return t; } } String n = value.replace(' ', '_'); n = n.replace('-', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().enumValueNotSupported3, section, subsection, name, value)); else throw new IllegalArgumentException( MessageFormat.format(JGitText.get().enumValueNotSupported2, section, name, value)); }
Source:
public long getMaxWalArchiveSize() { if (maxWalArchiveSize == UNLIMITED_WAL_ARCHIVE) return UNLIMITED_WAL_ARCHIVE; return maxWalArchiveSize <= 0 ? DFLT_WAL_ARCHIVE_MAX_SIZE : maxWalArchiveSize; }

Target:
public long getMaxWalArchiveSize() { return maxWalArchiveSize; }
Source:
private List<DeviceIdentifier> installApplication(String applicationUUID, List<DeviceIdentifier> deviceList) throws ApplicationManagementException { List<DeviceIdentifier> failedDeviceList = new ArrayList<>(deviceList); List<org.wso2.carbon.device.mgt.common.DeviceIdentifier> androidDevices = new ArrayList<>(); List<org.wso2.carbon.device.mgt.common.DeviceIdentifier> iosDevices = new ArrayList<>(); for (DeviceIdentifier device : deviceList) { org.wso2.carbon.device.mgt.common.DeviceIdentifier deviceIdentifier = new org.wso2.carbon.device.mgt .common.DeviceIdentifier(device.getId(), device.getType()); try { DeviceManagementDAOFactory.openConnection(); if (DeviceManagementDAOFactory.getDeviceDAO().getDevice(deviceIdentifier).isEmpty()) { log.error("Device with ID: " + device.getId() + " not found to install the application."); } else { if (log.isDebugEnabled()) { log.debug("Prepare application install to : " + device.getId()); } if (device.getType().equals(ANDROID)) { androidDevices.add(deviceIdentifier); } else { iosDevices.add(deviceIdentifier); } DAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false); failedDeviceList.remove(device); } } catch (DeviceManagementDAOException | SQLException e) { throw new ApplicationManagementException("Error locating device.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } } return failedDeviceList; }

Target:
private List<DeviceIdentifier> installApplication(String applicationUUID, List<DeviceIdentifier> deviceList) throws ApplicationManagementException { List<DeviceIdentifier> failedDeviceList = new ArrayList<>(deviceList); List<org.wso2.carbon.device.mgt.common.DeviceIdentifier> activeDeviceList = new ArrayList<>(); for (DeviceIdentifier device : deviceList) { org.wso2.carbon.device.mgt.common.DeviceIdentifier deviceIdentifier = new org.wso2.carbon.device.mgt .common.DeviceIdentifier(device.getId(), device.getType()); try { DeviceManagementDAOFactory.openConnection(); if (DeviceManagementDAOFactory.getDeviceDAO().getDevice(deviceIdentifier).isEmpty()) { log.error("Device with ID: " + device.getId() + " not found to install the application."); } else { if (log.isDebugEnabled()) { log.debug("Prepare application install to : " + device.getId()); } activeDeviceList.add(deviceIdentifier); DAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false); failedDeviceList.remove(device); } } catch (DeviceManagementDAOException | SQLException e) { throw new ApplicationManagementException("Error locating device.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } } return failedDeviceList; }
Source:
private static void deleteLocalFormInstances(Long formIdToDelete) { DeleteInstancesTask dit = new DeleteInstancesTask(); dit.setContentResolver( Collect.getInstance().getApplication() .getContentResolver()); dit.execute(formIdToDelete); }

Target:
private static void deleteLocalFormInstances(Long formIdToDelete) { DeleteInstancesTask dit = new DeleteInstancesTask(Collect.getInstance().getApplication() .getContentResolver()); dit.execute(formIdToDelete); }
Source:
public static void show(final CheckoutResult result, final Repository repository, final String target) { BranchResultDialog.target = target; if (result.getStatus() == CheckoutResult.Status.CONFLICTS) PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new BranchResultDialog(shell, repository, result, target) .open(); } }); else if (result.getStatus() == CheckoutResult.Status.NONDELETED) { boolean show = false; List<String> pathList = result.getUndeletedList(); for (String path : pathList) if (new File(repository.getWorkTree(), path).exists()) { show = true; break; } if (!show) return; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new NonDeletedFilesDialog(shell, repository, result .getUndeletedList()).open(); } }); } else if (result.getStatus() == CheckoutResult.Status.OK) { if (RepositoryUtil.isDetachedHead(repository)) { showDetachedHeadWarning(); } } }

Target:
public static void show(final CheckoutResult result, final Repository repository, final String target) { BranchResultDialog.target = target; if (result.getStatus() == CheckoutResult.Status.CONFLICTS) PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new BranchResultDialog(shell, repository, result, target) .open(); } }); else if (result.getStatus() == CheckoutResult.Status.NONDELETED) { boolean show = false; List<String> pathList = result.getUndeletedList(); for (String path : pathList) if (new File(repository.getWorkTree(), path).exists()) { show = true; break; } if (!show) return; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new NonDeletedFilesDialog(shell, repository, result .getUndeletedList()).open(); } }); } else if (result.getStatus() == CheckoutResult.Status.OK) { if (RepositoryUtil.isDetachedHead(repository)) showDetachedHeadWarning(); } }
Source:
private void handleResubscription() { if (_zkClient == null || _zkClient.isClosed()) { return; } _zkClient.unsubscribeAll(); ZkRoutingDataReader.subscribeRoutingDataChanges(_zkClient, this, this); _routingDataListener.refreshRoutingData(_namespace); }

Target:
private void handleResubscription() { if (_zkClient == null || _zkClient.isClosed()) { return; } _zkClient.unsubscribeAll(); _zkClient.subscribeRoutingDataChanges(this, this); _routingDataListener.refreshRoutingData(_namespace); }
Source:
protected Object getMdcContextObject() { Long stackId = getStackId(); return stackService.getByIdWithListsInTransaction(stackId); }

Target:
protected Object getMdcContextObject() { return stackService.getStackById(getStackId()); }
Source:
private void tryFulfillSlotRequestOrMakeAvailable(AllocatedSlot allocatedSlot) { Preconditions.checkState(!allocatedSlot.isUsed(), "Provided slot is still in use."); final PendingRequest pendingRequest = findMatchingPendingRequest(allocatedSlot); if (pendingRequest != null) { log.debug("Fulfilling pending slot request with slot [{}]", pendingRequest.getSlotRequestId(), allocatedSlot.getAllocationId()); final AllocationID allocationIdOfRequest = pendingRequests.getKeyBByKeyA(pendingRequest.getSlotRequestId()); removePendingRequest(pendingRequest.getSlotRequestId()); allocatedSlots.add(pendingRequest.getSlotRequestId(), allocatedSlot); pendingRequest.getAllocatedSlotFuture().complete(allocatedSlot); if (allocationIdOfRequest != null) { maybeRemapOrphanedAllocation(allocationIdOfRequest, allocatedSlot.getAllocationId()); } } else { log.debug("Adding slot to available slots", allocatedSlot.getAllocationId()); availableSlots.add(allocatedSlot, clock.relativeTimeMillis()); } }

Target:
private void tryFulfillSlotRequestOrMakeAvailable(AllocatedSlot allocatedSlot) { Preconditions.checkState(!allocatedSlot.isUsed(), "Provided slot is still in use."); final PendingRequest pendingRequest = findMatchingPendingRequest(allocatedSlot); if (pendingRequest != null) { log.debug("Fulfilling pending slot request with slot [{}]", pendingRequest.getSlotRequestId(), allocatedSlot.getAllocationId()); removePendingRequest(pendingRequest.getSlotRequestId()); allocatedSlots.add(pendingRequest.getSlotRequestId(), allocatedSlot); pendingRequest.getAllocatedSlotFuture().complete(allocatedSlot); final Optional<AllocationID> allocationIdOfRequest = pendingRequest.getAllocationId(); if (allocationIdOfRequest.isPresent()) { maybeRemapOrphanedAllocation(allocationIdOfRequest.get(), allocatedSlot.getAllocationId()); } } else { log.debug("Adding slot to available slots", allocatedSlot.getAllocationId()); availableSlots.add(allocatedSlot, clock.relativeTimeMillis()); } }