问:
InstallEventFilter for custom class
I have written small program and would like to installEventFilter for tracking mouse event. Any idea?</p>
```<code>#!/usr/bin/env python
import os
import sys
from PySide2.QtCore import Qt, QSize, QRegExp, QFile, QTextStream
from PySide2.QtGui import QKeySequence, QTextCharFormat, QBrush,QColor, QTextDocument, QTextCursor
from PySide2.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
                               QPlainTextEdit, QGridLayout, QGroupBox,
                               QFormLayout, QHBoxLayout, QLabel, QLineEdit,
                               QMenu, QMenuBar, QPushButton, QMessageBox,
                               QTextEdit, QVBoxLayout, QWidget, QAction)

class BlockWindow():
    def __init__(self, waiver_files, app):
        self.waiver_files = waiver_files
        self.app = app

    def create_widget(self):
        self.create_violation_text()
        self.create_violation_window()
        self.create_text_finder()
        #order matter
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.text_finder)
        main_layout.addWidget(self.create_violation_box)
        return main_layout

    def create_text_finder(self):
        """
        create text finder which wil search string into document
        """
        self.text_finder = QGroupBox()
        layout = QHBoxLayout()
        label = QLabel()
        label.setText("Keyword:")
        self.line_edit = QLineEdit()
        self.line_edit.setText("Enter your search here")
        push_button = QPushButton("Find")
        layout.addWidget(label)
        layout.addWidget(self.line_edit)
        layout.addWidget(push_button)
        self.text_finder.setLayout(layout)

    def create_violation_window(self):
        """
        creating violation window which contain text editor,
        violation type and checkbox
        """
        self.create_violation_box = QGroupBox()
        layout = QGridLayout()
        layout.addWidget(self.plain_textedit, 1, 0, 12, 1)
        layout.setColumnMinimumWidth(0, 10)
        self.create_violation_box.setLayout(layout)

    def create_violation_text(self):
        """
        creating main violation window which contain all violations
        """
        self.plain_textedit =  QPlainTextEdit()
        self.plain_textedit.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.plain_textedit.setStyleSheet(
        """QPlainTextEdit {font-size: 14pt;
                           font-family: Courier;}""")
        self.plain_textedit.viewport().installEventFilter(self)

class MainWindow(QMainWindow):
    def __init__(self, waiver_files, app):
        super().__init__()
        self.width = 1100
        self.height = 700
        self.waiver_files = waiver_files
        self.app = app
        self.set_main_window()

    def set_main_window(self):
        """
        Setting main window position
        """
        self.setWindowTitle("GUI %s" %(os.path.abspath(__file__)))
        self.setFixedSize(QSize(self.width, self.height))
        wid = QDesktopWidget()
        screen_width = wid.screen().frameGeometry().width()
        screen_height = wid.screen().frameGeometry().height()
        self.setGeometry(screen_width/2-self.width/2,
                         screen_height/2-self.height/2,
                         self.width, self.height)

    def create_block(self):
        blk = BlockWindow(self.waiver_files, self.app)
        main_layout = blk.create_widget()
        window = QWidget()
        window.setLayout(main_layout)
        self.setCentralWidget(window)

    def eventfilter(self, obj, event):
        print ("hi")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow(__file__, app)
    window.create_block()
    window.show()
    app.exec_()
</code>```

答:
The BlockWindow class is a simple python object, while installEventFilter() expects a QObject.

Right now your class is also completely useless as it's only used to call functions and return an object, then it gets completely deleted.

What you should do instead is to create a subclass of the widget you're going to add, and by doing it you will also get the event filter functionality (since QWidget inherits from QObject).

Note that:

eventFilter() (with a capitalized "F"!) must always return a bool and it's usually better to always return the result of the base implementation if the event isn't being handled;

mouse movements can only be tracked when a mouse button has been pressed on the target widget, or when using setMouseTracking(True) (which can be set on the scroll area, not the viewport);

class BlockWindow(QWidget):
    def __init__(self, waiver_files, app):
        super().__init__()
        self.waiver_files = waiver_files
        self.app = app

    def create_widget(self):
        self.create_violation_text()
        self.create_violation_window()
        self.create_text_finder()
        main_layout = QVBoxLayout(self) # <- note this, equivalent to
                                        # self.setLayout(main_layout)
        main_layout.addWidget(self.text_finder)
        main_layout.addWidget(self.create_violation_box)

    # ...

    def eventFilter(self, obj, event):
        if event.type() == event.MouseMove:
            print('mouse moving')
        return super().eventFilter(obj, event)

class MainWindow(QMainWindow):
    # ...
    def create_block(self):
        blk = BlockWindow(self.waiver_files, self.app)
        blk.create_widget()
        self.setCentralWidget(blk)
