auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public DistStageAck executeOnSlave() { if (groupName == null || (slaveState.getGroupName() != null && slaveState.getGroupName().equals(groupName))) { ProbeSlaveMonitor slaveMonitors = slaveState.get(ProbeSlaveMonitor.MONITORS) == null ? new ProbeSlaveMonitor(slaveState, period) : (ProbeSlaveMonitor) slaveState.get(ProbeSlaveMonitor.MONITORS); slaveMonitors.addMonitor(new Monitor() { @Override public void run() { JgroupsProbeMonitorStartStage.this.run(); } @Override public void start() { <START> JgroupsProbeMonitorStartStage.this.run(); <END> } @Override public void stop() { JgroupsProbeMonitorStartStage.this.run(); } }); slaveMonitors.start(); } return successfulResponse(); }</code><technical_language>do execute extra run in start() stop()</technical_language>

Target:
public DistStageAck executeOnSlave() { ProbeSlaveMonitor slaveMonitors = slaveState.get(ProbeSlaveMonitor.MONITORS) == null ? new ProbeSlaveMonitor(slaveState, period) : (ProbeSlaveMonitor) slaveState.get(ProbeSlaveMonitor.MONITORS); slaveMonitors.addMonitor(new Monitor() { @Override public void run() { try { monitor(JgroupsProbeMonitorStartStage.this.run()); } catch (IOException e) { log.error(e.getMessage(), e); } } @Override public void start() { try { monitor(JgroupsProbeMonitorStartStage.this.run()); } catch (IOException e) { log.error(e.getMessage(), e); } } @Override public void stop() { try { monitor(JgroupsProbeMonitorStartStage.this.run()); } catch (IOException e) { log.error(e.getMessage(), e); } } public void monitor(String[] packetsResponse) { for (String response : packetsResponse) { if (printResultsAsInfo) { log.info(response); } else { log.trace(response); } } } }); slaveMonitors.start(); return successfulResponse(); }
Source:
<code>public void testTraceSetWithExperiment() { Set<ITmfTrace> expected = ImmutableSet.of(trace1); Set<ITmfTrace> actual = TmfTraceManager.getTraceSetWithExperiment(trace1); assertEquals(1, actual.size()); <START> assertArrayEquals(expected.toArray(), actual.toArray()); <END> TmfExperiment exp = createExperiment(trace1, trace2); expected = ImmutableSet.of(trace1, trace2, exp); actual = TmfTraceManager.getTraceSetWithExperiment(exp); assertEquals(3, actual.size()); assertArrayEquals(expected.toArray(), actual.toArray()); }</code><technical_language>Set order though, fact elements present (LinkedHashSet ImmutableSet happen conserve iteration order, is specific implementations). If order of elements is important, a List then, a Set. question is, is this order important</technical_language>

Target:
public void testTraceSetWithExperiment() { Set<ITmfTrace> expected = ImmutableSet.of(trace1); Set<ITmfTrace> actual = TmfTraceManager.getTraceSetWithExperiment(trace1); assertEquals(1, actual.size()); assertEquals(expected, actual); TmfExperiment exp = createExperiment(trace1, trace2); expected = ImmutableSet.of(trace1, trace2, exp); actual = TmfTraceManager.getTraceSetWithExperiment(exp); assertEquals(3, actual.size()); assertEquals(expected, actual); }
Source:
<code>public void testImportVMFromConfigurationXMLCouldNotGetParsed() { OvfEntityData ovfEntity = getOvfEntityData(); ovfEntity.setOvfData("This is not a valid XML"); initCommand(ovfEntity); when(unregisteredOVFDataDao.getByEntityIdAndStorageDomain(vmId, storageDomainId)).thenReturn(ovfEntity); <START> when(validator.validateUnregisteredEntity(any(IVdcQueryable.class), any(OvfEntityData.class), any(List.class))).thenReturn(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED)); <END> CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED); }</code><technical_language>s/any(List.class)/anyList()</technical_language>

Target:
public void testImportVMFromConfigurationXMLCouldNotGetParsed() { OvfEntityData ovfEntity = getOvfEntityData(); ovfEntity.setOvfData("This is not a valid XML"); initCommand(ovfEntity); when(unregisteredOVFDataDao.getByEntityIdAndStorageDomain(vmId, storageDomainId)).thenReturn(ovfEntity); when(validator.validateUnregisteredEntity(any(IVdcQueryable.class), any(OvfEntityData.class), anyList())).thenReturn(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED)); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED); }
Source:
<code>public static <A> UniConstraintCollector<A, ?, Integer> countDistinct(Function<A, ?> groupValueMapping) { <START> return ConstraintCollectors.countDistinctLong(groupValueMapping, Long::intValue); <END> }</code><technical_language>cast longs impact performance impacts behavior overflowing: 2 000 000 000 + 1 000 000 000 result in a postive number this change, instead of a negative number (which is easier spot for overflow)</technical_language>

