auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<TaskError> setEnabledOrDisabled(final Task task) { LOGGER.info("Saving task: with ID: {}", task.getName(), task.getId()); Set<String> fieldsToUpdate = new HashSet<>(); fieldsToUpdate.add("enabled"); tasksDataService.updateFromTransient(task, fieldsToUpdate); return taskValidator.validate(tasksDataService.findById(task.getId())); }

Target:
public void setEnabledOrDisabled(final Task task) { LOGGER.info("Saving task: with ID: {}", task.getName(), task.getId()); Set<String> fieldsToUpdate = new HashSet<>(); fieldsToUpdate.add("enabled"); tasksDataService.updateFromTransient(task, fieldsToUpdate); }
Source:
private Collection<FeedbackResponse> getFeedbackResponseEntitiesForSessionInSection( String feedbackSessionName, String courseId, String section) { Map<String, FeedbackResponse> FeedbackResponseList = new HashMap<String,FeedbackResponse>(); Query q = getPM().newQuery(FeedbackResponse.class); q.declareParameters("String feedbackSessionNameParam, String courseIdParam, String sectionParam"); q.setFilter("feedbackSessionName == feedbackSessionNameParam && courseId == courseIdParam && giverSection == sectionParam"); @SuppressWarnings("unchecked") List<FeedbackResponse> firstQueryResponses = (List<FeedbackResponse>) q.execute(feedbackSessionName, courseId, section); for(FeedbackResponse response : firstQueryResponses){ if (!JDOHelper.isDeleted(response)) { FeedbackResponseList.put(response.getId(), response); } } q.setFilter("feedbackSessionName == feedbackSessionNameParam && courseId == courseIdParam && receiverSection == sectionParam"); @SuppressWarnings("unchecked") List<FeedbackResponse> secondQueryResponses = (List<FeedbackResponse>) q.execute(feedbackSessionName, courseId, section); for(FeedbackResponse response : secondQueryResponses){ if (!JDOHelper.isDeleted(response)) { FeedbackResponseList.put(response.getId(), response); } } return FeedbackResponseList.values(); }

Target:
private Collection<FeedbackResponse> getFeedbackResponseEntitiesForSessionInSection( String feedbackSessionName, String courseId, String section) { Map<String, FeedbackResponse> feedbackResponses = new HashMap<String,FeedbackResponse>(); Query q = getPM().newQuery(FeedbackResponse.class); q.declareParameters("String feedbackSessionNameParam, String courseIdParam, String sectionParam"); q.setFilter("feedbackSessionName == feedbackSessionNameParam && courseId == courseIdParam && giverSection == sectionParam"); @SuppressWarnings("unchecked") List<FeedbackResponse> firstQueryResponses = (List<FeedbackResponse>) q.execute(feedbackSessionName, courseId, section); for(FeedbackResponse response : firstQueryResponses){ if (!JDOHelper.isDeleted(response)) { feedbackResponses.put(response.getId(), response); } } q.setFilter("feedbackSessionName == feedbackSessionNameParam && courseId == courseIdParam && receiverSection == sectionParam"); @SuppressWarnings("unchecked") List<FeedbackResponse> secondQueryResponses = (List<FeedbackResponse>) q.execute(feedbackSessionName, courseId, section); for(FeedbackResponse response : secondQueryResponses){ if (!JDOHelper.isDeleted(response)) { feedbackResponses.put(response.getId(), response); } } return feedbackResponses.values(); }
Source:
private Optional<Channel> updateChannelWithAdvertisedDates( Channel channel, DateTime advertiseFromDate, DateTime advertiseToDate ) { if (advertiseFromDate != null && advertiseFromDate.getMillis() > 0) { channel.setAdvertiseFrom(advertiseFromDate); } else { channel.setAdvertiseFrom(null); } if (advertiseToDate != null && advertiseToDate.getMillis() > 0) { channel.setAdvertiseTo(advertiseToDate); } else { channel.setAdvertiseTo(null); } channelWriter.createOrUpdate(channel); return Optional.of(channel); }

Target:
private Channel updateChannelWithAdvertisedDates( Channel channel, DateTime advertiseFromDate, DateTime advertiseToDate ) { if (advertiseFromDate != null && advertiseFromDate.getMillis() > 0) { channel.setAdvertiseFrom(advertiseFromDate); } else { channel.setAdvertiseFrom(null); } if (advertiseToDate != null && advertiseToDate.getMillis() > 0) { channel.setAdvertiseTo(advertiseToDate); } else { channel.setAdvertiseTo(null); } channelWriter.createOrUpdate(channel); return channel; }
Source:
public String lastValue() { if (_lastvalue==null) { _lastvalue=nextString(); } return _lastvalue; }

