auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static PrePushHook prePush(Repository repo, PrintStream outputStream) { if (LfsFactory.getInstance().isAvailable()) { PrePushHook hook = LfsFactory.getInstance().getPrePushHook(repo, outputStream); if (hook != null) { if (hook.isNativeHookPresent()) { <START> (outputStream == null ? System.out : outputStream).println( <END> MessageFormat .format(JGitText.get().lfsHookConflict, repo)); } return hook; } } return new PrePushHook(repo, outputStream); }</code><technical_language>I feel this more readable if-else ternary operator</technical_language>

Target:
public static PrePushHook prePush(Repository repo, PrintStream outputStream) { if (LfsFactory.getInstance().isAvailable()) { PrePushHook hook = LfsFactory.getInstance().getPrePushHook(repo, outputStream); if (hook != null) { if (hook.isNativeHookPresent()) { PrintStream ps = outputStream; if (ps == null) { ps = System.out; } ps.println(MessageFormat .format(JGitText.get().lfsHookConflict, repo)); } return hook; } } return new PrePushHook(repo, outputStream); }
Source:
<code>private Users mapUsers(List<LdapUser> entities) { Users collection = new Users(); for (LdapUser entity : entities) { User user = map(entity); user = addLinks(user, true); <START> user = modifyDomain(user); <END> collection.getUsers().add(user); } return collection; }</code><technical_language>please add populate(...)</technical_language>

Target:
private Users mapUsers(List<LdapUser> entities) { Users collection = new Users(); for (LdapUser entity : entities) { User user = map(entity); user = populate(user, entity); user = addLinks(user, true); collection.getUsers().add(user); } return collection; }
Source:
<code>private Map<String, Long> getNavMarker(boolean current) { Collection<Source> sources = client.getAllSources(); HashMap<String, Long> newMarker = Maps. newHashMap(); for (Source source : sources) { String id = source.getIdentity(); <START> Long sourceExtractIteration = source.getSourceExtractIteration(); <END> if (sourceExtractIteration == null) { sourceExtractIteration = 0L; } newMarker.put(id, sourceExtractIteration); } return newMarker; }</code><technical_language>this change</technical_language>

Target:
private Map<String, Long> getNavMarker(boolean current) { Collection<Source> sources = client.getAllSources(); HashMap<String, Long> newMarker = Maps. newHashMap(); for (Source source : sources) { String id = source.getIdentity(); Long sourceExtractIteration = !current ? 0L : source.getSourceExtractIteration() != null ? source.getSourceExtractIteration() : 0L; newMarker.put(id, sourceExtractIteration); } return newMarker; }
Source:
<code>public Map<String, String> asMap(Locale locale) { Assert.notNull(locale, "locale is null"); if (codeListTable.containsRow(locale)) { if (logger.isDebugEnabled()) { logger.debug("Found codelist for specified locale '{}'.", locale); } return codeListTable.row(locale); } Locale langOnlyLocale = new Locale(locale.getLanguage()); if (codeListTable.containsRow(langOnlyLocale)) { if (logger.isDebugEnabled()) { logger.debug( "Found codelist for specified locale '{}' (language only).", locale); } return codeListTable.row(langOnlyLocale); } if (locale.equals(fallbackTo)) { throw new IllegalStateException("No codelist found for specified locale and fail to fallback"); <START> } <END> if (logger.isDebugEnabled()) { logger.debug( "There is no codelist for specified locale '{}'. Use '{}' as fallback.", locale, fallbackTo); } return asMap(fallbackTo); }</code><technical_language>[x] I return Null instead of IllegalStateException if CodeList of locales, , respecting previous design</technical_language>

Target:
public Map<String, String> asMap(Locale locale) { Assert.notNull(locale, "locale is null"); Locale resolvedLocale = resolveLocale(locale); return codeListTable.row(resolvedLocale); }
Source:
<code>public Builder(@NotNull Request req) { <START> if(req == null) { <END> throw new NullPointerException("`req` cannot be null"); } this.id = req.getId(); this.transportHeaders.put( TransportHeaders.ARG_SCHEME_KEY, req.getTransportHeaders().get(TransportHeaders.ARG_SCHEME_KEY) ); }</code><technical_language>need for manual check</technical_language>

Target:
public Builder(@NotNull Request req) { this.id = req.getId(); this.transportHeaders.put( TransportHeaders.ARG_SCHEME_KEY, req.getTransportHeaders().get(TransportHeaders.ARG_SCHEME_KEY) ); }
Source:
<code>void complete(BitmapHunter hunter) { <START> Action action = hunter.getAction(); <END> List<Action> joined = hunter.getActions(); boolean hasMultiple = joined != null && !joined.isEmpty(); boolean shouldDeliver = action != null || hasMultiple; if (!shouldDeliver) { return; } Uri uri = hunter.getData().uri; Exception exception = hunter.getException(); Bitmap result = hunter.getResult(); LoadedFrom from = hunter.getLoadedFrom(); if (action != null) { deliverAction(result, from, action); } if (hasMultiple) { for (int i = 0, n = joined.size(); i < n; i++) { Action join = joined.get(i); deliverAction(result, from, join); } } if (listener != null && exception != null) { listener.onImageLoadFailed(this, uri, exception); } }</code><technical_language>This remain "single". Hunters a "single" action "joined" actions</technical_language>

