auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void loadTrace(ITmfTrace trace) { fTrace = trace; long timestamp = TmfTraceManager.getInstance().getSelectionBeginTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long windowStartTime = TmfTraceManager.getInstance().getCurrentRange().getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long windowEndTime = TmfTraceManager.getInstance().getCurrentRange().getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long windowDuration = windowEndTime - windowStartTime; long startTime = fTrace.getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long endTime = fTrace.getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); setSelectionBeginTime(timestamp); setSelectionEndTime(timestamp); setStartTime(startTime); setWindowStartTime(windowStartTime); setWindowEndTime(windowEndTime); setWindowDuration(windowDuration); setEndTime(endTime); }

Target:
public void loadTrace(ITmfTrace trace) { fTrace = trace; long timestamp = TmfTraceManager.getInstance().getSelectionBeginTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); TmfTimeRange currentRange = TmfTraceManager.getInstance().getCurrentRange(); long windowStartTime = currentRange.getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long windowEndTime = currentRange.getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long windowDuration = windowEndTime - windowStartTime; long startTime = fTrace.getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long endTime = fTrace.getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); setSelectionBeginTime(timestamp); setSelectionEndTime(timestamp); setStartTime(startTime); setWindowStartTime(windowStartTime); setWindowEndTime(windowEndTime); setWindowDuration(windowDuration); setEndTime(endTime); }
Source:
public void removeBlock(final String dataType, final int blockId) { final Map<Integer, Block> blocks = typeToBlocks.get(dataType); if (null == blocks) { LOG.log(Level.FINE, "Blocks are not initialized for type {0}", dataType); return; } final Block block = blocks.remove(blockId); if (null == block) { LOG.log(Level.SEVERE, "Block with id {0} does not exist.", blockId); throw new RuntimeException(); } }

Target:
public void removeBlock(final String dataType, final int blockId) { final Map<Integer, Block> blocks = typeToBlocks.get(dataType); if (null == blocks) { LOG.log(Level.FINE, "Blocks are not initialized for type {0}", dataType); return; } final Block block = blocks.remove(blockId); if (null == block) { throw new RuntimeException("Block with id " + blockId + "does not exist."); } }
Source:
public void after() throws Exception { try { bb.close(); } catch (Exception e) { } try { lp.close(); } catch (Exception e) { } try { builder.close(); } catch (Exception e) { } }

Target:
public void after() throws Exception { IO.close(bb); IO.close(lp); IO.close(builder); }
Source:
public void streamsFromTestFactoriesShouldBeClosed() throws NoSuchMethodException { testMethod = DynamicCloseHookedStreamTest.class.getMethod("customStream"); when(testExtensionContext.getTestMethod()).thenReturn(Optional.of(testMethod)); Stream<DynamicTest> stream = Stream.<DynamicTest> of().onClose(() -> isClosed = true); when(testExtensionContext.getTestInstance()).thenReturn(new DynamicCloseHookedStreamTest(stream)); TestFactoryTestDescriptor descriptor = new TestFactoryTestDescriptor(UniqueId.forEngine("engine"), DynamicCloseHookedStreamTest.class, testMethod); descriptor.invokeTestMethod(context); assertTrue(isClosed); }

Target:
void streamsFromTestFactoriesShouldBeClosed() throws NoSuchMethodException { testMethod = DynamicCloseHookedStreamTest.class.getMethod("customStream"); when(testExtensionContext.getTestMethod()).thenReturn(Optional.of(testMethod)); Stream<DynamicTest> stream = Stream.empty(); Stream<DynamicTest> onCloseStream = stream.onClose(() -> isClosed = true); when(testExtensionContext.getTestInstance()).thenReturn(new DynamicCloseHookedStreamTest(onCloseStream)); TestFactoryTestDescriptor descriptor = new TestFactoryTestDescriptor(UniqueId.forEngine("engine"), DynamicCloseHookedStreamTest.class, testMethod); descriptor.invokeTestMethod(context, mock(Node.DynamicTestExecutor.class)); assertTrue(isClosed); }
Source:
private I_M_HU createPlanningVHU(final I_M_ReceiptSchedule receiptSchedule) { final IAllocationRequest allocationRequest = createAllocationRequest(receiptSchedule); if (allocationRequest == null || allocationRequest.isZeroQty()) { return null; } huReceiptScheduleBL.setInitialAttributeValueDefaults(allocationRequest, ImmutableList.of(receiptSchedule)); final IAllocationSource allocationSource = huReceiptScheduleBL.createAllocationSource(receiptSchedule); final HUProducerDestination huProducer = HUProducerDestination.ofVirtualPI(); HULoader.of(allocationSource, huProducer) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .load(allocationRequest); final List<I_M_HU> hus = huProducer.getCreatedHUs(); if (hus == null || hus.size() != 1) { throw new HUException("One and only one VHU was expected but we got: " + hus); } final I_M_HU vhu = hus.get(0); setAttributeBBD(vhu, receiptSchedule); setAttributeLotNumber(vhu); InterfaceWrapperHelper.setTrxName(vhu, ITrx.TRXNAME_None); return vhu; }