Target:
public String lastValue() { if (_lastvalue==null) { _lastvalue=nextValue(); } return _lastvalue; }
Source:
public RefundEntity createRefund(Long accountId, String chargeExternalId, RefundRequest refundRequest) { GatewayAccountEntity gatewayAccountEntity = gatewayAccountDao.findById(accountId).orElseThrow( () -> new GatewayAccountNotFoundException(accountId)); return chargeService.findCharge(chargeExternalId, gatewayAccountEntity.getId()).map(charge -> { List<RefundEntity> refundEntityList = refundDao.findRefundsByChargeExternalId(charge.getExternalId()); long availableAmount = validateRefundAndGetAvailableAmount(charge, gatewayAccountEntity, refundRequest, refundEntityList); RefundEntity refundEntity = createRefundEntity(refundRequest, charge); logger.info("Card refund request sent - charge_external_id={}, status={}, amount={}, transaction_id={}, account_id={}, operation_type=Refund, amount_available_refund={}, amount_requested_refund={}, provider={}, provider_type={}, user_external_id={}", charge.getExternalId(), charge.getStatus(), charge.getAmount(), charge.getGatewayTransactionId(), gatewayAccountEntity.getId(), availableAmount, refundRequest.getAmount(), gatewayAccountEntity.getGatewayName(), gatewayAccountEntity.getType(), refundRequest.getUserExternalId()); return refundEntity; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(chargeExternalId)); }

Target:
public RefundEntity createRefund(Long accountId, String chargeExternalId, RefundRequest refundRequest) { GatewayAccountEntity gatewayAccountEntity = gatewayAccountDao.findById(accountId).orElseThrow( () -> new GatewayAccountNotFoundException(accountId)); return chargeService.findCharge(chargeExternalId, gatewayAccountEntity.getId()).map(charge -> { List<RefundEntity> refundEntityList = refundDao.findRefundsByChargeExternalId(charge.getExternalId()); long availableAmount = validateRefundAndGetAvailableAmount(charge, gatewayAccountEntity, refundRequest, refundEntityList); RefundEntity refundEntity = createRefundEntity(refundRequest, charge); logger.info("Card refund request sent - charge_external_id={}, status={}, amount={}, transaction_id={}, account_id={}, operation_type=Refund, amount_available_refund={}, amount_requested_refund={}, provider={}, provider_type={}, user_external_id={}", charge.getExternalId(), charge.getExternalStatus(), charge.getAmount(), charge.getGatewayTransactionId(), gatewayAccountEntity.getId(), availableAmount, refundRequest.getAmount(), gatewayAccountEntity.getGatewayName(), gatewayAccountEntity.getType(), refundRequest.getUserExternalId()); return refundEntity; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(chargeExternalId)); }
Source:
public ArrayList<PowerAcceptorBlockEntityFace> getConnectedPowerAcceptors() { ArrayList<PowerAcceptorBlockEntityFace> result = new ArrayList<>(); for (Direction face : Direction.values()) { BlockEntity blockEntity = world.getBlockEntity(pos.offset(face)); if (blockEntity != null && Energy.valid(blockEntity) && blockEntity instanceof PowerAcceptorBlockEntity) { result.add(new PowerAcceptorBlockEntityFace((PowerAcceptorBlockEntity) blockEntity, face.getOpposite())); } } return result; }

Target:
public List<PowerAcceptorBlockEntityFace> getConnectedPowerAcceptors() { ArrayList<PowerAcceptorBlockEntityFace> result = new ArrayList<>(); for (Direction face : Direction.values()) { BlockEntity blockEntity = world.getBlockEntity(pos.offset(face)); if (blockEntity != null && Energy.valid(blockEntity) && blockEntity instanceof PowerAcceptorBlockEntity) { result.add(new PowerAcceptorBlockEntityFace((PowerAcceptorBlockEntity) blockEntity, face.getOpposite())); } } return result; }
Source:
public ECKey getKey() { byte[] hash = getRawHash(); return ECKey.recoverFromSignature(0, signature, hash); }

Target:
public ECKey getKey() { byte[] hash = getRawHash(); try { return ECKey.signatureToKey(hash, getSignature()); }catch (SignatureException e){ return null; } }
Source:
public void clean_before_checkout() throws IOException, InterruptedException, SftpException, JSchException { GitRepo repo = buildGitRepo(); repo.transferToDockerContainer(host, port); job.useScm(GitScm.class) .url(repoUrl) .credentials(USERNAME) .cleanBeforeCheckout(); job.addShellStep("touch untrackedFile.txt"); job.save(); job.startBuild().shouldSucceed(); job.configure(); job.removeFirstBuildStep(); job.addShellStep("ls && test ! -f untrackedFile.txt"); job.save(); job.startBuild().shouldSucceed(); }

Target:
public void clean_before_checkout() { test_clean_while_checkout(true); }
Source:
public void testDisplayingDataSeries() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { IViewPart viewSite = getSWTBotView().getViewReference().getView(true); assertTrue(viewSite instanceof CounterView); final TmfCommonXLineChartViewer chartViewer = getChartViewer(viewSite); assertNotNull(chartViewer); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); chartViewer.setNbPoints(NUMBER_OF_POINTS); final Chart chart = getChart(); assertNotNull(chart); assertEquals(0, chart.getSeriesSet().getSeries().length); SWTBotTree treeBot = getSWTBotView().bot().tree(); WaitUtils.waitUntil(tree -> tree.rowCount() >= 1, treeBot, "The tree viewer did not finish loading."); SWTBotTreeItem root = treeBot.getTreeItem(TRACE_NAME); SWTBotTreeItem counter = retrieveTreeItem(root, COUNTER_NAME); counter.check(); WaitUtils.waitUntil(c -> c.getSeriesSet().getSeries().length >= 1, chart, "The data series did not load."); verifySeriesStyle(MAIN_SERIES_NAME, ISeries.SeriesType.LINE, BLUE, LineStyle.SOLID, false); WaitUtils.waitUntil(json -> isChartDataValid(chart, json, MAIN_SERIES_NAME), "resources/minor_faults-res50.json", "The chart data is not valid."); }

Target:
public void testDisplayingDataSeries() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { IViewPart viewSite = getSWTBotView().getViewReference().getView(true); assertTrue(viewSite instanceof CounterView); final TmfCommonXLineChartViewer chartViewer = getChartViewer(viewSite); assertNotNull(chartViewer); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); chartViewer.setNbPoints(NUMBER_OF_POINTS); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); final Chart chart = getChart(); assertNotNull(chart); assertEquals(0, chart.getSeriesSet().getSeries().length); SWTBotTree treeBot = getSWTBotView().bot().tree(); WaitUtils.waitUntil(tree -> tree.rowCount() >= 1, treeBot, "The tree viewer did not finish loading."); SWTBotTreeItem root = treeBot.getTreeItem(TRACE_NAME); SWTBotTreeItem counter = retrieveTreeItem(root, COUNTER_NAME); counter.check(); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); WaitUtils.waitUntil(c -> c.getSeriesSet().getSeries().length >= 1, chart, "The data series did not load."); verifySeriesStyle(MAIN_SERIES_NAME, ISeries.SeriesType.LINE, BLUE, LineStyle.SOLID, false); WaitUtils.waitUntil(json -> isChartDataValid(chart, json, MAIN_SERIES_NAME), "resources/minor_faults-res50.json", "The chart data is not valid."); }
Source:
public void configure(Config config) throws Exception { serverHost = config.getProperty(SERVER_HOST_PROPERTY); serverPort = config.getProperty(SERVER_PORT_PROPERTY); clusterId = config.getProperty(CLUSTER_ID_PROPERTY); clientId = config.getProperty(CLIENT_ID_PROPERTY); if (clientId == null) { clientId = generateClientId(); } subject = config.getProperty (SUBJECT_PROPERTY); }

