auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldFetchModificationsWithMaterial() { MaterialRevisions materialRevisions = new MaterialRevisions(); SvnMaterial material = MaterialsMother.svnMaterial("http://username:password@localhost"); List<Modification> modificationList = getModifications(1); materialRevisions.addRevision(material, modificationList); dbHelper.saveRevs(materialRevisions); Modification expectedModification = modificationList.get(0); List<Modification> modifications = repo.getModificationWithMaterial(); assertThat(modifications.size(), is(1)); Modification modification = modifications.get(0); assertModificationEqual(expectedModification, modification); MaterialInstance instance = modification.getMaterialInstance(); assertThat(instance, instanceOf(SvnMaterialInstance.class)); assertThat(instance.getFingerprint(), is(material.getFingerprint())); assertThat(instance.getUrl(), is(material.getUrl())); assertThat(instance.getUsername(), is(material.getUserName())); assertThat(instance.getBranch(), isEmptyOrNullString()); assertThat(instance.getCheckExternals(), is(material.isCheckExternals())); }

Target:
public void shouldFetchModificationsWithMaterial() { MaterialRevisions materialRevisions = new MaterialRevisions(); SvnMaterial material = MaterialsMother.svnMaterial("http://username:password@localhost"); List<Modification> modificationList = getModifications(2); materialRevisions.addRevision(material, modificationList); dbHelper.saveRevs(materialRevisions); Modification expectedModification = modificationList.get(0); List<Modification> modifications = repo.getLatestModificationForEachMaterial(); assertThat(modifications.size(), is(1)); Modification modification = modifications.get(0); assertModificationEqual(expectedModification, modification); MaterialInstance instance = modification.getMaterialInstance(); assertThat(instance, instanceOf(SvnMaterialInstance.class)); assertThat(instance.getFingerprint(), is(material.getFingerprint())); assertThat(instance.getUrl(), is(material.getUrl())); assertThat(instance.getUsername(), is(material.getUserName())); assertThat(instance.getBranch(), isEmptyOrNullString()); assertThat(instance.getCheckExternals(), is(material.isCheckExternals())); }
Source:
private <T> QueryRunner<T> buildAndDecorateQueryRunner( final QueryRunnerFactory<T, Query<T>> factory, final QueryToolChest<T, Query<T>> toolChest, final ReferenceCountingSegment adapter, final QuerySegmentSpec segmentSpec ) { adapter.increment(); return new SpecificSegmentQueryRunner<T>( new MetricsEmittingQueryRunner<T>( emitter, new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override public ServiceMetricEvent.Builder apply(@Nullable final Query<T> input) { return toolChest.makeMetricBuilder(input); } }, new BySegmentQueryRunner<T>( adapter.getIdentifier(), adapter.getDataInterval().getStart(), new QueryRunner<T>() { @Override public Sequence<T> run(final Query<T> query) { return new ReferenceCountingSequence<T>(factory.createRunner(adapter).run(query), adapter); } } ) ).withWaitMeasuredFromNow(), segmentSpec ); }

Target:
private <T> QueryRunner<T> buildAndDecorateQueryRunner( final QueryRunnerFactory<T, Query<T>> factory, final QueryToolChest<T, Query<T>> toolChest, final ReferenceCountingSegment adapter, final QuerySegmentSpec segmentSpec ) { return new SpecificSegmentQueryRunner<T>( new MetricsEmittingQueryRunner<T>( emitter, new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override public ServiceMetricEvent.Builder apply(@Nullable final Query<T> input) { return toolChest.makeMetricBuilder(input); } }, new BySegmentQueryRunner<T>( adapter.getIdentifier(), adapter.getDataInterval().getStart(), new QueryRunner<T>() { @Override public Sequence<T> run(final Query<T> query) { return new ReferenceCountingSequence<T>(factory.createRunner(adapter).run(query), adapter); } } ) ).withWaitMeasuredFromNow(), segmentSpec ); }
Source:
public LogSource getLogSourceFromVmArgs() { int agentPathStart = vmArgs.indexOf("-agentpath") + "-agentpath".length(); int agentPathEnd = vmArgs.indexOf(' ', agentPathStart); String agentPath = vmArgs.substring(agentPathStart, agentPathEnd); int logPathStart = agentPath.indexOf("logPath=") + "logPath=".length(); int commaPos = agentPath.indexOf(",", logPathStart); int spacePos = agentPath.indexOf(' ', logPathStart); int logPathEnd = commaPos > 0 ? commaPos : (spacePos > 0 ? spacePos : agentPath.length()); return new FileLogSource(new File(agentPath.substring(logPathStart, logPathEnd))); }

