auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Iterator<Entry<Key,Value>> iterator() { smi.scanner.setBatchSize(size); smi.scanner.setTimeout(timeOut, TimeUnit.MILLISECONDS); smi.scanner.setBatchTimeout(batchTimeOut, TimeUnit.MILLISECONDS); smi.scanner.setReadaheadThreshold(readaheadThreshold); if (isolated) smi.scanner.enableIsolation(); else smi.scanner.disableIsolation(); smi.samplerConfig = getSamplerConfiguration(); final TreeMap<Integer,IterInfo> tm = new TreeMap<>(); for (IterInfo iterInfo : serverSideIteratorList) { tm.put(iterInfo.getPriority(), iterInfo); } try (SortedKeyValueIterator<Key,Value> skvi = IteratorUtil.loadIterators(smi, tm.values(), serverSideIteratorOptions, new ClientSideIteratorEnvironment( getSamplerConfiguration() != null, getIteratorSamplerConfigurationInternal()), false, null)) { final Set<ByteSequence> colfs = new TreeSet<>(); for (Column c : this.getFetchedColumns()) { colfs.add(new ArrayByteSequence(c.getColumnFamily())); } skvi.seek(range, colfs, true); return new IteratorAdapter(skvi); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public Iterator<Entry<Key,Value>> iterator() { smi.scanner.setBatchSize(size); smi.scanner.setTimeout(timeOut, TimeUnit.MILLISECONDS); smi.scanner.setBatchTimeout(batchTimeOut, TimeUnit.MILLISECONDS); smi.scanner.setReadaheadThreshold(readaheadThreshold); if (isolated) smi.scanner.enableIsolation(); else smi.scanner.disableIsolation(); smi.samplerConfig = getSamplerConfiguration(); final TreeMap<Integer,IterInfo> tm = new TreeMap<>(); for (IterInfo iterInfo : serverSideIteratorList) { tm.put(iterInfo.getPriority(), iterInfo); } SortedKeyValueIterator<Key,Value> skvi; try { skvi = IteratorUtil.loadIterators(smi, tm.values(), serverSideIteratorOptions, new ClientSideIteratorEnvironment(getSamplerConfiguration() != null, getIteratorSamplerConfigurationInternal()), false, null); } catch (IOException e) { throw new RuntimeException(e); } final Set<ByteSequence> colfs = new TreeSet<>(); for (Column c : this.getFetchedColumns()) { colfs.add(new ArrayByteSequence(c.getColumnFamily())); } try { skvi.seek(range, colfs, true); } catch (IOException e) { throw new RuntimeException(e); } return new IteratorAdapter(skvi); }
Source:
public void setRowData(int start, final List<? extends T> values) { if (values.size() == 1) { addStyleName(HIDE_ONE_ROW_SCROLL); } else { removeStyleName(HIDE_ONE_ROW_SCROLL); } super.setRowData(start, values); updateGridSize(calculateGridHeightOnlyRows(values.size())); }

Target:
public void setRowData(int start, final List<? extends T> values) { if (values.size() == 1) { addStyleName(HIDE_ONE_ROW_SCROLL); } else { removeStyleName(HIDE_ONE_ROW_SCROLL); } super.setRowData(start, values); updateGridSize(calculateGridHeight(values.size())); }
Source:
private static List<VdcOption> getAllReloadableVdcOptions() { List<VdcOption> list = getVdcOptionDAO().getAll(); List<VdcOption> result = new ArrayList<>(); for (VdcOption option : list) { try { if (isReloadable(option.getoption_name())) { result.add(option); } } catch (NoSuchFieldException e) { log.error("Not refreshing field '{}': does not exist in class {}.", option.getoption_name(), ConfigValues.class.getSimpleName()); } } return result; }

Target:
private static List<VdcOption> getAllReloadableVdcOptions() { List<VdcOption> list = getVdcOptionDAO().getAll(); List<VdcOption> result = new ArrayList<>(); for (VdcOption option : list) { if (isReloadable(option.getoption_name())) { result.add(option); } } return result; }
Source:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; for (int start = 0, end = size() - 1; start < end; start++, end--) { int tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }

Target:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; int tmp; for (int start = 0, end = size() - 1; start < end; start++, end--) { tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }
Source:
protected void releaseInstance(T instance) throws IOException { if(providedVsCount.containsKey(instance)) { AtomicInteger currentCount = providedVsCount.get(instance); if(currentCount.getAndDecrement() == 1) { providedVsCount.remove(instance); } } else { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instance instanceof Closeable) { ((Closeable)instance).close(); } }

Target:
protected void releaseInstance(T instance) throws IOException { AtomicInteger currentCount = providedVsCount.get(instance); if(currentCount != null) { if(currentCount.decrementAndGet() < 0) { currentCount.incrementAndGet(); throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } } else { throw new IllegalArgumentException("Given instance of " + instance.getClass().getName() + " is not managed by this provider"); } if(instance instanceof Closeable) { ((Closeable)instance).close(); } }
Source:
public boolean testNull() { if (failNext > 0) { filterIdx++; failNext--; return false; } Filter filter = nextFilter(); if (filter != null) { return processResult(filter.testNull()); } return true; }

Target:
public boolean testNull() { if (numNextPositionsToFail > 0) { filterIndex++; numNextPositionsToFail--; return false; } Filter filter = nextFilter(); if (filter != null) { return processResult(filter.testNull()); } return true; }
Source:
private boolean tryUnspillNext() { verify(probe == null); if (!partitionedConsumption.isDone()) { return false; } if (lookupPartitions == null) { lookupPartitions = getDone(partitionedConsumption).beginConsumption(); } if (unspilledInputPages.hasNext()) { addInput(unspilledInputPages.next()); verify(probe != null); return true; } else if (unspilledLookupSource.isPresent()) { if (!unspilledLookupSource.get().isDone()) { return false; } LookupSource lookupSource = getDone(unspilledLookupSource.get()).get(); unspilledLookupSource = Optional.empty(); lookupSourceProvider.close(); lookupSourceProvider = new SimpleLookupSourceProvider(lookupSource); int partition = currentPartition.get().number(); unspilledInputPages = spiller.map(spiller -> spiller.getSpilledPages(partition)) .orElse(emptyIterator()); Optional.ofNullable(savedRows.remove(partition)).ifPresent(savedRow -> { restoreProbe( savedRow.row, savedRow.joinPositionWithinPartition, savedRow.currentProbePositionProducedRow, savedRow.joinSourcePositions, SpillInfoSnapshot.noSpill()); }); return false; } else if (lookupPartitions.hasNext()) { currentPartition.ifPresent(Partition::release); currentPartition = Optional.of(lookupPartitions.next()); unspilledLookupSource = Optional.of(currentPartition.get().load()); return false; } else { currentPartition.ifPresent(Partition::release); if (lookupSourceProvider != null) { lookupSourceProvider.close(); lookupSourceProvider = null; } spiller.ifPresent(PartitioningSpiller::verifyAllPartitionsRead); finished = true; return true; } }

Target:
private void tryUnspillNext() { verify(probe == null); if (!partitionedConsumption.isDone()) { return; } if (lookupPartitions == null) { lookupPartitions = getDone(partitionedConsumption).beginConsumption(); } if (unspilledInputPages.hasNext()) { addInput(unspilledInputPages.next()); return; } if (unspilledLookupSource.isPresent()) { if (!unspilledLookupSource.get().isDone()) { return; } LookupSource lookupSource = getDone(unspilledLookupSource.get()).get(); unspilledLookupSource = Optional.empty(); lookupSourceProvider.close(); lookupSourceProvider = new StaticLookupSourceProvider(lookupSource); statisticsCounter.updateLookupSourcePositions(lookupSource.getJoinPositionCount()); int partition = currentPartition.get().number(); unspilledInputPages = spiller.map(spiller -> spiller.getSpilledPages(partition)) .orElse(emptyIterator()); Optional.ofNullable(savedRows.remove(partition)).ifPresent(savedRow -> { restoreProbe( savedRow.row, savedRow.joinPositionWithinPartition, savedRow.currentProbePositionProducedRow, savedRow.joinSourcePositions, SpillInfoSnapshot.noSpill()); }); return; } if (lookupPartitions.hasNext()) { currentPartition.ifPresent(Partition::release); currentPartition = Optional.of(lookupPartitions.next()); unspilledLookupSource = Optional.of(currentPartition.get().load()); return; } currentPartition.ifPresent(Partition::release); if (lookupSourceProvider != null) { lookupSourceProvider.close(); lookupSourceProvider = null; } spiller.ifPresent(PartitioningSpiller::verifyAllPartitionsRead); finished = true; }
Source:
public TmfEventTableColumn(ITmfEventAspect<?> aspect) { fAspect = aspect; fAspectDuplicate.add(aspect); }

Target:
public TmfEventTableColumn(ITmfEventAspect<?> aspect) { fAspects.add(aspect); }
Source:
private void copyContents() { try { File baseDir = new File(buildName, serverName); FileUtils.deleteRecursive(baseDir); final Path path = Paths.get(baseDir.getAbsolutePath()); final Path baseFile = project.getBasedir().toPath().resolve(configDir.getPath()); doCopy(path.resolve(Locations.CONTENT), baseFile.resolve(Locations.CONTENT)); doCopy(path.resolve(Locations.MODULES), baseFile.resolve(Locations.MODULES)); doCopy(path.resolve(Locations.CONFIGURATION), baseFile.resolve(Locations.CONFIGURATION)); doCopy(path.resolve(Locations.SUBSYSTEM_TEMPLATES), baseFile.resolve(Locations.SUBSYSTEM_TEMPLATES)); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private void copyContents() { try { File baseDir = new File(buildName, serverName); FileUtils.deleteRecursive(baseDir); final Path path = Paths.get(baseDir.getAbsolutePath()); final Path baseFile = Paths.get(configDir.getAbsolutePath() + resourcesDir); doCopy(path.resolve(Locations.CONTENT), baseFile.resolve(Locations.CONTENT)); doCopy(path.resolve(Locations.MODULES), baseFile.resolve(Locations.MODULES)); doCopy(path.resolve(Locations.CONFIGURATION), baseFile.resolve(Locations.CONFIGURATION)); doCopy(path.resolve(Locations.SUBSYSTEM_TEMPLATES), baseFile.resolve(Locations.SUBSYSTEM_TEMPLATES)); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void testListActivePlatformTypes() throws Exception { Set<PlatformType> platformTypes = dao.listActivePlatformTypes(); assertEquals(1, platformTypes.size()); assertTrue(platformTypes.contains(PlatformType.ILLUMINA)); }

Target:
public void testListActivePlatformTypes() throws Exception { Set<PlatformType> platformTypes = dao.listActivePlatformTypes(); assertEquals(1, platformTypes.size()); assertFalse(platformTypes.contains(PlatformType.SOLID)); assertTrue(platformTypes.contains(PlatformType.ILLUMINA)); }
Source:
public PhysicalOperation visitTableFinish(TableFinishNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); ImmutableMap.Builder<Symbol, Integer> outputMapping = ImmutableMap.builder(); OperatorFactory statisticsAggregation = node.getStatisticsAggregation().map(aggregation -> { List<Symbol> groupingKeys = aggregation.getGroupingSets() .stream() .flatMap(List::stream) .collect(toImmutableList()); if (groupingKeys.isEmpty()) { return createAggregationOperatorFactory( node.getId(), aggregation.getAggregations(), FINAL, 0, outputMapping, source, context); } else { return createHashAggregationOperatorFactory( node.getId(), aggregation.getAggregations(), aggregation.getGroupingSets(), groupingKeys, FINAL, Optional.empty(), Optional.empty(), source, false, false, new DataSize(0, BYTE), context, 0, outputMapping); } }).orElse(new NoOpOperatorFactory(context.getNextOperatorId(), node.getId())); Map<Symbol, Integer> aggregationOutput = outputMapping.build(); StatisticAggregationsDescriptor<Integer> descriptor = node.getStatisticsAggregationDescriptor() .map(desc -> desc.map(aggregationOutput::get)) .orElse(StatisticAggregationsDescriptor.<Integer>builder().build()); OperatorFactory operatorFactory = new TableFinishOperatorFactory( context.getNextOperatorId(), node.getId(), createTableFinisher(session, node, metadata), statisticsAggregation, descriptor); Map<Symbol, Integer> layout = ImmutableMap.of(node.getOutputSymbols().get(0), 0); return new PhysicalOperation(operatorFactory, layout, context, source); }

Target:
public PhysicalOperation visitTableFinish(TableFinishNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); ImmutableMap.Builder<Symbol, Integer> outputMapping = ImmutableMap.builder(); OperatorFactory statisticsAggregation = node.getStatisticsAggregation().map(aggregation -> { List<Symbol> groupingSymbols = aggregation.getGroupingSymbols(); if (groupingSymbols.isEmpty()) { return createAggregationOperatorFactory( node.getId(), aggregation.getAggregations(), FINAL, 0, outputMapping, source, context); } else { return createHashAggregationOperatorFactory( node.getId(), aggregation.getAggregations(), ImmutableList.of(groupingSymbols), groupingSymbols, FINAL, Optional.empty(), Optional.empty(), source, false, false, false, new DataSize(0, BYTE), context, 0, outputMapping); } }).orElse(new NoOpOperatorFactory(context.getNextOperatorId(), node.getId())); Map<Symbol, Integer> aggregationOutput = outputMapping.build(); StatisticAggregationsDescriptor<Integer> descriptor = node.getStatisticsAggregationDescriptor() .map(desc -> desc.map(aggregationOutput::get)) .orElse(StatisticAggregationsDescriptor.<Integer>builder().build()); OperatorFactory operatorFactory = new TableFinishOperatorFactory( context.getNextOperatorId(), node.getId(), createTableFinisher(session, node, metadata), statisticsAggregation, descriptor); Map<Symbol, Integer> layout = ImmutableMap.of(node.getOutputSymbols().get(0), 0); return new PhysicalOperation(operatorFactory, layout, context, source); }
Source:
private List<CloudResource> createCloudResources(String fqdn) { List<CloudResource> databaseResources = Lists.newArrayList(); databaseResources.add(CloudResource.builder() .type(ResourceType.RDS_HOSTNAME) .name(fqdn) .build()); databaseResources.add(CloudResource.builder() .type(ResourceType.RDS_PORT) .name(Integer.toString(POSTGRESQL_SERVER_PORT)) .build()); return databaseResources; }

Target:
private List<CloudResource> createCloudResources(String fqdn) { List<CloudResource> databaseResources = Lists.newArrayList(); databaseResources.add(createCloudResource(RDS_HOSTNAME, fqdn)); databaseResources.add(createCloudResource(ResourceType.RDS_PORT, Integer.toString(POSTGRESQL_SERVER_PORT))); return databaseResources; }
Source:
public void start() { LOG.info("Starting Azure job coordinator."); systemAdmins = new SystemAdmins(config); streamMetadataCache = new StreamMetadataCache(systemAdmins, METADATA_CACHE_TTL_MS, SystemClock.instance()); systemAdmins.start(); table.addProcessorEntity(INITIAL_STATE, processorId, false); LOG.info("Starting scheduler for heartbeating."); heartbeat.scheduleTask(); azureLeaderElector.tryBecomeLeader(); LOG.info("Starting scheduler to check for job model version upgrades."); versionUpgrade.setStateChangeListener(createJMVersionUpgradeListener()); versionUpgrade.scheduleTask(); LOG.info("Starting scheduler to check for leader liveness."); leaderAlive.setStateChangeListener(createLeaderLivenessListener()); leaderAlive.scheduleTask(); }

Target:
public void start() { LOG.info("Starting Azure job coordinator."); systemAdmins = new SystemAdmins(config); systemAdmins.start(); streamMetadataCache = new StreamMetadataCache(systemAdmins, METADATA_CACHE_TTL_MS, SystemClock.instance()); table.addProcessorEntity(INITIAL_STATE, processorId, false); LOG.info("Starting scheduler for heartbeating."); heartbeat.scheduleTask(); azureLeaderElector.tryBecomeLeader(); LOG.info("Starting scheduler to check for job model version upgrades."); versionUpgrade.setStateChangeListener(createJMVersionUpgradeListener()); versionUpgrade.scheduleTask(); LOG.info("Starting scheduler to check for leader liveness."); leaderAlive.setStateChangeListener(createLeaderLivenessListener()); leaderAlive.scheduleTask(); }
Source:
public void checkTimeoutOnPendingOperations() { int timedOutOperations = completionObjects.removeIf(timeoutCheck); synchronized (this) { Iterator<CompletionValue> iterator = completionObjectsV2Conflicts.values().iterator(); while (iterator.hasNext()) { CompletionValue value = iterator.next(); if (value.maybeTimeout()) { ++timedOutOperations; iterator.remove(); } } } if (timedOutOperations > 0) { LOG.info("Timed-out operations to channel for {}", new Object[] { timedOutOperations, channel, addr }); } }

Target:
public void checkTimeoutOnPendingOperations() { int timedOutOperations = completionObjects.removeIf(timeoutCheck); synchronized (this) { Iterator<CompletionValue> iterator = completionObjectsV2Conflicts.values().iterator(); while (iterator.hasNext()) { CompletionValue value = iterator.next(); if (value.maybeTimeout()) { ++timedOutOperations; iterator.remove(); } } } if (timedOutOperations > 0) { LOG.info("Timed-out operations to channel for {}", timedOutOperations, channel, addr); } }
Source:
public JsonObject getStats() { return new JsonObject() .add("default_topic", defaultTopic) .add("seen_messages", seenMessages.get()) .add("propagated_messages", propagatedMessages.get()) .add("failed_to_send", failedToSendMessageExceptions.get()) .add("failed_send", meterToJsonObject(producerStats.failedSendRate())) .add("resend", meterToJsonObject(producerStats.resendRate())) .add("serialization_error", meterToJsonObject(producerStats.serializationErrorRate())) .add("message", meterToJsonObject(producerAllTopicsStats.messageRate())) .add("dropped_message", meterToJsonObject(producerAllTopicsStats.droppedMessageRate())) .add("byte", meterToJsonObject(producerAllTopicsStats.byteRate())); }

Target:
public JsonObject getStats() { return new JsonObject() .add("default_topic", defaultTopic) .add("seen_messages", seenMessages.get()) .add("failed_to_send", failedToSendMessageExceptions.get()) .add("failed_send", meterToJsonObject(producerStats.failedSendRate())) .add("resend", meterToJsonObject(producerStats.resendRate())) .add("serialization_error", meterToJsonObject(producerStats.serializationErrorRate())) .add("message", meterToJsonObject(producerAllTopicsStats.messageRate())) .add("dropped_message", meterToJsonObject(producerAllTopicsStats.droppedMessageRate())) .add("byte", meterToJsonObject(producerAllTopicsStats.byteRate())); }
Source:
public HaplotypeProbabilitiesFromContaminatorSequence(HaplotypeProbabilitiesFromContaminatorSequence other){ this(other.getHaplotype(),other.contamination); for (final Genotype g : Genotype.values()) { System.arraycopy(other.likelihoodMap[g.v], 0, likelihoodMap[g.v], 0, nGeno); } }

Target:
public HaplotypeProbabilitiesFromContaminatorSequence(HaplotypeProbabilitiesFromContaminatorSequence other) { super(other); contamination = other.contamination; for (final Genotype g : Genotype.values()) { System.arraycopy(other.likelihoodMap[g.v], 0, likelihoodMap[g.v], 0, NUM_GENOTYPES); } }
Source:
public void checkHasCorrectResponseStatus(Endpoint endpoint) { try { mockMvc.perform(endpoint.toRequestBuilder()).andExpect(STATUS_NOT_401_OR_403); } catch (Exception e) { throw new AssertionError("Exception when calling endpoint: " + endpoint, e); } catch (AssertionError e) { throw e; } }

Target:
public void checkHasCorrectResponseStatus(Endpoint endpoint) { try { mockMvc.perform(endpoint.toRequestBuilder()).andExpect(STATUS_NOT_401_OR_403); } catch (Exception e) { throw new AssertionError("Exception when calling endpoint: " + endpoint, e); } catch (AssertionError e) { throw new AssertionError("Assertion error when calling endpoint: " + endpoint, e); } }
Source:
ArrayList<Pojo> getFavorites(Context context, int limit) { ArrayList<Pojo> favorites = new ArrayList<>(); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); List<String> favAppsList = Arrays.asList(favApps.split(";")); for (int i = 0; i < favAppsList.size(); i++) { Pojo pojo = getPojo(favAppsList.get(i)); if (pojo != null) { favorites.add(pojo); } } return favorites; }

Target:
ArrayList<Pojo> getFavorites(Context context, int limit) { ArrayList<Pojo> favorites = new ArrayList<>(limit); String favApps = PreferenceManager.getDefaultSharedPreferences(context). getString("favorite-apps-list", ""); List<String> favAppsList = Arrays.asList(favApps.split(";")); for (int i = 0; i < favAppsList.size(); i++) { Pojo pojo = getPojo(favAppsList.get(i)); if (pojo != null) { favorites.add(pojo); } if (favorites.size()>=limit) { break; } } return favorites; }
Source:
public View create(boolean shortSummary, RecordAdapter.HeaderViewHolder mainViewHolder) { view = layoutInflater.inflate(R.layout.view_summary_records, null); view.findViewById(R.id.iv_more).setVisibility(shortSummary ? View.VISIBLE : View.INVISIBLE); if (mainViewHolder == null) view.setTag(new ViewHolder(view)); else view.setTag(mainViewHolder); return view; }

Target:
public View create(boolean shortSummary, RecordAdapter.HeaderViewHolder mainViewHolder) { view = layoutInflater.inflate(R.layout.view_summary_records, null); view.findViewById(R.id.iv_more).setVisibility(shortSummary ? View.VISIBLE : View.INVISIBLE); view.setTag(mainViewHolder != null ? mainViewHolder : new ViewHolder(view)); return view; }
Source:
public void compact() { if (getRetainedSizeInBytes() <= getSizeInBytes()) { return; } for (int i = 0; i < blocks.length; i++) { Block block = blocks[i]; if (block instanceof DictionaryBlock) { continue; } Block compactedBlock = block.copyRegion(0, block.getPositionCount()); blocks[i] = compactedBlock; } Map<DictionaryId, DictionaryBlockIndexes> dictionaryBlocks = getRelatedDictionaryBlocks(); for (DictionaryBlockIndexes blockIndexes : dictionaryBlocks.values()) { List<DictionaryBlock> compactBlocks = compactRelatedBlocks(blockIndexes.getBlocks()); List<Integer> indexes = blockIndexes.getIndexes(); for (int i = 0; i < compactBlocks.size(); i++) { blocks[indexes.get(i)] = compactBlocks.get(i); } } long retainedSize = 0; for (Block block : blocks) { retainedSize += block.getRetainedSizeInBytes(); } retainedSizeInBytes.set(retainedSize); }

Target:
public void compact() { if (getRetainedSizeInBytes() <= getSizeInBytes()) { return; } for (int i = 0; i < blocks.length; i++) { Block block = blocks[i]; if (block instanceof DictionaryBlock) { continue; } blocks[i] = block.copyRegion(0, block.getPositionCount()); } Map<DictionaryId, DictionaryBlockIndexes> dictionaryBlocks = getRelatedDictionaryBlocks(); for (DictionaryBlockIndexes blockIndexes : dictionaryBlocks.values()) { List<DictionaryBlock> compactBlocks = compactRelatedBlocks(blockIndexes.getBlocks()); List<Integer> indexes = blockIndexes.getIndexes(); for (int i = 0; i < compactBlocks.size(); i++) { blocks[indexes.get(i)] = compactBlocks.get(i); } } long retainedSize = 0; for (Block block : blocks) { retainedSize += block.getRetainedSizeInBytes(); } retainedSizeInBytes.set(retainedSize); }
Source:
public static AuthenticationScheme getAuthenticationScheme() { AuthenticationScheme scheme = new UsernamePasswordAuthenticationScheme(); try { scheme = Context.getServiceContext().getApplicationContext().getBean(AuthenticationScheme.class); log.info("An authentication scheme override was provided. Using this one in place of the OpenMRS default authentication scheme."); } catch(NoUniqueBeanDefinitionException e) { log.error("Multiple authentication schemes overrides are being provided, this is currently not supported. Sticking to OpenMRS default authentication scheme."); } catch(NoSuchBeanDefinitionException e) { log.debug("No authentication scheme override was provided. Sticking to OpenMRS default authentication scheme."); } catch(BeansException e){ log.error("Fatal error encountered when injecting the authentication scheme override. Sticking to OpenMRS default authentication scheme."); } if (scheme instanceof DaoAuthenticationScheme) { ((DaoAuthenticationScheme) scheme).setContextDao(getContextDAO()); } return scheme; }

Target:
public static AuthenticationScheme getAuthenticationScheme() { return authenticationScheme; }
Source:
public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand command) { if (trace) log.tracef("About to send to backups %s, command %s", backups, command); boolean rsvp = isRsvpCommand(command); Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls = new HashMap<>(backups.size()); for (XSiteBackup xsb : backups) { Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(xsb.getSiteName())); long requestId = requests.newRequestId(); logRequest(requestId, command, recipient); SingleSiteRequest<ValidResponse> request = new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, xsb.getSiteName()); addRequest(request); backupCalls.put(xsb, request); DeliverOrder order = xsb.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER; long timeout = xsb.getTimeout(); try { Message message = new Message(toJGroupsAddress(recipient)); marshallRequest(message, command, request.getRequestId()); setMessageFlags(message, order, rsvp, false); remoteExecutor.submit(() -> { try { send(message); } catch (Throwable t) { request.completeExceptionally(t); } }); if (timeout > 0) { request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS); } } catch (Throwable t) { request.completeExceptionally(t); } } return new JGroupsBackupResponse(backupCalls, timeService); }