Target:
private I_M_HU createPlanningVHU(final I_M_ReceiptSchedule receiptSchedule) { final IAllocationRequest allocationRequest = createAllocationRequest(receiptSchedule); if (allocationRequest == null || allocationRequest.isZeroQty()) { return null; } huReceiptScheduleBL.setInitialAttributeValueDefaults(allocationRequest, ImmutableList.of(receiptSchedule)); final IAllocationSource allocationSource = huReceiptScheduleBL.createAllocationSource(receiptSchedule); final HUProducerDestination huProducer = HUProducerDestination.ofVirtualPI(); HULoader.of(allocationSource, huProducer) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .load(allocationRequest); final List<I_M_HU> hus = huProducer.getCreatedHUs(); if (hus == null || hus.size() != 1) { throw new HUException("One and only one VHU was expected but we got: " + hus); } final I_M_HU vhu = hus.get(0); updateAttributes(vhu, receiptSchedule); InterfaceWrapperHelper.setTrxName(vhu, ITrx.TRXNAME_None); return vhu; }
Source:
public synchronized void releasePersistentLock() { if (lockId == null) { log.info("Called releasePersistentLock, but no lock has been taken! Returning."); return; } log.info("Releasing persistent lock {}", lockId); try { persistentLockService.releaseBackupLock(lockId); lockId = null; } catch (CheckAndSetException e) { log.error("Failed to release persistent lock {}. The lock must have been released from under us. " + "If you didn't release it manually, this warrants investigation, but future sweeps " + "should correctly be able to re-acquire the lock.", SafeArg.of("lock id", lockId), e); lockId = null; } }

Target:
public synchronized void releasePersistentLock() { if (lockId == null) { log.info("Called releasePersistentLock, but no lock has been taken! Returning."); return; } log.info("Releasing persistent lock {}", SafeArg.of("lockId", lockId)); try { persistentLockService.releaseBackupLock(lockId); lockId = null; } catch (CheckAndSetException e) { log.error("Failed to release persistent lock {}. The lock must have been released from under us. " + "Future sweeps should correctly be able to re-acquire the lock.", SafeArg.of("lockId", lockId), e); lockId = null; } }
Source:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (fIsFlatViewClicked) { setTraceEntryChildren(fHierarchicalList); fIsFlatViewClicked = false; } } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_HIERARCHICAL_VIEW)); return action; }

Target:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (fIsFlatViewClicked) { ITmfTrace parentTrace = getTrace(); for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) { final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); List<ControlFlowEntry> currentRootList = (List<ControlFlowEntry>)(Object)getEntryList(ss); addEntriesToHierarchicalTree(currentRootList, parentTrace, ss); } fIsFlatViewClicked = false; refresh(); } } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_HIERARCHICAL_VIEW)); return action; }
Source:
private void checkIsNullEstimation(Map<String, Object> bug, Issue issue) { Double estimatedTime = (Double) bug.get(ESTIMATED_TIME); Double hoursWorked = (Double) bug.get(HOURS_WORKED); if (estimatedTime != null && hoursWorked != null) { issue.setEstimation(new IssueEstimation(estimatedTime, hoursWorked)); } if (estimatedTime != null && hoursWorked == null) { issue.setEstimation(new IssueEstimation(estimatedTime)); } }

Target:
private void checkIsNullEstimation(Map<String, Object> bug, Issue issue) { Double estimatedTime = (Double) bug.get(ESTIMATED_TIME); Double hoursWorked = (Double) bug.get(HOURS_WORKED); if (estimatedTime != null && hoursWorked != null) { issue.setEstimation(new IssueEstimation(estimatedTime, hoursWorked)); } else if (estimatedTime != null) { issue.setEstimation(new IssueEstimation(estimatedTime)); } }
Source:
protected String fireEMRJob(String paramsStr,String clusterId){ StepFactory stepFactory = new StepFactory(); AmazonElasticMapReduceClient emr = new AmazonElasticMapReduceClient(); emr.setRegion(Region.getRegion(Regions.US_EAST_1)); Application sparkConfig = new Application() .withName("Spark"); String[] params = paramsStr.split(","); StepConfig enabledebugging = new StepConfig() .withName("Enable debugging") .withActionOnFailure("TERMINATE_JOB_FLOW") .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); HadoopJarStepConfig sparkStepConf = new HadoopJarStepConfig() .withJar("command-runner.jar") .withArgs(params); final StepConfig sparkStep = new StepConfig() .withName("Spark Step") .withActionOnFailure("CONTINUE") .withHadoopJarStep(sparkStepConf); AddJobFlowStepsRequest request = new AddJobFlowStepsRequest(clusterId) .withSteps(new ArrayList<StepConfig>(){{add(sparkStep);}}); AddJobFlowStepsResult result = emr.addJobFlowSteps(request); return result.getStepIds().get(0); }

