auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testSendSerialDataOtherProtocolsTimeout() throws Exception { PowerMockito.doReturn(XBeeProtocol.ZIGBEE).when(xbeeDevice, "getXBeeProtocol"); PowerMockito.doThrow(new XBeeException(XBeeException.CONNECTION_TIMEOUT)).when(xbeeDevice, "sendXBeePacket", transmitPacket); try { xbeeDevice.sendSerialData(XBEE_16BIT_ADDRESS, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } try { xbeeDevice.sendSerialData(XBEE_16BIT_ADDRESS, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } try { xbeeDevice.sendSerialData(mockedDevice, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } }

Target:
public void testSendSerialDataOtherProtocolsTimeout() throws Exception { PowerMockito.doReturn(XBeeProtocol.ZIGBEE).when(xbeeDevice, "getXBeeProtocol"); PowerMockito.doThrow(new XBeeException(XBeeException.CONNECTION_TIMEOUT)).when(xbeeDevice, "sendXBeePacket", transmitPacket); try { xbeeDevice.sendSerialData(XBEE_16BIT_ADDRESS, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } try { xbeeDevice.sendSerialData(XBEE_64BIT_ADDRESS, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } try { xbeeDevice.sendSerialData(mockedDevice, SEND_DATA_BYTES); fail("TransmitRequest frame shouldn't have been sent successfully."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { assertEquals(XBeeException.CONNECTION_TIMEOUT, e.getErrorCode()); } }
Source:
protected void testAccessControl() throws Exception { ______TS("must be logged in"); verifyInaccessibleWithoutLogin(); ______TS("non-existent course"); InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); CourseAttributes courseAttributes = logic.getCourse(instructor1OfCourse1.getCourseId()); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "not-exist", }; loginAsInstructor(instructor1OfCourse1.getGoogleId()); verifyCannotAccess(submissionParams); ______TS("only instructors of the same course can access"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseAttributes.getId(), }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); }

Target:
protected void testAccessControl() throws Exception { ______TS("non-existent course"); InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); CourseAttributes courseAttributes = logic.getCourse(instructor1OfCourse1.getCourseId()); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "not-exist", }; loginAsInstructor(instructor1OfCourse1.getGoogleId()); verifyCannotAccess(submissionParams); ______TS("Inaccessible without being an instructor or student"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseAttributes.getId(), }; verifyInaccessibleWithoutLogin(submissionParams); verifyInaccessibleForUnregisteredUsers(submissionParams); verifyInaccessibleForAdmin(submissionParams); ______TS("instructors of the same course can access"); verifyInaccessibleForInstructorsOfOtherCourses(submissionParams); verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams); ______TS("students of the same course can access"); verifyAccessibleForStudentsOfTheSameCourse(submissionParams); }
Source:
public void setupGlobalStoreFromDefaultConfig() { SmartStoreLogger.d(TAG, "Setting up global store using config sound in res/raw/globalstore.json"); setupStoreFromConfig(getGlobalSmartStore(), R.raw.globalstore); }

Target:
public void setupGlobalStoreFromDefaultConfig() { SmartStoreLogger.d(TAG, "Setting up global store using config found in res/raw/globalstore.json"); setupStoreFromConfig(getGlobalSmartStore(), R.raw.globalstore); }
Source:
private Element createServerElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { if (!(clusteringServiceConfiguration.getConnectionSource() instanceof ConnectionSource.ServerList)) { throw new IllegalArgumentException("When connection URL is null, source of connection MUST be of type ConnectionSource.ServerList.class"); } ConnectionSource.ServerList servers = (ConnectionSource.ServerList)clusteringServiceConfiguration.getConnectionSource(); if (!servers.getServers().iterator().hasNext()) { throw new IllegalArgumentException("Empty server lists"); } Element rootElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + CLUSTER_ELEMENT_NAME); rootElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + TC_CLUSTERED_NAMESPACE_PREFIX, NAMESPACE.toString()); Element connElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + CLUSTER_CONNECTION_ELEMENT_NAME); connElement.setAttribute(CLUSTER_TIER_MANAGER_ATTRIBUTE_NAME, clusteringServiceConfiguration.getConnectionSource() .getClusterTierManager()); servers.getServers().forEach(server -> { Element serverElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + SERVER_ELEMENT_NAME); serverElement.setAttribute(HOST_ATTRIBUTE_NAME, server.getHostName()); if (server.getPort() < 0) { throw new IllegalArgumentException("Port for server:" + server.getHostName() + " must not be negative"); } if (server.getPort() > 0) { serverElement.setAttribute(PORT_ATTRIBUTE_NAME, Integer.toString(server.getPort())); } connElement.appendChild(serverElement); }); rootElement.appendChild(connElement); return rootElement; }