Target:
void complete(BitmapHunter hunter) { Action single = hunter.getAction(); List<Action> joined = hunter.getActions(); boolean hasMultiple = joined != null && !joined.isEmpty(); boolean shouldDeliver = single != null || hasMultiple; if (!shouldDeliver) { return; } Uri uri = hunter.getData().uri; Exception exception = hunter.getException(); Bitmap result = hunter.getResult(); LoadedFrom from = hunter.getLoadedFrom(); if (single != null) { deliverAction(result, from, single); } if (hasMultiple) { for (int i = 0, n = joined.size(); i < n; i++) { Action join = joined.get(i); deliverAction(result, from, join); } } if (listener != null && exception != null) { listener.onImageLoadFailed(this, uri, exception); } }
Source:
<code>public void commit(Map<DatastreamTask, String> checkpoints) { LOG.info("Commit called with checkpoints " + checkpoints.toString()); Validate.notNull(checkpoints, "Checkpoints should not be null"); checkpoints.forEach((key, value) -> { _zkAdapter.setDatastreamTaskStateForKey(key, CHECKPOINT_KEY_NAME, value); if (key.getDatastreamDestination().hasConnectionString()) { String topicName = key.getDatastreamDestination().getConnectionString(); <START> _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), topicName, NUM_CHECKPOINT_COMMITS, 1); <END> } }); }</code><technical_language>I need topic level checkpoint metrics, Commit latency number of commits in aggregate is enough, Thoughts</technical_language>

Target:
public void commit(Map<DatastreamTask, String> checkpoints) { LOG.info("Commit called with checkpoints " + checkpoints.toString()); Validate.notNull(checkpoints, "Checkpoints should not be null"); long startTime = System.currentTimeMillis(); checkpoints.forEach((key, value) -> { _zkAdapter.setDatastreamTaskStateForKey(key, CHECKPOINT_KEY_NAME, value); _numCheckpointCommits.inc(); }); _checkpointCommitLatency.update(System.currentTimeMillis() - startTime); }
Source:
<code>public static AvailabilitySetProperties create(final int platformUpdateDomainCount, final int platformFaultDomainCount, List<AvailabilitySetVirtualMachine> virtualMachines) { return new AutoValue_AvailabilitySet_AvailabilitySetProperties(platformUpdateDomainCount, platformFaultDomainCount, <START> virtualMachines); <END> }</code><technical_language>Initialize null immutable copy</technical_language>

Target:
public static AvailabilitySetProperties create(final int platformUpdateDomainCount, final int platformFaultDomainCount, List<AvailabilitySetVirtualMachine> virtualMachines) { return new AutoValue_AvailabilitySet_AvailabilitySetProperties(platformUpdateDomainCount, platformFaultDomainCount, virtualMachines == null ? null : ImmutableList.copyOf(virtualMachines)); }
Source:
<code>private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) { List<Criteria> criteriaList = getFiltersCriteria(filters); <START> if (existingCriteria != null) { <END> criteriaList.add(existingCriteria); } Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()])); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(criteria), Aggregation.group().count().as("count") ); AggregationResults<VariantAggregationCount> aggregationResults = mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class); return aggregationResults.getMappedResults().size() > 0 ? aggregationResults.getMappedResults().get(0).getCount() : 0; }</code><technical_language>is correct omit existingCriteria if null? if null, this if is bad: delays detection of a missing value, add else explanatory message (if field requires clarification null) throw NPE</technical_language>

Target:
private long countByComplexFiltersHelper(Criteria existingCriteria, List<VariantEntityRepositoryFilter> filters) { List<Criteria> criteriaList = getFiltersCriteria(filters); criteriaList.add(existingCriteria); Criteria criteria = new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()])); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(criteria), Aggregation.group().count().as("count") ); AggregationResults<VariantAggregationCount> aggregationResults = mongoTemplate.aggregate(aggregation, VariantEntity.class, VariantAggregationCount.class); return aggregationResults.getMappedResults().size() > 0 ? aggregationResults.getMappedResults().get(0).getCount() : 0; }
Source:
<code>public boolean canMoveToMaintenance(VDS vds) { if (!Config.<Boolean>getValue(ConfigValues.MaintenanceVdsIgnoreExternalVms)) { return vds.getVmCount() == 0 && !isAnyVmRunOnVdsInDb(vds.getId()); } Optional<VM> runningVm = vmDao.getAllRunningForVds(vds.getId()) .stream() .filter(vm -> !vm.isExternalVm()) .findFirst(); return !runningVm.isPresent() && <START> !isAnyVmRunOnVdsInDb(vds.getId()); <END> }</code><technical_language>vds.getVmCount returns number of VMs host reports while isAnyVmRunOnVdsInDb checks in database. here, is reason cal isAnyVmRunOnVdsInDb part checked database, do check</technical_language>

Target:
public boolean canMoveToMaintenance(VDS vds) { if (!Config.<Boolean>getValue(ConfigValues.MaintenanceVdsIgnoreExternalVms)) { return vds.getVmCount() == 0 && !isAnyVmRunOnVdsInDb(vds.getId()); } return !anyNonExternalVmRunning(vds); }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) <START> .add("_key", _key) <END> .add("_value", _value) .toString(); }</code><technical_language>match conventional toString implementation</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Key", _key) .add("Value", _value) .toString(); }
Source:
<code>public void register(String jobName, Collection<Step> steps) { Assert.notNull(jobName, "The job name cannot be null."); Assert.notNull(steps, "The job steps cannot be null."); <START> unregisterStepsFromJob(jobName); <END> synchronized (this.map) { final Map<String, Step> jobSteps = new HashMap<String, Step>(); for (Step step : steps) { jobSteps.put(step.getName(), step); } this.map.put(jobName, jobSteps); } }</code><technical_language>registering a Job, throw a DuplicateJobException if registered put onus caller unregister first. arguing other, I expect behavior similar calls..</technical_language>

