auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean afterLRANotification() { boolean notifiedAll = true; if (afterLRAListeners != null) { Client client = ClientBuilder.newClient(); try { Iterator<AfterLRAListener> listeners = afterLRAListeners.iterator(); while (listeners.hasNext()) { AfterLRAListener participant = listeners.next(); Response response = null; try { Future<Response> asyncResponse = client.target(participant.notificationURI) .request() .header(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER, id) .header(LRA_HTTP_RECOVERY_HEADER, participant.recoveryId.toASCIIString()) .async() .put(Entity.text(status.name())); response = asyncResponse.get(PARTICIPANT_TIMEOUT, TimeUnit.SECONDS); if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { listeners.remove(); } else { notifiedAll = false; } response = null; } catch (WebApplicationException | InterruptedException | ExecutionException | TimeoutException e) { notifiedAll = false; if (LRALogger.logger.isInfoEnabled()) { LRALogger.logger.infof("Could not notify AfterLRA listener at %s (%s)", participant.notificationURI, e.getMessage()); } } finally { if (response != null) { response.close(); } } } } finally { client.close(); } } return notifiedAll; }

Target:
public boolean afterLRANotification() { boolean notifiedAll = true; if (afterLRAListeners != null) { Client client = ClientBuilder.newClient(); try { Iterator<AfterLRAListener> listeners = afterLRAListeners.iterator(); while (listeners.hasNext()) { AfterLRAListener participant = listeners.next(); Response response = null; try { Future<Response> asyncResponse = client.target(participant.notificationURI) .request() .header(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER, id) .header(LRA_HTTP_RECOVERY_HEADER, participant.recoveryId.toASCIIString()) .async() .put(Entity.text(status.name())); response = asyncResponse.get(PARTICIPANT_TIMEOUT, TimeUnit.SECONDS); if (response.getStatus() == 200) { listeners.remove(); } else { notifiedAll = false; } response = null; } catch (WebApplicationException | InterruptedException | ExecutionException | TimeoutException e) { notifiedAll = false; if (LRALogger.logger.isInfoEnabled()) { LRALogger.logger.infof("Could not notify AfterLRA listener at %s (%s)", participant.notificationURI, e.getMessage()); } } finally { if (response != null) { response.close(); } } } } finally { client.close(); } } return notifiedAll; }
Source:
protected Boolean doCall() { LOGGER.info("Waiting for network interfaces to be detached: {}", attachedNetworkInterfaces); PagedList<NetworkInterface> networkInterfaces = context.getAzureClient().getNetworkInterfaces(context.getResourceGroupName()); networkInterfaces.loadAll(); List<NetworkInterface> filteredNetworkInterfaces = networkInterfaces .stream() .filter(networkInterface -> attachedNetworkInterfaces .contains(networkInterface.name())) .collect(Collectors.toList()); attachedNetworkInterfaces = filteredNetworkInterfaces .stream() .filter(ni -> ni.virtualMachineId() != null) .map(NetworkInterface::name) .collect(Collectors.toSet()); return attachedNetworkInterfaces.isEmpty(); }

Target:
protected Boolean doCall() { LOGGER.info("Waiting for network interfaces to be detached: {}", attachedNetworkInterfaces); AzureClient azureClient = context.getAzureClient(); String resourceGroupName = context.getResourceGroupName(); List<NetworkInterface> filteredNetworkInterfaces = azureClient.getNetworkInterfaceListByNames(resourceGroupName, attachedNetworkInterfaces); attachedNetworkInterfaces = filteredNetworkInterfaces .stream() .filter(ni -> ni.virtualMachineId() != null) .map(NetworkInterface::name) .collect(Collectors.toSet()); return attachedNetworkInterfaces.isEmpty(); }
Source:
protected Statement classBlock(final RunNotifier notifier) { Statement statement = childrenInvoker(notifier); if (areAllChildrenIgnored() == false) { statement = withBeforeClasses(statement); statement = withAfterClasses(statement); statement = withClassRules(statement); } return statement; }

Target:
protected Statement classBlock(final RunNotifier notifier) { Statement statement = childrenInvoker(notifier); if (!areAllChildrenIgnored()) { statement = withBeforeClasses(statement); statement = withAfterClasses(statement); statement = withClassRules(statement); } return statement; }
Source:
public CloseableIteration<? extends Entry<RyaStatement, BindingSet>, RyaDAOException> queryWithBindingSet( final Collection<Entry<RyaStatement, BindingSet>> stmts, MongoDBRdfConfiguration conf) throws RyaDAOException { if (conf == null) { conf = configuration; } final Multimap<RyaStatement, BindingSet> rangeMap = HashMultimap.create(); try { for (final Map.Entry<RyaStatement, BindingSet> stmtbs : stmts) { final RyaStatement stmt = stmtbs.getKey(); final BindingSet bs = stmtbs.getValue(); rangeMap.put(stmt, bs); } final RyaStatementBindingSetCursorIterator iterator = new RyaStatementBindingSetCursorIterator( getCollection(conf), rangeMap, strategy, conf.getAuthorizations()); return iterator; } catch (final Exception e) { throw new RyaDAOException(e); } }

Target:
public CloseableIteration<? extends Entry<RyaStatement, BindingSet>, RyaDAOException> queryWithBindingSet( final Collection<Entry<RyaStatement, BindingSet>> stmts, MongoDBRdfConfiguration conf) throws RyaDAOException { Preconditions.checkNotNull(stmts); Preconditions.checkNotNull(conf); final Multimap<RyaStatement, BindingSet> rangeMap = HashMultimap.create(); try { for (final Map.Entry<RyaStatement, BindingSet> stmtbs : stmts) { final RyaStatement stmt = stmtbs.getKey(); final BindingSet bs = stmtbs.getValue(); rangeMap.put(stmt, bs); } final RyaStatementBindingSetCursorIterator iterator = new RyaStatementBindingSetCursorIterator( getCollection(conf), rangeMap, strategy, conf.getAuthorizations()); return iterator; } catch (final Exception e) { throw new RyaDAOException(e); } }
Source:
public synchronized <V> Map<K, V> getNextTrainingData() { if (trainingDataKeySet.isEmpty()) { return Collections.emptyMap(); } final Iterator<K> iterator = trainingDataKeySet.iterator(); final List<K> nextTrainingDataKeyList = new ArrayList<>(); while (iterator.hasNext() && nextTrainingDataKeyList.size() < miniBatchSize) { nextTrainingDataKeyList.add(iterator.next()); } trainingDataKeySet.removeAll(nextTrainingDataKeyList); final Map<K, V> nextTrainingData = new HashMap<>(); for (final K key : nextTrainingDataKeyList) { final Pair<K, V> keyValuePair = memoryStore.get(key); if (keyValuePair == null) { continue; } nextTrainingData.put(keyValuePair.getFirst(), keyValuePair.getSecond()); } LOG.log(Level.INFO, "next training data size = " + nextTrainingData.size()); return nextTrainingData; }

