auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) { String taggerName = null; String inputFile = null; String parserName = null; try { taggerName = args[0]; inputFile = args[1]; if (args.length > 2) { parserName = args[2]; <START> if (args.length > 3) throw new Exception(); <END> } } catch (Exception e) { logger.error( "usage: java edu.illinois.cs.cogcomp.lbjava.edu.illinois.cs.cogcomp.lbjava.nlp.seg.SegmentTagPlain <word classifier> " + "<input file> \\\n" + " [<parser>]"); System.exit(1); } Classifier tagger = ClassUtils.getClassifier(taggerName); Parser parser; if (parserName == null) parser = new PlainToTokenParser( new WordSplitter(new SentenceSplitter(inputFile))); else parser = ClassUtils.getParser(parserName, new Class[]{Parser.class}, new Parser[]{new WordSplitter(new SentenceSplitter(inputFile))}); String previous = ""; for (Word w = (Word) parser.next(); w != null; w = (Word) parser.next()) { String prediction = tagger.discreteValue(w); if (prediction.startsWith("B-") || prediction.startsWith("I-") && !previous.endsWith(prediction.substring(2))) logger.info("[" + prediction.substring(2) + " "); logger.info(w.form + " "); if (!prediction.equals("O") && (w.next == null || tagger.discreteValue(w.next).equals("O") || tagger.discreteValue(w.next).startsWith("B-") || !tagger.discreteValue(w.next) .endsWith(prediction.substring(2)))) logger.info("] "); if (w.next == null) logger.info("\n"); previous = prediction; } }</code><technical_language>exception, STDERR</technical_language>

Target:
public static void main(String[] args) { String taggerName = null; String inputFile = null; String parserName = null; try { taggerName = args[0]; inputFile = args[1]; if (args.length > 2) { parserName = args[2]; if (args.length > 3) throw new Exception(); } } catch (Exception e) { System.err.println( "usage: java edu.illinois.cs.cogcomp.lbjava.edu.illinois.cs.cogcomp.lbjava.nlp.seg.SegmentTagPlain <word classifier> " + "<input file> \\\n" + " [<parser>]"); System.exit(1); } Classifier tagger = ClassUtils.getClassifier(taggerName); Parser parser; if (parserName == null) parser = new PlainToTokenParser( new WordSplitter(new SentenceSplitter(inputFile))); else parser = ClassUtils.getParser(parserName, new Class[]{Parser.class}, new Parser[]{new WordSplitter(new SentenceSplitter(inputFile))}); String previous = ""; for (Word w = (Word) parser.next(); w != null; w = (Word) parser.next()) { String prediction = tagger.discreteValue(w); if (prediction.startsWith("B-") || prediction.startsWith("I-") && !previous.endsWith(prediction.substring(2))) System.out.print("[" + prediction.substring(2) + " "); System.out.print(w.form + " "); if (!prediction.equals("O") && (w.next == null || tagger.discreteValue(w.next).equals("O") || tagger.discreteValue(w.next).startsWith("B-") || !tagger.discreteValue(w.next) .endsWith(prediction.substring(2)))) System.out.print("] "); if (w.next == null) System.out.println(); previous = prediction; } }
Source:
<code>public List<String> getWatcherNames() { if (watchers.isEmpty()) { return null; } <START> List<String> names = new ArrayList<String>(); <END> for (Account.Id id : watchers) { names.add(getNameFor(id)); } return names; }</code><technical_language>seed size known</technical_language>

Target:
public List<String> getWatcherNames() { if (watchers.isEmpty()) { return null; } List<String> names = new ArrayList<String>(watchers.size()); for (Account.Id id : watchers) { names.add(getNameFor(id)); } return names; }
Source:
<code>public boolean contentEquals(byte[] x) { if (length != x.length) return false; <START> for (int i = 0; i < length; i++) { <END> if (bytes[i] != x[i]) return false; } return true; }</code><technical_language>Arrays.equals? possibly intrinsic in JDK9</technical_language>

Target:
public boolean contentEquals(byte[] x) { if (length != x.length) return false; for (int i = 0; i < length; i++) { if (bytes[offset + i] != x[i]) return false; } return true; }
Source:
<code>private static ManagedBootstrapMetadataService buildBootstrapMetadataService(AtomixConfig config) { boolean hasCoreNodes = config.getClusterConfig().getNodes().stream().anyMatch(node -> node.getType() == Node.Type.CORE); ClusterMetadata metadata = ClusterMetadata.builder() .withNodes(config.getClusterConfig().getNodes() .stream() <START> .filter(node -> !hasCoreNodes || node.getType() == Node.Type.CORE) <END> .map(Node::new) .collect(Collectors.toList())) .build(); return new DefaultBootstrapMetadataService(metadata); }</code><technical_language>Do want clients in if core nodes defined</technical_language>

Target:
private static ManagedBootstrapMetadataService buildBootstrapMetadataService(AtomixConfig config) { boolean hasCoreNodes = config.getClusterConfig().getNodes().stream().anyMatch(node -> node.getType() == Node.Type.CORE); ClusterMetadata metadata = ClusterMetadata.builder() .withNodes(config.getClusterConfig().getNodes() .stream() .filter(node -> (!hasCoreNodes && node.getType() == Node.Type.DATA) || (hasCoreNodes && node.getType() == Node.Type.CORE)) .map(Node::new) .collect(Collectors.toList())) .build(); return new DefaultBootstrapMetadataService(metadata); }
Source:
<code>public void setParallel(XmlSuite.ParallelMode parallel) { <START> if (parallel == XmlSuite.ParallelMode.TRUE || parallel == XmlSuite.ParallelMode.FALSE) { <END> Utils.log("XmlTest", 1, "[WARN] 'parallel' value 'true' and 'false' are deprecated, use default value instead: '" + XmlSuite.DEFAULT_PARALLEL + "'."); m_parallel = XmlSuite.DEFAULT_PARALLEL; } else { m_parallel = parallel; } }</code><technical_language>XmlTest XmlSuite share this code. extract in a common parseParallelValue</technical_language>