Target:
public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand command) { if (trace) log.tracef("About to send to backups %s, command %s", backups, command); boolean rsvp = isRsvpCommand(command); Map<XSiteBackup, CompletableFuture<ValidResponse>> backupCalls = new HashMap<>(backups.size()); for (XSiteBackup xsb : backups) { Address recipient = JGroupsAddressCache.fromJGroupsAddress(new SiteMaster(xsb.getSiteName())); long requestId = requests.newRequestId(); logRequest(requestId, command, recipient); SingleSiteRequest<ValidResponse> request = new SingleSiteRequest<>(SingleResponseCollector.validOnly(), requestId, requests, xsb.getSiteName()); addRequest(request); backupCalls.put(xsb, request); DeliverOrder order = xsb.isSync() ? DeliverOrder.NONE : DeliverOrder.PER_SENDER; long timeout = xsb.getTimeout(); try { Message message = new Message(toJGroupsAddress(recipient)); marshallRequest(message, command, request.getRequestId()); setMessageFlags(message, order, rsvp, false); Callable<CompletionStage<Void>> sendAction = () -> { try { send(message); } catch (Throwable t) { request.completeExceptionally(t); } return CompletableFutures.completedNull(); }; if (order.preserveOrder()) { backupSequencer.orderOnKey(xsb.getSiteName(), sendAction); } else { remoteExecutor.submit(sendAction); } if (timeout > 0) { request.setTimeout(timeoutExecutor, timeout, TimeUnit.MILLISECONDS); } } catch (Throwable t) { request.completeExceptionally(t); } } return new JGroupsBackupResponse(backupCalls, timeService); }
Source:
private void checkPlayerAlive() { if (!game.getCurrentLevel().getPlayer().isAlive()) { Logger.log("--------------------PLAYER RESTARTED THE GAME--------------------"); game.restart(); renderStatic(); } }