Target:
public void register(String jobName, Collection<Step> steps) throws DuplicateJobException { Assert.notNull(jobName, "The job name cannot be null."); Assert.notNull(steps, "The job steps cannot be null."); final Map<String, Step> jobSteps = new HashMap<String, Step>(); for (Step step : steps) { jobSteps.put(step.getName(), step); } final Object previousValue = map.putIfAbsent(jobName, jobSteps); if (previousValue != null) { throw new DuplicateJobException("A job configuration with this name [" + jobName + "] was already registered"); } }
Source:
<code><START> public static List<GeneratorSwitch> getGeneratorSwitches(Stream<Project> projects, List<Folder> contentFolders) { <END> Stream<Project> projectsWithSourceFolder = projects.filter(λ -> Objects.nonNull(λ.getGeneratorSource())); Stream<Pair<Folder, Folder>> foldersWithSources = projectsWithSourceFolder .flatMap(λ -> λ.getFolders().stream().map(μ -> Pair.of(μ, λ.getGeneratorSource()))); Stream<Folder> allowedFolders = foldersWithSources.filter(λ -> !λ.getLeft().equals(λ.getRight())) .map(λ -> λ.getLeft()); Stream<Folder> generatableFolders = allowedFolders.filter(λ -> λ.getDerivative().isPresent() || λ.getDpi().isPresent() || λ.getImageScale().isPresent() || λ.getImageSize().isPresent()); Stream<GeneratorSwitch> taskGenerators = generatableFolders.map(λ -> new GeneratorSwitch(λ, contentFolders)); return new LinkedList<GeneratorSwitch>() { { taskGenerators.forEach(this::add); } }; }</code><technical_language>code redundancy Task bean</technical_language>

Target:
public static List<GeneratorSwitch> getGeneratorSwitches(Stream<Project> projects, List<Folder> contentFolders) { Stream<Project> projectsWithSourceFolder = projects.filter(λ -> Objects.nonNull(λ.getGeneratorSource())); Stream<Folder> allowedFolders = dropOwnSourceFolders(projectsWithSourceFolder); Stream<Folder> generatableFolders = allowedFolders.filter(λ -> λ.getDerivative().isPresent() || λ.getDpi().isPresent() || λ.getImageScale().isPresent() || λ.getImageSize().isPresent()); Stream<GeneratorSwitch> taskGenerators = generatableFolders.map(λ -> new GeneratorSwitch(λ, contentFolders)); List<GeneratorSwitch> result = taskGenerators.collect(Collectors.toCollection(LinkedList::new)); return result; }
Source:
<code>public DefaultTreeModel updateModel(Map<VirtualFile, Collection<LocalIssuePointer>> map, Predicate<VirtualFile> filePredicate) { this.filePredicate = filePredicate; index.getAllFiles().stream() .filter(f -> !map.containsKey(f)) <START> .forEach(this::removeFile); <END> for (Map.Entry<VirtualFile, Collection<LocalIssuePointer>> e : map.entrySet()) { setFileIssues(e.getKey(), e.getValue(), filePredicate); } return model; }</code><technical_language>This ConcurrentModificationException: removing items underlying collection while iterating</technical_language>

