问:
App crashes when navigating jetpack compose
I have total 2 screens i.e SplashScreen and BottomNavScreen(with bottom navigation).
BottomNavScreen has 2 screens i.e Screen1 and Screen2.

I want to go back to SplashScreen from Screen2 but i was getting this error while navigating to SplashScreen.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.lool, PID: 8610
    java.lang.IllegalStateException: ViewModelStore should be set before setGraph call
        at androidx.navigation.NavController.setViewModelStore(NavController.kt:2164)
        at androidx.navigation.NavHostController.setViewModelStore(NavHostController.kt:101)
        at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:106)
        at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:69)
        at com.example.lool.NavigationKt.BottomNav(navigation.kt:34)
        at com.example.lool.screens.Bottom_nav_screenKt$BottomNavScreen$2.invoke(bottom_nav_screen.kt:31)
        at com.example.lool.screens.Bottom_nav_screenKt$BottomNavScreen$2.invoke(bottom_nav_screen.kt:30)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1$bodyContentPlaceables$1.invoke(Scaffold.kt:316)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1$bodyContentPlaceables$1.invoke(Scaffold.kt:314)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:241)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:241)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.runtime.ComposerKt.invokeComposable(Composer.kt:3330)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2577)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2573)
        at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(SnapshotState.kt:540)
        at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:2566)
        at androidx.compose.runtime.ComposerImpl.composeContent$runtime_release(Composer.kt:2517)
        at androidx.compose.runtime.CompositionImpl.composeContent(Composition.kt:476)
        at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:727)
        at androidx.compose.runtime.ComposerImpl$CompositionContextImpl.composeInitial$runtime_release(Composer.kt:2980)
        at androidx.compose.runtime.CompositionImpl.setContent(Composition.kt:432)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcomposeInto(SubcomposeLayout.kt:259)
        at androidx.compose.ui.layout.SubcomposeLayoutState.access$subcomposeInto(SubcomposeLayout.kt:145)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:234)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:231)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.withNoObservations(SnapshotStateObserver.kt:144)
        at androidx.compose.ui.node.OwnerSnapshotObserver.withNoSnapshotReadObservation$ui_release(OwnerSnapshotObserver.kt:49)
        at androidx.compose.ui.node.LayoutNode.withNoSnapshotReadObservation$ui_release(LayoutNode.kt:1107)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose(SubcomposeLayout.kt:231)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose(SubcomposeLayout.kt:226)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose$ui_release(SubcomposeLayout.kt:215)
        at androidx.compose.ui.layout.SubcomposeLayoutState$Scope.subcompose(SubcomposeLayout.kt:466)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1.invoke(Scaffold.kt:314)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1.invoke(Scaffold.kt:241)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
E/AndroidRuntime:     at androidx.compose.ui.layout.SubcomposeLayoutState$createMeasurePolicy$1$measure$1.placeChildren(SubcomposeLayout.kt:357)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:126)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:125)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer(Placeable.kt:393)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer$default(Placeable.kt:266)
        at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:221)
E/AndroidRuntime:     at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:220)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:126)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:125)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer(Placeable.kt:393)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer$default(Placeable.kt:266)
        at androidx.compose.ui.graphics.BlockGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:164)
        at androidx.compose.ui.graphics.BlockGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:163)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$5.invoke(Box.kt:167)
E/AndroidRuntime:     at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$5.invoke(Box.kt:163)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:1776)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:123)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer-aW-9-wM(Placeable.kt:396)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:151)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.replace(OuterMeasurablePlaceable.kt:161)
        at androidx.compose.ui.node.LayoutNode.replace$ui_release(LayoutNode.kt:811)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.measureAndLayout(MeasureAndLayoutDelegate.kt:215)
        at androidx.compose.ui.platform.AndroidComposeView.measureAndLayout(AndroidComposeView.android.kt:510)
        at androidx.compose.ui.platform.AndroidComposeView.dispatchDraw(AndroidComposeView.android.kt:666)
        at android.view.View.draw(View.java:22707)
        at android.view.View.updateDisplayListIfDirty(View.java:21579)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:534)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:540)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:616)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:4457)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:4177)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3337)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2145)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8724)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1037)
        at android.view.Choreographer.doCallbacks(Choreographer.java:845)
        at android.view.Choreographer.doFrame(Choreographer.java:780)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7813)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
</code>```

This is my MainActivity.kt

```<code>class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LoolTheme {
                // A surface container using the 'background' color from the theme
                StartNav()
            }
        }
    }
}
</code>```

This is my Navigation.kt

```<code>@Composable
fun StartNav() {
    val navController = rememberNavController();
    val bottomNavController = rememberNavController();

    NavHost(navController = navController, startDestination = "splash_screen") {
        composable("splash_screen") {
            SplashScreen(navController)
        }
        composable("bottom_nav_screen") {
            BottomNavScreen(
                navController = navController,
                bottomNavHostController = bottomNavController
            )
        }
    }
}

@Composable
fun BottomNav(bottomNavController: NavHostController, navController: NavHostController) {
    NavHost(navController = bottomNavController, startDestination = "screen_1") {
        composable("screen_1") {
            Screen1()
        }
        composable("screen_2") {
            Screen2(navController)
        }
    }
}
</code>```

This is my SplashScreen.kt

```<code>@Composable
fun SplashScreen(navController: NavController) {
    LaunchedEffect(key1 = true) {
        delay(2000L)
        navController.navigate("bottom_nav_screen")
    }

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text("Splash Screen")
    }
}
</code>```

This is my BottomNavScreen.kt

```<code>var navItems = listOf<NavItem>(
    NavItem(label = "uyguy", route = "screen_1", icon = Icons.Filled.Add),
    NavItem(label = "fvvf", route = "screen_2", icon = Icons.Filled.AddCircle)
)

@Composable
fun BottomNavScreen(
    navController: NavHostController,
    bottomNavHostController: NavHostController,

    ) {
    Scaffold(
        bottomBar = {
            BottomNavBar(items = navItems, navController = bottomNavHostController, onClick = {
                bottomNavHostController.navigate(it.route)
            })
        }
    ) {
        BottomNav(navController = navController, bottomNavController = bottomNavHostController)
    }
}
</code>```

This is my Screen1.kt and Screen2.kt

```<code>@Composable
fun Screen1(){
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,

        ) {
        Text("1st Screen ", fontSize = 64.sp)
    }
}

@Composable
fun Screen2(navController: NavController) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,

        ) {
        Text("2nd Screen Logout ", fontSize = 64.sp, modifier = Modifier.clickable {
            navController.navigate("splash_screen") {

            }
        })
    }
}
</code>```

答:
When you call navigate, by default it adds a new view to the navigation stack. This is not always the expected behavior - your resources will not be freed, and when the user clicks back, he will see the previous screen. I suspect this is not what you expect after logout.

And it's also one of the reasons that leads to your crash - both view from backstack with index 1 and the new view with current index 3 use the same state of the navigation controller.

In such cases, you need to specify some parameter during navigation, such as clearing the navigation stack as follows:

```<code>navController.navigate("splash_screen") {
    popUpTo("splash_screen") {
        inclusive = true
    }
}
</code>```

You can also bring the splash screen out of the stack, for example, when you don't log out, but show the splash screen as some sort of information screen.

Even with this fix, your application still crashes. But the problem seems to be related to the fact that you split the definition of bottomNavHostController with its NavHost, so this NavController is reused when its reuse is not expected.

I'm not sure if this is a bug or an expected behavior. I suggest you report this to see what the maintainers think about it.

The easiest solution is to get rid of the second `NavHost', for example, see about Nested Navigation.