Target:
private void checkPlayerAlive() { if (!game.getCurrentLevel().getPlayer().isAlive()) { Logger.log("--------------------PLAYER RESTARTED THE GAME"); game.restart(); renderStatic(); } }
Source:
public void testJavaSizeString() { assertEquals(ByteSizeStrings.java().makeSizeString(0), "0"); assertEquals(ByteSizeStrings.java().makeSizeString(999), "999"); assertEquals(ByteSizeStrings.java().makeSizeString(1234), "1234"); assertEquals(ByteSizeStrings.java().makeSizeString(2345), "2345"); assertEquals(ByteSizeStrings.java().makeSizeString(4567), "4k"); assertEquals(ByteSizeStrings.java().makeSizeString(65535), "64k"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789), "22m"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789012L), "22g"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789012345L), "21846g"); }

Target:
public void testJavaSizeString() { assertEquals(ByteSizeStrings.java().makeSizeString(-1), "-1"); assertEquals(ByteSizeStrings.java().makeSizeString(0), "0"); assertEquals(ByteSizeStrings.java().makeSizeString(999), "999"); assertEquals(ByteSizeStrings.java().makeSizeString(1024), "1024"); assertEquals(ByteSizeStrings.java().makeSizeString(1234), "1234"); assertEquals(ByteSizeStrings.java().makeSizeString(2345), "2345"); assertEquals(ByteSizeStrings.java().makeSizeString(4096), "4096"); assertEquals(ByteSizeStrings.java().makeSizeString(4567), "4567"); assertEquals(ByteSizeStrings.java().makeSizeString(6789), "6789"); assertEquals(ByteSizeStrings.java().makeSizeString(65535), "64k"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789L), "22m"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789012L), "22g"); assertEquals(ByteSizeStrings.java().makeSizeString(23456789012345L), "21000g"); assertEquals(ByteSizeStrings.java().makeSizeString(Long.MAX_VALUE), "8388608000g"); }
Source:
public void beforeMethod() { HelixDataAccessor dataAccessor = _manager.getHelixDataAccessor(); PropertyKey propertyKey = dataAccessor.keyBuilder() .customizedStates(_participants[0].getInstanceName(), CUSTOMIZE_STATE_NAME); dataAccessor.removeProperty(propertyKey); CustomizedState customizedStates = dataAccessor.getProperty(propertyKey); Assert.assertNull(customizedStates); }