Target:
private Element createServerElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { if (!(clusteringServiceConfiguration.getConnectionSource() instanceof ConnectionSource.ServerList)) { throw new IllegalArgumentException("When connection URL is null, source of connection MUST be of type ConnectionSource.ServerList.class"); } ConnectionSource.ServerList servers = (ConnectionSource.ServerList)clusteringServiceConfiguration.getConnectionSource(); Element rootElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + CLUSTER_ELEMENT_NAME); rootElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + TC_CLUSTERED_NAMESPACE_PREFIX, NAMESPACE.toString()); Element connElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + CLUSTER_CONNECTION_ELEMENT_NAME); connElement.setAttribute(CLUSTER_TIER_MANAGER_ATTRIBUTE_NAME, clusteringServiceConfiguration.getConnectionSource() .getClusterTierManager()); servers.getServers().forEach(server -> { Element serverElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + SERVER_ELEMENT_NAME); serverElement.setAttribute(HOST_ATTRIBUTE_NAME, server.getHostName()); if (server.getPort() > 0) { serverElement.setAttribute(PORT_ATTRIBUTE_NAME, Integer.toString(server.getPort())); } connElement.appendChild(serverElement); }); rootElement.appendChild(connElement); return rootElement; }
Source:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.KVM && host.getHypervisorType() != HypervisorType.LXC) { s_logger.warn("Don't know how to fence non kvm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); int i = 0; for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.KVM || h.getHypervisorType() == HypervisorType.LXC) { if (h.getStatus() != Status.Up) { continue; } i++; if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (AgentUnavailableException | OperationCancelledException | OperationTimedoutException e) { s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable"); continue; } if (answer != null && answer.getResult()) { return true; } } } _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Unable to fence off host: " + host.getId(), "Fencing off host " + host.getId() + " did not succeed after asking " + i + " hosts. " + "Check Agent logs for more information."); s_logger.error("Unable to fence off " + vm.toString() + " on " + host.toString()); return false; }

Target:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.KVM && host.getHypervisorType() != HypervisorType.LXC) { s_logger.warn("Don't know how to fence non kvm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); int i = 0; for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.KVM || h.getHypervisorType() == HypervisorType.LXC) { if (h.getStatus() != Status.Up) { continue; } i++; if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("cancelling because " + h.toString() + " is unavailable(operation cancelled)"); } break; } catch (AgentUnavailableException | OperationTimedoutException e) { s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable"); continue; } if (answer != null && answer.getResult()) { return true; } } } _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Unable to fence off host: " + host.getId(), "Fencing off host " + host.getId() + " did not succeed after asking " + i + " hosts. " + "Check Agent logs for more information."); s_logger.error("Unable to fence off " + vm.toString() + " on " + host.toString()); return false; }
Source:
private void checkExposureCompensation(Parameters parameters) { assertEquals(parameters.getExposureCompensation(), 0); int max = parameters.getMaxExposureCompensation(); int min = parameters.getMinExposureCompensation(); float step = parameters.getExposureCompensationStep(); if (max == 0 && min == 0) { assertEquals(0, step, 0.000001); return; } assertTrue(step > 0); assertTrue(max >= 0); assertTrue(min <= 0); }

Target:
private void checkExposureCompensation(Parameters parameters) { assertEquals(parameters.getExposureCompensation(), 0); int max = parameters.getMaxExposureCompensation(); int min = parameters.getMinExposureCompensation(); float step = parameters.getExposureCompensationStep(); if (max == 0 && min == 0) { assertEquals(0f, step, 0.000001f); return; } assertTrue(step > 0); assertTrue(max >= 0); assertTrue(min <= 0); }
Source:
public int generateParameters(ExpressionClassBuilder acb, MethodBuilder mb) throws StandardException { boolean isPy = method.getName().equals("DEMO"); int param; String[] expectedTypes = methodParameterTypes; ClassInspector classInspector = getClassFactory().getClassInspector(); for (param = 0; param < methodParms.length; param++) { if(isPy){ mb.dup(); } generateOneParameter( acb, mb, param ); String argumentType = getParameterTypeName( methodParms[param] ); String parameterType = expectedTypes[param]; if (!parameterType.equals(argumentType)) { if (ClassInspector.primitiveType(parameterType)) { mb.cast(parameterType); } else { if (routineInfo != null) { if(isPy){ mb.setArrayElement(param); } continue; } if (SanityManager.DEBUG) { SanityManager.ASSERT(classInspector.assignableTo(argumentType, parameterType), "Argument type " + argumentType + " is not assignable to parameter " + parameterType); } mb.upCast(parameterType); } } if(isPy){ mb.setArrayElement(param); } } return methodParms.length; }

Target:
public int generateParameters(ExpressionClassBuilder acb, MethodBuilder mb) throws StandardException { boolean isPy = method.getName().equals(StaticMethodCallNode.PYPROCEDURE_WRAPPER_METHOD_NAME) && javaClassName.equals(StaticMethodCallNode.PYPROCEDURE_WRAPPER_CLASS_NAME); int param; String[] expectedTypes = methodParameterTypes; ClassInspector classInspector = getClassFactory().getClassInspector(); for (param = 0; param < methodParms.length; param++) { if(isPy){ mb.dup(); } generateOneParameter( acb, mb, param ); String argumentType = getParameterTypeName( methodParms[param] ); String parameterType = expectedTypes[param]; if (!parameterType.equals(argumentType)) { if (ClassInspector.primitiveType(parameterType)) { mb.cast(parameterType); } else { if (routineInfo != null) { if(isPy){ mb.setArrayElement(param); } continue; } if (SanityManager.DEBUG) { SanityManager.ASSERT(classInspector.assignableTo(argumentType, parameterType), "Argument type " + argumentType + " is not assignable to parameter " + parameterType); } mb.upCast(parameterType); } } if(isPy){ mb.setArrayElement(param); } } return methodParms.length; }
Source:
public ConsistentHash readConsistentHash() { switch (topology.getPhase()) { case NO_REBALANCE: return topology.getCurrentCH(); case TRANSITORY: return topology.getPendingCH(); case CONFLICT_RESOLUTION: case READ_OLD_WRITE_ALL: return topology.getCurrentCH(); case READ_ALL_WRITE_ALL: return joinInfo.getConsistentHashFactory().union(topology.getCurrentCH(), topology.getPendingCH()); case READ_NEW_WRITE_ALL: return topology.getPendingCH(); default: throw new IllegalStateException(); } }