Target:
public void setParallel(XmlSuite.ParallelMode parallel) { m_parallel = skipDeprecatedValues(parallel); }
Source:
<code><START> public boolean containsAll(Collection<?> tileEntities) <END> { for (Iterator<?> iterator = tileEntities.iterator(); iterator.hasNext();) { if(!contains(iterator.next())) return false; } return true; }</code><technical_language>Missing @ Override</technical_language>

Target:
public boolean containsAll(Collection<?> tileEntities) { for (Object object : tileEntities) { if (!contains(object)) return false; } return true; }
Source:
<code>public Set<String> getCatalogs() { Set<String> catalogs = new HashSet<>(2); <START> catalogs.add(nirCatalog); <END> catalogs.add(opticalCatalog); return catalogs; }</code><technical_language>Super Trivial: this part is some else's code I initial capacity of 2 a default load factor of 0.75 result in growing backing hash table soon catalog is added set, is intended. star initial capacity of 4</technical_language>

Target:
public Set<String> getCatalogs() { Set<String> catalogs = new HashSet<>(4); catalogs.add(nirCatalog); catalogs.add(opticalCatalog); return catalogs; }
Source:
<code>public void setUsePatternFly(boolean use) { <START> nameServerWidget.setUsePatternFly(use); <END> }</code><technical_language>Please delegate setDnsConfigurationEditor</technical_language>

Target:
public void setUsePatternFly(boolean use) { nameServerWidget.setUsePatternFly(use); setDnsConfigurationEditor.setUsePatternFly(use); }
Source:
<code>protected Map<DropStrategy, List<Command>> findStrategies(Request request) { Map<DropStrategy, List<Command>> matchingStrategies = new LinkedHashMap<DropStrategy, List<Command>>(); for (DropStrategy strategy : DropStrategyManager.instance.getActiveStrategies()) { ArrayList<Command> selectedCommands = new ArrayList<Command>(); if(strategy instanceof TransactionalCommandsDropStrategy){ List<Command> cs = ((TransactionalCommandsDropStrategy)strategy).getCommands(request, getHost()); for(Command command : cs){ if (command != null && command.canExecute()) { selectedCommands.add(command); } } } else if(strategy instanceof TransactionalDropStrategy){ Command command = strategy.getCommand(request, getHost()); if (command != null && command.canExecute()) { selectedCommands.add(command); } } else{ <START> Activator.log.info("strategy: "+strategy); <END> } if(selectedCommands.size()>0){ matchingStrategies.put(strategy, selectedCommands); } } ArrayList<Command> selectedCommands = new ArrayList<Command>(); selectedCommands.add(defaultDropStrategy.getCommand(request, getHost())); matchingStrategies.put(defaultDropStrategy, selectedCommands); return matchingStrategies; }</code><technical_language>Informative warning message, please ..</technical_language>

Target:
protected Map<DropStrategy, List<Command>> findStrategies(Request request) { Map<DropStrategy, List<Command>> matchingStrategies = new LinkedHashMap<DropStrategy, List<Command>>(); for (DropStrategy strategy : DropStrategyManager.instance.getActiveStrategies()) { ArrayList<Command> selectedCommands = new ArrayList<Command>(); if(strategy instanceof TransactionalCommandsDropStrategy){ List<Command> cs = ((TransactionalCommandsDropStrategy)strategy).getCommands(request, getHost()); for(Command command : cs){ if (command != null && command.canExecute()) { selectedCommands.add(command); } } } else{ Command command = strategy.getCommand(request, getHost()); if (command != null && command.canExecute()) { selectedCommands.add(command); } } if(selectedCommands.size()>0){ matchingStrategies.put(strategy, selectedCommands); } } ArrayList<Command> selectedCommands = new ArrayList<Command>(); selectedCommands.add(defaultDropStrategy.getCommand(request, getHost())); matchingStrategies.put(defaultDropStrategy, selectedCommands); return matchingStrategies; }
Source:
<code>private RawPacket doTransform(RawPacket pkt, boolean send) { RTCPIterator it = new RTCPIterator(pkt); while (it.hasNext()) { ByteArrayBuffer baf = it.next(); int pt = RTCPHeaderUtils.getPacketType(baf); if (pt == RTCPRRPacket.RR || RTCPREMBPacket.isREMBPacket(baf) <START> || RTCPTCCPacket.isTCCPacket(baf)) <END> { it.remove(); } if (!send) { int fmt = RTCPHeaderUtils.getReportCount(baf); if ((pt == RTCPFeedbackMessageEvent.PT_PS && fmt == RTCPFeedbackMessageEvent.FMT_PLI) || (pt == RTCPFeedbackMessageEvent.PT_PS && fmt == RTCPFeedbackMessageEvent.FMT_FIR)) { long source = RTCPFBPacket.getSourceSSRC(baf); ((RTPTranslatorImpl) stream.getRTPTranslator()) .getRtcpFeedbackMessageSender() .requestKeyframe(source); it.remove(); } } } return pkt.getLength() == 0 ? null : pkt; }</code><technical_language>do adding a "continue" here, changing "if" "else if"? Calling remove() is illegal (at for this iterator), code is unclear happen</technical_language>

Target:
private RawPacket doTransform(RawPacket pkt, boolean send) { RTCPIterator it = new RTCPIterator(pkt); while (it.hasNext()) { ByteArrayBuffer baf = it.next(); int pt = RTCPHeaderUtils.getPacketType(baf); if (pt == RTCPRRPacket.RR || RTCPREMBPacket.isREMBPacket(baf) || RTCPTCCPacket.isTCCPacket(baf)) { it.remove(); continue; } if (!send) { int fmt = RTCPHeaderUtils.getReportCount(baf); if ((pt == RTCPFeedbackMessageEvent.PT_PS && fmt == RTCPFeedbackMessageEvent.FMT_PLI) || (pt == RTCPFeedbackMessageEvent.PT_PS && fmt == RTCPFeedbackMessageEvent.FMT_FIR)) { long source = RTCPFBPacket.getSourceSSRC(baf); ((RTPTranslatorImpl) stream.getRTPTranslator()) .getRtcpFeedbackMessageSender() .requestKeyframe(source); it.remove(); continue; } } } return pkt.getLength() == 0 ? null : pkt; }
Source:
<code>public boolean ignorePrefix() { <START> return Boolean.TRUE.equals(ignorePrefix); <END> }</code><technical_language>new ignorePrefix() do !Boolean.FALSE.equals(ignorePrefix) in order return true if defined, "defaulting" true</technical_language>