Target:
public <V> Map<K, V> getNextTrainingData() { final List<K> nextTrainingDataKeyList = new ArrayList<>(miniBatchSize); synchronized (this) { if (trainingDataKeySet.isEmpty()) { LOG.log(Level.INFO, "no more training data for current epoch"); return Collections.emptyMap(); } final Iterator<K> iterator = trainingDataKeySet.iterator(); while (iterator.hasNext() && nextTrainingDataKeyList.size() < miniBatchSize) { nextTrainingDataKeyList.add(iterator.next()); } trainingDataKeySet.removeAll(nextTrainingDataKeyList); } final Map<K, V> nextTrainingData = new HashMap<>(); for (final K key : nextTrainingDataKeyList) { final Pair<K, V> keyValuePair = memoryStore.get(key); if (keyValuePair == null) { continue; } nextTrainingData.put(keyValuePair.getFirst(), keyValuePair.getSecond()); } LOG.log(Level.INFO, "Size of training data for next mini-batch: {0}", nextTrainingData.size()); if (nextTrainingDataKeyList.size() != nextTrainingData.size()) { LOG.log(Level.INFO, "The number of assigned data keys for next mini-batch is {0}," + " but ths size of actually prepared training data is {1}", new Object[]{nextTrainingDataKeyList.size(), nextTrainingData.size()}); } return nextTrainingData; }
Source:
public Map<Integer, EmulatedMachine> getOsEmulatedMachines() { Map<Integer, EmulatedMachine> emList = new HashMap<>(); for (int osId : getOsIds()) { String emValue = getValueByVersion(idToUnameLookup.get(osId), "emulatedMachine", null); if (emValue != null) { try { EmulatedMachine em = EmulatedMachine.valueOf(emValue); if (em != null) { emList.put(osId, em); } } catch (Exception ex) { log.error("osinfo: unknow Emulated Machine value {}", emValue); } } } return emList; }

Target:
public Map<Integer, EmulatedMachine> getOsEmulatedMachines() { Map<Integer, EmulatedMachine> osIdToEmulatedMachine = new HashMap<>(); for (int osId : getOsIds()) { String emValue = getValueByVersion(idToUnameLookup.get(osId), "emulatedMachine", null); if (emValue != null) { try { EmulatedMachine em = EmulatedMachine.valueOf(emValue); if (em != null) { osIdToEmulatedMachine.put(osId, em); } } catch (Exception ex) { log.error("osinfo: unknow Emulated Machine value {}", emValue); } } } return osIdToEmulatedMachine; }
Source:
public void mergeProjectsValidNameTests() { openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); onView(withText(R.string.merge)).perform(click()); onRecyclerView().atPosition(0) .performCheckItem(); onRecyclerView().atPosition(1) .performCheckItem(); onView(withId(R.id.confirm)).perform(click()); onView(allOf(withText(""), isDisplayed(), instanceOf(EditText.class))) .perform(replaceText(validName)); closeSoftKeyboard(); onView(Matchers.allOf(withId(android.R.id.button1), withText(R.string.ok))) .check(matches(Matchers.allOf(isDisplayed(), isEnabled()))); }

Target:
public void mergeProjectsValidNameTests() { openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); onView(withText(R.string.merge)).perform(click()); onRecyclerView().atPosition(0) .performCheckItem(); onRecyclerView().atPosition(1) .performCheckItem(); onView(withId(R.id.confirm)).perform(click()); onView(allOf(withText(""), isDisplayed(), instanceOf(EditText.class))) .perform(replaceText(VALIDNAME)); closeSoftKeyboard(); onView(allOf(withId(android.R.id.button1), withText(R.string.ok))) .check(matches(Matchers.allOf(isDisplayed(), isEnabled()))); }
Source:
protected <T extends Descriptor> T merge(Collection<T> descriptors) { T descriptor = null; for (T d : descriptors) { if (d.remove()) { descriptor = null; continue; } descriptor = descriptor == null ? d : (T) descriptor.merge(d); } return descriptor; }

Target:
protected <T extends Descriptor> T merge(Collection<T> descriptors) { T descriptor = null; for (T d : descriptors) { if (d.doesRemove()) { descriptor = null; } else { descriptor = descriptor == null ? d : (T) descriptor.merge(d); } } return descriptor; }
Source:
private ReplicationPeerImpl createPeer(String peerId) throws ReplicationException { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState syncReplicationState = peerStorage.getPeerSyncReplicationState(peerId); SyncReplicationState newSyncReplicationState = peerStorage.getPeerNewSyncReplicationState(peerId); ReplicationPeerConfig updatedPeerConfig = ReplicationPeerConfigUtil. addBasePeerConfigsIfNotPresent(this.conf, peerConfig); peerStorage.updatePeerConfig(peerId,updatedPeerConfig); return new ReplicationPeerImpl(ReplicationUtils.getPeerClusterConfiguration(peerConfig, conf), peerId, updatedPeerConfig, enabled, syncReplicationState, newSyncReplicationState); }

Target:
private ReplicationPeerImpl createPeer(String peerId) throws ReplicationException { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState syncReplicationState = peerStorage.getPeerSyncReplicationState(peerId); SyncReplicationState newSyncReplicationState = peerStorage.getPeerNewSyncReplicationState(peerId); return new ReplicationPeerImpl(ReplicationUtils.getPeerClusterConfiguration(peerConfig, conf), peerId, peerConfig, enabled, syncReplicationState, newSyncReplicationState); }
Source:
private void disconnectSession() { if (mSession == null) { return; } if (mSubscribers.size() > 0) { for (Subscriber subscriber : mSubscribers) { if (subscriber != null) { mSession.unsubscribe(subscriber); subscriber.destroy(); } } } if (mPublisher != null) { mSession.unpublish(mPublisher); mPublisher.destroy(); mPublisher = null; } mSession.disconnect(); }