Target:
public static <A> UniConstraintCollector<A, ?, Integer> countDistinct(Function<A, ?> groupValueMapping) { class CountDistinctResultContainer { int count = 0; Map<Object, int[]> objectCountMap = new HashMap<>(); } return new DefaultUniConstraintCollector<>( CountDistinctResultContainer::new, (resultContainer, a) -> { Object value = groupValueMapping.apply(a); int[] objectCount = resultContainer.objectCountMap.computeIfAbsent(value, k -> new int[1]); if (objectCount[0] == 0) { resultContainer.count++; } objectCount[0]++; return (() -> { int[] objectCount2 = resultContainer.objectCountMap.get(value); if (objectCount2 == null) { throw new IllegalStateException("Impossible state: the value (" + value + ") of A (" + a + ") is removed more times than it was added."); } objectCount2[0]--; if (objectCount2[0] == 0) { resultContainer.objectCountMap.remove(value); resultContainer.count--; } }); }, resultContainer -> resultContainer.count); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (mFacebookAuthHelper != null) { mFacebookAuthHelper.mCallbackManager.onActivityResult(requestCode, resultCode, data); } <START> if (mTwitterAuthHelper != null) { <END> mTwitterAuthHelper.onActivityResult(requestCode, resultCode, data); } if (mGoogleAuthHelper != null) { mGoogleAuthHelper.onActivityResult(requestCode, resultCode, data); } }</code><technical_language>app user clicked button sign in. call onActivityResult() for provider</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (mFacebookAuthProvider != null) { mFacebookAuthProvider.mCallbackManager.onActivityResult(requestCode, resultCode, data); } if (mTwitterAuthProvider != null) { mTwitterAuthProvider.onActivityResult(requestCode, resultCode, data); } if (mGoogleAuthProvider != null) { mGoogleAuthProvider.onActivityResult(requestCode, resultCode, data); } }
Source:
<code><START> private static Collection<ExternalVnicProfileMapping> mapVnicProfilesMapping(RegistrationVnicProfileMappings model) { Collection<ExternalVnicProfileMapping> result = new ArrayList<>(model.getRegistrationVnicProfileMappings().size()); model.getRegistrationVnicProfileMappings().forEach(regMapping -> { result.add(new ExternalVnicProfileMapping( regMapping.getFrom().getNetwork().getName(), regMapping.getFrom().getName(), regMapping.getTo() != null ? new Guid(regMapping.getTo().getId()) : null)); }); return result; } <END></code><technical_language>easier read? private static Collection<ExternalVnicProfileMapping> mapVnicProfilesMapping( RegistrationVnicProfileMappings model) { return model.getRegistrationVnicProfileMappings() .stream() .map(regMapping -> new ExternalVnicProfileMapping( regMapping.getFrom().getNetwork().getName(), regMapping.getFrom().getName(), regMapping.getTo() != null ? new Guid(regMapping.getTo().getId()) : null)) .collect(Collectors.toList()); }</technical_language>

Target:
private static Collection<ExternalVnicProfileMapping> mapVnicProfilesMapping( RegistrationVnicProfileMappings model) { return model.getRegistrationVnicProfileMappings() .stream() .map(regMapping -> new ExternalVnicProfileMapping( regMapping.getFrom().getNetwork().getName(), regMapping.getFrom().getName(), regMapping.getTo() != null ? new Guid(regMapping.getTo().getId()) : null)) .collect(Collectors.toList()); }
Source:
<code>private void endFilteredBlock(FilteredBlock m) { if (log.isDebugEnabled()) log.debug("{}: Received broadcast filtered block {}", getAddress(), m.getHash().toString()); if (!vDownloadData) { log.debug("{}: Received block we did not ask for: {}", getAddress(), m.getHash().toString()); return; } if (blockChain == null) { log.warn("Received filtered block but was not configured with an AbstractBlockChain"); return; } pendingBlockDownloads.remove(m.getBlockHeader().getHash()); try { lock.lock(); try { <START> if (awaitingFreshFilter != null || checkForFilterExhaustion(m)) { <END> if (awaitingFreshFilter == null) { log.info("Bloom filter exhausted whilst processing block {}, discarding", m.getHash()); awaitingFreshFilter = new LinkedList<Sha256Hash>(); awaitingFreshFilter.add(m.getHash()); awaitingFreshFilter.addAll(blockChain.drainOrphanBlocks()); } else { log.info("Discarding block because we're still waiting for a fresh filter", m.getHash()); awaitingFreshFilter.add(m.getHash()); } return; } } finally { lock.unlock(); } if (blockChain.add(m)) { invokeOnBlocksDownloaded(m.getBlockHeader()); } else { lock.lock(); try { final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash())); blockChainDownloadLocked(orphanRoot.getHash()); } finally { lock.unlock(); } } } catch (VerificationException e) { log.warn("{}: FilteredBlock verification failed", getAddress(), e); } catch (PrunedException e) { throw new RuntimeException(e); } }</code><technical_language>if statement else clause: if (awaitingFreshFilter != null) { ... return; } else if (checkForFilterExhaustion(m)) { ... return; }</technical_language>

Target:
private void endFilteredBlock(FilteredBlock m) { if (log.isDebugEnabled()) log.debug("{}: Received broadcast filtered block {}", getAddress(), m.getHash().toString()); if (!vDownloadData) { log.debug("{}: Received block we did not ask for: {}", getAddress(), m.getHash().toString()); return; } if (blockChain == null) { log.warn("Received filtered block but was not configured with an AbstractBlockChain"); return; } pendingBlockDownloads.remove(m.getBlockHeader().getHash()); try { lock.lock(); try { if (awaitingFreshFilter != null) { log.info("Discarding block because we're still waiting for a fresh filter", m.getHash()); awaitingFreshFilter.add(m.getHash()); return; } else if (checkForFilterExhaustion(m)) { log.info("Bloom filter exhausted whilst processing block {}, discarding", m.getHash()); awaitingFreshFilter = new LinkedList<Sha256Hash>(); awaitingFreshFilter.add(m.getHash()); awaitingFreshFilter.addAll(blockChain.drainOrphanBlocks()); return; } } finally { lock.unlock(); } if (blockChain.add(m)) { invokeOnBlocksDownloaded(m.getBlockHeader()); } else { lock.lock(); try { final Block orphanRoot = checkNotNull(blockChain.getOrphanRoot(m.getHash())); blockChainDownloadLocked(orphanRoot.getHash()); } finally { lock.unlock(); } } } catch (VerificationException e) { log.warn("{}: FilteredBlock verification failed", getAddress(), e); } catch (PrunedException e) { throw new RuntimeException(e); } }
Source:
<code>public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture) { requireNonNull(listenableFuture, "listenableFuture is null"); CompletableFuture<V> future = new CompletableFuture<>(); listenableFuture.addListener(() -> { <START> try { <END> future.complete(listenableFuture.get()); } catch (InterruptedException e) { future.completeExceptionally(e); } catch (ExecutionException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); future.completeExceptionally(cause); } }, MoreExecutors.directExecutor()); return future; }</code><technical_language>This formatting</technical_language>

