auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void buildTree(LayoutModel<N> layoutModel) { alreadyDone = Sets.newHashSet(); this.currentX = 0; this.currentY = 0; Set<N> roots = TreeUtils.roots(layoutModel.getGraph()); Preconditions.checkArgument(roots.size() > 0); <START> int overallWidth = calculateDimensionX(layoutModel, roots); <END> overallWidth += (roots.size() + 1) * distX; int overallHeight = calculateDimensionY(layoutModel, roots); overallHeight += 2 * distY; layoutModel.setSize( Math.max(layoutModel.getWidth(), overallWidth), Math.max(layoutModel.getHeight(), overallHeight)); for (N node : roots) { calculateDimensionX(layoutModel, node); currentX += (this.basePositions.get(node) / 2 + this.distX); buildTree(layoutModel, node, (int) currentX); } }</code><technical_language>do overloads of calculateDimension* accept roots incorporate "overall*" corrections in returned? this code easier read</technical_language>

Target:
protected void buildTree(LayoutModel<N> layoutModel) { alreadyDone = Sets.newHashSet(); this.currentX = 0; this.currentY = 0; Set<N> roots = TreeUtils.roots(layoutModel.getGraph()); Preconditions.checkArgument(roots.size() > 0); int overallWidth = calculateWidth(layoutModel, roots); overallWidth += (roots.size() + 1) * horizontalNodeSpacing; int overallHeight = calculateHeight(layoutModel, roots); overallHeight += 2 * verticalNodeSpacing; layoutModel.setSize( Math.max(layoutModel.getWidth(), overallWidth), Math.max(layoutModel.getHeight(), overallHeight)); for (N node : roots) { calculateWidth(layoutModel, node); currentX += (this.basePositions.get(node) / 2 + this.horizontalNodeSpacing); buildTree(layoutModel, node, (int) currentX); } }
Source:
<code>public void goToNewsDetail(final News news) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity()); if (pref.getBoolean(Constants.CONFIG_EXTERNAL_BROWSER, false)) { Intent intent = new Intent(getActivity(), NewsCommentsActivity.class); <START> intent.putExtra(Constants.NEWS, Parcels.wrap(news)); <END> startActivity(intent); if (news.getUrl() != null && !news.getUrl().isEmpty()) { new Handler().postDelayed(new Runnable() { @Override public void run() { Uri uri = Uri.parse(news.getUrl()); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }, 300); } } else { Intent intent = new Intent(getActivity(), NewsDetailActivity.class); intent.putExtra(Constants.NEWS, Parcels.wrap(news)); startActivity(intent); } }</code><technical_language>extract duplicate intent.putExtra startActivity(intent) if-else? (line 101,102 115,116)</technical_language>

Target:
public void goToNewsDetail(final News news) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity()); Intent intent; if (pref.getBoolean(Constants.CONFIG_EXTERNAL_BROWSER, false)) { intent = new Intent(getActivity(), NewsCommentsActivity.class); if (news.getUrl() != null && !news.getUrl().isEmpty()) { new Handler().postDelayed(new Runnable() { @Override public void run() { Uri uri = Uri.parse(news.getUrl()); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }, 300); } } else { intent = new Intent(getActivity(), NewsDetailActivity.class); } intent.putExtra(Constants.NEWS, Parcels.wrap(news)); startActivity(intent); }
Source:
<code>public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); RefactoringStatus result; try { result= new RefactoringStatus(); IJavaElement element= (IJavaElement) getModifiedElement(); result.merge(super.isValid(new SubProgressMonitor(pm, 1))); if (result.hasFatalError()) return result; if (element != null && element.exists() && element instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) element; if (fRenameSubpackages) { IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack); SubProgressMonitor subPm= new SubProgressMonitor(pm, 1); subPm.beginTask("", allPackages.length); for (IPackageFragment <START> fragmentpackage : <END> allPackages) { checkIfModifiable(result, fragmentpackage.getResource(), VALIDATE_NOT_DIRTY); if (result.hasFatalError()) return result; isValid(result, fragmentpackage, new SubProgressMonitor(subPm, 1)); } } else { isValid(result, pack, new SubProgressMonitor(pm, 1)); } } } finally { pm.done(); } return result; }</code><technical_language>rename pckg, fragment packageFragment</technical_language>

Target:
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); RefactoringStatus result; try { result= new RefactoringStatus(); IJavaElement element= (IJavaElement) getModifiedElement(); result.merge(super.isValid(new SubProgressMonitor(pm, 1))); if (result.hasFatalError()) return result; if (element != null && element.exists() && element instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) element; if (fRenameSubpackages) { IPackageFragment[] allPackages= JavaElementUtil.getPackageAndSubpackages(pack); SubProgressMonitor subPm= new SubProgressMonitor(pm, 1); subPm.beginTask("", allPackages.length); for (IPackageFragment pckg : allPackages) { checkIfModifiable(result, pckg.getResource(), VALIDATE_NOT_DIRTY); if (result.hasFatalError()) return result; isValid(result, pckg, new SubProgressMonitor(subPm, 1)); } } else { isValid(result, pack, new SubProgressMonitor(pm, 1)); } } } finally { pm.done(); } return result; }
Source:
<code>void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); <START> if (checkView && !clusterView.contains(target)) <END> return; send(message); }</code><technical_language>this in method</technical_language>