Target:
protected String fireEMRJob(String paramsStr,String clusterId){ StepFactory stepFactory = new StepFactory(); AmazonElasticMapReduceClient emr = new AmazonElasticMapReduceClient(); emr.setRegion(Region.getRegion(Regions.fromName(System.getenv().get("AWS_REGION")))); Application sparkConfig = new Application() .withName("Spark"); String[] params = paramsStr.split(","); StepConfig enabledebugging = new StepConfig() .withName("Enable debugging") .withActionOnFailure("TERMINATE_JOB_FLOW") .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); HadoopJarStepConfig sparkStepConf = new HadoopJarStepConfig() .withJar("command-runner.jar") .withArgs(params); final StepConfig sparkStep = new StepConfig() .withName("Spark Step") .withActionOnFailure("CONTINUE") .withHadoopJarStep(sparkStepConf); AddJobFlowStepsRequest request = new AddJobFlowStepsRequest(clusterId) .withSteps(new ArrayList<StepConfig>(){{add(sparkStep);}}); AddJobFlowStepsResult result = emr.addJobFlowSteps(request); return result.getStepIds().get(0); }
Source:
private void doFullTextSearch(final String searchTerm, final Map<String, String> continueOffset, final boolean clearOnSuccess) { final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(Observable.zip(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).fullTextSearch(searchTerm, BATCH_SIZE, continueOffset != null ? continueOffset.get("continue") : null, continueOffset != null ? continueOffset.get("gsroffset") : null), Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageForSearchQueryInAnyList(currentSearchTerm)), Observable.fromCallable(() -> HistoryDbHelper.INSTANCE.findHistoryItem(currentSearchTerm)), (searchResponse, readingListSearchResults, historySearchResults) -> { SearchResults searchResults; if (searchResponse.query() != null) { searchResults = new SearchResults(searchResponse.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), searchResponse.continuation(), null); } else { searchResults = new SearchResults(); } SearchResultsFragment.this.lastFullTextResults = searchResults; List<SearchResult> resultList = new ArrayList<>(searchResults.getResults()); resultList.addAll(readingListSearchResults.getResults()); resultList.addAll(historySearchResults.getResults()); addSearchResultsFromTabs(resultList); return resultList; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate(() -> updateProgressBar(false)) .subscribe(resultList -> { cache(resultList, searchTerm); log(resultList, startTime); if (clearOnSuccess) { clearResults(false); } searchErrorView.setVisibility(GONE); displayResults(resultList); }, throwable -> { logError(true, startTime); })); }

Target:
private void doFullTextSearch(final String searchTerm, final Map<String, String> continueOffset, final boolean clearOnSuccess) { final long startTime = System.nanoTime(); updateProgressBar(true); disposables.add(ServiceFactory.get(WikiSite.forLanguageCode(getSearchLanguageCode())).fullTextSearch(searchTerm, BATCH_SIZE, continueOffset != null ? continueOffset.get("continue") : null, continueOffset != null ? continueOffset.get("gsroffset") : null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response.query() != null) { return new SearchResults(response.query().pages(), WikiSite.forLanguageCode(getSearchLanguageCode()), response.continuation(), null); } return new SearchResults(); }) .doAfterTerminate(() -> updateProgressBar(false)) .subscribe(results -> { List<SearchResult> resultList = results.getResults(); cache(resultList, searchTerm); log(resultList, startTime); if (clearOnSuccess) { clearResults(false); } searchErrorView.setVisibility(View.GONE); SearchResultsFragment.this.lastFullTextResults = results; displayResults(resultList); }, throwable -> { logError(true, startTime); })); }
Source:
boolean isSettingProperty(ProgramState state, ExpressionTree arg0, XxeProperty property) { if (arg0.asConstant(String.class).filter(property.propertyName()::equals).isPresent()) { return true; } ConstraintsByDomain constraintsByDomain = state.getConstraints(state.peekValue(1)); return constraintsByDomain != null && constraintsByDomain.hasConstraint(property.namedConstraint()); }

Target:
boolean isSettingProperty(ProgramState state, ExpressionTree arg0, XxeProperty property) { if (arg0.asConstant(String.class).filter(property::isNamed).isPresent()) { return true; } ConstraintsByDomain constraintsByDomain = state.getConstraints(state.peekValue(1)); return constraintsByDomain != null && constraintsByDomain.hasConstraint(property.namedConstraint()); }
Source:
public String toString() { StringBuilder sb = new StringBuilder("Int128ArrayBlockEncodingBuffer{"); sb.append("valuesBufferCapacity=").append(valuesBuffer == null ? 0 : valuesBuffer.length).append(","); sb.append("valuesBufferIndex=").append(valuesBufferIndex).append("}"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("{"); sb.append("valuesBufferCapacity=").append(valuesBuffer == null ? 0 : valuesBuffer.length).append(","); sb.append("valuesBufferIndex=").append(valuesBufferIndex).append("}"); return sb.toString(); }
Source:
private boolean networkRequiredOnVds(VmNetworkInterface vmIface, Map<String, Network> networksByName, boolean onlyRequiredNetworks) { boolean networkRequiredOnVds = true; if (!vmIface.isPlugged()) { networkRequiredOnVds = false; } else if (onlyRequiredNetworks) { Network network = networksByName.get(vmIface.getNetworkName()); networkRequiredOnVds = network.getCluster().isRequired() && network.isVmNetwork(); } return networkRequiredOnVds; }

Target:
private boolean networkRequiredOnVds(VmNetworkInterface vmIface, Map<String, Network> networksByName, boolean onlyRequiredNetworks) { boolean networkRequiredOnVds = true; if (!vmIface.isPlugged()) { networkRequiredOnVds = false; } else if (onlyRequiredNetworks) { networkRequiredOnVds = networksByName.get(vmIface.getNetworkName()).getCluster().isRequired(); } return networkRequiredOnVds; }
Source:
public LoveFilmData getLatestData() throws FetchException { try { S3Service service = serviceSupplier.get(); S3Object[] objects = service.listObjects(bucketName, folder, NO_DELIMITER); S3Object file = getFileforName(objects); if (file != null) { InputSupplier<InputStream> in = inputStreamFor(service, file); return new LoveFilmData(CharStreams.newReaderSupplier(in, Charsets.UTF_8)); } throw new FetchException(String.format("No data file in %s/%s", bucketName, folder)); } catch (ServiceException e) { throw new FetchException(e.getMessage(), e); } }

Target:
public LoveFilmData getLatestData() throws FetchException { try { S3Service service = serviceSupplier.get(); S3Object[] objects = service.listObjects(bucketName, folder, NO_DELIMITER); S3Object file = getFileforName(objects); if (file == null) { throw new FetchException(String.format("No data file in %s/%s", bucketName, folder)); } InputSupplier<InputStream> in = inputStreamFor(service, file); return new LoveFilmData(CharStreams.newReaderSupplier(in, Charsets.UTF_8)); } catch (ServiceException e) { throw new FetchException(e.getMessage(), e); } }
Source:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); if(extensionRegisters != null && extensionRegisters.size() > 0) this.extensionRegisters.addAll(extensionRegisters); }