Target:
public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture) { requireNonNull(listenableFuture, "listenableFuture is null"); CompletableFuture<V> future = new CompletableFuture<>(); future.exceptionally(throwable -> { if (throwable instanceof CancellationException) { listenableFuture.cancel(true); } return null; }); Futures.addCallback(listenableFuture, new FutureCallback<V>() { @Override public void onSuccess(V result) { future.complete(result); } @Override public void onFailure(Throwable t) { future.completeExceptionally(t); } }); return future; }
Source:
<code>protected void setMatcherString(String pattern) { if (pattern.length() == 0) { searchPattern = null; } else { SearchPattern patternMatcher = new SearchPattern(); if (pattern.indexOf('*') != 0 && pattern.indexOf('?') != 0 && pattern.indexOf('.') != 0) { <START> pattern = "*" + pattern; END> } patternMatcher.setPattern(pattern); searchPattern = patternMatcher; } }</code><technical_language>@Lars Do for consistency (and another slight performance enhancement) this line changed well</technical_language>

Target:
protected void setMatcherString(String pattern) { if (pattern.length() == 0) { searchPattern = null; } else { SearchPattern patternMatcher = new SearchPattern(); if (pattern.indexOf('*') != 0 && pattern.indexOf('?') != 0 && pattern.indexOf('.') != 0) { pattern = '*' + pattern; } patternMatcher.setPattern(pattern); searchPattern = patternMatcher; } }
Source:
<code><START> public static final boolean hasReadPairedFlag(Read read) { <END> return read.getFlags() != null && ((read.getFlags() & READ_PAIRED_FLAG) != 0); }</code><technical_language>refactor out dupe code here, is a helper method like: boolean hasFlag(Read read, int flag) { ... } also, if method exists, necessary wrappers</technical_language>

Target:
public static boolean hasReadPairedFlag(Read read) { return hasFlag(read, READ_PAIRED_FLAG); }
Source:
<code>public void enqueueUpdatesNumberOfShards() { <START> assertThat(DEFAULT_SWEEP_QUEUE_SHARDS).isLessThan(DEFAULT_SHARDS); <END> assertThat(progress.getNumberOfShards()).isEqualTo(DEFAULT_SWEEP_QUEUE_SHARDS); enqueueWriteCommitted(TABLE_CONS, LOW_TS); assertThat(progress.getNumberOfShards()).isEqualTo(DEFAULT_SHARDS); }</code><technical_language>constants confusing - I difference be</technical_language>

Target:
public void enqueueUpdatesNumberOfShards() { assertThat(AtlasDbConstants.DEFAULT_SWEEP_QUEUE_SHARDS).isLessThan(DEFAULT_SHARDS); assertThat(progress.getNumberOfShards()).isEqualTo(AtlasDbConstants.DEFAULT_SWEEP_QUEUE_SHARDS); enqueueWriteCommitted(TABLE_CONS, LOW_TS); assertThat(progress.getNumberOfShards()).isEqualTo(DEFAULT_SHARDS); }
Source:
<code>boolean isSupportedKeyType(X509Certificate cert) { for (ClientCertificateType type : certificateTypes) { boolean isCompatibleType = type.isCompatibleWithKeyAlgorithm(cert.getPublicKey().getAlgorithm()); boolean meetsSigningRequirements = !type.requiresSigningCapability() <START> || (type.requiresSigningCapability() && (cert.getKeyUsage() == null || cert.getKeyUsage()[0])); <END> LOGGER.debug("type: {}, isCompatibleWithKeyAlgorithm[{}]: {}, meetsSigningRequirements: {}", new Object[]{ type, cert.getPublicKey().getAlgorithm(), isCompatibleType, meetsSigningRequirements}); if (isCompatibleType && meetsSigningRequirements) { return true; } } LOGGER.debug("certificate is not of any supported type", cert); return false; }</code><technical_language>!a || (a && b) := !a || b this reduced logic equivalent</technical_language>

Target:
boolean isSupportedKeyType(X509Certificate cert) { for (ClientCertificateType type : certificateTypes) { boolean isCompatibleType = type.isCompatibleWithKeyAlgorithm(cert.getPublicKey().getAlgorithm()); boolean meetsSigningRequirements = !type.requiresSigningCapability() || (cert.getKeyUsage() == null || cert.getKeyUsage()[0]); LOGGER.debug("type: {}, isCompatibleWithKeyAlgorithm[{}]: {}, meetsSigningRequirements: {}", new Object[] { type, cert.getPublicKey().getAlgorithm(), isCompatibleType, meetsSigningRequirements }); if (isCompatibleType && meetsSigningRequirements) { return true; } } LOGGER.debug("certificate is not of any supported type", cert); return false; }
Source:
<code>public Action<?, ?> startingDownscaleAction() { return new AbstractDownscaleAction<>(DownscaleEvent.class) { @Override protected void doExecute(FreeIpaDownscaleContext context, DownscaleEvent payload, Map<Object, Object> variables) { Stack stack = context.getStack(); <START> List<String> instanceIds = context.getInstanceIds(); <END> LOGGER.info("Starting downscale of stack instances [{}]", stack.getId(), instanceIds); stackUpdater.updateStackStatus(stack.getId(), DetailedStackStatus.DOWNSCALE_IN_PROGRESS, "Starting downscale"); sendEvent(context, STARTING_DOWNSCALE_FINISHED_EVENT.selector(), new StackEvent(stack.getId())); } }; }</code><technical_language>I simply get instanceIds event, put variables</technical_language>