Target:
public void beforeMethod() { _dataAccessor.removeProperty(_propertyKey); CustomizedState customizedStates = _dataAccessor.getProperty(_propertyKey); Assert.assertNull(customizedStates); }
Source:
protected final void verifyDataProviderType(Class<?> dataProviderType) { Class<?> supportedDataProviderType = getSupportedDataProviderType(); if (!supportedDataProviderType.isAssignableFrom(dataProviderType)) { final String message = String.format( "%s only supports '%s' or it's subclasses, but was given a '%s'." + "%nUse either 'getLazyDataView()', 'getListDataView()'" + " or getDataView() according to the used data type.", this.getClass().getSimpleName(), supportedDataProviderType.getSimpleName(), dataProviderType.getSuperclass().getSimpleName()); throw new IllegalStateException(message); } }

Target:
protected final void verifyDataProviderType(Class<?> dataProviderType) { Class<?> supportedDataProviderType = getSupportedDataProviderType(); if (!supportedDataProviderType.isAssignableFrom(dataProviderType)) { final String message = String.format( "%s only supports '%s' or it's subclasses, but was given a '%s'." + "%nUse either 'getLazyDataView()', 'getListDataView()'" + " or 'getDataView()' according to the used data type.", this.getClass().getSimpleName(), supportedDataProviderType.getSimpleName(), dataProviderType.getSuperclass().getSimpleName()); throw new IllegalStateException(message); } }
Source:
public void initialize(IManagedForm form) { super.initialize(form); fwkContentProvider.onContentReady(new Success<List<OSGiFramework>,Void>() { @Override public Promise<Void> call(Promise<List<OSGiFramework>> resolved) throws Exception { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { refreshFromModel(); } }); return Promises.resolved(null); } }); frameworkViewer.setInput(model.getWorkspace()); }