```

Also note that: width() and height() are existing dynamic attributes of all QWidgets, and shall not be overwritten with custom variables; the reference to the application is pointless, as it can (and should) always be get through the static QApplication.instance().

Title: InstallEventFilter for custom class

Body:
I have written small program and would like to installEventFilter for tracking mouse event. Any idea?

#!/usr/bin/env python
import os
import sys
from PySide2.QtCore import Qt, QSize, QRegExp, QFile, QTextStream
from PySide2.QtGui import QKeySequence, QTextCharFormat, QBrush,QColor, QTextDocument, QTextCursor
from PySide2.QtWidgets import (QApplication, QDesktopWidget, QMainWindow,
                               QPlainTextEdit, QGridLayout, QGroupBox,
                               QFormLayout, QHBoxLayout, QLabel, QLineEdit,
                               QMenu, QMenuBar, QPushButton, QMessageBox,
                               QTextEdit, QVBoxLayout, QWidget, QAction)

class BlockWindow():
    def __init__(self, waiver_files, app):
        self.waiver_files = waiver_files
        self.app = app

    def create_widget(self):
        self.create_violation_text()
        self.create_violation_window()
        self.create_text_finder()
        #order matter
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.text_finder)
        main_layout.addWidget(self.create_violation_box)
        return main_layout

    def create_text_finder(self):
        """
        create text finder which wil search string into document
        """
        self.text_finder = QGroupBox()
        layout = QHBoxLayout()
        label = QLabel()
        label.setText("Keyword:")
        self.line_edit = QLineEdit()
        self.line_edit.setText("Enter your search here")
        push_button = QPushButton("Find")
        layout.addWidget(label)
        layout.addWidget(self.line_edit)
        layout.addWidget(push_button)
        self.text_finder.setLayout(layout)

    def create_violation_window(self):
        """
        creating violation window which contain text editor,
        violation type and checkbox
        """
        self.create_violation_box = QGroupBox()
        layout = QGridLayout()
        layout.addWidget(self.plain_textedit, 1, 0, 12, 1)
        layout.setColumnMinimumWidth(0, 10)
        self.create_violation_box.setLayout(layout)

    def create_violation_text(self):
        """
        creating main violation window which contain all violations
        """
        self.plain_textedit =  QPlainTextEdit()
        self.plain_textedit.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.plain_textedit.setStyleSheet(
        """QPlainTextEdit {font-size: 14pt;
                           font-family: Courier;}""")
        self.plain_textedit.viewport().installEventFilter(self)

class MainWindow(QMainWindow):
    def __init__(self, waiver_files, app):
        super().__init__()
        self.width = 1100
        self.height = 700
        self.waiver_files = waiver_files
        self.app = app
        self.set_main_window()

    def set_main_window(self):
        """
        Setting main window position
        """
        self.setWindowTitle("GUI %s" %(os.path.abspath(__file__)))
        self.setFixedSize(QSize(self.width, self.height))
        wid = QDesktopWidget()
        screen_width = wid.screen().frameGeometry().width()
        screen_height = wid.screen().frameGeometry().height()
        self.setGeometry(screen_width/2-self.width/2,
                         screen_height/2-self.height/2,
                         self.width, self.height)

    def create_block(self):
        blk = BlockWindow(self.waiver_files, self.app)
        main_layout = blk.create_widget()
        window = QWidget()
        window.setLayout(main_layout)
        self.setCentralWidget(window)

    def eventfilter(self, obj, event):
        print ("hi")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow(__file__, app)
    window.create_block()
    window.show()
    app.exec_()

Body:
The BlockWindow class is a simple python object, while installEventFilter() expects a QObject.

Right now your class is also completely useless as it's only used to call functions and return an object, then it gets completely deleted.

What you should do instead is to create a subclass of the widget you're going to add, and by doing it you will also get the event filter functionality (since QWidget inherits from QObject).

Note that:

eventFilter() (with a capitalized "F"!) must always return a bool and it's usually better to always return the result of the base implementation if the event isn't being handled;

mouse movements can only be tracked when a mouse button has been pressed on the target widget, or when using setMouseTracking(True) (which can be set on the scroll area, not the viewport);

class BlockWindow(QWidget):
    def __init__(self, waiver_files, app):
        super().__init__()
        self.waiver_files = waiver_files
        self.app = app

    def create_widget(self):
        self.create_violation_text()
        self.create_violation_window()
        self.create_text_finder()
        main_layout = QVBoxLayout(self) # <- note this, equivalent to
                                        # self.setLayout(main_layout)
        main_layout.addWidget(self.text_finder)
        main_layout.addWidget(self.create_violation_box)

    # ...

    def eventFilter(self, obj, event):
        if event.type() == event.MouseMove:
            print('mouse moving')
        return super().eventFilter(obj, event)

class MainWindow(QMainWindow):
    # ...
    def create_block(self):
        blk = BlockWindow(self.waiver_files, self.app)
        blk.create_widget()
        self.setCentralWidget(blk)

Also note that: width() and height() are existing dynamic attributes of all QWidgets, and shall not be overwritten with custom variables; the reference to the application is pointless, as it can (and should) always be get through the static QApplication.instance().


来源: stackexchange

问:
Unable to push docker image to private repository - connect: no route to host
I am trying to push a docker image to a private docker repository from my local windows 10 machine running Docker Desktop with no success.

The command docker push 172.19.161.107:5000/ubuntu outputs the following:

```<code>Using default tag: latest
The push refers to repository [172.19.161.107:5000/ubuntu]
Get "http://172.19.161.107:5000/v2/": dial tcp 172.19.161.107:5000: connect: no route to host
</code>```

When I go to the url http://172.19.161.107:5000/v2/, everything looks fine. From reading other posts, a lot of people are asking what curl says, so here is the output:

```<code>curl -i http://172.19.161.107:5000/v2
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
Location: /v2/
Date: Wed, 02 Feb 2022 02:01:26 GMT
Content-Length: 39
</code>```

The machine is a VM in Hyper-V. When I push the ubuntu image from another VM on the same switch, it gets uploaded to the repository and I am able to see it in the catalog api as show below:

```<code>curl -i http://172.19.161.107:5000/v2/_catalog
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
X-Content-Type-Options: nosniff
Date: Wed, 02 Feb 2022 02:10:58 GMT
Content-Length: 37