Target:
public LogSource getLogSourceFromVmArgs() throws CantReadFromSourceException { if (vmArgs.indexOf(OPT_AGENT) < 0) { return getLogSource(); } int agentPathStart = vmArgs.indexOf(OPT_AGENT) + OPT_AGENT.length(); int agentPathEnd = vmArgs.indexOf(' ', agentPathStart); agentPathEnd = (agentPathEnd < 0) ? vmArgs.length() : agentPathEnd; String agentPath = vmArgs.substring(agentPathStart, agentPathEnd); if (agentPath.indexOf(OPT_LOG) < 0) { return getLogSource(); } int logPathStart = agentPath.indexOf(OPT_LOG) + OPT_LOG.length(); int commaPos = agentPath.indexOf(",", logPathStart); int spacePos = agentPath.indexOf(' ', logPathStart); int logPathEnd = commaPos > 0 ? commaPos : (spacePos > 0 ? spacePos : agentPath.length()); File result = new File(agentPath.substring(logPathStart, logPathEnd)); return result.exists() ? new FileLogSource(result) : getLogSource(); }
Source:
public Map<String, Map<String, String>> getCatalogSessionProperties() { ImmutableMap.Builder<String, Map<String, String>> catalogSessionProperties = ImmutableMap.builder(); session.getConnectorProperties().forEach((key, value) -> catalogSessionProperties.put(key.getCatalogName(), value)); return catalogSessionProperties.build(); }

Target:
public Map<String, Map<String, String>> getCatalogSessionProperties() { ImmutableMap.Builder<String, Map<String, String>> catalogSessionProperties = ImmutableMap.builder(); for (Entry<ConnectorId, Map<String, String>> entry : session.getConnectorProperties().entrySet()) { catalogSessionProperties.put(entry.getKey().getCatalogName(), entry.getValue()); } return catalogSessionProperties.build(); }
Source:
private void waitUntilReady(String vmName) { boolean ready = retry(new Predicate<String>() { @Override public boolean apply(String name) { return !api().get(name).properties().provisioningState().equals(VirtualMachineProperties.ProvisioningState.CREATING); } }, 60 * 20 * 1000).apply(vmName); assertTrue(ready, "createOrUpdateVault operation did not complete in the configured timeout"); VirtualMachineProperties.ProvisioningState status = api().get(vmName).properties().provisioningState(); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.CREATING); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.FAILED); }

Target:
private void waitUntilReady(String vmName) { boolean ready = retry(new Predicate<String>() { @Override public boolean apply(String name) { return !api().get(name).properties().provisioningState().equals(VirtualMachineProperties.ProvisioningState.CREATING); } }, 60 * 20 * 1000).apply(vmName); assertTrue(ready, "createOrUpdate operation did not complete in the configured timeout"); VirtualMachineProperties.ProvisioningState status = api().get(vmName).properties().provisioningState(); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.CREATING); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.FAILED); }
Source:
public Date getStartDate() { if (null == dataFile) { return null; } LocalDateTime date = dataFile.getStartDate(); if (null == date) { return null; } return Date.from(date.atZone(ZoneId.of("UTC")).toInstant()); }

Target:
public Date getStartDate() { Date date = null; if (null != dataFile) { LocalDateTime localDate = dataFile.getStartDate(); if (null != localDate) { date = Date.from(localDate.atZone(ZoneId.of("UTC")).toInstant()); } } return date; }
Source:
public void testCancel() { Capture<Request> capturedRequest = EasyMock.newCapture(); ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture(); SettableFuture<Object> cancellationFuture = SettableFuture.create(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancelledFuture) .once(); EasyMock.replay(httpClient); TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build(); query = query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, Long.MAX_VALUE)); cancellationFuture.set(new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled"))); Sequence results = client.run(QueryPlus.wrap(query)); Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod()); Assert.assertEquals(1, client.getNumOpenConnections()); QueryInterruptedException exception = null; try { results.toList(); } catch (QueryInterruptedException e) { exception = e; } Assert.assertNotNull(exception); EasyMock.verify(httpClient); }

Target:
public void testCancel() { Capture<Request> capturedRequest = EasyMock.newCapture(); ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture(); SettableFuture<Object> cancellationFuture = SettableFuture.create(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancelledFuture) .once(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancellationFuture) .anyTimes(); EasyMock.replay(httpClient); TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build(); query = query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, Long.MAX_VALUE)); cancellationFuture.set(new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled"))); Sequence results = client.run(QueryPlus.wrap(query)); Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod()); Assert.assertEquals(0, client.getNumOpenConnections()); QueryInterruptedException exception = null; try { results.toList(); } catch (QueryInterruptedException e) { exception = e; } Assert.assertNotNull(exception); EasyMock.verify(httpClient); }
Source:
public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem menuItemSavePage = menu.findItem(R.id.menu_save_page); if (menuItemSavePage == null) { return; } MenuItem menuItemShare = menu.findItem(R.id.menu_share_page); MenuItem menuItemOtherLang = menu.findItem(R.id.menu_other_languages); MenuItem menuItemFindInPage = menu.findItem(R.id.menu_find_in_page); MenuItem menuItemThemeChooser = menu.findItem(R.id.menu_themechooser); if (pageLoadStrategy.isLoading()) { menuItemSavePage.setEnabled(false); menuItemShare.setEnabled(false); menuItemOtherLang.setEnabled(false); menuItemFindInPage.setEnabled(false); menuItemThemeChooser.setEnabled(false); } else { menuItemSavePage.setEnabled(true); menuItemShare.setEnabled(true); menuItemOtherLang.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); menuItemOtherLang.setEnabled(true); menuItemFindInPage.setEnabled(true); menuItemThemeChooser.setEnabled(true); int subState = pageLoadStrategy.getSubState(); if (subState == SUBSTATE_PAGE_SAVED) { menuItemSavePage.setEnabled(false); menuItemSavePage.setTitle(WikipediaApp.getInstance().getString(R.string.menu_page_saved)); } else if (subState == SUBSTATE_SAVED_PAGE_LOADED) { menuItemSavePage.setTitle(WikipediaApp.getInstance().getString(R.string.menu_refresh_saved_page)); } else { menuItemSavePage.setTitle(WikipediaApp.getInstance().getString(R.string.menu_save_page)); } } }