Target:
private void disconnectSession() { if (mSession == null) { return; } if (mSubscribers.size() > 0) { for (Subscriber subscriber : mSubscribers) { if (subscriber != null) { mSession.unsubscribe(subscriber); subscriber.destroy(); } } } if (mPublisher != null) { mSession.unpublish(mPublisher); mContainer.removeView(mPublisher.getView()); mPublisher.destroy(); mPublisher = null; } mSession.disconnect(); }
Source:
public TaskLogAutoCleanerConfig( @JsonProperty("enabled") boolean enabled, @JsonProperty("initialDelay") Long initialDelay, @JsonProperty("delay") Long delay, @JsonProperty("durationToRetain") Long durationToRetain ){ if (enabled) { Preconditions.checkNotNull(durationToRetain, "durationToRetain must be provided."); } this.enabled = enabled; this.initialDelay = initialDelay == null ? 60000 + new Random().nextInt(4*60000) : initialDelay.longValue(); this.delay = delay == null ? 6*60*60*1000 : delay.longValue(); this.durationToRetain = durationToRetain == null ? Long.MAX_VALUE : durationToRetain.longValue(); }

Target:
public TaskLogAutoCleanerConfig( @JsonProperty("enabled") boolean enabled, @JsonProperty("initialDelay") Long initialDelay, @JsonProperty("delay") Long delay, @JsonProperty("durationToRetain") Long durationToRetain ){ if (enabled) { Preconditions.checkNotNull(durationToRetain, "durationToRetain must be provided."); } this.enabled = enabled; this.initialDelay = initialDelay == null ? 60000 + new Random().nextInt(4*60000) : initialDelay.longValue(); this.delay = delay == null ? 6*60*60*1000 : delay.longValue(); this.durationToRetain = durationToRetain == null ? Long.MAX_VALUE : durationToRetain.longValue(); Preconditions.checkArgument(this.initialDelay > 0, "initialDelay must be > 0."); Preconditions.checkArgument(this.delay > 0, "delay must be > 0."); Preconditions.checkArgument(this.durationToRetain > 0, "durationToRetain must be > 0."); }
Source:
private void initApprovalType(final PatchSetPublishDetail r, final Panel body, final ApprovalType ct, final PermissionRange range) { body.add(new SmallHeading(ct.getCategory().getName() + ":")); final VerticalPanel vp = new VerticalPanel(); vp.setStyleName(Gerrit.RESOURCES.css().approvalCategoryList()); final List<ApprovalCategoryValue> lst = new ArrayList<ApprovalCategoryValue>(ct.getValues()); Collections.reverse(lst); final ApprovalCategory.Id catId = ct.getCategory().getId(); final PatchSetApproval prior = r.getChangeApproval(catId); for (final ApprovalCategoryValue buttonValue : lst) { if (!range.contains(buttonValue.getValue())) { continue; } final ValueRadioButton b = new ValueRadioButton(buttonValue, ct.getCategory().getName()); b.setHTML(buttonValue.format()); if (lastState != null && patchSetId.equals(lastState.patchSetId) && lastState.approvals.containsKey(buttonValue.getCategoryId())) { b.setValue(lastState.approvals.get(buttonValue.getCategoryId()).equals( buttonValue)); } else { b.setValue(prior != null ? buttonValue.getValue() == prior.getValue() : buttonValue.getValue() == 0); } approvalButtons.add(b); vp.add(b); } body.add(vp); }

Target:
private void initApprovalType(final PatchSetPublishDetail r, final Panel body, final ApprovalType ct, final PermissionRange range) { body.add(new SmallHeading(ct.getCategory().getName() + ":")); final VerticalPanel vp = new VerticalPanel(); vp.setStyleName(Gerrit.RESOURCES.css().approvalCategoryList()); final List<ApprovalCategoryValue> lst = new ArrayList<ApprovalCategoryValue>(ct.getValues()); Collections.reverse(lst); final ApprovalCategory.Id catId = ct.getCategory().getId(); final PatchSetApproval prior = r.getChangeApproval(catId); for (final ApprovalCategoryValue buttonValue : lst) { if (!range.contains(buttonValue.getValue())) { continue; } ValueRadioButton b = new ValueRadioButton(ct.getCategory(), buttonValue); SafeHtml buf = new SafeHtmlBuilder().append(buttonValue.format()); buf = CommentLinkProcessor.apply(buf); SafeHtml.set(b, buf); if (lastState != null && patchSetId.equals(lastState.patchSetId) && lastState.approvals.containsKey(buttonValue.getCategoryId())) { b.setValue(lastState.approvals.get(buttonValue.getCategoryId()).equals( buttonValue)); } else { b.setValue(prior != null ? buttonValue.getValue() == prior.getValue() : buttonValue.getValue() == 0); } approvalButtons.add(b); vp.add(b); } body.add(vp); }
Source:
ExtractEdge() throws NoCurrentCaseException{ moduleName = NbBundle.getMessage(Chrome.class, "ExtractEdge.moduleName"); moduleTempResultsDir = RAImageIngestModule.getRATempPath(Case.getCurrentCaseThrows(), EDGE) + File.separator + "results"; }

Target:
ExtractEdge() throws NoCurrentCaseException { moduleTempResultPath = Paths.get(RAImageIngestModule.getRATempPath(Case.getCurrentCaseThrows(), EDGE), "results"); }
Source:
public double getY() { double speed; try { speed = motionController.getSafely(); } catch (InvalidSensorException e) { LogKitten.w("Cancelling ChassisMoveDistance"); chassisMove.cancel(); cancel(); if (fallbackCommand != null) { fallbackCommand.initialize(); } speed = 0; } LogKitten.d("MotionProfileSpeed: " + speed); return speed; }