Target:
public Action<?, ?> startingDownscaleAction() { return new AbstractDownscaleAction<>(DownscaleEvent.class) { @Override protected void doExecute(StackContext context, DownscaleEvent payload, Map<Object, Object> variables) { Stack stack = context.getStack(); List<String> instanceIds = payload.getInstanceIds(); setInstanceIds(variables, instanceIds); String operationId = payload.getOperationId(); setOperationId(variables, operationId); List<String> fqdns = getInstanceMetadataFromStack(stack, instanceIds).stream() .map(InstanceMetaData::getDiscoveryFQDN) .filter(Objects::nonNull) .collect(Collectors.toList()); setHosts(variables, fqdns); LOGGER.info("Starting downscale of stack instances [{}]", stack.getId(), instanceIds); stackUpdater.updateStackStatus(stack.getId(), DetailedStackStatus.DOWNSCALE_IN_PROGRESS, "Starting downscale"); sendEvent(context, STARTING_DOWNSCALE_FINISHED_EVENT.selector(), new StackEvent(stack.getId())); } }; }
Source:
<code>public byte[] getNoLeadZeroesData() { <START> return ByteUtil.stripLeadingZeroes(getData()); <END> }</code><technical_language>getData() absolutely unnecessary copy internally</technical_language>

Target:
public byte[] getNoLeadZeroesData() { return ByteUtil.stripLeadingZeroes(copyData()); }
Source:
<code>public void placeNewMarketOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (orderType == OrderType.BUY) { <START> BuyOrder order = new BuyOrder(symbol, volume, true, this); for (Order o : ordersPlaced) { <END> if (o.getStockSymbol() == order.getStockSymbol()) { throw new StockMarketExpection("An order for this stock has already been placed. Stock: " + symbol + " Trader: " + name); } } ordersPlaced.add(order); m.addOrder(order); } else { SellOrder order = new SellOrder(symbol, volume, true, this); boolean found = false; for (Order o : position) { if (o.getStockSymbol() == order.getStockSymbol()) { found = true; if (order.getSize() > o.getSize()) { throw new StockMarketExpection("The trader does not have enough stock to sell. Stock: " + symbol + " Trader: " + name); } } } for (Order o : ordersPlaced) { if (o.getStockSymbol() == order.getStockSymbol()) { throw new StockMarketExpection("An order for this stock has already been placed. Stock: " + symbol + " Trader: " + name); } } if (found == false) { throw new StockMarketExpection("The trader does not have the stock for this order. Stock: " + symbol + " Trader: " + name); } ordersPlaced.add(order); m.addOrder(order); } }</code><technical_language>More descriptive variable names difference order o</technical_language>

Target:
public void placeNewMarketOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (orderType == OrderType.BUY) { BuyOrder order = new BuyOrder(symbol, volume, true, this); for (Order orderIterator : ordersPlaced) { if (orderIterator.getStockSymbol() == order.getStockSymbol()) { throw new StockMarketExpection("An order for this stock has already been placed. Stock: " + symbol + " Trader: " + name); } } ordersPlaced.add(order); m.addOrderToMarket(order); } else { SellOrder order = new SellOrder(symbol, volume, true, this); boolean found = false; for (Order orderIterator : position) { if (orderIterator.getStockSymbol() == order.getStockSymbol()) { found = true; if (order.getSize() > orderIterator.getSize()) { throw new StockMarketExpection("The trader does not have enough stock to sell. Stock: " + symbol + " Trader: " + name); } } } for (Order orderIterator : ordersPlaced) { if (orderIterator.getStockSymbol() == order.getStockSymbol()) { throw new StockMarketExpection("An order for this stock has already been placed. Stock: " + symbol + " Trader: " + name); } } if (found == false) { throw new StockMarketExpection("The trader does not have the stock for this order. Stock: " + symbol + " Trader: " + name); } ordersPlaced.add(order); m.addOrderToMarket(order); } }
Source:
<code>private int readInt( long pageId, int pageOffset ) throws IOException { <START> int bytesInCurentPage = pageSize - pageOffset; <END> if ( bytesInCurentPage < 4 ) { return readPageCrossingInt( pageId, pageOffset, bytesInCurentPage ); } moveCursorTo( pageId, pageOffset ); int val; do { val = cursor.getInt( pageOffset ); } while ( cursor.shouldRetry() ); if ( cursor.checkAndClearBoundsFlag() ) { throw newEOFException( "Cursor bounds check failed" ); } return val; }</code><technical_language>This method pretty hot. I if optimistically combine pageId, pageOffset moveCursorTo a single method call, straight int-read loop. rely checkAndClearBoundsFlag if throw result try a cross-page instead instead, in turn figure out if EOF not</technical_language>

Target:
private int readInt( long pageId, int pageOffset ) throws IOException { moveCursorTo( pageId, pageOffset ); int val; do { val = cursor.getInt( pageOffset ); } while ( cursor.shouldRetry() ); if ( !cursor.checkAndClearBoundsFlag() ) { return val; } return readPageCrossingInt( pageId, pageOffset ); }
Source:
<code><START> public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) throws Exception { <END> try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:/ } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }</code><technical_language>Delete 'throws Exception'? above</technical_language>

Target:
public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) { try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:/ } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }
Source:
<code>public void viewWithNoResult_emptyList() throws IOException { init(); <START> assertEquals(0, db.getViewRequestBuilder("example", "by_tag").newRequest(Key.Type.STRING, Object.class).keys("javax").build().getResponse().getKeys().size(), "The results list should be of length 0"); <END> }</code><technical_language>some of code replacements produced long lines. end of review process is worth applying formatter classes final merge</technical_language>

Target:
public void viewWithNoResult_emptyList() throws IOException { init(); assertEquals(0, db.getViewRequestBuilder("example", "by_tag").newRequest(Key.Type.STRING, Object.class).keys("javax").build().getResponse().getKeys().size(), "The results " + "list should be of length 0"); }
Source:
<code>private void setJspVersion(CompileJSPs compile, Set<String> installedFeatures) { if (jspVersion != null) { compile.setJspVersion(jspVersion); } else if (installedFeatures.contains("jsp-2.2")) { compile.setJspVersion("2.2"); } <START> else if (installedFeatures.contains("jsp-2.3")) { <END> compile.setJspVersion("2.3"); } }</code><technical_language>I it. However, if is a new version of jsp in future, this code need updated. for a feature startsWith("jsp-") get version it</technical_language>

