auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void loadTrace(ITmfTrace trace) { fTrace = trace; <START> <END> 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); }</code><technical_language>cache getCurrentRange</technical_language>

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:
<code>public void removeBlock(final String dataType, final int blockId) { final Map<Integer, Block> blocks = typeToBlocks.get(dataType); if (null == blocks) { <START> LOG.log(Level.FINE, "Blocks are not initialized for type {0}", dataType); <END> 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(); } }</code><technical_language>this method is called in src Evaluator, data out. case data type is missing</technical_language>

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:
<code>public void after() throws Exception { try { <START> bb.close(); <END> } catch (Exception e) { } try { lp.close(); } catch (Exception e) { } try { builder.close(); } catch (Exception e) { } }</code><technical_language>IO.close(bb) IO.close throw exception</technical_language>

Target:
public void after() throws Exception { IO.close(bb); IO.close(lp); IO.close(builder); }
Source:
<code>public void streamsFromTestFactoriesShouldBeClosed() throws NoSuchMethodException { testMethod = DynamicCloseHookedStreamTest.class.getMethod("customStream"); when(testExtensionContext.getTestMethod()).thenReturn(Optional.of(testMethod)); <START> Stream<DynamicTest> stream = Stream.<DynamicTest> of().onClose(() -> isClosed = true); <END> when(testExtensionContext.getTestInstance()).thenReturn(new DynamicCloseHookedStreamTest(stream)); TestFactoryTestDescriptor descriptor = new TestFactoryTestDescriptor(UniqueId.forEngine("engine"), DynamicCloseHookedStreamTest.class, testMethod); descriptor.invokeTestMethod(context); assertTrue(isClosed); }</code><technical_language>Is this type argument <DynamicTest> needed? If so, suggest removing space > of for readability/brevity (assuming passes gradlew spotlessCheck!)</technical_language>

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:
<code>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); <START> setAttributeLotNumber(vhu); <END> InterfaceWrapperHelper.setTrxName(vhu, ITrx.TRXNAME_None); return vhu; }</code><technical_language>introduce method calls</technical_language>

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:
<code>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); <START> lockId = null; <END> } }</code><technical_language>this point move lockId = null out of try-catch block, is cleared a release(). fine</technical_language>

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:
<code>private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (fIsFlatViewClicked) { <START> setTraceEntryChildren(fHierarchicalList); <END> fIsFlatViewClicked = false; } } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_HIERARCHICAL_VIEW)); return action; }</code><technical_language>mentioned below, I reshuffle entries in hierarchical order. trace separately using: for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) trace state system entry list</technical_language>

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:
<code>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)); <START> } <END> }</code><technical_language>This had: java if (estimatedTime != null && hoursWorked != null) { issue.setEstimation(new IssueEstimation(estimatedTime, hoursWorked)); } else if (estimatedTime != null) { issue.setEstimation(new IssueEstimation(estimatedTime)); } else statement redundant</technical_language>

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:
<code>protected String fireEMRJob(String paramsStr,String clusterId){ StepFactory stepFactory = new StepFactory(); AmazonElasticMapReduceClient emr = new AmazonElasticMapReduceClient(); <START> emr.setRegion(Region.getRegion(Regions.US_EAST_1)); <END> 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); }</code><technical_language>This establish region Lambda environment. System.getEnv().get('AWS_REGION')</technical_language>

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:
<code>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), <START> Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageForSearchQueryInAnyList(currentSearchTerm)), <END> 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); })); }</code><technical_language>need do fullTextSearch phase. this time, performed a prefixSearch, means showing items history / tabs / reading lists top</technical_language>

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:
<code>boolean isSettingProperty(ProgramState state, ExpressionTree arg0, XxeProperty property) { <START> if (arg0.asConstant(String.class).filter(property.propertyName()::equals).isPresent()) { <END> return true; } ConstraintsByDomain constraintsByDomain = state.getConstraints(state.peekValue(1)); return constraintsByDomain != null && constraintsByDomain.hasConstraint(property.namedConstraint()); }</code><technical_language>options here: * replace property.propertyName()::equals property::isNamed * drop isNamed(String), I feeling end (see line below)</technical_language>

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:
<code>public String toString() { <START> StringBuilder sb = new StringBuilder("Int128ArrayBlockEncodingBuffer{"); <END> sb.append("valuesBufferCapacity=").append(valuesBuffer == null ? 0 : valuesBuffer.length).append(","); sb.append("valuesBufferIndex=").append(valuesBufferIndex).append("}"); return sb.toString(); }</code><technical_language>Int128ArrayBlockEncodingBuffer.class.getSimpleName(); ditto other places</technical_language>

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:
<code>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()); <START> networkRequiredOnVds = network.getCluster().isRequired() && network.isVmNetwork(); <END> } return networkRequiredOnVds; }</code><technical_language>this sense? non-vm network a vNIC? I this scenario blocked allowed arrive this state elsewhere</technical_language>

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:
<code>public LoveFilmData getLatestData() throws FetchException { try { S3Service service = serviceSupplier.get(); S3Object[] objects = service.listObjects(bucketName, folder, NO_DELIMITER); S3Object file = getFileforName(objects); <START> if (file != null) { <END> 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); } }</code><technical_language>Reverse this check, obvious throwing exception file is null, i.e. if (file == null) { throw new FetchException(...) } // Do</technical_language>

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:
<code>public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); if(extensionRegisters != null && extensionRegisters.size() > 0) <START> this.extensionRegisters.addAll(extensionRegisters); <END> }</code><technical_language>reworking this code in context of class, avoid potential NPE if extensionRegisters field initialized, no-args constructor</technical_language>