An other solution is to move the bottomNavHostController declaration from StartNav to BottomNavScreen, or just inside composable("bottom_nav_screen") (which is effectively the same thing), so the short fix is as follows:

```<code>composable("bottom_nav_screen") {
    val bottomNavHostController = rememberNavController()
    BottomNavScreen(
        navController = navController,
        bottomNavHostController = bottomNavHostController,
    )
}
</code>```

Body:
I have total 2 screens i.e SplashScreen and BottomNavScreen(with bottom navigation).
BottomNavScreen has 2 screens i.e Screen1 and Screen2.

I want to go back to SplashScreen from Screen2 but i was getting this error while navigating to SplashScreen.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.lool, PID: 8610
    java.lang.IllegalStateException: ViewModelStore should be set before setGraph call
        at androidx.navigation.NavController.setViewModelStore(NavController.kt:2164)
        at androidx.navigation.NavHostController.setViewModelStore(NavHostController.kt:101)
        at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:106)
        at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:69)
        at com.example.lool.NavigationKt.BottomNav(navigation.kt:34)
        at com.example.lool.screens.Bottom_nav_screenKt$BottomNavScreen$2.invoke(bottom_nav_screen.kt:31)
        at com.example.lool.screens.Bottom_nav_screenKt$BottomNavScreen$2.invoke(bottom_nav_screen.kt:30)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1$bodyContentPlaceables$1.invoke(Scaffold.kt:316)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1$bodyContentPlaceables$1.invoke(Scaffold.kt:314)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:241)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:241)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
        at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
        at androidx.compose.runtime.ComposerKt.invokeComposable(Composer.kt:3330)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2577)
        at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:2573)
        at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(SnapshotState.kt:540)
        at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:2566)
        at androidx.compose.runtime.ComposerImpl.composeContent$runtime_release(Composer.kt:2517)
        at androidx.compose.runtime.CompositionImpl.composeContent(Composition.kt:476)
        at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:727)
        at androidx.compose.runtime.ComposerImpl$CompositionContextImpl.composeInitial$runtime_release(Composer.kt:2980)
        at androidx.compose.runtime.CompositionImpl.setContent(Composition.kt:432)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcomposeInto(SubcomposeLayout.kt:259)
        at androidx.compose.ui.layout.SubcomposeLayoutState.access$subcomposeInto(SubcomposeLayout.kt:145)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:234)
        at androidx.compose.ui.layout.SubcomposeLayoutState$subcompose$2.invoke(SubcomposeLayout.kt:231)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.withNoObservations(SnapshotStateObserver.kt:144)
        at androidx.compose.ui.node.OwnerSnapshotObserver.withNoSnapshotReadObservation$ui_release(OwnerSnapshotObserver.kt:49)
        at androidx.compose.ui.node.LayoutNode.withNoSnapshotReadObservation$ui_release(LayoutNode.kt:1107)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose(SubcomposeLayout.kt:231)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose(SubcomposeLayout.kt:226)
        at androidx.compose.ui.layout.SubcomposeLayoutState.subcompose$ui_release(SubcomposeLayout.kt:215)
        at androidx.compose.ui.layout.SubcomposeLayoutState$Scope.subcompose(SubcomposeLayout.kt:466)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1.invoke(Scaffold.kt:314)
        at androidx.compose.material.ScaffoldKt$ScaffoldLayout$1$1$1.invoke(Scaffold.kt:241)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
E/AndroidRuntime:     at androidx.compose.ui.layout.SubcomposeLayoutState$createMeasurePolicy$1$measure$1.placeChildren(SubcomposeLayout.kt:357)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:126)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:125)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer(Placeable.kt:393)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer$default(Placeable.kt:266)
        at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:221)
E/AndroidRuntime:     at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:220)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper$measure$1$1.placeChildren(DelegatingLayoutNodeWrapper.kt:123)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:126)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$2.invoke(Box.kt:125)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:128)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer(Placeable.kt:393)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer$default(Placeable.kt:266)
        at androidx.compose.ui.graphics.BlockGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:164)
        at androidx.compose.ui.graphics.BlockGraphicsLayerModifier$measure$1.invoke(GraphicsLayerModifier.kt:163)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.placeAt-f8xVGno(DelegatingLayoutNodeWrapper.kt:111)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:149)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50(Placeable.kt:370)
        at androidx.compose.ui.layout.Placeable$PlacementScope.place-70tqf50$default(Placeable.kt:203)
        at androidx.compose.foundation.layout.BoxKt.placeInBox(Box.kt:186)
        at androidx.compose.foundation.layout.BoxKt.access$placeInBox(Box.kt:1)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$5.invoke(Box.kt:167)
E/AndroidRuntime:     at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1$measure$5.invoke(Box.kt:163)
        at androidx.compose.ui.layout.MeasureScope$layout$1.placeChildren(MeasureScope.kt:68)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:925)
        at androidx.compose.ui.node.LayoutNode$layoutChildren$1.invoke(LayoutNode.kt:915)
        at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:1776)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:123)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:75)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeLayoutSnapshotReads$ui_release(OwnerSnapshotObserver.kt:56)
        at androidx.compose.ui.node.LayoutNode.layoutChildren$ui_release(LayoutNode.kt:915)
        at androidx.compose.ui.node.LayoutNode.onNodePlaced$ui_release(LayoutNode.kt:901)
        at androidx.compose.ui.node.InnerPlaceable.placeAt-f8xVGno(InnerPlaceable.kt:94)
        at androidx.compose.ui.layout.Placeable.access$placeAt-f8xVGno(Placeable.kt:31)
        at androidx.compose.ui.layout.Placeable$PlacementScope.placeWithLayer-aW-9-wM(Placeable.kt:396)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.placeAt-f8xVGno(OuterMeasurablePlaceable.kt:151)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.replace(OuterMeasurablePlaceable.kt:161)
        at androidx.compose.ui.node.LayoutNode.replace$ui_release(LayoutNode.kt:811)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.measureAndLayout(MeasureAndLayoutDelegate.kt:215)
        at androidx.compose.ui.platform.AndroidComposeView.measureAndLayout(AndroidComposeView.android.kt:510)
        at androidx.compose.ui.platform.AndroidComposeView.dispatchDraw(AndroidComposeView.android.kt:666)
        at android.view.View.draw(View.java:22707)
        at android.view.View.updateDisplayListIfDirty(View.java:21579)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4485)
        at android.view.View.updateDisplayListIfDirty(View.java:21535)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:534)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:540)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:616)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:4457)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:4177)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3337)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2145)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8724)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1037)
        at android.view.Choreographer.doCallbacks(Choreographer.java:845)
        at android.view.Choreographer.doFrame(Choreographer.java:780)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7813)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