Target:
public DefaultTreeModel updateModel(Map<VirtualFile, Collection<LocalIssuePointer>> map, Predicate<VirtualFile> filePredicate) { this.filePredicate = filePredicate; index.getAllFiles().removeIf(f -> !map.containsKey(f)); for (Map.Entry<VirtualFile, Collection<LocalIssuePointer>> e : map.entrySet()) { setFileIssues(e.getKey(), e.getValue(), filePredicate); } return model; }
Source:
<code><START> private Type actualIteratorTypeArgument(Type type) { <END> if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Not supported type " + type.toString()); } ParameterizedType parameterizedType = (ParameterizedType) type; if (!Iterator.class.equals(parameterizedType.getRawType())) { throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); } return ((ParameterizedType) type).getActualTypeArguments()[0]; }</code><technical_language>this static</technical_language>

Target:
private static Type actualIteratorTypeArgument(Type type) { if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Not supported type " + type.toString()); } ParameterizedType parameterizedType = (ParameterizedType) type; if (!Iterator.class.equals(parameterizedType.getRawType())) { throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); } return ((ParameterizedType) type).getActualTypeArguments()[0]; }
Source:
<code>public Void visitSpatialJoin(SpatialJoinNode node, Set<Symbol> boundSymbols) { node.getLeft().accept(this, boundSymbols); node.getRight().accept(this, boundSymbols); <START> <END> Set<Symbol> leftInputs = createInputs(node.getLeft(), boundSymbols); Set<Symbol> rightInputs = createInputs(node.getRight(), boundSymbols); Set<Symbol> allInputs = ImmutableSet.<Symbol>builder() .addAll(leftInputs) .addAll(rightInputs) .build(); Set<Symbol> predicateSymbols = SymbolsExtractor.extractUnique(node.getFilter()); checkArgument( allInputs.containsAll(predicateSymbols), "Symbol from filter (%s) not in sources (%s)", predicateSymbols, allInputs); int leftMaxPosition = -1; Optional<Integer> rightMinPosition = Optional.empty(); Set<Symbol> leftSymbols = new HashSet<>(node.getLeft().getOutputSymbols()); for (int i = 0; i < node.getOutputSymbols().size(); i++) { Symbol symbol = node.getOutputSymbols().get(i); if (leftSymbols.contains(symbol)) { leftMaxPosition = i; } else if (!rightMinPosition.isPresent()) { rightMinPosition = Optional.of(i); } } checkState(!rightMinPosition.isPresent() || rightMinPosition.get() > leftMaxPosition, "Not all left output symbols are before right output symbols"); return null; }</code><technical_language>This code trivial. Please extract a method</technical_language>

Target:
public Void visitSpatialJoin(SpatialJoinNode node, Set<Symbol> boundSymbols) { node.getLeft().accept(this, boundSymbols); node.getRight().accept(this, boundSymbols); Set<Symbol> leftInputs = createInputs(node.getLeft(), boundSymbols); Set<Symbol> rightInputs = createInputs(node.getRight(), boundSymbols); Set<Symbol> allInputs = ImmutableSet.<Symbol>builder() .addAll(leftInputs) .addAll(rightInputs) .build(); Set<Symbol> predicateSymbols = SymbolsExtractor.extractUnique(node.getFilter()); checkArgument( allInputs.containsAll(predicateSymbols), "Symbol from filter (%s) not in sources (%s)", predicateSymbols, allInputs); checkLeftOutputSymbolsBeforeRight(node.getLeft().getOutputSymbols(), node.getOutputSymbols()); return null; }
Source:
<code><START> private String selectActionsAndSteps() { <END> if (DbConnectionFactory.isMySql()) { return MYSQL_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isOracle()) { return ORACLE_SELECT_ACTIONS_AND_STEPS; } else { return null; } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Reduce number of returns of this method 5, maximum allowed 3. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private String selectActionsAndSteps() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_SELECT_ACTIONS_AND_STEPS; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_SELECT_ACTIONS_AND_STEPS; } return sql; }
Source:
<code>protected static void cleanProjects() { new ShellMenuItem(new WithTextMatcher("Project"), new RegexMatcher("Clean.*")).select(); <START> new WaitUntil(new ShellIsActive("Clean")); <END> new PushButton("OK").click(); new WaitWhile(new ShellIsActive("Clean")); new WaitWhile(new JobIsRunning()); }</code><technical_language>ShellIsAvailable</technical_language>

Target:
protected static void cleanProjects() { new ShellMenuItem(new WithTextMatcher("Project"), new RegexMatcher("Clean.*")).select(); new WaitUntil(new ShellIsAvailable("Clean")); new PushButton("OK").click(); new WaitWhile(new ShellIsAvailable("Clean")); new WaitWhile(new JobIsRunning()); }
Source:
<code><START> if(isUniversalBuffer) { <END> bufferClsName = "org.msgpack.core.buffer.MessageBufferU"; unsafe = null; ARRAY_BYTE_BASE_OFFSET = 16; ARRAY_BYTE_INDEX_SCALE = 1; }</code><technical_language>this more robust? try { if (!isUniversalBuffer) { : boolean isLittleEndian = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; if(isLittleEndian) { bufferClsName = "org.msgpack.core.buffer.MessageBuffer"; } else { bufferClsName = "org.msgpack.core.buffer.MessageBufferBE"; } } } catch { // MessageBufferU } if (bufferClsName == null) { bufferClsName = "org.msgpack.core.buffer.MessageBufferU"; : }</technical_language>

Target:
if(isUniversalBuffer) { bufferClsName = UNIVERSAL_MESSAGE_BUFFER; }
Source:
<code>public static byte[] getRowKey(long txnId) { long beginTS = txnId & SIConstants.TRANSANCTION_ID_MASK; byte[] rowKey = new byte[9]; rowKey[0] = (byte)((beginTS / SIConstants.TRASANCTION_INCREMENT) & (TRANSACTION_TABLE_BUCKET_COUNT-1)); <START> rowKey[0] = (byte)(2); <END> Bytes.longToBytes(beginTS, rowKey, 1); return rowKey; }</code><technical_language>Remove</technical_language>

Target:
public static byte[] getRowKey(long txnId) { long beginTS = txnId & SIConstants.TRANSANCTION_ID_MASK; byte[] rowKey = new byte[9]; rowKey[0] = (byte)((beginTS / SIConstants.TRASANCTION_INCREMENT) & (TRANSACTION_TABLE_BUCKET_COUNT-1)); Bytes.longToBytes(beginTS, rowKey, 1); return rowKey; }
Source:
<code>public String getInitiateCollectionActivityDocumentUrl(String proposalNumber, String invoiceNumber) { String initiateUrl = KRADConstants.EMPTY_STRING; Properties parameters = new Properties(); parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.DOC_HANDLER_METHOD); if (!org.apache.commons.lang.StringUtils.isBlank(proposalNumber)) { parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_PROPOSAL_NUMBER, proposalNumber); } parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_INVOICE_DOCUMENT_NUMBER, invoiceNumber); parameters.put(KFSConstants.PARAMETER_COMMAND, KFSConstants.INITIATE_METHOD); parameters.put(KFSConstants.DOCUMENT_TYPE_NAME, ArConstants.ArDocumentTypeCodes.CONTRACTS_GRANTS_COLLECTION_ACTIVTY); <START> final String baseUrl = !org.apache.commons.lang.StringUtils.isBlank(proposalNumber) <END> ? getBaseContractsGrantsCollectionActivityDocumentUrl() : KFSConstants.EMPTY_STRING; initiateUrl = UrlFactory.parameterizeUrl(baseUrl, parameters); return initiateUrl; }</code><technical_language>specific this changeset, is a reason 2 StringUtils in this class</technical_language>

Target:
public String getInitiateCollectionActivityDocumentUrl(String proposalNumber, String invoiceNumber) { String initiateUrl = KRADConstants.EMPTY_STRING; Properties parameters = new Properties(); parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.DOC_HANDLER_METHOD); if (StringUtils.hasText(proposalNumber)) { parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_PROPOSAL_NUMBER, proposalNumber); } parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_INVOICE_DOCUMENT_NUMBER, invoiceNumber); parameters.put(KFSConstants.PARAMETER_COMMAND, KFSConstants.INITIATE_METHOD); parameters.put(KFSConstants.DOCUMENT_TYPE_NAME, ArConstants.ArDocumentTypeCodes.CONTRACTS_GRANTS_COLLECTION_ACTIVTY); final String baseUrl = StringUtils.hasText(proposalNumber) ? getBaseContractsGrantsCollectionActivityDocumentUrl() : KFSConstants.EMPTY_STRING; initiateUrl = UrlFactory.parameterizeUrl(baseUrl, parameters); return initiateUrl; }
Source:
<code>private Map<String, String> getTraceProperties() { for (ITmfTrace openedTrace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace singleTrace : TmfTraceManager.getTraceSet(openedTrace)) { <START> if (this.getLocation().toString().matches("(.*)" + singleTrace.getPath())) { END> if (singleTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) singleTrace; return traceProperties.getTraceProperties(); } } } } return new HashMap<String, String>(); }</code><technical_language>endsWith instead of matches? need string</technical_language>