Target:
public ConsistentHash readConsistentHash() { return AvailabilityStrategy.readConsistentHash(topology, joinInfo.getConsistentHashFactory()); }
Source:
public Account createAccount(CreateAccountRequest request) { Assert.notNull(request, "Request cannot be null."); final Account account = request.getAccount(); String href = getAccounts().getHref(); boolean first_param = true; if (request.isRegistrationWorkflowOptionSpecified()) { href += "?registrationWorkflowEnabled=" + request.isRegistrationWorkflowEnabled(); first_param = false; } if (request.isPasswordFormatSpecified()) { if (first_param){ href += "?passwordFormat=" + request.getPasswordFormat(); } else { href += "&passwordFormat=" + request.getPasswordFormat(); } } if (request.isAccountOptionsSpecified()) { return getDataStore().create(href, account, request.getAccountOptions()); } return getDataStore().create(href, account); }

Target:
public Account createAccount(CreateAccountRequest request) { Assert.notNull(request, "Request cannot be null."); final Account account = request.getAccount(); String href = getAccounts().getHref(); char querySeparator = '?'; if (request.isRegistrationWorkflowOptionSpecified()) { href += querySeparator + "registrationWorkflowEnabled=" + request.isRegistrationWorkflowEnabled(); querySeparator = '&'; } if (request.isPasswordFormatSpecified()) { href += querySeparator + "passwordFormat=" + request.getPasswordFormat(); } if (request.isAccountOptionsSpecified()) { return getDataStore().create(href, account, request.getAccountOptions()); } return getDataStore().create(href, account); }
Source:
public GeoserverXMLResourceProvider(final String configFileDirectory, final String configFileName, final ResourceStore resourceStore) throws ConfigurationException { this.configFileName = configFileName; if(configFileDirectory!=null) { if (configFileDirectory.startsWith("/") || configFileDirectory.contains(":\\") || configFileDirectory.startsWith("\\\\")) { log.info("Provided configuration directory as absolute path '" + configFileDirectory + "'"); this.configDirectory = Files.asResource(new File(configFileDirectory)); } else { log.info("Provided configuration directory in the resource store. "); this.configDirectory = resourceStore.get(configFileDirectory); } } else { this.configDirectory = resourceStore.get(DEFAULT_CONFIGURATION_DIR_NAME); } log.info("Will look for geowebcache.xml in '" + configDirectory + "'"); }

Target:
public GeoserverXMLResourceProvider(final String configFileDirectory, final String configFileName, final ResourceStore resourceStore) throws ConfigurationException { this.configFileName = configFileName; if(configFileDirectory != null) { if ((new File(configFileDirectory)).isAbsolute()) { log.info("Provided configuration directory as absolute path '" + configFileDirectory + "'"); this.configDirectory = Files.asResource(new File(configFileDirectory)); } else { log.info("Provided configuration directory in the resource store. "); this.configDirectory = resourceStore.get(configFileDirectory); } } else { this.configDirectory = resourceStore.get(DEFAULT_CONFIGURATION_DIR_NAME); } log.info("Will look for geowebcache.xml in '" + configDirectory + "'"); }
Source:
@Override public void onSubscribe(Subscription subscription) { this.s = subscription; try (CurrentTraceContext.Scope inScope = this.tracing.currentTraceContext().maybeScope(this.spanTraceContext)) { this.subscriber.onSubscribe(this); } }

Target:
@Override public void onSubscribe(Subscription subscription) { this.s = subscription; try (CurrentTraceContext.Scope inScope = this.currentTraceContext.maybeScope(this.spanTraceContext)) { this.subscriber.onSubscribe(this); } }
Source:
public final ImportResponse doExecute(TransactionContext context) { context.log().info("Importing components from source file '%s'.", this.attachment.getFileName()); try { InternalAttachmentRegistry iar = (InternalAttachmentRegistry) context.service(AttachmentRegistry.class); File attachment = iar.getAttachment(this.attachment.getAttachmentId()); ImportDefectAcceptor defectsAcceptor = new ImportDefectAcceptor(this.attachment.getFileName()); doValidate(context, attachment, defectsAcceptor, context.service(IProgressMonitor.class)); final List<ImportDefect> defects = defectsAcceptor.getDefects(); if (!CompareUtils.isEmpty(defects)) { return ImportResponse.defects(defects); } else { final Set<ComponentURI> visitedComponents = Sets.newHashSet(); doImport(context, attachment, visitedComponents::add, context.service(IProgressMonitor.class)); return ImportResponse.success(visitedComponents); } } catch (ApiException e) { throw e; } catch (Exception e) { String error = "Unexpected error happened during the import of the source file: " + attachment.getFileName(); context.log().error(error, e); return ImportResponse.error(error); } finally { context.log().info("Finished importing components from source file '%s'.", this.attachment.getFileName()); } }