Target:
private void setJspVersion(CompileJSPs compile, Set<String> installedFeatures) { if (jspVersion != null) { compile.setJspVersion(jspVersion); } else { Iterator it = installedFeatures.iterator(); String currentFeature; while (it.hasNext()) { currentFeature = (String) it.next(); if(currentFeature.startsWith("jsp-")) { String version = currentFeature.replace("jsp-", ""); compile.setJspVersion(version); break; } } } }
Source:
<code>public SXSSFWorkbook searchResultToExcel(List<Vertex> vertices, String rootType, int depth, List<String> relationNames) { SXSSFWorkbook workbook = new SXSSFWorkbook(); final String[] relationTypes = relationNames == null ? null : relationNames.toArray(new String[relationNames.size()]); Collection rootCollection = mappings.getCollectionForType(rootType).get(); Vre vre = rootCollection.getVre(); String detectedVre = vre.getVreName(); Map<String, Set<Vertex>> verticesPerType = Maps.newHashMap(); verticesPerType.put(rootCollection.getEntityTypeName(), Sets.newHashSet(vertices)); GraphTraversal<Vertex, Vertex> current = graphWrapper.getGraph().traversal().V(vertices); String relationPropTypeName = getRelationAcceptedPropName(vre); <START> for (int i = 0; i < depth - 1; i++) { <END> current = relationTypes == null ? current.bothE().and(__.has(relationPropTypeName, true), __.has("isLatest", true)).otherV() : current.bothE(relationTypes).and(__.has(relationPropTypeName, true), __.has("isLatest", true)).otherV(); mapVertices(detectedVre, current, verticesPerType); } renderEntitySheets(workbook, verticesPerType, relationPropTypeName, relationTypes); return workbook; }</code><technical_language>more clear for is written like: for (int i = 1; i < depth; i++)</technical_language>

Target:
public SXSSFWorkbook searchResultToExcel(List<Vertex> vertices, String rootType, int depth, List<String> relationNames) { SXSSFWorkbook workbook = new SXSSFWorkbook(); final String[] relationTypes = relationNames == null ? null : relationNames.toArray(new String[relationNames.size()]); Collection rootCollection = mappings.getCollectionForType(rootType).get(); Vre vre = rootCollection.getVre(); String detectedVre = vre.getVreName(); Map<String, Set<Vertex>> verticesPerType = Maps.newHashMap(); verticesPerType.put(rootCollection.getEntityTypeName(), Sets.newHashSet(vertices)); GraphTraversal<Vertex, Vertex> current = graphWrapper.getGraph().traversal().V(vertices); String relationPropTypeName = getRelationAcceptedPropName(vre); for (int i = 1; i < depth; i++) { current = relationTypes == null ? current.bothE().and(__.has(relationPropTypeName, true), __.has("isLatest", true)).otherV() : current.bothE(relationTypes).and(__.has(relationPropTypeName, true), __.has("isLatest", true)).otherV(); mapVertices(detectedVre, current, verticesPerType); } renderEntitySheets(workbook, verticesPerType, relationPropTypeName, relationTypes); return workbook; }
Source:
<code>private ANTLRv4GrammarProperties findSettingsForFile(String fileName) { for (ANTLRv4GrammarProperties settings : perGrammarGenerationSettings) { <START> WildcardFileNameMatcher wildcardFileNameMatcher = new WildcardFileNameMatcher(settings.fileName); <END> if (wildcardFileNameMatcher.acceptsCharSequence(fileName)) { return settings; } } return null; }</code><technical_language>check bahavior of invalid pattern constructor</technical_language>

Target:
private ANTLRv4GrammarProperties findSettingsForFile(String fileName) { for (ANTLRv4GrammarProperties settings : perGrammarGenerationSettings) { if (settings.fileName.equals(fileName)) { return settings; } } for (ANTLRv4GrammarProperties settings : perGrammarGenerationSettings) { if (matchesWildcardPattern(fileName, settings)) { return settings; } } return null; }
Source:
<code>public Extension deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { if (urn == null || urn.isEmpty()) { throw new IllegalStateException("The URN cannot be null or empty"); } JsonNode rootNode = jp.readValueAsTree(); if (rootNode.getNodeType() != JsonNodeType.OBJECT) { throw new JsonMappingException("Extension is of wrong JSON type"); } <START> Extension.Builder extension = new Extension.Builder(urn); <END> Iterator<Map.Entry<String, JsonNode>> fieldIterator = rootNode.fields(); while (fieldIterator.hasNext()) { Map.Entry<String, JsonNode> entry = fieldIterator.next(); switch (entry.getValue().getNodeType()) { case BOOLEAN: handleBoolean(extension, entry); break; case STRING: handleString(extension, entry); break; case NUMBER: handleNumber(extension, entry); break; default: throw new IllegalArgumentException("JSON type not supported: " + entry.getValue().getNodeType()); } } return extension.build(); }</code><technical_language>please rename variable "extension" "extensionBuilder" similar</technical_language>