Target:
private Map<String, String> getTraceProperties() { for (ITmfTrace openedTrace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace singleTrace : TmfTraceManager.getTraceSet(openedTrace)) { if (this.getLocation().toString().endsWith(singleTrace.getPath())) { if (singleTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) singleTrace; return traceProperties.getTraceProperties(); } } } } return new HashMap<String, String>(); }
Source:
<code>public void persist(final Runnable commitRunnable) { final List<Pair<FireHydrant, Interval>> indexesToPersist = Lists.newArrayList(); for (Sink sink : sinks.values()) { if (sink.swappable()) { indexesToPersist.add(Pair.of(sink.swap(), sink.getInterval())); } } log.info("Submitting persist runnable for dataSource[%s]", schema.getDataSource()); final Stopwatch runExecStopwatch = Stopwatch.createStarted(); final Stopwatch persistStopwatch = Stopwatch.createStarted(); persistExecutor.execute( new ThreadRenamingRunnable(String.format("%s-incremental-persist", schema.getDataSource())) { @Override public void doRun() { try { for (Pair<FireHydrant, Interval> pair : indexesToPersist) { metrics.incrementRowOutputCount(persistHydrant(pair.lhs, schema, pair.rhs)); } commitRunnable.run(); } catch (Exception e) { <START> metrics.incrementFailedPersists(); <END> } finally { metrics.incrementNumPersists(); metrics.incrementPersistTimeMillis(persistStopwatch.elapsed(TimeUnit.MILLISECONDS)); persistStopwatch.stop(); } } } ); final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.incrementPersistBackPressureMillis(startDelay); if (startDelay > WARN_DELAY) { log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay); } runExecStopwatch.stop(); }</code><technical_language>suppress exception here</technical_language>

Target:
public void persist(final Runnable commitRunnable) { final List<Pair<FireHydrant, Interval>> indexesToPersist = Lists.newArrayList(); for (Sink sink : sinks.values()) { if (sink.swappable()) { indexesToPersist.add(Pair.of(sink.swap(), sink.getInterval())); } } log.info("Submitting persist runnable for dataSource[%s]", schema.getDataSource()); final Stopwatch runExecStopwatch = Stopwatch.createStarted(); final Stopwatch persistStopwatch = Stopwatch.createStarted(); persistExecutor.execute( new ThreadRenamingRunnable(String.format("%s-incremental-persist", schema.getDataSource())) { @Override public void doRun() { try { for (Pair<FireHydrant, Interval> pair : indexesToPersist) { metrics.incrementRowOutputCount(persistHydrant(pair.lhs, schema, pair.rhs)); } commitRunnable.run(); } catch (Exception e) { metrics.incrementFailedPersists(); throw e; } finally { metrics.incrementNumPersists(); metrics.incrementPersistTimeMillis(persistStopwatch.elapsed(TimeUnit.MILLISECONDS)); persistStopwatch.stop(); } } } ); final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.incrementPersistBackPressureMillis(startDelay); if (startDelay > WARN_DELAY) { log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay); } runExecStopwatch.stop(); }
Source:
<code>protected void addJREClasspathContainer(IClasspathDescriptor classpath, String environmentId) { IClasspathEntry cpe; IExecutionEnvironment executionEnvironment = getExecutionEnvironment(environmentId); if(executionEnvironment == null) { cpe = JavaRuntime.getDefaultJREContainerEntry(); } else { IPath containerPath = JavaRuntime.newJREContainerPath(executionEnvironment); cpe = JavaCore.newContainerEntry(containerPath); } classpath.addAndReplaceEntry(cpe, new ClasspathDescriptor.EntryFilter() { public boolean accept(IClasspathEntryDescriptor descriptor) { return JavaRuntime.JRE_CONTAINER.equals(descriptor.getPath().segment(0)); <START> } <END> }); }</code><technical_language>I is split "addAndReplace" method in "replaceEntry", replace existing entry return null if exists. "addEntry", add new entry. This classpath order fully controlled this AbstractJavaProjectConfigurator, side effect of addAndReplace method implementation</technical_language>

Target:
protected void addJREClasspathContainer(IClasspathDescriptor classpath, String environmentId) { IClasspathEntry cpe; IExecutionEnvironment executionEnvironment = getExecutionEnvironment(environmentId); if(executionEnvironment == null) { cpe = JavaRuntime.getDefaultJREContainerEntry(); } else { IPath containerPath = JavaRuntime.newJREContainerPath(executionEnvironment); cpe = JavaCore.newContainerEntry(containerPath); } IClasspathEntryDescriptor cped = classpath.replaceEntry(new ClasspathDescriptor.EntryFilter() { public boolean accept(IClasspathEntryDescriptor descriptor) { return JavaRuntime.JRE_CONTAINER.equals(descriptor.getPath().segment(0)); } }, cpe); if(cped == null) { classpath.addEntry(cpe); } }
Source:
<code>public String getMoveAfterErrors() { if (resolveHostsDynamically) { try { return VFSUtils.resolveUriHost(moveAfterErrors); } catch (UnknownHostException | FileSystemException e) { <START> log.warn("Unable to resolving hostname of transport.vfs.MoveAfterErrors: " + <END> VFSUtils.maskURLPassword(moveAfterErrors), e); } } return moveAfterErrors; }</code><technical_language>Is this a Warning actual error</technical_language>

Target:
public String getMoveAfterErrors() { if (resolveHostsDynamically) { try { return VFSUtils.resolveUriHost(moveAfterErrors); } catch (UnknownHostException | FileSystemException e) { log.warn("Unable to resolve the hostname of transport.vfs.MoveAfterErrors: " + VFSUtils.maskURLPassword(moveAfterErrors), e); } } return moveAfterErrors; }
Source:
<code>public CliCommand init(final Arguments args) throws Exception { this.id = UUID.fromString(args.getId()); if (this.id == null) { throw new MissingOptionException("The eject storage domain command requires '-i' to be set."); } <START> this.bucket = args.getBucket(); <END> this.ejectLabel = args.GetEjectLabel(); this.ejectLocation = args.GetEjectLocation(); return this; }</code><technical_language>In jira request Jeff requested this a required arg</technical_language>