Target:
public final ImportResponse doExecute(TransactionContext context) { context.log().info("Importing components from source file '{}'.", this.attachment.getFileName()); try { InternalAttachmentRegistry iar = (InternalAttachmentRegistry) context.service(AttachmentRegistry.class); File attachment = iar.getAttachment(this.attachment.getAttachmentId()); ImportDefectAcceptor defectsAcceptor = new ImportDefectAcceptor(this.attachment.getFileName()); doValidate(context, attachment, defectsAcceptor, context.service(IProgressMonitor.class)); final ImportResponse validationResponse = ImportResponse.defects(defectsAcceptor.getDefects()); if (!validationResponse.getErrors().isEmpty()) { return validationResponse; } else { final Set<ComponentURI> visitedComponents = Sets.newHashSet(); doImport(context, attachment, visitedComponents::add, context.service(IProgressMonitor.class)); context.log().info("Finished importing components from source file '{}'.", this.attachment.getFileName()); return ImportResponse.success(visitedComponents, validationResponse.getDefects()); } } catch (ApiException e) { throw e; } catch (OperationLockException e) { throw new LockedException(e.getMessage()); } catch (Exception e) { String error = "Unexpected error happened during the import of the source file: " + attachment.getFileName(); context.log().error(error, e); return ImportResponse.error(error); } }
Source:
public FateMetrics(final ServerContext context, final long minimumRefreshDelay) { super("Fate", "Fate Metrics", "fate"); zooReaderWriter = context.getZooReaderWriter(); fateRootPath = context.getZooKeeperRoot() + Constants.ZFATE; try { zooStore = new ZooStore<>(fateRootPath, zooReaderWriter); } catch (KeeperException ex) { throw new IllegalStateException( "FATE Metrics - Failed to create zoo store - metrics unavailable", ex); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException( "FATE Metrics - Interrupt received while initializing zoo store"); } this.minimumRefreshDelay = Math.max(DEFAULT_MIN_REFRESH_DELAY, minimumRefreshDelay); metricsValuesLock.lock(); try { metricValues = updateFromZookeeper(); } finally { metricsValuesLock.unlock(); } MetricsRegistry registry = super.getRegistry(); currentFateOps = registry.newGauge("currentFateOps", "Current number of FATE Ops", 0L); zkChildFateOpsTotal = registry.newGauge("totalFateOps", "Total FATE Ops", 0L); zkConnectionErrorsTotal = registry.newGauge("totalZkConnErrors", "Total ZK Connection Errors", 0L); for (ReadOnlyTStore.TStatus t : ReadOnlyTStore.TStatus.values()) { MutableGaugeLong g = registry.newGauge(FATE_TX_STATE_METRIC_PREFIX + t.name().toUpperCase(), "Transaction count for " + t.name() + " transactions", 0L); fateTypeCounts.put(t.name(), g); } }

Target:
public FateMetrics(final ServerContext context, final long minimumRefreshDelay) { super("Fate", "Fate Metrics", "fate"); zooReaderWriter = context.getZooReaderWriter(); fateRootPath = context.getZooKeeperRoot() + Constants.ZFATE; try { zooStore = new ZooStore<>(fateRootPath, zooReaderWriter); } catch (KeeperException ex) { throw new IllegalStateException( "FATE Metrics - Failed to create zoo store - metrics unavailable", ex); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException( "FATE Metrics - Interrupt received while initializing zoo store"); } this.minimumRefreshDelay = Math.max(DEFAULT_MIN_REFRESH_DELAY, minimumRefreshDelay); metricValues = updateFromZookeeper(); MetricsRegistry registry = super.getRegistry(); currentFateOps = registry.newGauge("currentFateOps", "Current number of FATE Ops", 0L); zkChildFateOpsTotal = registry.newGauge("totalFateOps", "Total FATE Ops", 0L); zkConnectionErrorsTotal = registry.newGauge("totalZkConnErrors", "Total ZK Connection Errors", 0L); for (ReadOnlyTStore.TStatus t : ReadOnlyTStore.TStatus.values()) { MutableGaugeLong g = registry.newGauge(FATE_TX_STATE_METRIC_PREFIX + t.name().toUpperCase(), "Transaction count for " + t.name() + " transactions", 0L); fateTypeCounts.put(t.name(), g); } }
Source:
public GamesTilesContainerController(UiService uiService, PreferencesService preferencesService) { this.uiService = uiService; this.preferencesService = preferencesService; selectedGame = new SimpleObjectProperty<>(); sortingListener = (observable, oldValue, newValue) -> { if (newValue == null) { return; } preferencesService.getPreferences().setGameTileSortingOrder(newValue); preferencesService.storeInBackground(); appliedComparator = newValue.getComparator(); sortNodes(); }; gameListChangeListener = change -> { JavaFxUtil.assertApplicationThread(); while (change.next()) { change.getRemoved().forEach(gameInfoBean -> { Node card = uidToGameCard.remove(gameInfoBean.getId()); if (card != null) { Tooltip.uninstall(card, tooltip); } boolean remove = tiledFlowPane.getChildren().remove(card); if (!remove) { log.error("Tried to remove game tile that did not exist."); } }); change.getAddedSubList().forEach(GamesTilesContainerController.this::addGameCard); sortNodes(); } }; }

Target:
public GamesTilesContainerController(UiService uiService, PreferencesService preferencesService) { this.uiService = uiService; this.preferencesService = preferencesService; selectedGame = new SimpleObjectProperty<>(); sortingListener = (observable, oldValue, newValue) -> { if (newValue == null) { return; } preferencesService.getPreferences().setGameTileSortingOrder(newValue); preferencesService.storeInBackground(); appliedComparator = newValue.getComparator(); sortNodes(); }; gameListChangeListener = change -> { JavaFxUtil.assertApplicationThread(); while (change.next()) { change.getRemoved().forEach(gameInfoBean -> { Node card = uidToGameCard.remove(gameInfoBean.getId()); if (card != null) { Tooltip.uninstall(card, tooltip); boolean remove = tiledFlowPane.getChildren().remove(card); if (!remove) { log.error("Tried to remove game tile that did not exist in UI."); } } else { log.error("Tried to remove game tile that did not exist."); } }); change.getAddedSubList().forEach(GamesTilesContainerController.this::addGameCard); sortNodes(); } }; }
Source:
static String hostname(String hostname) { if (Strings.isNullOrEmpty(hostname)) { hostname = "localhost"; } else if (hostname.contains(":") && !hostname.startsWith("[")) { hostname = "[" + hostname + "]"; } return hostname; }