Target:
public void configure(Config config) throws Exception { serverHost = config.getProperty(SERVER_HOST_PROPERTY); if (serverHost == null) { throw new ConfigurationException(SERVER_HOST_PROPERTY + " is a required parameter"); } serverPort = config.getProperty(SERVER_PORT_PROPERTY); if (serverHost == null) { throw new ConfigurationException(SERVER_PORT_PROPERTY + " is a required parameter"); } clusterId = config.getProperty(CLUSTER_ID_PROPERTY); if (serverHost == null) { throw new ConfigurationException(CLUSTER_ID_PROPERTY + " is a required parameter"); } clientId = config.getProperty(CLIENT_ID_PROPERTY); }
Source:
public OrderType unretireOrderType(OrderType orderType) { orderType.setRetired(false); return dao.saveOrderType(orderType); }

Target:
public OrderType unretireOrderType(OrderType orderType) { orderType.setRetired(false); return saveOrderType(orderType); }
Source:
protected void checkUniquePropertyHeaderTitle(String propertyHeaderCellValue, int columnIndex) { if (propertyHeaderCellValue.isEmpty()) { throw new IllegalArgumentException(ScenarioSimulationEditorConstants.INSTANCE.propertyTitleEmptyError()); } SimulationDescriptor simulationDescriptor = simulation.getSimulationDescriptor(); FactIdentifier factIdentifier = simulationDescriptor.getFactMappingByIndex(columnIndex).getFactIdentifier(); if (IntStream.range(0, getColumnCount()) .filter(index -> index != columnIndex) .filter(index -> Objects.equals(factIdentifier, simulationDescriptor.getFactMappingByIndex(index).getFactIdentifier())) .mapToObj(index -> (ScenarioGridColumn) getColumns().get(index)) .filter(elem -> elem.getPropertyHeaderMetaData() != null) .map(ScenarioGridColumn::getPropertyHeaderMetaData) .anyMatch(elem -> Objects.equals(elem.getTitle(), propertyHeaderCellValue))) { throw new IllegalArgumentException(ScenarioSimulationEditorConstants.INSTANCE. propertyTitleAssignedError(propertyHeaderCellValue)); } }

Target:
protected void checkUniquePropertyHeaderTitle(String propertyHeaderCellValue, int columnIndex) { SimulationDescriptor simulationDescriptor = simulation.getSimulationDescriptor(); FactMapping factMapping = simulationDescriptor.getFactMappingByIndex(columnIndex); if (! Objects.equals(factMapping.getClassName(), ConstantsHolder.EXPRESSION_CLASSNAME) && propertyHeaderCellValue.endsWith(ConstantsHolder.EXPRESSION_SUFFIX)) { throw new IllegalArgumentException(ScenarioSimulationEditorConstants.INSTANCE.propertyTitleReservedKeyError()); } FactIdentifier factIdentifier = simulationDescriptor.getFactMappingByIndex(columnIndex).getFactIdentifier(); if (IntStream.range(0, getColumnCount()) .filter(index -> index != columnIndex) .filter(index -> Objects.equals(factIdentifier, simulationDescriptor.getFactMappingByIndex(index).getFactIdentifier())) .mapToObj(index -> (ScenarioGridColumn) getColumns().get(index)) .filter(elem -> elem.getPropertyHeaderMetaData() != null) .map(ScenarioGridColumn::getPropertyHeaderMetaData) .anyMatch(elem -> Objects.equals(elem.getTitle(), propertyHeaderCellValue))) { throw new IllegalArgumentException(ScenarioSimulationEditorConstants.INSTANCE. propertyTitleAssignedError(propertyHeaderCellValue)); } }
Source:
Substitution(ConfigOrigin origin, boolean optional, List<Token> expression) { super(TokenType.SUBSTITUTION, origin, "${" + (optional? "?" : "") + Tokenizer.render(expression.iterator()) + "}"); this.optional = optional; this.value = expression; }

Target:
Substitution(ConfigOrigin origin, boolean optional, List<Token> expression) { super(TokenType.SUBSTITUTION, origin); this.optional = optional; this.value = expression; }
Source:
public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); if (!stopping) { synchronized (this) { if (!stopping) { log.debugf("Stopping cache manager %s on %s", globalConfiguration.transport().clusterName(), getAddress()); stopping = true; Set<String> cachesToStop = new LinkedHashSet<>(); boolean defaultCacheHasDependency = false; try { List<String> ordered = cacheDependencyGraph.topologicalSort(); defaultCacheHasDependency = ordered.contains(DEFAULT_CACHE_NAME); cachesToStop.addAll(ordered); } catch (CyclicDependencyException e) { log.debugf("Cyclic dependency detect between caches, stop order ignored"); } cachesToStop.addAll(caches.keySet()); Cache<?, ?> defaultCache = null; for (String cacheName : cachesToStop) { if (cacheName.equals(ClusterRegistryImpl.GLOBAL_REGISTRY_CACHE_NAME)) { } else if (cacheName.equals(DEFAULT_CACHE_NAME) && !defaultCacheHasDependency) { defaultCache = this.caches.get(cacheName).cache; } else { terminate(this.caches.get(cacheName).cache); } } terminate(defaultCache); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } else { log.trace("Ignore call to stop as the cache manager is stopping"); } } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } }

Target:
public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); if (!stopping) { synchronized (this) { if (!stopping) { log.debugf("Stopping cache manager %s on %s", globalConfiguration.transport().clusterName(), getAddress()); stopping = true; Set<String> cachesToStop = new LinkedHashSet<>(); boolean defaultCacheHasDependency = false; try { List<String> ordered = cacheDependencyGraph.topologicalSort(); defaultCacheHasDependency = ordered.contains(DEFAULT_CACHE_NAME); cachesToStop.addAll(ordered); } catch (CyclicDependencyException e) { log.stopOrderIgnored(); } cachesToStop.addAll(caches.keySet()); Cache<?, ?> defaultCache = null; for (String cacheName : cachesToStop) { if (cacheName.equals(ClusterRegistryImpl.GLOBAL_REGISTRY_CACHE_NAME)) { } else if (cacheName.equals(DEFAULT_CACHE_NAME) && !defaultCacheHasDependency) { defaultCache = this.caches.get(cacheName).cache; } else { terminate(this.caches.get(cacheName).cache); } } terminate(defaultCache); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } else { log.trace("Ignore call to stop as the cache manager is stopping"); } } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } }
Source:
public static void main(String... args) throws Exception { TypeRegistry typeRegistry = new TypeRegistry(); new FunctionRegistry(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); for (String arg : args) { File path = new File(arg).getAbsoluteFile(); checksumHdfsOrcFile(path, false, typeRegistry); } }

Target:
public static void main(String... args) throws Exception { TypeRegistry typeRegistry = new TypeRegistry(); new FunctionRegistry(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); for (String arg : args) { File path = new File(arg).getAbsoluteFile(); checksumHdfsOrcFile(path, OrcEncoding.DWRF, typeRegistry); } }
Source:
public void close() throws IOException { super.close(); }

Target:
public void close() throws IOException { subscription.cancel(); if (this.buffer != null) { this.buffer.close(); } super.close(); if (this.lastError != null) { throw this.lastError; } }
Source:
public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService, final Lazy<FakeBigtableConnection> fakeBigtableConnection ) { if (fake.orElse(false)) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.resolved(fakeBigtableConnection.get()); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return value.close(); } }); } return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, executorService, disableBulkMutations, flushIntervalSeconds, batchSize)); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }

Target:
public Managed<BigtableConnection> connection( final AsyncFramework async, final ExecutorService executorService, final Lazy<FakeBigtableConnection> fakeBigtableConnection ) { if (fake) { return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.resolved(fakeBigtableConnection.get()); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return value.close(); } }); } return async.managed(new ManagedSetup<BigtableConnection>() { @Override public AsyncFuture<BigtableConnection> construct() throws Exception { return async.call( new BigtableConnectionBuilder(project, instance, credentials, async, executorService, disableBulkMutations, flushIntervalSeconds, batchSize)); } @Override public AsyncFuture<Void> destruct(final BigtableConnection value) throws Exception { return async.call(() -> { value.close(); return null; }); } }); }
Source:
public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_0.getUriString(), TransactionSubsystem10Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_1.getUriString(), TransactionSubsystem11Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_2.getUriString(), TransactionSubsystem12Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_3.getUriString(), TransactionSubsystem13Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_4.getUriString(), TransactionSubsystem14Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_5.getUriString(), TransactionSubsystem15Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_2_0.getUriString(), TransactionSubsystem20Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_3_0.getUriString(), TransactionSubsystem30Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_4_0.getUriString(), TransactionSubsystem40Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_5_0.getUriString(), TransactionSubsystem50Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_5_1.getUriString(), TransactionSubsystem51Parser::new); }

Target:
public void initializeParsers(ExtensionParsingContext context) { context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_0.getUriString(), TransactionSubsystem10Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_1.getUriString(), TransactionSubsystem11Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_2.getUriString(), TransactionSubsystem12Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_3.getUriString(), TransactionSubsystem13Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_4.getUriString(), TransactionSubsystem14Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_1_5.getUriString(), TransactionSubsystem15Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_2_0.getUriString(), TransactionSubsystem20Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_3_0.getUriString(), TransactionSubsystem30Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_4_0.getUriString(), TransactionSubsystem40Parser::new); context.setSubsystemXmlMapping(SUBSYSTEM_NAME, Namespace.TRANSACTIONS_5_0.getUriString(), TransactionSubsystem50Parser::new); }
Source:
protected IStatus run(IProgressMonitor monitor) { HashSet<ITask> relevantTasks = new HashSet<ITask>(); IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow workbenchWindow : workbenchWindows) { IWorkbenchPage[] workbenchPages = workbenchWindow.getPages(); for (IWorkbenchPage workbenchPage : workbenchPages) { IEditorReference[] editorReferences = workbenchPage.getEditorReferences(); for (IEditorReference editorReference : editorReferences) { IEditorPart editorPart = editorReference.getEditor(false); if (editorPart instanceof TaskEditor) { TaskEditorInput taskEditorInput = ((TaskEditor) editorPart).getTaskEditorInput(); if (taskEditorInput.exists()) { relevantTasks.add(taskEditorInput.getTask()); } } } } } ITask activeTask = taskActivityManager.getActiveTask(); if (activeTask != null) { relevantTasks.add(activeTask); } Set<ITask> dueTasks = taskActivityManager.getScheduledTasks(TaskActivityUtil.getCurrentWeek().getToday()); relevantTasks.addAll(dueTasks); ListMultimap<TaskRepository, ITask> repositoryMap = ArrayListMultimap.create(); for (ITask task : relevantTasks) { if (!(task instanceof LocalTask)) { String connectorKind = task.getConnectorKind(); String repositoryUrl = task.getRepositoryUrl(); TaskRepository taskRepository = repositoryManager.getRepository(connectorKind, repositoryUrl); repositoryMap.put(taskRepository, task); } } for (TaskRepository taskRepository : repositoryMap.keySet()) { List<ITask> repositoryTasks = repositoryMap.get(taskRepository); AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(taskRepository.getConnectorKind()); SynchronizationJob synchronizationJob = taskJobFactory.createSynchronizeTasksJob(connector, taskRepository, new HashSet<>(repositoryTasks)); synchronizationJob.setUser(false); synchronizationJob.setSystem(true); synchronizationJob.schedule(); } return Status.OK_STATUS; }