This is my MainActivity.kt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LoolTheme {
                // A surface container using the 'background' color from the theme
                StartNav()
            }
        }
    }
}

This is my Navigation.kt

@Composable
fun StartNav() {
    val navController = rememberNavController();
    val bottomNavController = rememberNavController();

    NavHost(navController = navController, startDestination = "splash_screen") {
        composable("splash_screen") {
            SplashScreen(navController)
        }
        composable("bottom_nav_screen") {
            BottomNavScreen(
                navController = navController,
                bottomNavHostController = bottomNavController
            )
        }
    }
}

@Composable
fun BottomNav(bottomNavController: NavHostController, navController: NavHostController) {
    NavHost(navController = bottomNavController, startDestination = "screen_1") {
        composable("screen_1") {
            Screen1()
        }
        composable("screen_2") {
            Screen2(navController)
        }
    }
}

This is my SplashScreen.kt

@Composable
fun SplashScreen(navController: NavController) {
    LaunchedEffect(key1 = true) {
        delay(2000L)
        navController.navigate("bottom_nav_screen")
    }

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text("Splash Screen")
    }
}

This is my BottomNavScreen.kt

var navItems = listOf<NavItem>(
    NavItem(label = "uyguy", route = "screen_1", icon = Icons.Filled.Add),
    NavItem(label = "fvvf", route = "screen_2", icon = Icons.Filled.AddCircle)
)

@Composable
fun BottomNavScreen(
    navController: NavHostController,
    bottomNavHostController: NavHostController,

    ) {
    Scaffold(
        bottomBar = {
            BottomNavBar(items = navItems, navController = bottomNavHostController, onClick = {
                bottomNavHostController.navigate(it.route)
            })
        }
    ) {
        BottomNav(navController = navController, bottomNavController = bottomNavHostController)
    }
}

This is my Screen1.kt and Screen2.kt

@Composable
fun Screen1(){
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,

        ) {
        Text("1st Screen ", fontSize = 64.sp)
    }
}

@Composable
fun Screen2(navController: NavController) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,

        ) {
        Text("2nd Screen Logout ", fontSize = 64.sp, modifier = Modifier.clickable {
            navController.navigate("splash_screen") {

            }
        })
    }
}

Body:
When you call navigate, by default it adds a new view to the navigation stack. This is not always the expected behavior - your resources will not be freed, and when the user clicks back, he will see the previous screen. I suspect this is not what you expect after logout.

And it's also one of the reasons that leads to your crash - both view from backstack with index 1 and the new view with current index 3 use the same state of the navigation controller.

In such cases, you need to specify some parameter during navigation, such as clearing the navigation stack as follows:

navController.navigate("splash_screen") {
    popUpTo("splash_screen") {
        inclusive = true
    }
}

You can also bring the splash screen out of the stack, for example, when you don't log out, but show the splash screen as some sort of information screen.

Even with this fix, your application still crashes. But the problem seems to be related to the fact that you split the definition of bottomNavHostController with its NavHost, so this NavController is reused when its reuse is not expected.

I'm not sure if this is a bug or an expected behavior. I suggest you report this to see what the maintainers think about it.

The easiest solution is to get rid of the second `NavHost', for example, see about Nested Navigation.

An other solution is to move the bottomNavHostController declaration from StartNav to BottomNavScreen, or just inside composable("bottom_nav_screen") (which is effectively the same thing), so the short fix is as follows:

composable("bottom_nav_screen") {
    val bottomNavHostController = rememberNavController()
    BottomNavScreen(
        navController = navController,
        bottomNavHostController = bottomNavHostController,
    )
}


来源: stackexchange

问:
Azure private link to AKS with private endpoint to another AKS cluster
I have a situation where my AKS cluster is already in place, two AKS clusters are there & they are internally available within their security zones only. I don't want to go via internet to access the internal resources within the cluster from another cluster.

I was exploring private link service & endpoint, any suggestions?

Both clusters are in different VNets.

答:
I have achieved this by creating private link service on load balancer where my internal ingress (private subnet) is connected in destination cluster. This will require resource ID & load balancer details.

Then created a private endpoint to the private link service in my source cluster that will require subnetId, Resource Group.

The IP created via private link endpoint can be used to communicate to internal LB & also created a DNS entry for it to be used as host in ingress object.

ContentLicense: CC BY-SA 4.0


问:
Controller get wrong namespace name for multipe operators instances in different namespaces
I developed a k8s Operator, after I deploy the first Operator in first namespace, it works well. Then I deploy the 2nd Operator in second namespace, I saw the 2nd controller to get the request that's namespace still is the first name, but the expected namespace should be second.

Please see the following code, when I play with second operator in the second namespace, request's namespace still is the first namespace.

```<code>func (r *AnexampleReconciler) Reconcile(request ctrl.Request) (ctrl.Result, error) {

    log := r.Log.WithValues("Anexample", request.NamespacedName)

    instance := &v1alpha1.Anexample{}
    err := r.Get(context.TODO(), request.NamespacedName, instance)
    if err != nil {
        if errors.IsNotFound(err) {
            log.Info("Anexample resource not found. Ignoring since object must be deleted.")
            return reconcile.Result{}, nil
        }

        log.Error(err, "Failed to get Anexample.")
        return reconcile.Result{}, err
    }
</code>```

I suspect it might be related to election, but I don't understand them.

```<code>    mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
        Scheme:             scheme,
        MetricsBindAddress: metricsAddr,
        Port:               9443,
        LeaderElection:     enableLeaderElection,
        LeaderElectionID:   "2eeda3e4.com.aaa.bbb.ccc",
    })
    if err != nil {
        setupLog.Error(err, "unable to start manager")
        os.Exit(1)
    }
</code>```

what happen in Controller? How to fix it?

答:
request.Namespaced depends on the namespace of the custom resource which you are deploying.

Operators are deployed in namespaces, but can still be configured to listen to custom resources in all namespaces.
This should not be related to the election but with the way you setup your manager.
You didn't specify a namespace in the ctrl.Options for the manager, so it will listen to CR changes in all namespaces.
If you want your operator to only listen to one single namespace, pass the namespace to to manager.

```<code>mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
        Scheme:             scheme,
        MetricsBindAddress: metricsAddr,
        Port:               9443,
        LeaderElection:     enableLeaderElection,
        LeaderElectionID:   "2eeda3e4.com.aaa.bbb.ccc",
        Namesace:           "<namespace-of-operator-two>",
    })
    if err != nil {
        setupLog.Error(err, "unable to start manager")
        os.Exit(1)
    }