Target:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); if ( !extensionRegisters.isEmpty() ) { this.extensionRegisters.addAll(extensionRegisters); } }
Source:
private List<PhoenixQueryServerNode> conductSanityCheckAndReturn() throws Exception{ Preconditions.checkNotNull(curaFramework ," curator framework in not initialized "); Preconditions.checkNotNull(cache," cache value is not initialized"); boolean connected = curaFramework.getZookeeperClient().isConnected(); if (!connected) { String message = " Zookeeper seems to be down. The data is stale "; Exception exception = new Exception(message); LOG.error(message, exception); throw exception; } List<String> currentNodes = curaFramework.getChildren().forPath(CONFIG.getParentPath()); List<PhoenixQueryServerNode> returnNodes = new ArrayList<>(); for(String node:currentNodes) { byte[] bytes = curaFramework.getData().forPath(CONFIG.getParentPath() + "/" + node); returnNodes.add(PhoenixQueryServerNode.fromJsonString(new String( bytes, StandardCharsets.UTF_8))); } return returnNodes; }

Target:
private List<HostAndPort> conductSanityCheckAndReturn() throws Exception{ Preconditions.checkNotNull(curaFramework ," curator framework in not initialized "); Preconditions.checkNotNull(cache," cache value is not initialized"); boolean connected = curaFramework.getZookeeperClient().isConnected(); if (!connected) { String message = " Zookeeper seems to be down. The data is stale "; ConnectException exception = new ConnectException(message); LOG.error(message, exception); throw exception; } List<String> currentNodes = curaFramework.getChildren().forPath(CONFIG.getParentPath()); List<HostAndPort> returnNodes = new ArrayList<>(); String nodeAsString = null; for(String node:currentNodes) { try { returnNodes.add(HostAndPort.fromString(node)); } catch(Throwable ex) { LOG.error(" something wrong with node string "+nodeAsString,ex); } } return returnNodes; }
Source:
protected GCSBatchSink(GCSSinkConfig config) { super(config); this.config = config; if (!this.config.containsMacro("fileSystemProperties") && !this.config.containsMacro("JsonKeyFile") && !this.config.containsMacro("ProjectId")) { this.config.fileSystemProperties = updateFileSystemProperties(this.config.fileSystemProperties, this.config.projectId, this.config.jsonKey); } }

Target:
protected GCSBatchSink(GCSSinkConfig config) { super(config); this.config = config; if (!this.config.containsMacro("fileSystemProperties") && !this.config.containsMacro("jsonKeyFile") && !this.config.containsMacro("projectId")) { this.config.fileSystemProperties = this.config.getFileSystemProperties(this.config.fileSystemProperties, this.config.projectId, this.config.jsonKeyFile); } }
Source:
public void testGetAllStoreSomeMatchLoaderSomeMatchDisjointFailWithBulkCacheLoadingException() throws Exception { final FakeStore fakeStore = new FakeStore(getEntryMap(KEY_SET_A, KEY_SET_B)); this.store = spy(fakeStore); final FakeCacheLoaderWriter fakeLoader = new FakeCacheLoaderWriter(getEntryMap(KEY_SET_E, KEY_SET_E), KEY_SET_C, true); this.loaderWriter = spy(fakeLoader); final Ehcache<String, String> ehcache = this.getEhcache(this.loaderWriter); final Set<String> fetchKeys = fanIn(KEY_SET_A, KEY_SET_C, KEY_SET_D, KEY_SET_F); try { ehcache.getAll(fetchKeys); fail(); } catch (BulkCacheLoadingException e) { assertThat(e.getSuccesses(), Matchers.<Map<?,?>>equalTo(union(getEntryMap(KEY_SET_A), getNullEntryMap(KEY_SET_C)))); assertThat(e.getFailures().keySet(), Matchers.<Set<?>>equalTo(union(KEY_SET_D, KEY_SET_F))); } verify(this.store).bulkComputeIfAbsent(eq(fetchKeys), getAnyIterableFunction()); assertThat(fakeStore.getEntryMap(), equalTo(getEntryMap(KEY_SET_A, KEY_SET_B))); verify(this.loaderWriter, atLeast(1)).loadAll(this.loadAllCaptor.capture()); assertThat(this.getLoadAllArgs(), equalTo(copyWithout(fetchKeys, KEY_SET_A))); verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); }

