问:
Material ui library margin bottom problem
Hi Everyone, Many Greetings from Turkey.

firstly this is my App.js Codes

```<code>/* React Imports*/
import { Routes, Route } from "react-router-dom";
import { useState } from "react";

/*Local Imports */
import { ColorModeContext, useMode } from "./theme";
import Dashboard from "./WorkPages/Dashboard/Dashboard";
import Topbar from "./WorkPages/GlobalPages/Topbar";
import Sidebar from "./WorkPages/GlobalPages/Sidebar";
import Team from "./WorkPages/Team/Team";
import CreateNewUser from "./WorkPages/CreateNewUser/CreateNewUser";
import Projects from "./WorkPages/Projects/Projects";
import CreateNewProjects from "./WorkPages/CreateNewProject/CreateNewProject";
import Bar from "./WorkPages/BarChart/BarChart";
import PieChart from "./WorkPages/PieChart/PieChart";
import LineChartGraph from "./WorkPages/LineChartGraph/LineChartGraph";
import TeamLocation from "./WorkPages/TeamLocation/TeamLocation";
import ProductBooks from "./WorkPages/ProductBooks/ProductBooks";
import WorkPlan from "./WorkPages/WorkPlan/WorkPlan";
import RoomInfoInput from "./WorkPages/RoomInfoInput/RoomInfoInput";
import StairsInfoInput from "./WorkPages/StairsInfoInput/StairsInfoInput";
import Specifications from "./WorkPages/Specifications/Specifications";
import InteractiveDB from "./WorkPages/InteractiveDB/InteractiveDB";
import Multiplication from "./WorkPages/Multiplication/Multiplication";
import ImportData from "./WorkPages/ImportData/ImportData";
import ExportData from "./WorkPages/ExportData/ExportData";
import HelpMenu from "./WorkPages/HelpMenu/HelpMenu";

/*MUI Imports */
import { CssBaseline, ThemeProvider } from "@mui/material";
import BarChart from "./components/_BarChart";
import Tabs from "@mui/material/Tabs";

function App() {
    const [theme, colorMode] = useMode();
    const [isSidebar, setIsSidebar] = useState(true);
    return (
        <ColorModeContext.Provider value={colorMode}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <Tabs>
                    <div className="app">
                        <Sidebar isSidebar={isSidebar} />
                        <main className="content">
                            <Topbar setIsSidebar={setIsSidebar} />
                            <Routes>
                                <Route path="/" element={<Dashboard />} />
                                <Route path="/team" element={<Team />} />
                                <Route
                                    path="/createnewuser"
                                    element={<CreateNewUser />}
                                />
                                <Route path="/projects" element={<Projects />} />
                                <Route
                                    path="/createnewproject"
                                    element={<CreateNewProjects />}
                                />
                                <Route path="/barchart" element={<BarChart />} />
                                <Route path="/piechart" element={<PieChart />} />
                                <Route path="/linechart" element={<LineChartGraph />} />
                                <Route
                                    path="/teamlocation"
                                    element={<TeamLocation />}
                                />
                                <Route
                                    path="/productbooks"
                                    element={<ProductBooks />}
                                />
                                <Route path="/workplan" element={<WorkPlan />} />
                                <Route
                                    path="/roominfoinput"
                                    element={<RoomInfoInput />}
                                />
                                <Route
                                    path="/stairsinfoinput"
                                    element={<StairsInfoInput />}
                                />
                                <Route
                                    path="/specifications"
                                    element={<Specifications />}
                                />
                                <Route
                                    path="/interactivedb"
                                    element={<InteractiveDB />}
                                />
                                <Route
                                    path="/multiplication"
                                    element={<Multiplication />}
                                />
                                <Route path="/importdata" element={<ImportData />} />
                                <Route path="/exportdata" element={<ExportData />} />
                                <Route path="/helpmenu" element={<HelpMenu />} />
                            </Routes>
                        </main>
                    </div>
                </Tabs>
            </ThemeProvider>
        </ColorModeContext.Provider>
    );
}

export default App;

</code>```

My index.css codes

```<code>/* Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600;700&display=swap');

/* CSS CODES*/
html,
body,
#root,
.app,
.content {
  height: 100%;
  width: 100%;
  font-family: "Source Sans Pro", sans-serif;
  overflow: hidden;
  /* Default Font Will be "Source Sans Pro" */
}

.app {
  display: flex;
  position: relative;
}

/* Scroll Bar Setting */
::-webkit-scrollbar {
  width: 10px;
}

/* Track Bar Setting */
::-webkit-scrollbar-track {
  background: #e0e0e0;
}

/* Handle Setting */
::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle On Hover Setting */
::-webkit-scrollbar-track:hover {
  background: #555;
}
</code>```

and current view of my project on the browser

How can I fix this problem with css codes or without css so with MUI classes? I tried many way to fix that but I didn't get a solution.

I tried

```<code>overflow:hidden
</code>```

code lines but they're doesn't working for my problem.

here is my sidebar codes

/*REACT IMPORTS*/
import { useState } from "react";
import { Link } from "react-router-dom";

/*MUI IMPORTS*/
import { Box, IconButton, Typography, useTheme } from "@mui/material";

/*MUI ICONS IMPORTS*/
import MenuOutlinedIcon from "@mui/icons-material/MenuOutlined";
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined";
import EngineeringOutlinedIcon from "@mui/icons-material/EngineeringOutlined";
import FoundationOutlinedIcon from "@mui/icons-material/FoundationOutlined";
import BarChartOutlinedIcon from "@mui/icons-material/BarChartOutlined";
import DonutSmallOutlinedIcon from "@mui/icons-material/DonutSmallOutlined";
import StackedLineChartOutlinedIcon from "@mui/icons-material/StackedLineChartOutlined";
import LocationSearchingOutlinedIcon from "@mui/icons-material/LocationSearchingOutlined";
import MenuBookOutlinedIcon from "@mui/icons-material/MenuBookOutlined";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import InputOutlinedIcon from "@mui/icons-material/InputOutlined";
import StairsOutlinedIcon from "@mui/icons-material/StairsOutlined";
import LibraryBooksOutlinedIcon from "@mui/icons-material/LibraryBooksOutlined";
import StorageOutlinedIcon from "@mui/icons-material/StorageOutlined";
import DynamicFeedOutlinedIcon from "@mui/icons-material/DynamicFeedOutlined";
import FileUploadOutlinedIcon from "@mui/icons-material/FileUploadOutlined";
import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined";

/*LOCAL IMPORTS*/
import { tokens } from "../../theme";

/*OTHER IMPORTS MAIN COMMENT*/

/*REACT PRO SIDEBAR IMPORTS*/
import { ProSidebar, Menu, MenuItem } from "react-pro-sidebar";
import "react-pro-sidebar/dist/css/styles.css";

/*-----------Components--------------*/

const Item = ({ title, to, icon, selected, setSelected }) => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);
    return (
        <MenuItem
            active={selected == title}
            style={{ color: colors.grey[100] }}
            onClick={() => setSelected(title)}
            icon={icon}>
            <Typography>{title}</Typography>
            <Link to={to} />
        </MenuItem>
    );
};

const Sidebar = () => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [selected, setSelected] = useState("Dashboard");

    return (
        <Box
            sx={{
                "& .pro-siderbar-inner": {
                    background: `${colors.primary[400]} !important`,
                },
                "& .pro-icon-wrapper": {
                    backgroundColor: "transparent ! important",
                },
                "& .pro-inner-item": {
                    padding: "5px 35px 5px 20px !important",
                },
                "& .pro-inner-item:hover": {
                    color: "#F08221 !important",
                },
                "& .pro-menu-item.active": {
                    colors: "#6870fa !important",
                },
            }}>
            <ProSidebar collapsed={isCollapsed}>
                {/* COMPANY LOGO AND MENU ICON */}
                <Menu iconShape='square'>
                    <MenuItem
                        onClick={() => setIsCollapsed(!isCollapsed)}
                        icon={
                            isCollapsed ? (
                                <MenuOutlinedIcon fontSize='large' />
                            ) : undefined
                        }
                        style={{ margin: "10px 0 20px 0", color: colors.grey[100] }}>
                        {!isCollapsed && (
                            <Box
                                display='flex'
                                justifyContent='space-between'
                                alignItems='center'
                                ml='15px'
                                overflow='hidden'>
                                <Typography variant='h3'>Metraj Merkezi</Typography>
                                <IconButton
                                    onClick={() => setIsCollapsed(!isCollapsed)}>
                                    <MenuOutlinedIcon fontSize='large' />
                                </IconButton>
                            </Box>
                        )}
                    </MenuItem>

                    {!isCollapsed && (
                        <Box mb='25px'>
                            <Box
                                display='flex'
                                justifyContent='center'
                                alignItems='center'>
                                <img
                                    alt='profile-user'
                                    width='100px'
                                    height='100px'
                                    src={`../../assets/fikret.jpg`}
                                    style={{ cursor: "pointer", borderRadius: "50%" }}
                                />
                            </Box>
                            <Box textAlign='center'>
                                <Typography variant='h3' color={colors.grey[100]}>
                                    Fikret AKBAŞ
                                </Typography>
                                <Typography variant='h6' color={colors.grey[500]}>
                                    Metraj Merkezi CEO
                                </Typography>
                            </Box>
                        </Box>
                    )}
                    <Box paddingLeft={isCollapsed ? undefined : "10%"}>
                        <Item
                            title='Anasayfa'
                            to='/'
                            icon={<HomeOutlinedIcon fontSize='large' />}
                            selected={selected}
                            setSelected={setSelected}
                        />
                        <Typography
                            variant='h6'
                            color={colors.grey[300]}
                            sx={{ m: "15px 0 5px 20px" }}>
                            Yönetici Paneli
                        </Typography>
                        <Item
                            title='Takımı Yönet'
                            to='/team'
                            icon={<EngineeringOutlinedIcon fontSize='large' />}
                            selected={selected}
                            setSelected={setSelected}
                        />
             ... there are  many items but I didn't add here for too long waste codes here
                    </Box>
                </Menu>
            </ProSidebar>
        </Box>
    );
};