Target:
public double getY() { double speed; try { speed = motionController.getSafely(); } catch (InvalidSensorException e) { LogKitten.w("Cancelling ChassisMoveDistance with InvalidSensorException"); chassisMove.cancel(); cancel(); if (fallbackCommand != null) { fallbackCommand.schedule(); } speed = 0; } LogKitten.d("MotionProfileSpeed: " + speed); return speed; }
Source:
protected void ensurePagesListCapacity(long size) { int capacity = pageIndex(size) + 1; if (capacity > maxPages) { throw LimitOverflowException.instance().put("Maximum number of pages (").put(maxPages).put(") breached in VirtualMemory"); } pages.ensureCapacity(capacity); }

Target:
protected void ensurePagesListCapacity(long size) { int capacity = pageIndex(size) + 1; pages.ensureCapacity(capacity); }
Source:
public void verifyBuilder() { final RollingOperation.Builder builder = RollingOperation.newBuilder(); final String setDeploymentGroupName = "foo-group"; final List<HostSelector> setHostSelectors = ImmutableList.of(HostSelector.parse("foo=bar"), HostSelector.parse("baz=qux")); final JobId setJobId = JobId.fromString("foo:0.1.0"); final RolloutOptions setRolloutOptions = RolloutOptions.newBuilder() .setTimeout(1000) .setParallelism(2) .setMigrate(false) .build(); final RollingOperation.Reason setReason = RollingOperation.Reason.MANUAL; builder.setDeploymentGroupName(setDeploymentGroupName); builder.setJobId(setJobId); builder.setRolloutOptions(setRolloutOptions); builder.setReason(setReason); assertEquals("name", setDeploymentGroupName, builder.getDeploymentGroupName()); assertEquals("jobId", setJobId, builder.getJobId()); assertEquals("rolloutOptions", setRolloutOptions, builder.getRolloutOptions()); assertEquals("reason", setReason, builder.getReason()); final RollingOperation deploymentGroup = builder.build(); assertEquals("name", setDeploymentGroupName, deploymentGroup.getDeploymentGroupName()); assertEquals("jobId", setJobId, deploymentGroup.getJobId()); assertEquals("rolloutOptions", setRolloutOptions, deploymentGroup.getRolloutOptions()); assertEquals("reason", setReason, deploymentGroup.getReason()); }

Target:
public void verifyBuilder() { final RollingOperation.Builder builder = RollingOperation.newBuilder(); final String setDeploymentGroupName = "foo-group"; final JobId setJobId = JobId.fromString("foo:0.1.0"); final RolloutOptions setRolloutOptions = RolloutOptions.newBuilder() .setTimeout(1000) .setParallelism(2) .setMigrate(false) .build(); final RollingOperation.Reason setReason = RollingOperation.Reason.MANUAL; builder.setDeploymentGroupName(setDeploymentGroupName); builder.setJobId(setJobId); builder.setRolloutOptions(setRolloutOptions); builder.setReason(setReason); assertEquals("name", setDeploymentGroupName, builder.getDeploymentGroupName()); assertEquals("jobId", setJobId, builder.getJobId()); assertEquals("rolloutOptions", setRolloutOptions, builder.getRolloutOptions()); assertEquals("reason", setReason, builder.getReason()); final RollingOperation deploymentGroup = builder.build(); assertEquals("name", setDeploymentGroupName, deploymentGroup.getDeploymentGroupName()); assertEquals("jobId", setJobId, deploymentGroup.getJobId()); assertEquals("rolloutOptions", setRolloutOptions, deploymentGroup.getRolloutOptions()); assertEquals("reason", setReason, deploymentGroup.getReason()); }
Source:
void validateValueParameter(String name, Object value) { Class<? extends IValueValidator> validators[] = wrappedParameter.validateValueWith(); if (validators != null && validators.length>0) { for(final Class<? extends IValueValidator> validator: validators) { validateValueParameter(validator, name, value); } } }

Target:
void validateValueParameter(String name, Object value) { final Class<? extends IValueValidator> validators[] = wrappedParameter.validateValueWith(); if (validators != null && validators.length > 0) { for(final Class<? extends IValueValidator> validator: validators) { validateValueParameter(validator, name, value); } } }
Source:
public Tracer getTracer() { Object tracerObject = servletContext.getAttribute(TracerInitializer.SMALLRYE_OPENTRACING_TRACER); TracingLogger.ROOT_LOGGER.warnf("Producing tracer from ServletContext, using %s", tracerObject); if (tracerObject instanceof Tracer) { return (Tracer) tracerObject; } return null; }

Target:
public Tracer getTracer() { Object tracerObject = servletContext.getAttribute(TracerInitializer.SMALLRYE_OPENTRACING_TRACER); TracingLogger.ROOT_LOGGER.producingTracer(tracerObject); if (tracerObject instanceof Tracer) { return (Tracer) tracerObject; } return null; }
Source:
private boolean isUnused(ImportPackageObject pkg, Collection<?> exportedPackages, IProgressMonitor monitor) { if (exportedPackages != null && exportedPackages.contains(pkg.getValue())) { monitor.done(); return false; } return !provideJavaClasses(pkg, monitor); }

Target:
private boolean isUnused(ImportPackageObject pkg, Collection<?> exportedPackages, IProgressMonitor monitor) { if (exportedPackages != null && exportedPackages.contains(pkg.getValue())) { return false; } return !provideJavaClasses(pkg, monitor); }
Source:
private void loadApns(SQLiteDatabase db, XmlPullParser parser) { if (parser != null) { try { db.beginTransaction(); while (true) { try { XmlUtils.nextElement(parser); } catch (XmlPullParserException e) { Log.e(TAG, "Got parser execption while getting next element", e); continue; } catch (Exception e) { Log.e(TAG, "Got execption while getting next element", e); continue; } ContentValues row = getRow(parser); if (row != null) { insertAddingDefaults(db, CARRIERS_TABLE, row); } else { break; } } db.setTransactionSuccessful(); } catch (SQLException e){ Log.e(TAG, "Got SQLException while loading apns.", e); } finally { db.endTransaction(); } } }