Target:
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { if (checkView && !clusterView.contains(target)) return; Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); send(message); }
Source:
<code>public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(WordPress.SITE, mSite); outState.putString(KEY_PLUGIN_SLUG, mSlug); outState.putBoolean(KEY_IS_CONFIGURING_PLUGIN, mIsConfiguringPlugin); outState.putBoolean(KEY_IS_INSTALLING_PLUGIN, mIsInstallingPlugin); outState.putBoolean(KEY_IS_UPDATING_PLUGIN, mIsUpdatingPlugin); outState.putBoolean(KEY_IS_REMOVING_PLUGIN, mIsRemovingPlugin); outState.putBoolean(KEY_IS_ACTIVE, mIsActive); outState.putBoolean(KEY_IS_AUTO_UPDATE_ENABLED, mIsAutoUpdateEnabled); outState.putBoolean(KEY_IS_SHOWING_REMOVE_PLUGIN_CONFIRMATION_DIALOG, mIsShowingRemovePluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_INSTALL_FIRST_PLUGIN_CONFIRMATION_DIALOG, mIsShowingInstallFirstPluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_AUTOMATED_TRANSFER_PROGRESS, mIsShowingAutomatedTransferProgress); <START> outState.putBoolean(KEY_IS_SHOWING_DOMAIN_CREDIT_CHECK_PROGRESS, mIsShowingDomainCreditCheckProgress); <END> }</code><technical_language>mIsShowingDomainCreditCheckProgress is set true, want consider checking mCheckingDomainCreditsProgressDialog!=null && mCheckingDomainCreditsProgressDialog.isShowing() instead a local variable in onCreate method. Wdyt</technical_language>

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(WordPress.SITE, mSite); outState.putString(KEY_PLUGIN_SLUG, mSlug); outState.putBoolean(KEY_IS_CONFIGURING_PLUGIN, mIsConfiguringPlugin); outState.putBoolean(KEY_IS_INSTALLING_PLUGIN, mIsInstallingPlugin); outState.putBoolean(KEY_IS_UPDATING_PLUGIN, mIsUpdatingPlugin); outState.putBoolean(KEY_IS_REMOVING_PLUGIN, mIsRemovingPlugin); outState.putBoolean(KEY_IS_ACTIVE, mIsActive); outState.putBoolean(KEY_IS_AUTO_UPDATE_ENABLED, mIsAutoUpdateEnabled); outState.putBoolean(KEY_IS_SHOWING_REMOVE_PLUGIN_CONFIRMATION_DIALOG, mIsShowingRemovePluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_INSTALL_FIRST_PLUGIN_CONFIRMATION_DIALOG, mIsShowingInstallFirstPluginConfirmationDialog); outState.putBoolean(KEY_IS_SHOWING_AUTOMATED_TRANSFER_PROGRESS, mIsShowingAutomatedTransferProgress); outState.putBoolean(KEY_IS_SHOWING_DOMAIN_CREDIT_CHECK_PROGRESS, mCheckingDomainCreditsProgressDialog != null && mCheckingDomainCreditsProgressDialog.isShowing()); }
Source:
<code>public RelRoot plan(String query) { try { Planner planner = getPlanner(); SqlNode sql = planner.parse(query); SqlNode validatedSql = planner.validate(sql); RelRoot relRoot = planner.rel(validatedSql); LOG.info("query plan without optimization:\n" <START> + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); <END> if (!isQueryPlanOptimizerEnabled) { return relRoot; } return optimize(relRoot); } catch (Exception e) { String errorMsg = SamzaSqlValidator.formatErrorString(query, e); LOG.error(errorMsg, e); throw new SamzaException(errorMsg, e); } }</code><technical_language>turn optimization ? if is optimization turned</technical_language>