Target:
static String hostname(String hostname) { if (Strings.isNullOrEmpty(hostname)) { return "localhost"; } else if (hostname.contains(":") && !hostname.startsWith("[")) { return "[" + hostname + "]"; } return hostname; }
Source:
public void readTuplesAndExecute(Communicator<HeronTuples.HeronTupleSet> inQueue) { TopologyContextImpl topologyContext = helper.getTopologyContext(); Duration instanceExecuteBatchTime = systemConfig.getInstanceExecuteBatchTime(); while (!inQueue.isEmpty()) { HeronTuples.HeronTupleSet tuples = inQueue.poll(); if (tuples.hasControl()) { throw new RuntimeException("Bolt cannot get acks/fails from other components"); } TopologyAPI.StreamId stream = tuples.getData().getStream(); int nValues = topologyContext.getComponentOutputFields( stream.getComponentName(), stream.getId()).size(); long startOfCycle = System.nanoTime(); long currentTime = startOfCycle; for (HeronTuples.HeronDataTuple dataTuple : tuples.getData().getTuplesList()) { List<Object> values = new ArrayList<>(nValues); for (int i = 0; i < nValues; i++) { values.add(serializer.deserialize(dataTuple.getValues(i).toByteArray())); } TupleImpl t = new TupleImpl(topologyContext, stream, dataTuple.getKey(), dataTuple.getRootsList(), values, currentTime, false); bolt.execute(t); long startTime = currentTime; currentTime = System.nanoTime(); long executeLatency = currentTime - startTime; topologyContext.invokeHookBoltExecute(t, Duration.ofNanos(executeLatency)); boltMetrics.executeTuple(stream.getId(), stream.getComponentName(), executeLatency); } if (currentTime - startOfCycle - instanceExecuteBatchTime.toNanos() > 0) { break; } } }

Target:
public void readTuplesAndExecute(Communicator<HeronTuples.HeronTupleSet> inQueue) { TopologyContextImpl topologyContext = helper.getTopologyContext(); Duration instanceExecuteBatchTime = systemConfig.getInstanceExecuteBatchTime(); long startOfCycle = System.nanoTime(); while (!inQueue.isEmpty()) { HeronTuples.HeronTupleSet tuples = inQueue.poll(); if (tuples.hasControl()) { throw new RuntimeException("Bolt cannot get acks/fails from other components"); } TopologyAPI.StreamId stream = tuples.getData().getStream(); int nValues = topologyContext.getComponentOutputFields( stream.getComponentName(), stream.getId()).size(); for (HeronTuples.HeronDataTuple dataTuple : tuples.getData().getTuplesList()) { long startExecuteTuple = System.nanoTime(); List<Object> values = new ArrayList<>(nValues); for (int i = 0; i < nValues; i++) { values.add(serializer.deserialize(dataTuple.getValues(i).toByteArray())); } TupleImpl t = new TupleImpl(topologyContext, stream, dataTuple.getKey(), dataTuple.getRootsList(), values, startExecuteTuple, false); bolt.execute(t); long endExecuteTuple = System.nanoTime(); long executeLatency = endExecuteTuple - startExecuteTuple; topologyContext.invokeHookBoltExecute(t, Duration.ofNanos(executeLatency)); boltMetrics.executeTuple(stream.getId(), stream.getComponentName(), executeLatency); } long currentTime = System.nanoTime(); if (currentTime - startOfCycle - instanceExecuteBatchTime.toNanos() > 0) { break; } } }
Source:
public void delete(ID id) { long count = datastore.entityCount(ServiceProviderEntity.class, Filter.where("_id").is(id.value)); if (count == 0) { throw new NotFoundException("Cant delete Unknown Service Provider."); } datastore.deleteById(ServiceProviderEntity.class, id.value); }

Target:
public void delete(ID id) { datastore.deleteById(ServiceProviderEntity.class, id.value); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IconWithOsDefault)) return false; IconWithOsDefault other = (IconWithOsDefault) obj; return Objects.equals(icon, other.icon) && Objects.equals(osDefaultIcon, other.osDefaultIcon) && Objects.equals(smallIconId, other.smallIconId) && Objects.equals(validationResult, other.validationResult); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IconWithOsDefault)) { return false; } IconWithOsDefault other = (IconWithOsDefault) obj; return Objects.equals(icon, other.icon) && Objects.equals(osDefaultIcon, other.osDefaultIcon) && Objects.equals(smallIconId, other.smallIconId) && Objects.equals(validationResult, other.validationResult); }
Source:
int getItemHeightInPixels () { checkWidget(); int itemCount = GTK.gtk_tree_model_iter_n_children (modelHandle, 0); long column = GTK.gtk_tree_view_get_column (handle, 0); if (itemCount == 0) { int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); int height = h [0]; if (GTK.GTK3) { long textRenderer = getTextRenderer (column); GTK.gtk_cell_renderer_get_preferred_height_for_width (textRenderer, handle, 0, h, null); height += h [0]; } return height; } else { int height = 0; long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); GTK.gtk_tree_model_get_iter_first (modelHandle, iter); GTK.gtk_tree_view_column_cell_set_cell_data (column, modelHandle, iter, false, false); int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); if (GTK.GTK3) { long textRenderer = getTextRenderer (column); int ypad = new int[1]; GTK.gtk_cell_renderer_get_padding(textRenderer, null, ypad); height = h [0] + ypad [0]; } else { height = h [0]; } OS.g_free (iter); return height; } }