Target:
private void loadApns(SQLiteDatabase db, XmlPullParser parser) { if (parser != null) { try { db.beginTransaction(); while (parser.getEventType() != XmlPullParser.END_DOCUMENT) { try { XmlUtils.nextElement(parser); } catch (XmlPullParserException e) { Log.e(TAG, "Got parser execption while getting next element", e); continue; } ContentValues row = getRow(parser); if (row == null) { continue; } insertAddingDefaults(db, CARRIERS_TABLE, row); } db.setTransactionSuccessful(); } catch (XmlPullParserException e) { Log.e(TAG, "Got XmlPullParserException while loading apns.", e); } catch (IOException e) { Log.e(TAG, "Got IOException while loading apns.", e); } catch (SQLException e) { Log.e(TAG, "Got SQLException while loading apns.", e); } finally { db.endTransaction(); } } }
Source:
protected void setDefaultNetwork(Long accountId) { Account account = objectManager.loadResource(Account.class, accountId); if (account == null) { return; } Long defaultNetworkId = account.getDefaultNetworkId(); Long newDefaultNetworkId = null; for (Network network : networkDao.getActiveNetworks(account.getId())) { if (network.getKind().startsWith(NetworkConstants.PREFIX_KIND_DOCKER) || network.getKind().equals("hostOnlyNetwork")) { continue; } if (network.getId().equals(defaultNetworkId)) { newDefaultNetworkId = defaultNetworkId; break; } if (CommonStatesConstants.ACTIVATING.equals(network.getState()) && newDefaultNetworkId == null) { newDefaultNetworkId = network.getId(); } else if (CommonStatesConstants.UPDATING_ACTIVE.equals(network.getState()) && newDefaultNetworkId == null) { newDefaultNetworkId = network.getId(); } else if (CommonStatesConstants.ACTIVE.equals(network.getState())) { newDefaultNetworkId = network.getId(); } } if (!ObjectUtils.equals(defaultNetworkId, newDefaultNetworkId)) { objectManager.setFields(account, AccountConstants.FIELD_DEFAULT_NETWORK_ID, newDefaultNetworkId); } }

Target:
protected void setDefaultNetwork(Long accountId) { Account account = objectManager.loadResource(Account.class, accountId); if (account == null) { return; } Long defaultNetworkId = account.getDefaultNetworkId(); Long newDefaultNetworkId = null; for (Network network : networkDao.getActiveNetworks(account.getId())) { if (network.getKind().startsWith(NetworkConstants.PREFIX_KIND_DOCKER) || network.getKind().equals("hostOnlyNetwork")) { continue; } if (network.getId().equals(defaultNetworkId)) { newDefaultNetworkId = defaultNetworkId; break; } if ((CommonStatesConstants.ACTIVATING.equals(network.getState()) || CommonStatesConstants.UPDATING_ACTIVE.equals(network.getState())) && newDefaultNetworkId == null) { newDefaultNetworkId = network.getId(); } else if (CommonStatesConstants.ACTIVE.equals(network.getState())) { newDefaultNetworkId = network.getId(); } } if (!ObjectUtils.equals(defaultNetworkId, newDefaultNetworkId)) { objectManager.setFields(account, AccountConstants.FIELD_DEFAULT_NETWORK_ID, newDefaultNetworkId); } }
Source:
public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) { return source.getUserProvidedIdentifier() != null ? source.getUserProvidedIdentifier() : toIdentifier( NamingHelper.INSTANCE.generateHashedFkName( "FK", source.getTableName(), source.getReferencedTableName(), source.getColumnNames() ), source.getBuildingContext() ); }

Target:
public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) { Identifier userProvidedIdentifier = source.getUserProvidedIdentifier(); return userProvidedIdentifier != null ? userProvidedIdentifier : toIdentifier( NamingHelper.INSTANCE.generateHashedFkName( "FK", source.getTableName(), source.getReferencedTableName(), source.getColumnNames() ), source.getBuildingContext() ); }
Source:
public void shouldNotifyEventWhenRemoveComment() { Comment comment = createComment(commentedDocumentModel); DocumentModel commentDocModel = session.getDocument(new IdRef(comment.getId())); commentDocModel.detach(true); transactionalFeature.nextTransaction(); try (CapturingEventListener listener = new CapturingEventListener(COMMENT_REMOVED)) { commentManager.deleteComment(session, comment.getId()); DocumentModel commentParentDocumentModel = session.getDocument( new IdRef((String) commentDocModel.getPropertyValue(COMMENT_PARENT_ID))); transactionalFeature.nextTransaction(); Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, commentDocModel, commentParentDocumentModel, commentedDocumentModel); } }

Target:
public void shouldNotifyEventWhenRemoveComment() { Comment comment = createComment(commentedDocumentModel); transactionalFeature.nextTransaction(); try (CapturingEventListener listener = new CapturingEventListener(COMMENT_REMOVED)) { DocumentModel commentDocModel = session.getDocument(new IdRef(comment.getId())); commentManager.deleteComment(session, comment.getId()); transactionalFeature.nextTransaction(); DocumentModel commentParentDocumentModel = session.getDocument( new IdRef((String) commentDocModel.getPropertyValue(COMMENT_PARENT_ID))); Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, commentDocModel, commentParentDocumentModel, commentedDocumentModel); } }
Source:
public boolean isPotionApplicable(PotionEffect potioneffectIn) { if (potioneffectIn.getPotion() == MobEffects.POISON && getFaction().equals("lizardman|coven")) { net.minecraftforge.event.entity.living.PotionEvent.PotionApplicableEvent event = new net.minecraftforge.event.entity.living.PotionEvent.PotionApplicableEvent(this, potioneffectIn); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event); return event.getResult() == net.minecraftforge.fml.common.eventhandler.Event.Result.ALLOW; } return super.isPotionApplicable(potioneffectIn); }

Target:
public boolean isPotionApplicable(PotionEffect potioneffectIn) { if (potioneffectIn.getPotion() == MobEffects.POISON && getFaction().equals("lizardman|coven")) { PotionEvent.PotionApplicableEvent event = new PotionEvent.PotionApplicableEvent(this, potioneffectIn); EVENT_BUS.post(event); return event.getResult() == ALLOW; } return super.isPotionApplicable(potioneffectIn); }
Source:
public void silentlyMigrateConfigsTest() throws Exception { j.jenkins.save(); assertThat(j.jenkins.getLabelString(), is("I am a label")); File configFile = new File(j.jenkins.getRootPath().getRemote() + File.separator + "config.xml"); assertThat(configFile.exists(), is(true)); BufferedReader config = new BufferedReader(new FileReader(configFile)); assertThat(config.readLine(), is("<?xml version='1.1' encoding='UTF-8'?>")); config.close(); }