{"repositories":["alpine","ubuntu"]}
</code>```

From what I have read, it is very possibly a firewall issue, but I am not sure where to look. In my mind, if I am able to hit the URL and it loads, the port should be open. I have also allowed all traffic by default on my VMs.

What could be stopping me from pushing images from my local machine to my private repository?

Where should I look

答:
I had similar issues which were solved by editing the daemon.json file for my local docker instance as follows

daemon.json

```<code>{
  "bip": "192.168.1.1/24",
  "builder": {
    "gc": {
      "defaultKeepStorage": "20GB",
      "enabled": true
    }
  },
  "experimental": false,
  "features": {
    "buildkit": true
  },
  "insecure-registries": [
    "worker1.intra.net:30082"
  ]
}
</code>```

The daemon.json can be accessed on the windows docker dashboard under

settings / Docker Engine

The entries which were added are "bip" and "insecure-registries".

"insecure-registries" allows http access instead of https,

"bip" sets the Bridge IP address range which was clashing locally with my kubernetes cluster.

In my setup I have a nexus-repository-manager running on a rke2 cluster,

however I'm using local storage so I have a node affinity to single worker node which is not ideal and could be made more resilient.

See also https://github.com/docker/for-win/issues/522

ContentLicense: CC BY-SA 4.0

Body:
I am trying to push a docker image to a private docker repository from my local windows 10 machine running Docker Desktop with no success.

The command docker push 172.19.161.107:5000/ubuntu outputs the following:

Using default tag: latest
The push refers to repository [172.19.161.107:5000/ubuntu]
Get "http://172.19.161.107:5000/v2/": dial tcp 172.19.161.107:5000: connect: no route to host

When I go to the url http://172.19.161.107:5000/v2/, everything looks fine. From reading other posts, a lot of people are asking what curl says, so here is the output:

curl -i http://172.19.161.107:5000/v2
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
Location: /v2/
Date: Wed, 02 Feb 2022 02:01:26 GMT
Content-Length: 39

The machine is a VM in Hyper-V. When I push the ubuntu image from another VM on the same switch, it gets uploaded to the repository and I am able to see it in the catalog api as show below:

curl -i http://172.19.161.107:5000/v2/_catalog
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
X-Content-Type-Options: nosniff
Date: Wed, 02 Feb 2022 02:10:58 GMT
Content-Length: 37

{"repositories":["alpine","ubuntu"]}

From what I have read, it is very possibly a firewall issue, but I am not sure where to look. In my mind, if I am able to hit the URL and it loads, the port should be open. I have also allowed all traffic by default on my VMs.

What could be stopping me from pushing images from my local machine to my private repository?

Where should I look

Body:
I had similar issues which were solved by editing the daemon.json file for my local docker instance as follows

daemon.json

{
  "bip": "192.168.1.1/24",
  "builder": {
    "gc": {
      "defaultKeepStorage": "20GB",
      "enabled": true
    }
  },
  "experimental": false,
  "features": {
    "buildkit": true
  },
  "insecure-registries": [
    "worker1.intra.net:30082"
  ]
}

The daemon.json can be accessed on the windows docker dashboard under

settings / Docker Engine

The entries which were added are "bip" and "insecure-registries".

"insecure-registries" allows http access instead of https,

"bip" sets the Bridge IP address range which was clashing locally with my kubernetes cluster.

In my setup I have a nexus-repository-manager running on a rke2 cluster,

however I'm using local storage so I have a node affinity to single worker node which is not ideal and could be made more resilient.

See also https://github.com/docker/for-win/issues/522


问:
Custom OIDC login page - host on identity server or client application server?
Most IDAM servers (Identity Server 4, Gluu, Cloud services) provide a way to host a login UI on the actually identity server. This login page can be customized so that it can be branded like your website. This works well for security flows so when you reach an authorization end-point you are redirected to your identityserver/login page.

But can you host the login page on the client application instead?

And if so:

Is this advisable?

Is this more/less secure than hosting the login UI on the Identity Server?

Would this break security flow standards like OIDC / Auth 2.0 authorization code flow?

Would this simply call an API to authenticate against? e.g. one that is hosted on the identity
server. Some appear to support this, but this seems a bit old / insecure compared to existing security flows.

Thanks.

答:
Not really: the point of (federated) Single Sign On (SSO) is that one can use a single credential to login across different domains without divulging that credential to every domain/application.

Users use those credentials in one place against one server only to a trusted party aka. the Identity Provider. The Identity Provider then creates a derived token that is consumed by the 3rd-party application because the latter trusts the former to do so.

In case all applications belong to the same domain as the Identity Provider, the argument above no longer holds, but not using SSO would still mean that you'd have to login to each application separately, one by one.


问:
Best Practices for Over/Under-determined Modelica Sources
In standard Modelica fluid flow sources, normally either the flow rate or the pressure is specified. For example, the following boundary setups (P meaning pressure boundary, F meaning flow boundary) would typically surround a pipe component:

P - Pipe - P

F - Pipe - P

However, sometimes it can be convenient/desirable to specify both the flow rate and the pressure on the same side and let the other side be determined:

(P, F) - Pipe - ()

In my experience, this works just fine in Modelica tools if you create these sources and solve them at the system level. The issue is that, since the (P, F) component is locally overdetermined (+1 equation) and the () component is locally underdetermined (-1 equation), those components throw check errors locally since Modelica tools assume you always want locally balanced components. With this in mind, are there any best practices for creating overdetermined/underdetermined components in Modelica for this scenario? At the very least to tell the tool that this is intentional/don't throw check errors?

答:
In Dymola it will work, but for bad models and check of classes it can cause confusing diagnostics. They can be avoided by using:

```<code>annotation (defaultConnectionStructurallyInconsistent=true)
</code>```

(Inside those two models.)

Technically this is a bit extended meaning compared to the standard, https://specification.modelica.org/master/annotations.html#annotations-for-the-graphical-user-interface but it will work.

Body:
In Dymola it will work, but for bad models and check of classes it can cause confusing diagnostics. They can be avoided by using:

annotation (defaultConnectionStructurallyInconsistent=true)

(Inside those two models.)

Technically this is a bit extended meaning compared to the standard, https://specification.modelica.org/master/annotations.html#annotations-for-the-graphical-user-interface but it will work.


问:
ASP.NET / MVC 1.0 Components and Ajax controls - Grid - Calendar - Search?
Hello I'm rather new to developing with MVC and I'm looking to find as many Ajax controls that integrate seamlessly into my new MVC 1.0 ASP.Net application. Specifically, tree controls, searching, outlook calendaresque, and inline updating.</p>

答:
You should see jQuery plugins.

Some of them are commented here.

OwnerDisplayName: Jukeman

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Ekeko


问:
Javascript window.location is getting called again and again IE-8
I am  checking, getting and setting a cookie to trace the last visited page. And to do this I am calling a Javascript onload. Issue is when I execute this js, it refreshes again and again,  very much like a even on mouse movement. But I am not having any event other than onload.

Here is my js:

```<code><script type='text/javascript'>
//<![CDATA[