Target:
public boolean ignorePrefix() { return !Boolean.FALSE.equals(ignorePrefix); }
Source:
<code>public AnnotationMongoWriter(MongoOperations mongoOperations, String collection) { super(); Assert.notNull(mongoOperations); Assert.hasText(collection); <START> converter = new AnnotationToSimplifiedDBObjectConverter(); <END> this.mongoOperations = mongoOperations; this.collection = collection; createIndexes(); }</code><technical_language>this consistent</technical_language>

Target:
public AnnotationMongoWriter(MongoOperations mongoOperations, String collection) { Assert.notNull(mongoOperations); Assert.hasText(collection); this.mongoOperations = mongoOperations; this.collection = collection; createIndexes(); }
Source:
<code>protected void executeQueryCommand() { GetHostsByClusterIdParameters params = new GetHostsByClusterIdParameters(getParameters().getId()); params.setFiltered(getParameters().isFiltered()); <START> VdcQueryReturnValue hostsReturnValue = Backend.getInstance().RunQuery(VdcQueryType.GetHostsByClusterId, params); <END> @SuppressWarnings("unchecked") List<VDS> hosts = (List<VDS>) hostsReturnValue.getReturnValue(); getQueryReturnValue().setReturnValue(!isConsoleAddressPartiallyOverridden(hosts)); }</code><technical_language>for DAO</technical_language>

Target:
protected void executeQueryCommand() { List<VDS> hosts = DbFacade.getInstance() .getVdsDao() .getAllForVdsGroup(getParameters().getId(), getUserID(), getParameters().isFiltered()); getQueryReturnValue().setReturnValue(!isDisplayAddressPartiallyOverridden(hosts)); }
Source:
<code><START> default boolean startsWith(Iterable<? extends T> that, int offset) { <END> Objects.requireNonNull(that, "that is null"); if(offset < 0) return false; Iterator<T> i = this.iterator().drop(offset); java.util.Iterator<? extends T> j = that.iterator(); while(i.hasNext() && j.hasNext()) { if(!Objects.equals(i.next(), j.next())) return false; } return !j.hasNext(); }</code><technical_language>null-check</technical_language>

Target:
default boolean startsWith(Iterable<? extends T> that, int offset) { Objects.requireNonNull(that, "that is null"); if(offset < 0) return false; Iterator<T> i = this.iterator().drop(offset); java.util.Iterator<? extends T> j = that.iterator(); while(i.hasNext() && j.hasNext()) { if(!Objects.equals(i.next(), j.next())) { return false; } } return !j.hasNext(); }
Source:
<code>private Maybe<String> getImage(Element element) { Elements imageElements = element.getFirstChildElement("images").getChildElements("image"); if (imageElements.size() > 0) { <START> if (!imageElements.get(0).getValue().contains("api-images.channel5.com/images/default")) { <END> return Maybe.just(imageElements.get(0).getValue()); } } return Maybe.nothing(); }</code><technical_language>logic in places extract if branch condition a method avoid duplication</technical_language>

Target:
private Maybe<String> getImage(Element element) { Elements imageElements = element.getFirstChildElement("images").getChildElements("image"); if (imageElements.size() > 0) { String image = imageElements.get(0).getValue(); if (!image.contains("api-images.channel5.com/images/default")) { return Maybe.just(image); } } return Maybe.nothing(); }
Source:
<code>public BatchingSyncUpTarget(JSONObject target) throws JSONException { super(target); this.soupName = target.getString(SOUP_NAME); <START> this.maxBatchSize = target.getInt(MAX_BATCH_SIZE); <END> }</code><technical_language>This a check for max of 25 constructor above, i.e. Math.min(...)</technical_language>

Target:
public BatchingSyncUpTarget(JSONObject target) throws JSONException { super(target); this.maxBatchSize = Math.min(target.optInt(MAX_BATCH_SIZE, MAX_SUB_REQUESTS_COMPOSITE_API), MAX_SUB_REQUESTS_COMPOSITE_API); }
Source:
<code><START> public double getRatio(final CounterEntity entity) { <END> double ratio = DEFAULT_RATIO; if (this.configuration.get(entity) != null) { ratio = this.configuration.get(entity).doubleValue(); } return ratio; }</code><technical_language>Avoid lookup, this? final Double ratio = this.configuration.get(entity); return ratio == null ? DEFAULT_RATIO : ratio.doubleValue();</technical_language>

Target:
public double getRatio(final CounterEntity entity) { final Double ratio = this.configuration.get(entity); return ratio == null ? DEFAULT_RATIO : ratio.doubleValue(); }
Source:
<code><START> public static FeignClientFactory withEncoderAndDecoder(Encoder encoder, Decoder decoder, <END> Request.Options timeoutOptions) { return FeignClientFactory.of( new GuavaOptionalAwareContract(new JaxRsWithHeaderAndQueryMapContract()), new InputStreamDelegateEncoder(new TextDelegateEncoder(encoder)), new OptionalAwareDecoder(new InputStreamDelegateDecoder(new TextDelegateDecoder(decoder))), FeignSerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient(), NeverRetryingBackoffStrategy.INSTANCE, timeoutOptions); }</code><technical_language>this private</technical_language>

Target:
private static FeignClientFactory withEncoderAndDecoder(Encoder encoder, Decoder decoder, Request.Options timeoutOptions) { return FeignClientFactory.of( new GuavaOptionalAwareContract(new JaxRsWithHeaderAndQueryMapContract()), new InputStreamDelegateEncoder(new TextDelegateEncoder(encoder)), new OptionalAwareDecoder(new InputStreamDelegateDecoder(new TextDelegateDecoder(decoder))), FeignSerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient(), NeverRetryingBackoffStrategy.INSTANCE, timeoutOptions); }
Source:
<code>public Page getOutput() { if (lookupSource == null) { return null; } Page outputPage = null; Counter lookupPositionsConsidered = new Counter(); if (probe != null) { while (true) { if (probe.getPosition() >= 0) { if (!joinCurrentPosition(lookupPositionsConsidered)) { break; } if (!currentProbePositionProducedRow) { currentProbePositionProducedRow = true; if (!outerJoinCurrentPosition()) { break; } } } currentProbePositionProducedRow = false; if (!advanceProbePosition()) { break; } } if (readyToBuildOutputPage()) { outputPage = probe.buildDictionaryPage(probeIndexBuilder.getArray(), buildPageBuilder); reset(); } } <START> return outputPage; <END> }</code><technical_language>I preferred return null; better. shows output produced. Please inline outputPage</technical_language>