</code>```

See also here: https://developers.redhat.com/blog/2020/06/26/migrating-a-namespace-scoped-operator-to-a-cluster-scoped-operator#migration_guide__namespace_scoped_to_cluster_scoped

Body:
I developed a k8s Operator, after I deploy the first Operator in first namespace, it works well. Then I deploy the 2nd Operator in second namespace, I saw the 2nd controller to get the request that's namespace still is the first name, but the expected namespace should be second.

Please see the following code, when I play with second operator in the second namespace, request's namespace still is the first namespace.

func (r *AnexampleReconciler) Reconcile(request ctrl.Request) (ctrl.Result, error) {

    log := r.Log.WithValues("Anexample", request.NamespacedName)

    instance := &v1alpha1.Anexample{}
    err := r.Get(context.TODO(), request.NamespacedName, instance)
    if err != nil {
        if errors.IsNotFound(err) {
            log.Info("Anexample resource not found. Ignoring since object must be deleted.")
            return reconcile.Result{}, nil
        }

        log.Error(err, "Failed to get Anexample.")
        return reconcile.Result{}, err
    }

I suspect it might be related to election, but I don't understand them.

    mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
        Scheme:             scheme,
        MetricsBindAddress: metricsAddr,
        Port:               9443,
        LeaderElection:     enableLeaderElection,
        LeaderElectionID:   "2eeda3e4.com.aaa.bbb.ccc",
    })
    if err != nil {
        setupLog.Error(err, "unable to start manager")
        os.Exit(1)
    }

what happen in Controller? How to fix it?

Body:
request.Namespaced depends on the namespace of the custom resource which you are deploying.

Operators are deployed in namespaces, but can still be configured to listen to custom resources in all namespaces.
This should not be related to the election but with the way you setup your manager.
You didn't specify a namespace in the ctrl.Options for the manager, so it will listen to CR changes in all namespaces.
If you want your operator to only listen to one single namespace, pass the namespace to to manager.

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
        Scheme:             scheme,
        MetricsBindAddress: metricsAddr,
        Port:               9443,
        LeaderElection:     enableLeaderElection,
        LeaderElectionID:   "2eeda3e4.com.aaa.bbb.ccc",
        Namesace:           "<namespace-of-operator-two>",
    })
    if err != nil {
        setupLog.Error(err, "unable to start manager")
        os.Exit(1)
    }

See also here: https://developers.redhat.com/blog/2020/06/26/migrating-a-namespace-scoped-operator-to-a-cluster-scoped-operator#migration_guide__namespace_scoped_to_cluster_scoped


问:
Trouble with arrays in Javascript
I need an array to be created with a PHP loop.

It will look like:

```<code>[ utcdate1:[ series1:[value], series2:[value], series3:[value], utcdate2:[ series1:[value], series2:[value], series3:[value], etc..... ]
</code>```

Here is my code:

```<code>totals = { <?php
    for ($i=0; $i < count($date); $i++) {
        echo "Date.UTC(".
             $year[$i].",".
             $month[$i].",".
             $day[$i].
             "):[ Movies:[".$nomovies[$i].
             "], Shows:[".$noshows[$i].
             "], Music:[".$nomusic[$i].
             "] ]";
        if ($i < (count($date)-1)) {
            echo ",";
        }
    } ?> };
</code>```

Why doesn't this code work?

答:
JavaScript does not support associative arrays (hashes), so you can't convert this to an array. Also you're very confused, you are not trying to make a JavaScript array, it's obvious you are trying to make a JSON object.

You can do it like this:

This is the first approach:

```<code>totals = {
    <?php
        for ( $i = 0; $i < count($date); $i++ )
        {
            $tempDate = new DateTime("{$year[$i]}-{$month[$i]}-{$day[$i]}");
            echo $tempDate->getTimestamp() . ": {"
                . "Movies: [{$nomovies[$i]}],"
                . "Shows: [{$noshows[$i]}],"
                . "Music: [{$nomusic[$i]}],"
            // Add trailing comma, until last element in array is reeached.
            if ( $i < count($date)-1 )
            {
                echo ",";
            }
        }
        // Close the object.
        echo . "}";
    ?>
};
</code>```

Here is a second:

```<code><?php
    // Init an empty array.
    $someArray = array();
    // Fill the array up with the correct structure and all.
    for ( $i = 0; $i < count($date); $i++ )
    {
        // Init a date object with the desired time.
        $tempDate = new DateTime("{$year[$i]}-{$month[$i]}-{$day[$i]}");
        // Convert the time to seconds and use as a hash in the array.
        $someArray[ $tempDate->getTimestamp() ] = array(
            "Movies" => array( $nomovies[$i] ),
            "Shows" => array( $noshows[$i] ),
            "Music" => array( $nomusic[$i] ),
        );
    }
    // Encode that bad boy into a JSON object.
    echo "totals = " . json_encode( $someArray ) . ";";

?>
</code>```

I updated my answer, I think this is what you really want. This way the date gets converted to seconds since the epoch date, and will be safe to use as a property/key in a JSON object.

ContentLicense: CC BY-SA 3.0

Title: Trouble with arrays in Javascript

Body:
I need an array to be created with a PHP loop.

It will look like:

[ utcdate1:[ series1:[value], series2:[value], series3:[value], utcdate2:[ series1:[value], series2:[value], series3:[value], etc..... ]

Here is my code:

totals = { <?php
    for ($i=0; $i < count($date); $i++) {
        echo "Date.UTC(".
             $year[$i].",".
             $month[$i].",".
             $day[$i].
             "):[ Movies:[".$nomovies[$i].
             "], Shows:[".$noshows[$i].
             "], Music:[".$nomusic[$i].
             "] ]";
        if ($i < (count($date)-1)) {
            echo ",";
        }
    } ?> };

Why doesn't this code work?

Body:
JavaScript does not support associative arrays (hashes), so you can't convert this to an array. Also you're very confused, you are not trying to make a JavaScript array, it's obvious you are trying to make a JSON object.

You can do it like this:

This is the first approach:

totals = {
    <?php
        for ( $i = 0; $i < count($date); $i++ )
        {
            $tempDate = new DateTime("{$year[$i]}-{$month[$i]}-{$day[$i]}");
            echo $tempDate->getTimestamp() . ": {"
                . "Movies: [{$nomovies[$i]}],"
                . "Shows: [{$noshows[$i]}],"
                . "Music: [{$nomusic[$i]}],"
            // Add trailing comma, until last element in array is reeached.
            if ( $i < count($date)-1 )
            {
                echo ",";
            }
        }
        // Close the object.
        echo . "}";
    ?>
};

Here is a second:

<?php
    // Init an empty array.
    $someArray = array();
    // Fill the array up with the correct structure and all.
    for ( $i = 0; $i < count($date); $i++ )
    {
        // Init a date object with the desired time.
        $tempDate = new DateTime("{$year[$i]}-{$month[$i]}-{$day[$i]}");
        // Convert the time to seconds and use as a hash in the array.
        $someArray[ $tempDate->getTimestamp() ] = array(
            "Movies" => array( $nomovies[$i] ),
            "Shows" => array( $noshows[$i] ),
            "Music" => array( $nomusic[$i] ),
        );
    }
    // Encode that bad boy into a JSON object.
    echo "totals = " . json_encode( $someArray ) . ";";

?>

I updated my answer, I think this is what you really want. This way the date gets converted to seconds since the epoch date, and will be safe to use as a property/key in a JSON object.


问:
Python: Determine which package contains the currently running code (in order to retrieve package resources)?
Learning about Python package resources. I understand I can include arbitrary files and directories in my package using include_package_data.

Let's say I write a package that contains a single class:

```<code>(mypackage / __init__.py)

from importlib_resources import files

class myClass:

    def getResource(self, filename):
        return files('mypackage').joinpath(filename).read_text()
</code>```

Now I package up this code into an installable Python package using a setup.py file, and install it.

Now, another developer comes along and wants to subclass my class. That user is also going to package their code in a package and release it, with a dependency being my package. And they want the getResource function to pull resources from their package, not mine:

```<code>( otherpackage / __init__.py )

from importlib_resources import files
from mypackage import myClass

class myNewClass(myClass):

    def getResource(self, filename):
        return files('otherpackage').joinpath(filename).read_text()
</code>```

This is hardly ideal, since the other developer must supersede the getResource method, copy my code, and just change the package name. (Edit: This could be accomplished with super and passing in the package name, but it's still an extra step and could be argued to violate the DRY principle)

The question is: Is there a way to get the name of the Python package that the currently executing code is part of? (Or perhaps a better approach would be determining which package a class belongs to) That way, my package could simply discover that it's now running inside a subclass of otherpackage, and get the resources from otherpackage appropriately. (I could code a fallback, so that if the user doesn't include a resource in their package, I can retrieve it from a default resource in mypackage).

In this example, I want code running in an instance of myClass to get mypackage, but code running in an instance of myNewClass to get otherpackage, so I can pass this as the parameter to files(). I'd expect that if the code were not running in a package, I could simply get None back, and handle that situation using a fallback utilizing __file__.

Put yet another way, I wish for a function such that if the developer directly instantiates myClass and the function is called in the class's code, it should pull resources from mypackage; if the developer instantiates myNewClass it should use that developer's package. If the developer instantiated myNewClass outside of a package, I should be able to detect that and fallback on locating resources by way of path composition with __file__. I would like this to happen without the other developer ever needing to explicitly provide the name of their package to my code - the DRY principle applies here.

Secondary question: if this second developer sets up their package in dev/link mode (using -e on pip install), will this work while they are developing the package? In other words, can the other developer use the importlib.resources library to access the files in their dev tree from their code transparently?

Naturally, I would document how developers who subclass the API must deal with package resources (e.g. where to put files), so they would simply follow any directory names or other conventions I built into myClass's expectations.

答:
In order to find the module where a certain class was defined you can use inspect.getmodule:

from importlib.resources import read_text
from inspect import getmodule

class myClass:
    def getResource(self, filename):
        return read_text(getmodule(self).__name__, filename)
```
<p>If you want to take into account where a certain class gets instantiated, you'd have to rely on frame inspection, e.g. via <code>inspect.stack</code>:</p>
<pre class="lang-py prettyprint-override"><code>from inspect import stack

class myClass:
    def getResource(self, filename):
        caller_filename = stack()[1].filename
        ...  # do something based on `caller_filename`
        return read_text(getmodule(self).__name__, filename)
</code>```

However, you problem description sounds like namespace packages would be useful (see also PEP 420), where developers can just drop their own stuff into the namespace package. So only your distribution would contain the logic for picking up the various resources.

Body:
Learning about Python package resources. I understand I can include arbitrary files and directories in my package using include_package_data.

Let's say I write a package that contains a single class:

(mypackage / __init__.py)

from importlib_resources import files

class myClass:

    def getResource(self, filename):
        return files('mypackage').joinpath(filename).read_text()

Now I package up this code into an installable Python package using a setup.py file, and install it.

Now, another developer comes along and wants to subclass my class. That user is also going to package their code in a package and release it, with a dependency being my package. And they want the getResource function to pull resources from their package, not mine:

( otherpackage / __init__.py )

from importlib_resources import files
from mypackage import myClass

class myNewClass(myClass):

    def getResource(self, filename):
        return files('otherpackage').joinpath(filename).read_text()

This is hardly ideal, since the other developer must supersede the getResource method, copy my code, and just change the package name. (Edit: This could be accomplished with super and passing in the package name, but it's still an extra step and could be argued to violate the DRY principle)

The question is: Is there a way to get the name of the Python package that the currently executing code is part of? (Or perhaps a better approach would be determining which package a class belongs to) That way, my package could simply discover that it's now running inside a subclass of otherpackage, and get the resources from otherpackage appropriately. (I could code a fallback, so that if the user doesn't include a resource in their package, I can retrieve it from a default resource in mypackage).

In this example, I want code running in an instance of myClass to get mypackage, but code running in an instance of myNewClass to get otherpackage, so I can pass this as the parameter to files(). I'd expect that if the code were not running in a package, I could simply get None back, and handle that situation using a fallback utilizing __file__.

Put yet another way, I wish for a function such that if the developer directly instantiates myClass and the function is called in the class's code, it should pull resources from mypackage; if the developer instantiates myNewClass it should use that developer's package. If the developer instantiated myNewClass outside of a package, I should be able to detect that and fallback on locating resources by way of path composition with __file__. I would like this to happen without the other developer ever needing to explicitly provide the name of their package to my code - the DRY principle applies here.

Secondary question: if this second developer sets up their package in dev/link mode (using -e on pip install), will this work while they are developing the package? In other words, can the other developer use the importlib.resources library to access the files in their dev tree from their code transparently?

Naturally, I would document how developers who subclass the API must deal with package resources (e.g. where to put files), so they would simply follow any directory names or other conventions I built into myClass's expectations.

Body:
In order to find the module where a certain class was defined you can use inspect.getmodule:

from importlib.resources import read_text
from inspect import getmodule

class myClass:
    def getResource(self, filename):
        return read_text(getmodule(self).__name__, filename)

If you want to take into account where a certain class gets instantiated, you'd have to rely on frame inspection, e.g. via inspect.stack:

from inspect import stack

class myClass:
    def getResource(self, filename):
        caller_filename = stack()[1].filename
        ...  # do something based on `caller_filename`
        return read_text(getmodule(self).__name__, filename)

However, you problem description sounds like namespace packages would be useful (see also PEP 420), where developers can just drop their own stuff into the namespace package. So only your distribution would contain the logic for picking up the various resources.


问:
keyword argument clashes with variable
Although this is most likely a newbie question I struggled to find any information online to help me with my problem

My code is meant to scrap onion sites, and despite being able to connect to TOR and the web scraper working fine as a stand-alone, when I tried combining both code blocks I kept getting numerous errors regarding the keyword argument in my code, even attempting to delete it presents me with bugs, I am a bit lost on what I'm supposed to do

```<code>import socket
import socks
import requests
from pywebcopy import save_webpage

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5h://127.0.0.1:9050',
                       'https': 'socks5h://127.0.0.1:9050'}
    return session

session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

kwargs = {'project_name': 'site folder'}

save_webpage(

        # url of the website

session.get(url="http://elfqv3zjfegus3bgg5d7pv62eqght4h6sl6yjjhe7kjpi2s56bzgk2yd.onion"),

    # folder where the copy will be saved

        project_folder=r"C:\Users\admin\Desktop\WebScraping",
        **kwargs
)
</code>```

In this case, I'm presented with the following error:

TypeError: Cannot mix str and non-str arguments

attempting to replace

```<code>project_folder=r"C:\Users\admin\Desktop\WebScraping",
**kwargs
</code>```

with

```<code>kwargs,
project_folder=r"C:\Users\admin\Desktop\WebScraping"
</code>```

presents me with this error:

TypeError: save_webpage() got multiple values for argument

traceback for the first error:

```<code>  File "C:\Users\admin\Desktop\WebScraping\tor.py", line 43, in <module>
    **kwargs

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\api.py", line 58, in save_webpage
    config.setup_config(url, project_folder, project_name, **kwargs)

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\configs.py", line 189, in setup_config
    SESSION.load_rules_from_url(urljoin(project_url, '/robots.txt'))

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 487, in urljoin
    base, url, _coerce_result = _coerce_args(base, url)

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 120, in _coerce_args
    raise TypeError("Cannot mix str and non-str arguments")
</code>```

I'd really appreciate an explanation on what causes such a bug and how to avoid it in the future

答:
SOLVED

adding the following code resolved the issue:

```<code>def getaddrinfo(*args):
    return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]