Target:
public void testGetAllStoreSomeMatchLoaderSomeMatchDisjointFailWithBulkCacheLoadingException() throws Exception { final FakeStore fakeStore = new FakeStore(getEntryMap(KEY_SET_A, KEY_SET_B)); this.store = spy(fakeStore); final FakeCacheLoaderWriter fakeLoader = new FakeCacheLoaderWriter(TEST_ENTRIES, union(KEY_SET_D, KEY_SET_F), true); this.loaderWriter = spy(fakeLoader); final Ehcache<String, String> ehcache = this.getEhcache(this.loaderWriter); final Set<String> fetchKeys = fanIn(KEY_SET_A, KEY_SET_C, KEY_SET_D, KEY_SET_F); try { ehcache.getAll(fetchKeys); fail(); } catch (BulkCacheLoadingException e) { assertThat(e.getSuccesses(), Matchers.<Map<?,?>>equalTo(union(getEntryMap(KEY_SET_A), getNullEntryMap(KEY_SET_C)))); assertThat(e.getFailures().keySet(), Matchers.<Set<?>>equalTo(union(KEY_SET_D, KEY_SET_F))); } verify(this.store).bulkComputeIfAbsent(eq(fetchKeys), getAnyIterableFunction()); assertThat(fakeStore.getEntryMap(), equalTo(getEntryMap(KEY_SET_A, KEY_SET_B))); verify(this.loaderWriter, atLeast(1)).loadAll(this.loadAllCaptor.capture()); assertThat(this.getLoadAllArgs(), equalTo(copyWithout(fetchKeys, KEY_SET_A))); verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); }
Source:
public FileResponse readFile(String fileName, String reference) { FileResponse cwl = new FileResponse(); try { Repository repo = service.getRepository(gitUsername, gitRepository); List<RepositoryContents> contents; try { contents = checkNotNull(cService.getContents(repo, fileName, reference)); } catch (Exception e) { contents = checkNotNull(cService.getContents(repo, fileName.toLowerCase(), reference)); } if (!(contents == null || contents.isEmpty())) { String encoded = contents.get(0).getContent().replace("\n", ""); byte[] decode = Base64.getDecoder().decode(encoded); String content = new String(decode, StandardCharsets.UTF_8); cwl.setContent(content); } else { return null; } } catch (IOException e) { LOG.error(e.getMessage()); return null; } return cwl; }

Target:
public FileResponse readFile(String fileName, String reference) { FileResponse cwl = new FileResponse(); checkNotNull(fileName, "The fileName given is null."); try { Repository repo = service.getRepository(gitUsername, gitRepository); List<RepositoryContents> contents; try { contents = cService.getContents(repo, fileName, reference); } catch (Exception e) { contents = cService.getContents(repo, fileName.toLowerCase(), reference); } if (!(contents == null || contents.isEmpty())) { String encoded = contents.get(0).getContent().replace("\n", ""); byte[] decode = Base64.getDecoder().decode(encoded); String content = new String(decode, StandardCharsets.UTF_8); cwl.setContent(content); } else { return null; } } catch (IOException e) { LOG.error(e.getMessage()); return null; } return cwl; }
Source:
void addFirst (RunnableLock[] toAdd, int numToAdd) { if (numToAdd == 0) { return; } boolean wake = false; synchronized (messageLock) { int nextSize = messageCount + Math.max(numToAdd, GROW_SIZE); if (messages == null) messages = new RunnableLock[nextSize]; if (messages.length < messageCount + numToAdd) { RunnableLock[] newMessages = new RunnableLock[nextSize]; System.arraycopy(messages, 0, newMessages, numToAdd, messageCount); messages = newMessages; } else { System.arraycopy(messages, 0, messages, numToAdd, messageCount); } System.arraycopy(toAdd, 0, messages, 0, numToAdd); wake = (messageCount == 0); messageCount += numToAdd; } if (wake) display.wakeThread(); }

Target:
void addFirst (RunnableLock[] toAdd, int numToAdd) { if (numToAdd <= 0) { return; } boolean wake = false; synchronized (messageLock) { int nextSize = messageCount + Math.max(numToAdd, GROW_SIZE); if (messages == null) messages = new RunnableLock[nextSize]; if (messages.length < messageCount + numToAdd) { RunnableLock[] newMessages = new RunnableLock[nextSize]; System.arraycopy(messages, 0, newMessages, numToAdd, messageCount); messages = newMessages; } else { System.arraycopy(messages, 0, messages, numToAdd, messageCount); } System.arraycopy(toAdd, 0, messages, 0, numToAdd); wake = (messageCount == 0); messageCount += numToAdd; } if (wake) display.wakeThread(); }
Source:
public void post(JSONObject json) { post(json.toString(), null); }

Target:
public void post(JSONObject json) { post(json, null); }
Source:
public Response importTenantTheme(InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { String errorMessage = "Super Tenant " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME + " is not allowed to import a tenant theme"; throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_NOT_ALLOWED, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); } try { RestApiAdminUtils.importTenantTheme(fileInputStream, tenantDomain); return Response.status(Response.Status.OK).entity("Theme imported successfully").build(); } catch (IOException e) { throw new APIManagementException(e.getMessage(), ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, e.getMessage())); } }

Target:
public Response importTenantTheme(InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { String errorMessage = "Super Tenant " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME + " is not allowed to import a tenant theme"; throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_NOT_ALLOWED, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); } try { RestApiAdminUtils.importTenantTheme(fileInputStream, tenantDomain); return Response.status(Response.Status.OK).entity("Theme imported successfully").build(); } catch (IOException e) { throw new APIManagementException(e.getMessage(), e, ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, e.getMessage())); } }
Source:
public void readOnly_initialTransaction_throws() { RealmConfiguration.Builder config = new RealmConfiguration.Builder(); config = config.assetFile("foo", true); try { config.initialData(null); } catch (IllegalStateException ignored) { } config = new RealmConfiguration.Builder(); config.initialData(null); try { config = config.assetFile("foo", true); } catch (IllegalStateException ignored) { } }