Target:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); if ( !extensionRegisters.isEmpty() ) { this.extensionRegisters.addAll(extensionRegisters); } }
Source:
<code>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 = <START> new Exception(message); <END> 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; }</code><technical_language>Throw a named exception here</technical_language>

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:
<code>protected GCSBatchSink(GCSSinkConfig config) { super(config); this.config = config; <START> if (!this.config.containsMacro("fileSystemProperties") && !this.config.containsMacro("JsonKeyFile") && <END> !this.config.containsMacro("ProjectId")) { this.config.fileSystemProperties = updateFileSystemProperties(this.config.fileSystemProperties, this.config.projectId, this.config.jsonKey); } }</code><technical_language>update fields in object in constructor of another object</technical_language>

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:
<code>public void testGetAllStoreSomeMatchLoaderSomeMatchDisjointFailWithBulkCacheLoadingException() throws Exception { final FakeStore fakeStore = new FakeStore(getEntryMap(KEY_SET_A, KEY_SET_B)); this.store = spy(fakeStore); <START> final FakeCacheLoaderWriter fakeLoader = new FakeCacheLoaderWriter(getEntryMap(KEY_SET_E, KEY_SET_E), KEY_SET_C, true); <END> 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)); }</code><technical_language>Do start in inconsistent state: loader needs a super set of store knows. If test a duplicate, delete it. key set here</technical_language>

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:
<code>public FileResponse readFile(String fileName, String reference) { FileResponse cwl = new FileResponse(); try { Repository repo = service.getRepository(gitUsername, gitRepository); List<RepositoryContents> contents; try { <START> contents = checkNotNull(cService.getContents(repo, fileName, reference)); <END> } 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; }</code><technical_language>Is correct? I this checks cService.getContents(repo, fileName, reference) is null fileName null, issue</technical_language>

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:
<code>void addFirst (RunnableLock[] toAdd, int numToAdd) { <START> if (numToAdd == 0) { <END> 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(); }</code><technical_language>if(numToAdd <= 0)</technical_language>

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:
<code>public void post(JSONObject json) { <START> post(json.toString(), null); <END> }</code><technical_language>JSONObject more efficient StringEventsWork starts parsing string a JSONObject. in this case pure JSONEventsWork used. I a bit fuzzy details, if work. if work ;)</technical_language>

Target:
public void post(JSONObject json) { post(json, null); }
Source:
<code>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) { <START> throw new APIManagementException(e.getMessage(), ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, e.getMessage())); <END> } }</code><technical_language>propagate "e" object well? Otherwise, stacktrace swallowed. suggestion throw new APIManagementException(e.getMessage(), e, ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, e.getMessage()));</technical_language>

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:
<code>public void readOnly_initialTransaction_throws() { RealmConfiguration.Builder config = new RealmConfiguration.Builder(); config = config.assetFile("foo", true); try { config.initialData(null); <START> } catch (IllegalStateException ignored) { <END> } config = new RealmConfiguration.Builder(); config.initialData(null); try { config = config.assetFile("foo", true); } catch (IllegalStateException ignored) { } }</code><technical_language>do want a fail() in here</technical_language>

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:
<code>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 ); <START> verify( placeManager ).goTo( BaseViewPresenter.PROJECT_SCREEN ); <END> verify( spy ).setupActiveContextFor( any() ); }</code><technical_language>Do need duplicate verification</technical_language>

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:
<code>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; } <START> opt.inJustDecodeBounds = true; <END> 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; }</code><technical_language>Explaining this needs decode, decode bounds, decode more helpful. need return of decodeFile? I read docs, returns decoded bitmap, this code expecting original file get decoded</technical_language>

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:
<code>public String[] getTraceNames() { Collection<ITmfTrace> traces = TmfTraceManager.getTraceSet(fTrace); <START> String[] traceNames = new String[traces.size()]; <END> int i = 0; for (ITmfTrace tr : traces) { traceNames[i] = tr.getName(); i++; } return traceNames; }</code><technical_language>gah, this screams Stream + lambda</technical_language>

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:
<code>protected boolean containsLinkedResources() { for (IPackageFragmentRoot <START> fPackageFragmentRoot : <END> fPackageFragmentRoots) { if (fPackageFragmentRoot.getResource().isLinked()) { return true; } } return false; }</code><technical_language>rename root</technical_language>