Target:
public Extension deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { if (urn == null || urn.isEmpty()) { throw new IllegalStateException("The URN cannot be null or empty"); } JsonNode rootNode = jp.readValueAsTree(); if (rootNode.getNodeType() != JsonNodeType.OBJECT) { throw new JsonMappingException("Extension is of wrong JSON type"); } Extension.Builder extensionBuilder = new Extension.Builder(urn); Iterator<Map.Entry<String, JsonNode>> fieldIterator = rootNode.fields(); while (fieldIterator.hasNext()) { Map.Entry<String, JsonNode> entry = fieldIterator.next(); switch (entry.getValue().getNodeType()) { case BOOLEAN: handleBoolean(extensionBuilder, entry); break; case STRING: handleString(extensionBuilder, entry); break; case NUMBER: handleNumber(extensionBuilder, entry); break; default: throw new IllegalArgumentException("JSON type not supported: " + entry.getValue().getNodeType()); } } return extensionBuilder.build(); }
Source:
<code>public void sendRoutingTableUpdateMsg(final String destId, final List<Integer> blocks, final String oldEvalId, final String newEvalId, @Nullable final TraceInfo parentTraceInfo) { <START> Span detached = null; <END> try (final TraceScope sendRoutingTableUpdateMsgScope = Trace.startSpan(SEND_ROUTING_TABLE_UPDATE_MSG + ". destId: " + destId, parentTraceInfo)) { LOG.entering(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendRoutingTableUpdateMsg"); final RoutingTableUpdateMsg routingTableUpdateMsg = RoutingTableUpdateMsg.newBuilder() .setOldEvalId(oldEvalId) .setNewEvalId(newEvalId) .setBlockIds(blocks) .build(); detached = sendRoutingTableUpdateMsgScope.detach(); send(destId, AvroElasticMemoryMessage.newBuilder() .setType(Type.RoutingTableUpdateMsg) .setSrcId(emNetworkSetup.getMyId().toString()) .setDestId(destId) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .setRoutingTableUpdateMsg(routingTableUpdateMsg) .build()); LOG.exiting(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendRoutingTableUpdateMsg"); } finally { Trace.continueSpan(detached).close(); } }</code><technical_language>add a description here: _We detach span transit another thread (local remote), detached span call Trace.continueSpan(detached).close() explicitly for stitching spans other threads children_</technical_language>