Target:
public RelRoot plan(String query) { try (Planner planner = getPlanner()) { SqlNode sql = planner.parse(query); SqlNode validatedSql = planner.validate(sql); RelRoot relRoot = planner.rel(validatedSql); LOG.info( "query plan without optimization:\n" + RelOptUtil.toString(relRoot.rel, SqlExplainLevel.EXPPLAN_ATTRIBUTES)); if (!isQueryPlanOptimizerEnabled) { LOG.info("Skipping query optimization as it is disabled."); return relRoot; } return optimize(planner, relRoot); } catch (Exception e) { String errorMsg = SamzaSqlValidator.formatErrorString(query, e); LOG.error(errorMsg, e); throw new SamzaException(errorMsg, e); } }
Source:
<code>public void writeLac(final BookieSocketAddress addr, final long ledgerId, final byte[] masterKey, final long lac, final ByteBufList toSend, final WriteLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.writeLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } toSend.retain(); client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.writeLacComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.writeLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.writeLac(ledgerId, masterKey, lac, toSend, cb, ctx); } toSend.release(); <START> }, ledgerId, conf.getUseV2WireProtocol()); <END> }</code><technical_language>I conf.getUseV2WireProtocol(). true /* forceUseV3 *, right</technical_language>

Target:
public void writeLac(final BookieSocketAddress addr, final long ledgerId, final byte[] masterKey, final long lac, final ByteBufList toSend, final WriteLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.writeLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } toSend.retain(); client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, safeRun(() -> { cb.writeLacComplete(rc, ledgerId, addr, ctx); })); } catch (RejectedExecutionException re) { cb.writeLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.writeLac(ledgerId, masterKey, lac, toSend, cb, ctx); } toSend.release(); }, ledgerId, useV3Enforced); }
Source:
<code>public static <M, K> Window<M, K, Collection<M>> keyedTumblingWindow(Function<M, K> keyFn, Duration interval) { BiFunction<M, Collection<M>, Collection<M>> aggregator = (m, c) -> { if (c == null) { <START> return new ArrayList<>(Arrays.asList(m)); <END> } c.add(m); return c; }; return keyedTumblingWindow(keyFn, interval, aggregator); }</code><technical_language>Pedantic: changing this c = new ArrayList<M>(); returning save object creation. Pedanticer: creating array in outer scope allow drop branch invocation of aggregator</technical_language>

Target:
public static <M, K> Window<M, K, Collection<M>> keyedTumblingWindow(Function<M, K> keyFn, Duration interval) { FoldLeftFunction<M, Collection<M>> aggregator = createAggregator(); Supplier<Collection<M>> initialValue = () -> new ArrayList<>(); return keyedTumblingWindow(keyFn, interval, initialValue, aggregator); }
Source:
<code>public void canDeserializeAdminConfig() throws IOException { PrivilegesConfiguration configuration = deserialize(getConfigFile(ADMIN_PRIVILEGES_CONFIG)); assertThat(configuration).isInstanceOf(AdminPrivilegesConfiguration.class); <START> assertThat(configuration.id()).isEqualTo(ADMIN_ID); <END> assertThat(configuration.privileges()).isEqualTo(Privileges.ADMIN); }</code><technical_language>construct AdminPrivilegesConfiguration compare, instead of field field</technical_language>

Target:
public void canDeserializeAdminConfig() throws IOException { PrivilegesConfiguration deserializedConfiguration = deserialize(getConfigFile(ADMIN_PRIVILEGES_CONFIG)); AdminPrivilegesConfiguration expectedConfiguration = ImmutableAdminPrivilegesConfiguration.builder() .clientId(ADMIN_ID) .build(); assertThat(deserializedConfiguration).isEqualTo(expectedConfiguration); }
Source:
<code>public Pair<Boolean, AuditLogType> disconnectHostFromStoragePoolServersCommandCompleted(HostStoragePoolParametersBase parameters) { if (FeatureSupported.cinderProviderSupported(parameters.getStoragePool().getCompatibilityVersion())) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(parameters.getVds().getId(), Collections.<LibvirtSecret>emptyList(), true)); if (!returnValue.getSucceeded()) { <START> log.error("Failed to register libvirt secret on vds {}.", parameters.getVds().getName()); <END> return new Pair<Boolean, AuditLogType>(false, AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET_ON_VDS); } } return new Pair<Boolean, AuditLogType>(true, null); }</code><technical_language>Consider switch register unregister</technical_language>

Target:
public Pair<Boolean, AuditLogType> disconnectHostFromStoragePoolServersCommandCompleted(HostStoragePoolParametersBase parameters) { if (FeatureSupported.cinderProviderSupported(parameters.getStoragePool().getCompatibilityVersion())) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(parameters.getVds().getId(), Collections.<LibvirtSecret>emptyList(), true)); if (!returnValue.getSucceeded()) { log.error("Failed to unregister libvirt secret on vds {}.", parameters.getVds().getName()); return new Pair<Boolean, AuditLogType>(false, AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET_ON_VDS); } } return new Pair<Boolean, AuditLogType>(true, null); }
Source:
<code>private void initMetricsInvoker() { metricsInvoker = new Invoker<MetricsService>() { @Override public Class<MetricsService> getInterface() { return MetricsService.class; } @Override public Result invoke(Invocation invocation) throws RpcException { String group = invocation.getArguments()[0].toString(); MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup(group); SortedMap<MetricName, FastCompass> fastCompasses = registry.getFastCompasses(); long timestamp = System.currentTimeMillis(); double rateFactor = TimeUnit.SECONDS.toSeconds(1); double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1); MetricsCollector collector = MetricsCollectorFactory.createNew( CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); for (Map.Entry<MetricName, FastCompass> entry : fastCompasses.entrySet()) { collector.collect(entry.getKey(), entry.getValue(), timestamp); } RpcResult result = new RpcResult(); List res = collector.build(); res.addAll(getThreadPoolMessage()); result.setValue(JSON.toJSONString(res)); return result; } @Override public URL getUrl() { <START> return URL.valueOf(protocolName + "://" + NetUtils.getLocalAddress().getHostName() + ":" + port + "/" + MetricsService.class.getName()); <END> } @Override public boolean isAvailable() { return false; } @Override public void destroy() { } }; }</code><technical_language>NetUtils.getLocalAddress().getHostName() IP address a problem, a unified tool for outward IP, I remember thread discussing topic</technical_language>

Target:
private Invoker<MetricsService> initMetricsInvoker() { Invoker<MetricsService> metricsInvoker = new Invoker<MetricsService>() { @Override public Class<MetricsService> getInterface() { return MetricsService.class; } @Override public Result invoke(Invocation invocation) throws RpcException { String group = invocation.getArguments()[0].toString(); MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup(group); SortedMap<MetricName, FastCompass> fastCompasses = registry.getFastCompasses(); long timestamp = System.currentTimeMillis(); double rateFactor = TimeUnit.SECONDS.toSeconds(1); double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1); MetricsCollector collector = MetricsCollectorFactory.createNew( CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); for (Map.Entry<MetricName, FastCompass> entry : fastCompasses.entrySet()) { collector.collect(entry.getKey(), entry.getValue(), timestamp); } RpcResult result = new RpcResult(); List res = collector.build(); res.addAll(getThreadPoolMessage()); result.setValue(JSON.toJSONString(res)); return result; } @Override public URL getUrl() { return URL.valueOf(protocolName + "://" + NetUtils.getIpByConfig() + ":" + port + "/" + MetricsService.class.getName()); } @Override public boolean isAvailable() { return false; } @Override public void destroy() { } }; return metricsInvoker; }
Source:
<code>public void testPostingsNonExistings() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); <START> assertEquals(null, IndexReaderUtils.getPostingsList(reader, "asxe")); <END> }</code><technical_language>assertNull for consistency</technical_language>

Target:
public void testPostingsNonExistings() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); assertNull(IndexReaderUtils.getPostingsList(reader, "asxe")); }
Source:
<code>public void virtLimitFromFirstVirtLimitEntBatch() { <START> <END> stackedEnts.clear(); Entitlement e1 = createEntFromPool(pool1); e1.setQuantity(4); stackedEnts.add(e1); Entitlement e2 = createEntFromPool(pool4); e2.setQuantity(16); stackedEnts.add(e2); Class<Set<String>> listClass = (Class<Set<String>>) (Class) HashSet.class; ArgumentCaptor<Set<String>> arg = ArgumentCaptor.forClass(listClass); when(entCurMock.findByStackIds(eq(consumer), arg.capture())).thenReturn(stackedEnts); List<PoolUpdate> updates = poolRules.updatePoolsFromStack(consumer, Arrays.asList(stackDerivedPool, stackDerivedPool2), false); Set<String> stackIds = arg.getValue(); assertEquals(2, stackIds.size()); assertTrue(stackIds.contains(STACK)); assertTrue(stackIds.contains(STACK + "3")); for (PoolUpdate update : updates) { assertTrue(update.changed()); assertTrue(update.getQuantityChanged()); } assertEquals((Long) 2L, stackDerivedPool.getQuantity()); assertEquals((Long) 9L, stackDerivedPool2.getQuantity()); }</code><technical_language>Extraneous whitespace</technical_language>

Target:
public void virtLimitFromFirstVirtLimitEntBatch() { stackedEnts.clear(); Entitlement e1 = createEntFromPool(pool1); e1.setQuantity(4); stackedEnts.add(e1); Entitlement e2 = createEntFromPool(pool4); e2.setQuantity(16); stackedEnts.add(e2); Class<Set<String>> listClass = (Class<Set<String>>) (Class) HashSet.class; ArgumentCaptor<Set<String>> arg = ArgumentCaptor.forClass(listClass); when(entCurMock.findByStackIds(eq(consumer), arg.capture())).thenReturn(stackedEnts); List<PoolUpdate> updates = poolRules.updatePoolsFromStack(consumer, Arrays.asList(stackDerivedPool, stackDerivedPool2), false); Set<String> stackIds = arg.getValue(); assertEquals(2, stackIds.size()); assertThat(stackIds, hasItems(STACK, STACK + "3")); for (PoolUpdate update : updates) { assertTrue(update.changed()); assertTrue(update.getQuantityChanged()); } assertEquals((Long) 2L, stackDerivedPool.getQuantity()); assertEquals((Long) 9L, stackDerivedPool2.getQuantity()); }
Source:
<code>private SshClient getClient() { if (sshClient == null) { sshClient = SshClient.setUpDefaultClient(); <START> sshClient.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, idleTimeoutMillis); sshClient.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, readTimeoutMillis); <END> sshClient.setHostConfigEntryResolver(new HostConfigEntryResolver() { @Override public HostConfigEntry resolveEffectiveHost(String host, int port, SocketAddress socketAddress, String username, AttributeRepository attributeRepository) throws IOException { return new HostConfigEntry(host, host, port, username); } }); sshClient.start(); } return sshClient; }</code><technical_language>this putIfAbsent ? If setUpDefaultClient changes provides a idle timeout default, this longer apply apply</technical_language>

Target:
private SshClient getClient() { if (sshClient == null) { sshClient = SshClient.setUpDefaultClient(); sshClient.getProperties().put(FactoryManager.IDLE_TIMEOUT, idleTimeoutMillis); sshClient.getProperties().put(FactoryManager.NIO2_READ_TIMEOUT, readTimeoutMillis); sshClient.setHostConfigEntryResolver(new HostConfigEntryResolver() { @Override public HostConfigEntry resolveEffectiveHost(String host, int port, SocketAddress socketAddress, String username, AttributeRepository attributeRepository) throws IOException { return new HostConfigEntry(host, host, port, username); } }); sshClient.start(); } return sshClient; }
Source:
<code>protected ActionResult execute() { String thisCourseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, thisCourseId); InstructorAttributes thisInstructor = logic.getInstructorForGoogleId(thisCourseId, account.googleId); gateKeeper.verifyAccessible(thisInstructor, logic.getCourse(thisCourseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR); List<InstructorAttributes> copiableInstructors = new ArrayList(); List<CourseAttributes> coursesOfThisInstructor = logic.getCoursesForInstructor(account.googleId); List<InstructorAttributes> existingInstructors = logic.getInstructorsForCourse(thisCourseId); for (CourseAttributes course : coursesOfThisInstructor) { String courseId = course.getId(); if (!courseId.equals(thisCourseId)) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); for (InstructorAttributes instructor : instructors) { if (!instructorInThisCourse(instructor, existingInstructors)) { copiableInstructors.add(instructor); <START> } <END> } } } InstructorCourseInstructorCopyPageData data = new InstructorCourseInstructorCopyPageData(account, sessionToken, copiableInstructors); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, data); }</code><technical_language>Is for innermost for loop: for (InstructorAttributes instructor : instructors) { if (!instructorInThisCourse(instructor, existingInstructors)) { copiableInstructors.add(instructor); } } simplified Java 8 lambda features</technical_language>

Target:
protected ActionResult execute() { String thisCourseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, thisCourseId); InstructorAttributes thisInstructor = logic.getInstructorForGoogleId(thisCourseId, account.googleId); gateKeeper.verifyAccessible(thisInstructor, logic.getCourse(thisCourseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_INSTRUCTOR); List<InstructorAttributes> copiableInstructors = new ArrayList(); List<CourseAttributes> coursesOfThisInstructor = logic.getCoursesForInstructor(account.googleId); List<InstructorAttributes> existingInstructors = logic.getInstructorsForCourse(thisCourseId); for (CourseAttributes course : coursesOfThisInstructor) { String courseId = course.getId(); if (!courseId.equals(thisCourseId)) { List<InstructorAttributes> instructors = logic.getInstructorsForCourse(courseId); instructors.forEach(instructor -> { if (!instructorInThisCourse(instructor, existingInstructors)) { copiableInstructors.add(instructor); } }); } } InstructorCourseInstructorCopyPageData data = new InstructorCourseInstructorCopyPageData(account, sessionToken, copiableInstructors); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, data); }
Source:
<code>protected Warning createWarning(Matcher matcher) { <START> String fileName = matcher.group(2); <END> String lineNumber = matcher.group(3); String category = matcher.group(4); String message = matcher.group(5); return createWarning(fileName, getLineNumber(lineNumber), category, message); }</code><technical_language>sense give errors a priority HIGH</technical_language>

Target:
protected Warning createWarning(Matcher matcher) { Priority p = matcher.group(1).equals("[ERROR]") ? Priority.HIGH : Priority.NORMAL; String fileName = matcher.group(2); String lineNumber = matcher.group(3); String category = matcher.group(4); String message = matcher.group(5); return createWarning(fileName, getLineNumber(lineNumber), category, message, p); }
Source:
<code>public ODatabaseSession getSession() { orientDB.createIfNotExists(databaseName, ODatabaseType.PLOCAL); <START> if (session == null) { <END> session = orientDB.open(databaseName, username, password); scriptPath.ifPresent(path -> loadScript(path, session)); } return session; }</code><technical_language>If getSession() is called concurrently, end loading script multiple times? I safer this method synchronized</technical_language>

Target:
public ODatabaseSession getSession() { return getSession(DEFAULT_USERNAME, DEFAULT_PASSWORD); }
Source:
<code>public ProtobufMessages.Timers.Timer serialize(JobContext jobCtx, MarshallerWriteContext outputCtx) { ExpireJobContext ejobCtx = ( ExpireJobContext ) jobCtx; WorkingMemoryReteExpireAction expireAction = ejobCtx.getExpireAction(); DefaultJobHandle jobHandle = ( DefaultJobHandle ) ejobCtx.getJobHandle(); PointInTimeTrigger trigger = ( PointInTimeTrigger ) jobHandle.getTimerJobInstance().getTrigger(); final ExpireTimer.Builder expireTimerBuilder = ProtobufMessages.Timers.ExpireTimer.newBuilder() .setHandleId( expireAction.getFactHandle().getId() ); if (trigger.hasNextFireTime() != null) { expireTimerBuilder.setNextFireTimestamp(trigger.hasNextFireTime().getTime()); } return ProtobufMessages.Timers.Timer.newBuilder() .setType(ProtobufMessages.Timers.TimerType.EXPIRE) .setExpire(expireTimerBuilder.build()) <START> .build(); <END> }</code><technical_language>This is dual: a trigger a next fire time marshalled all</technical_language>

Target:
public ProtobufMessages.Timers.Timer serialize(JobContext jobCtx, MarshallerWriteContext outputCtx) { ExpireJobContext ejobCtx = (ExpireJobContext) jobCtx; WorkingMemoryReteExpireAction expireAction = ejobCtx.getExpireAction(); DefaultJobHandle jobHandle = (DefaultJobHandle) ejobCtx.getJobHandle(); PointInTimeTrigger trigger = (PointInTimeTrigger) jobHandle.getTimerJobInstance().getTrigger(); Date nextFireTime = trigger.hasNextFireTime(); if (nextFireTime != null) { return ProtobufMessages.Timers.Timer.newBuilder() .setType(ProtobufMessages.Timers.TimerType.EXPIRE) .setExpire(ProtobufMessages.Timers.ExpireTimer.newBuilder() .setHandleId(expireAction.getFactHandle().getId()) .setNextFireTimestamp(nextFireTime.getTime()) .build()) .build(); } else { return null; } }
Source:
<code>private boolean loadNewTask(String command) { try { <START> ZNRecord taskConfig = _manager.getHelixDataAccessor().getBaseDataAccessor() <END> .get("/" + _manager.getClusterName() + "/TASK_DEFINITION", null, 0); File taskJar = new File(taskConfig.getSimpleField("JAR_FILE")); URL taskJarUrl = taskJar.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{taskJarUrl}); for(String taskClass : taskConfig.getListField("TASK_CLASSES")) { classLoader.loadClass(taskClass); } Class cl = classLoader.loadClass(taskConfig.getSimpleField("TASKFACTORY")); _taskFactoryRegistry.put(command, (TaskFactory) cl.newInstance()); } catch (MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.info("Loading new task " + command + " for instance " + _manager.getInstanceName() + " in cluster " + _manager.getClusterName() + " failed."); return false; } return true; }</code><technical_language>If this path exist, throw exception return null? If exception, do need handle exception? If null, need do a check in next line of code prevent NPE</technical_language>

Target:
private void loadNewTask(String command) { if (!_manager.getHelixDataAccessor().getBaseDataAccessor() .exists(TaskConstants.DYNAMICALLY_LOADED_TASK_PATH, 0)) { String errorMessage = "Path for dynamic tasks doesn't exist!"; LOG.error(errorMessage); throw new IllegalStateException(errorMessage); } DynamicTaskConfig taskConfig = new DynamicTaskConfig( _manager.getHelixDataAccessor().getBaseDataAccessor() .get(TaskConstants.DYNAMICALLY_LOADED_TASK_PATH + "/" + command, null, ~AccessOption.THROW_EXCEPTION_IFNOTEXIST)); if (taskConfig.getTaskConfigZNRecord() == null) { String errorMessage = "Failed to read ZNRecord for task " + command + " for instance " + _manager .getInstanceName() + " in cluster " + _manager.getClusterName() + "."; LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage); } JarLoader jarLoader = new LocalJarLoader(); URL taskJarUrl = jarLoader.loadJar(taskConfig.getJarFilePath()); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{taskJarUrl}); for (String taskClass : taskConfig.getTaskClassesFqns()) { loadClass(classLoader, taskClass); } TaskFactory taskFactory; try { taskFactory = (TaskFactory) loadClass(classLoader, taskConfig.getTaskFactoryFqn()).newInstance(); } catch (InstantiationException | IllegalAccessException e) { String errorMessage = "Failed to instantiate TaskFactory class for new task in instance " + _manager .getInstanceName() + " in cluster " + _manager.getClusterName() + "."; LOG.error(errorMessage); throw new IllegalStateException(errorMessage); } _taskFactoryRegistry.put(command, taskFactory); }
Source:
<code>public List<Pool> createPools(Subscription sub) { <START> return createPools(sub, new ArrayList<Pool>()); <END> }</code><technical_language>worth a linkedlist well, I doubt allocating 10 ints difference compared other stuff do</technical_language>

Target:
public List<Pool> createPools(Subscription sub) { return createPools(sub, new LinkedList<Pool>()); }
Source:
<code>protected Comparator getItemsComparator() { return (Comparator<RepositoryCommit>) (RepositoryCommit o1, RepositoryCommit o2) -> { int compare = o1.getRepositoryName().compareToIgnoreCase( o2.getRepositoryName()); if (compare == 0) compare = o1.getRevCommit().compareTo(o2.getRevCommit()); <START> return compare; <END> }; }</code><technical_language>Inconsistent indentation, cast I find clearer original. Please revert this change in this file</technical_language>

Target:
protected Comparator getItemsComparator() { return new Comparator<RepositoryCommit>() { @Override public int compare(RepositoryCommit o1, RepositoryCommit o2) { int compare = o1.getRepositoryName().compareToIgnoreCase( o2.getRepositoryName()); if (compare == 0) compare = o1.getRevCommit().compareTo(o2.getRevCommit()); return compare; } }; }
Source:
<code>public void healtCheckRequestTest() throws ExecutionException, InterruptedException, JSONException, IOException { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/healthCheck", Unpooled.buffer(0)); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); <START> assertEquals("Unexpected no of parts ", 1, responseParts.size()); <END> HttpContent actualLastContent = (HttpContent) responseParts.poll(); assertTrue("Last Http Content expected", actualLastContent instanceof LastHttpContent); assertEquals("GET content does not match original content", "GOOD", RestTestUtils.getContentString(actualLastContent)); }</code><technical_language>Instead of lines 133, 134, 135 discardContent(responseParts, 1). checks for LastHttpContent too. do this line of test</technical_language>

Target:
public void healtCheckRequestTest() throws ExecutionException, InterruptedException, IOException { FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/healthCheck", Unpooled.buffer(0)); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); ByteBuffer content = getContent(response, responseParts); assertEquals("GET content does not match original content", "GOOD", new String(content.array())); }
Source:
<code>protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperation operation = null; operation = new GetRemoteSharesForFileOperation(mPath, false, false); RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client); if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); <START> share.setShareLink(client.getBaseUri() + SHARING_LINK_TOKEN + share.getToken()); <END> Log_OC.d(TAG, "Build Share link= " + share.getShareLink()); updateData(share); } else { operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload, mPassword, mPermissions); result = ((CreateRemoteShareOperation)operation).execute(client); if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); updateData(share); } } } } return result; }</code><technical_language>this done library</technical_language>

Target:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperation operation = null; operation = new GetRemoteSharesForFileOperation(mPath, false, false); RemoteOperationResult result = ((GetRemoteSharesForFileOperation)operation).execute(client); if (!result.isSuccess() || result.getData().size() <= 0) { operation = new CreateRemoteShareOperation(mPath, mShareType, mShareWith, mPublicUpload, mPassword, mPermissions); result = ((CreateRemoteShareOperation)operation).execute(client); } if (result.isSuccess()) { if (result.getData().size() > 0) { OCShare share = (OCShare) result.getData().get(0); updateData(share); } } return result; }
Source:
<code>public void setOpenStackAgentProperties(OpenstackNetworkProviderProperties properties) { _openStackAgentProperties = properties; if (_openStackAgentProperties != null) { _customizationConditions.add(CustomizationCondition.NEUTRON_SETUP); <START> if (OpenstackNetworkPluginType.LINUX_BRIDGE.name().equals(_openStackAgentProperties.getPluginType())) { <END> _customizationConditions.add(CustomizationCondition.NEUTRON_LINUX_BRIDGE_SETUP); } else if (OpenstackNetworkPluginType.OPEN_VSWITCH.name().equals(_openStackAgentProperties.getPluginType())) { _customizationConditions.add(CustomizationCondition.NEUTRON_OPEN_VSWITCH_SETUP); } } }</code><technical_language>simple condition? example ask class? _openStackAgentProperties.isLinuxBridge() _openStackAgentProperties.isOpenVSwitch()</technical_language>

Target:
public void setOpenStackAgentProperties(OpenstackNetworkProviderProperties properties) { _openStackAgentProperties = properties; if (_openStackAgentProperties != null) { _customizationConditions.add(CustomizationCondition.NEUTRON_SETUP); if (_openStackAgentProperties.isLinuxBridge()) { _customizationConditions.add(CustomizationCondition.NEUTRON_LINUX_BRIDGE_SETUP); } else if (_openStackAgentProperties.isOpenVSwitch()) { _customizationConditions.add(CustomizationCondition.NEUTRON_OPEN_VSWITCH_SETUP); } } }
Source:
<code>private static boolean isWeakCipherSuite(final String cipherSuite) { for (final String weakAlgorithm : WEAK_ALGORITHMS) { <START> if (cipherSuite.contains(weakAlgorithm)) { <END> return true; } } return false; }</code><technical_language>@artem-smotrakov this replaced regexp matching</technical_language>

Target:
static boolean isWeakCipherSuite(final String cipherSuite) { for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) { if (pattern.matcher(cipherSuite).matches()) { return true; } } return false; }
Source:
<code>public boolean isArray() { <START> return descriptor.endsWith("[]"); <END> }</code><technical_language>Is this a bug fix</technical_language>

Target:
public boolean isArray() { return isArray; }
Source:
<code>private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; <START> capacity = newCapacity; <END> resizeThreshold = (int) (capacity * MapFillFactor); }</code><technical_language>Please check if is a lazySet (maybe AtomicFieldUpdater similar) write release keys/values in order avoid a full barrier</technical_language>

Target:
private void rehash() { int newCapacity = capacity * 2; long[] newKeys = new long[newCapacity]; V[] newValues = (V[]) new Object[newCapacity]; for (int i = 0; i < keys.length; i++) { long storedKey = keys[i]; V storedValue = values[i]; if (storedValue != EmptyValue && storedValue != DeletedValue) { insertKeyValueNoLock(newKeys, newValues, storedKey, storedValue); } } keys = newKeys; values = newValues; usedBuckets = size; capacityUpdater.lazySet(this, newCapacity); resizeThreshold = (int) (newCapacity * MapFillFactor); }
Source:
<code>public Flux<Aggregation> aggregate(HttpHeaders headers, SearchRequest searchRequest) { <START> return sendRequest(searchRequest, requestCreator.search(), SearchResponse.class, headers) END> .map(SearchResponse::getAggregations) .flatMap(Flux::fromIterable); }</code><technical_language>suggestion Assert.notNull(headers, "headers null"); Assert.notNull(searchRequest, "searchRequest null"); searchRequest.source().size(0); return sendRequest(searchRequest, requestCreator.search(), SearchResponse.class, headers) // check non-nullable parameters need source in response, set zero</technical_language>

Target:
public Flux<Aggregation> aggregate(HttpHeaders headers, SearchRequest searchRequest) { Assert.notNull(headers, "headers must not be null"); Assert.notNull(searchRequest, "searchRequest must not be null"); searchRequest.source().size(0); return sendRequest(searchRequest, requestCreator.search(), SearchResponse.class, headers) .map(SearchResponse::getAggregations) .flatMap(Flux::fromIterable); }
Source:
<code>public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { try { log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor())); pluginWrapper.getPlugin().start(); pluginWrapper.setPluginState(PluginState.STARTED); startedPlugins.add(pluginWrapper); <START> firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState)); <END> } catch (Exception e) { pluginWrapper.setPluginState(PluginState.FAILED); log.error(e.getMessage(), e); } } } }</code><technical_language>I need fire plugin state event with: firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState)); (probably move call of firePluginStateEvent of try/catch block). I feel keep/save problem/exception for late use, I where: - a property failedException in PluginWrapper - a property (Map, ...) in AbstractPluginManager, similar resolvedPlugins, startedPlugins, ... - other variant</technical_language>

Target:
public void startPlugins() { for (PluginWrapper pluginWrapper : resolvedPlugins) { PluginState pluginState = pluginWrapper.getPluginState(); if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) { try { log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor())); pluginWrapper.getPlugin().start(); pluginWrapper.setPluginState(PluginState.STARTED); pluginWrapper.setFailedException(null); startedPlugins.add(pluginWrapper); } catch (Exception e) { pluginWrapper.setPluginState(PluginState.FAILED); pluginWrapper.setFailedException(e); log.error(e.getMessage(), e); } finally { firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState)); } } } }
Source:
<code>public void constructorValidValues() { <START> final List<BinaryData> binaryDataList = Collections.singletonList(DATA_BYTES); <END> AmqpDataBody actual = new AmqpDataBody(binaryDataList); assertEquals(AmqpBodyType.DATA, actual.getBodyType()); List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList()); assertEquals(binaryDataList.size(), dataList.size()); byte[] actualData = dataList.get(0).getData(); assertArrayEquals(CONTENTS_BYTES, actualData); }</code><technical_language>a single item collection. add another current implementation layer support it</technical_language>

Target:
public void constructorValidValues() { final List<BinaryData> expectedDataList = new ArrayList<>(); expectedDataList.add(new BinaryData("some data 1".getBytes())); expectedDataList.add(new BinaryData("some data 2".getBytes())); final AmqpDataBody actual = new AmqpDataBody(expectedDataList); assertEquals(AmqpBodyType.DATA, actual.getBodyType()); final List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList()); assertEquals(expectedDataList.size(), dataList.size()); assertArrayEquals(expectedDataList.toArray(), dataList.toArray()); }
Source:
<code>public void persistContent() { try { String stringContent = getStringContent(); stringContent = stringContent.replaceAll("\n", ""); Matcher topInstructions = orderListPattern.matcher(stringContent); if (topInstructions.find()) { stringContent = stringContent.substring(topInstructions.start()); } else { results.error("OrderList tag no longer exists and instructions cannot be removed"); } Matcher editMatch = editPattern.matcher(stringContent); while (editMatch.find()) { String editedList = stringContent.substring(editMatch.start() + 1, editMatch.end() - 1); String guidList = getGuidList(editedList); stringContent = stringContent.replaceAll(editedList, guidList); editMatch = editPattern.matcher(stringContent); } checkValidXML(stringContent); <START> if (results.isErrors()) { END> throw new OseeCoreException(results.toString()); } else { attributeConflict.setAttributeValue(stringContent); } } catch (OseeCoreException ex) { OseeLog.log(RelationOrderCompareItem.class, OseeLevel.SEVERE_POPUP, ex); } }</code><technical_language>Instead of throwing exception, do XResultDataUi.report(results, "Relation Order Errors");</technical_language>

Target:
public void persistContent() { try { String stringContent = getStringContent(); stringContent = stringContent.replaceAll("\n", ""); Matcher topInstructions = orderListPattern.matcher(stringContent); if (topInstructions.find()) { stringContent = stringContent.substring(topInstructions.start()); } else { results.errorf("OrderList tag no longer exists and instructions cannot be removed"); } Matcher editMatch = editPattern.matcher(stringContent); while (editMatch.find()) { String editedList = stringContent.substring(editMatch.start() + 1, editMatch.end() - 1); String guidList = getGuidList(editedList); stringContent = stringContent.replaceAll(editedList, guidList); editMatch = editPattern.matcher(stringContent); } checkValidXML(stringContent); if (results.isErrors()) { XResultDataUI.report(results, "Relation Order Errors"); } else { attributeConflict.setAttributeValue(stringContent); } } catch (OseeCoreException ex) { OseeLog.log(RelationOrderCompareItem.class, OseeLevel.SEVERE_POPUP, ex); } }
Source:
<code>private TrieNode findTrieNode(String path, boolean findLeafAlongPath) throws IllegalArgumentException { if (path.equals("/") || path.equals("")) { if (findLeafAlongPath && !_rootNode._isLeaf) { throw new IllegalArgumentException("no leaf node found along the path"); } return _rootNode; } if (path.substring(0, 1).equals("/")) { path = path.substring(1); } String[] splitPath = path.split("/", 0); TrieNode curNode = _rootNode; <START> if (findLeafAlongPath && curNode._isLeaf) { return curNode; } <END> Map<String, TrieNode> curChildren = curNode._children; for (String pathSection : splitPath) { curNode = curChildren.get(pathSection); if (curNode == null) { throw new IllegalArgumentException("the provided path is missing from the trie"); } if (findLeafAlongPath && curNode._isLeaf) { return curNode; } curChildren = curNode._children; } if (findLeafAlongPath) { throw new IllegalArgumentException("no leaf node found along the path"); } return curNode; }</code><technical_language>This logic confuse here. If trie: a - leaf b c -leaf d e - leaf for /a/b leaf flag false. return root /a. right? for searching purpose. I is correct return b node. explain is expected scenario</technical_language>

Target:
private TrieNode findTrieNode(String path, boolean findLeafAlongPath) throws NoSuchElementException { if (path.equals(DELIMITER) || path.equals("")) { if (findLeafAlongPath && !_rootNode._isLeaf) { throw new NoSuchElementException("No leaf node found along the path. Path: " + path); } return _rootNode; } String[] splitPath; if (path.substring(0, 1).equals(DELIMITER)) { splitPath = path.substring(1).split(DELIMITER, 0); } else { splitPath = path.split(DELIMITER, 0); } TrieNode curNode = _rootNode; if (findLeafAlongPath && curNode._isLeaf) { return curNode; } Map<String, TrieNode> curChildren = curNode._children; for (String pathSection : splitPath) { curNode = curChildren.get(pathSection); if (curNode == null) { throw new NoSuchElementException( "The provided path is missing from the trie. Path: " + path); } if (findLeafAlongPath && curNode._isLeaf) { return curNode; } curChildren = curNode._children; } if (findLeafAlongPath) { throw new NoSuchElementException("No leaf node found along the path. Path: " + path); } return curNode; }