window.onload = function(event){
    var currentPage = window.location.href;
    var lastVisited = getCookie('udis');
    var sessionId= getCookie('udisSession');
    if(lastVisited === null || lastVisited === undefined){
        setCookie("udis", currentPage, 365);
        lastVisited = getCookie('udis');
    }
    if(sessionId === null || sessionId === undefined){
        setSessionCookie('udisSession');
        if(lastVisited !== currentPage){
            window.location.href = lastVisited;
        }
    }
    setCookie("udis", currentPage, 365);
    updateBreadCrumb();
}

    function getCookie(c_name) {
        var i,x,y,ARRcookies=document.cookie.split(";");
        for (i=0;i<ARRcookies.length;i++){
            x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
            y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
            x=x.replace(/^\s+|\s+$/g,"");
            if (x==c_name) {
                return unescape(y);
            }
        }
    }
    function setSessionCookie(c_name){
    document.cookie=c_name + "=" + 'testSession'+';expires=;path=/';
}

    function setCookie(c_name,value,exdays){
        var exdate=new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value=escape(value) + ((exdays==null) ? "" : ";   expires="+exdate.toUTCString());
        document.cookie=c_name + "=" + c_value;
    }

//]]>
</script>
</code>```

This above code flawlessly in Firefox but in IE-8 it causing page to reload again and again.

答:
This causes your page to be reloaded.

```<code>window.location.href=lastVisited
</code>```

You should probably check with an if statement to see if the current page is not the same and then refresh. Something like window.location.href != lastVisited

Body:
I am  checking, getting and setting a cookie to trace the last visited page. And to do this I am calling a Javascript onload. Issue is when I execute this js, it refreshes again and again,  very much like a even on mouse movement. But I am not having any event other than onload.

Here is my js:

This above code flawlessly in Firefox but in IE-8 it causing page to reload again and again.

Body:
This causes your page to be reloaded.

window.location.href=lastVisited

You should probably check with an if statement to see if the current page is not the same and then refresh. Something like window.location.href != lastVisited

ContentLicense: CC BY-SA 3.0


问:
SyntaxError: Unexpected token ‘ in JSON at position 0
I was trying to claim the staked $Aurora rewards with NEAR-CLI by following this medium article but when I run the command:

NEAR_ENV=mainnet near call aaaaaa20d9e0e2461697782ef11675f668207961.factory.bridge.near storage_deposit ‘’ --accountId bailey12.near --amount 0.0125

The terminal displayed:

```<code>An error occured
SyntaxError: Unexpected token ‘ in JSON at position 0
    at JSON.parse (<anonymous>)
    at scheduleFunctionCall (/usr/local/lib/node_modules/near-cli/commands/call.js:54:84)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.handler (/usr/local/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)
SyntaxError: Unexpected token ‘ in JSON at position 0
    at JSON.parse (<anonymous>)
    at scheduleFunctionCall (/usr/local/lib/node_modules/near-cli/commands/call.js:54:84)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.handler (/usr/local/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)
</code>```

Any idea how to recorrect this? Thank in advance.

答: Use proper single quote ' instead of ’</p>

Body:
I was trying to claim the staked $Aurora rewards with NEAR-CLI by following this medium article but when I run the command:

NEAR_ENV=mainnet near call aaaaaa20d9e0e2461697782ef11675f668207961.factory.bridge.near storage_deposit ‘’ --accountId bailey12.near --amount 0.0125

The terminal displayed:

An error occured
SyntaxError: Unexpected token ‘ in JSON at position 0
    at JSON.parse (<anonymous>)
    at scheduleFunctionCall (/usr/local/lib/node_modules/near-cli/commands/call.js:54:84)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.handler (/usr/local/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)
SyntaxError: Unexpected token ‘ in JSON at position 0
    at JSON.parse (<anonymous>)
    at scheduleFunctionCall (/usr/local/lib/node_modules/near-cli/commands/call.js:54:84)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Object.handler (/usr/local/lib/node_modules/near-cli/utils/exit-on-error.js:52:9)

Any idea how to recorrect this? Thank in advance.

Body: Use proper single quote ' instead of ’


问:
Paragraph input in pygame
im tryna make a python gui application  using pygame but now i realised that its meant for games specifically and not for regular applications... ive done the most part but now im stuck at a point where i wanna take input in a paragraph box from a user but i cant really find a way to do it, is there really a way to do that or do i have to switch to a completely different module and start from scratch

```<code>import pygame