Target:
public Page getOutput() { if (lookupSource == null) { return null; } Counter lookupPositionsConsidered = new Counter(); if (probe != null) { while (true) { if (probe.getPosition() >= 0) { if (!joinCurrentPosition(lookupPositionsConsidered)) { break; } if (!currentProbePositionProducedRow) { currentProbePositionProducedRow = true; if (!outerJoinCurrentPosition()) { break; } } } currentProbePositionProducedRow = false; if (!advanceProbePosition()) { break; } } if (readyToBuildOutputPage()) { Page outputPage = probe.buildDictionaryPage(probeIndexBuilder.toIntArray(null), buildPageBuilder); reset(); return outputPage; } } return null; }
Source:
<code>public String apply(@Nullable String value) { <START> try { <END> return bucket(Double.parseDouble(value)); } catch (NumberFormatException | NullPointerException ex) { return null; } }</code><technical_language>Null is "expected" here, suggested check for explicitly, operate exception handling, is antipattern in java</technical_language>

Target:
public String apply(@Nullable String value) { if (value == null) { return null; } try { return bucket(Double.parseDouble(value)); } catch (NumberFormatException | NullPointerException ex) { return null; } }
Source:
<code>private void registerBuiltins(ConfigurationSection mainSection) { <START> ConfigurationSection valuesSection = mainSection.getConfigurationSection("rewards"); <END> Set<String> categories = valuesSection.getKeys(false); for (String strCategorie : categories) { RewardCategory category = RewardCategory.valueOf(strCategorie); List<Map<?, ?>> items = valuesSection.getMapList(strCategorie); for (Map<?, ?> item : items) { values.put(category, RewardItem.deserialize((Map<String, Object>) item)); } } }</code><technical_language>Check if mainSection in fact "rewards", add a warning do otherwise</technical_language>

Target:
private void registerBuiltins(ConfigurationSection mainSection) { ConfigurationSection valuesSection = mainSection.getConfigurationSection("rewards"); if (valuesSection == null) { GlowServer.logger.warning("Invalid fishingRewards.yml: no 'rewards' section"); return; } Set<String> categories = valuesSection.getKeys(false); for (String strCategory : categories) { RewardCategory category = RewardCategory.valueOf(strCategory); List<Map<?, ?>> items = valuesSection.getMapList(strCategory); for (Map<?, ?> item : items) { values.put(category, RewardItem.deserialize((Map<String, Object>) item)); } } }
Source:
<code>private String getAnnotatedFieldName() { if (isAnnotationPresent(Field.class)) { final Field annotation = findAnnotation(Field.class); <START> Assert.notNull(annotation, "findAnnotation() returned null on existing Annotation"); <END> return annotation.name(); } return ""; }</code><technical_language>check isAnnotationPresent ensures annotation is present</technical_language>

Target:
private String getAnnotatedFieldName() { if (isAnnotationPresent(Field.class)) { String name = findAnnotation(Field.class).name(); return StringUtils.hasText(name) ? name : null; } return null; }
Source:
<code>public boolean isStarted() { <START> synchronized (lock) { <END> return currentStartOrder >= 0; } }</code><technical_language>Perf change is unimportant? wait for long scheduled poll()</technical_language>

Target:
public boolean isStarted() { readLock.lock(); try { return currentStartOrder >= 0; } finally { readLock.unlock(); } }
Source:
<code>public void set(FilterableNode node, String filter) { try { <START> loader.join(); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } cache.computeIfAbsent(node.getRepository().getDirectory(), k -> new ConcurrentHashMap<>()).put(node.getType(), filter); node.setFilter(filter); }</code><technical_language>If done in background, join-calls replaced simple ensureCacheInitialized() calls</technical_language>

Target:
public void set(FilterableNode node, String filter) { cache.computeIfAbsent(node.getRepository().getDirectory(), k -> new ConcurrentHashMap<>()).put(node.getType(), filter); node.setFilter(filter); }
Source:
<code>public void doParse_handledFieldTypeRecursion() throws UnableToCompleteException { Set<? extends JClassType> ownerTypeParentFieldTypeSubField1TypeFlattenedSupertypeHierarchy = <START> new HashSet<>(Collections.singletonList(ownerTypeParentFieldTypeSubField1Type)); <END> doReturn(ownerTypeParentFieldTypeSubField1TypeFlattenedSupertypeHierarchy) .when(ownerTypeParentFieldTypeSubField1Type).getFlattenedSupertypeHierarchy(); when(ownerTypeParentFieldTypeSubField1Type.getFields()).thenReturn(new JField[] { ownerTypeParentField }); stubFieldIdAnnotation(ownerTypeParentField, "", false); tested.doParse(ownerType, new ArrayList<JClassType>(), ".", "IdPrefix"); List<ElementIdStatement> expected = Arrays.asList( getExpectedStatement("ownerTypeParentField", "IdPrefix_ownerTypeParentField"), getExpectedStatement("ownerTypeField1", "IdPrefix_ownerTypeField1"), getExpectedStatement("ownerTypeField2", "IdPrefix_ownerTypeField2")); assertThat(tested.statements.size(), is(equalTo(expected.size()))); assertThat(tested.statements.containsAll(expected), is(equalTo(true))); }</code><technical_language>please Collections.singleton(...)</technical_language>