Target:
public CliCommand init(final Arguments args) throws Exception { if (args.getId() == null) { throw new MissingOptionException("The eject storage domain command requires '-i' to be set."); } this.id = UUID.fromString(args.getId()); this.bucket = args.getBucket(); if (Guard.isStringNullOrEmpty(this.bucket)) { throw new MissingOptionException("The eject storage domain command requires '-b' to be set."); } this.ejectLabel = args.GetEjectLabel(); this.ejectLocation = args.GetEjectLocation(); return this; }
Source:
<code>public void updateDocument(String operation, IndexDocumentBean idb) throws IndexingException { try { SolrInputDocument sid = new SolrInputDocument(); Map<String, Object> fields = idb.getDynamicFields(); for (Entry<String, Object> field : fields.entrySet()) { String fieldName = field.getKey(); if (UPDATE_TIMESTAMP.equals(fieldName)) { continue; } Object value = field.getValue(); if (ID.getSolrField().equals(fieldName)) { sid.addField(fieldName, value); continue; } } <START> <END> if (log.isDebugEnabled()) { log.debug("Performing partial update:\n{}", ClientUtils.toXML(sid)); } updateSolrClient.add(sid); } catch (IOException e) { throw new IndexingException("Failed to add document to solr", e); } catch (SolrServerException e) { throw new IndexingException("Failed to add document to solr", e); } }</code><technical_language>I a part is missing <LINK_0></technical_language>

Target:
public void updateDocument(String operation, IndexDocumentBean idb) throws IndexingException { try { SolrInputDocument sid = new SolrInputDocument(); Map<String, Object> fields = idb.getDynamicFields(); for (Entry<String, Object> field : fields.entrySet()) { String fieldName = field.getKey(); if (UPDATE_TIMESTAMP.equals(fieldName)) { continue; } Object value = field.getValue(); if (ID.getSolrField().equals(fieldName)) { sid.addField(fieldName, value); continue; } Map<String, Object> partialUpdate = new HashMap<>(); partialUpdate.put(operation, value); sid.setField(fieldName, partialUpdate); } if (log.isDebugEnabled()) { log.debug("Performing partial update:\n{}", ClientUtils.toXML(sid)); } updateSolrClient.add(sid); } catch (IOException e) { throw new IndexingException("Failed to add document to solr", e); } catch (SolrServerException e) { throw new IndexingException("Failed to add document to solr", e); } }
Source:
<code><START> public ProgramState stackValue(SymbolicValue sv) { <END> Deque<SymbolicValue> newStack = new LinkedList<>(stack); newStack.push(sv); return new ProgramState(this, newStack); }</code><technical_language>public</technical_language>

Target:
ProgramState stackValue(SymbolicValue sv) { Deque<SymbolicValue> newStack = new LinkedList<>(stack); newStack.push(sv); return new ProgramState(this, newStack); }
Source:
<code>protected List<String> getPrefixKeys(String key) { List<String> ret = new ArrayList<>(10); Iterable<String> split = Splitter.on('.').split(key); String path = null; for (String part : split) { if (path == null) { path = part; } else { path += "." + part; } ret.add(path); } if (path == null) { ret.add(key); } <START> return ret; <END> }</code><technical_language>I iterating of string find . characters creating a new substring time faster, substring allocations fast (reuse char[] of string new allocation)</technical_language>

Target:
protected List<String> getPrefixKeys(String key) { List<String> ret = new ArrayList<>(10); int i=0; while ((i = key.indexOf('.', i)) > 0) { ret.add(key.substring(0, i++)); } ret.add(key); return ret; }
Source:
<code>public int compareTo(final ITmfTimestamp ts) { long value = getValue(); int scale = getScale(); if (BIG_BANG.equals(ts)) { return 1; } if (BIG_CRUNCH.equals(ts)) { return -1; } if (this == ts || (value == ts.getValue() && scale == ts.getScale())) { return 0; } if (getScale() == ts.getScale()) { final long delta = saturatedAdd(getValue(), -ts.getValue()); return (delta == 0) ? 0 : (delta > 0) ? 1 : -1; } <START> final ITmfTimestamp nts = ts.normalize(0, scale); <END> if (hasSaturated(ts, nts)) { final long otherValue = ts.getValue(); if (value == 0 && otherValue == 0) { return 0; } if (value < 0 && otherValue >= 0) { return -1; } if (value >= 0 && otherValue < 0) { return 1; } final int otherScale = ts.getScale(); return (scale > otherScale) ? (otherValue >= 0) ? 1 : -1 : (otherValue >= 0) ? -1 : 1; } final long delta = value - nts.getValue(); return Long.compare(delta, 0); }</code><technical_language>Ha! noticed this, normalize smallest scale. Right now, 1234ms > 1s 1s == 1234ms !!! ITmfTimestamp t1 = TmfTimestamp.fromMillis(1234); ITmfTimestamp t2 = TmfTimestamp.fromSeconds(1); assertTrue(t1.compareTo(t2) > 0); assertTrue(t2.compareTo(t1) < 0); assert fails</technical_language>

Target:
public int compareTo(final ITmfTimestamp ts) { long value = getValue(); int scale = getScale(); if (BIG_BANG.equals(ts)) { return 1; } if (BIG_CRUNCH.equals(ts)) { return -1; } if (this == ts || isIdentical(this, ts)) { return 0; } if (scale == ts.getScale()) { if(ts.getValue() == Long.MIN_VALUE){ return 1; } final long delta = saturatedAdd(getValue(), -ts.getValue()); return Long.compare(delta, 0); } final ITmfTimestamp largerScale = (scale > ts.getScale()) ? this : ts; final ITmfTimestamp smallerScale = (scale < ts.getScale()) ? this : ts; final ITmfTimestamp nts = largerScale.normalize(0, smallerScale.getScale()); if (hasSaturated(largerScale, nts)) { if (smallerScale.getScale() == scale) { return Long.compare(0, nts.getValue()); } return Long.compare(nts.getValue(), 0); } if (smallerScale.getScale() == scale) { if(nts.getValue()==Long.MIN_VALUE){ return 1; } final long delta = saturatedAdd(value, - nts.getValue()); return Long.compare(delta, 0); } if (smallerScale.getValue() == Long.MIN_VALUE) { return 1; } final long delta = saturatedAdd(-smallerScale.getValue(), nts.getValue()); return Long.compare(delta, 0); }
Source:
<code>public void getAuthorizationFailureTest() throws Exception { MockId addedId = put(1, PUT_RECORD_SIZE, Utils.Infinite_Time).get(0); assertNotSame("accountId should not be -1 for added Blob.", -1, addedId.getAccountId()); assertNotSame("containerId should not be -1 for added Blob.", -1, addedId.getContainerId()); if (store.getStoreConfig().storeValidateAuthorization == true) { verifyGetFailure(new MockId(addedId.getID()), StoreErrorCodes.Authorization_Failure); } else { <START> store.get(Collections.singletonList(addedId), EnumSet.noneOf(StoreGetOptions.class)); <END> } }</code><technical_language>do this all? succeeds? check return is ok in case</technical_language>