pygame.init()
screen = pygame.display.set_mode((600,600))
app_fps = pygame.time.Clock()
bg = pygame.image.load('Moment-Book/GUI/assets/login_bg.jpg')
font = pygame.font.Font(None,32)
active_color = pygame.Color('dodgerblue2')
inactive_color = pygame.Color('white')
back_button = pygame.image.load('Moment-Book/GUI/assets/back_button.png')

class InputBox():
    def __init__(self,max_len,x,y,width,height,text = ''):
        self.color = inactive_color
        self.len = max_len
        self.rect = pygame.Rect(x,y,width,height)
        self.text = text
        self.text_surf = font.render(text,True,self.color)
        self.active = False

    def event_handler(self,event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        self.color = active_color if self.active else inactive_color

        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE or len(self.text)>self.len:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode

                self.text_surf = font.render(self.text,True,self.color)

    def draw(self,screen):
        screen.blit(self.text_surf, (self.rect.x+5,self.rect.y+5))
        pygame.draw.rect(screen,self.color,self.rect,2,border_radius=2)

    def update(self):
        width = max(200, self.text_surf.get_width()+10)
        self.rect.w = width

back_rect = pygame.Rect(30,30,45,45)

def login():
    inputbox = InputBox(15,180,305,140,32)
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if back_rect.collidepoint(event.pos):
                    running = False
            inputbox.event_handler(event)

        screen.blit(bg,(-167,0))
        screen.blit(back_button,(back_rect.topleft,back_rect.bottomleft))

        inputbox.draw(screen)
        inputbox.update()

        pygame.display.update()
        app_fps.tick(60)
</code>```

this is a sample code of my login page where i take input but its just the username and password, how do i take inputs in paragraphs because when i try this the text goes outside the screen

答:
You must combine the answers to the following questions:

How to create a text input box with pygame?

Rendering text with multiple lines in pygame

Use the code for the text input box form How to create a text input box with pygame? and render the texture using the drawText function from Rendering text with multiple lines in pygame.

Minimal example based on the code from the question:

import pygame

pygame.init()
screen = pygame.display.set_mode((600,600))
app_fps = pygame.time.Clock()
font = pygame.font.SysFont(None,32)
active_color = pygame.Color('dodgerblue2')
inactive_color = pygame.Color('white')

textAlignLeft = 0
textAlignRight = 1
textAlignCenter = 2
textAlignBlock = 3

def drawText(surface, text, color, rect, font, align=textAlignLeft, aa=False, bkg=None):
    lineSpacing = -2
    spaceWidth, fontHeight = font.size(" ")[0], font.size("Tg")[1]

    listOfWords = text.split(" ")
    if bkg:
        imageList = [font.render(word, 1, color, bkg) for word in listOfWords]
        for image in imageList: image.set_colorkey(bkg)
    else:
        imageList = [font.render(word, aa, color) for word in listOfWords]

    maxLen = rect[2]
    lineLenList = [0]
    lineList = [[]]
    for image in imageList:
        width = image.get_width()
        lineLen = lineLenList[-1] + len(lineList[-1]) * spaceWidth + width
        if len(lineList[-1]) == 0 or lineLen <= maxLen:
            lineLenList[-1] += width
            lineList[-1].append(image)
        else:
            lineLenList.append(width)
            lineList.append([image])

    lineBottom = rect[1]
    lastLine = 0
    for lineLen, lineImages in zip(lineLenList, lineList):
        lineLeft = rect[0]
        if align == textAlignRight:
            lineLeft += + rect[2] - lineLen - spaceWidth * (len(lineImages)-1)
        elif align == textAlignCenter:
            lineLeft += (rect[2] - lineLen - spaceWidth * (len(lineImages)-1)) // 2
        elif align == textAlignBlock and len(lineImages) > 1:
            spaceWidth = (rect[2] - lineLen) // (len(lineImages)-1)
        if lineBottom + fontHeight > rect[1] + rect[3]:
            break
        lastLine += 1
        for i, image in enumerate(lineImages):
            x, y = lineLeft + i*spaceWidth, lineBottom
            surface.blit(image, (round(x), y))
            lineLeft += image.get_width()
        lineBottom += fontHeight + lineSpacing

    if lastLine < len(lineList):
        drawWords = sum([len(lineList[i]) for i in range(lastLine)])
        remainingText = ""
        for text in listOfWords[drawWords:]: remainingText += text + " "
        return remainingText
    return ""

class InputBox():
    def __init__(self,max_len,x,y,width,height,text = ''):
        self.color = inactive_color
        self.len = max_len
        self.rect = pygame.Rect(x,y,width,height)
        self.text = text
        self.text_surf = font.render(text,True,self.color)
        self.active = False

    def event_handler(self,event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        self.color = active_color if self.active else inactive_color

        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode

    def draw(self,screen):
        pygame.draw.rect(screen, self.color, self.rect, 1)
        drawTextRect = self.rect.inflate(-5, -5)
        drawText(screen, self.text, self.color, drawTextRect, font, textAlignLeft, True)

    def update(self):
        pass

back_rect = pygame.Rect(30,30,45,45)

inputbox = InputBox(15,180,305,140,96)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        inputbox.event_handler(event)

    screen.fill(0)

    inputbox.update()
    inputbox.draw(screen)
    pygame.display.update()
    app_fps.tick(60)
```

Title: Paragraph input in pygame

Body:
im tryna make a python gui application  using pygame but now i realised that its meant for games specifically and not for regular applications... ive done the most part but now im stuck at a point where i wanna take input in a paragraph box from a user but i cant really find a way to do it, is there really a way to do that or do i have to switch to a completely different module and start from scratch

import pygame

pygame.init()
screen = pygame.display.set_mode((600,600))
app_fps = pygame.time.Clock()
bg = pygame.image.load('Moment-Book/GUI/assets/login_bg.jpg')
font = pygame.font.Font(None,32)
active_color = pygame.Color('dodgerblue2')
inactive_color = pygame.Color('white')
back_button = pygame.image.load('Moment-Book/GUI/assets/back_button.png')

class InputBox():
    def __init__(self,max_len,x,y,width,height,text = ''):
        self.color = inactive_color
        self.len = max_len
        self.rect = pygame.Rect(x,y,width,height)
        self.text = text
        self.text_surf = font.render(text,True,self.color)
        self.active = False

    def event_handler(self,event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.active = not self.active
            else:
                self.active = False
        self.color = active_color if self.active else inactive_color

        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    print(self.text)
                    self.text = ''
                elif event.key == pygame.K_BACKSPACE or len(self.text)>self.len:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode

                self.text_surf = font.render(self.text,True,self.color)

    def draw(self,screen):
        screen.blit(self.text_surf, (self.rect.x+5,self.rect.y+5))
        pygame.draw.rect(screen,self.color,self.rect,2,border_radius=2)

    def update(self):
        width = max(200, self.text_surf.get_width()+10)
        self.rect.w = width

back_rect = pygame.Rect(30,30,45,45)

def login():
    inputbox = InputBox(15,180,305,140,32)
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if back_rect.collidepoint(event.pos):
                    running = False
            inputbox.event_handler(event)

        screen.blit(bg,(-167,0))
        screen.blit(back_button,(back_rect.topleft,back_rect.bottomleft))

        inputbox.draw(screen)
        inputbox.update()

        pygame.display.update()
        app_fps.tick(60)

this is a sample code of my login page where i take input but its just the username and password, how do i take inputs in paragraphs because when i try this the text goes outside the screen


问:
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>```

答:
This is my updated code.
https://github.com/deadman00069/bottom_nav_jetpack_compose

I have made a scaffold above my navHost where i have created bottomNavbar.

This line will determine whether to show bottomNavBar or not

if (currentRoute !in items) return@Scaffold

MainActivity.kt

```<code>class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LoolTheme {
                var navItems = listOf<NavItem>(
                    NavItem(label = "label_1", route = "screen_1", icon = Icons.Filled.Add),
                    NavItem(label = "label_2", route = "screen_2", icon = Icons.Filled.AddCircle)
                )
                val navController = rememberNavController()
                Scaffold(
                    bottomBar = {
                        val items = navItems.map {
                            it.route
                        }
                        val navBackStackEntry by navController.currentBackStackEntryAsState()
                        val currentRoute =
                            navBackStackEntry?.destination?.hierarchy?.first()?.route

                        //to hide bottomNavBar
                        if (currentRoute !in items) return@Scaffold

                        BottomNavBar(
                            items = navItems,
                            navController = navController,
                            onClick = {
                                navController.navigate(it.route)
                            })

                    }
                ) {
                    StartNav(navController)
                }

            }
        }
    }
}
</code>```

navigation.kt

```<code>@Composable
fun StartNav(navController: NavHostController) {

    NavHost(navController = navController, startDestination = "splash_screen") {
        composable("splash_screen") {
            SplashScreen(navController)
        }
        composable("screen_1") {
            Screen1(navController)
        }
        composable("screen_2") {
            Screen2(navController)
        }

        composable("screen_3") {
            Screen3(navController)
        }
    }
}
</code>```

Splashscreen.kt

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

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

Screen1.kt

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

        ) {
        Text("1st Screen ", fontSize = 64.sp)
    }
}
</code>```