Target:
int getItemHeightInPixels () { checkWidget(); int itemCount = GTK.gtk_tree_model_iter_n_children (modelHandle, 0); long column = GTK.gtk_tree_view_get_column (handle, 0); if (itemCount == 0) { int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); int height = h [0]; if (GTK.GTK3) { long textRenderer = getTextRenderer (column); if (textRenderer != 0) GTK.gtk_cell_renderer_get_preferred_height_for_width (textRenderer, handle, 0, h, null); height += h [0]; } return height; } else { int height = 0; long iter = OS.g_malloc (GTK.GtkTreeIter_sizeof ()); GTK.gtk_tree_model_get_iter_first (modelHandle, iter); GTK.gtk_tree_view_column_cell_set_cell_data (column, modelHandle, iter, false, false); int w = new int [1], h = new int [1]; GTK.gtk_tree_view_column_cell_get_size (column, null, null, null, w, h); if (GTK.GTK3) { long textRenderer = getTextRenderer (column); int ypad = new int[1]; if (textRenderer != 0) GTK.gtk_cell_renderer_get_padding(textRenderer, null, ypad); height = h [0] + ypad [0]; } else { height = h [0]; } OS.g_free (iter); return height; } }
Source:
public void adapt(MessageChannel streamListenerResult, MessageChannel boundElement) { BridgeHandler handler = new BridgeHandler(); handler.setOutputChannel(boundElement); ((SubscribableChannel) streamListenerResult).subscribe(handler); }

Target:
public void adapt(MessageChannel streamListenerResult, MessageChannel boundElement) { BridgeHandler handler = new BridgeHandler(); handler.setOutputChannel(boundElement); handler.afterPropertiesSet(); ((SubscribableChannel) streamListenerResult).subscribe(handler); }
Source:
protected void calculateNextCheckpointWindow() { if (PROCESSING_MODE != ProcessingMode.EXACTLY_ONCE) { nextCheckpointWindowCount = (int)Math.ceil((double)(DAG_CHECKPOINT_WINDOW_COUNT - dagCheckpointOffsetCount)/CHECKPOINT_WINDOW_COUNT) * CHECKPOINT_WINDOW_COUNT; } else { nextCheckpointWindowCount = 1; } }

Target:
protected void calculateNextCheckpointWindow() { if (PROCESSING_MODE != ProcessingMode.EXACTLY_ONCE) { nextCheckpointWindowCount = ((DAG_CHECKPOINT_WINDOW_COUNT - dagCheckpointOffsetCount + CHECKPOINT_WINDOW_COUNT - 1)/CHECKPOINT_WINDOW_COUNT) * CHECKPOINT_WINDOW_COUNT; } else { nextCheckpointWindowCount = 1; } }
Source:
private void rejectMalformedAccumulator(String missing) { throw new UserError( "The accumulator annotation " + accumulator + " must " + missing + ". " + "The accumulator type annotation must have exactly one argument, of type String[] with the name " + "\"value\" and an empty default. See the documentation in " + "the manual for creating an accumulation checker."); }

Target:
private void rejectMalformedAccumulator(String missing) { throw new BugInCF("The accumulator annotation " + accumulator + " must " + missing + "."); }
Source:
private Multimap<String, String> newMultimap(Multimap<String, String> map) { Multimap<String, String> multimap = HashMultimap.create(); if (map != null) multimap.putAll(map); return multimap; }

Target:
private Multimap<String, String> newMultimap(Multimap<String, String> map) { return (map != null) ? HashMultimap.create(map) : HashMultimap.create(); }
Source:
private ListenableFuture<GraphAndDataResults> combineFuture(Statement dataStatement, Statement graphStatement) { ListenableFuture<ResultSet> dataResult = session.executeAsync(dataStatement); ListenableFuture<ResultSet> graphResult = session.executeAsync(graphStatement); ListenableFuture<List<ResultSet>> future = Futures.allAsList(graphResult, dataResult); return Futures.transformAsync(future, combinedResults -> { List<Row> graphResults = getGraphResults(combinedResults); List<Row> dataResults = getDataResults(combinedResults); boolean resultsMatch = resultsMatch(graphResults, dataResults); if (resultsMatch || attempt.incrementAndGet() > NUMBER_OF_CASSANDRA_SELECT_RETRIES) { if (!resultsMatch) { log.warn("Exceeded retry count for combined data and graph future"); } return Futures.immediateFuture(new GraphAndDataResults(graphResults, dataResults)); } else { return combineFuture(dataStatement, graphStatement); } }); }