export default Sidebar;```
</div>
</div>
</p>
<p>here is my Topbar codes</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*REACT IMPORTS*/
import { useContext } from "react";

/*MUI IMPORTS*/
import { Box, IconButton, useTheme } from "@mui/material";
import InputBase from "@mui/material/InputBase";

/*MUI ICONS IMPORTS*/
import LightModeOutlinedIcon from "@mui/icons-material/LightModeOutlined";
import DarkModeOutlinedIcon from "@mui/icons-material/DarkModeOutlined";
import NotificationsOutlinedIcon from "@mui/icons-material/NotificationsOutlined";
import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined";
import PersonOutlinedIcon from "@mui/icons-material/PersonOutlined";
import SearchIcon from "@mui/icons-material/Search";
import FolderSharedOutlinedIcon from "@mui/icons-material/FolderSharedOutlined";
import FactCheckOutlinedIcon from "@mui/icons-material/FactCheckOutlined";

/*LOCAL IMPORTS*/
import { ColorModeContext, tokens } from "../../theme";

/*OTHER IMPORTS MAIN COMMENT*/
/*OTHER IMPORTS*/

/*-----------Components--------------*/

const Topbar = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  const colorMode = useContext(ColorModeContext);

  return (
    <Box display="flex" justifyContent="space-between" p={2}>
      {/* SEARCH BAR */}
      <Box
        display="flex"
        backgroundColor={colors.primary[700]}
        borderRadius="3px"
      >
        <InputBase sx={{ ml: 2, flex: 1 }} placeholder="Search" />
        <IconButton type="button" sx={{ p: 1 }}>
          <SearchIcon />
        </IconButton>
      </Box>

      {/* ICONS */}
      <Box display="flex" border="1px solid" borderRadius={3}>
        <IconButton onClick={colorMode.toggleColorMode}>
          {theme.palette.mode === "dark" ? (
            <LightModeOutlinedIcon />
          ) : (
            <DarkModeOutlinedIcon />
          )}
        </IconButton>
        <IconButton>
          <FactCheckOutlinedIcon />
        </IconButton>

        <IconButton>
          <FolderSharedOutlinedIcon />
        </IconButton>
        <IconButton>
          <NotificationsOutlinedIcon />
        </IconButton>
        <IconButton>
          <SettingsOutlinedIcon />
        </IconButton>
        <IconButton>
          <PersonOutlinedIcon />
        </IconButton>
      </Box>
    </Box>
  );
};

export default Topbar;</code>```

Body:
Hi Everyone, Many Greetings from Turkey.

firstly this is my App.js Codes

/* React Imports*/
import { Routes, Route } from "react-router-dom";
import { useState } from "react";

/*Local Imports */
import { ColorModeContext, useMode } from "./theme";
import Dashboard from "./WorkPages/Dashboard/Dashboard";
import Topbar from "./WorkPages/GlobalPages/Topbar";
import Sidebar from "./WorkPages/GlobalPages/Sidebar";
import Team from "./WorkPages/Team/Team";
import CreateNewUser from "./WorkPages/CreateNewUser/CreateNewUser";
import Projects from "./WorkPages/Projects/Projects";
import CreateNewProjects from "./WorkPages/CreateNewProject/CreateNewProject";
import Bar from "./WorkPages/BarChart/BarChart";
import PieChart from "./WorkPages/PieChart/PieChart";
import LineChartGraph from "./WorkPages/LineChartGraph/LineChartGraph";
import TeamLocation from "./WorkPages/TeamLocation/TeamLocation";
import ProductBooks from "./WorkPages/ProductBooks/ProductBooks";
import WorkPlan from "./WorkPages/WorkPlan/WorkPlan";
import RoomInfoInput from "./WorkPages/RoomInfoInput/RoomInfoInput";
import StairsInfoInput from "./WorkPages/StairsInfoInput/StairsInfoInput";
import Specifications from "./WorkPages/Specifications/Specifications";
import InteractiveDB from "./WorkPages/InteractiveDB/InteractiveDB";
import Multiplication from "./WorkPages/Multiplication/Multiplication";
import ImportData from "./WorkPages/ImportData/ImportData";
import ExportData from "./WorkPages/ExportData/ExportData";
import HelpMenu from "./WorkPages/HelpMenu/HelpMenu";

/*MUI Imports */
import { CssBaseline, ThemeProvider } from "@mui/material";
import BarChart from "./components/_BarChart";
import Tabs from "@mui/material/Tabs";

function App() {
    const [theme, colorMode] = useMode();
    const [isSidebar, setIsSidebar] = useState(true);
    return (
        <ColorModeContext.Provider value={colorMode}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <Tabs>

                        <Sidebar isSidebar={isSidebar} />

                            <Topbar setIsSidebar={setIsSidebar} />
                            <Routes>
                                <Route path="/" element={<Dashboard />} />
                                <Route path="/team" element={<Team />} />
                                <Route
                                    path="/createnewuser"
                                    element={<CreateNewUser />}
                                />
                                <Route path="/projects" element={<Projects />} />
                                <Route
                                    path="/createnewproject"
                                    element={<CreateNewProjects />}
                                />
                                <Route path="/barchart" element={<BarChart />} />
                                <Route path="/piechart" element={<PieChart />} />
                                <Route path="/linechart" element={<LineChartGraph />} />
                                <Route
                                    path="/teamlocation"
                                    element={<TeamLocation />}
                                />
                                <Route
                                    path="/productbooks"
                                    element={<ProductBooks />}
                                />
                                <Route path="/workplan" element={<WorkPlan />} />
                                <Route
                                    path="/roominfoinput"
                                    element={<RoomInfoInput />}
                                />
                                <Route
                                    path="/stairsinfoinput"
                                    element={<StairsInfoInput />}
                                />
                                <Route
                                    path="/specifications"
                                    element={<Specifications />}
                                />
                                <Route
                                    path="/interactivedb"
                                    element={<InteractiveDB />}
                                />
                                <Route
                                    path="/multiplication"
                                    element={<Multiplication />}
                                />
                                <Route path="/importdata" element={<ImportData />} />
                                <Route path="/exportdata" element={<ExportData />} />
                                <Route path="/helpmenu" element={<HelpMenu />} />
                            </Routes>

                </Tabs>
            </ThemeProvider>
        </ColorModeContext.Provider>
    );
}

export default App;

My index.css codes

/* Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600;700&display=swap');

/* CSS CODES*/
html,
body,
#root,
.app,
.content {
  height: 100%;
  width: 100%;
  font-family: "Source Sans Pro", sans-serif;
  overflow: hidden;
  /* Default Font Will be "Source Sans Pro" */
}

.app {
  display: flex;
  position: relative;
}

/* Scroll Bar Setting */
::-webkit-scrollbar {
  width: 10px;
}

/* Track Bar Setting */
::-webkit-scrollbar-track {
  background: #e0e0e0;
}

/* Handle Setting */
::-webkit-scrollbar-thumb {
  background: #888;
}

/* Handle On Hover Setting */
::-webkit-scrollbar-track:hover {
  background: #555;
}

and current view of my project on the browser

How can I fix this problem with css codes or without css so with MUI classes? I tried many way to fix that but I didn't get a solution.

I tried

overflow:hidden

code lines but they're doesn't working for my problem.

here is my sidebar codes

/*REACT IMPORTS*/
import { useState } from "react";
import { Link } from "react-router-dom";

/*MUI IMPORTS*/
import { Box, IconButton, Typography, useTheme } from "@mui/material";

/*MUI ICONS IMPORTS*/
import MenuOutlinedIcon from "@mui/icons-material/MenuOutlined";
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined";
import EngineeringOutlinedIcon from "@mui/icons-material/EngineeringOutlined";
import FoundationOutlinedIcon from "@mui/icons-material/FoundationOutlined";
import BarChartOutlinedIcon from "@mui/icons-material/BarChartOutlined";
import DonutSmallOutlinedIcon from "@mui/icons-material/DonutSmallOutlined";
import StackedLineChartOutlinedIcon from "@mui/icons-material/StackedLineChartOutlined";
import LocationSearchingOutlinedIcon from "@mui/icons-material/LocationSearchingOutlined";
import MenuBookOutlinedIcon from "@mui/icons-material/MenuBookOutlined";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import InputOutlinedIcon from "@mui/icons-material/InputOutlined";
import StairsOutlinedIcon from "@mui/icons-material/StairsOutlined";
import LibraryBooksOutlinedIcon from "@mui/icons-material/LibraryBooksOutlined";
import StorageOutlinedIcon from "@mui/icons-material/StorageOutlined";
import DynamicFeedOutlinedIcon from "@mui/icons-material/DynamicFeedOutlined";
import FileUploadOutlinedIcon from "@mui/icons-material/FileUploadOutlined";
import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined";

/*LOCAL IMPORTS*/
import { tokens } from "../../theme";

/*OTHER IMPORTS MAIN COMMENT*/

/*REACT PRO SIDEBAR IMPORTS*/
import { ProSidebar, Menu, MenuItem } from "react-pro-sidebar";
import "react-pro-sidebar/dist/css/styles.css";

/*-----------Components--------------*/

const Item = ({ title, to, icon, selected, setSelected }) => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);
    return (
        <MenuItem
            active={selected == title}
            style={{ color: colors.grey[100] }}
            onClick={() => setSelected(title)}
            icon={icon}>
            <Typography>{title}</Typography>
            <Link to={to} />
        </MenuItem>
    );
};

const Sidebar = () => {
    const theme = useTheme();
    const colors = tokens(theme.palette.mode);
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [selected, setSelected] = useState("Dashboard");

    return (
        <Box
            sx={{
                "& .pro-siderbar-inner": {
                    background: `${colors.primary[400]} !important`,
                },
                "& .pro-icon-wrapper": {
                    backgroundColor: "transparent ! important",
                },
                "& .pro-inner-item": {
                    padding: "5px 35px 5px 20px !important",
                },
                "& .pro-inner-item:hover": {
                    color: "#F08221 !important",
                },
                "& .pro-menu-item.active": {
                    colors: "#6870fa !important",
                },
            }}>
            <ProSidebar collapsed={isCollapsed}>
                {/* COMPANY LOGO AND MENU ICON */}
                <Menu iconShape='square'>
                    <MenuItem
                        onClick={() => setIsCollapsed(!isCollapsed)}
                        icon={
                            isCollapsed ? (
                                <MenuOutlinedIcon fontSize='large' />
                            ) : undefined
                        }
                        style={{ margin: "10px 0 20px 0", color: colors.grey[100] }}>
                        {!isCollapsed && (
                            <Box
                                display='flex'
                                justifyContent='space-between'
                                alignItems='center'
                                ml='15px'
                                overflow='hidden'>
                                <Typography variant='h3'>Metraj Merkezi</Typography>
                                <IconButton
                                    onClick={() => setIsCollapsed(!isCollapsed)}>
                                    <MenuOutlinedIcon fontSize='large' />
                                </IconButton>
                            </Box>
                        )}
                    </MenuItem>

                    {!isCollapsed && (
                        <Box mb='25px'>
                            <Box
                                display='flex'
                                justifyContent='center'
                                alignItems='center'>
                                <img
                                    alt='profile-user'
                                    width='100px'
                                    height='100px'
                                    src={`../../assets/fikret.jpg`}
                                    style={{ cursor: "pointer", borderRadius: "50%" }}
                                />
                            </Box>
                            <Box textAlign='center'>
                                <Typography variant='h3' color={colors.grey[100]}>
                                    Fikret AKBAŞ
                                </Typography>
                                <Typography variant='h6' color={colors.grey[500]}>
                                    Metraj Merkezi CEO
                                </Typography>
                            </Box>
                        </Box>
                    )}
                    <Box paddingLeft={isCollapsed ? undefined : "10%"}>
                        <Item
                            title='Anasayfa'
                            to='/'
                            icon={<HomeOutlinedIcon fontSize='large' />}
                            selected={selected}
                            setSelected={setSelected}
                        />
                        <Typography
                            variant='h6'
                            color={colors.grey[300]}
                            sx={{ m: "15px 0 5px 20px" }}>
                            Yönetici Paneli
                        </Typography>
                        <Item
                            title='Takımı Yönet'
                            to='/team'
                            icon={<EngineeringOutlinedIcon fontSize='large' />}
                            selected={selected}
                            setSelected={setSelected}
                        />
             ... there are  many items but I didn't add here for too long waste codes here
                    </Box>
                </Menu>
            </ProSidebar>
        </Box>
    );
};