Target:
public void getAuthorizationFailureTest() throws Exception { MockId mockId = put(1, PUT_RECORD_SIZE, Utils.Infinite_Time).get(0); assertNotSame("accountId should not be -1 for added Blob.", -1, mockId.getAccountId()); assertNotSame("containerId should not be -1 for added Blob.", -1, mockId.getContainerId()); short[] accountIds = {-1, Utils.getRandomShort(TestUtils.RANDOM), -1, mockId.getAccountId(), Utils.getRandomShort(TestUtils.RANDOM)}; short[] containerIds = {-1, -1, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort( TestUtils.RANDOM), mockId.getContainerId()}; for (int i = 0; i < accountIds.length; i++) { verifyGetFailure(new MockId(mockId.getID(), accountIds[i], containerIds[i]), StoreErrorCodes.Authorization_Failure); } }
Source:
<code>public Response createNewPayment(JsonNode node) { int amount = node.get("amount").asInt(); String connectorRequestPayload = jsonStringBuilder() .add("amount", amount).build(); JsonNode connectorResponse = ClientBuilder <START> .newClient() <END> .target(config.getConnectorUrl()) .request(APPLICATION_JSON_TYPE) .post( Entity.json(connectorRequestPayload), JsonNode.class ); String payId = connectorResponse.get("pay_id").asText(); String responsePayload = jsonStringBuilder() .add("pay_id", payId) .build(); return Response.ok(responsePayload).build(); }</code><technical_language>Good point. added Dropwizards Jersey Client integration</technical_language>

Target:
public Response createNewPayment(JsonNode node) { int amount = node.get("amount").asInt(); String connectorRequestPayload = jsonStringBuilder() .add("amount", amount).build(); JsonNode connectorResponse = client .target(connectorUrl) .request(APPLICATION_JSON_TYPE) .post( Entity.json(connectorRequestPayload), JsonNode.class ); String payId = connectorResponse.get("pay_id").asText(); String responsePayload = jsonStringBuilder() .add("pay_id", payId) .build(); return Response.ok(responsePayload).build(); }
Source:
<code>public void sortFile() { try { FileReader fileReader = new FileReader(this.resultFile); BufferedReader reader = new BufferedReader(fileReader); String line; ArrayList<String> fullText = new ArrayList<>(); while ((line = reader.readLine()) != null) { fullText.add(line); } System.out.println("Sorting....."); <START> Collections.sort(fullText); <END> String[] sortedText = fullText.toArray(new String[fullText.size()]); this.eraseFile(); this.writeToFile(sortedText); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>Add a //TODO statement optimizing sort for large files</technical_language>

Target:
public void sortFile() { File resultFile = new File(path); try { FileReader fileReader = new FileReader(resultFile); BufferedReader reader = new BufferedReader(fileReader); String line; ArrayList<String> fullText = new ArrayList<>(); while ((line = reader.readLine()) != null) { fullText.add(line); } logger.log(Level.INFO, "Sorting....."); Collections.sort(fullText); String[] sortedText = fullText.toArray(new String[fullText.size()]); this.eraseFile(resultFile); this.writeToFile(sortedText); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public static Object[][] outputFies() { return new Object[][] { {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + VcfUtils.COMPRESSED_VCF_ENDING}, {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + VcfUtils.UNCOMPRESSED_VCF_ENDING}, {STD_OUT_NAME} }; <START> } <END></code><technical_language>Needs a test of output: final ByteArrayOutputStream myOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(myOut));</technical_language>

Target:
public static Object[][] outputFies() { return new Object[][] { {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + IOUtil.COMPRESSED_VCF_FILE_EXTENSION}, {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + IOUtil.VCF_FILE_EXTENSION}, {STD_OUT_NAME} }; }
Source:
<code>public static INDArray expandDims(INDArray input, int dimension) { if (dimension < 0) dimension += input.rank(); long[] shape = input.shape(); long[] indexes = new long[input.rank() + 1]; for (int i = 0; i < indexes.length; i++) indexes[i] = i < dimension ? shape[i] : i == dimension ? 1 : shape[i - 1]; <START> return input.reshape(indexes); <END> }</code><technical_language>order arg is important ND4J works reshaped arrays a view of original</technical_language>

Target:
public static INDArray expandDims(INDArray input, int dimension) { if (dimension < 0) dimension += input.rank(); long[] shape = input.shape(); long[] indexes = new long[input.rank() + 1]; for (int i = 0; i < indexes.length; i++) indexes[i] = i < dimension ? shape[i] : i == dimension ? 1 : shape[i - 1]; return input.reshape(input.ordering(), indexes); }
Source:
<code>public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { MockChartData2D data = new MockChartData2D(editor); addComponent(data); <START> data.addToChart(MockChart.this); <END> data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }</code><technical_language>Is qualifying this necessary? context MockChart already</technical_language>

Target:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(this); data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }
Source:
<code>public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { <START> String countryCode = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); <END> result.set(Geocode.getCountryName(countryCode)); } return result; }</code><technical_language>Arguments.length is checked for above, I is need do again</technical_language>

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && arguments[0] != null) { String countryCode = argumentOI.getPrimitiveJavaObject(arguments[0].get()); result.set(Geocode.getCountryName(countryCode)); } return result; }
Source:
<code>private MenuItem createRefreshMenuItem() { MenuItem refreshMenuItem = new MenuItem("Refresh"); refreshMenuItem.setOnAction((e) -> { logger.info("Menu: View > Refresh"); if (ui.isNotificationPaneShowing()) { <START> Platform.runLater(() -> { <END> ui.triggerNotificationTimeoutAction(); ui.logic.refresh(false); }); } else { ui.logic.refresh(false); } }); refreshMenuItem.setAccelerator(REFRESH); return refreshMenuItem; }</code><technical_language>Is this needed? menu item clicked/navigated UI thread</technical_language>