Target:
public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem savePageItem = menu.findItem(R.id.menu_save_page); if (savePageItem == null) { return; } MenuItem shareItem = menu.findItem(R.id.menu_share_page); MenuItem otherLangItem = menu.findItem(R.id.menu_other_languages); MenuItem findInPageItem = menu.findItem(R.id.menu_find_in_page); MenuItem themeChooserItem = menu.findItem(R.id.menu_themechooser); if (pageLoadStrategy.isLoading()) { savePageItem.setEnabled(false); shareItem.setEnabled(false); otherLangItem.setEnabled(false); findInPageItem.setEnabled(false); themeChooserItem.setEnabled(false); } else { savePageItem.setEnabled(true); shareItem.setEnabled(true); otherLangItem.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); otherLangItem.setEnabled(true); findInPageItem.setEnabled(true); themeChooserItem.setEnabled(true); int subState = pageLoadStrategy.getSubState(); if (subState == SUBSTATE_PAGE_SAVED) { savePageItem.setEnabled(false); savePageItem.setTitle(WikipediaApp.getInstance().getString(R.string.menu_page_saved)); } else if (subState == SUBSTATE_SAVED_PAGE_LOADED) { savePageItem.setTitle(WikipediaApp.getInstance().getString(R.string.menu_refresh_saved_page)); } else { savePageItem.setTitle(WikipediaApp.getInstance().getString(R.string.menu_save_page)); } } }
Source:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues, final String namespace) { List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); if (accessConstentValues != null) { attributes.add(createAttribute(null, "AccessConsentPolicy", namespace, accessConstentValues)); } if (evidenceInstanceAccessConsentValues != null) { attributes.add(createAttribute(null, "InstanceAccessConsentPolicy", namespace, evidenceInstanceAccessConsentValues)); } if (!attributes.isEmpty()) { statements = createAttributeStatement(attributes); } return statements; }

Target:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues, final String namespace) { List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); if (accessConstentValues != null) { attributes.add(createAttribute(null, NhincConstants.ACCESS_CONSENT_ATTR, namespace, accessConstentValues)); } if (evidenceInstanceAccessConsentValues != null) { attributes.add(createAttribute(null, NhincConstants.INST_ACCESS_CONSENT_ATTR, namespace, evidenceInstanceAccessConsentValues)); } if (!attributes.isEmpty()) { statements = createAttributeStatement(attributes); } return statements; }
Source:
private static SerializationDelegate getSerializationDelegate(Map<String, Object> topoConf) { String delegateClassName = (String) topoConf.get(Config.STORM_META_SERIALIZATION_DELEGATE); SerializationDelegate delegate; try { Class delegateClass = Class.forName(delegateClassName); delegate = (SerializationDelegate) delegateClass.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.error("Failed to construct serialization delegate, falling back to default", e); delegate = new GzipThriftSerializationDelegate(); } delegate.prepare(topoConf); return delegate; }