socket.getaddrinfo = getaddrinfo
</code>```

Title: keyword argument clashes with variable

Body:
Although this is most likely a newbie question I struggled to find any information online to help me with my problem

My code is meant to scrap onion sites, and despite being able to connect to TOR and the web scraper working fine as a stand-alone, when I tried combining both code blocks I kept getting numerous errors regarding the keyword argument in my code, even attempting to delete it presents me with bugs, I am a bit lost on what I'm supposed to do

import socket
import socks
import requests
from pywebcopy import save_webpage

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5h://127.0.0.1:9050',
                       'https': 'socks5h://127.0.0.1:9050'}
    return session

session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

kwargs = {'project_name': 'site folder'}

save_webpage(

        # url of the website

session.get(url="http://elfqv3zjfegus3bgg5d7pv62eqght4h6sl6yjjhe7kjpi2s56bzgk2yd.onion"),

    # folder where the copy will be saved

        project_folder=r"C:\Users\admin\Desktop\WebScraping",
        **kwargs
)

In this case, I'm presented with the following error:

TypeError: Cannot mix str and non-str arguments

attempting to replace

project_folder=r"C:\Users\admin\Desktop\WebScraping",
**kwargs

with

kwargs,
project_folder=r"C:\Users\admin\Desktop\WebScraping"

presents me with this error:

TypeError: save_webpage() got multiple values for argument

traceback for the first error:

  File "C:\Users\admin\Desktop\WebScraping\tor.py", line 43, in <module>
    **kwargs

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\api.py", line 58, in save_webpage
    config.setup_config(url, project_folder, project_name, **kwargs)

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\configs.py", line 189, in setup_config
    SESSION.load_rules_from_url(urljoin(project_url, '/robots.txt'))

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 487, in urljoin
    base, url, _coerce_result = _coerce_args(base, url)

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 120, in _coerce_args
    raise TypeError("Cannot mix str and non-str arguments")

I'd really appreciate an explanation on what causes such a bug and how to avoid it in the future

Body:
SOLVED

adding the following code resolved the issue:

def getaddrinfo(*args):
    return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]

socket.getaddrinfo = getaddrinfo


问:
How can I get treemap datalabels to wrap consistently?
I'm making a Highcharts treemap with some rather long datalabels. Sometimes they wrap, sometimes highcharts truncates them with ellipses (but it really seems like it could wrap them instead). The inconsistency makes it look a bit messy. Is there a way I can force the labels to always wrap?

Here is an example:

Highcharts.chart('container', {

  colorAxis: {
    minColor: '#003A85',
    maxColor: '#F7F8FA',
    visible: false
  },

  series: [{
    type: "treemap",
    layoutAlgorithm: 'strip',
    layoutStartingDirection: 'horizontal',
    dataLabels: {
      align: 'left',
      verticalAlign: 'top',
      x: 5,
      y: 5,
      style: {
        textShadow: 'unset',
        textOutline: 'none',
        fontSize: '14px',
        fontWeight: 'normal',

      }
    },
    data: [{
      name: 'This is quite a long sentence really, oh well never mind',
      value: 4911,
      colorValue: 0
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3701,
      colorValue: 1
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3602,
      colorValue: 2
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3502,
      colorValue: 3
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3114,
      colorValue: 4
    }]
  }],

  plotOptions: {
    treemap: {
      borderWidth: 0,
      dataLabels: {
        borderRadius: 0,
        shadow: {
          enabled: false
        }
      }
    }
  },
  title: {
    text: 'Highcharts Treemap'
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  min-width: 300px;
  max-width: 400px;
  margin: 0 auto;
}</code>```