export default Sidebar;

here is my Topbar codes

/*REACT IMPORTS*/
import { useContext } from "react";

/*MUI IMPORTS*/
import { Box, IconButton, useTheme } from "@mui/material";
import InputBase from "@mui/material/InputBase";

/*MUI ICONS IMPORTS*/
import LightModeOutlinedIcon from "@mui/icons-material/LightModeOutlined";
import DarkModeOutlinedIcon from "@mui/icons-material/DarkModeOutlined";
import NotificationsOutlinedIcon from "@mui/icons-material/NotificationsOutlined";
import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined";
import PersonOutlinedIcon from "@mui/icons-material/PersonOutlined";
import SearchIcon from "@mui/icons-material/Search";
import FolderSharedOutlinedIcon from "@mui/icons-material/FolderSharedOutlined";
import FactCheckOutlinedIcon from "@mui/icons-material/FactCheckOutlined";

/*LOCAL IMPORTS*/
import { ColorModeContext, tokens } from "../../theme";

/*OTHER IMPORTS MAIN COMMENT*/
/*OTHER IMPORTS*/

/*-----------Components--------------*/

const Topbar = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  const colorMode = useContext(ColorModeContext);

  return (
    <Box display="flex" justifyContent="space-between" p={2}>
      {/* SEARCH BAR */}
      <Box
        display="flex"
        backgroundColor={colors.primary[700]}
        borderRadius="3px"
      >
        <InputBase sx={{ ml: 2, flex: 1 }} placeholder="Search" />
        <IconButton type="button" sx={{ p: 1 }}>
          <SearchIcon />
        </IconButton>
      </Box>

      {/* ICONS */}
      <Box display="flex" border="1px solid" borderRadius={3}>
        <IconButton onClick={colorMode.toggleColorMode}>
          {theme.palette.mode === "dark" ? (
            <LightModeOutlinedIcon />
          ) : (
            <DarkModeOutlinedIcon />
          )}
        </IconButton>
        <IconButton>
          <FactCheckOutlinedIcon />
        </IconButton>

        <IconButton>
          <FolderSharedOutlinedIcon />
        </IconButton>
        <IconButton>
          <NotificationsOutlinedIcon />
        </IconButton>
        <IconButton>
          <SettingsOutlinedIcon />
        </IconButton>
        <IconButton>
          <PersonOutlinedIcon />
        </IconButton>
      </Box>
    </Box>
  );
};

export default Topbar;


来源: stackexchange

问:
AWS Amplify/Cognito: Dynamically Selecting Auth Flow
I'd like to set up an authentication system in AWS Amplify with a Cognito User Pool that supports either the USER_SRP_AUTH or CUSTOM_AUTH, and have the app dynamically select between the two at the sign-in step.

The Amplify documentation for Switching Authentication Flows shows how you can do this by updating the global Amplify config, but is there any way to do this by just setting a single value (the authentication flow) instead of needing to store, update, and set the entire Amplify configuration each time?

ContentLicense: CC BY-SA 4.0


问:
A string parses as class for set "db.Set<Class>"
I want to db.Set to query different tables dynamically.
I have many entity models such as User, Invoice, Address or Product classes.
How can I parse string "User" to become a class then db.Set? which can be set dynamically.

I have tried:

```<code>if (s=="User")
  db.Set<User>...
else if (s=="Invoice")
  db.Set<Invoice>...
</code>```

.. above and so on...

Any solutions that make it simple as db.Set< s >?
It means "s" can directly string to its Class.

Body:
I want to db.Set to query different tables dynamically.
I have many entity models such as User, Invoice, Address or Product classes.
How can I parse string "User" to become a class then db.Set? which can be set dynamically.

I have tried:

if (s=="User")
  db.Set<User>...
else if (s=="Invoice")
  db.Set<Invoice>...

.. above and so on...

Any solutions that make it simple as db.Set< s >?
It means "s" can directly string to its Class.


问:
Modern TypeScript won't compile with Webpack when using type: module in package.json and importing .js files
I have configured my tsconfig.json file as follows:

{
    "extends": "./tsconfig.paths.json",
    "compilerOptions": {
        "target": "ES2017",
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "noEmit": true,
        "baseUrl": "./",
        "allowJs": false,
        "skipLibCheck": true,
        "jsx": "react",
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "incremental": true,
        "removeComments": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "allowUnreachableCode": false,
        "allowUnusedLabels": false,
        "alwaysStrict": true,
        "noFallthroughCasesInSwitch": true,
        "noImplicitAny": true,
        "noImplicitOverride": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noPropertyAccessFromIndexSignature": true,
        "noUncheckedIndexedAccess": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "typeRoots": ["./node_modules/@types", "./@types"]
    }
}
```
<p>Then, I configured my <code>webpack.config.js</code> file:</p>
<pre class="lang-js prettyprint-override"><code>const webpack = require('webpack');
const isCI = require('is-ci');
const { merge } = require('webpack-merge');

const isDev = process.env.NODE_ENV === 'development' && !isCI;
const cliApiDomain = isDev ? 'localhost' : 'blavblblblb';
const cliApiUrl = isDev ? `http://${cliApiDomain}:4000` : `https://www.${cliApiDomain}`;
const dashboardUrl = isDev ? 'http://localhost:8080' : 'blalblals';

const configuration = (options) =>
    merge(options, {
        plugins: [
            new webpack.DefinePlugin({
                __CLI_API_DOMAIN__: JSON.stringify(cliApiDomain),
                __CLI_API_URL__: JSON.stringify(cliApiUrl),
                __DASHBOARD_URL__: JSON.stringify(dashboardUrl),
            }),
        ],
        experiments: { topLevelAwait: true },
    });

module.exports = configuration;
</code>```

I'm using NestJS, so this Webpack configuration uses Nest's Webpack configuration.

My nest-cli.json file:

{
    "$schema": "https://json.schemastore.org/nest-cli",
    "sourceRoot": "src",
    "compilerOptions": {
        "webpack": true,
        "webpackConfigPath": "./webpack.config.js",
        "deleteOutDir": true
    }
}
```
<p>And I've also configured <code>"type": "module"</code> in my <code>package.json</code> file.
However when I compile the code using <code>nest build</code>, I get:</p>
```ERROR in ./src/main.ts 2:0-44
Module not found: Error: Can't resolve './app.module.js' in '/Users/.../.../cli/src'
resolve './app.module.js' in '/Users/.../.../cli/src'
  using description file: /Users/.../.../cli/package.json (relative path: ./src)
    using description file: /Users/.../.../cli/package.json (relative path: ./src/app.module.js)
      no extension
        /Users/.../.../cli/src/app.module.js doesn't exist
      .tsx
        /Users/.../.../cli/src/app.module.js.tsx doesn't exist
      .ts
        /Users/.../.../cli/src/app.module.js.ts doesn't exist
      .js
        /Users/.../.../.../src/app.module.js.js doesn't exist
      as directory
        /Users/..../.../.../src/app.module.js doesn't exist

ERROR in ./src/main.ts
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:
 * ./node_modules/.pnpm/ts-loader@9.4.2_qqxisngxjbp7lstdk7boexbu3e/node_modules/ts-loader/index.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
```
<p>A typical <code>import</code> statement in my code:</p>
```import { CommandFactory } from 'nest-commander';

import { AppModule } from './app.module.js';

await CommandFactory.run(AppModule);
```

As described in TypeScript documentation, although all my files are .ts or .tsx extensions, I should import from js?x: https://github.com/microsoft/TypeScript/issues/33588

So anyone could tell how can I fix it?

Body:
I have configured my tsconfig.json file as follows:

{
    "extends": "./tsconfig.paths.json",
    "compilerOptions": {
        "target": "ES2017",
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "noEmit": true,
        "baseUrl": "./",
        "allowJs": false,
        "skipLibCheck": true,
        "jsx": "react",
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "incremental": true,
        "removeComments": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "allowUnreachableCode": false,
        "allowUnusedLabels": false,
        "alwaysStrict": true,
        "noFallthroughCasesInSwitch": true,
        "noImplicitAny": true,
        "noImplicitOverride": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noPropertyAccessFromIndexSignature": true,
        "noUncheckedIndexedAccess": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "typeRoots": ["./node_modules/@types", "./@types"]
    }
}

Then, I configured my webpack.config.js file:

const webpack = require('webpack');
const isCI = require('is-ci');
const { merge } = require('webpack-merge');

const isDev = process.env.NODE_ENV === 'development' && !isCI;
const cliApiDomain = isDev ? 'localhost' : 'blavblblblb';
const cliApiUrl = isDev ? `http://${cliApiDomain}:4000` : `https://www.${cliApiDomain}`;
const dashboardUrl = isDev ? 'http://localhost:8080' : 'blalblals';

const configuration = (options) =>
    merge(options, {
        plugins: [
            new webpack.DefinePlugin({
                __CLI_API_DOMAIN__: JSON.stringify(cliApiDomain),
                __CLI_API_URL__: JSON.stringify(cliApiUrl),
                __DASHBOARD_URL__: JSON.stringify(dashboardUrl),
            }),
        ],
        experiments: { topLevelAwait: true },
    });

module.exports = configuration;

I'm using NestJS, so this Webpack configuration uses Nest's Webpack configuration.

My nest-cli.json file:

{
    "$schema": "https://json.schemastore.org/nest-cli",
    "sourceRoot": "src",
    "compilerOptions": {
        "webpack": true,
        "webpackConfigPath": "./webpack.config.js",
        "deleteOutDir": true
    }
}

And I've also configured "type": "module" in my package.json file.
However when I compile the code using nest build, I get:

ERROR in ./src/main.ts 2:0-44
Module not found: Error: Can't resolve './app.module.js' in '/Users/.../.../cli/src'
resolve './app.module.js' in '/Users/.../.../cli/src'
  using description file: /Users/.../.../cli/package.json (relative path: ./src)
    using description file: /Users/.../.../cli/package.json (relative path: ./src/app.module.js)
      no extension
        /Users/.../.../cli/src/app.module.js doesn't exist
      .tsx
        /Users/.../.../cli/src/app.module.js.tsx doesn't exist
      .ts
        /Users/.../.../cli/src/app.module.js.ts doesn't exist
      .js
        /Users/.../.../.../src/app.module.js.js doesn't exist
      as directory
        /Users/..../.../.../src/app.module.js doesn't exist

ERROR in ./src/main.ts
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:
 * ./node_modules/.pnpm/ts-loader@9.4.2_qqxisngxjbp7lstdk7boexbu3e/node_modules/ts-loader/index.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

A typical import statement in my code:

import { CommandFactory } from 'nest-commander';

import { AppModule } from './app.module.js';

await CommandFactory.run(AppModule);

As described in TypeScript documentation, although all my files are .ts or .tsx extensions, I should import from js?x: https://github.com/microsoft/TypeScript/issues/33588

So anyone could tell how can I fix it?


Title: How to calculate Month to Date (MTD) and YTD using Pandas dataframe?

Body:
I want to calculate MTD and YTD in a dataframe. I want to calculate MTD and YTD as cumulative mean, if products are grapes and kiwi.Otherwise I want to calculative cumulative sum.I wrote below code,but my output is wrong.

Can anyone suggest a solution to calculate MTD and YTD in proper way?

code:

import pandas as pd
import numpy as np

#MTD AND YTD calculation

data = {'date' : ['2016/11/01', '2016/11/02', '2016/11/03', '2016/11/04', '2016/11/05', '2016/11/05', '2016/12/01', '2016/12/02', '2016/12/03', '2016/12/04', '2016/12/15', '2016/12/20', '2016/12/23', '2016/12/30','2017/01/01', '2017/01/02', '2017/01/03', '2017/01/04', '2017/01/15', '2017/01/20', '2017/01/23', '2017/01/30','2017/01/01', '2017/01/02', '2017/01/03', '2017/01/04', '2017/01/15', '2017/01/20', '2017/01/23', '2017/01/30', '2017/04/01', '2017/04/02', '2017/04/03', '2017/04/04', '2017/04/15', '2017/04/20', '2017/04/23', '2017/04/30','2017/04/01', '2017/04/02', '2017/04/03', '2017/04/04', '2017/04/15', '2017/04/20', '2017/04/23', '2017/04/30', '2017/05/01', '2017/05/02', '2017/05/03', '2017/05/04', '2017/05/15', '2017/05/20', '2017/05/23', '2017/05/30','2017/05/01', '2017/05/02', '2017/05/03', '2017/05/04', '2017/05/15', '2017/05/20', '2017/05/23', '2017/05/30'],
        'category': ['fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit',
                    'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit',
                    'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit',
                    'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit',
                    'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit', 'fruit',
                    'fruit', 'fruit', 'fruit', 'fruit', 'fruit'],

        'product': ['grapes', 'grapes', 'grapes', 'kiwi', 'kiwi', 'grapes', 'Apple', 'Apple', 'Apple','Apple', 'Apple', 'Apple','Apple', 'Apple','Apple', 'Apple', 'Apple','Apple', 'Apple', 'Apple','Apple', 'Apple', 'Orange', 'Orange', 'Orange','Orange', 'Orange', 'Orange','Orange', 'Orange', 'Apple', 'Apple', 'Apple','Apple', 'Apple', 'Apple','Apple', 'Apple', 'Orange', 'Orange', 'Orange','Orange', 'Orange', 'Orange','Orange', 'Orange', 'Apple', 'Apple', 'Apple','Apple', 'Apple', 'Apple','Apple', 'Apple', 'Orange', 'Orange', 'Orange','Orange', 'Orange', 'Orange','Orange', 'Orange'],
        'price': [10, 10, 20, 40, 60, 30, 10, 20, 10, 50, 10, 5, 10, 10, 10, 20, 10, 50, 10, 5, 10, 10, 20, 10, 5, 5, 10, 10, 20, 50, 10, 5, 20, 10, 10, 20, 50, 20, 5, 5, 10, 10, 20, 50, 30, 10, 20, 5, 5, 10, 20, 10, 20, 10, 40, 20, 10, 10, 20, 20, 10, 5]}

df = pd.DataFrame(data)

df.date = pd.to_datetime(df.date)
df['MTD'] = np.select([(df['product'].isin(['grapes', 'kiwi'])),
                        (~df['product'].isin(['grapes', 'kiwi']))],
                        [df.groupby([df.date.dt.to_period('m'),'product']).price.expanding().mean(),
                        df.groupby([df.date.dt.to_period('m'),'product']).price.cumsum()],
                        0)
df['YTD'] = np.select([(df['product'].isin(['grapes', 'kiwi'])),
                        (~df['product'].isin(['grapes', 'kiwi']))],
                        [df.groupby([df.date.dt.to_period('A-MAR'),'product']).price.expanding().mean(),
                        df.groupby([df.date.dt.to_period('A-MAR'),'product']).price.cumsum()],
                        0)
print(df)

output:

        date category product  price         MTD         YTD
0  2016-11-01    fruit  grapes     10   10.000000   10.000000
1  2016-11-02    fruit  grapes     10   10.000000   15.000000
2  2016-11-03    fruit  grapes     20   13.333333   13.333333
3  2016-11-04    fruit    kiwi     40   17.500000   22.500000
4  2016-11-05    fruit    kiwi     60   40.000000   20.000000
..        ...      ...     ...    ...         ...         ...
57 2017-05-04    fruit  Orange     10   80.000000  220.000000
58 2017-05-15    fruit  Orange     20  100.000000  240.000000
59 2017-05-20    fruit  Orange     20  120.000000  260.000000
60 2017-05-23    fruit  Orange     10  130.000000  270.000000
61 2017-05-30    fruit  Orange      5  135.000000  275.000000


问:
How to open multiple mui DialogProvider dynamically?
I have a generic DialogProvider that written with MUI and I open all dialog modals with this generic provider.

Code is below.

```<code>import React from "react";
import { makeAutoObservable } from "mobx";
import {
  BooleanValuePaths,
  getValue,
  setValue,
  Paths,
  PathValueType,
  StringValuePaths,
} from "../utils/utils";
import { IAppState, useAppState } from "./app-state";

type BaseType = object;

export class DialogState<T extends BaseType> {
  _data: T;
  _resetFunction?: () => T;
  _touched: BooleanValuePaths<Paths<T>>;
  _error: StringValuePaths<Paths<T>>;
  _formError?: string;
  _initialData: T;

  constructor(dataInitiator: () => T) {
    this._data = dataInitiator();
    this._initialData = dataInitiator();
    this._resetFunction = dataInitiator;
    this._touched = {};
    this._error = {};
    makeAutoObservable(this);
  }

  reset() {
    this._resetFunction?.();
  }

  get data() {
    return this._data;
  }

  get formTouched() {
    const touched = Object.keys(this._touched).find(
      (key) => this._touched[key as Paths<T>],
    );
    return touched;
  }

  setValue<P extends Paths<T>>(path: P, value: PathValueType<T, P>): void {
    setValue(this._data, path, value as any); //TODO remove the "as any", but the typescript has problem
    this._touched[path] = true;
  }

  getValue<P extends Paths<T>>(path: P): PathValueType<T, P> {
    return getValue(this._data, path) as PathValueType<T, P>; //TODO remove the "as PathValueType<T, P>", but the typescript has problem
  }

  isTouched<P extends Paths<T>>(path: P) {
    return this._touched[path];
  }

  errorOf<P extends Paths<T>>(path: P) {
    return this._error[path];
  }

  setErrorOf<P extends Paths<T> | "">(path: P, error: string) {
    this._error[path] = error;
  }

  resetErrors() {
    this._error = {};
  }

  resetTouches() {
    this._touched = {};
  }

  resetData() {
    this._data = this._initialData;
  }

  setFormError(error: string) {
    this._formError = error;
  }
}

function processErrorFunction<T extends BaseType>(
  state: DialogState<T>,
  err: any,
  appState: IAppState,
  errorKeyMap?: { errorKey: string; dataKey: string }[],
) {
  try {
    const json = JSON.parse(err?.message);
    if (Array.isArray(json?.message)) {
      (json.message as any[]).forEach((m) => {
        if (
          typeof m?.property === "string" &&
          typeof m?.constraints === "object"
        ) {
          const msg = Object.keys(m.constraints)
            .map((k) => m.constraints[k])
            .join(", ");
          const dataKey =
            errorKeyMap?.find((erk) => erk.errorKey === m.property)?.dataKey ??
            m.property;
          state.setErrorOf(dataKey, msg);
        }
      });
    } else {
      appState.setSnackMessage({ message: json?.message || "unknown" });
    }
  } catch (_) {
    appState.setSnackMessage({ message: err?.message || "unknown" });
  }
}

export function useDialogStateProvider<T extends BaseType>(
  stateInitiator: () => T,
  saverFunction: (v: T, appState: IAppState) => Promise<any>,
  closeFunction?: (value?: T) => void,
  errorKeyMap?: { errorKey: string; dataKey: string }[],
) {
  const appState = useAppState();
  const [loading, setLoading] = React.useState(false);
  const state = React.useMemo(
    () => new DialogState(stateInitiator),
    [stateInitiator],
  );

  const reset = () => {
    state.reset();
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      state.resetErrors();
      await saverFunction(state.data, appState);
      state.resetTouches();

      if (closeFunction) {
        state.resetData();
        closeFunction(state.data);
        reset();
      }
    } catch (err: any) {
      processErrorFunction(state, err, appState, errorKeyMap);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    try {
      if (closeFunction) {
        setLoading(false);
        state.resetErrors();
        state.resetData();
        state.resetTouches();

        closeFunction(state.data);
        reset();
      }
    } catch (err: any) {
      processErrorFunction(state, err, appState, errorKeyMap);
    } finally {
      setLoading(false);
    }
  };

  return {
    reset,
    state,
    loading,
    handleSave,
    handleClose,
  };
}
interface useDialogStateProviderInterface<T extends BaseType> {
  (stateProvider: () => T): {
    reset: () => void;
    state: DialogState<T>;
    loading: boolean;
    handleSave: () => Promise<void>;
    handleClose?: () => void;
  };
}

export type DialogStateProviderType<T extends BaseType> = ReturnType<
  useDialogStateProviderInterface<T>
>;

export const DialogStateContext =
  React.createContext<DialogStateProviderType<any> | null>(null);

export function DialogStateProvider<
  K extends BaseType,
  T extends DialogStateProviderType<K>,
>({ state, children }: { state: T; children?: React.ReactNode }) {
  return (
    <DialogStateContext.Provider value={state}>
      {children}
    </DialogStateContext.Provider>
  );
}

export function useDialogState<T extends BaseType>() {
  const store = React.useContext(DialogStateContext);
  if (!store) {
    throw new Error("useDialogState must be used within DialogStateProvider");
  }
  return store as DialogStateProviderType<T>;
}

</code>```