Target:
private static SerializationDelegate getSerializationDelegate(Map<String, Object> topoConf) { String delegateClassName = (String) topoConf.get(Config.STORM_META_SERIALIZATION_DELEGATE); SerializationDelegate delegate; try { Class delegateClass = Class.forName(delegateClassName); delegate = (SerializationDelegate) delegateClass.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to construct serialization delegate class " + delegateClassName, e); } delegate.prepare(topoConf); return delegate; }
Source:
public void setBusyNode(final String nodeUrl, Client owner) throws NotConnectedException { final RMNode rmNode = this.allNodes.get(nodeUrl); if (rmNode == null) { logger.error("Unknown node " + nodeUrl); return; } if ((!clients.containsKey(owner.getId()) && owner != localClient)) { logger.warn(nodeUrl + " cannot set busy as the client disconnected " + owner); throw new NotConnectedException("Client " + owner + " is not connected to the resource manager"); } if (rmNode.isBusy()) { return; } final NodeState previousNodeState = rmNode.getState(); rmNode.setBusy(owner); this.eligibleNodes.remove(rmNode); persistUpdatedRMNodeIfRecoveryEnabled(rmNode); this.registerAndEmitNodeEvent(rmNode.createNodeEvent(RMEventType.NODE_STATE_CHANGED, previousNodeState, owner.getName())); }

Target:
public void setBusyNode(final String nodeUrl, Client owner) throws NotConnectedException { final RMNode rmNode = this.allNodes.get(nodeUrl); if (rmNode == null) { logger.error("Unknown node " + nodeUrl); return; } if (!clients.containsKey(owner.getId()) && owner != localClient) { logger.warn(nodeUrl + " cannot set busy as the client disconnected " + owner); throw new NotConnectedException("Client " + owner + " is not connected to the resource manager"); } if (rmNode.isBusy()) { return; } final NodeState previousNodeState = rmNode.getState(); rmNode.setBusy(owner); this.eligibleNodes.remove(rmNode); persistUpdatedRMNodeIfRecoveryEnabled(rmNode); this.registerAndEmitNodeEvent(rmNode.createNodeEvent(RMEventType.NODE_STATE_CHANGED, previousNodeState, owner.getName())); }
Source:
protected ProjectState(final AnonymousUser anonymousUser, final ProjectCache projectCache, @WildProjectName final Project.NameKey wildProject, final ProjectControl.AssistedFactory projectControlFactory, @Assisted final Project project, @Assisted Collection<RefRight> rights) { this.anonymousUser = anonymousUser; this.projectCache = projectCache; this.wildProject = wildProject; this.projectControlFactory = projectControlFactory; if (wildProject.equals(project.getNameKey())) { rights = new ArrayList<RefRight>(rights); for (Iterator<RefRight> itr = rights.iterator(); itr.hasNext();) { if (!itr.next().getApprovalCategoryId().canBeOnWildProject()) { itr.remove(); } } rights = Collections.unmodifiableCollection(rights); } this.project = project; this.localRights = rights; final HashSet<AccountGroup.Id> groups = new HashSet<AccountGroup.Id>(); for (final RefRight right : rights) { if (ApprovalCategory.OWN.equals(right.getApprovalCategoryId()) && right.getMaxValue() > 0) { groups.add(right.getAccountGroupId()); } } localOwners = Collections.unmodifiableSet(groups); }

Target:
protected ProjectState(final AnonymousUser anonymousUser, final ProjectCache projectCache, @WildProjectName final Project.NameKey wildProject, final ProjectControl.AssistedFactory projectControlFactory, @Assisted final Project project, @Assisted Collection<RefRight> rights) { this.anonymousUser = anonymousUser; this.projectCache = projectCache; this.wildProject = wildProject; this.projectControlFactory = projectControlFactory; if (wildProject.equals(project.getNameKey())) { rights = new ArrayList<RefRight>(rights); for (Iterator<RefRight> itr = rights.iterator(); itr.hasNext();) { if (!itr.next().getApprovalCategoryId().canBeOnWildProject()) { itr.remove(); } } rights = Collections.unmodifiableCollection(rights); } this.project = project; this.localRights = rights; final HashSet<AccountGroup.Id> groups = new HashSet<AccountGroup.Id>(); for (final RefRight right : rights) { if (ApprovalCategory.OWN.equals(right.getApprovalCategoryId()) && right.getMaxValue() > 0 && right.getRefPattern().equals(RefRight.ALL)) { groups.add(right.getAccountGroupId()); } } localOwners = Collections.unmodifiableSet(groups); }
Source:
public void createServiceDuplicate() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); try { client.addService(serviceRepo, "admin@admin.com", installationId); } catch (ApiException ex) { assertEquals("Should have error code 418", 418, ex.getCode()); } final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }

Target:
public void createServiceDuplicate() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); try { client.addService(serviceRepo, "admin@admin.com", installationId); } catch (ApiException ex) { assertEquals("Should have error code 418", LAMBDA_FAILURE, ex.getCode()); } final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }
Source:
public BackendRequest<?> visitFlushWork(FlushLuceneWork work, IndexingMonitor monitor) { Flush flush = new Flush.Builder().addIndex( indexName ).refresh( true ).build(); return new BackendRequest<>( flush, work, indexName, monitor, NoopBackendRequestSuccessHandler.INSTANCE, refreshAfterWrite ); }