Target:
public void doParse_handledFieldTypeRecursion() throws UnableToCompleteException { Set<? extends JClassType> ownerTypeParentFieldTypeSubField1TypeFlattenedSupertypeHierarchy = Collections.singleton(ownerTypeParentFieldTypeSubField1Type); doReturn(ownerTypeParentFieldTypeSubField1TypeFlattenedSupertypeHierarchy) .when(ownerTypeParentFieldTypeSubField1Type).getFlattenedSupertypeHierarchy(); when(ownerTypeParentFieldTypeSubField1Type.getFields()).thenReturn(new JField[] { ownerTypeParentField }); stubFieldIdAnnotation(ownerTypeParentField, "", false); tested.doParse(ownerType, new ArrayList<JClassType>(), ".", "IdPrefix"); List<ElementIdStatement> expected = Arrays.asList( getExpectedStatement("ownerTypeParentField", "IdPrefix_ownerTypeParentField"), getExpectedStatement("ownerTypeField1", "IdPrefix_ownerTypeField1"), getExpectedStatement("ownerTypeField2", "IdPrefix_ownerTypeField2")); assertThat(tested.statements.size(), is(equalTo(expected.size()))); assertThat(tested.statements.containsAll(expected), is(equalTo(true))); }
Source:
<code>protected Content doPutContent(final String path, final TempBlob tempBlob, final Payload payload) throws IOException { StorageTx tx = UnitOfWork.currentTx(); CondaPath condaPath = CondaPath.build(path); Asset asset = getOrCreateAsset(condaPath, getRepository()); AttributesMap contentAttributes = null; if (payload instanceof Content) { contentAttributes = ((Content) payload).getAttributes(); } Content.applyToAsset(asset, Content.maintainLastModified(asset, contentAttributes)); AssetBlob assetBlob = tx.setBlob(asset, path, tempBlob, null, payload.getContentType(), false); Content content = toContent(asset, assetBlob.getBlob()); <START> if (!path.contains("repodata.json")) { <END> String json = readIndexJson(content.openInputStream()); toAttributes(asIndex(json), asset.formatAttributes()); } tx.saveAsset(asset); return content; }</code><technical_language>seance create static variable for this</technical_language>

Target:
protected Content doPutContent(final String path, final TempBlob tempBlob, final Payload payload) throws IOException { StorageTx tx = UnitOfWork.currentTx(); CondaPath condaPath = CondaPath.build(path); Asset asset = getOrCreateAsset(condaPath, getRepository()); AttributesMap contentAttributes = null; if (payload instanceof Content) { contentAttributes = ((Content) payload).getAttributes(); } Content.applyToAsset(asset, Content.maintainLastModified(asset, contentAttributes)); AssetBlob assetBlob = tx.setBlob(asset, path, tempBlob, null, payload.getContentType(), false); Content content = toContent(asset, assetBlob.getBlob()); if (!path.contains(REPODATA_JSON)) { String json = readIndexJson(content.openInputStream()); toAttributes(asIndex(json), asset.formatAttributes()); } tx.saveAsset(asset); return content; }
Source:
<code>public void close() throws IOException { <START> if (getStream() != null) { writeFooter(); } <END> super.close(); }</code><technical_language>ImageJ style</technical_language>

Target:
public void close() throws IOException { if (getStream() != null) writeFooter(); super.close(); }
Source:
<code>public VersionResponse getVersion() throws ParseException { Instant date; if (molgenisBuildDate.equals("${maven.build.timestamp}")) { date = now().toInstant(); <START> } else { <END> date = new SimpleDateFormat(VERSION_DATE_FORMAT).parse(molgenisBuildDate).toInstant(); } AppVersionResponse appVersionResponse = AppVersionResponse.create(molgenisVersion, date); return VersionResponse.create(appVersionResponse); }</code><technical_language>Deprecate /api/v2 version endpoint refer this endpoint</technical_language>

Target:
public OptionsResponse getVersion() throws ParseException { Instant date; if (molgenisBuildDate.equals("${maven.build.timestamp}")) { date = now().toInstant(); } else { date = new SimpleDateFormat(VERSION_DATE_FORMAT).parse(molgenisBuildDate).toInstant(); } AppVersionResponse appVersionResponse = AppVersionResponse.create(molgenisVersion, date); return OptionsResponse.create(appVersionResponse); }
Source:
<code>private UnionOperator(@Parameter(QueryId.class) final String queryId, @Parameter(OperatorId.class) final String operatorId, final StringIdentifierFactory idfactory) { super(idfactory.getNewInstance(queryId), idfactory.getNewInstance(operatorId)); this.leftUpstreamQueue = new LinkedBlockingQueue<>(); this.rightUpstreamQueue = new LinkedBlockingQueue<>(); this.recentLeftWatermark = 0L; <START> this.recentRightWatermark = 0L; <END> }</code><technical_language>set default watermarks minimum long value</technical_language>

Target:
private UnionOperator(@Parameter(QueryId.class) final String queryId, @Parameter(OperatorId.class) final String operatorId, final StringIdentifierFactory idfactory) { super(idfactory.getNewInstance(queryId), idfactory.getNewInstance(operatorId)); this.leftUpstreamQueue = new LinkedBlockingQueue<>(); this.rightUpstreamQueue = new LinkedBlockingQueue<>(); this.recentLeftWatermark = Long.MIN_VALUE; this.recentRightWatermark = Long.MIN_VALUE; }
Source:
<code>public int write(final ByteBuffer src) throws IOException { if (!this.writeMode.get()) { throw new IOException("Cannot write to buffer, buffer already switched to read mode"); } final int initialPos = position(); <START> while(src.hasRemaining()) { <END> if(position() >= limit()) { return index-initialPos; } this.internalMemorySegment.put(position(), src.get()); position(position()+1); } return position()-initialPos; }</code><technical_language>bulk put method of memory segment "put(ByteBuffer)"</technical_language>