Target:
public void initialize(IManagedForm form) { super.initialize(form); fwkContentProvider.onContentReady(new Success<List<OSGiFramework>,Void>() { @Override public Promise<Void> call(Promise<List<OSGiFramework>> resolved) throws Exception { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { refreshFromModel(); } }); return null; } }); frameworkViewer.setInput(model.getWorkspace()); }
Source:
public void testNoTimestampInMessage() { RadixTreeParser oldRadixParser = RadixTreeSyslogParser.getRadixParser(); RadixTreeParser radixParser = new RadixTreeParser(); radixParser.teach(GrokParserStageSequenceBuilder.parseGrok("%{STRING:message}").toArray(new ParserStage[0])); RadixTreeSyslogParser.setRadixParser(radixParser); String syslogMessage = "%CDP-4-NATIVE_VLAN_MISMATCH: Native VLAN mismatch discovered on GigabitEthernet5/9 " + "(75), with switch.fqdn.com GigabitEthernet2/4/21 (2)"; Date now = new Date(); Event event = parseSyslog("testNoTimestampInMessage", radixConfig, syslogMessage, now); RadixTreeSyslogParser.setRadixParser(oldRadixParser); Date eventTime = event.getTime(); assertNotNull(eventTime); assertEquals(eventTime, now); }

