auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void readNextContainer() { nextContainer = containerFromStream(cramHeader.getVersion(), countingInputStream); if (nextContainer.isEOF()) { eof = true; nextContainer = null; } <START> } <END></code><technical_language>This is cleaning nicely</technical_language>

Target:
private void readNextContainer() { nextContainer = containerFromStream(countingInputStream); if (nextContainer.isEOF()) { eof = true; nextContainer = null; } }
Source:
<code>private void addCustomActionPlugins() { <START> if ( actionPlugins != null ) { <END> for ( RuleModellerActionPlugin actionPlugin : actionPlugins ) { final IAction iAction = actionPlugin.createIAction( oracle.getResourcePath() ); actionPlugin.addPluginToActionList( oracle.getResourcePath(), () -> { choices.addItem( actionPlugin.getActionAddDescription(), actionPlugin.getId() ); cmds.put( actionPlugin.getId(), () -> { model.addRhsItem( iAction, Integer.parseInt( positionCbo.getValue( positionCbo.getSelectedIndex() ) ) ); hide(); } ); } ); } } }</code><technical_language>I prefer of Optional null</technical_language>

Target:
private void addCustomActionPlugins() { if (actionPlugins != null) { for (RuleModellerActionPlugin actionPlugin : actionPlugins) { final IAction iAction = actionPlugin.createIAction(ruleModeller); actionPlugin.addPluginToActionList(ruleModeller, () -> { choices.addItem(actionPlugin.getActionAddDescription(), actionPlugin.getId()); cmds.put(actionPlugin.getId(), () -> { model.addRhsItem(iAction, Integer.parseInt(positionCbo.getValue(positionCbo.getSelectedIndex()))); hide(); }); }); } } }
Source:
<code>static void checkConfigGroupsHasServiceName() { Map<Long, ConfigGroup> configGroupMap = collectConfigGroupsWithoutServiceName(); if (MapUtils.isEmpty(configGroupMap)) return; StringBuilder output = new StringBuilder("[(ConfigGroup) => "); for (ConfigGroup configGroup : configGroupMap.values()) { <START> configGroupMap.put(configGroup.getId(), configGroup); <END> output.append("( "); output.append(configGroup.getName()); output.append(" ), "); } output.replace(output.lastIndexOf(","), output.length(), "]"); warning("You have config groups present in the database with no " + " service name, {}. Run --auto-fix-database to fix " + "this automatically.", output.toString()); }</code><technical_language>values in map</technical_language>

Target:
static void checkConfigGroupsHasServiceName() { Map<Long, ConfigGroup> configGroupMap = collectConfigGroupsWithoutServiceName(); if (MapUtils.isEmpty(configGroupMap)) return; StringBuilder output = new StringBuilder("[(ConfigGroup) => "); for (ConfigGroup configGroup : configGroupMap.values()) { output.append("( "); output.append(configGroup.getName()); output.append(" ), "); } output.replace(output.lastIndexOf(","), output.length(), "]"); warning("You have config groups present in the database with no " + "service name, {}. Run --auto-fix-database to fix " + "this automatically. Please backup Ambari Server database before running --auto-fix-database.", output.toString()); }
Source:
<code>public ColumnCapabilities getColumnCapabilities(String column) { <START> if (index.getColumn(column) == null) { <END> return null; } return index.getColumn(column).getCapabilities(); }</code><technical_language>nice save index.getColumn(column) do lookup if non-null</technical_language>

Target:
public ColumnCapabilities getColumnCapabilities(String column) { Column columnObj = index.getColumn(column); if (columnObj == null) { return null; } return columnObj.getCapabilities(); }
Source:
<code>private Set<String> generateIds(final String namespace, final ComponentCategory category, final int quantity) { final Set<String> generatedComponentIds = newLinkedHashSet(); final int maxAttempts = getConfig().getMaxIdGenerationAttempts(); int remainingQuantity = quantity; for (int attempt = 1; attempt <= maxAttempts && generatedComponentIds.size() != quantity; attempt++) { final int currentAttempt = attempt; final Set<String> newGeneratedComponentIds = IntStream.range(0, remainingQuantity) <START> .mapToObj(i -> generateId(namespace, category, currentAttempt)) <END> .collect(Collectors.toSet()); Set<String> reservedIds = isReserved(newGeneratedComponentIds, generatedComponentIds); newGeneratedComponentIds.removeAll(reservedIds); generatedComponentIds.addAll(newGeneratedComponentIds); } if (generatedComponentIds.size() != quantity) { throw new BadRequestException("Couldn't generate %s identifiers [%s, %s] in maximum (%s) number of attempts", quantity, category, namespace, maxAttempts); } else { return ImmutableSet.<String>copyOf(generatedComponentIds); } }</code><technical_language>sequential generation strategy relies currentAttempt re-set 1 for sequence number. If attempt number is kept, revert next number a bigger "knot". Before: ||||x|||| After: ||||x|?|?|?| Legend: |=generated x=collision (already assigned) ?=unknown This track of attempt counters, for set of SCTIDs, another for a single SCTID</technical_language>