Target:
public void silentlyMigrateConfigsTest() throws Exception { j.jenkins.save(); assertThat(j.jenkins.getLabelString(), is("I am a label")); File configFile = new File(j.jenkins.getRootDir(), "config.xml"); assertThat(configFile.exists(), is(true)); try (BufferedReader config = new BufferedReader(new FileReader(configFile))) { assertThat(config.readLine(), is("<?xml version='1.1' encoding='UTF-8'?>")); config.close(); } }
Source:
public void onFailure(Exception e) { Timber.d("Resources fetching failed. 1"); }

Target:
public void onFailure(Exception e) { Timber.d("Resources fetching failed."); }
Source:
public void onApiChange(SyncthingService.State currentState) { if (mGui == null) { return; } if (currentState != SyncthingService.State.ACTIVE && !isFinishing()) { if (currentState == SyncthingService.State.DISABLED) { if (mLoadingDialog != null) { mLoadingDialog.dismiss(); } mDisabledDialog = SyncthingService.showDisabledDialog(mGui); } else if (mLoadingDialog == null) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.loading_dialog, null); TextView loadingText = (TextView) dialogLayout.findViewById(R.id.loading_text); loadingText.setText((getService().isFirstStart()) ? R.string.web_gui_creating_key : R.string.api_loading); mLoadingDialog = new AlertDialog.Builder(mGui) .setCancelable(false) .setView(dialogLayout) .show(); if (prefs.getBoolean("first_start", true)) { new AlertDialog.Builder(mGui) .setTitle(R.string.welcome_title) .setMessage(R.string.welcome_text) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { prefs.edit().putBoolean("first_start", false).commit(); } }) .show(); } } return; } if (mLoadingDialog != null) { mLoadingDialog.dismiss(); } if (mDisabledDialog != null) { mDisabledDialog.dismiss(); } mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); }

Target:
public void onApiChange(SyncthingService.State currentState) { if (currentState != SyncthingService.State.ACTIVE && !isFinishing() && !isDestroyed()) { if (currentState == SyncthingService.State.DISABLED) { if (mLoadingDialog != null) { mLoadingDialog.dismiss(); } mDisabledDialog = SyncthingService.showDisabledDialog(this); } else if (mLoadingDialog == null) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.loading_dialog, null); TextView loadingText = (TextView) dialogLayout.findViewById(R.id.loading_text); loadingText.setText((getService().isFirstStart()) ? R.string.web_gui_creating_key : R.string.api_loading); mLoadingDialog = new AlertDialog.Builder(this) .setCancelable(false) .setView(dialogLayout) .show(); if (prefs.getBoolean("first_start", true)) { new AlertDialog.Builder(this) .setTitle(R.string.welcome_title) .setMessage(R.string.welcome_text) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { prefs.edit().putBoolean("first_start", false).commit(); } }) .show(); } } return; } if (mLoadingDialog != null) { mLoadingDialog.dismiss(); } if (mDisabledDialog != null) { mDisabledDialog.dismiss(); } mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); }
Source:
public GroupByStrategy strategize(GroupByQuery query) { final String strategyString = getStrategy(query); switch (strategyString) { case STRATEGY_V2: return strategyV2; case STRATEGY_V1: return strategyV1; default: throw new ISE("No such strategy[%s]", strategyString); } }

Target:
public GroupByStrategy strategize(GroupByQuery query) { final String strategyString = config.withOverrides(query).getDefaultStrategy(); switch (strategyString) { case STRATEGY_V2: return strategyV2; case STRATEGY_V1: return strategyV1; default: throw new ISE("No such strategy[%s]", strategyString); } }
Source:
protected Integer calculateRecordsJSON(String jsonStr) { Integer rec; try { JSONObject j = new JSONObject(jsonStr); try { rec = j.getJSONArray("data").length(); } catch (JSONException e2) { rec = null; } } catch (JSONException e) { rec = null; } return rec; }

Target:
protected Integer calculateRecordsJSON(String jsonStr) { Integer rec; try { JSONObject j = new JSONObject(jsonStr); rec = j.getJSONArray("data").length(); } catch (JSONException e) { rec = null; } return rec; }
Source:
protected void onError(HttpField field, Throwable t) { LOG.warn("Exception while processing {}", field, t); throw new BadMessageException("Bad header value for " + field.getName()); }

Target:
protected void onError(HttpField field, Throwable t) { throw new BadMessageException("Bad header value for " + field.getName(), t); }
Source:
public static LoadBalancer getDefault(String urls) { String[] endpoints = new String[0]; if (urls != null) { endpoints = urls.split("\\|"); } return getDefault(Arrays.asList(endpoints)); }

Target:
public static LoadBalancer getDefault(String urls) { String[] endpoints = new String[0]; if (urls != null) { endpoints = urls.split(URL_SEP); } return getDefault(Arrays.asList(endpoints)); }
Source:
public MinMaxStats(@NonNull INDArray lower, @NonNull INDArray upper) { INDArray diff = upper.sub(lower); INDArray withEpsilon = Transforms.max(diff, Nd4j.EPS_THRESHOLD); INDArray addedPadding = withEpsilon.sub(diff); if (addedPadding.sumNumber().doubleValue() > 0) { logger.info("API_INFO: max val minus min val found to be zero. Transform will round up to epsilon to avoid nans."); upper.addi(addedPadding); } this.lower = lower; this.upper = upper; }

Target:
public MinMaxStats(@NonNull INDArray lower, @NonNull INDArray upper) { INDArray diff = upper.sub(lower); INDArray addedPadding = Transforms.max(diff, Nd4j.EPS_THRESHOLD).subi(diff); if (addedPadding.sumNumber().doubleValue() > 0) { logger.info("API_INFO: max val minus min val found to be zero. Transform will round up to epsilon to avoid nans."); upper.addi(addedPadding); } this.lower = lower; this.upper = upper; }
Source:
private void launch() { if(zibaseListener!=null) { zibaseListener.shutdown(); } try { zibase = new Zibase(ip); logger.info("connected to zibase for command sending"); } catch(Throwable th) { logger.info("Error connecting to zibase using specified ip address"); } try { logger.info("Starting zibase listener thread..."); zibaseListener = new ZibaseListener(); zibaseListener.setZibase(zibase); zibaseListener.setEventPubisher(eventPublisher); zibaseListener.setListenerHost(listenerHost); zibaseListener.setListenerPort(listenerPort); zibaseListener.start(); } catch(Throwable th) { logger.info("Error connecting to zibase for listening"); } }