Target:
protected boolean containsLinkedResources() { for (IPackageFragmentRoot root : fPackageFragmentRoots) { if (root.getResource().isLinked()) { return true; } } return false; }
Source:
<code>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()); <START> response.getMetadata().put("Content-Type", contentType); <END> } return response; }</code><technical_language>need change response built. In original code do: if (blob.getEncoding() != null) { type += "; charset=" + blob.getEncoding(); }</technical_language>

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:
<code>public void connectionDown() { <START> for (Object listenerObject : coordinateListenerList.toArray()) { <END> CoordinateListener coordinateListener = (CoordinateListener) listenerObject; coordinateListener.onCoordinateEvent( CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, "down"); } isSynchronizedWithZooKeeper.set(false); }</code><technical_language>toArray copies elements of list array I think. depend implementation, ways loop this. lose type information</technical_language>

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

Target:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
<code>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 = <START> new Range(range.getEndKey(), true, range.getEndKey(), range.isEndKeyInclusive()); <END> } else { newRange = new Range(seekKey, true, range.getEndKey(), range.isEndKeyInclusive()); } seek(newRange); break; } source.next(); count++; } }</code><technical_language>explain this</technical_language>

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:
<code>public LocalizationUtils(final String fileName) { log.info("Start initializing {}", getClass().getSimpleName()); messageSource = fileName.replaceAll("\\.properties$", ""); resourceBundlesByLocale = new ConcurrentHashMap<>(); <START> getResourceBundle(Locale.getDefault()); <END> log.info("Finished initializing {}", getClass().getSimpleName()); }</code><technical_language>Btw check if translation for default locale (some users en_US default)? if en_US default, no</technical_language>

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:
<code>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( <START> secret.getMetadata().getAnnotations().getOrDefault("useSecretAsEnv", "false")); <END> String targetContainerName = secret.getMetadata().getAnnotations().get("targetContainer"); if (mountAsEnv) { mountAsEnv(env, secret, targetContainerName); } else { mountAsFile(env, secret, targetContainerName); } } }</code><technical_language>useSecretAsEnv -> org.eclipse.che/mount-as=(env|file)</technical_language>

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:
<code>private void listen() { try { socket = new ServerSocket(PORT); <START> logger.info("Language Server running on port {}", PORT); <END> 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); } }</code><technical_language>"started" instead of "running"</technical_language>

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:
<code>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) { <START> scanStateLock.lock(); <END> 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(); } }</code><technical_language>a bit strange release lock reacquire it. I do need check for state BETWEEN_PASSES do removes I if check for isHelperInUse(xaResourceRecoveryHelper)) { waitForScanState(ScanStates.IDLE); } scanStateLock.lock() code</technical_language>

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:
<code>public boolean areActiveCommands() { return (this.activeCommandList.size() > 0) || (this.commandStream != null && this.commandStream.getNumRowsRemaining() > 0) <START> || nextCommand != null; <END> }</code><technical_language>this simplified numActiveCommands() != 0</technical_language>

Target:
public boolean areActiveCommands() { return numActiveCommands() > 0; }