Target:
private ListenableFuture<GraphAndDataResults> combineFuture(Statement dataStatement, Statement graphStatement) { ListenableFuture<ResultSet> dataResult = session.executeAsync(dataStatement); ListenableFuture<ResultSet> graphResult = session.executeAsync(graphStatement); ListenableFuture<List<ResultSet>> future = Futures.allAsList(graphResult, dataResult); return Futures.transformAsync(future, combinedResults -> { List<Row> graphResults = getGraphResults(combinedResults); List<Row> dataResults = getDataResults(combinedResults); boolean resultsMatch = resultsMatch(graphResults, dataResults); int attemptNumber = attempt.incrementAndGet(); if (resultsMatch || attemptNumber > NUMBER_OF_CASSANDRA_SELECT_RETRIES) { if (!resultsMatch) { log.warn("Exceeded retry count for combined data and graph future"); } else { if (attemptNumber > 1) { log.info("Succeeded to fetch combined data and graph future after attempts", attemptNumber); } } return Futures.immediateFuture(new GraphAndDataResults(graphResults, dataResults)); } else { return combineFuture(dataStatement, graphStatement); } }); }
Source:
private BlockRead cacheBlock(String _lookup, BlockCache cache, BlockReader _currBlock, String block) throws IOException { int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; if ((cache == null) || (_currBlock.getRawSize() > Math.min(cache.getMaxSize(), MAX_ARRAY_SIZE))) { return new BlockRead(_currBlock, _currBlock.getRawSize()); } else { byte b[] = null; try { b = new byte[(int) _currBlock.getRawSize()]; _currBlock.readFully(b); } catch (IOException e) { log.debug("Error full blockRead for file " + fileName + " for block " + block, e); throw e; } finally { _currBlock.close(); } CacheEntry ce = null; try { ce = cache.cacheBlock(_lookup, b); } catch (Exception e) { log.warn("Already cached block: " + _lookup, e); } if (ce == null) return new BlockRead(new DataInputStream(new ByteArrayInputStream(b)), b.length); else return new CachedBlockRead(ce, ce.getBuffer()); } }

Target:
private BlockRead cacheBlock(String _lookup, BlockCache cache, BlockReader _currBlock, String block) throws IOException { if ((cache == null) || (_currBlock.getRawSize() > Math.min(cache.getMaxSize(), MAX_ARRAY_SIZE))) { return new BlockRead(_currBlock, _currBlock.getRawSize()); } else { byte b[] = null; try { b = new byte[(int) _currBlock.getRawSize()]; _currBlock.readFully(b); } catch (IOException e) { log.debug("Error full blockRead for file " + fileName + " for block " + block, e); throw e; } finally { _currBlock.close(); } CacheEntry ce = null; try { ce = cache.cacheBlock(_lookup, b); } catch (Exception e) { log.warn("Already cached block: " + _lookup, e); } if (ce == null) return new BlockRead(new DataInputStream(new ByteArrayInputStream(b)), b.length); else return new CachedBlockRead(ce, ce.getBuffer()); } }
Source:
static boolean isValid(String value) { return isBlank(value) || value.matches("[0-9]+"); }

Target:
static boolean isValid(String value) { return isBlank(value) || ALL_DIGITS.matcher(value).matches(); }
Source:
public void processContents(MElementContainer<MUIElement> container) { if (container == null) { return; } Object obj = container; ToolBarManager parentManager = getManager((MToolBar) obj); if (parentManager == null) { return; } List<MUIElement> parts = container.getChildren(); if (parts != null) { MUIElement[] plist = parts.toArray(new MUIElement[parts.size()]); for (int i = 0; i < plist.length; i++) { MUIElement childME = plist[i]; modelProcessSwitch(parentManager, (MToolBarElement) childME); } } parentManager.update(true); ToolBar tb = getToolbarFrom(container.getWidget()); if (tb != null) { tb.pack(true); tb.requestLayout(); } }

Target:
public void processContents(MElementContainer<MUIElement> container) { if (container == null) { return; } Object obj = container; ToolBarManager parentManager = getManager((MToolBar) obj); if (parentManager == null) { return; } List<MUIElement> parts = container.getChildren(); if (parts != null) { MUIElement[] plist = parts.toArray(new MUIElement[parts.size()]); for (int i = 0; i < plist.length; i++) { MUIElement childME = plist[i]; modelProcessSwitch(parentManager, (MToolBarElement) childME); } } parentManager.update(true); ToolBar tb = getToolbarFrom(container.getWidget()); if (tb != null) { tb.requestLayout(); } }
Source:
private boolean batchContainerInitializations() { synchronized (this.batchContainerInitializationsLock) { while (this.batchContainerInitializations == BATCH_INITIALIZATION_IN_PROGRESS) { if (this.batchContainerInitializingThread == Thread.currentThread()) { this.batchContainerInitializationNesting++; return true; } try { this.batchContainerInitializationsLock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } if (this.batchContainerInitializations == NEED_BATCH_INITIALIZATION) { this.batchContainerInitializations = BATCH_INITIALIZATION_IN_PROGRESS; this.batchContainerInitializingThread = Thread.currentThread(); this.batchContainerInitializationNesting++; return true; } return false; } }

Target:
private synchronized boolean batchContainerInitializations() { switch (this.batchContainerInitializations) { case NEED_BATCH_INITIALIZATION: this.batchContainerInitializations = BATCH_INITIALIZATION_IN_PROGRESS; return true; case BATCH_INITIALIZATION_IN_PROGRESS: return true; } return false; }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getHookName() == null || getParameters().getHookName().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NAME_IS_REQUIRED); return false; } if (getParameters().getGlusterCommand() == null || getParameters().getGlusterCommand().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_COMMAND_IS_REQUIRED); return false; } if (getParameters().getLevel() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_LEVEL_IS_REQUIRED); return false; } if (getParameters().getLevel() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_LEVEL_IS_REQUIRED); return false; } List<Guid> upServerIds = getUpServerIds(); if (upServerIds == null || upServerIds.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); return false; } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if ( Guid.isNullOrEmpty(getParameters().getHookId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED); return false; } List<Guid> upServerIds = getUpServerIds(); if (upServerIds == null || upServerIds.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_UP_SERVER_FOUND); return false; } return true; }
Source:
public CompactSketch getResult(final boolean dstOrdered, final WritableMemory dstMem, final boolean reset) { final CompactSketch result = CompactOperations.componentsToCompact( thetaLong_, curCount_, seedHash_, empty_, true, false, dstOrdered, dstMem, hashArr_); if (reset) { reset(); } return result; }