Usage is like below:

```<code><DialogStateProvider state={taskState}>
  <BaseDialog open={open} handleClose={handleClose} title={title}>
    <AssignedTaskEditor isSubsequent={isSubsequent} />
  </BaseDialog>
</DialogStateProvider>
</code>```

BaseDialog code is this:

```<code>import {
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  SxProps,
  Theme,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

export function BaseDialog({
  open,
  handleClose,
  title,
  children,
  sx,
}: {
  open: boolean;
  handleClose: () => void;
  title?: React.ReactNode;
  children: React.ReactNode;
  sx?: SxProps<Theme>;
}) {
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down("md"));

  return (
    <Dialog
      fullScreen={fullScreen}
      open={open}
      onClose={handleClose}
      maxWidth="lg"
      sx={{
        ...sx,
        "& .MuiDialog-container > .MuiPaper-root": {
          height: "100%",
          backgroundColor: "background.default",
          ...(sx as any)?.["& .MuiDialog-container > .MuiPaper-root"],
        },
        "& .MuiDialogContent-root": {
          flexGrow: 1,
          backgroundColor: "background.default",
          maxHeight: "80vh",
          marginBlock: 2,
          ...(sx as any)?.["& .MuiDialogContent-root"],
        },
        "& .dialogBox-Icon": {
          position: "absolute",
          right: (theme) => theme.spacing(2.5),
          top: (theme) => theme.spacing(1),
          ...(sx as any)?.["& .dialogBox-Icon"],
        },
      }}
    >
      {title && <DialogTitle>{title}</DialogTitle>}

      <IconButton onClick={handleClose} className="dialogBox-Icon" size="large">
        <CloseIcon />
      </IconButton>
      <DialogContent dividers>{children}</DialogContent>
    </Dialog>
  );
}
</code>```

I want to open multiple dialog concurrently like that:

Save and add a subsequent task button should call an API endpoint to save data and it should close current modal and open another dialog and this should go forever. There should not be an end.

I have searched on internet but I couldn't find good example for this.
How can I do that with this current generic DialogProvider?

Body:
I have a generic DialogProvider that written with MUI and I open all dialog modals with this generic provider.

Code is below.

import React from "react";
import { makeAutoObservable } from "mobx";
import {
  BooleanValuePaths,
  getValue,
  setValue,
  Paths,
  PathValueType,
  StringValuePaths,
} from "../utils/utils";
import { IAppState, useAppState } from "./app-state";

type BaseType = object;

export class DialogState<T extends BaseType> {
  _data: T;
  _resetFunction?: () => T;
  _touched: BooleanValuePaths<Paths<T>>;
  _error: StringValuePaths<Paths<T>>;
  _formError?: string;
  _initialData: T;

  constructor(dataInitiator: () => T) {
    this._data = dataInitiator();
    this._initialData = dataInitiator();
    this._resetFunction = dataInitiator;
    this._touched = {};
    this._error = {};
    makeAutoObservable(this);
  }

  reset() {
    this._resetFunction?.();
  }

  get data() {
    return this._data;
  }

  get formTouched() {
    const touched = Object.keys(this._touched).find(
      (key) => this._touched[key as Paths<T>],
    );
    return touched;
  }

  setValue<P extends Paths<T>>(path: P, value: PathValueType<T, P>): void {
    setValue(this._data, path, value as any); //TODO remove the "as any", but the typescript has problem
    this._touched[path] = true;
  }

  getValue<P extends Paths<T>>(path: P): PathValueType<T, P> {
    return getValue(this._data, path) as PathValueType<T, P>; //TODO remove the "as PathValueType<T, P>", but the typescript has problem
  }

  isTouched<P extends Paths<T>>(path: P) {
    return this._touched[path];
  }

  errorOf<P extends Paths<T>>(path: P) {
    return this._error[path];
  }

  setErrorOf<P extends Paths<T> | "">(path: P, error: string) {
    this._error[path] = error;
  }

  resetErrors() {
    this._error = {};
  }

  resetTouches() {
    this._touched = {};
  }

  resetData() {
    this._data = this._initialData;
  }

  setFormError(error: string) {
    this._formError = error;
  }
}

function processErrorFunction<T extends BaseType>(
  state: DialogState<T>,
  err: any,
  appState: IAppState,
  errorKeyMap?: { errorKey: string; dataKey: string }[],
) {
  try {
    const json = JSON.parse(err?.message);
    if (Array.isArray(json?.message)) {
      (json.message as any[]).forEach((m) => {
        if (
          typeof m?.property === "string" &&
          typeof m?.constraints === "object"
        ) {
          const msg = Object.keys(m.constraints)
            .map((k) => m.constraints[k])
            .join(", ");
          const dataKey =
            errorKeyMap?.find((erk) => erk.errorKey === m.property)?.dataKey ??
            m.property;
          state.setErrorOf(dataKey, msg);
        }
      });
    } else {
      appState.setSnackMessage({ message: json?.message || "unknown" });
    }
  } catch (_) {
    appState.setSnackMessage({ message: err?.message || "unknown" });
  }
}

export function useDialogStateProvider<T extends BaseType>(
  stateInitiator: () => T,
  saverFunction: (v: T, appState: IAppState) => Promise<any>,
  closeFunction?: (value?: T) => void,
  errorKeyMap?: { errorKey: string; dataKey: string }[],
) {
  const appState = useAppState();
  const [loading, setLoading] = React.useState(false);
  const state = React.useMemo(
    () => new DialogState(stateInitiator),
    [stateInitiator],
  );

  const reset = () => {
    state.reset();
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      state.resetErrors();
      await saverFunction(state.data, appState);
      state.resetTouches();

      if (closeFunction) {
        state.resetData();
        closeFunction(state.data);
        reset();
      }
    } catch (err: any) {
      processErrorFunction(state, err, appState, errorKeyMap);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    try {
      if (closeFunction) {
        setLoading(false);
        state.resetErrors();
        state.resetData();
        state.resetTouches();

        closeFunction(state.data);
        reset();
      }
    } catch (err: any) {
      processErrorFunction(state, err, appState, errorKeyMap);
    } finally {
      setLoading(false);
    }
  };

  return {
    reset,
    state,
    loading,
    handleSave,
    handleClose,
  };
}
interface useDialogStateProviderInterface<T extends BaseType> {
  (stateProvider: () => T): {
    reset: () => void;
    state: DialogState<T>;
    loading: boolean;
    handleSave: () => Promise<void>;
    handleClose?: () => void;
  };
}

export type DialogStateProviderType<T extends BaseType> = ReturnType<
  useDialogStateProviderInterface<T>
>;

export const DialogStateContext =
  React.createContext<DialogStateProviderType<any> | null>(null);

export function DialogStateProvider<
  K extends BaseType,
  T extends DialogStateProviderType<K>,
>({ state, children }: { state: T; children?: React.ReactNode }) {
  return (
    <DialogStateContext.Provider value={state}>
      {children}
    </DialogStateContext.Provider>
  );
}

export function useDialogState<T extends BaseType>() {
  const store = React.useContext(DialogStateContext);
  if (!store) {
    throw new Error("useDialogState must be used within DialogStateProvider");
  }
  return store as DialogStateProviderType<T>;
}

Usage is like below:

<DialogStateProvider state={taskState}>
  <BaseDialog open={open} handleClose={handleClose} title={title}>
    <AssignedTaskEditor isSubsequent={isSubsequent} />
  </BaseDialog>
</DialogStateProvider>

BaseDialog code is this:

import {
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  SxProps,
  Theme,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

export function BaseDialog({
  open,
  handleClose,
  title,
  children,
  sx,
}: {
  open: boolean;
  handleClose: () => void;
  title?: React.ReactNode;
  children: React.ReactNode;
  sx?: SxProps<Theme>;
}) {
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down("md"));

  return (
    <Dialog
      fullScreen={fullScreen}
      open={open}
      onClose={handleClose}
      maxWidth="lg"
      sx={{
        ...sx,
        "& .MuiDialog-container > .MuiPaper-root": {
          height: "100%",
          backgroundColor: "background.default",
          ...(sx as any)?.["& .MuiDialog-container > .MuiPaper-root"],
        },
        "& .MuiDialogContent-root": {
          flexGrow: 1,
          backgroundColor: "background.default",
          maxHeight: "80vh",
          marginBlock: 2,
          ...(sx as any)?.["& .MuiDialogContent-root"],
        },
        "& .dialogBox-Icon": {
          position: "absolute",
          right: (theme) => theme.spacing(2.5),
          top: (theme) => theme.spacing(1),
          ...(sx as any)?.["& .dialogBox-Icon"],
        },
      }}
    >
      {title && <DialogTitle>{title}</DialogTitle>}

      <IconButton onClick={handleClose} className="dialogBox-Icon" size="large">
        <CloseIcon />
      </IconButton>
      <DialogContent dividers>{children}</DialogContent>
    </Dialog>
  );
}

I want to open multiple dialog concurrently like that:

Save and add a subsequent task button should call an API endpoint to save data and it should close current modal and open another dialog and this should go forever. There should not be an end.

I have searched on internet but I couldn't find good example for this.
How can I do that with this current generic DialogProvider?


问:
Problem when multiple times asking for input using ReadString in Golang
I'm still learning to use golang.

I want to request input from the user several times using Bufio ReadString in the console. The first asks for the user Id, then the username, and lastly the user's contact number.

when running it. what happens in the console is that the 'enter a name' command is displayed immediately even though the user has not given the first input to the 'enter an id' command.

```<code>func kasirUtility() entity.Kasir {
    var id, name, contact string

    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter an ID : ")
    id, _ = reader.ReadString('\n')
    id = strings.TrimSpace(id)

    fmt.Print("Enter a name : ")
    name, _ = reader.ReadString('\n')
    name = strings.TrimSpace(name)

    fmt.Print("Enter a contact : ")
    contact, _ = reader.ReadString('\n')
    contact = strings.TrimSpace(contact)

    return entity.Kasir{Id: id, Nama: name, Kontak: contact}
}
</code>```

the result I get in the console :

```<code>Enter an ID : Enter a name : John
Enter a contact : 8773316
</code>```

how to solve it? is there something i missed?