Target:
private Set<String> generateIds(final String namespace, final ComponentCategory category, final int quantity) { final Set<String> generatedComponentIds = newLinkedHashSet(); final int maxAttempts = getConfig().getMaxIdGenerationAttempts(); for (int attempt = 1; attempt <= maxAttempts && generatedComponentIds.size() != quantity; attempt++) { final int remainingQuantity = quantity - generatedComponentIds.size(); Set<String> newGeneratedComponentIds = doGenerateIds(namespace, category, remainingQuantity, attempt); Set<String> reservedIds = isReserved(newGeneratedComponentIds, generatedComponentIds); newGeneratedComponentIds.removeAll(reservedIds); generatedComponentIds.addAll(newGeneratedComponentIds); } if (generatedComponentIds.size() != quantity) { final String namespaceValue = Strings.isNullOrEmpty(namespace) ? SnomedIdentifiers.INT_NAMESPACE : namespace; throw new BadRequestException("Couldn't generate %s identifiers [%s, %s] in maximum (%s) number of attempts", quantity, category, namespaceValue, maxAttempts); } else { return ImmutableSet.<String>copyOf(generatedComponentIds); } }
Source:
<code>public StreamingOutput create(RegisterDetail registerDetail, List<Record> records) { return output -> { try (ZipEntryWriter zipEntryWriter = new ZipEntryWriter(output)) { zipEntryWriter.writeEntry("register.json", registerDetail); records.stream() <START> .collect(Collectors.toMap(e -> e.entry.getSha256hex(), e -> e)) <END> .forEach((hash, d) -> { zipEntryWriter.writeEntry(String.format("item/%s.json", hash), d.item.content); zipEntryWriter.writeEntry(String.format("entry/%s.json", d.entry.entryNumber), new ArchiveEntryData(d.entry.entryNumber, d.entry.getSha256hex(), d.entry.getTimestamp())); } ); } }; }</code><technical_language>If entries in this list of records refer item, this raise a "duplicate key" exception e.entry.getSha256hex() same. create() method separate lists of Entry Item objects avoid this</technical_language>

Target:
public StreamingOutput create(RegisterDetail registerDetail, List<Record> records) { return output -> { try (ZipEntryWriter zipEntryWriter = new ZipEntryWriter(output)) { zipEntryWriter.writeEntry("register.json", registerDetail); records.stream().map(r -> r.item).distinct().forEach(item -> zipEntryWriter.writeEntry(String.format("item/%s.json", item.sha256hex), item.content) ); records.stream().map(r -> r.entry).forEach(entry -> zipEntryWriter.writeEntry(String.format("entry/%s.json", entry.entryNumber), new ArchiveEntryData(entry.entryNumber, entry.getSha256hex(), entry.getTimestamp())) ); } }; }
Source:
<code>public VersionInfo getVersionInfo() { String versionString = BuildConfig.VERSION_NAME; String splits[] = versionString.split("\\."); int major = Integer.parseInt(splits[0]); int minor = Integer.parseInt(splits[1]); <START> int micro = Integer.parseInt(splits[2]) * 100 + Integer.parseInt(splits[3]); <END> return new VersionInfo(major, minor, micro); }</code><technical_language>Please add if() statement. In case adapter version changes, this crash</technical_language>

Target:
public VersionInfo getVersionInfo() { String versionString = BuildConfig.VERSION_NAME; String splits[] = versionString.split("\\."); int major = 0; int minor = 0; int micro = 0; if (splits.length > 2) { major = Integer.parseInt(splits[0]); minor = Integer.parseInt(splits[1]); micro = Integer.parseInt(splits[2]) * 100; if (splits.length > 3) { micro += Integer.parseInt(splits[3]); } } else if (splits.length == 2) { major = Integer.parseInt(splits[0]); minor = Integer.parseInt(splits[1]); } else if (splits.length == 1) { major = Integer.parseInt(splits[0]); } return new VersionInfo(major, minor, micro); }
Source:
<code>private Set<String> collectMapValues(Map<String, Set<String>> map) { <START> return map.values() <END> .stream() .flatMap(set -> set.stream()) .collect(Collectors.toCollection(HashSet::new)); }</code><technical_language>This overly complicated. Set<String> set = new HashSet<>(); map.values().forEach((s) -> set.addAll(s)); return set;</technical_language>

Target:
private Set<String> collectMapValues(Map<String, Set<String>> map) { Set<String> set = new HashSet<>(); map.values().forEach((s) -> set.addAll(s)); return set; }
Source:
<code><START> private boolean isCommonCacheUsed(){ <END> AuthenticationContext authenticationContext = createAuthenticationContext(); if(authenticationContext.getCache() instanceof DefaultTokenCacheStore){ return true; } return false; }</code><technical_language>need based version default token cache is used. If want test versions of ADAL do common cache... for example</technical_language>

Target:
private boolean isCommonCacheUsed() { boolean isCommonAvailable = false; try { Class.forName("com.microsoft.identity.common.internal.cache.ADALOAuth2TokenCache"); isCommonAvailable = true; } catch (ClassNotFoundException e) { e.printStackTrace(); } if(isCommonAvailable) { AuthenticationContext authenticationContext = createAuthenticationContext(); return authenticationContext.getCache() instanceof DefaultTokenCacheStore; } return false; }
Source:
<code>public void testNonBlockingRouterFactory() throws Exception { MockClusterMap mockClusterMap = new MockClusterMap(); try { <START> Properties props = getNonBlockingRouterProperties("NotInClusterMap"); <END> VerifiableProperties verifiableProperties = new VerifiableProperties((props)); router = (NonBlockingRouter) new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); Assert.fail("NonBlockingRouterFactory instantiation should have failed because the router datacenter is not in " + "the cluster map"); } catch (IllegalStateException e) { } Properties props = getNonBlockingRouterProperties("DC1"); VerifiableProperties verifiableProperties = new VerifiableProperties((props)); router = (NonBlockingRouter) new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); assertExpectedThreadCounts(1); router.close(); assertExpectedThreadCounts(0); }</code><technical_language>minor. out creation of props verifiable props of try block over-ride for next test case</technical_language>