Target:
public void readOnly_initialTransaction_throws() { RealmConfiguration.Builder config = new RealmConfiguration.Builder() .assetFile("foo") .readOnly() .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { } }); try { config.build(); fail(); } catch (IllegalStateException ignored) { } }
Source:
public void testOnLibraryContextSwitchEvent() { LibraryContextSwitchEvent event = mock( LibraryContextSwitchEvent.class ); BaseViewPresenter spy = spy( presenter ); when( event.isProjectSelected() ).thenReturn( true ); when( event.getUri() ).thenReturn( "uri" ); doNothing().when( spy ).setupActiveContextFor( any() ); spy.onLibraryContextSwitchEvent( event ); verify( placeManager ).goTo( BaseViewPresenter.PROJECT_SCREEN ); verify( placeManager ).goTo( BaseViewPresenter.PROJECT_SCREEN ); verify( spy ).setupActiveContextFor( any() ); }

Target:
public void testOnLibraryContextSwitchEvent() { LibraryContextSwitchEvent event = mock( LibraryContextSwitchEvent.class ); BaseViewPresenter spy = spy( presenter ); when( event.isProjectSelected() ).thenReturn( true ); when( event.getUri() ).thenReturn( "uri" ); doNothing().when( spy ).setupActiveContextFor( any() ); spy.onLibraryContextSwitchEvent( event ); verify( placeManager ).goTo( BaseViewPresenter.PROJECT_SCREEN ); verify( spy ).setupActiveContextFor( any() ); }
Source:
protected Bitmap doInBackground(String... params) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPurgeable = true; opt.inPreferQualityOverSpeed = false; opt.inSampleSize = 1; Bitmap bitmap = null; if(isCancelled()) { return bitmap; } opt.inJustDecodeBounds = true; BitmapFactory.decodeFile(params[0], opt); while(opt.outHeight > MaxTextureSize || opt.outWidth > MaxTextureSize) { opt.inSampleSize++; BitmapFactory.decodeFile(params[0], opt); } opt.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(params[0], opt); return bitmap; }

Target:
protected Bitmap doInBackground(String... params) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPurgeable = true; opt.inPreferQualityOverSpeed = false; opt.inSampleSize = 1; Bitmap bitmap = null; if(isCancelled()) { return bitmap; } opt.inJustDecodeBounds = true; BitmapFactory.decodeFile(params[0], opt); while(opt.outHeight > MaxTextureSize || opt.outWidth > MaxTextureSize) { opt.inSampleSize++; BitmapFactory.decodeFile(params[0], opt); } opt.inJustDecodeBounds = false; return BitmapFactory.decodeFile(params[0], opt); }
Source:
public String[] getTraceNames() { Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(fTrace); String[] traceNames = new String[traces.size()]; int i = 0; for (ITmfTrace tr : traces) { traceNames[i] = tr.getName(); i++; } return traceNames; }

Target:
public String[] getTraceNames() { FluentIterable<ITmfTrace> traces = FluentIterable.from(TmfTraceManager.getTraceSet(fTrace)); FluentIterable<String> traceNames = traces.transform(new Function<ITmfTrace, String>() { @Override public String apply(ITmfTrace input) { return input.getName(); } }); return traceNames.toArray(String.class); }
Source:
protected boolean containsLinkedResources() { for (IPackageFragmentRoot fPackageFragmentRoot : fPackageFragmentRoots) { if (fPackageFragmentRoot.getResource().isLinked()) { return true; } } return false; }

Target:
protected boolean containsLinkedResources() { for (IPackageFragmentRoot root : fPackageFragmentRoots) { if (root.getResource().isLinked()) { return true; } } return false; }
Source:
public static Response blob(Blob blob, int httpStatus) { String type = blob.getMimeType(); if (type == null || "???".equals(type)) { type = MediaType.APPLICATION_OCTET_STREAM; } Response response = Response.status(httpStatus) .entity(blob) .type(type) .header("Content-Disposition", "attachment; filename=" + blob.getFilename()) .build(); if (blob.getEncoding() != null) { List<Object> contentType = new ArrayList<Object>(); contentType.add(type + "; charset=" + blob.getEncoding()); response.getMetadata().put("Content-Type", contentType); } return response; }

Target:
public static Response blob(Blob blob, int httpStatus) { String type = blob.getMimeType(); if (type == null || "???".equals(type)) { type = MediaType.APPLICATION_OCTET_STREAM; } if (blob.getEncoding() != null) { type += "; charset=" + blob.getEncoding(); } return Response.status(httpStatus) .entity(blob) .type(type) .header("Content-Disposition", "attachment; filename=" + blob.getFilename()) .build(); }
Source:
public void connectionDown() { for (Object listenerObject : coordinateListenerList.toArray()) { CoordinateListener coordinateListener = (CoordinateListener) listenerObject; coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); }

Target:
public void connectionDown() { for (CoordinateListener coordinateListener : coordinateListenerList) { coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); }
Source:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }

Target:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
public void skipColumn(Key curCol) throws IOException { source.next(); int count = 0; while (source.hasTop() && curCol.equals(source.getTopKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) { if (count == 10) { Key seekKey = curCol.followingKey(PartialKey.ROW_COLFAM_COLQUAL_COLVIS); Range newRange; if (range.afterEndKey(seekKey)) { newRange = new Range(range.getEndKey(), true, range.getEndKey(), range.isEndKeyInclusive()); } else { newRange = new Range(seekKey, true, range.getEndKey(), range.isEndKeyInclusive()); } seek(newRange); break; } source.next(); count++; } }

Target:
public void skipColumn(Key curCol) throws IOException { source.next(); int count = 0; while (source.hasTop() && curCol.equals(source.getTopKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) { if (count == 10) { Key seekKey = curCol.followingKey(PartialKey.ROW_COLFAM_COLQUAL_COLVIS); Range newRange; if (range.afterEndKey(seekKey)) { newRange = new Range(range.getEndKey(), true, range.getEndKey(), false); } else { newRange = new Range(seekKey, true, range.getEndKey(), range.isEndKeyInclusive()); } seek(newRange); break; } source.next(); count++; } }
Source:
public LocalizationUtils(final String fileName) { log.info("Start initializing {}", getClass().getSimpleName()); messageSource = fileName.replaceAll("\\.properties$", ""); resourceBundlesByLocale = new ConcurrentHashMap<>(); getResourceBundle(Locale.getDefault()); log.info("Finished initializing {}", getClass().getSimpleName()); }

Target:
public LocalizationUtils(final String fileName) { log.info("Start initializing {}", getClass().getSimpleName()); messageSource = fileName.replaceAll("\\.properties$", ""); resourceBundlesByLocale = new ConcurrentHashMap<>(); defaultResourceBundle = loadResourceBundle(Locale.getDefault()); if (defaultResourceBundle == null) { defaultResourceBundle = loadResourceBundle(Locale.US); } log.info("Finished initializing {}", getClass().getSimpleName()); }
Source:
public void provision(E env, KubernetesNamespace namespace) throws InfrastructureException { LabelSelector selector = new LabelSelectorBuilder().withMatchLabels(secretLabels).build(); for (Secret secret : namespace.secrets().get(selector)) { boolean mountAsEnv = parseBoolean( secret.getMetadata().getAnnotations().getOrDefault("useSecretAsEnv", "false")); String targetContainerName = secret.getMetadata().getAnnotations().get("targetContainer"); if (mountAsEnv) { mountAsEnv(env, secret, targetContainerName); } else { mountAsFile(env, secret, targetContainerName); } } }

Target:
public void provision(E env, KubernetesNamespace namespace) throws InfrastructureException { LabelSelector selector = new LabelSelectorBuilder().withMatchLabels(secretLabels).build(); for (Secret secret : namespace.secrets().get(selector)) { String targetContainerName = secret.getMetadata().getAnnotations().get(ANNOTATION_TARGET_CONTAINER); String mountType = secret.getMetadata().getAnnotations().get(ANNOTATION_MOUNT_AS); if ("env".equalsIgnoreCase(mountType)) { mountAsEnv(env, secret, targetContainerName); } else if ("file".equalsIgnoreCase(mountType)) { mountAsFile(env, secret, targetContainerName); } else { throw new InfrastructureException( format( "Unable to mount secret '%s': it has missing or unknown type of the mount. Please make sure that '%s' annotation has value either 'env' or 'file'.", secret.getMetadata().getName(), ANNOTATION_MOUNT_AS)); } } }
Source:
private void listen() { try { socket = new ServerSocket(PORT); logger.info("Language Server running on port {}", PORT); while (!socket.isClosed()) { logger.debug("Going to wait for a client to connect"); try { Socket client = socket.accept(); new Thread(() -> { handleConnection(client); }, "Client " + client.getRemoteSocketAddress()).start(); } catch (IOException e) { logger.error("Error accepting the client connection", e); } } } catch (IOException e) { logger.error("Error starting the Language Server", e); } }

Target:
private void listen() { try { socket = new ServerSocket(PORT); logger.info("Language Server started on port {}", PORT); while (!socket.isClosed()) { logger.debug("Going to wait for a client to connect"); try { Socket client = socket.accept(); new Thread(() -> { handleConnection(client); }, "Client " + client.getRemoteSocketAddress()).start(); } catch (IOException e) { logger.error("Error accepting the client connection", e); } } } catch (IOException e) { logger.error("Error starting the Language Server", e); } }
Source:
public void removeXAResourceRecoveryHelper(XAResourceRecoveryHelper xaResourceRecoveryHelper) { scanStateLock.lock(); try { waitForNotScanState(ScanStates.FIRST_PASS); if (!getScanState().equals(ScanStates.IDLE)) { if (isHelperInUse(xaResourceRecoveryHelper)) { waitForScanState(ScanStates.IDLE); } else { scanStateLock.unlock(); synchronized (this) { scanStateLock.lock(); if (getScanState().equals(ScanStates.BETWEEN_PASSES)) { XAResource[] xaResources = recoveryHelpersXAResource.get(xaResourceRecoveryHelper); if (xaResources != null) { for (XAResource xar : xaResources) { xaRecoverySecondPass(xar); _resources.remove(xar); } } else { jtaLogger.logger.debugf("nothing to remove - xa resources of recovery helper '%s' were null", xaResourceRecoveryHelper); } } } } } _xaResourceRecoveryHelpers.remove(xaResourceRecoveryHelper); } finally { scanStateLock.unlock(); } }

Target:
public synchronized void removeXAResourceRecoveryHelper(XAResourceRecoveryHelper xaResourceRecoveryHelper) { switch (getScanState()) { case FIRST_PASS: waitForNotScanState(ScanStates.FIRST_PASS); this.removeXAResourceRecoveryHelper(xaResourceRecoveryHelper); return; case SECOND_PASS: if (isHelperInUse(xaResourceRecoveryHelper)) { waitForScanState(ScanStates.IDLE); this.removeXAResourceRecoveryHelper(xaResourceRecoveryHelper); return; } break; case BETWEEN_PASSES: if (isHelperInUse(xaResourceRecoveryHelper)) { waitForScanState(ScanStates.IDLE); this.removeXAResourceRecoveryHelper(xaResourceRecoveryHelper); return; } XAResource[] xaResources = recoveryHelpersXAResource.get(xaResourceRecoveryHelper); if (xaResources != null) { for (XAResource xar : xaResources) { xaRecoverySecondPass(xar); _resources.remove(xar); } } else { jtaLogger.logger.debugf("nothing to remove - xa resources of recovery helper '%s' were null", xaResourceRecoveryHelper); } break; case IDLE: break; } _xaResourceRecoveryHelpers.remove(xaResourceRecoveryHelper); }
Source:
public boolean areActiveCommands() { return (this.activeCommandList.size() > 0) || (this.commandStream != null && this.commandStream.getNumRowsRemaining() > 0) || nextCommand != null; }

Target:
public boolean areActiveCommands() { return numActiveCommands() > 0; }
Source:
public void execute() throws ExecutionException, InterruptedException { final DefaultAddDiscountCodeFormData addDiscountFormData = new DefaultAddDiscountCodeFormData(); addDiscountFormData.setCode(DISCOUNT_CODE); when: { when(hookRunner.runUnaryOperatorHook(any(), any(), cartUpdateCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(hookRunner.runActionHook(any(), any(), any())) .thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(2))); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(cart)); } final Cart updatedCart = defaultAddDiscountCodeControllerAction.apply(cart, addDiscountFormData) .toCompletableFuture().get(); then: { assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()).hasSize(1); final UpdateAction<Cart> cartUpdateAction = cartUpdateCommand.getUpdateActions().get(0); assertThat(cartUpdateAction).isInstanceOf(AddDiscountCode.class); final AddDiscountCode addDiscountCode = (AddDiscountCode) cartUpdateAction; assertThat(addDiscountCode.getCode()).isEqualTo(DISCOUNT_CODE); } }