Target:
protected IStatus run(IProgressMonitor monitor) { HashSet<ITask> relevantTasks = new HashSet<ITask>(); addOpenEditorTasks(relevantTasks); addActiveTask(relevantTasks); addTodaysTasks(relevantTasks); ListMultimap<TaskRepository, ITask> repositoryMap = mapTasksToRepository(relevantTasks); scheduleSynchronizationJobs(repositoryMap); return Status.OK_STATUS; }
Source:
public void test1b() { List<String> results = new ArrayList<String>(); final BaragonAgentMetadata agentMetadata = new BaragonAgentMetadata(BASE_URI, AGENT_ID, Optional.of(DOMAIN), new BaragonAgentEc2Metadata(Optional.absent(), Optional.of("us-east-1b"), Optional.absent(), Optional.absent(), Optional.absent()), Optional.absent(), Collections .emptyMap(), true); for (String AZ: availabilityZones) { final UpstreamInfo currentUpstream = new UpstreamInfo("testhost:8080", Optional.absent(), Optional.of(AZ)); final PreferSameRackWeightingHelper helper = new PreferSameRackWeightingHelper(configuration, agentMetadata); CharSequence result = helper.preferSameRackWeightingBalanced(upstreams, currentUpstream, null); results.add(result.toString()); } Assert.assertEquals(Arrays.asList("", "", "weight=4", "backup", "backup"), results); }

Target:
public void test1b() { List<String> results = new ArrayList<>(); final BaragonAgentMetadata agentMetadata = generateBaragonAgentMetadata("us-east-1b"); for (String availabilityZone: AVAILABILITY_ZONES) { final UpstreamInfo currentUpstream = new UpstreamInfo("testhost:8080", Optional.absent(), Optional.of(availabilityZone)); final PreferSameRackWeightingHelper helper = new PreferSameRackWeightingHelper(CONFIGURATION, agentMetadata); CharSequence result = helper.preferSameRackWeighting(UPSTREAMS, currentUpstream, allRacks, capacity, totalPendingLoad, null); results.add(result.toString()); } Assert.assertEquals(Arrays.asList("", "", "weight=4", "backup", "backup"), results); }
Source:
public IdRange getReusableIdBatch( int maxSize ) { long[] tmpIdArr = new long[maxSize]; int count = 0; while ( count < maxSize ) { long id = freeIdKeeper.getId(); if ( id == FreeIdKeeper.NO_RESULT ) { break; } tmpIdArr[count++] = id; } long[] defragIdArr = new long[count]; System.arraycopy( tmpIdArr, 0, defragIdArr, 0, count ); return new IdRange( defragIdArr, 0, 0 ); }

Target:
public IdRange getReusableIdBatch( int maxSize ) { long[] tmpIdArr = new long[maxSize]; int count = 0; while ( count < maxSize ) { long id = freeIdKeeper.getId(); if ( id == FreeIdKeeper.NO_RESULT ) { break; } tmpIdArr[count++] = id; } long[] defragIdArr = count == maxSize ? tmpIdArr : Arrays.copyOfRange( tmpIdArr, 0, count ); return new IdRange( defragIdArr, 0, 0 ); }
Source:
public void execute(SensorContext context) { Iterable<InputFile> sourceFiles = filesystem.inputFiles(filePredicates.and(filePredicates.hasLanguage(Php.KEY), filePredicates.hasType(InputFile.Type.MAIN))); for (InputFile file : sourceFiles) { org.sonar.api.resources.File phpFile = org.sonar.api.resources.File.create(file.relativePath()); if (phpFile != null) { Source source = analyseSourceCode(file.file(), filesystem.encoding()); if (source != null) { filter.addComponent(phpFile.getEffectiveKey(), source.getNoSonarTagLines()); int measure = source.getMeasure(Metric.COMMENTED_OUT_CODE_LINES); context.<Integer>newMeasure().on(file).withValue(measure).forMetric(CoreMetrics.COMMENTED_OUT_CODE_LINES).save(); } } } }

Target:
public void execute(SensorContext context) { Iterable<InputFile> sourceFiles = filesystem.inputFiles(filePredicates.and(filePredicates.hasLanguage(Php.KEY), filePredicates.hasType(InputFile.Type.MAIN))); for (InputFile file : sourceFiles) { Source source = analyseSourceCode(file.file(), filesystem.encoding()); if (source != null) { filter.noSonarInFile(file, source.getNoSonarTagLines()); int measure = source.getMeasure(Metric.COMMENTED_OUT_CODE_LINES); context.<Integer>newMeasure().on(file).withValue(measure).forMetric(CoreMetrics.COMMENTED_OUT_CODE_LINES).save(); } } }
Source:
public int getItemCount() { return wikipediaLanguages.size(); }

Target:
public int getItemCount() { return wikipediaLanguages.size() + NUM_HEADERS + NUM_FOOTERS; }
Source:
public InstalledDriver getInstalledDriver(String name, String profileName) throws IllegalStateException { InstalledDriver returnValue = null; if (profileName != null) { if (drivers.get(profileName) == null) { throw ROOT_LOGGER.driverNotDefinedInDefaultProfile(name); } returnValue = drivers.get(profileName).get(name); } if (returnValue == null) { returnValue = drivers.get(DEFAULT_PROFILE).get(name); } return returnValue; }

Target:
public InstalledDriver getInstalledDriver(String name, String profileName) throws IllegalStateException { InstalledDriver returnValue = null; synchronized (drivers) { if (profileName != null) { if (drivers.get(profileName) != null) { returnValue = drivers.get(profileName).get(name); } } else { if (drivers.get(DEFAULT_PROFILE) == null) { throw ROOT_LOGGER.driverNotDefinedInDefaultProfile(name); } } if (returnValue == null) { returnValue = drivers.get(DEFAULT_PROFILE).get(name); } } return returnValue; }
Source:
public MultiTouchAction perform() { List<TouchAction> touchActions = actions.build(); checkArgument(touchActions.size() > 0, "MultiTouch action must have at least one TouchAction added before it can be performed"); if (touchActions.size() > 1) { performsTouchActions.performMultiTouchAction(this); } else { performsTouchActions.performTouchAction(actions.build().get(0)); } return this; }