Target:
public void testNonBlockingRouterFactory() throws Exception { MockClusterMap mockClusterMap = new MockClusterMap(); Properties props = getNonBlockingRouterProperties("NotInClusterMap"); VerifiableProperties verifiableProperties = new VerifiableProperties((props)); try { router = (NonBlockingRouter) new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); Assert.fail("NonBlockingRouterFactory instantiation should have failed because the router datacenter is not in " + "the cluster map"); } catch (IllegalStateException e) { } props = getNonBlockingRouterProperties("DC1"); verifiableProperties = new VerifiableProperties((props)); router = (NonBlockingRouter) new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); assertExpectedThreadCounts(1); router.close(); assertExpectedThreadCounts(0); }
Source:
<code>public synchronized void send(final EventualMessage msg) { assert msg.getTarget() == this; if (firstMessage == null) { firstMessage = msg; if (VmSettings.MESSAGE_TIMESTAMPS) { firstMessageTimeStamp = System.currentTimeMillis(); } } else { appendToMailbox(msg); } logMessageAddedToMailbox(msg); <START> if ((!isExecuting) && replayCanProcess(msg)) { <END> isExecuting = true; executeOnPool(); } }</code><technical_language>solve this overriding send() in TracingActor? if this trace replay code in class</technical_language>

Target:
public synchronized void send(final EventualMessage msg) { assert msg.getTarget() == this; if (firstMessage == null) { firstMessage = msg; if (VmSettings.MESSAGE_TIMESTAMPS) { firstMessageTimeStamp = System.currentTimeMillis(); } } else { appendToMailbox(msg); } if (!isExecuting) { isExecuting = true; executeOnPool(); } }
Source:
<code>private static void dumpMetadata(Checker checker, String path) throws CheckstyleException, IOException { final List<File> validFiles = new ArrayList<>(); if (path.endsWith(".java")) { validFiles.add(new File(path)); } else { final List<String> moduleFolders = Arrays.asList("checks", "filters", "filefilters"); for (String folder : moduleFolders) { try (Stream<Path> files = Files.walk(Paths.get(path + "/" + folder))) { <START> validFiles.addAll(files.map(Path::toString) <END> .filter(fileName -> { return fileName.endsWith("SuppressWarningsHolder.java") || fileName.endsWith("Check.java") || fileName.endsWith("Filter.java"); }) .map(File::new) .collect(Collectors.toList())); } } } checker.process(validFiles); }</code><technical_language>files.map(Path::toString) is need convert Path string file, Path methods boolean endsWith(String other) File toFile() simpler Please correct other occurrences if</technical_language>

Target:
private static void dumpMetadata(Checker checker, String path) throws CheckstyleException, IOException { final List<File> validFiles = new ArrayList<>(); if (path.endsWith(".java")) { validFiles.add(new File(path)); } else { final List<String> moduleFolders = Arrays.asList("checks", "filters", "filefilters"); for (String folder : moduleFolders) { try (Stream<Path> files = Files.walk(Paths.get(path + "/" + folder))) { validFiles.addAll( files.map(Path::toFile) .filter(file -> { return file.getName().endsWith("SuppressWarningsHolder.java") || file.getName().endsWith("Check.java") || file.getName().endsWith("Filter.java"); }) .collect(Collectors.toList())); } } } checker.process(validFiles); }
Source:
<code>private void onNext() { String phoneNumber = getPseudoValidPhoneNumber(); <START> if (phoneNumber == null) { <END> mPhoneInputLayout.setError(getString(R.string.fui_invalid_phone_number)); } else { mHandler.verifyPhoneNumber(phoneNumber, false); } }</code><technical_language>If isCountryValid is true isValid is false call onNext() a situation getPseudoValidPhoneNumber() return null put error screen</technical_language>

Target:
private void onNext() { String phoneNumber = getPseudoValidPhoneNumber(); if (phoneNumber == null) { mPhoneInputLayout.setError(getString(R.string.fui_invalid_phone_number)); } else { mVerificationHandler.verifyPhoneNumber(phoneNumber, false); } }
Source:
<code>private void toBoolean(Value value) { ValueType type = value.getType(); if (type == ValueType.STRING) { String s = value.getString(); if (Boolean.TRUE.toString().equalsIgnoreCase(s)) { value.set(Boolean.TRUE); } else if (Boolean.FALSE.toString().equalsIgnoreCase(s)) { value.set(Boolean.FALSE); <START> } else if ("true".equalsIgnoreCase(s)) { END> value.set(Boolean.TRUE); } else if ("false".equalsIgnoreCase(s)) { value.set(Boolean.TRUE); } else if ("0".equals(s)) { value.set(Boolean.FALSE); } else if ("1".equals(s)) { value.set(Boolean.TRUE); } else { try { double d = Double.parseDouble(s); value.set(d != 0d); } catch (Exception ignore) { } } } else if (type == ValueType.NUMBER) { Number num = value.getNumber(); if (num instanceof Double) { value.set(num.doubleValue() != 0d); } else if (num instanceof Float) { value.set(num.floatValue() != 0f); } else { value.set(num.longValue() != 0l); } } }</code><technical_language>bad. Tridiums Niagara version of Boolean I fix for Distech</technical_language>