Body:
I'm still learning to use golang.

I want to request input from the user several times using Bufio ReadString in the console. The first asks for the user Id, then the username, and lastly the user's contact number.

when running it. what happens in the console is that the 'enter a name' command is displayed immediately even though the user has not given the first input to the 'enter an id' command.

func kasirUtility() entity.Kasir {
    var id, name, contact string

    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter an ID : ")
    id, _ = reader.ReadString('\n')
    id = strings.TrimSpace(id)

    fmt.Print("Enter a name : ")
    name, _ = reader.ReadString('\n')
    name = strings.TrimSpace(name)

    fmt.Print("Enter a contact : ")
    contact, _ = reader.ReadString('\n')
    contact = strings.TrimSpace(contact)

    return entity.Kasir{Id: id, Nama: name, Kontak: contact}
}

the result I get in the console :

Enter an ID : Enter a name : John
Enter a contact : 8773316

how to solve it? is there something i missed?


问:
Force image to load while we are above the fold and it is not in the viewport
I have searched a bit and found that we should get data-src and other similar attributes in order to put that in the src to load the image. However, what if it is not using this specific attribute? What if it is by data-lzy? What if it is not a library and just using loading="lazy"?

So I thought it would be good to scroll the page completely in order to make all the images load. However, it seems it is not standard and I needed to do it programmatically and not using UIs.

This is the code that observes the page and if the image is in the viewport, it will trigger:

```<code>function isInViewport() {
  return new IntersectionObserver(entries => {
    entries.forEach(entry => callback(entry));
  }, options).observe(elem);
}

isInViewport(img, element => {

  // *** I want to focus on this line below ***
  if(element.isIntersecting) { // <------
    // img is in the viewport
  }
}, { root: null, threshold: 1 });
</code>```

My question is, is it possible to force the image which is lazy to load while not in the viewport? Something like changing the element.isIntersecting = true; in order to pretend that the image is on viewport?

Body:
I have searched a bit and found that we should get data-src and other similar attributes in order to put that in the src to load the image. However, what if it is not using this specific attribute? What if it is by data-lzy? What if it is not a library and just using loading="lazy"?

So I thought it would be good to scroll the page completely in order to make all the images load. However, it seems it is not standard and I needed to do it programmatically and not using UIs.

This is the code that observes the page and if the image is in the viewport, it will trigger:

function isInViewport() {
  return new IntersectionObserver(entries => {
    entries.forEach(entry => callback(entry));
  }, options).observe(elem);
}

isInViewport(img, element => {

  // *** I want to focus on this line below ***
  if(element.isIntersecting) { // <------
    // img is in the viewport
  }
}, { root: null, threshold: 1 });

My question is, is it possible to force the image which is lazy to load while not in the viewport? Something like changing the element.isIntersecting = true; in order to pretend that the image is on viewport?


问:
Keras CNN that uses matrix (single channel) input as its argument. And the layer between the input and first is MLP
Using Keras, I want to model CNN that uses matrix (single channel) input as its argument,
but the layer between the input and first is MLP. The convolution is carried out to the outputs of the first hidden layer

How can I code this?


问:
Dart: Add dynamic List Json into another dynamic list json where key Bank Name matches
I wanted add to one dynamic list to another. There is an existing dynamic Bank List in which there is a Bank Name and account details of a customer. Like this

Variable name existedAccountList

```<code>[
   {
      "BankName":"HDFC",
      "accountsDetails":[
         {
            "Type":"SAVINGS",
            "accReferenceNumber":"HDFC560811476",
            "AccNumber":"XXXXX1476"
         },
         {
            "Type":"current",
            "accReferenceNumber":"HDFC560811476",
            "AccNumber":"XXXXX1476"
         }
      ]
   }
]
</code>```

If user creates one or more accounts in HDFC i am storing it like this

Variable name accountList

```<code>[
   {
      "Type":"SAVINGS",
      "accReferenceNumber":"HDFC002255588",
      "AccNumber":"XXXXX1564"
   },
   {
      "Type":"current",
      "accReferenceNumber":"HDFC002255589",
      "AccNumber":"XXXXX1576"
   }
]
</code>```

I want to merge all the the accounts into  existedAccountList on key accountsDetails.

I tried to created one function but giving me type error

Uncaught Error: TypeError: Instance of 'JSArray<dynamic>': type 'JSArray<dynamic>' is not a subtype of type 'Iterable<Map<String, String>>

tried different types solutions but could not find the right solution.

```<code>List<dynamic> addAccountToExistedBankAccountList(
  List<dynamic> existedAccountList,
  List<dynamic> accountlist,
  String bankName,
) {
for (Map data in existedAccountList) {
    if (bankName.toLowerCase() == data["BankName"].toString().toLowerCase()) {
      data["accountsDetails"].addAll(accountlist);
    }
  }
  return existedAccountList;
}
</code>```

Body:
I wanted add to one dynamic list to another. There is an existing dynamic Bank List in which there is a Bank Name and account details of a customer. Like this

Variable name existedAccountList

[
   {
      "BankName":"HDFC",
      "accountsDetails":[
         {
            "Type":"SAVINGS",
            "accReferenceNumber":"HDFC560811476",
            "AccNumber":"XXXXX1476"
         },
         {
            "Type":"current",
            "accReferenceNumber":"HDFC560811476",
            "AccNumber":"XXXXX1476"
         }
      ]
   }
]

If user creates one or more accounts in HDFC i am storing it like this

Variable name accountList

[
   {
      "Type":"SAVINGS",
      "accReferenceNumber":"HDFC002255588",
      "AccNumber":"XXXXX1564"
   },
   {
      "Type":"current",
      "accReferenceNumber":"HDFC002255589",
      "AccNumber":"XXXXX1576"
   }
]

I want to merge all the the accounts into  existedAccountList on key accountsDetails.

I tried to created one function but giving me type error

Uncaught Error: TypeError: Instance of 'JSArray<dynamic>': type 'JSArray<dynamic>' is not a subtype of type 'Iterable<Map<String, String>>

tried different types solutions but could not find the right solution.

List<dynamic> addAccountToExistedBankAccountList(
  List<dynamic> existedAccountList,
  List<dynamic> accountlist,
  String bankName,
) {
for (Map data in existedAccountList) {
    if (bankName.toLowerCase() == data["BankName"].toString().toLowerCase()) {
      data["accountsDetails"].addAll(accountlist);
    }
  }
  return existedAccountList;
}


问:
Issue retrieving information about previously hosted Twitter Spaces by userID via API
I'm having issues gathering information about previously hosted Twitter Spaces based on a Twitter username. Based on the the Twitter API documentation, the GET /2/spaces/by/creator_ids endpoint retrieves scheduled and live spaces by a particular Twitter user.

Additionally, the documentation description for the ended_at response field state indicates that there is an ended state for the state response field. However, in the description for the state response field, it indicates that the two states are live and scheduled.

I've attempted to run the following curl command and receive an invalid parameter error--and it is unclear to me why.

curl "https://api.twitter.com/2/spaces/by/creator_ids?user_ids='SAMPLE_USER_ID'&state=ended” -H "Authorization: Bearer $BEARER_TOKEN"

All I am looking to do is gather information about Twitter spaces previously hosted by a user-such as date_scheduled, participant_count, start_time and end_time. Additionally, if there are other ways to gather the IDs for previously hosted Twitter spaces by a particular user that don't involve any of the Spaces API endpoints, please let me know. Thanks

I ran the following curl command--with my credentials and the creator_id of a Twitter user who has hosted multiple Twitter spaces within the past month.

curl "https://api.twitter.com/2/spaces/by/creator_ids?user_ids='SAMPLE_USER_ID'&state=ended” -H "Authorization: Bearer $BEARER_TOKEN"

I expected to receive a list of default information about a maximum of 100 of the most recent Twitter spaces hosted by the Twitter user. Instead, I received an error message indicating that state is not a valid parameter.


问:
Vitest can't read CommonJS deps
I'm trying to migrate to vitest and facing a problem. One of the tests failed because it is reading a CommonJS file from one of the dependencies. The run does not fail on other tests that not using imports from CommonJS files

This is what my defineConfig in vitest.config.ts looks like:

```<code>import graphql from '@rollup/plugin-graphql';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  plugins: [
    graphql(),
    react()
  ],
  test: {
    environment: 'jsdom',
    deps: {
      registerNodeLoader: true,
      fallbackCJS: true,
    },
  },
});

</code>```

This is the error I got:

```<code>ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js'
file extension and '/Users/nadavnassi/Desktop/dev/admin-client/node_modules/@rapidapi/ui-lib-icons/package.json'
contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
</code>```

Title: Vitest can't read CommonJS deps

Body:
I'm trying to migrate to vitest and facing a problem. One of the tests failed because it is reading a CommonJS file from one of the dependencies. The run does not fail on other tests that not using imports from CommonJS files

This is what my defineConfig in vitest.config.ts looks like:

import graphql from '@rollup/plugin-graphql';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  plugins: [
    graphql(),
    react()
  ],
  test: {
    environment: 'jsdom',
    deps: {
      registerNodeLoader: true,
      fallbackCJS: true,
    },
  },
});

This is the error I got:

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js'
file extension and '/Users/nadavnassi/Desktop/dev/admin-client/node_modules/@rapidapi/ui-lib-icons/package.json'
contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.


问:
Why is the date recorded in Jalali format different from retrieving the same date from the database?
I use Angular 15.0 and ASP.NET Core 5 and SQL Server for my project. I install Jalali-moment in my SPA project to record and get Shamsi dates. When I record the date in Jalali format (e.g. 1401-10-10) of course, the time also is attached to the date, it is converted to Gregorian date and stored in the database.

Now when I retrieve the same date from the database it shows the previous day (e.g. 1401-10-09), Of course not always? I uses Jalali pipe to show retrieved date as Shamsi format.

The Jalali pipe I used:

import * as moment from 'jalali-moment';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'jalali'
})
export class JalaliPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (value === null || value === undefined) {
      return '';
    }
    const MomentDate = moment(value, 'YYYY/MM/DD');
    return MomentDate.locale('fa').format('YYYY/M/D');
  }
}```

I know There is a time difference, but Jalali-moment package should have solved this difference problem. However I have this problem and how to solve it? best regards

Body:
I use Angular 15.0 and ASP.NET Core 5 and SQL Server for my project. I install Jalali-moment in my SPA project to record and get Shamsi dates. When I record the date in Jalali format (e.g. 1401-10-10) of course, the time also is attached to the date, it is converted to Gregorian date and stored in the database.

Now when I retrieve the same date from the database it shows the previous day (e.g. 1401-10-09), Of course not always? I uses Jalali pipe to show retrieved date as Shamsi format.

The Jalali pipe I used:

import * as moment from 'jalali-moment';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'jalali'
})
export class JalaliPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (value === null || value === undefined) {
      return '';
    }
    const MomentDate = moment(value, 'YYYY/MM/DD');
    return MomentDate.locale('fa').format('YYYY/M/D');
  }
}

I know There is a time difference, but Jalali-moment package should have solved this difference problem. However I have this problem and how to solve it? best regards


问:
Unable to deploy my ROR application to fly.io
This is my first experience deploying a rails application to production. I want to deploy to Fly.io and have created credentials and initiated files fly.io configuration files for deployment. But when I deploy I get the following error:

```<code> Starting init (commit: f447594)...
     Setting up swapspace version 1, size = 512 MiB (536866816 bytes)
     no label, UUID=af164c5a-e60d-4061-98ea-5d4af379bce2
     Preparing to run: `bin/rails fly:release` as root
     2023/01/01 07:53:05 listening on [fdaa:1:1737:a7b:80:5bf5:b65f:2]:22 (DNS: [fdaa::3]:53)
        Is the server running on host "::1" and accepting
        TCP/IP connections on port 5432?
     could not connect to server: Connection refused
        Is the server running on host "127.0.0.1" and accepting
        TCP/IP connections on port 5432?
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/postgresql_adapter.rb:37:in `postgresql_connection'
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/abstract/connection_pool.rb:700:in `checkout_new_connection'
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/abstract/connection_pool.rb:341:in `checkout'
....
...
...
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-
1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     Tasks: TOP => fly:release => db:migrate
     (See full trace by running task with --trace)
     Starting clean up.
Error release command failed, deployment aborted
</code>```

I followed the instructions given by Chris Oliver from GoRails & Deanin but that wasn't of any help as they can get it up & running with just a couple of commands. I believe my issue is in my config/database/yml file but I am able to figure out the specifics.

Any ideas on how should I debug this problem?

Body:
This is my first experience deploying a rails application to production. I want to deploy to Fly.io and have created credentials and initiated files fly.io configuration files for deployment. But when I deploy I get the following error:

 Starting init (commit: f447594)...
     Setting up swapspace version 1, size = 512 MiB (536866816 bytes)
     no label, UUID=af164c5a-e60d-4061-98ea-5d4af379bce2
     Preparing to run: `bin/rails fly:release` as root
     2023/01/01 07:53:05 listening on [fdaa:1:1737:a7b:80:5bf5:b65f:2]:22 (DNS: [fdaa::3]:53)
        Is the server running on host "::1" and accepting
        TCP/IP connections on port 5432?
     could not connect to server: Connection refused
        Is the server running on host "127.0.0.1" and accepting
        TCP/IP connections on port 5432?
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/postgresql_adapter.rb:37:in `postgresql_connection'
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/abstract/connection_pool.rb:700:in `checkout_new_connection'
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/connection_adapters/abstract/connection_pool.rb:341:in `checkout'
....
...
...
     /app/vendor/bundle/ruby/3.1.0/gems/activerecord-
1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     Tasks: TOP => fly:release => db:migrate
     (See full trace by running task with --trace)
     Starting clean up.
Error release command failed, deployment aborted

I followed the instructions given by Chris Oliver from GoRails & Deanin but that wasn't of any help as they can get it up & running with just a couple of commands. I believe my issue is in my config/database/yml file but I am able to figure out the specifics.

Any ideas on how should I debug this problem?


问:
How to clone and modify a Flutter package that depends on other hosted packages?
I'm planning to make modifications to the video_player package so I have cloned and made my own repository of it for editing.

The problem is that it for example imports another hosted package within it like this: 'package:video_player_platform_interface/video_player_platform_interface.dart'.

I tried basically copying that dart file and making a local copy in my repository but it just breaks the package and throws and Exception when it reaches relevant code, probably because even that package depends on another package itself.

How do I make changes to say, this video_player_platform_interface.dart for my own cloned package?


问:
Plot Real Time Serial Data in Python
I couldn't plot the real time serial data come from arduino.

I working on a project this project details are like that :
I have pressure sensor that detects the pressure on them probs.I transfer the pressure measured on the probes to the computer via serial port communication with the help of arduino uno.
ı can read the data come from arduino on the Spyder Editor(python)
Using this data ( 2 pressure value coming from arduino) ı have to plot  real time serial data on the GUI.
I create the GUI.
But I couldn't plot the data.
I would really appreciate any help or comments , thanks for every effort !
`

```<code># -*- coding: utf-8 -*-
"""
Created on Thu Dec 29 03:57:27 2022

@author: Berk
"""

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import numpy as np
import serial
import time
import datetime

xs=[]
ys=[]
serialPort=serial.Serial(port="COM5", baudrate=9600,
                              bytesize=8,timeout=2,stopbits=serial.STOPBITS_ONE)
cond=False
date=str(datetime.datetime.now())
date=date.replace(" ",",")
date=date.replace(":",".")

while (True):
    try:

        if (serialPort.in_waiting > 0):
            serialString=serialPort.readline()

            data=serialString.decode("utf8", errors="replace")

            replaced_data=data.replace("\r","")
            replaced_data=replaced_data.replace("\n","")
            # replaced_data=replaced_data.replace(":","-")

            print(replaced_data)

###---plot data---###
  def plot_data():
        global cond,data
        data=np.append()
        print(data)

        if(cond==True):
            a=serialPort.readline()
            a.decode()
            if(len(data<100)):
                data=np.append(data,float(a[0:4]))
            else:
                data[0:99]=data[1:100]
                data[99]=float(a[0:4])
                print(a)

            lines.set_xdata(np.arange(0,len(data)))
            lines.set_ydata(data)
            canvas.draw()

    def plot_start():
        global cond
        cond=True
        serialPort.reset_input_buffer()

    def plot_stop():
        global cond
        cond=False

    #######GUI########
    root=tk.Tk()
    root.title('Pressure Value From Sensor')
    root.configure(background='light blue')
    root.geometry("700x500")

    #####PLOTTİN ON GUI##########
    fig=Figure();
    ax=fig.add_subplot(111)

    ax.set_title('Pressure By Time')
    ax.set_xlabel('By Time')
    ax.set_ylabel('Pressure')
    ax.set_xlim(0,500)
    ax.set_ylim(0,500)
    lines=ax.plot([],[],0)

    canvas=FigureCanvasTkAgg(fig,master=root)
    canvas.get_tk_widget().place(x=10,y=10,width=500,height=400)
    canvas.draw()

    root.after(1,plot_data)

    ##button##
    root.update();
    start=tk.Button(root,text='Stop',font=('calibri',12),command=lambda:plot_start())
    start.place(x=100,y=450)

    root.update();
    start=tk.Button(root,text='Start',font=('calibri',12),command=lambda:plot_stop())
    start.place(x=start.winfo_x()+start.winfo_reqwidth()+20,y=450)

    ##startint serial port###
    serialPort=serial.Serial(port="COM5", baudrate=9600,
                                  bytesize=8,timeout=2,stopbits=serial.STOPBITS_ONE)
    serialPort.reset_input_buffer()

    root.after(1,plot_data)
    root.mainloop()

</code>```

`

Title: Plot Real Time Serial Data in Python

Body:
I couldn't plot the real time serial data come from arduino.

I working on a project this project details are like that :
I have pressure sensor that detects the pressure on them probs.I transfer the pressure measured on the probes to the computer via serial port communication with the help of arduino uno.
ı can read the data come from arduino on the Spyder Editor(python)
Using this data ( 2 pressure value coming from arduino) ı have to plot  real time serial data on the GUI.
I create the GUI.
But I couldn't plot the data.
I would really appreciate any help or comments , thanks for every effort !
`

# -*- coding: utf-8 -*-
"""
Created on Thu Dec 29 03:57:27 2022

@author: Berk
"""

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import numpy as np
import serial
import time
import datetime

xs=[]
ys=[]
serialPort=serial.Serial(port="COM5", baudrate=9600,
                              bytesize=8,timeout=2,stopbits=serial.STOPBITS_ONE)
cond=False
date=str(datetime.datetime.now())
date=date.replace(" ",",")
date=date.replace(":",".")

while (True):
    try:

        if (serialPort.in_waiting > 0):
            serialString=serialPort.readline()

            data=serialString.decode("utf8", errors="replace")

            replaced_data=data.replace("\r","")
            replaced_data=replaced_data.replace("\n","")
            # replaced_data=replaced_data.replace(":","-")

            print(replaced_data)

###---plot data---###
  def plot_data():
        global cond,data
        data=np.append()
        print(data)

        if(cond==True):
            a=serialPort.readline()
            a.decode()
            if(len(data<100)):
                data=np.append(data,float(a[0:4]))
            else:
                data[0:99]=data[1:100]
                data[99]=float(a[0:4])
                print(a)

            lines.set_xdata(np.arange(0,len(data)))
            lines.set_ydata(data)
            canvas.draw()

    def plot_start():
        global cond
        cond=True
        serialPort.reset_input_buffer()

    def plot_stop():
        global cond
        cond=False

    #######GUI########
    root=tk.Tk()
    root.title('Pressure Value From Sensor')
    root.configure(background='light blue')
    root.geometry("700x500")

    #####PLOTTİN ON GUI##########
    fig=Figure();
    ax=fig.add_subplot(111)

    ax.set_title('Pressure By Time')
    ax.set_xlabel('By Time')
    ax.set_ylabel('Pressure')
    ax.set_xlim(0,500)
    ax.set_ylim(0,500)
    lines=ax.plot([],[],0)

    canvas=FigureCanvasTkAgg(fig,master=root)
    canvas.get_tk_widget().place(x=10,y=10,width=500,height=400)
    canvas.draw()

    root.after(1,plot_data)

    ##button##
    root.update();
    start=tk.Button(root,text='Stop',font=('calibri',12),command=lambda:plot_start())
    start.place(x=100,y=450)

    root.update();
    start=tk.Button(root,text='Start',font=('calibri',12),command=lambda:plot_stop())
    start.place(x=start.winfo_x()+start.winfo_reqwidth()+20,y=450)

    ##startint serial port###
    serialPort=serial.Serial(port="COM5", baudrate=9600,
                                  bytesize=8,timeout=2,stopbits=serial.STOPBITS_ONE)
    serialPort.reset_input_buffer()

    root.after(1,plot_data)
    root.mainloop()

`


问:
How do I order related objects of ManyToMany field in Django?
So I have a ManyToMany field, and the related objects need to be ordered by id. But somehow I cannot order it as intended.
 This is how the models look like:

```<code>class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answer', null=True)
    body = models.TextField(blank=True, null=True)

class AllAnswers(models.Model):
    answers = models.ManyToManyField(Answer, null=True)
    title = models.CharField(blank=True, null=True, max_length=30)
    created_at = models.DateField(auto_now_add=True)