Target:
private void launch() { if(zibaseListener!=null) { zibaseListener.shutdown(); } zibase = new Zibase(ip); logger.info("connected to zibase for command sending"); logger.info("Starting zibase listener thread..."); zibaseListener = new ZibaseListener(); zibaseListener.setZibase(zibase); zibaseListener.setEventPubisher(eventPublisher); zibaseListener.setListenerHost(listenerHost); zibaseListener.setListenerPort(listenerPort); zibaseListener.start(); }
Source:
public Widget setHidden(boolean hidden) { this.hidden = hidden; if (content != null && content instanceof Form) { ((Form) content).setHidden(hidden); } else if (content != null && content instanceof Property) { Property prop = (Property) content; if (hidden) { prop.addFlag(Property.Flags.HIDDEN); } else { prop.removeFlag(Property.Flags.HIDDEN); } } else if (content != null && content instanceof PropertiesImpl) { Arrays.stream(content.getClass().getFields()).forEach(field -> { if (!field.isAccessible()) { field.setAccessible(true); } try { Object o = field.get(content); if (o instanceof Property) { if (hidden) { ((Property) o).addFlag(Property.Flags.HIDDEN); } else { ((Property) o).removeFlag(Property.Flags.HIDDEN); } } } catch (IllegalArgumentException | IllegalAccessException e) { } }); } return this; }

Target:
public Widget setHidden(boolean hidden) { this.hidden = hidden; if (content == null) { return this; } if (content instanceof Form) { ((Form) content).setHidden(hidden); } else { setHiddenProperty(content, hidden); } return this; }
Source:
public CompletableFuture<List<SnapshotDescription>> listSnapshots(Pattern arg0) { throw new UnsupportedOperationException("updateConfiguration"); }

Target:
public CompletableFuture<List<SnapshotDescription>> listSnapshots(Pattern arg0) { throw new UnsupportedOperationException("listSnapshots"); }
Source:
private synchronized Map<String, String> scheduleTasks(List<String> tableNamesWithType, boolean isLeader) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.NUMBER_TIMES_SCHEDULE_TASKS_CALLED, 1L); Set<String> taskTypes = _taskGeneratorRegistry.getAllTaskTypes(); Map<String, List<TableConfig>> enabledTableConfigMap = new HashMap<>(); for (String tableNameWithType : tableNamesWithType) { TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType); if (tableConfig != null && tableConfig.getTaskConfig() != null) { Set<String> enabledTaskTypes = tableConfig.getTaskConfig().getTaskTypeConfigsMap().keySet(); for (String enabledTaskType : enabledTaskTypes) { if (taskTypes.contains(enabledTaskType)) { enabledTableConfigMap.computeIfAbsent(enabledTaskType, k -> new ArrayList<>()).add(tableConfig); } else { LOGGER.warn("Task type: is not registered, cannot enable it for table: {}", enabledTaskType, tableNameWithType); } } } } Map<String, String> tasksScheduled = new HashMap<>(); for (Map.Entry<String, List<TableConfig>> entry : enabledTableConfigMap.entrySet()) { String taskType = entry.getKey(); _helixTaskResourceManager.ensureTaskQueueExists(taskType); String taskName = scheduleTask(_taskGeneratorRegistry.getTaskGenerator(taskType), entry.getValue(), isLeader); if (taskName != null) { tasksScheduled.put(taskType, taskName); } } return tasksScheduled; }

Target:
private synchronized Map<String, String> scheduleTasks(List<String> tableNamesWithType, boolean isLeader) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.NUMBER_TIMES_SCHEDULE_TASKS_CALLED, 1L); Map<String, List<TableConfig>> enabledTableConfigMap = new HashMap<>(); for (String tableNameWithType : tableNamesWithType) { TableConfig tableConfig = _pinotHelixResourceManager.getTableConfig(tableNameWithType); if (tableConfig != null && tableConfig.getTaskConfig() != null) { Set<String> enabledTaskTypes = tableConfig.getTaskConfig().getTaskTypeConfigsMap().keySet(); for (String enabledTaskType : enabledTaskTypes) { enabledTableConfigMap.computeIfAbsent(enabledTaskType, k -> new ArrayList<>()).add(tableConfig); } } } Map<String, String> tasksScheduled = new HashMap<>(); for (Map.Entry<String, List<TableConfig>> entry : enabledTableConfigMap.entrySet()) { String taskType = entry.getKey(); List<TableConfig> enabledTableConfigs = entry.getValue(); PinotTaskGenerator taskGenerator = _taskGeneratorRegistry.getTaskGenerator(taskType); if (taskGenerator != null) { _helixTaskResourceManager.ensureTaskQueueExists(taskType); tasksScheduled.put(taskType, scheduleTask(taskGenerator, enabledTableConfigs, isLeader)); } else { List<String> enabledTables = new ArrayList<>(enabledTableConfigs.size()); for (TableConfig enabledTableConfig : enabledTableConfigs) { enabledTables.add(enabledTableConfig.getTableName()); } LOGGER.warn("Task type: is not registered, cannot enable it for tables: {}", taskType, enabledTables); tasksScheduled.put(taskType, null); } } return tasksScheduled; }
Source:
public void partitioned(Map<Integer, Partition<T>> partitions) { logger.debug("Partitioned Map: {}", partitions); partitionedInstanceStatus.clear(); for (Map.Entry<Integer, Partition<T>> entry : partitions.entrySet()) { if (partitionedInstanceStatus.containsKey(entry.getKey())) { logger.debug("entry: {}", entry); } else { partitionedInstanceStatus.put(entry.getKey(), null); logger.debug("partitionedInstanceStatus: {}", partitionedInstanceStatus); } } }