Target:
public void sendRoutingTableUpdateMsg(final String destId, final List<Integer> blocks, final String oldEvalId, final String newEvalId, @Nullable final TraceInfo parentTraceInfo) { Span detached = null; try (final TraceScope sendRoutingTableUpdateMsgScope = Trace.startSpan(String.format("send_routing_table_update_msg. destId: %s", destId), parentTraceInfo)) { LOG.entering(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendRoutingTableUpdateMsg"); final RoutingTableUpdateMsg routingTableUpdateMsg = RoutingTableUpdateMsg.newBuilder() .setOldEvalId(oldEvalId) .setNewEvalId(newEvalId) .setBlockIds(blocks) .build(); detached = sendRoutingTableUpdateMsgScope.detach(); send(destId, AvroElasticMemoryMessage.newBuilder() .setType(Type.RoutingTableUpdateMsg) .setSrcId(emNetworkSetup.getMyId().toString()) .setDestId(destId) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .setRoutingTableUpdateMsg(routingTableUpdateMsg) .build()); LOG.exiting(ElasticMemoryMsgSenderImpl.class.getSimpleName(), "sendRoutingTableUpdateMsg"); } finally { Trace.continueSpan(detached).close(); } }
Source:
<code>public void setMaxSession(final Integer value) { if (logger.isTraceEnabled()) { logger.trace("setMaxSession(" + value + ")"); } if ( value < 1 ) { <START> logger.warn("Invalid number of session (negative):" + value + ", defaulting to 1."); <END> maxSession = 1; } else maxSession = value; }</code><technical_language>this requires a declared logger in ActiveMQRALogger logger code</technical_language>

Target:
public void setMaxSession(final Integer value) { if (logger.isTraceEnabled()) { logger.trace("setMaxSession(" + value + ")"); } if ( value < 1 ) { maxSession = 1; ActiveMQRALogger.LOGGER.invalidNumberOfMaxSession(value, maxSession); } else maxSession = value; }
Source:
<code>private HandshakeStatus wrap( ByteBuffer buffer ) throws IOException { HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); Status status = sslEngine.wrap( buffer, cipherOut ).getStatus(); switch ( status ) { case OK: handshakeStatus = runDelegatedTasks(); cipherOut.flip(); while ( cipherOut.hasRemaining() ) { channelWrite( cipherOut ); } cipherOut.clear(); break; case BUFFER_OVERFLOW: int curNetSize = cipherOut.capacity(); int netSize = sslEngine.getSession().getPacketBufferSize(); if ( netSize > curNetSize ) { cipherOut = ByteBuffer.allocate( netSize ); logger.debug( "Enlarged network output buffer from %s to %s. " + "This operation should be a rare operation.", curNetSize, netSize ); } else { cipherOut.flip(); <START> channelWrite( cipherOut ); <END> cipherOut.compact(); logger.debug( "Network output buffer couldn't be enlarged, flushing data to the channel instead." ); } break; default: throw new ClientException( "Got unexpected status " + status ); } return handshakeStatus; }</code><technical_language>written == 0 check</technical_language>

Target:
private HandshakeStatus wrap( ByteBuffer buffer ) throws IOException, ClientException { HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); Status status = sslEngine.wrap( buffer, cipherOut ).getStatus(); switch ( status ) { case OK: handshakeStatus = runDelegatedTasks(); cipherOut.flip(); while ( cipherOut.hasRemaining() ) { channelWrite( cipherOut ); } cipherOut.clear(); break; case BUFFER_OVERFLOW: int curNetSize = cipherOut.capacity(); int netSize = sslEngine.getSession().getPacketBufferSize(); if ( netSize > curNetSize ) { cipherOut = ByteBuffer.allocate( netSize ); logger.debug( "Enlarged network output buffer from %s to %s. " + "This operation should be a rare operation.", curNetSize, netSize ); } else { cipherOut.flip(); if ( channelWrite( cipherOut ) == 0 ) { throw new ClientException( format( "Failed to enlarge network buffer from %s to %s. This is either because the " + "new size is however less than the old size, or because the application " + "buffer size %s is so big that the application data still cannot fit into the " + "new network buffer.", curNetSize, netSize, buffer.capacity() ) ); } cipherOut.compact(); logger.debug( "Network output buffer couldn't be enlarged, flushing data to the channel instead." ); } break; default: throw new ClientException( "Got unexpected status " + status ); } return handshakeStatus; }
Source:
<code><START> public void testSetMaxSize() throws Exception { SizeLimitedVector slv = new SizeLimitedVector(10); slv.setMaxSize(14); assertEquals(slv.getMaxSize(), 14); <END> }</code><technical_language>Please add 14+1 elements verify more setter changed. e.g. calling getSize capacity verify contents of vector</technical_language>

Target:
public void testSetMaxSize() throws Exception { SizeLimitedVector slv = new SizeLimitedVector(5); slv.setMaxSize(6); slv.add(1); slv.add(2); slv.add(3); slv.add(4); slv.add(5); slv.add(6); slv.add(7); assertEquals(slv.getMaxSize(), 6); assertEquals(slv.capacity(), 10); assertEquals(slv.size(), 6); assertEquals(slv.get(0), 2); }
Source:
<code><START> public void buildAntProject(Path path) { <END> File buildFile = new File(path.toString() + File.separatorChar + "build.xml"); Project buildProject = new Project(); buildProject.setUserProperty("ant.file", buildFile.getAbsolutePath()); buildProject.init(); buildProject.setBaseDir(path.toAbsolutePath().toFile()); DefaultLogger logger = new DefaultLogger(); logger.setErrorPrintStream(System.err); logger.setOutputPrintStream(System.out); logger.setMessageOutputLevel(Project.MSG_ERR); buildProject.addBuildListener(logger); try { buildProject.fireBuildStarted(); ProjectHelper helper = ProjectHelper.getProjectHelper(); buildProject.addReference("ant.projectHelper", helper); helper.parse(buildProject, buildFile); buildProject.executeTarget("compile-test"); buildProject.fireBuildFinished(null); } catch (BuildException e) { buildProject.fireBuildFinished(e); } }</code><technical_language>Mark Guava's @VisibleForTesting prefer package private instead of public</technical_language>

Target:
protected boolean buildAntProject(Path path) { final File buildFile = new File(path.toString() + File.separatorChar + "build.xml"); final File buildLog; Project buildProject = new Project(); buildProject.setUserProperty("ant.file", buildFile.getAbsolutePath()); buildProject.setProperty("javac.fork", "true"); buildProject.init(); buildProject.setBaseDir(path.toAbsolutePath().toFile()); try { DefaultLogger logger = new DefaultLogger(); buildLog = new File(path.toString(), "build_log.txt"); PrintStream errorPrintStream = new PrintStream(buildLog); logger.setErrorPrintStream(errorPrintStream); logger.setOutputPrintStream(System.out); logger.setMessageOutputLevel(Project.MSG_ERR); buildProject.addBuildListener(logger); try { buildProject.fireBuildStarted(); ProjectHelper helper = ProjectHelper.getProjectHelper(); buildProject.addReference("ant.projectHelper", helper); helper.parse(buildProject, buildFile); buildProject.executeTarget("compile-test"); buildProject.fireBuildFinished(null); return true; } catch (BuildException e) { buildProject.fireBuildFinished(e); buildRunResult = new RunResult(Status.COMPILE_FAILED, ImmutableList.copyOf(new ArrayList<TestResult>()), new ImmutableMap.Builder<String, byte[]>().put(SpecialLogs.COMPILER_OUTPUT, Files.readAllBytes(buildLog.toPath())).build()); return false; } } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
<code><START> private static <K, V> CacheNotifier<K, V> blockNotifierPartitionStatusChanged(final CheckPoint checkPoint, <END> Cache<K, V> cache) { return Mocks.blockingMock(checkPoint, CacheNotifier.class, cache, (stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false))); }</code><technical_language>void</technical_language>

Target:
private static <K, V> void blockNotifierPartitionStatusChanged(final CheckPoint checkPoint, Cache<K, V> cache) { Mocks.blockingMock(checkPoint, CacheNotifier.class, cache, (stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false))); }
Source:
<code>public void onUpgrade(SQLiteDatabase db, int oldVersion) throws SQLException { switch (oldVersion) { case 1: upgradeToVersion2(db); case 2: case 3: upgradeToVersion4(db, oldVersion); case 4: upgradeToVersion5(db); case 5: upgradeToVersion6(db); case 6: upgradeToVersion7(db); case 7: upgradeToVersion8(db); <START> break; <END> case 8: upgradeToVersion9(db); default: Timber.i("Unknown version %s", oldVersion); } }</code><technical_language>Move break allow upgrades versions other 8</technical_language>

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion) throws SQLException { switch (oldVersion) { case 1: upgradeToVersion2(db); case 2: case 3: upgradeToVersion4(db, oldVersion); case 4: upgradeToVersion5(db); case 5: upgradeToVersion6(db); case 6: upgradeToVersion7(db); case 7: upgradeToVersion8(db); case 8: upgradeToVersion9(db); } }
Source:
<code>public void loadIds(Map<ResourceLocation, Integer> ids, Map<ResourceLocation, Integer> missingIds, Map<ResourceLocation, Integer[]> remappedIds, FMLControlledNamespacedRegistry<I> currentRegistry, ResourceLocation registryName) { for (Map.Entry<ResourceLocation, Integer> entry : ids.entrySet()) { ResourceLocation itemName = entry.getKey(); int newId = entry.getValue(); int currId = currentRegistry.getId(itemName); if (currId == -1) { FMLLog.info("Found a missing id from the world %s", itemName); <START> if(!itemName.getResourceDomain().equals("minecraft")) <END> { missingIds.put(itemName, newId); } else { FMLLog.fine("Ignoring missing vanilla id as minecraft will probably take care of it"); } continue; } else if (currId != newId) { FMLLog.fine("Fixed %s id mismatch %s: %d (init) -> %d (map).", registryName, itemName, currId, newId); remappedIds.put(itemName, new Integer[] {currId, newId}); } I obj = currentRegistry.getRaw(itemName); I sub = obj; if (currentRegistry.substitutionOriginals.containsKey(itemName)) { obj = currentRegistry.substitutionOriginals.get(itemName); } add(newId, itemName, obj); if (currentRegistry.substitutionOriginals.containsKey(itemName) && substitutionCallback != null) { substitutionCallback.onSubstituteActivated(slaves, sub, obj, itemName); } } }</code><technical_language>java if (!itemName.getResourceDomain().equals("minecraft"))</technical_language>