Target:
public int write(final ByteBuffer src) throws IOException { int numBytes = src.remaining(); final int thisRemaining = this.remaining(); if(thisRemaining == 0) { return 0; } if(numBytes > thisRemaining) { numBytes = thisRemaining; } this.internalMemorySegment.put(position(), src, numBytes); this.index += numBytes; return numBytes; }
Source:
<code>private void initAndStartRevWalk(boolean forceNewWalk, ObjectId newSelectedObj) throws IllegalStateException { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (input == null) return; Repository db = input.getRepository(); if (repoHasBeenRemoved(db)) { clearHistoryPage(); return; } <START> if (db == null) <END> throw new IllegalStateException("Repository is null"); AnyObjectId headId = resolveHead(db, true); if (headId == null) { currentHeadId = null; currentFetchHeadId = null; selectedObj = null; setCurrentRepo(db); clearViewers(); return; } AnyObjectId fetchHeadId = resolveFetchHead(db); List<FilterPath> paths = buildFilterPaths(input.getItems(), input .getFileList(), db); boolean repoChanged = false; if (!db.equals(getCurrentRepo())) { repoChanged = true; setCurrentRepo(db); } boolean objChanged = false; if (newSelectedObj != null && newSelectedObj != selectedObj) { objChanged = !newSelectedObj.equals(selectedObj); } selectedObj = newSelectedObj; if (forceNewWalk || repoChanged || objChanged || shouldRedraw(headId, fetchHeadId, paths)) { releaseGenerateHistoryJob(); if (repoChanged) { clearViewers(); } SWTWalk walk = createNewWalk(db, headId, fetchHeadId); fileDiffWalker = createFileWalker(walk, db, paths); loadInitialHistory(walk); } else { graph.setHistoryPageInput(input); } } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } }</code><technical_language>missing braces</technical_language>

Target:
private void initAndStartRevWalk(boolean forceNewWalk, ObjectId newSelectedObj) throws IllegalStateException { try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); if (input == null) return; Repository db = input.getRepository(); if (repoHasBeenRemoved(db)) { clearHistoryPage(); return; } if (db == null) { throw new NullPointerException("Repository is null"); } AnyObjectId headId = resolveHead(db, true); if (headId == null) { currentHeadId = null; currentFetchHeadId = null; selectedObj = null; setCurrentRepo(db); clearViewers(); return; } AnyObjectId fetchHeadId = resolveFetchHead(db); List<FilterPath> paths = buildFilterPaths(input.getItems(), input .getFileList(), db); boolean repoChanged = false; if (!db.equals(getCurrentRepo())) { repoChanged = true; setCurrentRepo(db); } boolean objChanged = false; if (newSelectedObj != null && newSelectedObj != selectedObj) { objChanged = !newSelectedObj.equals(selectedObj); } selectedObj = newSelectedObj; if (forceNewWalk || repoChanged || objChanged || shouldRedraw(headId, fetchHeadId, paths)) { releaseGenerateHistoryJob(); if (repoChanged) { clearViewers(); } SWTWalk walk = createNewWalk(db, headId, fetchHeadId); fileDiffWalker = createFileWalker(walk, db, paths); loadInitialHistory(walk); } else { graph.setHistoryPageInput(input); } } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } }
Source:
<code>public void setUp() { <START> ArgumentParser parser = ArgumentParsers.newArgumentParser("test"); <END> Subparser subparser = parser.addSubparsers().addParser("list"); command = new JobListCommand(subparser); Map<JobId, Job> jobs = ImmutableMap.of( new JobId("job", "1-aaa"), Job.newBuilder().build(), new JobId("job", "3-ccc"), Job.newBuilder().build(), new JobId("job", "2-bbb"), Job.newBuilder().build()); when(client.jobs()).thenReturn(Futures.immediateFuture(jobs)); Map<JobId, JobStatus> statuses = new HashMap<>(); for (JobId jobId : jobs.keySet()) { JobStatus status = JobStatus.newBuilder() .setDeployments(ImmutableMap.of("host", Deployment.of(jobId, Goal.START))) .build(); statuses.put(jobId, status); } when(client.jobStatuses(jobs.keySet())).thenReturn(Futures.immediateFuture(statuses)); expectedOrder = ImmutableList.of("job:1-aaa", "job:2-bbb", "job:3-ccc"); }</code><technical_language>final. for subparser, command, jobs, JobId jobId in loop status loop</technical_language>