Screen2.kt

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

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

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

Screen3.kt

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

        ) {
        Text("3st Screen ", fontSize = 64.sp, modifier = Modifier.clickable {
            navController.navigate("splash_screen") {
                popUpTo("splash_screen") {
                    inclusive = true
                }
            }
        })
    }
}
</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:
This is my updated code.
https://github.com/deadman00069/bottom_nav_jetpack_compose

I have made a scaffold above my navHost where i have created bottomNavbar.

This line will determine whether to show bottomNavBar or not

if (currentRoute !in items) return@Scaffold

MainActivity.kt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LoolTheme {
                var navItems = listOf<NavItem>(
                    NavItem(label = "label_1", route = "screen_1", icon = Icons.Filled.Add),
                    NavItem(label = "label_2", route = "screen_2", icon = Icons.Filled.AddCircle)
                )
                val navController = rememberNavController()
                Scaffold(
                    bottomBar = {
                        val items = navItems.map {
                            it.route
                        }
                        val navBackStackEntry by navController.currentBackStackEntryAsState()
                        val currentRoute =
                            navBackStackEntry?.destination?.hierarchy?.first()?.route

                        //to hide bottomNavBar
                        if (currentRoute !in items) return@Scaffold

                        BottomNavBar(
                            items = navItems,
                            navController = navController,
                            onClick = {
                                navController.navigate(it.route)
                            })

                    }
                ) {
                    StartNav(navController)
                }

            }
        }
    }
}

navigation.kt

@Composable
fun StartNav(navController: NavHostController) {

    NavHost(navController = navController, startDestination = "splash_screen") {
        composable("splash_screen") {
            SplashScreen(navController)
        }
        composable("screen_1") {
            Screen1(navController)
        }
        composable("screen_2") {
            Screen2(navController)
        }

        composable("screen_3") {
            Screen3(navController)
        }
    }
}

Splashscreen.kt

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

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

Screen1.kt

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

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

Screen2.kt

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

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

                }
            })
    }
}