Target:
public void loadIds(Map<ResourceLocation, Integer> ids, Map<ResourceLocation, Integer> missingIds, Map<ResourceLocation, Integer[]> remappedIds, FMLControlledNamespacedRegistry<I> currentRegistry, ResourceLocation registryName) { for (Map.Entry<ResourceLocation, Integer> entry : ids.entrySet()) { ResourceLocation itemName = entry.getKey(); int newId = entry.getValue(); int currId = currentRegistry.getId(itemName); if (currId == -1) { FMLLog.info("Found a missing id from the world %s", itemName); missingIds.put(itemName, newId); continue; } else if (currId != newId) { FMLLog.fine("Fixed %s id mismatch %s: %d (init) -> %d (map).", registryName, itemName, currId, newId); remappedIds.put(itemName, new Integer[] {currId, newId}); } I obj = currentRegistry.getRaw(itemName); I sub = obj; if (currentRegistry.substitutionOriginals.containsKey(itemName)) { obj = currentRegistry.substitutionOriginals.get(itemName); } add(newId, itemName, obj); if (currentRegistry.substitutionOriginals.containsKey(itemName) && substitutionCallback != null) { substitutionCallback.onSubstituteActivated(slaves, sub, obj, itemName); } } }
Source:
<code>public NexusUnexpectedResponseException( final int statusCode, final String statusMessage ) { this( statusCode, statusMessage, String.format( "Unexpected response: %s %s", String.valueOf( statusCode ), String.valueOf( statusMessage ) ) ); <START> } <END></code><technical_language>Uneeded String.valueOf() in arguments String.format()</technical_language>

Target:
public NexusUnexpectedResponseException( final int statusCode, final String statusMessage ) { this( statusCode, statusMessage, String.format( "Unexpected response: %s %s", statusCode, statusMessage ) ); }
Source:
<code>public Page getPageById(Long id) { <START> return pageRepository.findById(id).orElseThrow(() -> new RestException("Not found", 404)); <END> }</code><technical_language>HttpServletResponse.SC_NOT_FOUND</technical_language>

Target:
public Page getPageById(Long id) { return pageRepository.findById(id).orElseThrow(() -> new RestException("Not found", HttpServletResponse.SC_NOT_FOUND)); }
Source:
<code>public RqFake(final List<String> head, final InputStream body) { super( <START> new RqOf( <END> () -> Collections.unmodifiableList(head), () -> body ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RqFake(final List<String> head, final InputStream body) { super(new RequestOf(Collections.unmodifiableList(head), body)); }
Source:
<code>public List<String> getSecurityGroups() { return this.configuration.get(List.class, <START> "security:groups", <END> new ArrayList()); }</code><technical_language>constant</technical_language>

Target:
public List<String> getSecurityGroups() { return this.configuration.get(List.class, SECURITY_GROUPS, new ArrayList()); }
Source:
<code>public boolean isTrue(State state, String[] params) { ObjectInstance tool = state.getObject(params[1]); ObjectInstance container = state.getObject(params[2]); Set<String> contents = ContainerFactory.getContentNames(container); <START> if (!params[2].equalsIgnoreCase("")) { <END> if (contents.isEmpty()) { return false; } ObjectInstance ingredient; for (String name : contents) { ingredient = state.getObject(name); boolean match = false; for (IngredientRecipe content : this.topLevelIngredient.getConstituentIngredients()) { if (content.getName().equals(ingredient.getName())) { if (!ToolFactory.toolCanBeUsed(tool, content)) { return false; } if (!ToolFactory.toolHasBeenUsed(tool, content)) { return false; } match = true; break; } } if (!match) { AbstractMap<String, IngredientRecipe> necessaryTraits = this.topLevelIngredient.getNecessaryTraits(); Set<String> toMeltTraits = IngredientFactory.getTraits(ingredient); for (String trait : necessaryTraits.keySet()) { if (toMeltTraits.contains(trait)) { IngredientRecipe ing = necessaryTraits.get(trait); if (ToolFactory.toolCanBeUsed(tool, ing) && ToolFactory.toolHasBeenUsed(tool, ing)) { match = true; break; } } } if (!match) { return false; } } } return true; } else { for (IngredientRecipe content : topLevelIngredient.getConstituentIngredients()) { if (ToolFactory.toolHasBeenUsed(tool, content)) { return true; } } AbstractMap<String, IngredientRecipe> traitMap = topLevelIngredient.getConstituentNecessaryTraits(); for (String trait : traitMap.keySet()) { if (ToolFactory.toolHasBeenUsed(tool, traitMap.get(trait))) { return true; } } return false; } }</code><technical_language>is a lot of levels of controls in this method. broken methods for readability</technical_language>

Target:
public boolean isTrue(State state, String[] params) { ObjectInstance tool = state.getObject(params[1]); return this.recipe.getRecipeToolAttributes().contains(ToolFactory.getToolAttribute(tool)); }
Source:
<code>public static boolean isFreePlan(long planID) { <START> return planID == 2002 || planID == 1; <END> }</code><technical_language>values defined in PlanConstants.java instead of 2002 1 here</technical_language>

Target:
public static boolean isFreePlan(long planID) { return planID == PlansConstants.JETPACK_FREE_PLAN_ID || planID == PlansConstants.FREE_PLAN_ID; }