Target:
public void setUp() { final ArgumentParser parser = ArgumentParsers.newArgumentParser("test"); final Subparser subparser = parser.addSubparsers().addParser("list"); command = new JobListCommand(subparser); when(client.jobs()).thenReturn(Futures.immediateFuture(jobs)); Map<JobId, JobStatus> statuses = new HashMap<>(); for (final JobId jobId : jobs.keySet()) { final JobStatus status = JobStatus.newBuilder() .setDeployments(ImmutableMap.of("host", Deployment.of(jobId, Goal.START))) .build(); statuses.put(jobId, status); } when(client.jobStatuses(jobs.keySet())).thenReturn(Futures.immediateFuture(statuses)); }
Source:
<code>public JSONObject createElementSelectDataTable(HttpSession session, JSONObject json) { if (json.has("platform") && !isStringEmptyOrNull(json.getString("platform"))) { try { String platform = json.getString("platform"); long poolId = json.has("poolId") ? json.getLong("poolId") : 0L; JSONObject j = new JSONObject(); JSONArray arr = new JSONArray(); for (LibraryDilution libraryDilution : requestManager.listAllLibraryDilutionsByPlatform((PlatformType.get(platform)))) { JSONArray pout = new JSONArray(); pout.add(libraryDilution.getName()); <START> pout.add(String.format("%.1f", libraryDilution.getConcentration())); <END> pout.add(libraryDilution.getLibrary().getAlias() + " (" + libraryDilution.getLibrary().getName() + ")"); pout.add(libraryDilution.getLibrary().getSample().getAlias() + " (" + libraryDilution.getLibrary().getSample().getName() + ")"); StringBuilder indices = new StringBuilder(); collectIndices(indices, libraryDilution); pout.add(indices.toString()); pout.add(libraryDilution.getLibrary().isLowQuality() ? "⚠" : ""); pout.add( "<div style='cursor:inherit;' onclick=\"Pool.search.poolSearchSelectElement(" + poolId + ", '" + libraryDilution.getId() + "', '" + libraryDilution.getName() + "')\"><span class=\"ui-icon ui-icon-plusthick\"></span></div>"); arr.add(pout); } j.put("poolelements", arr); return j; } catch (IOException e) { log.debug("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } } else { return JSONUtils.SimpleJSONError("No platform specified"); } }</code><technical_language>Is a reason limit 1 decimal place? If so, input validated similarly</technical_language>

Target:
public JSONObject createElementSelectDataTable(HttpSession session, JSONObject json) { if (json.has("platform") && !isStringEmptyOrNull(json.getString("platform"))) { try { String platform = json.getString("platform"); long poolId = json.has("poolId") ? json.getLong("poolId") : 0L; JSONObject j = new JSONObject(); JSONArray arr = new JSONArray(); for (LibraryDilution libraryDilution : requestManager.listAllLibraryDilutionsByPlatform((PlatformType.get(platform)))) { JSONArray pout = new JSONArray(); pout.add(libraryDilution.getName()); pout.add(libraryDilution.getConcentration().toString()); pout.add(libraryDilution.getLibrary().getAlias() + " (" + libraryDilution.getLibrary().getName() + ")"); pout.add(libraryDilution.getLibrary().getSample().getAlias() + " (" + libraryDilution.getLibrary().getSample().getName() + ")"); StringBuilder indices = new StringBuilder(); collectIndices(indices, libraryDilution); pout.add(indices.toString()); pout.add(libraryDilution.getLibrary().isLowQuality() ? "⚠" : ""); pout.add( "<div style='cursor:inherit;' onclick=\"Pool.search.poolSearchSelectElement(" + poolId + ", '" + libraryDilution.getId() + "', '" + libraryDilution.getName() + "')\"><span class=\"ui-icon ui-icon-plusthick\"></span></div>"); arr.add(pout); } j.put("poolelements", arr); return j; } catch (IOException e) { log.debug("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } } else { return JSONUtils.SimpleJSONError("No platform specified"); } }
Source:
<code>public List<Endpoint> resolve(String addressExpression) throws CloudnameException { Parameters parameters = new Parameters(addressExpression); ZooKeeper localZkPointer = zkGetter.getZookeeper(); if (localZkPointer == null) { throw new CloudnameException("No connection to ZooKeeper."); } List<Integer> instances = resolveInstances(parameters, localZkPointer); List<Endpoint> endpoints = new ArrayList<Endpoint>(); for (Integer instance : instances) { String statusPath = ZkCoordinatePath.getStatusPath( parameters.getCell(), parameters.getUser(), parameters.getService(), instance); try { if (! Util.exist(localZkPointer, statusPath)) { continue; } } catch (InterruptedException e) { throw new CloudnameException(e); } <START> ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData( <END> statusPath, localZkPointer, null); addEndpoints(zkCoordinateData.snapshot(), endpoints, parameters.getEndpointName()); } if (parameters.getStrategy().equals("")) { return endpoints; } ResolverStrategy strategy = strategies.get(parameters.getStrategy()); return strategy.order(strategy.filter(endpoints)); }</code><technical_language>final</technical_language>

Target:
public List<Endpoint> resolve(String addressExpression) throws CloudnameException { Parameters parameters = new Parameters(addressExpression); ZooKeeper localZkPointer = zkGetter.getZookeeper(); if (localZkPointer == null) { throw new CloudnameException("No connection to ZooKeeper."); } List<Integer> instances = resolveInstances(parameters, localZkPointer); List<Endpoint> endpoints = new ArrayList<Endpoint>(); for (Integer instance : instances) { String statusPath = ZkCoordinatePath.getStatusPath( parameters.getCell(), parameters.getUser(), parameters.getService(), instance); try { if (! Util.exist(localZkPointer, statusPath)) { continue; } } catch (InterruptedException e) { throw new CloudnameException(e); } final ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData( statusPath, localZkPointer, null); addEndpoints(zkCoordinateData.snapshot(), endpoints, parameters.getEndpointName()); } if (parameters.getStrategy().equals("")) { return endpoints; } ResolverStrategy strategy = strategies.get(parameters.getStrategy()); return strategy.order(strategy.filter(endpoints)); }
Source:
<code>public void onBindViewHolder(ViewHolder holder, Trend trend) { String owner = trend.getRepoOwner(); String name = trend.getRepoName(); SpannableStringBuilder title = new SpannableStringBuilder(); title.append(owner).append("/").append(name); title.setSpan(new StyleSpan(Typeface.BOLD), 0, owner.length(), 0); holder.tvTitle.setText(title); String desc = trend.getDescription(); holder.tvDesc.setText(desc != null ? EmojiParser.parseToUnicode(desc) : null); String lang = trend.getLanguage(); if (TextUtils.isEmpty(lang)) { <START> lang = "Unknown"; <END> } holder.tvLang.setText(lang); holder.tvStars.setText(mContext.getString(mStarsTemplate, trend.getNewStars(), trend.getStars())); holder.tvForks.setText(String.valueOf(trend.getForks())); }</code><technical_language>This a string resource (use setText variant takes a string resource in case)</technical_language>

Target:
public void onBindViewHolder(ViewHolder holder, Trend trend) { String owner = trend.getRepoOwner(); String name = trend.getRepoName(); SpannableStringBuilder title = new SpannableStringBuilder(); title.append(owner).append("/").append(name); title.setSpan(new StyleSpan(Typeface.BOLD), 0, owner.length(), 0); holder.tvTitle.setText(title); String desc = trend.getDescription(); holder.tvDesc.setText(desc != null ? EmojiParser.parseToUnicode(desc) : null); String lang = trend.getLanguage(); if (TextUtils.isEmpty(lang)) { holder.tvLang.setText(R.string.unknown); } else { holder.tvLang.setText(lang); } holder.tvStars.setText(mContext.getString(mStarsTemplate, trend.getNewStars(), trend.getStars())); holder.tvForks.setText(String.valueOf(trend.getForks())); }
Source:
<code>public void suspendNode(String id) { <START> waitServerUntilRunning.apply(getNode(id)); <END> api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_OFF, Types.ServerActionMethod.HARDWARE)); }</code><technical_language>if call this suspended node? block times out? is a idea validate state a precondition fail, validate fail in server side</technical_language>

Target:
public void suspendNode(String id) { waitServerUntilAvailable.apply(getNode(id)); api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_OFF, Types.ServerActionMethod.HARDWARE)); }
Source:
<code>public <T> T getService(long l, ServiceConfiguration<T> serviceConfiguration) { Class<T> serviceType = serviceConfiguration.getServiceType(); <START> return serviceType != org.terracotta.diagnostic.server.api.extension.LogicalServerStateProvider.class ? null : serviceType.cast(detailedServerState); <END> }</code><technical_language>replace full import a qualified import</technical_language>

Target:
public <T> T getService(long l, ServiceConfiguration<T> serviceConfiguration) { Class<T> serviceType = serviceConfiguration.getServiceType(); return serviceType != LogicalServerStateProvider.class ? null : serviceType.cast(logicalServerStateMBean); }
Source:
<code>private void handleOptimizationOption(final Map<String, Boolean> options, final String optionName, final String sysOptionName) { String propValue = getSystemPropertySafe(sysOptionName); boolean optionEnabled = propValue == null <START> ? Boolean.TRUE.equals(DEFAULT.getOptimizationOptions().get(optionName)) <END> : Boolean.parseBoolean(propValue); if (optionEnabled) { options.put(optionName, Boolean.TRUE); } }</code><technical_language>DEFAULT is null while constructor in initializer expression is running</technical_language>

Target:
private void handleOptimizationOption(final Map<String, Boolean> options, final String optionName, final String sysOptionName) { String propValue = getSystemPropertySafe(sysOptionName); boolean optionEnabled = propValue == null ? (DEFAULT != null && Boolean.TRUE.equals(DEFAULT.getOptimizationOptions().get(optionName))) : Boolean.parseBoolean(propValue); if (optionEnabled) { options.put(optionName, Boolean.TRUE); } }
Source:
<code>public void reindex() { indexBuilt = false; Runnable build = () -> { logInfo("Start building data index.").log(); long startTime = System.nanoTime(); try { Files.walkFileTree(contentReader.getRootFolder(), new IndexBuilder(index, contentReader)); } catch (IOException e) { <START> logError(e, "Failed to build data index"); <END> } long duration = System.nanoTime() - startTime; logInfo("Finished building data index.").addParameter("entries", index.size()).addParameter("duration_ns", duration).log(); indexBuilt = true; }; pool.submit(build); }</code><technical_language>need call .log() end of logError is a logAndThrow() if wanted throw exception</technical_language>

Target:
public void reindex() { indexBuilt = false; Runnable build = () -> { logInfo("Start building data index.").log(); long startTime = System.nanoTime(); try { Files.walkFileTree(contentReader.getRootFolder(), new IndexBuilder(index, contentReader)); } catch (IOException e) { logError(e, "Failed to build data index").log(); } long duration = System.nanoTime() - startTime; logInfo("Finished building data index.").addParameter("entries", index.size()).addParameter("duration_ns", duration).log(); indexBuilt = true; }; pool.submit(build); }
Source:
<code>public StatsTotalRequest(ITmfTrace trace, TmfTimeRange range) { super(trace.getEventType(), range, TmfDataRequest.ALL_DATA, <START> chunkSize, ITmfDataRequest.ExecutionType.FOREGROUND); <END> total = 0; }</code><technical_language>background</technical_language>

Target:
public StatsTotalRequest(ITmfTrace trace, TmfTimeRange range) { super(trace.getEventType(), range, TmfDataRequest.ALL_DATA, trace.getCacheSize(), ITmfDataRequest.ExecutionType.BACKGROUND); total = 0; }
Source:
<code>private InputTransformer getTransformer(String mimeType, String id) throws Exception { LOGGER.trace("ENTERING: getTransformer"); InputTransformer transformer = null; ServiceReference[] refs = null; try { <START> String filter = "(&(" + "mime-type" + "=" + mimeType + ")(" + "id" + "=" + id + "))"; <END> LOGGER.debug("Looking for InputTransformer with filter: {}", filter); refs = bundleContext.getServiceReferences(InputTransformer.class.getName(), filter); } catch (Exception e) { String msg = "Invalid input transformer for mime type: " + mimeType; LOGGER.debug(msg, e); throw new Exception(msg); } if (refs != null && refs.length > 0) { transformer = (InputTransformer) bundleContext.getService(refs[0]); LOGGER.debug("Found an InputTransformer: {}", transformer.getClass().getName()); } LOGGER.trace("EXITING: getTransformer"); return transformer; }</code><technical_language>String.format("(&(mime-type=%s)(id=%s))", mimeType, id);</technical_language>

Target:
private InputTransformer getTransformer(String mimeType, String id) throws Exception { LOGGER.trace("ENTERING: getTransformer"); InputTransformer transformer = null; ServiceReference[] refs = null; try { String filter = String.format("(&(mime-type=%s)(id=%s))", mimeType, id); LOGGER.debug("Looking for InputTransformer with filter: {}", filter); refs = bundleContext.getServiceReferences(InputTransformer.class.getName(), filter); } catch (Exception e) { String msg = "Invalid input transformer for mime type: " + mimeType; LOGGER.debug(msg, e); throw new Exception(msg); } if (refs != null && refs.length > 0) { transformer = (InputTransformer) bundleContext.getService(refs[0]); LOGGER.debug("Found an InputTransformer: {}", transformer.getClass().getName()); } LOGGER.trace("EXITING: getTransformer"); return transformer; }
Source:
<code>private void loadHeader(final Reader headerReader) throws IOException { final LineNumberReader lnr = new LineNumberReader(headerReader); try { while (true) { <START> final String line = lnr.readLine(); <END> if (line == null) { break; } readerLines.add(line); } postProcessHeaderLines(); } finally { Closeables.closeQuietly(lnr); } }</code><technical_language>please refactor code a bit more like: do{ String line = lnr.readLine(); if (line != null) { readerLines.add(line); } } while (line != null)</technical_language>

Target:
private void loadHeader(final Reader headerReader) throws IOException { final LineNumberReader lnr = new LineNumberReader(headerReader); try { String line; do { line = lnr.readLine(); if (line != null) { readerLines.add(line); } } while (line != null); postProcessHeaderLines(); } finally { Closeables.closeQuietly(lnr); } }