Target:
public BackendRequest<?> visitFlushWork(FlushLuceneWork work, IndexingMonitor monitor) { Flush flush = new Flush.Builder().setParameter( "wait_if_ongoing", "true" ) .addIndex( indexName ) .refresh( true ) .build(); return new BackendRequest<>( flush, work, indexName, monitor, NoopBackendRequestSuccessHandler.INSTANCE, false ); }
Source:
public RoomInfoPage doubleClickOverRoomName(String displayName) { UI.doubleClick(driver.findElement(By.xpath(" return new RoomInfoPage(); }

Target:
public RoomInfoPage doubleClickOverRoomName(String displayName) { UI.doubleClick(driver.findElement(By.xpath(" + displayName + "')and@class='ng-binding']"))); return new RoomInfoPage(); }
Source:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); int lastDot = expr.lastIndexOf('.'); while (lastDot > 0) { Function function; function = FUNCTIONS.get(expr.substring(lastDot + 1)); if (function == null) { function = NOOP; } functions.add(function); expr = expr.substring(0, lastDot); lastDot = expr.lastIndexOf('.'); } functions.add(NOOP); final Parameter p = new Parameter(expr, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }

Target:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } functions.add(NOOP); final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }
Source:
public String acquireLease(int leaseTimeInSec, String leaseId) { try { String id = leaseBlob.acquireLease(leaseTimeInSec, leaseId); LOG.info("Acquired lease with lease id = " + id); return id; } catch (StorageException storageException) { int httpStatusCode = storageException.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { LOG.info("The blob you're trying to acquire is leased already."); } else if (httpStatusCode == HttpStatus.NOT_FOUND_404) { LOG.error("The blob you're trying to lease does not exist.", storageException); throw new AzureException(storageException); } else { LOG.error("Error acquiring lease!", storageException); throw new AzureException(storageException); } } return null; }

Target:
public String acquireLease(int leaseTimeInSec, String leaseId) { try { String id = leaseBlob.acquireLease(leaseTimeInSec, leaseId); LOG.info("Acquired lease with lease id = " + id); return id; } catch (StorageException storageException) { int httpStatusCode = storageException.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { LOG.info("The blob you're trying to acquire is leased already.", storageException.getMessage()); } else if (httpStatusCode == HttpStatus.NOT_FOUND_404) { LOG.error("The blob you're trying to lease does not exist.", storageException); throw new AzureException(storageException); } else { LOG.error("Error acquiring lease!", storageException); throw new AzureException(storageException); } } return null; }
Source:
public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); if (message instanceof CloneableMessage) { return ((CloneableMessage<T>) message).cloneMessage(); } else { return new MessageBuilder<T>(message.getPayload(), message); } }

Target:
public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); return new MessageBuilder<T>(message.getPayload(), message); }
Source:
public IgniteEx start() throws Exception { IgniteConfiguration cfg = getConfiguration(gridName); cfg.setConsistentId(gridName); DataStorageConfiguration storageCfg = new DataStorageConfiguration(); storageCfg.setDataRegionConfigurations(regions.toArray(new DataRegionConfiguration[] {})); cfg.setDataStorageConfiguration(storageCfg); if (dfltRegionConfiguration != null) storageCfg.setDefaultDataRegionConfiguration(dfltRegionConfiguration); cfg.setCacheConfiguration(caches.toArray(new CacheConfiguration[] {})); return startGrid(cfg); }

Target:
public IgniteEx start() throws Exception { IgniteConfiguration cfg = getConfiguration(gridName); cfg.setConsistentId(gridName); DataStorageConfiguration storageCfg = new DataStorageConfiguration(); storageCfg.setDataRegionConfigurations(regions.toArray(new DataRegionConfiguration[regions.size()])); cfg.setDataStorageConfiguration(storageCfg); if (dfltRegionConfiguration != null) storageCfg.setDefaultDataRegionConfiguration(dfltRegionConfiguration); cfg.setCacheConfiguration(caches.toArray(new CacheConfiguration[caches.size()])); return startGrid(cfg); }
Source:
private static void writeFromInputToOutputNewInner(InputStream is, OutputStream os, @Nullable StreamReadObserver observer) throws InputIOException, OutputIOException { byte[] buffer = new byte[8192]; long counter = 0; try { int count = readIntoBuffer(is, buffer); while (count != -1) { counter += count; if (observer != null) { observer.notifyCurrentCount(counter); } try { os.write(buffer, 0, count); } catch (IOException e) { throw new StreamsUtil().new OutputIOException(e); } count = readIntoBuffer(is, buffer); } } finally { closeStream(is); closeStream(os); } }

Target:
private static void writeFromInputToOutputNewInner(InputStream is, OutputStream os, @Nullable StreamReadObserver observer) throws InputIOException, OutputIOException { byte[] buffer = new byte[8192]; long counter = 0; try { int count = readIntoBuffer(is, buffer); while (count != -1) { counter += count; if (observer != null) { observer.notifyCurrentCount(counter); } writeFromBuffer(os, buffer, count); count = readIntoBuffer(is, buffer); } } finally { closeStream(is); closeStream(os); } }
Source:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }

Target:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkArgument(Compatibility.isCompatibleName(namespace), "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }
Source:
private void fillInRepository() { for (int i = 0; i < CACHE_SIZE; i++) repo.save(i, new Person("person" + Integer.toHexString(i), "lastName" + Integer.toHexString((i + 16) % 256))); }

Target:
private void fillInRepository() { for (int i = 0; i < CACHE_SIZE; i++) { repo.save(i, new Person("person" + Integer.toHexString(i), "lastName" + Integer.toHexString((i + 16) % 256))); } }
Source:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { myProxyDelegate = reproxy(AndroidProject.class, myDelegate);; } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }

Target:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { myProxyDelegate = reproxy(AndroidProject.class, myDelegate); } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }
Source:
public IncompleteInformationException(Variant variant) { super("The variant " + variant + " has no samples data, AC and AF INFO tags"); }

Target:
public IncompleteInformationException(Variant variant) { super("The variant " + variant + " has no allele frequencies or counts in its INFO column"); }
Source:
private void encodeChainedFeatures(String attributeName, List<Feature> chainedFeatures) { key(attributeName); if (!isInsideArrayAttributeName(attributeName)) jsonWriter.array(); for (Feature feature : chainedFeatures) { if (feature.getType().getGeometryDescriptor() != null) { encodeFeature(feature, false); } else { jsonWriter.object(); encodeProperties(null, feature.getType(), feature.getProperties()); jsonWriter.endObject(); } } if (!isInsideArrayAttributeName(attributeName)) jsonWriter.endArray(); }

Target:
private void encodeChainedFeatures(String attributeName, List<Feature> chainedFeatures) { key(attributeName); if (!isInsideArrayAttributeName(attributeName)) { jsonWriter.array(); } for (Feature feature : chainedFeatures) { if (feature.getType().getGeometryDescriptor() != null) { encodeFeature(feature, false); } else { jsonWriter.object(); encodeProperties(null, feature.getType(), feature.getProperties()); jsonWriter.endObject(); } } if (!isInsideArrayAttributeName(attributeName)) { jsonWriter.endArray(); } }
Source:
Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); final TextDocumentInput textDocumentInput = new TextDocumentInput("0", document).setLanguage(language); return recognizePiiEntitiesBatch(Collections.singletonList(textDocumentInput), null) .map(resultCollectionResponse -> { PiiEntityCollection entityCollection = null; for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) { if (entitiesResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError())); } entityCollection = new PiiEntityCollection(entitiesResult.getEntities(), entitiesResult.getEntities().getWarnings()); } return entityCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }

Target:
Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) { try { Objects.requireNonNull(document, "'document' cannot be null."); return recognizePiiEntitiesBatch( Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language)), null) .map(resultCollectionResponse -> { PiiEntityCollection entityCollection = null; for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) { if (entitiesResult.isError()) { throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError())); } entityCollection = new PiiEntityCollection(entitiesResult.getEntities(), entitiesResult.getEntities().getWarnings()); } return entityCollection; }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
public synchronized long startForwarding(LearnerHandler learnerHandler, long lastSeenZxid) { Iterator<QuorumPacket> itr = committedPkts.iterator(); if (itr.hasNext()) { QuorumPacket packet = itr.next(); if (packet.getZxid() > lastSeenZxid + 1) { LOG.error( "LearnerHandler is too far behind ({} < {}), disconnecting at {}", Long.toHexString(lastSeenZxid + 1), Long.toHexString(packet.getZxid()), learnerHandler.getSid(), learnerHandler.getRemoteAddress()); learnerHandler.shutdown(); return -1; } else if (packet.getZxid() == lastSeenZxid + 1) { learnerHandler.queuePacket(packet); } long queueHeadZxid = packet.getZxid(); long queueBytesUsed = LearnerHandler.packetSize(packet); while (itr.hasNext()) { packet = itr.next(); if (packet.getZxid() <= lastSeenZxid) { continue; } learnerHandler.queuePacket(packet); queueBytesUsed += LearnerHandler.packetSize(packet); } LOG.info( "finished syncing observer from retained commit queue: sid {}, " + "queue head 0x{}, queue tail 0x{}, sync position 0x{}, num packets used {}, " + "num bytes used {}", learnerHandler.getSid(), Long.toHexString(queueHeadZxid), Long.toHexString(packet.getZxid()), Long.toHexString(lastSeenZxid), packet.getZxid() - lastSeenZxid, queueBytesUsed); } activeObservers.add(learnerHandler); return lastProposedZxid; }

Target:
public synchronized long startForwarding(LearnerHandler learnerHandler, long lastSeenZxid) { Iterator<QuorumPacket> itr = committedPkts.iterator(); if (itr.hasNext()) { QuorumPacket packet = itr.next(); if (packet.getZxid() > lastSeenZxid + 1) { LOG.error( "LearnerHandler is too far behind (0x{} < 0x{}), disconnecting at {}", Long.toHexString(lastSeenZxid + 1), Long.toHexString(packet.getZxid()), learnerHandler.getSid(), learnerHandler.getRemoteAddress()); learnerHandler.shutdown(); return -1; } else if (packet.getZxid() == lastSeenZxid + 1) { learnerHandler.queuePacket(packet); } long queueHeadZxid = packet.getZxid(); long queueBytesUsed = LearnerHandler.packetSize(packet); while (itr.hasNext()) { packet = itr.next(); if (packet.getZxid() <= lastSeenZxid) { continue; } learnerHandler.queuePacket(packet); queueBytesUsed += LearnerHandler.packetSize(packet); } LOG.info( "finished syncing observer from retained commit queue: sid {}, " + "queue head 0x{}, queue tail 0x{}, sync position 0x{}, num packets used {}, " + "num bytes used {}", learnerHandler.getSid(), Long.toHexString(queueHeadZxid), Long.toHexString(packet.getZxid()), Long.toHexString(lastSeenZxid), packet.getZxid() - lastSeenZxid, queueBytesUsed); } activeObservers.add(learnerHandler); return lastProposedZxid; }
Source:
public void validatesInMultipleThreadsAgain() throws Exception { final int zero = 0; final int ten = 10; final int hundred = 100; final int fifty = 50; final Random rand = new SecureRandom(); final XSD xsd = new XSDDocument( StringUtils.join( "<xs:schema xmlns:xs ='<LINK_0>' >", "<xs:element name='r'><xs:complexType><xs:sequence>", "<xs:element name='x' type='xs:integer'", " minOccurs='0' maxOccurs='unbounded'/>", "</xs:sequence></xs:complexType></xs:element></xs:schema>" ) ); final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { final int cnt = rand.nextInt(hundred); MatcherAssert.assertThat( xsd.validate( new DOMSource( new XMLDocument( StringUtils.join( "<r>", StringUtils.repeat("<x>hey</x>", cnt), "</r>" ) ).node() ) ), Matchers.hasSize(cnt << 1) ); return null; } }; final ExecutorService executorService = Executors.newFixedThreadPool(5); for (int count = zero; count < fifty; count = count + 1) { executorService.submit(callable); } executorService.awaitTermination(ten, TimeUnit.SECONDS); executorService.shutdown(); }