Screen3.kt

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

        ) {
        Text("3st Screen ", fontSize = 64.sp, modifier = Modifier.clickable {
            navController.navigate("splash_screen") {
                popUpTo("splash_screen") {
                    inclusive = true
                }
            }
        })
    }
}


问:
Is it possible to run scatter matmul in pytorch?
Edit: apparently DGL is working on it already: https://github.com/dmlc/dgl/pull/3641

I have several types of embeddings and each one needs its own linear projection. I can solve the problem with a for loop of type:

```<code>emb_out = dict()
for ntype in ntypes:
    emb_out[ntype] = self.lin_layer[ntype](emb[ntype])
</code>```

But ideally, I wanted to do some sort of scatter operation to run it in parallel. Something like:

pytorch_scatter(lin_layers, embeddings, layer_map, reduce='matmul'), where the layer map tells which embedding should go through which layer. If I have 2 types of linear layers and batch_size = 5, then layer_map would be something like [1,0,1,1,0].

Would it be possible to vectorize the for loop in a efficient way, like in pytorch_scatter? Please check below minimal examples.

```<code>import torch
import random
import numpy as np

seed = 42
torch.manual_seed(seed)
random.seed(seed)

def matmul_single_embtype(lin_layers, embeddings, layer_map):
   #run single linear layer over all embeddings, irrespective of type
   output_embeddings = torch.matmul(lin_layers[0], embeddings.T).T
   return output_embeddings

def matmul_for_loop(lin_layers, embeddings, layer_map):
   #let each embedding type have its own projection, looping over emb types
   output_embeddings = dict()
   for emb_type in np.unique(layer_map):
       output_embeddings[emb_type] = torch.matmul(lin_layers[emb_type], embeddings[layer_map == emb_type].T).T
   return output_embeddings

def matmul_scatter(lin_layers, embeddings, layer_map):
   #parallelize the for loop by creating a diagonal matrix of lin layers
   #this is very innefficient, because creates a copy of the layer for each embedding, instead of broadcasting
   mapped_lin_layers = [lin_layers[i] for i in layer_map]
   mapped_lin_layers = torch.block_diag(*mapped_lin_layers) #batch_size*inp_size x batch_size*output_size
   embeddings_stacked = embeddings.view(-1,1) #stack all embeddings to multiply the linear block
   output_embeddings = torch.matmul(mapped_lin_layers, embeddings_stacked).view(embeddings.shape)
   return output_embeddings

"""
GENERATE DATA
lin_layers:
   List of matrices of size n_layer x inp_size x output_size
embeddings:
   Matrix of size batch_size x inp_size
layer_map:
   Vector os size batch_size stating which embedding should go thorugh each layer
"""

emb_size = 32
batch_size = 500
emb_types = 20
layer_map = [random.choice(list(range(emb_types))) for i in range(batch_size)]

lin_layers = [torch.arange(emb_size*emb_size, dtype=torch.float32).view(emb_size,emb_size) for i in range(emb_types)]
embeddings = torch.arange(batch_size*emb_size, dtype=torch.float32).view(batch_size,emb_size)
grouped_emb = {i: embeddings[layer_map==i] for i in np.unique(layer_map)} #separate embeddings by embedding type

#Run experiments
%timeit matmul_scatter(lin_layers, embeddings, layer_map)
%timeit matmul_for_loop(lin_layers, embeddings, layer_map)
%timeit matmul_single_embtype(lin_layers, embeddings, layer_map)

>>>>>133 ms ± 2.47 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>>>>1.64 ms ± 14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>>>>31.4 µs ± 805 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Related stackoverflow question: how to vectorize the scatter-matmul operation

Related issue in pytorch: https://github.com/pytorch/pytorch/issues/31942

答: Just found out that DGL is working on this feature already: https://github.com/dmlc/dgl/pull/3641</p>

Body:
Edit: apparently DGL is working on it already: https://github.com/dmlc/dgl/pull/3641

I have several types of embeddings and each one needs its own linear projection. I can solve the problem with a for loop of type:

emb_out = dict()
for ntype in ntypes:
    emb_out[ntype] = self.lin_layer[ntype](emb[ntype])

But ideally, I wanted to do some sort of scatter operation to run it in parallel. Something like:

pytorch_scatter(lin_layers, embeddings, layer_map, reduce='matmul'), where the layer map tells which embedding should go through which layer. If I have 2 types of linear layers and batch_size = 5, then layer_map would be something like [1,0,1,1,0].

Would it be possible to vectorize the for loop in a efficient way, like in pytorch_scatter? Please check below minimal examples.

import torch
import random
import numpy as np

seed = 42
torch.manual_seed(seed)
random.seed(seed)

def matmul_single_embtype(lin_layers, embeddings, layer_map):
   #run single linear layer over all embeddings, irrespective of type
   output_embeddings = torch.matmul(lin_layers[0], embeddings.T).T
   return output_embeddings

def matmul_for_loop(lin_layers, embeddings, layer_map):
   #let each embedding type have its own projection, looping over emb types
   output_embeddings = dict()
   for emb_type in np.unique(layer_map):
       output_embeddings[emb_type] = torch.matmul(lin_layers[emb_type], embeddings[layer_map == emb_type].T).T
   return output_embeddings

def matmul_scatter(lin_layers, embeddings, layer_map):
   #parallelize the for loop by creating a diagonal matrix of lin layers
   #this is very innefficient, because creates a copy of the layer for each embedding, instead of broadcasting
   mapped_lin_layers = [lin_layers[i] for i in layer_map]
   mapped_lin_layers = torch.block_diag(*mapped_lin_layers) #batch_size*inp_size x batch_size*output_size
   embeddings_stacked = embeddings.view(-1,1) #stack all embeddings to multiply the linear block
   output_embeddings = torch.matmul(mapped_lin_layers, embeddings_stacked).view(embeddings.shape)
   return output_embeddings

"""
GENERATE DATA
lin_layers:
   List of matrices of size n_layer x inp_size x output_size
embeddings:
   Matrix of size batch_size x inp_size
layer_map:
   Vector os size batch_size stating which embedding should go thorugh each layer
"""

emb_size = 32
batch_size = 500
emb_types = 20
layer_map = [random.choice(list(range(emb_types))) for i in range(batch_size)]

lin_layers = [torch.arange(emb_size*emb_size, dtype=torch.float32).view(emb_size,emb_size) for i in range(emb_types)]
embeddings = torch.arange(batch_size*emb_size, dtype=torch.float32).view(batch_size,emb_size)
grouped_emb = {i: embeddings[layer_map==i] for i in np.unique(layer_map)} #separate embeddings by embedding type

#Run experiments
%timeit matmul_scatter(lin_layers, embeddings, layer_map)
%timeit matmul_for_loop(lin_layers, embeddings, layer_map)
%timeit matmul_single_embtype(lin_layers, embeddings, layer_map)

>>>>>133 ms ± 2.47 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>>>>1.64 ms ± 14 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>>>>31.4 µs ± 805 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Related stackoverflow question: how to vectorize the scatter-matmul operation

Related issue in pytorch: https://github.com/pytorch/pytorch/issues/31942


问:
How can I create a column containing the maximum across columns in SQL Server
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA
</code>```

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