Target:
public void testNoTimestampInMessage() { RadixTreeParser oldRadixParser = RadixTreeSyslogParser.getRadixParser(); RadixTreeParser radixParser = new RadixTreeParser(); radixParser.teach(GrokParserStageSequenceBuilder.parseGrok("%{STRING:message}").toArray(new ParserStage[0])); RadixTreeSyslogParser.setRadixParser(radixParser); String syslogMessage = "%CDP-4-NATIVE_VLAN_MISMATCH: Native VLAN mismatch discovered on GigabitEthernet5/9 " + "(75), with switch.fqdn.com GigabitEthernet2/4/21 (2)"; Date now = new Date(); Event event = parseSyslog("testNoTimestampInMessage", radixConfig, syslogMessage, now); RadixTreeSyslogParser.setRadixParser(oldRadixParser); Date eventTime = event.getTime(); assertEquals(now, eventTime); }
Source:
public static Method normalizedValueOf(final String method) { return valueOf(Objects.requireNonNull(method, "method").toUpperCase(Locale.ROOT)); }

Target:
public static Method normalizedValueOf(final String method) { return valueOf(Args.notNull(method, "method").toUpperCase(Locale.ROOT)); }
Source:
private AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest request, AssertionType assertion, NhinTargetCommunitiesType targets) { AdhocQueryResponse response = null; if (targets == null) { targets = new ObjectFactory().createNhinTargetCommunitiesType(); } if (StringUtils.isBlank(targets.getUseSpecVersion())) { targets.setUseSpecVersion("3.0"); } response = outboundDocQuery.respondingGatewayCrossGatewayQuery(request, assertion, targets); return response; }

Target:
private AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest request, AssertionType assertion, NhinTargetCommunitiesType targets) { if (targets == null) { targets = new ObjectFactory().createNhinTargetCommunitiesType(); } if (StringUtils.isBlank(targets.getUseSpecVersion())) { targets.setUseSpecVersion("3.0"); } return outboundDocQuery.respondingGatewayCrossGatewayQuery(request, assertion, targets); }
Source:
public AlarmButtonViewModel(final AlarmCounter alarmCounter, String buttonLabel) { super(buttonLabel); flash = new FlashingButton(this, ALARM_COLOR); flash.setDefaultColour(DEFOCUSSED); alarmCounter.addPropertyChangeListener("alarmCount", arg0 -> { alarmCount = alarmCounter.getCount(); if (!active) { alarmSeen = false; } update(); updateFlashing(); } ); update(); }

Target:
public AlarmButtonViewModel(final AlarmCounter alarmCounter, String buttonLabel) { super(buttonLabel); flash = new FlashingButton(this, ALARM_COLOR); flash.setDefaultColour(DEFOCUSSED); alarmCounter.addPropertyChangeListener("alarmCount", ignored -> { alarmCount = alarmCounter.getCount(); if (!active) { alarmSeen = false; } update(); updateFlashing(); }); update(); }
Source:
private Set<IType> getRelatedTypes() { Set<IMethod> methods= getMethodsToRename(); Set<IType> result= new HashSet<>(methods.size()); for (IMethod iMethod : methods) { result.add(iMethod.getDeclaringType()); } return result; }