Target:
public void validatesInMultipleThreadsAgain() throws Exception { final int timeout = 10; final int random = 100; final int loop = 50; final Random rand = new SecureRandom(); final XSD xsd = new XSDDocument( StringUtils.join( "<xs:schema xmlns:xs ='<LINK_0>' >", "<xs:element name='r'><xs:complexType><xs:sequence>", "<xs:element name='x' type='xs:integer'", " minOccurs='0' maxOccurs='unbounded'/>", "</xs:sequence></xs:complexType></xs:element></xs:schema>" ) ); final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { final int cnt = rand.nextInt(random); MatcherAssert.assertThat( xsd.validate( new DOMSource( new XMLDocument( StringUtils.join( "<r>", StringUtils.repeat("<x>hey</x>", cnt), "</r>" ) ).node() ) ), Matchers.hasSize(cnt << 1) ); return null; } }; final ExecutorService executorService = Executors.newFixedThreadPool(5); for (int count = 0; count < loop; count = count + 1) { executorService.submit(callable); } executorService.shutdown(); MatcherAssert.assertThat( executorService.awaitTermination(timeout, TimeUnit.SECONDS), Matchers.is(true) ); executorService.shutdownNow(); }
Source:
boolean sameField(ArgumentFilter another) { if (field == null) { return another.field == null; } boolean result = field.equals(another.field); return result; }

Target:
boolean sameField(ArgumentFilter another) { return Objects.equals(field, another.field); }
Source:
void counterGet(Consumer<Response> sendResponse) { String name = operationContext(); CounterConfiguration config = counterManager.getConfiguration(name); if (config == null) { sendResponse.accept(missingCounterResponse()); return; } switch (config.type()) { case UNBOUNDED_STRONG: case BOUNDED_STRONG: counterManager.getStrongCounter(name).getValue().whenComplete((value, throwable) -> { if (throwable != null) { checkCounterThrowable(sendResponse, throwable); } else { sendResponse.accept(new CounterValueResponse(header, value)); } }); break; case WEAK: long value = counterManager.getWeakCounter(name).getValue(); sendResponse.accept(new CounterValueResponse(header, value)); break; } }

Target:
void counterGet(Consumer<Response> sendResponse) { applyCounter(operationContext(), sendResponse, (counter, responseConsumer) -> counter.getValue().whenComplete(longResultHandler(responseConsumer)), (counter, responseConsumer) -> longResultHandler(responseConsumer).accept(counter.getValue(), null) ); }
Source:
private static boolean visitDelta(IResourceDelta delta) { IResource resource = delta.getResource(); if ((resource.getType() & IResource.PROJECT) != 0 && (delta.getFlags() & IResourceDelta.OPEN) != 0) { ISonarLintProject project = Adapters.adapt(delta.getResource(), ISonarLintProject.class); if (project != null && project.isBound()) { SonarLintProjectConfiguration config = SonarLintProjectConfiguration.read(project.getScopeContext()); String moduleKey = config.getModuleKey(); Server server = (Server) SonarLintCorePlugin.getServersManager().getServer(config.getServerId()); System.out.printf("Register %s for server %s? -> %s\n", moduleKey, server.getId(), project.isOpen()); if (project.isOpen()) { } else { } } return false; } return true; }

Target:
private static boolean visitDelta(IResourceDelta delta) { if ((delta.getFlags() & IResourceDelta.OPEN) != 0) { ISonarLintProject project = Adapters.adapt(delta.getResource(), ISonarLintProject.class); if (project != null && project.isBound()) { if (project.isOpen()) { SonarLintUiPlugin.subscribeToNotifications(project); } else { SonarLintCorePlugin.getInstance().notificationsManager().unsubscribe(project); } } return false; } return true; }
Source:
public PlanWithProperties visitExchange(ExchangeNode node, StreamPreferredProperties parentPreferences) { checkArgument(node.getScope() != LOCAL, "AddLocalExchanges can not process a plan containing a local exchange"); if (node.isOrderSensitive()) { return planAndEnforceChildren( node, parentPreferences.withoutPreference().withDefaultParallelism(session), parentPreferences.withDefaultParallelism(session)); } return planAndEnforceChildren(node, any(), defaultParallelism(session)); }

Target:
public PlanWithProperties visitExchange(ExchangeNode node, StreamPreferredProperties parentPreferences) { checkArgument(node.getScope() != LOCAL, "AddLocalExchanges can not process a plan containing a local exchange"); if (node.isOrderSensitive()) { return planAndEnforceChildren( node, singleStream().withOrderSensitivity(), singleStream().withOrderSensitivity()); } return planAndEnforceChildren(node, any(), defaultParallelism(session)); }
Source:
public Translation itemstack$getTranslation() { String id; if (shadow$getItem() instanceof ItemBed) { id = shadow$getItem().getUnlocalizedName((net.minecraft.item.ItemStack) (IMixinItemStack) this) + ".name"; } else if (shadow$getItem() instanceof ItemBanner) { EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(this.getMetadata() & 15); id = "item.banner." + enumdyecolor.getUnlocalizedName() + ".name"; } else if (shadow$getItem() instanceof ItemTippedArrow) { id = PotionUtils.getPotionFromItem((net.minecraft.item.ItemStack) (IMixinItemStack) this).getNamePrefixed("tipped_arrow.effect."); } else if (shadow$getItem() instanceof ItemSplashPotion) { id = PotionUtils.getPotionFromItem((net.minecraft.item.ItemStack) (IMixinItemStack) this).getNamePrefixed("splash_potion.effect."); } else if (shadow$getItem() instanceof ItemLingeringPotion) { id = PotionUtils.getPotionFromItem((net.minecraft.item.ItemStack) (IMixinItemStack) this).getNamePrefixed("lingering_potion.effect."); } else if (shadow$getItem() instanceof ItemPotion) { id = PotionUtils.getPotionFromItem((net.minecraft.item.ItemStack) (IMixinItemStack) this).getNamePrefixed("potion.effect."); } else { id = shadow$getItem().getUnlocalizedNameInefficiently((net.minecraft.item.ItemStack) (IMixinItemStack) this) + ".name"; } return new SpongeTranslation(id); }