```

(image) Highcharts treemap with inconsistent label wrapping

答:
More complex way to control text wrapping can be achieved when combined with the option for datalables, useHTML: true and displaying dataLabels.format as a string you can add your styles and customization there.

```<code>  plotOptions: {
    treemap: {
      dataLabels: {
        useHTML: true,
        format: '<p class="truncate"><b>{point.name}</b></a>',
        style: {
          textOverflow: 'allow'
        }
      }
    }
</code>```

Live demo: https://jsfiddle.net/BlackLabel/zkwg2vnq/

Body:
I'm making a Highcharts treemap with some rather long datalabels. Sometimes they wrap, sometimes highcharts truncates them with ellipses (but it really seems like it could wrap them instead). The inconsistency makes it look a bit messy. Is there a way I can force the labels to always wrap?

Here is an example:

Highcharts.chart('container', {

  colorAxis: {
    minColor: '#003A85',
    maxColor: '#F7F8FA',
    visible: false
  },

  series: [{
    type: "treemap",
    layoutAlgorithm: 'strip',
    layoutStartingDirection: 'horizontal',
    dataLabels: {
      align: 'left',
      verticalAlign: 'top',
      x: 5,
      y: 5,
      style: {
        textShadow: 'unset',
        textOutline: 'none',
        fontSize: '14px',
        fontWeight: 'normal',

      }
    },
    data: [{
      name: 'This is quite a long sentence really, oh well never mind',
      value: 4911,
      colorValue: 0
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3701,
      colorValue: 1
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3602,
      colorValue: 2
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3502,
      colorValue: 3
    }, {
      name: 'This is quite a long sentence really, oh well never mind',
      value: 3114,
      colorValue: 4
    }]
  }],

  plotOptions: {
    treemap: {
      borderWidth: 0,
      dataLabels: {
        borderRadius: 0,
        shadow: {
          enabled: false
        }
      }
    }
  },
  title: {
    text: 'Highcharts Treemap'
  }
});

#container {
  min-width: 300px;
  max-width: 400px;
  margin: 0 auto;
}

(image) Highcharts treemap with inconsistent label wrapping

Body:
More complex way to control text wrapping can be achieved when combined with the option for datalables, useHTML: true and displaying dataLabels.format as a string you can add your styles and customization there.

  plotOptions: {
    treemap: {
      dataLabels: {
        useHTML: true,
        format: '<p class="truncate"><b>{point.name}</b></a>',
        style: {
          textOverflow: 'allow'
        }
      }
    }

Live demo: https://jsfiddle.net/BlackLabel/zkwg2vnq/


问:
How to use Flexjson JSONDeserializer?
I have a string:

```<code> [{"product_id":"2","name":'stack"'},{"product_id":"2","name":"overflow"}]"
</code>```

How can I use Flexjson's JSONDeserializer to obtain all product_ids from the above string?

I have a class called productinformation which has fields like product_id and name.

答:
You could use the JSONDeserializer.use() methods to tell it how to deserialize the array and each object in the array, in this case of class ProductInformation . The product_id attribute does not match up with the standard naming that flexjson expects, so your properties on the object will need to have an underscore in them.

```<code>String products= "[{\"product_id\": \"123\",\"name\":\"stack\"},{\"product_id\": \"456\",\"name\":\"overflow\"}]";
List<ProductInformation> productInfoList = new JSONDeserializer<List<ProductInformation> >()
    .use(null, ArrayList.class)
    .use("values",ProductInformation.class)
    .deserialize(products);

for(ProductInformation productInformation : productInfoList){
    System.out.println(productInformation.getProduct_id();
}
</code>```

The section on "Deserialization Without the Training Wheels" in Deserialization section of the docs goes into additional details on the other cases to consider if the type information is not included in the JSON string.

Title: How to use Flexjson JSONDeserializer?

Body:
I have a string:

 [{"product_id":"2","name":'stack"'},{"product_id":"2","name":"overflow"}]"

How can I use Flexjson's JSONDeserializer to obtain all product_ids from the above string?

I have a class called productinformation which has fields like product_id and name.

Body:
You could use the JSONDeserializer.use() methods to tell it how to deserialize the array and each object in the array, in this case of class ProductInformation . The product_id attribute does not match up with the standard naming that flexjson expects, so your properties on the object will need to have an underscore in them.

String products= "[{\"product_id\": \"123\",\"name\":\"stack\"},{\"product_id\": \"456\",\"name\":\"overflow\"}]";
List<ProductInformation> productInfoList = new JSONDeserializer<List<ProductInformation> >()
    .use(null, ArrayList.class)
    .use("values",ProductInformation.class)
    .deserialize(products);

for(ProductInformation productInformation : productInfoList){
    System.out.println(productInformation.getProduct_id();
}

The section on "Deserialization Without the Training Wheels" in Deserialization section of the docs goes into additional details on the other cases to consider if the type information is not included in the JSON string.


问:
Finding the root directory of a multi module Maven reactor project
Is there an easy way to find the root of a multi-module Maven project, like Gradle's rootDir?

Background:

I want to use the maven-dependency-plugin to copy artifacts from all sub-modules of my multi-module project to a directory that is relative to the root directory of the entire project.

That is, my layout looks similar to this, names changed:

```<code>to-deploy/
my-project/
    module-a/
    module-b/
    more-modules-1/
        module-c/
        module-d/
    more-modules-2/
        module-e/
        module-f/
    ...
</code>```

And i want all the artifacts to be copied from the target-directories of their respective modules to my-project/../to-deploy so i end up with

```<code>to-deploy/
    module-a.jar
    module-b.jar
    module-c.jar
    module-d.jar
    module-e.jar
    module-f.jar
my-project/
    ...
</code>```

I could do it with a relative path in each module, like so:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>jar</type>
                                <outputDirectory>../../to-deploy</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

But i'd rather not specify a relative path in the <outputDirectory> element.
I'd prefer something like ${reactor.root.directory}/../to-deploy, but i can't find anything like this.

Also, i'd prefer if there was some way to inherit this maven-dependency-plugin configuration so i don't have to specify it for each module.

I also tried inheriting a custom property from the root pom:

```<code><properties>
    <myproject.root>${basedir}</myproject.root>
</properties>
</code>```

But when i tried to use ${myproject.root} in the module POM's, the ${basedir} would resolve to the basedir of the module.

Also, i found http://labs.consol.de/lang/de/blog/maven/project-root-path-in-a-maven-multi-module-project/ where it's suggested that each developer and presumably the continuous integration server should configure the root directory in a profiles.xml file, but i don't consider it a solution.

So is there an easy way to find the root of a multi-module project?

答:
Except use absolutely root path, in some case, I have another way to solve the problem.

Use maven plugin combine.children feature, refs: maven plugin

I can write my code:

parent pom:

```<code><build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
          <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                  <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                  <includeScope>runtime</includeScope>
                  <outputDirectory combine.children="override">${project.basedir}/to-deploy</outputDirectory>
              </configuration>
          </execution>
      </executions>
    </plugin>
  </plugins>
</build>
</code>```

or write in plugin management, if parent pom doesn't use this plugin.

child pom:

```<code><build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
          <execution>
              <!--same as parent plugin id-->
              <id>copy-dependencies</id>
              <configuration>
                  <outputDirectory combine.children="override">${project.parent.basedir}/to-deploy</outputDirectory>
              </configuration>
          </execution>
      </executions>
    </plugin>
  </plugins>
</build>
</code>```

Similar way
grandchild pom:

```<code><outputDirectory combine.children="override">${project.parent.parent.basedir}/to-deploy</outputDirectory>
</code>```

Body:
Is there an easy way to find the root of a multi-module Maven project, like Gradle's rootDir?

Background:

I want to use the maven-dependency-plugin to copy artifacts from all sub-modules of my multi-module project to a directory that is relative to the root directory of the entire project.

That is, my layout looks similar to this, names changed:

to-deploy/
my-project/
    module-a/
    module-b/
    more-modules-1/
        module-c/
        module-d/
    more-modules-2/
        module-e/
        module-f/
    ...

And i want all the artifacts to be copied from the target-directories of their respective modules to my-project/../to-deploy so i end up with

to-deploy/
    module-a.jar
    module-b.jar
    module-c.jar
    module-d.jar
    module-e.jar
    module-f.jar
my-project/
    ...

I could do it with a relative path in each module, like so:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>jar</type>
                                <outputDirectory>../../to-deploy</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

But i'd rather not specify a relative path in the <outputDirectory> element.
I'd prefer something like ${reactor.root.directory}/../to-deploy, but i can't find anything like this.

Also, i'd prefer if there was some way to inherit this maven-dependency-plugin configuration so i don't have to specify it for each module.

I also tried inheriting a custom property from the root pom:

<properties>
    <myproject.root>${basedir}</myproject.root>
</properties>

But when i tried to use ${myproject.root} in the module POM's, the ${basedir} would resolve to the basedir of the module.

Also, i found http://labs.consol.de/lang/de/blog/maven/project-root-path-in-a-maven-multi-module-project/ where it's suggested that each developer and presumably the continuous integration server should configure the root directory in a profiles.xml file, but i don't consider it a solution.

So is there an easy way to find the root of a multi-module project?

Body:
Except use absolutely root path, in some case, I have another way to solve the problem.

Use maven plugin combine.children feature, refs: maven plugin

I can write my code:

parent pom:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
          <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                  <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                  <includeScope>runtime</includeScope>
                  <outputDirectory combine.children="override">${project.basedir}/to-deploy</outputDirectory>
              </configuration>
          </execution>
      </executions>
    </plugin>
  </plugins>
</build>

or write in plugin management, if parent pom doesn't use this plugin.

child pom:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
          <execution>
              <!--same as parent plugin id-->
              <id>copy-dependencies</id>
              <configuration>
                  <outputDirectory combine.children="override">${project.parent.basedir}/to-deploy</outputDirectory>
              </configuration>
          </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Similar way
grandchild pom:

<outputDirectory combine.children="override">${project.parent.parent.basedir}/to-deploy</outputDirectory>


问:
UIAnimation works normally but stops working after i exit from the view(it enters background) where it is placed and enter again(enters foreground)
i am presently running an animation that makes an image move on screen, it works but i noticed that anytime i run the app for the first time, it works normally but when i exit the view and re-enter the view of the animation, it never runs again. i have tried placing the function that runs the animation in different view controller life cycles but no improvement. code is below.</p>
```<code>  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    moveIt(rootView.eclipseImageView)
    applyGradient()
  }

    func moveIt(_ imageView: UIImageView) {
    let date = Date()
    let calendar = Calendar.current
    hour = calendar.component(.hour, from: date)
    let viewWidth = view.frame.size.width
    let fullDayCycle = 24
    let secondsInAnHour = 3600
    let hoursLeftToMoveSun = fullDayCycle - hour
    let totalSecondsLeftToMoveSun = secondsInAnHour * hoursLeftToMoveSun
    let moveSunBy = (Int(viewWidth) * hoursLeftToMoveSun) / 24
    let moveSunByInCGFloat = CGFloat(moveSunBy)

    UIView.animate(withDuration: 30, delay: 0, options: [.curveLinear, .repeat, .autoreverse], animations: {
      imageView.frame.origin.x =  viewWidth  // moveSunByInCGFloat
      // self.view.backgroundColor =   UIColor(hexaString: "#1f0001")
    }, completion: { [weak self] (_) in
      self?.moveIt(imageView)
    })
  }

    func applyGradient() {
    let gradient = CAGradientLayer()

    gradient.frame = view.bounds
    let hour = 4
    gradient.colors = switchNewColors(hour)
    gradient.transform = CATransform3DMakeRotation(CGFloat.pi, 0, 0, 1)
    gradient.shouldRasterize = true
    view.layer.insertSublayer(gradient, at: 0)  // addSublayer(gradient)
  }
</code>```

答:
Your code animates your imageView from it's original frame to a frame with origin.x at viewWidth. Once you've run that animation, your imageView's frame's origin.x will be equal to viewWidth forever after. Future calls to moveIt() won't change anything because you've already changed the imageView's frame.

Further, your animation's completion closure calls moveIt(_:) again, which also won't change anything.

What do you want new calls to moveIt(_:) to do?

Body:
i am presently running an animation that makes an image move on screen, it works but i noticed that anytime i run the app for the first time, it works normally but when i exit the view and re-enter the view of the animation, it never runs again. i have tried placing the function that runs the animation in different view controller life cycles but no improvement. code is below.

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    moveIt(rootView.eclipseImageView)
    applyGradient()
  }

    func moveIt(_ imageView: UIImageView) {
    let date = Date()
    let calendar = Calendar.current
    hour = calendar.component(.hour, from: date)
    let viewWidth = view.frame.size.width
    let fullDayCycle = 24
    let secondsInAnHour = 3600
    let hoursLeftToMoveSun = fullDayCycle - hour
    let totalSecondsLeftToMoveSun = secondsInAnHour * hoursLeftToMoveSun
    let moveSunBy = (Int(viewWidth) * hoursLeftToMoveSun) / 24
    let moveSunByInCGFloat = CGFloat(moveSunBy)

    UIView.animate(withDuration: 30, delay: 0, options: [.curveLinear, .repeat, .autoreverse], animations: {
      imageView.frame.origin.x =  viewWidth  // moveSunByInCGFloat
      // self.view.backgroundColor =   UIColor(hexaString: "#1f0001")
    }, completion: { [weak self] (_) in
      self?.moveIt(imageView)
    })
  }

    func applyGradient() {
    let gradient = CAGradientLayer()

    gradient.frame = view.bounds
    let hour = 4
    gradient.colors = switchNewColors(hour)
    gradient.transform = CATransform3DMakeRotation(CGFloat.pi, 0, 0, 1)
    gradient.shouldRasterize = true
    view.layer.insertSublayer(gradient, at: 0)  // addSublayer(gradient)
  }


问:
ChromeDriver support issue
I updated my Chrome Browser and installed the latest ChromeDriver version. Somehow I now gut the following erreor:

This version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.81

How can I resolve this issue.

If possible answer as simple as possible because I am new to all of this.

Thanks in advance

答: for chromedriver of 98.0.4758.81, try using 98.0.4758.80. It shall work, and if not, please comment the error/issue. I have chrome 98.0.4758.81 and i just downloaded chromedriver 98.0.4758.80 recently (even myself hoping it will work)</p>

Title: ChromeDriver support issue


问:
Is Main/UI Thread same as System UI Thread in Android?
This question is different than what's being discussed about Main thread and UI thread in Android.

By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...

By mean of Main thread - App's thread which handles UI (forked when process launched)

I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.

My doubt is only for the purpose:
If system can manage a separate thread for it self (to do UI work) than any process/app's-main thread; then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)

Please provide references as well while pointing out answers on this.

答:
By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...

There may well be several threads involved in this.

I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.

More importantly, system UI is handled by separate OS processes, independent of the OS process for an app. As with most modern operating systems, in Android, a thread is owned by a process. Hence, by definition, separate processes have separate threads.

then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)

That was an architectural decision, made close to 15 years ago, back when phone hardware was a lot more limited than it is today. Having a single "magic thread" is a common practice in constrained environments, as it avoids the overhead of constant checking for locks and other approaches to ensure thread-safety of data structures. While Google has done some things to try to improve on this (e.g., added a separate rendering thread), the core architectural limit remains, for backwards compatibility with older apps.

Also note that a fair amount of work is going into Jetpack Compose to try to allow for multi-threaded composables. Basically, since we now have a lot better hardware, Google is handling low-level synchronization for us in Compose, so composables can perhaps run on several threads without issue.


问:
How can I filter a list of OS files and only return the entries that have a specific extension?
I'm using Python 3.9 and I need to write a function that returns only the names of files ending in ".zip" from a list of files?
What is the most effective way to accomplish this using one or two lines of code?

答:
You can make a list of file types you want and iterate like so:

```<code>lstFileNames = ['test.txt', 'test.py']
lstOfTypes = ['txt', 'xlsx']
for fileName in lstFileNames: #for each file
    if fileName.split('.')[1] in lstOfTypes: #if the type is what we want
        pass #do some stuff
</code>```

This code would only run the "do some stuff" line for test.txt

You can also use list comprehensions like so:

```<code>[fn for fn in lstFileNames if fn.split('.')[1] in lstOfTypes]
</code>```

Body:
You can make a list of file types you want and iterate like so:

lstFileNames = ['test.txt', 'test.py']
lstOfTypes = ['txt', 'xlsx']
for fileName in lstFileNames: #for each file
    if fileName.split('.')[1] in lstOfTypes: #if the type is what we want
        pass #do some stuff

This code would only run the "do some stuff" line for test.txt

You can also use list comprehensions like so:

[fn for fn in lstFileNames if fn.split('.')[1] in lstOfTypes]