Target:
private Set<IType> getRelatedTypes() { Set<IMethod> methods= getMethodsToRename(); Set<IType> result= new HashSet<>(methods.size()); for (IMethod method : methods) { result.add(method.getDeclaringType()); } return result; }
Source:
public void testComma() throws Exception { checkConfig.addAttribute("option", "EOL"); checkConfig.addAttribute("tokens", "COMMA"); final String[] expected = { "39:17: " + getCheckMessage(MSG_LINE_PREVIOUS, ","), }; verify(checkConfig, getPath("InputSeparatorWrapAfter3904.java"), expected); }

Target:
public void testComma() throws Exception { checkConfig.addAttribute("option", "EOL"); checkConfig.addAttribute("tokens", "COMMA"); final String[] expected = { "39:17: " + getCheckMessage(MSG_LINE_PREVIOUS, ","), }; verify(checkConfig, getPath("InputSeparatorWrapForTestComma.java"), expected); }
Source:
protected void addFileProperties(FileSetProperties.Builder propertiesBuilder) { propertiesBuilder .setInputFormat(AvroKeyInputFormat.class) .setOutputFormat(TextOutputFormat.class) .setEnableExploreOnCreate(true) .setExploreFormat("text") .setExploreSchema("text string"); }

Target:
protected void addFileProperties(FileSetProperties.Builder propertiesBuilder) { propertiesBuilder .setInputFormat(TextInputFormat.class) .setOutputFormat(TextOutputFormat.class) .setEnableExploreOnCreate(true) .setExploreFormat("text") .setExploreSchema("text string"); }
Source:
public static Object percent3( ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB ) throws KettleValueException { if ( dataA == null || dataB == null ) { return null; } switch ( metaA.getType() ) { case ValueMetaInterface.TYPE_NUMBER: return new Double( metaA.getNumber( dataA ).doubleValue() + divideDoubles( multiplyDoubles( metaA.getNumber( dataA ), metaB.getNumber( dataB ) ), 100.0D ) ); case ValueMetaInterface.TYPE_INTEGER: return new Long( metaA.getInteger( dataA ).longValue() + divideLongs( multiplyLongs( metaA.getInteger( dataA ), metaB.getInteger( dataB ) ), 100L ) ); case ValueMetaInterface.TYPE_BIGNUMBER: return metaA.getBigNumber( dataA ).add( divideBigDecimals( multiplyBigDecimals( metaB.getBigNumber( dataB ), metaA.getBigNumber( dataA ), null ), new BigDecimal( 100 ) ) ); default: throw new KettleValueException( "The 'A+B%' function only works on numeric data" ); } }

Target:
public static Object percent3( ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB ) throws KettleValueException { if ( dataA == null || dataB == null ) { return null; } switch ( metaA.getType() ) { case ValueMetaInterface.TYPE_NUMBER: return new Double( metaA.getNumber( dataA ).doubleValue() + divideDoubles( multiplyDoubles( metaA.getNumber( dataA ), metaB.getNumber( dataB ) ), 100.0D ) ); case ValueMetaInterface.TYPE_INTEGER: return new Long( metaA.getInteger( dataA ).longValue() + divideLongs( multiplyLongs( metaA.getInteger( dataA ), metaB.getInteger( dataB ) ), 100L ) ); case ValueMetaInterface.TYPE_BIGNUMBER: return metaA.getBigNumber( dataA ).add( divideBigDecimals( multiplyBigDecimals( metaB.getBigNumber( dataB ), metaA.getBigNumber( dataA ), null ), new BigDecimal( 100 ), (MathContext) null ) ); default: throw new KettleValueException( "The 'A+B%' function only works on numeric data" ); } }
Source:
public Optional<DyeableData> from(DataHolder dataHolder) { if (supports(dataHolder)) { if (dataHolder instanceof EntitySheep) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) ((EntitySheep) dataHolder).getFleeceColor())); } else if (dataHolder instanceof EntityWolf) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) ((EntityWolf) dataHolder).getCollarColor())); } else if (dataHolder instanceof ItemStack) { if(((ItemStack) dataHolder).getItem().equals(Items.DYE)) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) EnumDyeColor.byDyeDamage(((ItemStack) dataHolder).getItemDamage()))); } else { return Optional.of(new SpongeDyeableData((DyeColor) (Object) EnumDyeColor.byMetadata(((ItemStack) dataHolder).getItemDamage()))); } } else if (dataHolder instanceof TileEntityShulkerBox) { return Optional.ofNullable(((IMixinTileEntityShulkerBox) dataHolder).getColor()).map(enumType -> (DyeColor) (Object) enumType).map (SpongeDyeableData::new); } } return Optional.empty(); }

Target:
public Optional<DyeableData> from(DataHolder dataHolder) { if (supports(dataHolder)) { if (dataHolder instanceof EntitySheep) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) ((EntitySheep) dataHolder).getFleeceColor())); } else if (dataHolder instanceof EntityWolf) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) ((EntityWolf) dataHolder).getCollarColor())); } else if (dataHolder instanceof ItemStack) { if(((ItemStack) dataHolder).getItem().equals(Items.DYE)) { return Optional.of(new SpongeDyeableData((DyeColor) (Object) EnumDyeColor.byDyeDamage(((ItemStack) dataHolder).getItemDamage()))); } else { return Optional.of(new SpongeDyeableData((DyeColor) (Object) EnumDyeColor.byMetadata(((ItemStack) dataHolder).getItemDamage()))); } } } return Optional.empty(); }
Source:
public void testAttrToSnakeAndLowerCase() { JmxCollector.Receiver rc = mock(JmxCollector.Receiver.class); when(rc.toSnakeAndLowerCase(anyString())).thenCallRealMethod(); String snakeAndLowerString = rc.toSnakeAndLowerCase(input); assertEquals(expected, snakeAndLowerString); }

Target:
public void testAttrToSnakeAndLowerCase() { String snakeAndLowerString = JmxCollector.toSnakeAndLowerCase(input); assertEquals(expected, snakeAndLowerString); }
Source:
public boolean is64bit() { return "x64".equals(arch); }