Target:
private void toBoolean(Value value) { ValueType type = value.getType(); if (type == ValueType.STRING) { String s = value.getString(); if ("true".equalsIgnoreCase(s)) { value.set(Boolean.TRUE); } else if ("false".equalsIgnoreCase(s)) { value.set(Boolean.FALSE); } else if ("0".equals(s)) { value.set(Boolean.FALSE); } else if ("1".equals(s)) { value.set(Boolean.TRUE); } else { try { double d = Double.parseDouble(s); value.set(d != 0d); } catch (Exception ignore) { } } } else if (type == ValueType.NUMBER) { Number num = value.getNumber(); if (num instanceof Double) { value.set(num.doubleValue() != 0d); } else if (num instanceof Float) { value.set(num.floatValue() != 0f); } else { value.set(num.longValue() != 0l); } } }
Source:
<code><START> private void finishPage() { <END> IStatus status= fPage.getModuleStatus(); if (status.isOK()) { moduleName= fPage.getModuleText(); if (project != null) { try { IPackageFragmentRoot[] packageFragmentRoots= project.getPackageFragmentRoots(); List<IPackageFragmentRoot> packageFragmentRootsAsList= new ArrayList<>(Arrays.asList(packageFragmentRoots)); for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) { IResource res= packageFragmentRoot.getCorrespondingResource(); if (res == null || res.getType() != IResource.FOLDER || packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE) { packageFragmentRootsAsList.remove(packageFragmentRoot); } } packageFragmentRoots= packageFragmentRootsAsList.toArray(new IPackageFragmentRoot[packageFragmentRootsAsList.size()]); if (packageFragmentRoots.length == 0) { return; } IPackageFragmentRoot targetPkgFragmentRoot= null; for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) { if (packageFragmentRoot.getPackageFragment("").getCompilationUnit(MODULE_INFO_JAVA_FILENAME).exists()) { targetPkgFragmentRoot= packageFragmentRoot; break; } } if (targetPkgFragmentRoot == null) { targetPkgFragmentRoot= packageFragmentRoots[0]; } createAndOpenFile(targetPkgFragmentRoot, packageFragmentRoots); } catch (CoreException e) { JavaPlugin.log(e); } } } return; }</code><technical_language>This method inlined</technical_language>