</code>```

Now, let's say there are five Answer objects (ordered by id) : answer1, answer2, answer3, answer4, answer5.
 In my views.py, I'm creating an AllAnswers object but cannot give order to the Answer objects, like the code below.

```<code>AllAnswers.objects.create(
    title = 'title #1',
)
new_article = AllAnswers.objects.get(title='title #1')
all_answers = Answer.objects.all().order_by('id') # This would get answer1 through answer5
new_article.answers.add(*all_answers)
</code>```

Now what I expect is the answers in new_article object to be displayed in the order I set. (by id) But in the template, the order is not the way I intended. (I can't figure out which order it is being displayed, but it definitely is NOT by id)

```<code># article.html
...
{% for a in new_article.answers.all %}
{{x.body}}
{% endfor %}
...
</code>```

Body:
So I have a ManyToMany field, and the related objects need to be ordered by id. But somehow I cannot order it as intended.
 This is how the models look like:

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answer', null=True)
    body = models.TextField(blank=True, null=True)

class AllAnswers(models.Model):
    answers = models.ManyToManyField(Answer, null=True)
    title = models.CharField(blank=True, null=True, max_length=30)
    created_at = models.DateField(auto_now_add=True)

Now, let's say there are five Answer objects (ordered by id) : answer1, answer2, answer3, answer4, answer5.
 In my views.py, I'm creating an AllAnswers object but cannot give order to the Answer objects, like the code below.

AllAnswers.objects.create(
    title = 'title #1',
)
new_article = AllAnswers.objects.get(title='title #1')
all_answers = Answer.objects.all().order_by('id') # This would get answer1 through answer5
new_article.answers.add(*all_answers)

Now what I expect is the answers in new_article object to be displayed in the order I set. (by id) But in the template, the order is not the way I intended. (I can't figure out which order it is being displayed, but it definitely is NOT by id)

# article.html
...
{% for a in new_article.answers.all %}
{{x.body}}
{% endfor %}
...


问:
django admin - add multiple entries to db with single form submit
I have a model Point where i have a field called name charField. I trying to add multiple entries on Point with single Form submission. For example, the form has textarea field where i will entry 10 names line by line and then i try to split names one by one and save to point table.

```<code>class Point(models.Model):
    name = models.CharField(blank=True)
</code>```
```<code>class PointForm(forms.ModelForm):
    pointlist = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = Point
        fields = '__all__'

    def save(self, commit=True):
        return super(Point, self).save(commit=False)
</code>```

I tried to add multiple entries with single form submission in django admin page

getting below error:
super(type, obj): obj must be an instance or subtype of type

Body:
I have a model Point where i have a field called name charField. I trying to add multiple entries on Point with single Form submission. For example, the form has textarea field where i will entry 10 names line by line and then i try to split names one by one and save to point table.

class Point(models.Model):
    name = models.CharField(blank=True)

class PointForm(forms.ModelForm):
    pointlist = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = Point
        fields = '__all__'

    def save(self, commit=True):
        return super(Point, self).save(commit=False)

I tried to add multiple entries with single form submission in django admin page

getting below error:
super(type, obj): obj must be an instance or subtype of type


问:
Finding the cause of Dill Pycapsule recursion error
I'm using the multiprocess library (note, not multiprocessing), in a notebook along with nbdev. When I change and save one of the modules in the project, which is then imported in the notebook using multiprocess, I get this error message and the processes crash:

```<code>/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py:1890: PicklingWarning: Pickling a PyCapsule (b'datetime.datetime_CAPI') does not pickle any C data structures and could cause segmentation faults or other memory errors when unpickling.
  warnings.warn('Pickling a PyCapsule (%s) does not pickle any C data structures and could cause segmentation faults or other memory errors when unpickling.' % (name,), PicklingWarning)
Process SpawnPoolWorker-8:
Traceback (most recent call last):
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/process.py", line 315, in _bootstrap
    self.run()
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/pool.py", line 114, in worker
    task = get()
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/queues.py", line 361, in get
    return _ForkingPickler.loads(res)
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 286, in loads
    return load(file, ignore, **kwds)
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 272, in load
    return Unpickler(file, ignore=ignore, **kwds).load()
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 419, in load
    obj = StockUnpickler.load(self)
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  [Previous line repeated 2986 more times]
RecursionError: maximum recursion depth exceeded
</code>```

This is somewhat generic, alluding to perhaps a problem with pickling datetime.datetime_CAPI objects. How can I start to find the source of the problem?

Body:
I'm using the multiprocess library (note, not multiprocessing), in a notebook along with nbdev. When I change and save one of the modules in the project, which is then imported in the notebook using multiprocess, I get this error message and the processes crash:

/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py:1890: PicklingWarning: Pickling a PyCapsule (b'datetime.datetime_CAPI') does not pickle any C data structures and could cause segmentation faults or other memory errors when unpickling.
  warnings.warn('Pickling a PyCapsule (%s) does not pickle any C data structures and could cause segmentation faults or other memory errors when unpickling.' % (name,), PicklingWarning)
Process SpawnPoolWorker-8:
Traceback (most recent call last):
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/process.py", line 315, in _bootstrap
    self.run()
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/pool.py", line 114, in worker
    task = get()
  File "/home/user/code/env/lib/python3.8/site-packages/multiprocess/queues.py", line 361, in get
    return _ForkingPickler.loads(res)
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 286, in loads
    return load(file, ignore, **kwds)
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 272, in load
    return Unpickler(file, ignore=ignore, **kwds).load()
  File "/home/user/code/env/lib/python3.8/site-packages/dill/_dill.py", line 419, in load
    obj = StockUnpickler.load(self)
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  File "/home/user/code/env/lib/python3.8/site-packages/fastcore/basics.py", line 877, in __getattr__
    if not self.ready:
  [Previous line repeated 2986 more times]
RecursionError: maximum recursion depth exceeded

This is somewhat generic, alluding to perhaps a problem with pickling datetime.datetime_CAPI objects. How can I start to find the source of the problem?


问:
How to cancel a script after it has started Lua
If I start my script then realise I pressed the wrong button, or don't want it to run all the way to the end, can I add something to the code that if I press the button again, or another button if it can't be the same, it will immediately stop the script?

This is my current script

```<code>    if (event == "G_PRESSED" and arg == 4 and GetMKeyState("kb") == 3) then
    MoveMouseTo( 36165, 57821)
    Sleep(math.random(10, 25))
    PressMouseButton(3)
    ReleaseMouseButton(3)
    Sleep(math.random(40, 135))
    MoveMouseTo( 36131, 59461)
    Sleep(math.random(30, 65))
    PressKey ("lalt")
    Sleep(math.random(30, 65))
    PressKey ("X")
    Sleep(math.random(30, 65))
    ReleaseKey ("lalt")
    ReleaseKey ("X")
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(math.random(2220, 2270))
    MoveMouseTo( 38932, 56060)
    Sleep(math.random(10, 25))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(math.random(40, 135))
    MoveMouseTo( 2595, 3037)
    Sleep(math.random(40, 135))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    MoveMouseTo( 4166, 1518)
    Sleep(math.random(250, 350))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    MoveMouseTo( 38932, 56060)
    Sleep(math.random(40, 135))
    PressMouseButton(3)
    ReleaseMouseButton(3)
    Sleep(math.random(40, 135))
    MoveMouseTo( 38590, 57882)
    Sleep(math.random(40, 135))
    PressKey ("lalt")
    Sleep(math.random(40, 135))
    PressKey ("X")
    Sleep(math.random(40, 135))
    ReleaseKey ("lalt")
    ReleaseKey ("X")
    Sleep(math.random(40, 135))
    PressKey ("O")
    Sleep(math.random(40, 135))
    ReleaseKey ("O")
    Sleep(200)
    MoveMouseTo( 54436, 55453)
    Sleep(math.random(40, 135))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(400)
    MoveMouseTo( 54299, 48650)
       Sleep(150)
       PressMouseButton(1)
       ReleaseMouseButton(1)
    end
</code>```

Body:
If I start my script then realise I pressed the wrong button, or don't want it to run all the way to the end, can I add something to the code that if I press the button again, or another button if it can't be the same, it will immediately stop the script?

This is my current script

    if (event == "G_PRESSED" and arg == 4 and GetMKeyState("kb") == 3) then
    MoveMouseTo( 36165, 57821)
    Sleep(math.random(10, 25))
    PressMouseButton(3)
    ReleaseMouseButton(3)
    Sleep(math.random(40, 135))
    MoveMouseTo( 36131, 59461)
    Sleep(math.random(30, 65))
    PressKey ("lalt")
    Sleep(math.random(30, 65))
    PressKey ("X")
    Sleep(math.random(30, 65))
    ReleaseKey ("lalt")
    ReleaseKey ("X")
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(math.random(2220, 2270))
    MoveMouseTo( 38932, 56060)
    Sleep(math.random(10, 25))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(math.random(40, 135))
    MoveMouseTo( 2595, 3037)
    Sleep(math.random(40, 135))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    MoveMouseTo( 4166, 1518)
    Sleep(math.random(250, 350))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    MoveMouseTo( 38932, 56060)
    Sleep(math.random(40, 135))
    PressMouseButton(3)
    ReleaseMouseButton(3)
    Sleep(math.random(40, 135))
    MoveMouseTo( 38590, 57882)
    Sleep(math.random(40, 135))
    PressKey ("lalt")
    Sleep(math.random(40, 135))
    PressKey ("X")
    Sleep(math.random(40, 135))
    ReleaseKey ("lalt")
    ReleaseKey ("X")
    Sleep(math.random(40, 135))
    PressKey ("O")
    Sleep(math.random(40, 135))
    ReleaseKey ("O")
    Sleep(200)
    MoveMouseTo( 54436, 55453)
    Sleep(math.random(40, 135))
    PressMouseButton(1)
    ReleaseMouseButton(1)
    Sleep(400)
    MoveMouseTo( 54299, 48650)
       Sleep(150)
       PressMouseButton(1)
       ReleaseMouseButton(1)
    end


问:
Shopify - How to complete abandoned checkout using Graphql
I have created abandoned checkout using "checkoutcreate" mutation of the Shopify storefront API. It is successfully created, but how do I mark it as completed using Rest API or Graphql API, I have tried the "checkoutCompleteFree" mutation, but it throws a "Payment Pending" error.

I have tried to mark it from Shopify admin too, but it is not possible from there too, they just give the option to archive.


问:
Firebase authentication email goes to spam when started using a custom domain?
I have this case where when I switched to production and all the sudden all firebase auth emails go to spam, I rest all setting back to default yet it keeps happening, any idea how to fix this I mean before it was working like charm and all of it went to the main box.. now it goes to spam.