Target:
public MultiTouchAction perform() { List<TouchAction> touchActions = actions.build(); checkArgument(touchActions.size() > 0, "MultiTouch action must have at least one TouchAction added before it can be performed"); if (touchActions.size() > 1) { performsTouchActions.performMultiTouchAction(this); return this; } performsTouchActions.performTouchAction(touchActions.get(0)); return this; }
Source:
public void testAppendNonexistentFile() throws Throwable { try { getFileSystem().append(target).close(); } catch (Exception ex) { handleExpectedException(ex); } }

Target:
public void testAppendNonexistentFile() throws Throwable { try { FSDataOutputStream out = getFileSystem().append(target); out.close(); fail("expected a failure"); } catch (Exception e) { handleExpectedException(e); } }
Source:
public void start() { taskManagementExecutor.scheduleWithFixedDelay(() -> { try { requestMemoryRevokingIfNeeded(currentTasksSupplier.get()); } catch (Throwable e) { log.warn(e, "Error requesting system memory revoking"); } }, 0, 1, TimeUnit.SECONDS); }

Target:
public void start() { registerPeriodicCheck(); registerPoolListeners(); }
Source:
private static ByteBuffer readRgbModelFrom(BufferedImage image) { int w = image.getWidth(); int h = image.getHeight(); int[] pixels = new int[w * h]; image.getRGB(0, 0, w, h, pixels, 0, w); ByteBuffer rgbBytes = ByteBuffer.allocate(w * h * BLOCK_SIZE); for (int r = 0; r < h; r++) { for (int c = 0; c < w; c++) { int index = r * w + c; int indexRgb = r * w * BLOCK_SIZE + c * BLOCK_SIZE; rgbBytes.put(indexRgb, (byte) ((pixels[index] >> 16) & 0xff)); rgbBytes.put(indexRgb + 1, (byte) ((pixels[index] >> 8) & 0xff)); rgbBytes.put(indexRgb + 2, (byte) (pixels[index] & 0xff)); rgbBytes.put(indexRgb + 3, (byte) ((pixels[index] >> 24) & 0xff)); } } return rgbBytes; }

Target:
private static ByteBuffer readRgbModelFrom(BufferedImage image) { int w = image.getWidth(); int h = image.getHeight(); int[] pixels = new int[w * h]; image.getRGB(0, 0, w, h, pixels, 0, w); ByteBuffer rgbBytes = ByteBuffer.allocateDirect(w * h * BLOCK_SIZE); for (int r = 0; r < h; r++) { for (int c = 0; c < w; c++) { int index = r * w + c; int indexRgb = r * w * BLOCK_SIZE + c * BLOCK_SIZE; rgbBytes.put(indexRgb, (byte) ((pixels[index] >> 16) & 0xff)); rgbBytes.put(indexRgb + 1, (byte) ((pixels[index] >> 8) & 0xff)); rgbBytes.put(indexRgb + 2, (byte) (pixels[index] & 0xff)); rgbBytes.put(indexRgb + 3, (byte) ((pixels[index] >> 24) & 0xff)); } } return rgbBytes; }
Source:
public void readMaxVarInt() throws Exception { int actual = makeReader("077F7F7FFF").readVarInt(); assertEquals(Integer.MAX_VALUE, actual); }

Target:
public void readMaxVarInt() throws Exception { assertEquals(Integer.MAX_VALUE, makeReader("077F7F7FFF").readVarInt()); }
Source:
protected boolean markCompleted(String processId, @Nullable Map<String, Average> timings) { return modify(processId, process -> process.getState() != ProcessState.TERMINATED && process.getState() != ProcessState.STANDBY, process -> { process.setState(ProcessState.TERMINATED); process.setCompleted(LocalDateTime.now()); if (timings != null) { timings.forEach((key, avg) -> { process.getPerformanceCounters().put(key, (int) avg.getCount()); process.getTimings().put(key, (int) avg.getAvg()); }); } }); }