Target:
private void finishPage() { IStatus status= fPage.getModuleNameStatus(); if (status.isOK()) { if (fProject != null && fTargetPkgFragmentRoot != null && fPackageFragmentRoots != null && fPackageFragmentRoots.length > 0) { try { createAndOpenFile(fTargetPkgFragmentRoot, fPackageFragmentRoots); } catch (CoreException e) { JavaPlugin.log(e); } } } return; }
Source:
<code>private byte[] convertToByteArray(Object value) { if (value instanceof IndexedRecord) { IndexedRecord payloadRecord = (IndexedRecord) value; try { return AvroUtils.encodeAvroRecord(payloadRecord.getSchema(), payloadRecord); } catch (IOException e) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to encode event in Avro, event=" + payloadRecord, e); } } else if (value instanceof String) { return ((String) value).getBytes(); } <START> throw new DatastreamRuntimeException("Transport provider supports payloads of type String or AvroRecords"); <END> }</code><technical_language>nit: AvroRecords -> Avro IndexRecords KafkaTransportProvider in place of "Transport provider"</technical_language>

Target:
private byte[] convertToByteArray(Object value) { if (value instanceof IndexedRecord) { IndexedRecord payloadRecord = (IndexedRecord) value; try { return AvroUtils.encodeAvroIndexedRecord(payloadRecord.getSchema(), payloadRecord); } catch (IOException e) { ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to encode event in Avro, event=" + payloadRecord, e); } } else if (value instanceof String) { return ((String) value).getBytes(); } throw new DatastreamRuntimeException("Transport provider supports payloads of type String or AvroRecords"); }
Source:
<code>public synchronized void dispose() { fDisposed = true; ModelNode[] childrenNodes = getChildrenNodes(); if (childrenNodes != null) { for (ModelNode <START> childrenNode : <END> childrenNodes) { childrenNode.dispose(); } } }</code><technical_language>rename childNode node</technical_language>

Target:
public synchronized void dispose() { fDisposed = true; ModelNode[] childrenNodes = getChildrenNodes(); if (childrenNodes != null) { for (ModelNode node : childrenNodes) { node.dispose(); } } }
Source:
<code>static RuleSet getVoltPhysicalConversionRules() { <START> final List<RelOptRule> ruleList = new ArrayList<>(); <END> ruleList.add(VoltDBPCalcRule.INSTANCE); ruleList.add(VoltDBPSeqScanRule.INSTANCE); ruleList.add(VoltDBPSortConvertRule.INSTANCE_VOLTDB); ruleList.add(VoltDBPLimitRule.INSTANCE); ruleList.add(VoltDBPAggregateRule.INSTANCE); ruleList.add(VoltDBPJoinRule.INSTANCE); return RuleSets.ofList(ruleList); }</code><technical_language>Minor: create static final private RuleSet member, return instance in method. way, free of cost of creating a new instance time call getVoltPhysicalConversionRules()</technical_language>

Target:
static RuleSet getVoltPhysicalConversionRules() { return s_VoltPhysicalConversionRules; }
Source:
<code>public void visitIfStatement(IfStatementTree tree) { Tree parentTree = tree.parent(); <START> if (parentTree.is(Tree.Kind.IF_STATEMENT) && ((IfStatementTree) parentTree).elseKeyword() != null) { <END> checkForReport(tree.thenStatement(), ((IfStatementTree) parentTree).elseKeyword(), tree.closeParenToken(), tree.ifKeyword().firstToken().text()); } else { checkForReport(tree.thenStatement(), tree.ifKeyword(), tree.closeParenToken(), tree.ifKeyword().text()); } SyntaxToken elseKeyword = tree.elseKeyword(); if (elseKeyword != null && !tree.elseStatement().is(Tree.Kind.IF_STATEMENT)) { checkForReport(tree.elseStatement(), elseKeyword, elseKeyword, elseKeyword.firstToken().text()); } super.visitIfStatement(tree); }</code><technical_language>replace condition ((IfStatementTree) parentTree).elseKeyword() != null tree.equals(((IfStatementTree) parentTree).elseStatement()) current if a child of if-statement else if statement (i.e. current if-statement is thenStatement of parent). Ex: if (i > 0) if (i >1) // Noncompliant issue caught current implementation doTheThing(); else doTheOtherThing(); else somethingElseEntirely();</technical_language>

Target:
public void visitIfStatement(IfStatementTree tree) { Tree parentTree = tree.parent(); if (parentTree.is(Tree.Kind.IF_STATEMENT) && tree.equals(((IfStatementTree) parentTree).elseStatement())) { checkForReport(tree.thenStatement(), ((IfStatementTree) parentTree).elseKeyword(), tree.closeParenToken(), tree.ifKeyword().firstToken().text()); } else { checkForReport(tree.thenStatement(), tree.ifKeyword(), tree.closeParenToken(), tree.ifKeyword().text()); } SyntaxToken elseKeyword = tree.elseKeyword(); if (elseKeyword != null && !tree.elseStatement().is(Tree.Kind.IF_STATEMENT)) { checkForReport(tree.elseStatement(), elseKeyword, elseKeyword, elseKeyword.firstToken().text()); } super.visitIfStatement(tree); }
Source:
<code>void okbuck() { boolean hasGroovyLib = okBuckExtension.buckProjects.parallelStream().anyMatch(project -> ProjectUtil.getType(project) == ProjectType.GROOVY_LIB); if (hasGroovyLib) { GroovyUtil.setupGroovyHome(getProject()); } <START> boolean hasKotlinLib = ProjectUtil.hasArtifactInClasspath(getProject(), KotlinUtil.KOTLIN_GROUP, KotlinUtil.KOTLIN_GRADLE_MODULE); <END> if (hasKotlinLib) { KotlinUtil.setupKotlinHome(getProject()); } generate(okBuckExtension, hasGroovyLib ? GroovyUtil.GROOVY_HOME_LOCATION : null, hasKotlinLib ? KotlinUtil.KOTLIN_HOME_LOCATION : null); }</code><technical_language>move this utility method KotlinUtil instead? weird put this project util if reused else</technical_language>

Target:
void okbuck() { boolean hasGroovyLib = okBuckExtension.buckProjects.parallelStream().anyMatch(project -> ProjectUtil.getType(project) == ProjectType.GROOVY_LIB); if (hasGroovyLib) { GroovyUtil.setupGroovyHome(getProject()); } boolean hasKotlinLib = KotlinUtil.hasKotlinPluginInClasspath(getProject()); if (hasKotlinLib) { KotlinUtil.setupKotlinHome(getProject()); } generate(okBuckExtension, hasGroovyLib ? GroovyUtil.GROOVY_HOME_LOCATION : null, hasKotlinLib ? KotlinUtil.KOTLIN_HOME_LOCATION : null); }
Source:
<code>private Stream<ConfigurationSetting> listSettings(SettingSelector options, Context context) { List<ConfigurationSetting> listConfigurationSettings = client.listSettings(options, context).collectList().block(); <START> return listConfigurationSettings != null ? listConfigurationSettings.stream() : Stream.empty(); <END> }</code><technical_language>This is unnecessary extra work, do return client.listSettings(options, context).toStream()</technical_language>

Target:
public PagedIterable<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedIterable<>(client.listSettings(options, context)); }
Source:
<code>protected Boolean visitDereferenceExpression(DereferenceExpression expected, RowExpression actual) { if (!(actual instanceof SpecialFormExpression) || !(((SpecialFormExpression) actual).getForm().equals(DEREFERENCE))) { return false; } SpecialFormExpression actualDereference = (SpecialFormExpression) actual; if (actualDereference.getArguments().size() == 2 && actualDereference.getArguments().get(0).getType() instanceof RowType && actualDereference.getArguments().get(1) instanceof ConstantExpression) { RowType rowType = (RowType) actualDereference.getArguments().get(0).getType(); Object value = LiteralInterpreter.evaluate(TEST_SESSION.toConnectorSession(), (ConstantExpression) actualDereference.getArguments().get(1)); Preconditions.checkState(value instanceof Long); long index = (Long) value; Preconditions.checkState(index >= 0 && index < rowType.getFields().size()); <START> RowType.Field field = rowType.getFields().get((int) index); <END> Preconditions.checkState(field.getName().isPresent()); return expected.getField().getValue().equals(field.getName().get()) && process(expected.getBase(), actualDereference.getArguments().get(0)); } return false; }</code><technical_language>Math.toIntExact</technical_language>

Target:
protected Boolean visitDereferenceExpression(DereferenceExpression expected, RowExpression actual) { if (!(actual instanceof SpecialFormExpression) || !(((SpecialFormExpression) actual).getForm().equals(DEREFERENCE))) { return false; } SpecialFormExpression actualDereference = (SpecialFormExpression) actual; if (actualDereference.getArguments().size() == 2 && actualDereference.getArguments().get(0).getType() instanceof RowType && actualDereference.getArguments().get(1) instanceof ConstantExpression) { RowType rowType = (RowType) actualDereference.getArguments().get(0).getType(); Object value = LiteralInterpreter.evaluate(TEST_SESSION.toConnectorSession(), (ConstantExpression) actualDereference.getArguments().get(1)); checkState(value instanceof Long); long index = (Long) value; checkState(index >= 0 && index < rowType.getFields().size()); RowType.Field field = rowType.getFields().get(toIntExact(index)); checkState(field.getName().isPresent()); return expected.getField().getValue().equals(field.getName().get()) && process(expected.getBase(), actualDereference.getArguments().get(0)); } return false; }
Source:
<code>public WindowedStream<T> window(final WindowInformation windowInfo) { <START> final WindowedStream<T> downStream = windowInfo.getWindowedStream(dag); <END> dag.addVertex(downStream); dag.addEdge(this, downStream, StreamType.Direction.LEFT); return downStream; }</code><technical_language>windowInfo returns windowdStream? this is intuitive</technical_language>

Target:
public WindowOperatorStream<T> window(final WindowInformation windowInfo) { final WindowOperatorStream<T> downStream = new WindowOperatorStream<>(windowInfo, dag); dag.addVertex(downStream); dag.addEdge(this, downStream, StreamType.Direction.LEFT); return downStream; }
Source:
<code>public void visitFileInput(FileInput fileInput) { scopesByRootTree = new HashMap<>(); fileInput.accept(new FirstPhaseVisitor()); fileInput.accept(new SecondPhaseVisitor()); addSymbolsToTree((FileInputImpl) fileInput); <START> handleClassMemberAccess(fileInput); <END> if (!SymbolUtils.isTypeShedFile(pythonFile)) { TypeInference.inferTypes(fileInput); } }</code><technical_language>define a ThirdPhaseVisitor (or name) write fileInput.accept(new ThirdPhaseVisitor()) for consistency</technical_language>

Target:
public void visitFileInput(FileInput fileInput) { scopesByRootTree = new HashMap<>(); fileInput.accept(new FirstPhaseVisitor()); fileInput.accept(new SecondPhaseVisitor()); addSymbolsToTree((FileInputImpl) fileInput); fileInput.accept(new ThirdPhaseVisitor()); if (!SymbolUtils.isTypeShedFile(pythonFile)) { TypeInference.inferTypes(fileInput); } }
Source:
<code>public void deleteGroupRole(String group, String role) { throw new RuntimeException("Deleting a group role is not supporting in LDAP"); <START> <END> }</code><technical_language>extra space necessary</technical_language>

Target:
public void deleteGroupRole(String group, String role) { throw new UnsupportedOperationException("Deleting a group role is not supporting in LDAP"); }
Source:
<code>public void testTemplateMemberAccessibilities() throws Exception { BindingAssertionHelper bh = getAssertionHelper(); ICPPClassTemplate aTemplate = bh.assertNonProblem("ATemplate"); ICPPField defaultMemberVariable = bh.assertNonProblem("defaultMemberVariable"); <START> VisibilityHelper.assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(defaultMemberVariable)); <END> ICPPField publicMemberVariable = bh.assertNonProblem("publicMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_public, aTemplate.getVisibility(publicMemberVariable)); ICPPField protectedMemberVariable = bh.assertNonProblem("protectedMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_protected, aTemplate.getVisibility(protectedMemberVariable)); ICPPField privateMemberVariable = bh.assertNonProblem("privateMemberVariable"); VisibilityHelper.assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(privateMemberVariable)); }</code><technical_language>Add a static import for assertVisibility method</technical_language>

Target:
public void testTemplateMemberAccessibilities() throws Exception { BindingAssertionHelper bh = getAssertionHelper(); ICPPClassTemplate aTemplate = bh.assertNonProblem("ATemplate"); ICPPField defaultMemberVariable = bh.assertNonProblem("defaultMemberVariable"); assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(defaultMemberVariable)); ICPPField publicMemberVariable = bh.assertNonProblem("publicMemberVariable"); assertVisibility(ICPPClassType.v_public, aTemplate.getVisibility(publicMemberVariable)); ICPPField protectedMemberVariable = bh.assertNonProblem("protectedMemberVariable"); assertVisibility(ICPPClassType.v_protected, aTemplate.getVisibility(protectedMemberVariable)); ICPPField privateMemberVariable = bh.assertNonProblem("privateMemberVariable"); assertVisibility(ICPPClassType.v_private, aTemplate.getVisibility(privateMemberVariable)); }
Source:
<code>private static void assertAggregationInternal(InternalAggregationFunction function, BiFunction<Object, Object, Boolean> isEqual, String testDescription, Object expectedValue, Page... pages) { assertFunctionEquals(isEqual, testDescription, aggregation(function, pages), expectedValue); assertFunctionEquals(isEqual, testDescription, partialAggregation(function, pages), expectedValue); if (pages.length > 0) { assertFunctionEquals(isEqual, testDescription, groupedAggregation(function, pages), expectedValue); assertFunctionEquals(isEqual, testDescription, groupedPartialAggregation(function, pages), expectedValue); <START> assertFunctionEquals(isEqual, testDescription, distinctAggregation(function, pages), expectedValue); <END> } }</code><technical_language>groupedPartialAggregation distinctAggregation Assert.assertEquals check aggregation results. Is this case? If so, need pass a version of Assert.assertEquals</technical_language>

Target:
private static void assertAggregationInternal(InternalAggregationFunction function, BiFunction<Object, Object, Boolean> isEqual, String testDescription, Object expectedValue, Page... pages) { assertFunctionEquals(isEqual, testDescription, aggregation(function, pages), expectedValue); assertFunctionEquals(isEqual, testDescription, partialAggregation(function, pages), expectedValue); if (pages.length > 0) { assertFunctionEquals(isEqual, testDescription, groupedAggregation(isEqual, function, pages), expectedValue); assertFunctionEquals(isEqual, testDescription, groupedPartialAggregation(isEqual, function, pages), expectedValue); assertFunctionEquals(isEqual, testDescription, distinctAggregation(function, pages), expectedValue); } }
Source:
<code>private static void putSwtVersion(VersionMap values, Version swtVersion) { if (!(swtVersion instanceof OSGiVersion)) return; int major = ((OSGiVersion) swtVersion).getMajor(); if (major != 3) return; int minor = ((OSGiVersion) swtVersion).getMinor(); <START> if (minor == 100) { <END> values.put(VERSION, "4.2"); } else if (minor < 200) { values.put(VERSION, "4." + (minor - 99)); } }</code><technical_language>Do remove</technical_language>

Target:
private static void putSwtVersion(VersionMap values, Version swtVersion) { if (!(swtVersion instanceof OSGiVersion)) return; int major = ((OSGiVersion) swtVersion).getMajor(); if (major != 3) return; int minor = ((OSGiVersion) swtVersion).getMinor(); if (minor < 100) { values.put(VERSION, "3." + minor); } else if (minor == 100) { values.put(VERSION, "4.2"); } else if (minor < 200) { values.put(VERSION, "4." + (minor - 99)); } }
Source:
<code>public List<NodeHistory> getNodesHistory(long windowStart, long windowEnd) { return executeReadTransaction(session -> { <START> Query query = session.createQuery("FROM NodeHistory " + <END> "WHERE (:windowStart <= startTime AND startTime <= :windowEnd) " + "OR (:windowStart <= endTime AND endTime <= :windowEnd)"); query.setParameter("windowStart", windowStart); query.setParameter("windowEnd", windowEnd); return query.list(); }); }</code><technical_language>endtime is default null, this query behave for :windowStart <= endTime endTime <= :windowEnd</technical_language>

Target:
public List<NodeHistory> getNodesHistory(long windowStart, long windowEnd) { return executeReadTransaction(session -> { Query query = session.createQuery("FROM NodeHistory " + "WHERE (endTime = 0 OR :windowStart <= endTime) " + "AND ( startTime <= :windowEnd )"); query.setParameter("windowStart", windowStart); query.setParameter("windowEnd", windowEnd); return (List<NodeHistory>) query.list(); }); }
Source:
<code>protected void recursivelyPrint(AbstractPlanNode node, StringBuilder sb) { for (int i = 0; i < indent; i++) { sb.append("\t"); } sb.append(node.toJSONString() + "\n"); indent++; if (node.getChildCount() > 0) { recursivelyPrint(node.getChild(0), sb); } <START> } <END></code><technical_language>This class a member variable called indent incur a data race in recursivelyPrint. This is easily fixable making indent a parameter recursivelyPrint. I realize debug-only code</technical_language>

Target:
protected void recursivelyPrint(AbstractPlanNode node, StringBuilder sb) { recursivelyPrint(node, sb, 0); }
Source:
<code>public Collection[] getCollections() throws SQLException { List<Collection> collections = new ArrayList<Collection>(); TableRowIterator tri = null; try { String query = "SELECT c.* FROM community2collection c2c, collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) " + "WHERE c2c.collection_id=c.collection_id AND c2c.community_id=? "; <START> if("oracle".equals(ConfigurationManager.getProperty("db.name"))){ <END> query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } tri = DatabaseManager.query( ourContext, query, Constants.COLLECTION, MetadataField.findByElement(ourContext, MetadataSchema.find(ourContext, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), getID() ); } catch (SQLException e) { log.error("Find all Collections for this community - ",e); throw e; } try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) ourContext.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(ourContext, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }</code><technical_language>DatabaseManager.isOracle()</technical_language>

Target:
public Collection[] getCollections() throws SQLException { List<Collection> collections = new ArrayList<Collection>(); TableRowIterator tri = null; try { String query = "SELECT c.* FROM community2collection c2c, collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) " + "WHERE c2c.collection_id=c.collection_id AND c2c.community_id=? "; if(DatabaseManager.isOracle()){ query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } tri = DatabaseManager.query( ourContext, query, Constants.COLLECTION, MetadataField.findByElement(ourContext, MetadataSchema.find(ourContext, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), getID() ); } catch (SQLException e) { log.error("Find all Collections for this community - ",e); throw e; } try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) ourContext.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(ourContext, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }
Source:
<code>private void runLoop() { subscribeConsumer(); boolean needRebalance = false; while (isRunning()) { try { if (needRebalance) { enforceRebalance(); needRebalance = false; } runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoining the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskWithChangelogs()); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group."); taskManager.handleLostAll(); needRebalance = true; } <START> } <END> }</code><technical_language>Do need this here? call unsubscribe later, invoke: if (generation() != Generation.NO_GENERATION) { e = invokePartitionsRevoked(droppedPartitions); } else { e = invokePartitionsLost(droppedPartitions); } consumer manage task lifecycle, lost _all_ tasks. WDYT removing this line setting needRebalance flag</technical_language>

Target:
private void runLoop() { subscribeConsumer(); while (isRunning()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoining the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskWithChangelogs()); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group."); taskManager.handleLostAll(); enforceRebalance(); } } }
Source:
<code>public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); initStreamLogDirectory(); <START> String logSizeQuotaParam = serverContext.getServerConfig().get("--log-size-quota").toString(); <END> logSizeLimit = Long.parseLong(logSizeQuotaParam); long initialLogSize = estimateSize(logDir); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }</code><technical_language>check for actual disk capacity? if actual disk capacity is smaller than--log-size-quota, quota help, right</technical_language>

Target:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeQuotaParam = (String) serverContext.getServerConfig().get("--log-size-quota-bytes"); logSizeLimit = Long.parseLong(logSizeQuotaParam); initStreamLogDirectory(); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit == -1 ? Long.MAX_VALUE : logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }
Source:
<code>private void broadcastSuccess(final Migration migration) { final Set<String> activeEvaluatorIds = partitionManager.getActiveEvaluators(); final String senderId = migration.getSenderId(); final String receiverId = migration.getReceiverId(); activeEvaluatorIds.remove(senderId); <START> activeEvaluatorIds.remove(receiverId); <END> final List<Integer> blockIds = migration.getBlockIds(); LOG.log(Level.INFO, "Broadcast the result of migration to other active evaluators: {0}", activeEvaluatorIds); try (final TraceScope traceScope = Trace.startSpan("ROUTING_UPDATE")) { final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); for (final String evalId : activeEvaluatorIds) { sender.get().sendRoutingUpdateMsg(evalId, blockIds, senderId, receiverId, traceInfo); } } }</code><technical_language>good mention sender receiver aware of result of migration</technical_language>

Target:
private void broadcastSuccess(final Migration migration) { final Set<String> activeEvaluatorIds = partitionManager.getActiveEvaluators(); final String senderId = migration.getSenderId(); final String receiverId = migration.getReceiverId(); activeEvaluatorIds.remove(senderId); activeEvaluatorIds.remove(receiverId); final List<Integer> blockIds = migration.getBlockIds(); LOG.log(Level.INFO, "Broadcast the result of migration to other active evaluators: {0}", activeEvaluatorIds); try (final TraceScope traceScope = Trace.startSpan("ROUTING_UPDATE")) { final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); for (final String evalId : activeEvaluatorIds) { sender.get().sendRoutingTableUpdateMsg(evalId, blockIds, senderId, receiverId, traceInfo); } } }
Source:
<code>public <START> @Nullable Long <END> getTimeForPoint(int x) { return UIThreadRunnable.syncExec((Result<@Nullable Long>) () -> { Rectangle bounds = widget.getBounds(); Point p = new Point(x, bounds.y + bounds.height / 2); if (!bounds.contains(p)) { return null; } return widget.getTimeAtX(x); }); }</code><technical_language>@Nullable forces test do a null check, in a unit test acceptable fail a NullPointerException if is expected</technical_language>

Target:
public Long getTimeForPoint(int x) { return UIThreadRunnable.syncExec((Result<@Nullable Long>) () -> { Rectangle bounds = widget.getBounds(); Point p = new Point(x, bounds.y + bounds.height / 2); if (!bounds.contains(p)) { return null; } return widget.getTimeAtX(x); }); }
Source:
<code>public void prepare(Object configurationObject) { <START> this.mapper = new StreamsJacksonMapper(); <END> this.datasiftInteractionActivitySerializer = new DatasiftActivitySerializer(); if(this.outClass.equals(Activity.class)) { this.converter = new ActivityConverter(); } else if (this.outClass.equals(String.class)) { this.converter = new StringConverter(); } else { throw new NotImplementedException("No converter implemented for class : "+this.outClass.getName()); } }</code><technical_language>I is a StreamsJacksonMapper.getInstance() method create a new object</technical_language>

Target:
public void prepare(Object configurationObject) { this.mapper = StreamsJacksonMapper.getInstance(); this.datasiftInteractionActivitySerializer = new DatasiftActivitySerializer(); if(this.outClass.equals(Activity.class)) { this.converter = new ActivityConverter(); } else if (this.outClass.equals(String.class)) { this.converter = new StringConverter(); } else { throw new NotImplementedException("No converter implemented for class : "+this.outClass.getName()); } }
Source:
<code>static void assertAccountInAccountService(Account account, AccountService accountService) { <START> account = adjustSnapshotVersion(account, 1); <END> Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); assertEquals("Account got by name from accountService does not match account to assert.", account, accountFoundByName); assertEquals("Account got by id from accountService does not match the account to assert", account, accountFoundById); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }</code><technical_language>is adjusting of version required removal of snapshot version equals()</technical_language>

Target:
static void assertAccountInAccountService(Account account, AccountService accountService) { Account accountFoundById = accountService.getAccountById(account.getId()); Account accountFoundByName = accountService.getAccountByName(account.getName()); assertEquals("Account got by name from accountService does not match account to assert.", account, accountFoundByName); assertEquals("Account got by id from accountService does not match the account to assert", account, accountFoundById); assertEquals("The number of containers in the account is wrong.", accountFoundById.getAllContainers().size(), account.getAllContainers().size()); for (Container container : account.getAllContainers()) { assertContainerInAccountService(container, accountService); } }
Source:
<code>protected String getTemplateFileName(boolean html) { <START> if(tank instanceof GunEmplacement) { <END> if (html) { return "gunemplacement.ftlh"; } return "gunemplacement.ftl"; } if (html) { return "vehicle.ftlh"; } return "vehicle.ftl"; }</code><technical_language>suggestion if (tank instanceof GunEmplacement) {</technical_language>

Target:
protected String getTemplateFileName(boolean html) { if (tank instanceof GunEmplacement) { if (html) { return "gunemplacement.ftlh"; } else { return "gunemplacement.ftl"; } } if (html) { return "vehicle.ftlh"; } return "vehicle.ftl"; }