Target:
private MenuItem createRefreshMenuItem() { MenuItem refreshMenuItem = new MenuItem("Refresh"); refreshMenuItem.setOnAction((e) -> { logger.info("Menu: View > Refresh"); if (ui.isNotificationPaneShowing()) { ui.triggerNotificationTimeoutAction(); } ui.logic.refresh(false); }); refreshMenuItem.setAccelerator(REFRESH); return refreshMenuItem; }
Source:
<code>private LoadingCache<URI, String> createCache() { return CacheBuilder.newBuilder() .maximumSize(100) <START> .expireAfterWrite(LIFE_SPAN_SECS - 10, TimeUnit.SECONDS) <END> .ticker( new Ticker() { @Override public long read() { return TimeUnit.MILLISECONDS.toNanos(clock.currentTimeMillis()); } } ) .build( new CacheLoader<URI, String>() { @Override public String load(URI key) throws Exception { return generateJwtAccess(key); } } ); }</code><technical_language>60 seconds a choice</technical_language>

Target:
private LoadingCache<URI, String> createCache() { return CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(LIFE_SPAN_SECS - 300, TimeUnit.SECONDS) .ticker( new Ticker() { @Override public long read() { return TimeUnit.MILLISECONDS.toNanos(clock.currentTimeMillis()); } } ) .build( new CacheLoader<URI, String>() { @Override public String load(URI key) throws Exception { return generateJwtAccess(key); } } ); }
Source:
<code>public byte[] compress(byte[] bytes) { try(final ResourceHolder<ChunkEncoder> encoder = CompressedPools.getChunkEncoder()) { LZFChunk chunk = encoder.get().encodeChunk(bytes, 0, bytes.length); return chunk.getData(); } catch (IOException e) { <START> throw Throwables.propagate(e); <END> } }</code><technical_language>throw exception here, is safe do now</technical_language>

Target:
public byte[] compress(byte[] bytes) { try (final ResourceHolder<ChunkEncoder> encoder = CompressedPools.getChunkEncoder()) { final LZFChunk chunk = encoder.get().encodeChunk(bytes, 0, bytes.length); return chunk.getData(); } catch (IOException e) { log.error(e, "IOException thrown while closing ChunkEncoder."); } return null; }
Source:
<code>public void testMapMapperOrdering() throws Exception { h.execute("insert into something (id, name) values (?, ?)", 1, "hello"); h.execute("insert into something (id, name) values (?, ?)", 2, "world"); List<Map<String, Object>> rs = h.createQuery("select id, name from something") <START> .setMaxRows(1) <END> .mapToMap() .list(); assertThat(rs).hasSize(2); assertThat(rs).hasOnlyElementsOfType(LinkedHashMap.class); }</code><technical_language>This max rows disagrees assertion, is test is failing</technical_language>

Target:
public void testMapMapperOrdering() throws Exception { h.execute("insert into something (id, name) values (?, ?)", 1, "hello"); h.execute("insert into something (id, name) values (?, ?)", 2, "world"); List<Map<String, Object>> rs = h.createQuery("select id, name from something") .mapToMap() .list(); assertThat(rs).hasSize(2); assertThat(rs).hasOnlyElementsOfType(LinkedHashMap.class); }
Source:
<code>public void testTruncateInvalidTx() throws Exception { Transaction tx1 = txClient.startLong(); Transaction tx2 = txClient.startShort(); txClient.invalidate(tx1.getWritePointer()); txClient.invalidate(tx2.getWritePointer()); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); TransactionAdmin txAdmin = new TransactionAdmin(new PrintStream(out), new PrintStream(err)); txAdmin.doMain(new String[]{"--truncate-invalid-tx", String.valueOf(tx2.getWritePointer())}, conf); <START> List<String> expected = ImmutableList.of("Invalid list size before truncation: 2", <END> "Invalid list size after truncation: 1", ""); Assert.assertEquals(Joiner.on("\n").join(expected), Bytes.toString(out.toByteArray())); Assert.assertEquals(0, err.toByteArray().length); }</code><technical_language>calls txClient tx service running admin command test change in state? Asserting exact match in printed output is brittle subject easy breakage in future</technical_language>

Target:
public void testTruncateInvalidTx() throws Exception { Transaction tx1 = txClient.startLong(); Transaction tx2 = txClient.startShort(); txClient.invalidate(tx1.getWritePointer()); txClient.invalidate(tx2.getWritePointer()); Assert.assertEquals(2, txClient.getInvalidSize()); TransactionAdmin txAdmin = new TransactionAdmin(new PrintStream(System.out), new PrintStream(System.err)); int status = txAdmin.doMain(new String[]{"--truncate-invalid-tx", String.valueOf(tx2.getWritePointer())}, conf); Assert.assertEquals(0, status); Assert.assertEquals(1, txClient.getInvalidSize()); }
Source:
<code>public void addVesselCrew(Person p) { <START> addVesselCrew(Objects.requireNonNull(p), false); <END> }</code><technical_language>this duplicate nonNull check</technical_language>

Target:
public void addVesselCrew(Person p) { addVesselCrew(p, false); }