Target:
protected boolean markCompleted(String processId, @Nullable Map<String, Average> timings) { return modify(processId, process -> process.getState() != ProcessState.TERMINATED, process -> { if (process.getState() != ProcessState.STANDBY) { process.setState(ProcessState.TERMINATED); process.setCompleted(LocalDateTime.now()); } if (timings != null) { timings.forEach((key, avg) -> { process.getPerformanceCounters().put(key, (int) avg.getCount()); process.getTimings().put(key, (int) avg.getAvg()); }); } }); }
Source:
public ModelAndView heroRanking(@RequestParam(value = "tradingTime", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date tradingTime) { ModelAndView modelAndView = new ModelAndView("/hero-ranking"); if (tradingTime == null) { tradingTime = new Date(); } List<HeroRankingView> heroRankingViewReferrerList = investMapper.findHeroRankingByReferrer(tradingTime, 1, 10); List<HeroRankingView> heroRankingViewInvestList = heroRankingService.obtainHeroRanking(tradingTime); long avgInvestAmount = 0; for (HeroRankingView heroRankingView : heroRankingViewInvestList) { avgInvestAmount += heroRankingView.getSumAmount(); } modelAndView.addObject("tradingTime", tradingTime); modelAndView.addObject("heroRankingViewReferrerList", heroRankingViewReferrerList); modelAndView.addObject("heroRankingViewInvestList", heroRankingViewInvestList); modelAndView.addObject("avgInvestAmount", new BigDecimal(avgInvestAmount).divide(new BigDecimal(10)).setScale(0, RoundingMode.DOWN)); modelAndView.addObject("todayMysteriousPrizeDto",heroRankingService.obtainMysteriousPrizeDto(new DateTime().withTimeAtStartOfDay().toString("yyyy-MM-dd"))); modelAndView.addObject("tomorrowMysteriousPrizeDto",heroRankingService.obtainMysteriousPrizeDto(new DateTime().plusDays(1).withTimeAtStartOfDay().toString("yyyy-MM-dd"))); return modelAndView; }

Target:
public ModelAndView heroRanking(@RequestParam(value = "tradingTime", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") Date tradingTime) { ModelAndView modelAndView = new ModelAndView("/hero-ranking"); if (tradingTime == null) { tradingTime = new Date(); } List<HeroRankingView> heroRankingViewReferrerList = heroRankingService.obtainHeroRankingReferrer(tradingTime); List<HeroRankingView> heroRankingViewInvestList = heroRankingService.obtainHeroRanking(tradingTime); long avgInvestAmount = 0; for (HeroRankingView heroRankingView : heroRankingViewInvestList) { avgInvestAmount += heroRankingView.getSumAmount(); } modelAndView.addObject("tradingTime", tradingTime); modelAndView.addObject("heroRankingViewReferrerList", heroRankingViewReferrerList); modelAndView.addObject("heroRankingViewInvestList", heroRankingViewInvestList); modelAndView.addObject("avgInvestAmount", new BigDecimal(avgInvestAmount).divide(new BigDecimal(10)).setScale(0, RoundingMode.DOWN)); modelAndView.addObject("todayMysteriousPrizeDto",heroRankingService.obtainMysteriousPrizeDto(new DateTime().withTimeAtStartOfDay().toString("yyyy-MM-dd"))); modelAndView.addObject("tomorrowMysteriousPrizeDto",heroRankingService.obtainMysteriousPrizeDto(new DateTime().plusDays(1).withTimeAtStartOfDay().toString("yyyy-MM-dd"))); return modelAndView; }
Source:
public boolean verifyUser(String username, String password, ESClientVersionInfo clientVersionInfo) { try { final Optional<ESAuthenticationInformation> information = doVerifyUser(username, password, clientVersionInfo); if (!information.isPresent()) { ModelUtil.logWarning( MessageFormat.format(Messages.LoginService_VerifyUserTooManyFailedRequests, username, delay)); } return information.isPresent(); } catch (final AccessControlException ex) { return false; } }

Target:
public boolean verifyUser(String username, String password, ESClientVersionInfo clientVersionInfo) { try { final Optional<ESAuthenticationInformation> information = doVerifyUser(username, password, clientVersionInfo); if (!information.isPresent()) { ModelUtil.logWarning( MessageFormat.format(Messages.LoginService_VerifyUserTooManyFailedRequests, username, delay)); } return true; } catch (final AccessControlException ex) { return false; } }
Source:
private void initUnregisteredTemplate() { if (vmTemplateFromConfiguration == null) { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getVmTemplateId(), getParameters().getStorageDomainId()); if (!ovfEntityList.isEmpty()) { ovfEntityData = ovfEntityList.get(0); try { FullEntityOvfData fullEntityOvfData = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration = fullEntityOvfData.getVmTemplate(); setVmTemplate(vmTemplateFromConfiguration); images = fullEntityOvfData.getDiskImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception: ", e); } } } }

Target:
private void initUnregisteredTemplate() { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getVmTemplateId(), getParameters().getStorageDomainId()); if (!ovfEntityList.isEmpty()) { ovfEntityData = ovfEntityList.get(0); try { FullEntityOvfData fullEntityOvfData = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration = fullEntityOvfData.getVmTemplate(); setVmTemplate(vmTemplateFromConfiguration); images = fullEntityOvfData.getDiskImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception: ", e); } } }
Source:
public CloneProjectJobRequest cloneRepository(String spaceName, CloneProjectRequest cloneProjectRequest) { log.info("Creating new space '{}'", cloneProjectRequest.getName()); CloneProjectJobRequest request = target.path("/spaces/{spaceName}/git/clone") .resolveTemplate("spaceName", spaceName) .request() .post(createEntity(cloneProjectRequest), CloneProjectJobRequest.class); return waitUntilJobFinished(request, cloneRepoTimeoutSeconds); }

Target:
public CloneProjectJobRequest cloneRepository(String spaceName, CloneProjectRequest cloneProjectRequest) { log.info("Cloning a project '{}'", cloneProjectRequest.getName()); CloneProjectJobRequest request = target.path("/spaces/{spaceName}/git/clone") .resolveTemplate("spaceName", spaceName) .request() .post(createEntity(cloneProjectRequest), CloneProjectJobRequest.class); return waitUntilJobFinished(request, cloneRepoTimeoutSeconds); }
Source:
public void validateLinksWithGlobalConfig() { log.info("Navigate to '" + MODAL_DIALOG_CONFIG_MENU_BUTTON + "' and validate links with global config"); DefaultText dt = new DefaultText(); String localText = dt.getText(); log.debug("Text of global config:\n" + localText); ConfigPropertiesHelper rcph = new ConfigPropertiesHelper(localText); String majorVersion = getJbossToolsMajorVersion(); log.info("Major version: " + majorVersion); Arrays.stream(regexArray).forEach(regexRaw -> { String regex = regexRaw.replace("{majorVersion}", majorVersion); log.info("Validating local and remote config with regex: '" + regex + "'"); boolean result = rcph.isRegexValid(regex); assertTrue("Unable to match regex '" + regex + "' to either local or remote config with result: " + result, result); }); log.info("Finished: validateLinksWithGlobalConfig"); }

Target:
public void validateLinksWithGlobalConfig() { log.info("Navigate to '" + MODAL_DIALOG_CONFIG_MENU_BUTTON + "' and validate links with global config"); DefaultText dt = new DefaultText(installationDetails); String localText = dt.getText(); log.debug("Text of global config:\n" + localText); ConfigPropertiesHelper rcph = new ConfigPropertiesHelper(localText); String majorVersion = getJbossToolsMajorVersion(); log.info("Major version: " + majorVersion); Arrays.stream(regexArray).forEach(regexRaw -> { String regex = regexRaw.replace("{majorVersion}", majorVersion); log.info("Validating local and remote config with regex: '" + regex + "'"); boolean result = rcph.isRegexValid(regex); assertTrue("Unable to match regex '" + regex + "' to either local or remote config with result: " + result, result); }); log.info("Finished: validateLinksWithGlobalConfig"); }
Source:
public JandexClassFileServices(JandexDiscoveryStrategy strategy) { index = strategy.getCompositeJandexIndex(); if (index == null) { throw CommonLogger.LOG.jandexIndexNotCreated(ClassFileServices.class.getSimpleName()); } this.classLoader = WeldResourceLoader.getClassLoader(); this.annotationClassAnnotationsCache = ComputingCacheBuilder.newBuilder().build(new AnnotationClassAnnotationLoader()); try { Method setFlags = ClassFileInfo.class.getMethod("setFlags"); jandexStaticCheckAvailable = setFlags != null; } catch (NoSuchMethodException e) { jandexStaticCheckAvailable = false; CommonLogger.LOG.usingOldJandexVersion(); } }

Target:
public JandexClassFileServices(JandexDiscoveryStrategy strategy) { index = strategy.getCompositeJandexIndex(); if (index == null) { throw CommonLogger.LOG.jandexIndexNotCreated(ClassFileServices.class.getSimpleName()); } this.classLoader = WeldResourceLoader.getClassLoader(); this.annotationClassAnnotationsCache = ComputingCacheBuilder.newBuilder().build(new AnnotationClassAnnotationLoader()); }
Source:
public boolean isThereANeedToSetDefaultType(final InterpolationVariable newVar, final InterpolationVariable oldVar) { if (newVar.getDataType().equals(oldVar.getDataType()) && Objects.equals(newVar.getFactType(), oldVar.getFactType()) && Objects.equals(newVar.getFactField(), oldVar.getFactField())) { return false; } else { return true; } }

Target:
public boolean isThereANeedToSetDefaultType(final InterpolationVariable newVar, final InterpolationVariable oldVar) { if (Objects.equals(newVar.getDataType(), oldVar.getDataType()) && Objects.equals(newVar.getFactType(), oldVar.getFactType()) && Objects.equals(newVar.getFactField(), oldVar.getFactField())) { return false; } else { return true; } }
Source:
public int read() throws IOException { streamPos++; return 0; }

Target:
public int read() throws IOException { byte[] b = new byte[1]; read(b, 0, 1); return b[0]; }
Source:
public EquivalenceUpdatingWorker(ContentResolver contentResolver, LookupEntryStore entryStore, EquivalenceResultStore resultStore, EquivalenceUpdater<Content> equivUpdater, Predicate<Content> filter) { this.contentResolver = checkNotNull(contentResolver); this.entryStore = checkNotNull(entryStore); this.resultStore = checkNotNull(resultStore); this.equivUpdater = checkNotNull(equivUpdater); this.filter = checkNotNull(filter); this.telescopeProxy = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); }

Target:
public EquivalenceUpdatingWorker(ContentResolver contentResolver, LookupEntryStore entryStore, EquivalenceResultStore resultStore, EquivalenceUpdater<Content> equivUpdater, Predicate<Content> filter) { this.contentResolver = checkNotNull(contentResolver); this.entryStore = checkNotNull(entryStore); this.resultStore = checkNotNull(resultStore); this.equivUpdater = checkNotNull(equivUpdater); this.filter = checkNotNull(filter); }
Source:
public void getTest() throws SQLException { String userId = "test"; String classification = "test"; String itemId="test"; final State.Builder state = State.newBuilder(); state.setCompleted(true); state.setStarted(true); state.setGraded(true); IMocksControl control = createControl (); Connection conn = control.createMock (Connection. class); PreparedStatement st = control.createMock (PreparedStatement. class); ResultSet rs = control.createMock (ResultSet. class); final String query = "SELECT * FROM State WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; expect(conn.prepareStatement(query)).andReturn(st); st.setString(1, userId); st.setString(2, classification); st.setString(3, itemId); expect(st.executeQuery()).andReturn(rs); expect(rs.getBoolean("Completed")).andReturn(true); expect(rs.getBoolean("Started")).andReturn(true); expect(rs.getBoolean("Graded")).andReturn(true); st.close(); rs.close(); control.replay (); State res=null; try { res = SqlStateManager.getState(conn, userId, classification, itemId); } catch (DatabaseAccessException e) { } State expected = state.build(); assertEquals (expected, res); control.verify (); }

Target:
public void getTest() throws SQLException { String userId = "test"; String classification = "test"; String itemId="test"; final State.Builder state = State.newBuilder(); state.setCompleted(true); state.setStarted(true); state.setGraded(true); IMocksControl control = createControl (); Connection conn = control.createMock (Connection. class); PreparedStatement st = control.createMock (PreparedStatement. class); ResultSet rs = control.createMock (ResultSet. class); final String query = "SELECT * FROM State WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; expect(conn.prepareStatement(query)).andReturn(st); st.setString(1, userId); st.setString(2, classification); st.setString(3, itemId); expect(st.executeQuery()).andReturn(rs); expect(rs.getBoolean(DatabaseStringConstants.STATE_COMPLETED)).andReturn(true); expect(rs.getBoolean(DatabaseStringConstants.STATE_STARTED)).andReturn(true); expect(rs.getBoolean(DatabaseStringConstants.STATE_GRADED)).andReturn(true); st.close(); rs.close(); control.replay (); State res=null; try { res = SqlStateManager.getState(conn, userId, classification, itemId); } catch (DatabaseAccessException e) { } State expected = state.build(); assertEquals (expected, res); control.verify (); }
Source:
public List<Modification> modificationsSince(Revision revision) { return gitLog("--date=iso", "--pretty=medium", "--no-decorate", "--no-color", String.format("%s..%s", revision.getRevision(), remoteBranch())); }

Target:
public List<Modification> modificationsSince(Revision revision) { return gitLog("--date=iso", "--pretty=medium", "--no-color", String.format("%s..%s", revision.getRevision(), remoteBranch())); }