```<code>(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
</code>```

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

```<code>SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot
</code>```

答:
I hesitate to offer a solution that masks the bad data design that @Larnu points out, but you could also create a user-defined function that would simplify your query.

```<code>create function udfBiggestOfFive
(
     @arg1 as float = null
    ,@arg2 as float = null
    ,@arg3 as float = null
    ,@arg4 as float = null
    ,@arg5 as float = null
)
returns float
as
begin

    declare @result as float

    set @result = @arg1

    if @result < @arg2 set @result = @arg2
    if @result < @arg3 set @result = @arg3
    if @result < @arg4 set @result = @arg4
    if @result < @arg5 set @result = @arg5

    return @result
end
</code>```

Then your query could be as simple as:

```<code>select
    Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
    dbo.BiggestOfFive(DMD1, DMD0, DMD2, DMD3, DMD4) as LargestDmd,
    dbo.BiggestOfFive(DRC1, DRC0, DRC2, DRC3, DRC4) as LargestDrc,
    CHG0
from Reporter.CHA
</code>```

You would create another function for smallest-of-five, if that's what you're interested in (your question kinda jumps around on that) and you'd also want to use Coalesce judiciously if you're not sure there will always be values instead of nulls. But hopefully you get the point.

But... rethink your data design - normalize it. You'll be glad you did. Even this function is a bit silly in its rigid design.

Body:
I have a table CHA with many columns. There are two sets of 5 columns containing numeric data. I am looking to aggregate this data.

Select for the table below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
              DMD1, DMD0, DMD2, DMD3, DMD4, DRC1, DRC0, DRC2, DRC3, DRC4, CHG0
FROM            Reporter.CHA

I am looking to add some aggregate functions DMD_Min, DMD_Max, etc.

I have the following syntax for the new value, but I keep getting an error.

(SELECT MIN(MIN_DMD) FROM (VALUES (DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD

Can anyone proved a better method for finding the row by row aggregate across columns?

Edit:

The error I am seeing in SQL server is:

Error in FROM clause: near 'Values'

Error in FROM clause: near ')'

Unable to parse query text.

This happens when I try to update the query from the select statement above to add in the DMD_MIN column as below:

SELECT        Project_Num, Project_Title_Full, PTL, LOB, PL,
JobTitle, [Function], MGR, MonthNum, DMD1, DMD0, DMD2, DMD3, DMD4,
DRC1, DRC0, DRC2, DRC3, DRC4, CHG0,
(SELECT MIN(MIN_DMD) FROM (VALUES
(DMD0), (DMD1), (DMD2), (DMD3), (DMD4)) AS value(MIN_DMD)) AS MIN_DMD
FROM            Reporter.Compare_HA_Unpivot

Body:
I hesitate to offer a solution that masks the bad data design that @Larnu points out, but you could also create a user-defined function that would simplify your query.

create function udfBiggestOfFive
(
     @arg1 as float = null
    ,@arg2 as float = null
    ,@arg3 as float = null
    ,@arg4 as float = null
    ,@arg5 as float = null
)
returns float
as
begin

    declare @result as float

    set @result = @arg1

    if @result < @arg2 set @result = @arg2
    if @result < @arg3 set @result = @arg3
    if @result < @arg4 set @result = @arg4
    if @result < @arg5 set @result = @arg5

    return @result
end

Then your query could be as simple as:

select
    Project_Num, Project_Title_Full, PTL, LOB, PL, JobTitle, [Function], MGR, MonthNum,
    dbo.BiggestOfFive(DMD1, DMD0, DMD2, DMD3, DMD4) as LargestDmd,
    dbo.BiggestOfFive(DRC1, DRC0, DRC2, DRC3, DRC4) as LargestDrc,
    CHG0
from Reporter.CHA

You would create another function for smallest-of-five, if that's what you're interested in (your question kinda jumps around on that) and you'd also want to use Coalesce judiciously if you're not sure there will always be values instead of nulls. But hopefully you get the point.

But... rethink your data design - normalize it. You'll be glad you did. Even this function is a bit silly in its rigid design.