Target:
public boolean is64bit() { return IS_64_BIT.equals(arch); }
Source:
StandardRealmObjectSchema getSchemaForClass(String className) { throw new UnsupportedOperationException(); }

Target:
OsRealmObjectSchema getSchemaForClass(String className) { throw new UnsupportedOperationException(); }
Source:
public void endSuccessfully() { setQcowCompatForQcowImage(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); setSucceeded(true); }

Target:
public void endSuccessfully() { super.endSuccessfully(); setQcowCompatForQcowImage(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); setSucceeded(true); }
Source:
private void cacheDistribution(GridClient client, CacheArguments cacheArgs) throws GridClientException { CacheDistributionTaskArg taskArg = new CacheDistributionTaskArg(cacheArgs.caches()); UUID nodeId = cacheArgs.nodeId() == null ? BROADCAST_UUID : cacheArgs.nodeId(); taskArg.setUserAttributes(cacheArgs.getUserAttributes()); CacheDistributionTaskResult res = executeTaskByNameOnNode(client, CacheDistributionTask.class.getName(), taskArg, nodeId); res.print(System.out); }

Target:
private void cacheDistribution(GridClient client, CacheArguments cacheArgs) throws GridClientException { CacheDistributionTaskArg taskArg = new CacheDistributionTaskArg(cacheArgs.caches(), cacheArgs.getUserAttributes()); UUID nodeId = cacheArgs.nodeId() == null ? BROADCAST_UUID : cacheArgs.nodeId(); CacheDistributionTaskResult res = executeTaskByNameOnNode(client, CacheDistributionTask.class.getName(), taskArg, nodeId); res.print(System.out); }
Source:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandStatus commandStatus = CommandCoordinatorUtil.getCommandStatus(childCmdId); switch (commandStatus) { case ACTIVE: log.info("Waiting on CloneCinderDisksCommandCallback child commands to complete"); return; case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; log.error("Unknown command status."); break; default: log.error("Invalid command status: '{}", commandStatus); break; } } T command = getCommand(cmdId); command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); }

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandStatus commandStatus = CommandCoordinatorUtil.getCommandStatus(childCmdId); switch (commandStatus) { case ACTIVE: log.info("Waiting on CloneCinderDisksCommandCallback child commands to complete"); return; case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; default: log.error("Invalid command status: '{}", commandStatus); break; } } T command = getCommand(cmdId); command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); }
Source:
public void assertBinEqual(Key key, Record record, Bin bin) { assertRecordFound(key, record); Object received = record.getValue(bin.name); Object expected = bin.value.getObject(); if (received == null || ! received.equals(expected)) { throw new IllegalArgumentException("Data mismatch: Expected " + expected + ". Received " + received); } }

Target:
public void assertBinEqual(Key key, Record record, Bin bin) { assertRecordFound(key, record); Object received = record.getValue(bin.name); Object expected = bin.value.getObject(); assertThat(received).isEqualTo(expected); }
Source:
public String type() { if (ctx == null) return null; switch (ctx.type()) { case ODBC_CLIENT: return "ODBC"; case JDBC_CLIENT: return "JDBC"; case THIN_CLIENT: return "THIN"; default: return "unknown"; } }

Target:
public String type() { if (ctx == null) return null; if (ctx instanceof OdbcConnectionContext) return "ODBC"; else if (ctx instanceof JdbcConnectionContext) return "JDBC"; else if (ctx instanceof ClientConnectionContext) return "THIN"; return "unknown"; }
Source:
public void handleDownloadProgressMenuItem(Menu menu) { downloadsMenuItem = menu.findItem(R.id.menu_item_download_progress); final View progressView = downloadsMenuItem.getActionView(); final ProgressWheel progressWheel = (ProgressWheel) progressView.findViewById(R.id.progress_wheel); downloadsMenuItem.setVisible(downloadsMenuItem.isVisible()); progressWheel.setProgress(progressWheel.getProgress()); progressView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { environment.getRouter().showDownloads(getActivity()); } }); if (updateDownloadProgressRunnable == null) { updateDownloadProgressRunnable = new Runnable() { @Override public void run() { logger.debug("KHALID:: updateDownloadProgressRunnable RUNNING"); if (!NetworkUtil.isConnected(getContext()) || !environment.getDatabase().isAnyVideoDownloading(null)) { downloadsMenuItem.setVisible(false); } else { downloadsMenuItem.setVisible(true); environment.getStorage().getAverageDownloadProgress( new DataCallback<Integer>() { @Override public void onResult(Integer result) { int progressPercent = result; if (progressPercent >= 0 && progressPercent <= 100) { progressWheel.setProgressPercent(progressPercent); } } @Override public void onFail(Exception ex) { logger.error(ex); } }); } handler.postDelayed(this, DateUtils.SECOND_IN_MILLIS); } }; updateDownloadProgressRunnable.run(); } }

Target:
public void handleDownloadProgressMenuItem(Menu menu) { downloadsMenuItem = menu.findItem(R.id.menu_item_download_progress); final View progressView = downloadsMenuItem.getActionView(); final ProgressWheel progressWheel = (ProgressWheel) progressView.findViewById(R.id.progress_wheel); downloadsMenuItem.setVisible(downloadsMenuItem.isVisible()); progressWheel.setProgress(progressWheel.getProgress()); progressView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { environment.getRouter().showDownloads(getActivity()); } }); if (updateDownloadProgressRunnable == null) { updateDownloadProgressRunnable = new Runnable() { @Override public void run() { if (!NetworkUtil.isConnected(getContext()) || !environment.getDatabase().isAnyVideoDownloading(null)) { downloadsMenuItem.setVisible(false); } else { downloadsMenuItem.setVisible(true); environment.getStorage().getAverageDownloadProgress( new DataCallback<Integer>() { @Override public void onResult(Integer result) { int progressPercent = result; if (progressPercent >= 0 && progressPercent <= 100) { progressWheel.setProgressPercent(progressPercent); } } @Override public void onFail(Exception ex) { logger.error(ex); } }); } handler.postDelayed(this, DateUtils.SECOND_IN_MILLIS); } }; updateDownloadProgressRunnable.run(); } }