Target:
public void execute() throws ExecutionException, InterruptedException { final DefaultAddDiscountCodeFormData addDiscountFormData = new DefaultAddDiscountCodeFormData(); addDiscountFormData.setCode(DISCOUNT_CODE); mockHookRunnerThatReturnsCart(); mockSphereClientThatReturnsCart(); final Cart updatedCart = defaultAddDiscountCodeControllerAction.apply(cart, addDiscountFormData) .toCompletableFuture().get(); assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()) .hasSize(1) .hasOnlyElementsOfType(AddDiscountCode.class); final AddDiscountCode addDiscountCode = (AddDiscountCode) cartUpdateCommand.getUpdateActions().get(0); assertThat(addDiscountCode.getCode()).isEqualTo(DISCOUNT_CODE); }
Source:
public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https://<RESOURCE_NAME>.communication.azure.com"; String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); CommunicationClientCredential credential = new CommunicationClientCredential(accessToken); HttpPipelinePolicy hmacAuthenticationPolicy = new HmacAuthenticationPolicy(credential); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(credential) .addPolicy(hmacAuthenticationPolicy) .httpClient(httpClient) .buildClient(); return phoneNumberClient; }

Target:
public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https://<RESOURCE_NAME>.communication.azure.com"; String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return phoneNumberClient; }
Source:
public void run() { while (true) { if (shutdown) { return; } try { Thread.sleep(sleepMs); } catch (InterruptedException e) { LOG.error("Sleep interrupted", e); continue; } try { purgeMetrics(); } catch (MetricException e) { LOG.error("Failed to purge metrics", e); if (this.failureMeter != null) { this.failureMeter.mark(); } } } }

Target:
public void run() { while (!shutdown) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { LOG.error("Sleep interrupted", e); continue; } try { purgeMetrics(); } catch (MetricException e) { LOG.error("Failed to purge metrics", e); if (this.failureMeter != null) { this.failureMeter.mark(); } } } }
Source:
private void createContext(final Grid parent, final int row, final int col) { parent.resizeRows(row + 1); final CheckBox cb = new CheckBox(PatchUtil.C.showFullFiles()); cb.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if (event.getValue()) { scriptSettings.setContext(WHOLE_FILE_CONTEXT); } else { initContextLines(); } refresh(false ); } }); parent.setWidget(row, col + 1, cb); if (Gerrit.isSignedIn()) { final CheckBox ku = new CheckBox(PatchUtil.C.keepUnreviewed()); ku.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { updateReviewedStatus(event.getValue() ? 0 : 1); } }); parent.setWidget(row, col + 2, ku); } }

Target:
private void createContext(final Grid parent, final int row, final int col) { parent.resizeRows(row + 1); final CheckBox cb = new CheckBox(PatchUtil.C.showFullFiles()); cb.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if (event.getValue()) { scriptSettings.setContext(WHOLE_FILE_CONTEXT); } else { initContextLines(); } refresh(false ); } }); parent.setWidget(row, col + 1, cb); if (Gerrit.isSignedIn()) { final CheckBox ku = new CheckBox(PatchUtil.C.reviewed()); ku.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { setReviewedByCurrentUser(event.getValue()); } }); ku.setValue(true); parent.setWidget(row, col + 2, ku); } }
Source:
protected IOSample getIOSample(IOLine ioLine) throws TimeoutException, XBeeException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); IOSample ioSample; try { ioSample = new IOSample(response.getResponse()); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; }

Target:
protected IOSample getIOSample(IOLine ioLine) throws TimeoutException, XBeeException { if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); IOSample ioSample; try { ioSample = new IOSample(response.getResponse()); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; }