Target:
public CompactSketch getResult(final boolean dstOrdered, final WritableMemory dstMem, final boolean reset) { final CompactSketch result = CompactOperations.componentsToCompact( thetaLong_, curCount_, seedHash_, empty_, true, false, dstOrdered, dstMem, hashArr_.clone()); if (reset) { reset(); } return result; }
Source:
private boolean excludePoint(final String label, int index) { if (inclusionFlag == null || inclusionFlag == InclusionFlag.OFF) { return false; } boolean retVal; switch (inclusionFlag) { case INCLUDE_BY_STRING: retVal = !(strExclusionSet.contains(label) || strExclusionSet .stream() .parallel() .anyMatch(label::matches)); break; case EXCLUDE_BY_STRING: retVal = strExclusionSet.contains(label) || strExclusionSet .stream() .parallel() .anyMatch(label::matches); break; case INCLUDE_BY_COLUMN: retVal = !(colExclusionSet.contains(Integer.valueOf(index))); break; case EXCLUDE_BY_COLUMN: retVal = colExclusionSet.contains(Integer.valueOf(index)); break; default: retVal = false; } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(((retVal) ? "excluded" : "included") + " CSV Column: " + index + " : " + label); } return retVal; }

Target:
private boolean excludePoint(final String label, int index) { if (inclusionFlag == null || inclusionFlag == InclusionFlag.OFF) { return false; } boolean retVal; switch (inclusionFlag) { case INCLUDE_BY_STRING: retVal = !checkExclusionSet(label); break; case EXCLUDE_BY_STRING: retVal = checkExclusionSet(label); break; case INCLUDE_BY_COLUMN: retVal = !(colExclusionSet.contains(Integer.valueOf(index))); break; case EXCLUDE_BY_COLUMN: retVal = colExclusionSet.contains(Integer.valueOf(index)); break; default: retVal = false; } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(((retVal) ? "excluded" : "included") + " CSV Column: " + index + " : " + label); } return retVal; }
Source:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; fileDropDown.setItemEnabled(MESSAGES.trashProjectMenuItem(), true); String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem(numSelectedProjects) : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }

Target:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; fileDropDown.setItemEnabled(MESSAGES.trashProjectMenuItem(), allowDelete); fileDropDown.setItemEnabled(MESSAGES.deleteFromTrashButton(), allowDelete); String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem(numSelectedProjects) : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }
Source:
public InstructorCourseStudentDetailsEditPage submitUnsuccessfully(String studentName, String teamName, String studentEmail, String comments){ if (studentName != null) { fillTextBox(studentNameTextbox, studentName); } if (teamName != null) { fillTextBox(teamNameTextbox, teamName); } if (studentEmail != null) { fillTextBox(studentEmailTextbox, studentEmail); } if (comments != null) { fillTextBox(commentsTextbox, comments); } if(teamName != null){ clickAndConfirm(submitButton); }else{ submitButton.click(); } return this; }

Target:
public InstructorCourseStudentDetailsEditPage submitUnsuccessfully(String studentName, String teamName, String studentEmail, String comments) { fillStudentDetailsForm(studentName, teamName, studentEmail, comments); return this; }
Source:
public void onEventMainThread(QueueEvent event) { Log.d(TAG, "onEvent(" + event + ")"); switch(event.action) { case ADDED: queue.add(event.position, event.item); recyclerAdapter.notifyItemInserted(event.position); break; case SET_QUEUE: queue = event.items; recyclerAdapter.notifyDataSetChanged(); break; case REMOVED: case IRREVERSIBLE_REMOVED: int position = FeedItemUtil.indexOfItemWithId(queue, event.item.getId()); queue.remove(position); recyclerAdapter.notifyItemRemoved(position); break; case CLEARED: queue.clear(); recyclerAdapter.notifyDataSetChanged(); break; case SORTED: queue = event.items; recyclerAdapter.notifyDataSetChanged(); break; case MOVED: break; } onFragmentLoaded(); }

Target:
public void onEventMainThread(QueueEvent event) { Log.d(TAG, "onEvent(" + event + ")"); switch(event.action) { case ADDED: queue.add(event.position, event.item); recyclerAdapter.notifyItemInserted(event.position); break; case SET_QUEUE: queue = event.items; recyclerAdapter.notifyDataSetChanged(); break; case REMOVED: case IRREVERSIBLE_REMOVED: int position = FeedItemUtil.indexOfItemWithId(queue, event.item.getId()); queue.remove(position); recyclerAdapter.notifyItemRemoved(position); break; case CLEARED: queue.clear(); recyclerAdapter.notifyDataSetChanged(); break; case SORTED: queue = event.items; recyclerAdapter.notifyDataSetChanged(); break; case MOVED: return; } saveScrollPosition(); onFragmentLoaded(); }
Source:
public void waitForLeader(long timeout) throws Exception { final LeaderInformation leader = leaderQueue.poll(timeout, TimeUnit.MILLISECONDS); if (leader == null || leader.equals(LeaderInformation.empty())) { throw new TimeoutException("Contender was not elected as the leader within " + timeout + "ms"); } isLeader = true; }

Target:
public void waitForLeader(long timeout) throws Exception { throwExceptionIfNotNull(); final String errorMsg = "Contender was not elected as the leader within " + timeout + "ms"; CommonTestUtils.waitUntilCondition( () -> { final LeaderInformation leader = leaderEventQueue.poll(timeout, TimeUnit.MILLISECONDS); return leader != null && !leader.isEmpty(); }, Deadline.fromNow(Duration.ofMillis(timeout)), errorMsg); isLeader = true; }