Target:
public Translation itemstack$getTranslation() { if (this.translation == null) { this.translation = ((ItemType) shadow$getItem()).getTranslation((ItemStack) this); } return this.translation; }
Source:
public VersionInfo versionInfoForUpdate() { if (isDevelopmentServer() || isVersionInfoUpdatedToday() || isUpdateInProgress()) return null; versionInfoUpdatingFrom = clock.currentDateTime(); return this.serverVersionInfo; }

Target:
public VersionInfo versionInfoForUpdate() { synchronized (VERSION_INFO_MUTEX) { if (isDevelopmentServer() || isVersionInfoUpdatedToday() || isUpdateInProgress()) return null; versionInfoUpdatingFrom = clock.currentDateTime(); return this.serverVersionInfo; } }
Source:
public LabelStyleDescription createLabelStyleDescription() { LabelStyleDescriptionImpl labelStyleDescription = new LabelStyleDescriptionImpl(); return labelStyleDescription; }

Target:
public LabelStyleDescription createLabelStyleDescription() { LabelStyleDescriptionImpl labelStyleDescription = new LabelStyleDescriptionImpl(); new DefaultColorStyleDescription().setDefaultColors(labelStyleDescription); return labelStyleDescription; }
Source:
public void setUp() throws Exception { buildFlowProject = jenkinsRule.createBuildFlowProject(); jenkinsRule.createFreeStyleProject("downstreamProject1"); jenkinsRule.createFreeStyleProject("downstreamProject2"); jenkinsRule.createFreeStyleProject("downstreamProject3"); String dsl = "parallel (" + " { build(\"downstreamProject1\") }," + " { build(\"downstreamProject2\") }" + ")" + "{ build(\"downstreamProject3\") }"; buildFlowProject.setDsl(dsl); given(ghPullRequest.getNumber()).willReturn(1); given(ghRepository.getPullRequest(1)).willReturn(ghPullRequest); super.beforeTest(null, null, buildFlowProject); }

Target:
public void setUp() throws Exception { buildFlowProject = jenkinsRule.createBuildFlowProject(); jenkinsRule.createFreeStyleProject("downstreamProject1"); jenkinsRule.createFreeStyleProject("downstreamProject2"); jenkinsRule.createFreeStyleProject("downstreamProject3"); StringBuilder dsl = new StringBuilder(); dsl.append("parallel ("); dsl.append(" { build(\"downstreamProject1\") },"); dsl.append(" { build(\"downstreamProject2\") }"); dsl.append(")"); dsl.append("{ build(\"downstreamProject3\") }"); buildFlowProject.setDsl(dsl.toString()); given(ghPullRequest.getNumber()).willReturn(1); given(ghRepository.getPullRequest(1)).willReturn(ghPullRequest); super.beforeTest(null, null, buildFlowProject); }
Source:
public double getEnergyDemand( final double maxRequired ) { final Queue<IEnergyGridProvider> toVisit = new LinkedList<>(); final Set<IEnergyGridProvider> visited = new HashSet<>(); toVisit.add( this ); double required = this.buffer() - this.extra; while( !toVisit.isEmpty() && required < maxRequired ) { final IEnergyGridProvider next = toVisit.poll(); visited.add( next ); required += next.getProviderEnergyDemand( maxRequired - required, visited ); for( IEnergyGridProvider iEnergyGridProvider : next.providers() ) { if( !visited.contains( iEnergyGridProvider ) ) { toVisit.add( iEnergyGridProvider ); } } } return required; }

Target:
public double getEnergyDemand( final double maxRequired ) { final Queue<IEnergyGridProvider> toVisit = new ArrayDeque<>(); final Set<IEnergyGridProvider> visited = new HashSet<>(); toVisit.add( this ); double required = 0; while( !toVisit.isEmpty() && required < maxRequired ) { final IEnergyGridProvider next = toVisit.poll(); visited.add( next ); required += next.getProviderEnergyDemand( maxRequired - required, visited ); for( IEnergyGridProvider iEnergyGridProvider : next.providers() ) { if( !visited.contains( iEnergyGridProvider ) ) { toVisit.add( iEnergyGridProvider ); } } } return required; }
Source:
public void close() throws IOException { addEml(); addMeta(); flushLastCoreRecord(); for (TabWriter w : writers.values()) { w.close(); } }

Target:
public void close() throws IOException { try { addEml(); addMeta(); flushLastCoreRecord(); } finally { for (TabWriter w : writers.values()) { try { w.close(); } catch (Exception ex) { log.error("Unable to close writer " + w, ex); } } } }