Target:
public void partitioned(Map<Integer, Partition<T>> partitions) { logger.debug("Partitioned Map: {}", partitions); partitionedInstanceStatus.clear(); for (Map.Entry<Integer, Partition<T>> entry : partitions.entrySet()) { if (partitionedInstanceStatus.containsKey(entry.getKey())) { } else { partitionedInstanceStatus.put(entry.getKey(), null); } } }
Source:
public void registerTables() { tableEnv.executeSql("create table MyTable (a int, b bigint, c varchar(32)) " + "with ('connector' = 'filesystem', 'path' = '/non')"); tableEnv.executeSql("create table MyOtherTable (a int, b bigint) " + "with ('connector' = 'filesystem', 'path' = '/non')"); tableEnv.executeSql("create table MySink (a int, c varchar(32)) with ('connector' = 'COLLECTION' )"); }

Target:
public void registerTables() { registerTable("create table MyTable (a int, b bigint, c varchar(32)) " + "with ('connector' = 'filesystem', 'path' = '/non')"); registerTable("create table MyOtherTable (a int, b bigint) " + "with ('connector' = 'filesystem', 'path' = '/non')"); registerTable("create table MySink (a int, c varchar(32)) with ('connector' = 'COLLECTION' )"); }
Source:
public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException { JobExecution jobExecution = findExecutionById(executionId); BatchStatus status = jobExecution.getStatus(); if (!(status == BatchStatus.STARTED || status == BatchStatus.STARTING)) { throw new JobExecutionNotRunningException("JobExecution must be running so that it can be stopped: "+jobExecution); } jobExecution.setStatus(BatchStatus.STOPPING); jobRepository.update(jobExecution); Job job; try { job = jobRegistry.getJob(jobExecution.getJobInstance().getJobName()); if (job instanceof AbstractJob) { Collection<String> stepNames = ((AbstractJob)job).getStepNames(); for (String stepName : stepNames) { Step step = ((AbstractJob)job).getStep(stepName); if (step instanceof TaskletStep) { Tasklet tasklet = ((TaskletStep) step).getTasklet(); if (tasklet instanceof StoppableTasklet) { ((StoppableTasklet)tasklet).stop(); } } } } } catch (NoSuchJobException e) { logger.error("Couldn't find Job for the execution:" + jobExecution.getJobInstance().getJobName()); } return true; }

Target:
public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExecutionNotRunningException { JobExecution jobExecution = findExecutionById(executionId); BatchStatus status = jobExecution.getStatus(); if (!(status == BatchStatus.STARTED || status == BatchStatus.STARTING)) { throw new JobExecutionNotRunningException("JobExecution must be running so that it can be stopped: "+jobExecution); } jobExecution.setStatus(BatchStatus.STOPPING); jobRepository.update(jobExecution); try { Job job = jobRegistry.getJob(jobExecution.getJobInstance().getJobName()); if (job instanceof StepLocator) { for (StepExecution stepExecution : jobExecution.getStepExecutions()) { if (stepExecution.getStatus().isRunning()) { try { Step step = ((StepLocator)job).getStep(stepExecution.getStepName()); if (step instanceof TaskletStep) { Tasklet tasklet = ((TaskletStep)step).getTasklet(); if (tasklet instanceof StoppableTasklet) { ((StoppableTasklet)tasklet).stop(); } } } catch (NoSuchStepException e) { logger.warn("Step not found",e); } } } } } catch (NoSuchJobException e) { logger.warn("Cannot find Job object",e); } return true; }
Source:
public void testMoveCostMultiplier() throws Exception { Configuration conf = HBaseConfiguration.create(); StochasticLoadBalancer.CostFunction costFunction = new StochasticLoadBalancer.MoveCostFunction(conf); BaseLoadBalancer.Cluster cluster = mockCluster(clusterStateMocks[0]); costFunction.init(cluster); costFunction.cost(); assertEquals(7, costFunction.getMultiplier(), 0.01); conf.setInt("hbase.offpeak.start.hour",0); conf.setInt("hbase.offpeak.end.hour",23); costFunction = new StochasticLoadBalancer.MoveCostFunction(conf); costFunction.init(cluster); costFunction.cost(); assertEquals(3, costFunction.getMultiplier(), 0.01); }

Target:
public void testMoveCostMultiplier() throws Exception { Configuration conf = HBaseConfiguration.create(); StochasticLoadBalancer.CostFunction costFunction = new StochasticLoadBalancer.MoveCostFunction(conf); BaseLoadBalancer.Cluster cluster = mockCluster(clusterStateMocks[0]); costFunction.init(cluster); costFunction.cost(); assertEquals(StochasticLoadBalancer.MoveCostFunction.DEFAULT_MOVE_COST, costFunction.getMultiplier(), 0.01); conf.setInt("hbase.offpeak.start.hour",0); conf.setInt("hbase.offpeak.end.hour",23); costFunction = new StochasticLoadBalancer.MoveCostFunction(conf); costFunction.init(cluster); costFunction.cost(); assertEquals(StochasticLoadBalancer.MoveCostFunction.DEFAULT_MOVE_COST_OFFPEAK , costFunction.getMultiplier(), 0.01); }
Source:
public void when_resetIsCalled_expect_poolContentFlushed() { CircularFifoObservationPool sut = CircularFifoObservationPool.builder().build(); sut.add(Nd4j.create(new double[] { 0.0 })); sut.add(Nd4j.create(new double[] { 1.0 })); sut.add(Nd4j.create(new double[] { 2.0 })); sut.add(Nd4j.create(new double[] { 3.0 })); sut.add(Nd4j.create(new double[] { 4.0 })); sut.add(Nd4j.create(new double[] { 5.0 })); sut.add(Nd4j.create(new double[] { 6.0 })); sut.reset(); INDArray[] result = sut.get(); assertEquals(0, result.length); }

Target:
public void when_resetIsCalled_expect_poolContentFlushed() { CircularFifoObservationPool sut = CircularFifoObservationPool.builder().build(); sut.add(Nd4j.createFromArray(0.0)); sut.add(Nd4j.createFromArray(1.0)); sut.add(Nd4j.createFromArray(2.0)); sut.add(Nd4j.createFromArray(3.0)); sut.add(Nd4j.createFromArray(4.0)); sut.add(Nd4j.createFromArray(5.0)); sut.add(Nd4j.createFromArray(6.0)); sut.reset(); INDArray[] result = sut.get(); assertEquals(0, result.length); }