问:
How to check in react axios response if response is NotFound()
I am making an api call from React app with axios.

The user selects 2 values from 2 dropdowns, and the api call is made using these 2 values. Normally the response will be an object, but occassionally if the user selects 2 values which dont have a match, then it wont return anything.

I want to ensure a message is displayed if nothing exists for those 2 items.

Currently in my axios response if nothing is return I get a long bunch of what looks like the index html page.

```<code><!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><script defer="defer" src="/static/js/main.adebe8fe.js"></script><link href="/static/css/main.aa245bf1.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
</code>```

I am getting the data from a c# controller,

```<code>[HttpGet("search/{antifungal}/{interacting}")]
        public async Task<ActionResult<DrugInteractionDTO>> getAntifungalInteraction(string antifungal, string interacting)
        {
            var interactions =  await _context.DrugInteractions
            .Include(di => di.AntifungalAgent)
            .Include(di => di.InteractingDrug)
            .Where(di => di.AntifungalAgent.Name.ToLower() == antifungal.ToLower())
            .Where(di => di.InteractingDrug.GenericName.ToLower() == interacting.ToLower())
            .Select(x => new DrugInteractionDTO
            {
                Severity = x.Severity,
                SeverityAsString = x.Severity.ToString(),
                ProDetailedInformation = x.ProDetailedInformation,
                BasicDetailedInformation = x.BasicDetailedInformation,
                Antifungal = x.AntifungalAgent.Name,
                InteractingDrug = x.InteractingDrug.GenericName,
                ID = x.ID
            }).FirstOrDefaultAsync();

            if (interactions == null) return NotFound();

            return interactions;
        }
</code>```

Using swagger if I enter 2 items in the query that dont exist I get

```<code>{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-29b4bb56b99fe26416be4e3c09add6b7-dc13efbf731e6a72-00"
}
</code>```

So I would have thought calling console.log(response.data) in my axios call would log 404, but it just gives undefined`

This is currently what I have in React,

```<code>const getInteractionDetails = () => {
  agent.drugInteractions.getIndividual(antifungalDrug, interactingDrug)
  .then((response) => {
    console.log(response.status)
    if(response.status === 404){
      setError('No interaction exists')
    } else {
      setInteractionDetails(response)
    }

  })
  .catch(error => console.log(error))
}
</code>```

How come status isnt being shown in my axios response?

Body:
I am making an api call from React app with axios.

The user selects 2 values from 2 dropdowns, and the api call is made using these 2 values. Normally the response will be an object, but occassionally if the user selects 2 values which dont have a match, then it wont return anything.

I want to ensure a message is displayed if nothing exists for those 2 items.

Currently in my axios response if nothing is return I get a long bunch of what looks like the index html page.

<!doctype html><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><link href="/static/css/main.aa245bf1.css" rel="stylesheet">You need to enable JavaScript to run this app.

I am getting the data from a c# controller,

[HttpGet("search/{antifungal}/{interacting}")]
        public async Task<ActionResult<DrugInteractionDTO>> getAntifungalInteraction(string antifungal, string interacting)
        {
            var interactions =  await _context.DrugInteractions
            .Include(di => di.AntifungalAgent)
            .Include(di => di.InteractingDrug)
            .Where(di => di.AntifungalAgent.Name.ToLower() == antifungal.ToLower())
            .Where(di => di.InteractingDrug.GenericName.ToLower() == interacting.ToLower())
            .Select(x => new DrugInteractionDTO
            {
                Severity = x.Severity,
                SeverityAsString = x.Severity.ToString(),
                ProDetailedInformation = x.ProDetailedInformation,
                BasicDetailedInformation = x.BasicDetailedInformation,
                Antifungal = x.AntifungalAgent.Name,
                InteractingDrug = x.InteractingDrug.GenericName,
                ID = x.ID
            }).FirstOrDefaultAsync();

            if (interactions == null) return NotFound();

            return interactions;
        }

Using swagger if I enter 2 items in the query that dont exist I get

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-29b4bb56b99fe26416be4e3c09add6b7-dc13efbf731e6a72-00"
}

So I would have thought calling console.log(response.data) in my axios call would log 404, but it just gives undefined`

This is currently what I have in React,

const getInteractionDetails = () => {
  agent.drugInteractions.getIndividual(antifungalDrug, interactingDrug)
  .then((response) => {
    console.log(response.status)
    if(response.status === 404){
      setError('No interaction exists')
    } else {
      setInteractionDetails(response)
    }

  })
  .catch(error => console.log(error))
}

How come status isnt being shown in my axios response?


来源: stackexchange

问:
How do I align those divs perfectly?
I am making a website with some facts and I made a "card" for each fact. It includes an image, a title and the fact itself.

When I display it, I get this. It automatically displays from mysql server. I expect it to be aligned and perfect.

Example of unaligned cards

This is the index.js code (using express, mysql and ejs), index.ejs and css code:

INDEX.JS

app.get('/', (req, res) => {
    connection.query('SELECT * FROM facts WHERE 1', function (error, results, fields) {
        if (error) throw error;
        console.log(results.length)
        var html = '';
        for (var i = 0; i < results.length; i++) {
            html+=`

${results[i].title}

${results[i].fact}

            `;
        }

        res.render(__dirname + '/views/index.ejs', {results: html})
    })

})
```
<p>INDEX.EJS</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <%- include('components/head.ejs') %>
</head>
<body>
    <%- include('components/menu.ejs') %>
    <div style="margin-left:15%;padding:1px 16px;height:1000px;">
        <h1>Welcome everyone</h1>
        <div class="container">
            <%- results %>
        </div>
    </div>

</body>
</html>

</code>```

CSS

@font-face {
    font-family: 'Longreach';
    src: url('Longreach.otf');
}

@font-face {
    font-family: 'Gemstone';
    src: url('Gemstone.ttf');
}

@font-face {
    font-family: 'Roboto';
    src: url('Roboto.ttf');
}

h1 {
    font-family: 'Gemstone';
    -webkit-text-stroke: 1px rgb(0, 0, 0);
    color: white;
    font-size: 60px;
}

p {
    font-size: 20px;
}

* {
    font-family: Roboto, Helvetica, sans-serif;
}

body {
    background-color: rgb(232, 232, 232);
    margin: 0;

}

.container .special {
    display: inline-block !important;
}

.special {
    display: inline-block !important;
    height: 500px;
    width: 400px;
    border: 1px solid black;
    margin: 5px;
    padding: 5px;
    text-align: center;
    margin-left: 5%;
}

.special img {
    width: 100%;
    height: 50%;
    padding: 0 !important;
    margin: 0 !important;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 15%;
    background-color: #f1f1f1;
    position: fixed;
    height: 100%;
    overflow: auto;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a.active {
    background-color: #04AA6D;
    color: white;
}

li a:hover:not(.active) {
    background-color: #555;
    color: white;
}

```
<p>menu.ejs (component)</p>
<pre class="lang-html prettyprint-override"><code><ul>
    <li>Home</li>
    <li>Editor login</li>
</ul>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I align those divs perfectly?

Body:
I am making a website with some facts and I made a "card" for each fact. It includes an image, a title and the fact itself.

When I display it, I get this. It automatically displays from mysql server. I expect it to be aligned and perfect.

Example of unaligned cards

This is the index.js code (using express, mysql and ejs), index.ejs and css code:

INDEX.JS

app.get('/', (req, res) => {
    connection.query('SELECT * FROM facts WHERE 1', function (error, results, fields) {
        if (error) throw error;
        console.log(results.length)
        var html = '';
        for (var i = 0; i < results.length; i++) {
            html+=`

${results[i].title}

${results[i].fact}

            `;
        }

        res.render(__dirname + '/views/index.ejs', {results: html})
    })

})

INDEX.EJS

<!DOCTYPE html>

    <%- include('components/head.ejs') %>

    <%- include('components/menu.ejs') %>

Welcome everyone

            <%- results %>

CSS

@font-face {
    font-family: 'Longreach';
    src: url('Longreach.otf');
}

@font-face {
    font-family: 'Gemstone';
    src: url('Gemstone.ttf');
}

@font-face {
    font-family: 'Roboto';
    src: url('Roboto.ttf');
}

h1 {
    font-family: 'Gemstone';
    -webkit-text-stroke: 1px rgb(0, 0, 0);
    color: white;
    font-size: 60px;
}

p {
    font-size: 20px;
}

* {
    font-family: Roboto, Helvetica, sans-serif;
}

body {
    background-color: rgb(232, 232, 232);
    margin: 0;

}

.container .special {
    display: inline-block !important;
}

.special {
    display: inline-block !important;
    height: 500px;
    width: 400px;
    border: 1px solid black;
    margin: 5px;
    padding: 5px;
    text-align: center;
    margin-left: 5%;
}

.special img {
    width: 100%;
    height: 50%;
    padding: 0 !important;
    margin: 0 !important;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 15%;
    background-color: #f1f1f1;
    position: fixed;
    height: 100%;
    overflow: auto;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a.active {
    background-color: #04AA6D;
    color: white;
}

li a:hover:not(.active) {
    background-color: #555;
    color: white;
}

menu.ejs (component)

Home

Editor login


问:
How do I prevent the infinite rendering of message tiles despite the number of chat rooms there are?
To whom it may concern,

I am working on a project in which I am required to work on functionality for chat rooms. I have the bulk of the code made and most of it runs just fine, but I am having issues rendering the user message tiles to the chats scroll list, or the tile the user clicks to enter a specific chat room. My problem is that I am trying to render only as many chat rooms as there are in the database for the user, and right now there is only 1 in the database, meaning only 1 message tile should be rendered. However, when the message tile is rendered, it is just rendered infinitely down the list, over and over. Even after adding a second user to the Added Users collection in Cloud Firestore, only the first user is ever rendered, and infinitely at that. How can I make it to where there are only as many message tiles as there are added users in the database and each user in the Added Users collection is only rendered once? I need this issue fixed in order to complete the functionality of chatting in my application, since the person the user chats with is dependent on which message tile they tap.

Please note that I am using Android Studio, Flutter/Dart, Firebase Authentication (though this is not very relevant in this case), and Firebase Cloud Firestore.

To be clear, I expect to see one message tile per Added Users in the Cloud Firestore database, and to have the ability to scroll through this list of users if there are more than the screen can hold. So far, I have tried debugging to see the issue. However, I believe that the infinite render issue is an issue with the logic of my code, which is why I am posting on Stack Overflow.

Below are pictures of the chats scroll page itself and the Cloud Firestore database for this project. Below these pictures is the code responsible for the chats scroll list page:

Pictures:

The chats scroll list. Message tiles can be seen here, being infinitely rendered

Picture of the Cloud Firestore database for this project. Note that Added Users is a subcollection of a user document within the collection Users

Code:

```<code>class ChatsPage extends StatelessWidget{
  const ChatsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context){
    UserObject testReceiver = UserObject("test2@gmail.com", "MyTestUser2", "Test", "2", "456", "Test", "Test", "Test", "Test", 123456, "https://imgv3.fotor.com/images/blog-cover-image/10-profile-picture-ideas-to-make-you-stand-out.jpg");
    // Create a custom scroll view to list user chats.
    return CustomScrollView(
      // Using slivers...
      slivers: [
        // Create a sliver app bar.
        SliverAppBar(
          // Set the color to whatever is necessary.
          backgroundColor: Colors.black,
          // Center the title text.
          centerTitle: true,
          // Set the title text.
          title: Text("Chats Page"),
          // Create an IconBackground object to display the back arrow icon.
          leading: IconBackground(
              // Set the icon itself to the back arrow icon.
              icon: Icons.arrow_back,
              // Upon pressing the icon...
              onTap: (){
                // Simply return to the previous screen.
                Navigator.pop(context);
              }),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 10.0),
                // Add chat functionality should be implemented here.
              child: IconBackground( icon: Icons.add, onTap: (){ print("Must complete add chat functionality"); })
            ),
            Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: IconBackground(icon: Icons.search, onTap: (){ print("Must complete search functionality"); })
            )
          ],
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return StreamBuilder<QuerySnapshot>(
                      stream: FirebaseFirestore.instance.collection("Users").doc(FirebaseAuth.instance.currentUser?.uid.toString()).collection("Added Users").snapshots(),
                      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                        if(snapshot.hasError) {
                          return const Text('Something went wrong');
                        }
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const Text("Loading");
                        }
                        return SizedBox(
                          height: 75,
                          child: ListView(
                            physics: const NeverScrollableScrollPhysics(),
                            children: snapshot.data!.docs.map((DocumentSnapshot document){
                              UserObject docUser = UserObject(
                                  document.get("email"),
                                  document.get("userName"),
                                  document.get("firstName"),
                                  document.get("lastName"),
                                  document.get("userID"),
                                  document.get("birthday"),
                                  document.get("university"),
                                  document.get("city"),
                                  document.get("state"),
                                  document.get("zipCode"),
                                  document.get("profilePictureURL")
                              );
                              return _MessageChatTile(user: docUser);
                            }).toList(),
                          ),
                        );
                      },
                    );
              }
          ),
        )
      ],
    );
  }
}
</code>```
```<code>class _MessageChatTile extends StatelessWidget{
  const _MessageChatTile({
    Key? key,
    required this.user
  }) : super(key: key);

  final UserObject user;

  // There are 19 children in this one function.
  @override
  Widget build(BuildContext context){
    // log("Hello? Does this work?");
    return Material(
        color: Colors.black,
        child: InkWell(
          onTap: () {
            Navigator.of(context).push(ChatRoom.routeMessage(user));
          },
          child: Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(11.0),
                child: Avatar.medium(url: user.profilePictureURL),
              ),
              Expanded(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      DefaultTextStyle(
                        style: const TextStyle(
                            fontSize: 20,
                            color: Colors.white,
                            letterSpacing: 0.2,
                            wordSpacing: 1.5
                          // fontWeight: FontWeight.w900
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(user.userName, overflow: TextOverflow.ellipsis),
                            // TODO: Add functionality for seeing messages outside of chat room.
                            //Text(messageData.message, overflow: TextOverflow.ellipsis)
                          ],
                        ),
                      )
                    ]
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 20.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    DefaultTextStyle(
                        style: const TextStyle(
                            fontSize: 11,
                            letterSpacing: -0.2,
                            fontWeight: FontWeight.w600
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const SizedBox(
                              height: 4,
                            ),
                            // TODO: Add functionality for seeing message dates outside of chat room.
                            // Text(
                            //   messageData.dateMessage.toUpperCase(),
                            //   style: const TextStyle(
                            //       fontSize: 11,
                            //       letterSpacing: -0.2,
                            //       fontWeight: FontWeight.w600,
                            //       color: Colors.blueGrey
                            //   ),
                            // ),
                            const SizedBox(
                              height: 8,
                            ),
                            Container(
                              width: 18,
                              height: 18,
                              decoration: const BoxDecoration(
                                  color: Colors.blueAccent,
                                  shape: BoxShape.circle
                              ),
                              child: const Center(
                                child: Text(
                                  '1',
                                  style: TextStyle(
                                      fontSize: 10,
                                      color: Colors.white
                                  ),
                                ),
                              ),
                            )
                          ],
                        )
                    )
                  ],
                ),
              )
            ],
          ),
        )
    );
  }
}
</code>```

Body:
To whom it may concern,

I am working on a project in which I am required to work on functionality for chat rooms. I have the bulk of the code made and most of it runs just fine, but I am having issues rendering the user message tiles to the chats scroll list, or the tile the user clicks to enter a specific chat room. My problem is that I am trying to render only as many chat rooms as there are in the database for the user, and right now there is only 1 in the database, meaning only 1 message tile should be rendered. However, when the message tile is rendered, it is just rendered infinitely down the list, over and over. Even after adding a second user to the Added Users collection in Cloud Firestore, only the first user is ever rendered, and infinitely at that. How can I make it to where there are only as many message tiles as there are added users in the database and each user in the Added Users collection is only rendered once? I need this issue fixed in order to complete the functionality of chatting in my application, since the person the user chats with is dependent on which message tile they tap.

Please note that I am using Android Studio, Flutter/Dart, Firebase Authentication (though this is not very relevant in this case), and Firebase Cloud Firestore.

To be clear, I expect to see one message tile per Added Users in the Cloud Firestore database, and to have the ability to scroll through this list of users if there are more than the screen can hold. So far, I have tried debugging to see the issue. However, I believe that the infinite render issue is an issue with the logic of my code, which is why I am posting on Stack Overflow.

Below are pictures of the chats scroll page itself and the Cloud Firestore database for this project. Below these pictures is the code responsible for the chats scroll list page:

Pictures:

The chats scroll list. Message tiles can be seen here, being infinitely rendered

Picture of the Cloud Firestore database for this project. Note that Added Users is a subcollection of a user document within the collection Users

Code:

class ChatsPage extends StatelessWidget{
  const ChatsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context){
    UserObject testReceiver = UserObject("test2@gmail.com", "MyTestUser2", "Test", "2", "456", "Test", "Test", "Test", "Test", 123456, "https://imgv3.fotor.com/images/blog-cover-image/10-profile-picture-ideas-to-make-you-stand-out.jpg");
    // Create a custom scroll view to list user chats.
    return CustomScrollView(
      // Using slivers...
      slivers: [
        // Create a sliver app bar.
        SliverAppBar(
          // Set the color to whatever is necessary.
          backgroundColor: Colors.black,
          // Center the title text.
          centerTitle: true,
          // Set the title text.
          title: Text("Chats Page"),
          // Create an IconBackground object to display the back arrow icon.
          leading: IconBackground(
              // Set the icon itself to the back arrow icon.
              icon: Icons.arrow_back,
              // Upon pressing the icon...
              onTap: (){
                // Simply return to the previous screen.
                Navigator.pop(context);
              }),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 10.0),
                // Add chat functionality should be implemented here.
              child: IconBackground( icon: Icons.add, onTap: (){ print("Must complete add chat functionality"); })
            ),
            Padding(
              padding: const EdgeInsets.only(right: 15.0),
              child: IconBackground(icon: Icons.search, onTap: (){ print("Must complete search functionality"); })
            )
          ],
        ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return StreamBuilder<QuerySnapshot>(
                      stream: FirebaseFirestore.instance.collection("Users").doc(FirebaseAuth.instance.currentUser?.uid.toString()).collection("Added Users").snapshots(),
                      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                        if(snapshot.hasError) {
                          return const Text('Something went wrong');
                        }
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const Text("Loading");
                        }
                        return SizedBox(
                          height: 75,
                          child: ListView(
                            physics: const NeverScrollableScrollPhysics(),
                            children: snapshot.data!.docs.map((DocumentSnapshot document){
                              UserObject docUser = UserObject(
                                  document.get("email"),
                                  document.get("userName"),
                                  document.get("firstName"),
                                  document.get("lastName"),
                                  document.get("userID"),
                                  document.get("birthday"),
                                  document.get("university"),
                                  document.get("city"),
                                  document.get("state"),
                                  document.get("zipCode"),
                                  document.get("profilePictureURL")
                              );
                              return _MessageChatTile(user: docUser);
                            }).toList(),
                          ),
                        );
                      },
                    );
              }
          ),
        )
      ],
    );
  }
}

class _MessageChatTile extends StatelessWidget{
  const _MessageChatTile({
    Key? key,
    required this.user
  }) : super(key: key);

  final UserObject user;

  // There are 19 children in this one function.
  @override
  Widget build(BuildContext context){
    // log("Hello? Does this work?");
    return Material(
        color: Colors.black,
        child: InkWell(
          onTap: () {
            Navigator.of(context).push(ChatRoom.routeMessage(user));
          },
          child: Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(11.0),
                child: Avatar.medium(url: user.profilePictureURL),
              ),
              Expanded(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      DefaultTextStyle(
                        style: const TextStyle(
                            fontSize: 20,
                            color: Colors.white,
                            letterSpacing: 0.2,
                            wordSpacing: 1.5
                          // fontWeight: FontWeight.w900
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(user.userName, overflow: TextOverflow.ellipsis),
                            // TODO: Add functionality for seeing messages outside of chat room.
                            //Text(messageData.message, overflow: TextOverflow.ellipsis)
                          ],
                        ),
                      )
                    ]
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 20.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    DefaultTextStyle(
                        style: const TextStyle(
                            fontSize: 11,
                            letterSpacing: -0.2,
                            fontWeight: FontWeight.w600
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const SizedBox(
                              height: 4,
                            ),
                            // TODO: Add functionality for seeing message dates outside of chat room.
                            // Text(
                            //   messageData.dateMessage.toUpperCase(),
                            //   style: const TextStyle(
                            //       fontSize: 11,
                            //       letterSpacing: -0.2,
                            //       fontWeight: FontWeight.w600,
                            //       color: Colors.blueGrey
                            //   ),
                            // ),
                            const SizedBox(
                              height: 8,
                            ),
                            Container(
                              width: 18,
                              height: 18,
                              decoration: const BoxDecoration(
                                  color: Colors.blueAccent,
                                  shape: BoxShape.circle
                              ),
                              child: const Center(
                                child: Text(
                                  '1',
                                  style: TextStyle(
                                      fontSize: 10,
                                      color: Colors.white
                                  ),
                                ),
                              ),
                            )
                          ],
                        )
                    )
                  ],
                ),
              )
            ],
          ),
        )
    );
  }
}


问:
EHCache has too many misses on the heap tier
I am using a standalone EHcache 3.10 with heap tier, and disk tier.
The heap is configured to contain 100 entries with no expirations.
Actually, the algorithm insert only 30 entries into the cache, but it perform many "updates" and "reads" of these 30 entries.

Before I insert a new entry to the cache, there is a check if the entry already exist.

Therefore when I check ehcache statistics, I expect to see only 30 - misses on the heap tier, and 30 misses on the disk tier. But,

Instead I get 9806 misses on the heap tier, and 9806 hits on the disk tier. (Meaning 9806 times ehcache did not found the entry on the heap, but instead it was found on the disk)
These numbers make no sense to me, since the heap tier should contain 100 entries, so, why there are so many misses?

Here is my configuration:

```<code>      statisticsService = new DefaultStatisticsService();

      // create temp dir
      Path cacheDirectory = getCacheDirectory();

      ResourcePoolsBuilder resourcePoolsBuilder =
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .heap(100, EntryUnit.ENTRIES)
              .disk(Long.MAX_VALUE, MemoryUnit.B, true)
              ;

      CacheConfigurationBuilder cacheConfigurationBuilder =
          CacheConfigurationBuilder.newCacheConfigurationBuilder(
                  String.class, // The cache key
                  ARFileImpl.class, // The cache value
                  resourcePoolsBuilder)
              .withExpiry(ExpiryPolicyBuilder.noExpiration()) // No expiration
              .withResilienceStrategy(new ThrowingResilienceStrategy<>())
              .withSizeOfMaxObjectGraph(100000);

      // Create the cache manager
      cacheManager =
          CacheManagerBuilder.newCacheManagerBuilder()
              // Set the persistent directory
              .with(CacheManagerBuilder.persistence(cacheDirectory.toFile()))
              .withCache(ARFILE_CACHE_NAME, cacheConfigurationBuilder)
              .using(statisticsService)
              .build(true);
</code>```

Here is the result of the statistics:

Cache stats:

```<code>CacheExpirations: 0
CacheEvictions: 0
CacheGets: 6669684
CacheHits: 6669684
CacheMisses: 0
CacheHitPercentage: 100.0
CacheMissPercentage: 0.0
CachePuts: 10525
CacheRemovals: 0
</code>```

Heap stats:

```<code>    AllocatedByteSize: -1
    Mappings: 30
    Evictions: 0
    Expirations: 0
    Hits: 6659878
    Misses: 9806
    OccupiedByteSize: -1
    Puts: 0
    Removals: 0
</code>```

Disk stats:

```<code>    AllocatedByteSize: 22429696
    Mappings: 30
    Evictions: 0
    Expirations: 0
    Hits: 9806
    Misses: 0
    OccupiedByteSize: 9961952
    Puts: 10525
    Removals: 0
</code>```

The reason for asking this question is that there are a lot of redundant disk reads, which result with performance degradation.

Body:
I am using a standalone EHcache 3.10 with heap tier, and disk tier.
The heap is configured to contain 100 entries with no expirations.
Actually, the algorithm insert only 30 entries into the cache, but it perform many "updates" and "reads" of these 30 entries.

Before I insert a new entry to the cache, there is a check if the entry already exist.

Therefore when I check ehcache statistics, I expect to see only 30 - misses on the heap tier, and 30 misses on the disk tier. But,

Instead I get 9806 misses on the heap tier, and 9806 hits on the disk tier. (Meaning 9806 times ehcache did not found the entry on the heap, but instead it was found on the disk)
These numbers make no sense to me, since the heap tier should contain 100 entries, so, why there are so many misses?

Here is my configuration:

      statisticsService = new DefaultStatisticsService();

      // create temp dir
      Path cacheDirectory = getCacheDirectory();

      ResourcePoolsBuilder resourcePoolsBuilder =
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .heap(100, EntryUnit.ENTRIES)
              .disk(Long.MAX_VALUE, MemoryUnit.B, true)
              ;

      CacheConfigurationBuilder cacheConfigurationBuilder =
          CacheConfigurationBuilder.newCacheConfigurationBuilder(
                  String.class, // The cache key
                  ARFileImpl.class, // The cache value
                  resourcePoolsBuilder)
              .withExpiry(ExpiryPolicyBuilder.noExpiration()) // No expiration
              .withResilienceStrategy(new ThrowingResilienceStrategy<>())
              .withSizeOfMaxObjectGraph(100000);

      // Create the cache manager
      cacheManager =
          CacheManagerBuilder.newCacheManagerBuilder()
              // Set the persistent directory
              .with(CacheManagerBuilder.persistence(cacheDirectory.toFile()))
              .withCache(ARFILE_CACHE_NAME, cacheConfigurationBuilder)
              .using(statisticsService)
              .build(true);

Here is the result of the statistics:

Cache stats:

CacheExpirations: 0
CacheEvictions: 0
CacheGets: 6669684
CacheHits: 6669684
CacheMisses: 0
CacheHitPercentage: 100.0
CacheMissPercentage: 0.0
CachePuts: 10525
CacheRemovals: 0

Heap stats:

    AllocatedByteSize: -1
    Mappings: 30
    Evictions: 0
    Expirations: 0
    Hits: 6659878
    Misses: 9806
    OccupiedByteSize: -1
    Puts: 0
    Removals: 0

Disk stats:

    AllocatedByteSize: 22429696
    Mappings: 30
    Evictions: 0
    Expirations: 0
    Hits: 9806
    Misses: 0
    OccupiedByteSize: 9961952
    Puts: 10525
    Removals: 0

The reason for asking this question is that there are a lot of redundant disk reads, which result with performance degradation.


问:
How to build customized dbt logging capabilities / extend already existing logging solutions
I am looking for a way to build a customized logging. I am aware of the existing packages like dbt_artifacts, elementary etc. For my use case I'd like to add further information related to the latest run which can be queried from the model itself. An example for the logging table could be:

country
inserted_at
batch_id
exported_at
invocation_id
database_name
schema_name
etc.

Cell 1
Cell 2
Cell 3
Cell 4
Cell 5
Cell 6
Cell 7
Cell 9

The first four columns can be derived by the model itself (fyi: the information are part of the data which get pushed in my staging area; with every run I want to process data from one batch related to one country etc., so the information will be distinct), the other columns as far as I know can be derived from the internal results variable (very well shown under the following link https://medium.com/@oravidov/dbt-observability-101-how-to-monitor-dbt-run-and-test-results-f7e5f270d6b6).

I'm wondering how to extend the solution described in the link above by the information which can be queried after the model has been run (first four columns in the table above). I'm thinking of a combination of the solution presented at the link (which already shows how to access metadata like invocation_id, unique_id, rows_affected etc.) and adding info from the model itself.

My ideas go in the following direction:

- Make use of the macros parse_dbt_results and log_dbt_results shown at the link by Or Avidov.

```<code>{% macro parse_dbt_results(results) %}
    -- Create a list of parsed results
    {%- set parsed_results = [] %}
    -- Flatten results and add to list
    {% for run_result in results %}
        -- Convert the run result object to a simple dictionary
        {% set run_result_dict = run_result.to_dict() %}
        -- Get the underlying dbt graph node that was executed
        {% set node = run_result_dict.get('node') %}
        {% set rows_affected = run_result_dict.get('adapter_response', {}).get('rows_affected', 0) %}
        {%- if not rows_affected -%}
            {% set rows_affected = 0 %}
        {%- endif -%}
        {% set parsed_result_dict = {
                'result_id': invocation_id ~ '.' ~ node.get('unique_id'),
                'invocation_id': invocation_id,
                'unique_id': node.get('unique_id'),
                'database_name': node.get('database'),
                'schema_name': node.get('schema'),
                'name': node.get('name'),
                'resource_type': node.get('resource_type'),
                'status': run_result_dict.get('status'),
                'execution_time': run_result_dict.get('execution_time'),
                'rows_affected': rows_affected
                }%}
        {% do parsed_results.append(parsed_result_dict) %}
    {% endfor %}
    {{ return(parsed_results) }}
{% endmacro %}
</code>```
```<code>{% macro log_dbt_results(results) %}
    -- depends_on: {{ ref('dbt_results') }}
    {%- if execute -%}
        {%- set parsed_results = parse_dbt_results(results) -%}
        {%- if parsed_results | length  > 0 -%}
            {% set insert_dbt_results_query -%}
                insert into {{ ref('dbt_results') }}
                    (
                        result_id,
                        invocation_id,
                        unique_id,
                        database_name,
                        schema_name,
                        name,
                        resource_type,
                        status,
                        execution_time,
                        rows_affected
                ) values
                    {%- for parsed_result_dict in parsed_results -%}
                        (
                            '{{ parsed_result_dict.get('result_id') }}',
                            '{{ parsed_result_dict.get('invocation_id') }}',
                            '{{ parsed_result_dict.get('unique_id') }}',
                            '{{ parsed_result_dict.get('database_name') }}',
                            '{{ parsed_result_dict.get('schema_name') }}',
                            '{{ parsed_result_dict.get('name') }}',
                            '{{ parsed_result_dict.get('resource_type') }}',
                            '{{ parsed_result_dict.get('status') }}',
                            {{ parsed_result_dict.get('execution_time') }},
                            {{ parsed_result_dict.get('rows_affected') }}
                        ) {{- "," if not loop.last else "" -}}
                    {%- endfor -%}
            {%- endset -%}
            {%- do run_query(insert_dbt_results_query) -%}
        {%- endif -%}
    {%- endif -%}
    -- This macro is called from an on-run-end hook and therefore must return a query txt to run. Returning an empty string will do the trick
    {{ return ('') }}
{% endmacro %}
</code>```

- Extend the macro to include the latest country, batch_id etc. that has been inserted:

```<code>{% set parse_information(model) %}

  select
     country
    ,inserted_at
    ,batch_id
    ,exported_at
  from
    model
  where
    model.invocation_id = invocation_id (the latter in access via results variable!?)

{% endset %}

{% do run_query(parse_information) %}
</code>```

- Add this to the parsed_result_dict in the parse_dbt_results.sql macro (which already is part of the solution at the link).

- Insert everything into a defined variable via log_dbt_results.sql macro (which is also already part of the solution at the link).

Does anyone know how this could be implemented? Does anyone use similar loggings that persist content information about the last batch processed or similar? Or maybe someone sees a much simpler solution?

Thanks in advance for any ideas and tips.

Body:
I am looking for a way to build a customized logging. I am aware of the existing packages like dbt_artifacts, elementary etc. For my use case I'd like to add further information related to the latest run which can be queried from the model itself. An example for the logging table could be:

country
inserted_at
batch_id
exported_at
invocation_id
database_name
schema_name
etc.

Cell 1
Cell 2
Cell 3
Cell 4
Cell 5
Cell 6
Cell 7
Cell 9

The first four columns can be derived by the model itself (fyi: the information are part of the data which get pushed in my staging area; with every run I want to process data from one batch related to one country etc., so the information will be distinct), the other columns as far as I know can be derived from the internal results variable (very well shown under the following link https://medium.com/@oravidov/dbt-observability-101-how-to-monitor-dbt-run-and-test-results-f7e5f270d6b6).

I'm wondering how to extend the solution described in the link above by the information which can be queried after the model has been run (first four columns in the table above). I'm thinking of a combination of the solution presented at the link (which already shows how to access metadata like invocation_id, unique_id, rows_affected etc.) and adding info from the model itself.

My ideas go in the following direction:

- Make use of the macros parse_dbt_results and log_dbt_results shown at the link by Or Avidov.

{% macro parse_dbt_results(results) %}
    -- Create a list of parsed results
    {%- set parsed_results = [] %}
    -- Flatten results and add to list
    {% for run_result in results %}
        -- Convert the run result object to a simple dictionary
        {% set run_result_dict = run_result.to_dict() %}
        -- Get the underlying dbt graph node that was executed
        {% set node = run_result_dict.get('node') %}
        {% set rows_affected = run_result_dict.get('adapter_response', {}).get('rows_affected', 0) %}
        {%- if not rows_affected -%}
            {% set rows_affected = 0 %}
        {%- endif -%}
        {% set parsed_result_dict = {
                'result_id': invocation_id ~ '.' ~ node.get('unique_id'),
                'invocation_id': invocation_id,
                'unique_id': node.get('unique_id'),
                'database_name': node.get('database'),
                'schema_name': node.get('schema'),
                'name': node.get('name'),
                'resource_type': node.get('resource_type'),
                'status': run_result_dict.get('status'),
                'execution_time': run_result_dict.get('execution_time'),
                'rows_affected': rows_affected
                }%}
        {% do parsed_results.append(parsed_result_dict) %}
    {% endfor %}
    {{ return(parsed_results) }}
{% endmacro %}

{% macro log_dbt_results(results) %}
    -- depends_on: {{ ref('dbt_results') }}
    {%- if execute -%}
        {%- set parsed_results = parse_dbt_results(results) -%}
        {%- if parsed_results | length  > 0 -%}
            {% set insert_dbt_results_query -%}
                insert into {{ ref('dbt_results') }}
                    (
                        result_id,
                        invocation_id,
                        unique_id,
                        database_name,
                        schema_name,
                        name,
                        resource_type,
                        status,
                        execution_time,
                        rows_affected
                ) values
                    {%- for parsed_result_dict in parsed_results -%}
                        (
                            '{{ parsed_result_dict.get('result_id') }}',
                            '{{ parsed_result_dict.get('invocation_id') }}',
                            '{{ parsed_result_dict.get('unique_id') }}',
                            '{{ parsed_result_dict.get('database_name') }}',
                            '{{ parsed_result_dict.get('schema_name') }}',
                            '{{ parsed_result_dict.get('name') }}',
                            '{{ parsed_result_dict.get('resource_type') }}',
                            '{{ parsed_result_dict.get('status') }}',
                            {{ parsed_result_dict.get('execution_time') }},
                            {{ parsed_result_dict.get('rows_affected') }}
                        ) {{- "," if not loop.last else "" -}}
                    {%- endfor -%}
            {%- endset -%}
            {%- do run_query(insert_dbt_results_query) -%}
        {%- endif -%}
    {%- endif -%}
    -- This macro is called from an on-run-end hook and therefore must return a query txt to run. Returning an empty string will do the trick
    {{ return ('') }}
{% endmacro %}

- Extend the macro to include the latest country, batch_id etc. that has been inserted:

{% set parse_information(model) %}

  select
     country
    ,inserted_at
    ,batch_id
    ,exported_at
  from
    model
  where
    model.invocation_id = invocation_id (the latter in access via results variable!?)

{% endset %}

{% do run_query(parse_information) %}

- Add this to the parsed_result_dict in the parse_dbt_results.sql macro (which already is part of the solution at the link).

- Insert everything into a defined variable via log_dbt_results.sql macro (which is also already part of the solution at the link).

Does anyone know how this could be implemented? Does anyone use similar loggings that persist content information about the last batch processed or similar? Or maybe someone sees a much simpler solution?

Thanks in advance for any ideas and tips.


问:
"Compile Error - Sub or Error Function Not Defined" Excel VBA Error for Trying to Filter Across Columns
I am trying to find an excel VBA macro that allows me to filter across columns instead of rows. If anyone has any code or a template for excel that already does that, please share.

Otherwise I was watching a video that had code that'd do exactly what I want. However, when I do the keyboard shortcut for "FillFilters" I get the error message "Compile Error - Sub or Error Function Not Defined". Can anyone help on this issue? Code is posted below, thanks

Sub FillFilters() 'with sortcut
        Dim oRange As Range, l As Long, r As Long, c As Long, sFilter As String, arr As Variant, sTemp As String, bDone As Boolean
        If Range("A1") = "Filters" Then Exit Sub
        Range("A2").EntireColumn.Insert
        Set oRange = Sheet4.Range("A2").CurrentRegion
        With oRange
                .Cells.EntireColumn.Hidden = False
                .Cells(1, 1) = "Filters"
                For r = 2 To .Rows.Count
                    For c = 3 To .Columns.Count
                        If WorksheetFunction.CountIf(Range(Cells(r, 3), Cells(r, c)), Cell(r, c)) = 1 Then
                            sFilter = sFilter & "," & Cells(r, c)
                        End If
                    Next c
                    arr = Split(sFilter, ",")
                    Do
                        bDone = True
                        For I = 1 To UBound(arr) - 1
                            If arr(I) > arr(I + 1) Then
                                bDone = False: sTemp = arr(I): arr(I) = arrr(I + 1): arr(I + 1) = sTemp
                            End If
                    Next I
                Loop While bDonw = False
                sFilter = Join(arr, ",")
                With .Cells(r, I).Validation
                    .Delete
                    .Add Type:=xiValidateList, Formula1:="-" & sFilter & ",Blanks"
                    .InCellDropdown = True
                End With
                sFilter = ""
            Next r
            .Cells.EntireColumn.Hidden = False
        End With

End Sub

Sub DeleteFilters() 'with shortcut
    If Range("A1") = "Filters" Then
        Cells.EntireColumn.Hidden = False
        Range("A1").EntireColumn.Delete
        Range("A1").Select
    End If

End Sub

Sub Filtering(oFIlter As Range)
    Dim oRange As Range, sCell As String, r As Long, c As Long, iRow As Long, iCount As Long
    Set oRange = Sheet1.Range("A2").CurrentRegion
    sCell = oFIlter.Value
    If sCell = "Filters" Then oRange.Cells.EntireColumn.Hidden = False: Exit Sub
    If sCell = "" Then oRange.Cells.EntireColumn.Hidden = False: Exit Sub
    If sCell = "-" Then oRange.Cells.EntireColumn.Hidden = False: Exit Sub
    If sCell = "Blanks" Then oRange.Cells.EntireColumn.Hidden = False: sCell = ""
    oRange.Cells.EntireColmn.Hidden = False
    iRow = oFIlter.Row
    With oRange
        For c = 3 To .Columns.Count
            If .Cells(iRow, c) <> sCell Then
                .Cell(iRow, c).EntireColumn.Hidden = True
            Else
                iCount = iCount + 1
            End If
        Next c
        MsgBox iCount & " columns for row " & iRow
    End With

End Sub

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") <> "FIlters" Then Exit Sub
    If Target Is Nothing Then Exit Sub
    If Target.Column = 1 Then Filtering Target
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Range("A1") <> "Filters" Then Exit Sub
    If Target Is Nothing Then Exit Sub
    If Target.Column <> 1 Then Exit Sub
    If Target.Cells.Count > 1 Then Exit Sub
    If Target.Value = "" Then Exit Sub
    Filtering Target
```


问:
use of gTTS in Django project
i want to use gTTS in my Django project. Accordingly i installed django-gtts(pip install Django-Gtts). It is installed successfully..

later i added 'gTTS' under INSTALLED-APPS of setting.py file.  Then run the server and also tried makemigrations gTTS. in both the case got below errir.

```<code>    import_module(entry)
  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in imp
ort_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'gTTS'
</code>```

please suggest what i should next.. i tried all possible way with my litte knowledge but unable to fix it..
please let me know if you need more information.

Title: use of gTTS in Django project

Body:
i want to use gTTS in my Django project. Accordingly i installed django-gtts(pip install Django-Gtts). It is installed successfully..

later i added 'gTTS' under INSTALLED-APPS of setting.py file.  Then run the server and also tried makemigrations gTTS. in both the case got below errir.

    import_module(entry)
  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in imp
ort_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'gTTS'

please suggest what i should next.. i tried all possible way with my litte knowledge but unable to fix it..
please let me know if you need more information.


问:
<embed> - src from proxy server
I am currently struggling with setting the src attribute of the <embed> element. I have my PDF documents stored in the cloud storage with limited access. My application has users, and each user has its own set of PDF contracts on the dedicated namespace.

Since I do not want to expose any URL to the users nor call the storage from the front end, I prepared a proxy endpoint (with authorized access) that returns the application/pdf response to be displayed in a particular <embed> component.

Does anyone know how to display the content with this paradigm?

Thank you for any hint.

Title: <embed> - src from proxy server


问:
VS Code Terminal - launching multiple commands on one button press
I have been wondering for a long time how to make the terminal run 4 (or any number) different commands by itself at the press of one button, and the commands are launched in different directories?

I searched for the answers on the internet, but did not actually find anything relatable.


问:
Hide Blank Cells in Excel Form ComboBox
I have a sheet where I am supposed to filter models of cars from 2 Combobox, one is for the manufacturer, another for the car models. I created a simple form Combobox and the data for that Combobox is coming from cell C in my sheets, the data in this cell C are from another sheet. I get that through a simple =(Models!D2). When I change the manufacturer, the models of the car change and that is working well.

The problem is that depending on the manufacturer of the cars that I choose from another combobox, the range of models change. So if I chose BMW for example, I have 3 cars, if I choose Volkswagen I have way more, and then there are some blank cells on my Combobox.

I tried many tutorials, but none of them worked for me.

Just to Resume:

I have 2 sheets, one named "TIM" where are my Combobox, and one named
"Models" where is the models of cars. TIM is getting data from
Models.

The combobox is getting the range data from Colum C, starting
on cell 20. And I need to have a cell where the result of the
combobox selection is shown.

Title: Hide Blank Cells in Excel Form ComboBox


问:
Flutter CupertinoTabScaffold tabBuilder error
I want to make the BottomNavBar always stay open in my app.
When I compile my code i get this Error:
RenderBox was not laid out: RenderIgnorePointer#59187 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED

I'm trying to do it in the following way:

```<code>bottomNavigationBar: CupertinoTabScaffold(
            tabBar: CupertinoTabBar(
              iconSize: 30,
              currentIndex: currentIndex,
              onTap: (index) => setState(() => currentIndex = index),
              items: [
                BottomNavigationBarItem(icon: Icon(Icons.home, size: 25)),
                BottomNavigationBarItem(
                    icon: Icon(
                  Icons.store,
                  size: 25,
                )),
                BottomNavigationBarItem(
                    icon: Icon(Icons.shopping_bag, size: 25)),
                BottomNavigationBarItem(icon: Icon(Icons.person, size: 25)),
              ],
            ),
            tabBuilder: (BuildContext context, int index) {
              return CupertinoTabView(
                builder: (BuildContext context) {
                  return SafeArea(
                    top: false,
                    bottom: false,
                    child: MaterialApp(
                      home: CupertinoPageScaffold(
                        resizeToAvoidBottomInset: false,
                        child: MainScreen(
                          currentIndex: currentIndex,
                        ),
                      ),
                    ),
                  );
                },
              );
            }));
</code>```

Please tell me how to make it work, and how correct is it to do it this way?

Body:
I want to make the BottomNavBar always stay open in my app.
When I compile my code i get this Error:
RenderBox was not laid out: RenderIgnorePointer#59187 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED

I'm trying to do it in the following way:

bottomNavigationBar: CupertinoTabScaffold(
            tabBar: CupertinoTabBar(
              iconSize: 30,
              currentIndex: currentIndex,
              onTap: (index) => setState(() => currentIndex = index),
              items: [
                BottomNavigationBarItem(icon: Icon(Icons.home, size: 25)),
                BottomNavigationBarItem(
                    icon: Icon(
                  Icons.store,
                  size: 25,
                )),
                BottomNavigationBarItem(
                    icon: Icon(Icons.shopping_bag, size: 25)),
                BottomNavigationBarItem(icon: Icon(Icons.person, size: 25)),
              ],
            ),
            tabBuilder: (BuildContext context, int index) {
              return CupertinoTabView(
                builder: (BuildContext context) {
                  return SafeArea(
                    top: false,
                    bottom: false,
                    child: MaterialApp(
                      home: CupertinoPageScaffold(
                        resizeToAvoidBottomInset: false,
                        child: MainScreen(
                          currentIndex: currentIndex,
                        ),
                      ),
                    ),
                  );
                },
              );
            }));

Please tell me how to make it work, and how correct is it to do it this way?


问:
How do I read from file and print one byte at a time? Then remove the spaces and puctuations. Then store the words in a character array
Code:

```<code>#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>

#define WM 15

int main()                 {
    int i=0,j=0,k=0,n, counter2, counter1, low, high, mid;

char sort, dummy, quit;
int a, GotBack, count, Got, innerCount;
bool DEBUG;
char temp[WM];
a = 0;
char* line[a][255];
char* search[a];
char* words[a];
long filelen;
char *buffer;
int buff;

FILE* Cprograms;

Cprograms = fopen("finalread.c", "r");

printf("Words in from the paragarph:");

    fseek(Cprograms, 0, SEEK_END);
    filelen = ftell(Cprograms);
    rewind(Cprograms);
    buffer = (char *)malloc((filelen+1)*sizeof(char));

    for(i = 0; i < filelen; i++) {

       fread(buffer+i, 1, 1, Cprograms);

     }

    printf("File len: %d\n", filelen);
    printf("%s\n",*&buffer);

fclose(Cprograms);
    return 0;
}
</code>```

Output:

```<code>Words in from the paragarph:File len: 559
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep,
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to: 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep, perchance to dream, ay, there's the rub:
For in that sleep of death what dreams may come,
When we have shuffled off this mortal coil,
Must give us pause☻☺♥►☻☺♥ ☻☺♥ ☻←┌yç╧‼

</code>```

I want the code to read only one byte at a time. Then I need the code to split the one-byte buffer into words and remove punctuation and make them lowercase and store them. Like char *words[] = { "to", "be", "or" }. I want it in a loop so each time it reads one byte does everything and goes back to start again.

For example,
if this stored in the file
"To be, or not to be, that is the question:"
I'll need the code to first read "To Be, or" which is a byte
Then print "To Be, or"
Then remover spaces and puctuations and divde them by words and make them lower case like
"to", "be", "or.
Then store them in an array.
Then goes back to read "not to be,"

Thanks in advance

Body:
Code:

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>

#define WM 15

int main()                 {
    int i=0,j=0,k=0,n, counter2, counter1, low, high, mid;

char sort, dummy, quit;
int a, GotBack, count, Got, innerCount;
bool DEBUG;
char temp[WM];
a = 0;
char* line[a][255];
char* search[a];
char* words[a];
long filelen;
char *buffer;
int buff;

FILE* Cprograms;

Cprograms = fopen("finalread.c", "r");

printf("Words in from the paragarph:");

    fseek(Cprograms, 0, SEEK_END);
    filelen = ftell(Cprograms);
    rewind(Cprograms);
    buffer = (char *)malloc((filelen+1)*sizeof(char));

    for(i = 0; i < filelen; i++) {

       fread(buffer+i, 1, 1, Cprograms);

     }

    printf("File len: %d\n", filelen);
    printf("%s\n",*&buffer);

fclose(Cprograms);
    return 0;
}

Output:

Words in from the paragarph:File len: 559
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep,
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to: 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep, perchance to dream, ay, there's the rub:
For in that sleep of death what dreams may come,
When we have shuffled off this mortal coil,
Must give us pause☻☺♥►☻☺♥ ☻☺♥ ☻←┌yç╧‼

I want the code to read only one byte at a time. Then I need the code to split the one-byte buffer into words and remove punctuation and make them lowercase and store them. Like char *words[] = { "to", "be", "or" }. I want it in a loop so each time it reads one byte does everything and goes back to start again.

For example,
if this stored in the file
"To be, or not to be, that is the question:"
I'll need the code to first read "To Be, or" which is a byte
Then print "To Be, or"
Then remover spaces and puctuations and divde them by words and make them lower case like
"to", "be", "or.
Then store them in an array.
Then goes back to read "not to be,"

Thanks in advance


问:
How do you search for specific text in an entire string of text using RegEx in Notepad++?
I'm trying to figure out how to capture specific text in a log file that will only capture text within the first 25 character of a line of text.  This is using the Analyse Plugin in Notepad++.

Example:

```<code>0.469132 CANFD   1 Rx        122f1                                   1 0 d 32 05 d3 07 ca 00 1f 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 a0 00 00 00 00 00 00 00 00
</code>```

In the example above,  I have written the following regex code

RegEx code:

```<code>(x|rx\s+(...))\s+\d\s+\d\s+(\d|\D)\s+(\d|\D|\d\d|\D\D)\s+.*?(?:(02\s(11|51)\s01))
</code>```

This code will return the line if it sees 11 01 or 51 01 but I don't want to search the entire line I only want to search the next 25 characters after the \d\s+\d\s+(\d|\D)\s+(\d|\D|\d\d|\D\D).

Does anyone have any suggestions on how this can be done?

Body:
I'm trying to figure out how to capture specific text in a log file that will only capture text within the first 25 character of a line of text.  This is using the Analyse Plugin in Notepad++.

Example:

0.469132 CANFD   1 Rx        122f1                                   1 0 d 32 05 d3 07 ca 00 1f 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 a0 00 00 00 00 00 00 00 00

In the example above,  I have written the following regex code

RegEx code:

(x|rx\s+(...))\s+\d\s+\d\s+(\d|\D)\s+(\d|\D|\d\d|\D\D)\s+.*?(?:(02\s(11|51)\s01))

This code will return the line if it sees 11 01 or 51 01 but I don't want to search the entire line I only want to search the next 25 characters after the \d\s+\d\s+(\d|\D)\s+(\d|\D|\d\d|\D\D).

Does anyone have any suggestions on how this can be done?


问:
Python - how to make abstract class constants?
What is the python way of defining abstract class constants?

For example, if I have this abstract class:

class MyBaseClass(SomeOtherClass, metaclass=ABCMeta):
    CONS_A: str
    CONS_B: str
```
<p>So, the type checker/"compiler" (at least Pycharm's one) doesn't complain about the above.
But if I inherit it to another class and don't implement <code>CONS_A</code> and <code>CONS_B</code>, it doesn't complain either:</p>
<pre class="lang-py prettyprint-override"><code>class MyChildClass(MyBaseClass):
    pass
</code>```

What is the python way of enforcing (the much we can with a duck-type language) implementation of MyBaseClass to actually implement CONS_A and CONS_B?

Bonus question: once I can enforce, how can I only enforce for non-abstract classes? I suppose it should be the same answer as the main question. But, I might be wrong. So, for example:

# "compiler" should not complain
class MyChildAbstractClass(MyBaseClass):
    pass

# here it must complain if I don't implement `CONS_A` and `CONS_B`
class MyChildImplementationClass(MyChildAbstractClass):
    pass
```

Obs: I am aware of @abstractmethod, but I didn't find a solution for abstract class constants.

Thank you.

Body:
What is the python way of defining abstract class constants?

For example, if I have this abstract class:

class MyBaseClass(SomeOtherClass, metaclass=ABCMeta):
    CONS_A: str
    CONS_B: str

So, the type checker/"compiler" (at least Pycharm's one) doesn't complain about the above.
But if I inherit it to another class and don't implement CONS_A and CONS_B, it doesn't complain either:

class MyChildClass(MyBaseClass):
    pass

What is the python way of enforcing (the much we can with a duck-type language) implementation of MyBaseClass to actually implement CONS_A and CONS_B?

Bonus question: once I can enforce, how can I only enforce for non-abstract classes? I suppose it should be the same answer as the main question. But, I might be wrong. So, for example:

# "compiler" should not complain
class MyChildAbstractClass(MyBaseClass):
    pass

# here it must complain if I don't implement `CONS_A` and `CONS_B`
class MyChildImplementationClass(MyChildAbstractClass):
    pass

Obs: I am aware of @abstractmethod, but I didn't find a solution for abstract class constants.

Thank you.


问:
What is the correct format and syntax for reading data with subarrays into numpy structured array?
I'm trying to use np.genfromtxt to read in a text file into a variety of data types, some of which are ideally sub arrays, however I can't seem to find the right code or input format for this, I've managed to get numpy to complain I both have too many and too few columns!

example data:

```<code>id;bar;foo;snakes
1;2.46;2.616;(1,1)
</code>```

(or without brackets, e.g. 1;2.46;2.616;1,1  )

```<code>x = np.genfromtxt(file, delimiter=';', names=True, dtype='u4,f8,f8,(2,)u4')
</code>```

Results in "ValueError: could not assign tuple of length 4 to structure with 5 fields."

```<code>id;bar;foo;snakes
1;2.46;2.616;1;1
</code>```

Results in "ValueError: Some errors were detected !   Line #2 (got 5 columns instead of 4)"

Tried different delimiters. Is this not possible? The two different errors suggests it should be but I'm just not getting the correct syntax or data format

Body:
I'm trying to use np.genfromtxt to read in a text file into a variety of data types, some of which are ideally sub arrays, however I can't seem to find the right code or input format for this, I've managed to get numpy to complain I both have too many and too few columns!

example data:

id;bar;foo;snakes
1;2.46;2.616;(1,1)

(or without brackets, e.g. 1;2.46;2.616;1,1  )

x = np.genfromtxt(file, delimiter=';', names=True, dtype='u4,f8,f8,(2,)u4')

Results in "ValueError: could not assign tuple of length 4 to structure with 5 fields."

id;bar;foo;snakes
1;2.46;2.616;1;1

Results in "ValueError: Some errors were detected !   Line #2 (got 5 columns instead of 4)"

Tried different delimiters. Is this not possible? The two different errors suggests it should be but I'm just not getting the correct syntax or data format


问:
How to target opengl ES 3.1 or lower on Unreal Engine 5?
Building a default scene can not open the scene on android latest available emulator with android 13 Tiramisu at the time of writing showing the following error:

1080×2340 126 KB
Only supports ES 3.2+.

This happens with or without opengl es 3.2 ticked on the project settings.

So how can I target it with a lower ES version?


问:
Excel formula to look up date that corresponds with 2nd 'non zero' value in column
In an excel model with two columns, column A = date by month, column B = cash projections (only two values in column B). Hoping to create a formula to search column b for the second value and return the corresponding month from column A.

In example below, looking for formula to return 'May 20' as answer

Column A
Column B

Jan 20
240,000

Feb 20

Mar 20

Apr 20

May 20
345,000

Jun 20

Tried using a min/max function, however, the second value is not consistently higher or lower than the first value. Assuming it can be done with some type of INDEX or LOOKUP function, however, I am unsure of how to select the second non-zero value


问:
reload shortcut key ‘R’ no longer active on iOS simulator?
```<code>SDK Version: 46
├── eas-cli@2.8.0
├── expo-cli@6.0.8
Platforms(Android/iOS/web/all): iOS
</code>```

I just updated my eas & expo cli’s while already on SDK 46. I used to be able to press R key to reload the app while focus in the simulator. It seems this is no longer working. Any ideas?

I can still press R on the terminal

Body:
SDK Version: 46
├── eas-cli@2.8.0
├── expo-cli@6.0.8
Platforms(Android/iOS/web/all): iOS

I just updated my eas & expo cli’s while already on SDK 46. I used to be able to press R key to reload the app while focus in the simulator. It seems this is no longer working. Any ideas?

I can still press R on the terminal


问:
php8.1 Call to undefined function iconv
Please help me

my source code

```<code>iconv('UTF-8', 'UTF-8//IGNORE', $value);
</code>```

error message

PHP Fatal error:  Uncaught Error: Call to undefined function iconv()

server
ubuntu : 22.04
php v : PHP 8.1.13
use : php8.1-fpm.service

I want to use the iconv function

try

```<code>apt install php8.1-common

phpenmod common

WARNING: Module common ini file doesn't exist under /etc/php/8.1/mods-available
</code>```
```<code>php-fpm8.1 -m

bcmath
cgi-fcgi
Core
curl
date
dom
filter
gd
hash
igbinary
imagick
imap
intl
json
libxml
mbstring
mysqli
mysqlnd
OAuth
openssl
pcre
redis
Reflection
session
SimpleXML
soap
sodium
SPL
standard
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

[Zend Modules]
</code>```

Title: php8.1 Call to undefined function iconv

Body:
Please help me

my source code

iconv('UTF-8', 'UTF-8//IGNORE', $value);

error message

PHP Fatal error:  Uncaught Error: Call to undefined function iconv()

server
ubuntu : 22.04
php v : PHP 8.1.13
use : php8.1-fpm.service

I want to use the iconv function

try

apt install php8.1-common

phpenmod common

WARNING: Module common ini file doesn't exist under /etc/php/8.1/mods-available

php-fpm8.1 -m

bcmath
cgi-fcgi
Core
curl
date
dom
filter
gd
hash
igbinary
imagick
imap
intl
json
libxml
mbstring
mysqli
mysqlnd
OAuth
openssl
pcre
redis
Reflection
session
SimpleXML
soap
sodium
SPL
standard
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

[Zend Modules]


问:
saving redis-cli command response to file using c#
I am trying to bulk add keys to my redis server using type filename.txt | redis-cli --pipe. This works well and all data inserted successfully and i can see response in cmd window. but when tried with c# app then response file is always empty.
here is code snippet.

```<code>Process.Start("CMD.exe", "/K type c:\\Users\\username\\Desktop\\file.txt | redis-cli -h 192.168.100.28 --pipe >result.txt");
</code>```

Edit 1

Also tried the solution provide by @Grigory Zhadko it displays the output of echo command but not the redis-cli output.

```<code>        var process = new Process();
        process.StartInfo.FileName = "CMD.exe";
        process.StartInfo.Arguments = "/K type c:\\Users\\username\\Desktop\\file.txt | redis-cli -h 192.168.100.29 --pipe";
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.UseShellExecute = false;
        process.Start();
        process.StandardInput.WriteLine("echo hello");
        process.StandardInput.WriteLine("exit");
        string output = process.StandardOutput.ReadToEnd();
</code>```

Here is output of this.

```<code>D:\Projects\projectname\bin\Debug>echo hello
hello

D:\Projects\projectname\bin\Debug>exit
</code>```

Body:
I am trying to bulk add keys to my redis server using type filename.txt | redis-cli --pipe. This works well and all data inserted successfully and i can see response in cmd window. but when tried with c# app then response file is always empty.
here is code snippet.

Process.Start("CMD.exe", "/K type c:\\Users\\username\\Desktop\\file.txt | redis-cli -h 192.168.100.28 --pipe >result.txt");

Edit 1

Also tried the solution provide by @Grigory Zhadko it displays the output of echo command but not the redis-cli output.

        var process = new Process();
        process.StartInfo.FileName = "CMD.exe";
        process.StartInfo.Arguments = "/K type c:\\Users\\username\\Desktop\\file.txt | redis-cli -h 192.168.100.29 --pipe";
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.UseShellExecute = false;
        process.Start();
        process.StandardInput.WriteLine("echo hello");
        process.StandardInput.WriteLine("exit");
        string output = process.StandardOutput.ReadToEnd();

Here is output of this.

D:\Projects\projectname\bin\Debug>echo hello
hello

D:\Projects\projectname\bin\Debug>exit


问:
Using member in swi prolog
I am totaly new to prolog and have just started. I am currently learning about the build in function 'member' that seems simple; however, it returns the opposite of what I would expect it to do.

I tried printing the output of a very simple query:

```<code>member(6, [2,4,3,5]).
</code>```

My expectation was that the output of this would be False

However, it returns True

I played with this further trying:

```<code>member(2, [2,4,3,5]).
</code>```

Which returns False!?

Could someone explain if this is a mistake by me or that this is normal for prolog to do?

Title: Using member in swi prolog

Body:
I am totaly new to prolog and have just started. I am currently learning about the build in function 'member' that seems simple; however, it returns the opposite of what I would expect it to do.

I tried printing the output of a very simple query:

member(6, [2,4,3,5]).

My expectation was that the output of this would be False

However, it returns True

I played with this further trying:

member(2, [2,4,3,5]).

Which returns False!?

Could someone explain if this is a mistake by me or that this is normal for prolog to do?


问:
Term for CS Concept of Generating Number to Compare "Similarities" Between Some Objects
Sorry if this question is unclear. I'm looking for a concept similar to hashing, but not quite. I'll frame it in SQL terms.

Let's say I have some data like

d[0] = 'foo bar'

d[1] = 'foo baz'

d[2] = 'abcdefg'

I want to somehow create a function f for generating values such that

|f(d[i]) - f(d[j])| < |f(d[i]) - (d[k])|

if and only if d[i] and d[j] are "more similar" than d[i] and d[k], as they are in this example.

Then, if the values of f are stored in a table, like

```<code>==========================
      d    |     f(d)
==========================
 'foo bar' |    61236
--------------------------
 'abcdefg' |    7714551
--------------------------
 'foo baz' |    61229
</code>```

and I want to search for similar strings to 'foo buz', I can run it through f to get 61233 and then query with comparison < to find 'foo bar' and 'foo baz'.

There is probably some CS concept I can't remember.

Body:
Sorry if this question is unclear. I'm looking for a concept similar to hashing, but not quite. I'll frame it in SQL terms.

Let's say I have some data like

d[0] = 'foo bar'

d[1] = 'foo baz'

d[2] = 'abcdefg'

I want to somehow create a function f for generating values such that

|f(d[i]) - f(d[j])| < |f(d[i]) - (d[k])|

if and only if d[i] and d[j] are "more similar" than d[i] and d[k], as they are in this example.

Then, if the values of f are stored in a table, like

==========================
      d    |     f(d)
==========================
 'foo bar' |    61236
--------------------------
 'abcdefg' |    7714551
--------------------------
 'foo baz' |    61229

and I want to search for similar strings to 'foo buz', I can run it through f to get 61233 and then query with comparison < to find 'foo bar' and 'foo baz'.

There is probably some CS concept I can't remember.


问:
NameError: name 'sideways_target' is not defined
I have an error where python is not able to find my file. (if I understand correctly) I can't find what I have missed. If anyone could take the time to point it out to me, it would be much appreciated.

```<code>def _check_target_edges(self):
        """Respond appropriately if the target has reached an edge."""
        if sideways_target.check_edges():
            self._change_target_direction()
</code>```

this code is giving error messages

```<code>pygame 2.1.2 (SDL 2.0.18, Python 3.10.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 218, in <module>
    ss.run_game()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 53, in run_game
    self._update_target()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 157, in _update_target
    self._check_target_edges()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 207, in _check_target_edges
    if sideways_target.check_edges():
NameError: name 'sideways_target' is not defined
[Finished in 2.7s]
</code>```

```<code>def check_edges(self):
        """Return True if target is at edge of screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.bottom >= screen_rect.bottom or self.rect.top <= 0:
            return True
</code>```

This is what I want the code to find. So it updates any changes in True/False.
I would like to know where can I define 'sideways_target' so the error clears up and I can run the project.

If you need more detail... the files are down below

File of the 1st piece of code

```<code># ship spawns on the left side
# bullets travel to the right
# target moves up and down
# shoot the target
#

import sys, pygame

from sideways_settings import Settings
from sideways_ship import Ship
from sideways_bullet import Bullet
from sideways_game_stats import GameStats
from sideways_target import Target
from sideways_button import Button

class ShipShooter:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.sideways_settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.sideways_settings.screen_width = self.screen.get_rect().width
        self.sideways_settings.screen_width = self.screen.get_rect().height
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics.
        self.sideways_stats = GameStats(self)

        self.sideways_ship = Ship(self)
        self.bullets = pygame.sprite.Group()

        # Make the button.
        self.sideways_play_button = Button(self, "Play")

        # Make the target
        self.sideways_target = Target(self)

        # Set the background color.
        self.bg_color = (230, 230, 230)

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            if self.sideways_stats.game_active:
                self.sideways_ship.update()
                self._update_bullets()
                self._update_target()

            self._update_screen()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.sideways_play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.sideways_stats.game_active:
            # Reset the game statistics.
            self.sideways_stats.reset_stats()
            self.sideways_stats.game_active = True

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship
            self.sideways_ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_play_button2(self):
        """Start a new game when the player clicks Play."""
        if self.key_p == True:
            # Reset the game statistics.
            self.sideways_stats.reset_stats()
            self.sideways_stats.game_active = True

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship
            self.sideways_ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_UP:
            self.sideways_ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.sideways_ship.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        elif event.key == pygame.K_p:
            self.key_p = True
            self._check_play_button2()

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_UP:
            self.sideways_ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.sideways_ship.moving_down = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.sideways_settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.right >= self.sideways_ship.screen_rect.right :
                self.bullets.remove(bullet)
        #   print(len(self.bullets))

        # Look for bullets hitting the side of the screen.
        self._check_bullets_bottom()

    def _check_bullet_target_collisions(self):
        """Respond to bullet-target collisions."""
        # Remove any bullets that have collided with the target
        collisions = pygame.sprite.groupcollide(
                self.bullets, self.sideways_target, True, True)

    def _update_target(self):
        """
        Check if the target is at the edge,
            then update the position of the target
        """
        self._check_target_edges()
        self.sideways_target.update()

        # Look for bullet-target collisions.
        if pygame.sprite.spritecollideany(self.bullets, self.sideways_target):
            self._target_hit()

    def _target_hit(self):
        """Respond to the target being hit by a bullet."""
        if self.sideways_stats.targets_left > 0:
            # Decrement targets_left.
            self.sideways_stats.targets_left -= 1

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship.
            self.sideways_ship.center_ship()

            # Pause.
            sleep(1.5)
        else:
            self.sideways_stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_bullets_bottom(self):
        """Check if any bullets have reached the side of your screen."""
        screen_rect = self.screen.get_rect()
        for bullet in self.bullets.sprites():
            if bullet.rect.right >= screen_rect.right:
                # Treat this the same as if the target got hit.
                self.target_hit()
                break

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.sideways_settings.bg_color)
        self.sideways_ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.sideways_target.draw_target()

        # Draw the play button if the game is inactive.
        if not self.sideways_stats.game_active:
            self.sideways_play_button.draw_button()

        pygame.display.flip()

    def _check_target_edges(self):
        """Respond appropriately if the target has reached an edge."""
        if sideways_target.check_edges():
            self._change_target_direction()

    def _change_target_direction(self):
        """Change the target's direction."""
        self.sideways_settings.target_direction *= -1

if __name__ == '__main__':
    # Make a game instance, and run the game.
    ss = ShipShooter()
    ss.run_game()
</code>```

File of the 2nd piece of code

```<code>import pygame
from pygame.sprite import Sprite

class Target:

    def __init__(self, ai_game):
        """Initialize target attributes."""
        self.screen = ai_game.screen
        self.screen_rect = self.screen.get_rect()

        # Set the dimensions and properties of the target
        self.width, self.height = 70, 300
        self.target_color = (0, 0, 0)

        # Build the target's rect object and center it.
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.midright = self.screen_rect.midright

        # Store the target's exact vertical position.
        self.y = float(self.rect.y)

    def check_edges(self):
        """Return True if target is at edge of screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.bottom >= screen_rect.bottom or self.rect.top <= 0:
            return True

    def update(self):
        """Move the target up or down."""
        self.y += (self.sideways_settings.target_speed *
                    self.sideways_settings.target_direction)
        self.rect.y = self.y

    def draw_target(self):
        # Draw the target to the screen
        pygame.draw.rect(self.screen, self.target_color, self.rect)
</code>```

Body:
I have an error where python is not able to find my file. (if I understand correctly) I can't find what I have missed. If anyone could take the time to point it out to me, it would be much appreciated.

def _check_target_edges(self):
        """Respond appropriately if the target has reached an edge."""
        if sideways_target.check_edges():
            self._change_target_direction()

this code is giving error messages

pygame 2.1.2 (SDL 2.0.18, Python 3.10.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 218, in <module>
    ss.run_game()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 53, in run_game
    self._update_target()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 157, in _update_target
    self._check_target_edges()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 207, in _check_target_edges
    if sideways_target.check_edges():
NameError: name 'sideways_target' is not defined
[Finished in 2.7s]

def check_edges(self):
        """Return True if target is at edge of screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.bottom >= screen_rect.bottom or self.rect.top <= 0:
            return True

This is what I want the code to find. So it updates any changes in True/False.
I would like to know where can I define 'sideways_target' so the error clears up and I can run the project.

If you need more detail... the files are down below

File of the 1st piece of code

# ship spawns on the left side
# bullets travel to the right
# target moves up and down
# shoot the target
#

import sys, pygame

from sideways_settings import Settings
from sideways_ship import Ship
from sideways_bullet import Bullet
from sideways_game_stats import GameStats
from sideways_target import Target
from sideways_button import Button

class ShipShooter:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.sideways_settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.sideways_settings.screen_width = self.screen.get_rect().width
        self.sideways_settings.screen_width = self.screen.get_rect().height
        pygame.display.set_caption("Sideways Shooter")

        # Create an instance to store game statistics.
        self.sideways_stats = GameStats(self)

        self.sideways_ship = Ship(self)
        self.bullets = pygame.sprite.Group()

        # Make the button.
        self.sideways_play_button = Button(self, "Play")

        # Make the target
        self.sideways_target = Target(self)

        # Set the background color.
        self.bg_color = (230, 230, 230)

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            if self.sideways_stats.game_active:
                self.sideways_ship.update()
                self._update_bullets()
                self._update_target()

            self._update_screen()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.sideways_play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.sideways_stats.game_active:
            # Reset the game statistics.
            self.sideways_stats.reset_stats()
            self.sideways_stats.game_active = True

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship
            self.sideways_ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_play_button2(self):
        """Start a new game when the player clicks Play."""
        if self.key_p == True:
            # Reset the game statistics.
            self.sideways_stats.reset_stats()
            self.sideways_stats.game_active = True

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship
            self.sideways_ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_UP:
            self.sideways_ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.sideways_ship.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        elif event.key == pygame.K_p:
            self.key_p = True
            self._check_play_button2()

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_UP:
            self.sideways_ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.sideways_ship.moving_down = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.sideways_settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.right >= self.sideways_ship.screen_rect.right :
                self.bullets.remove(bullet)
        #   print(len(self.bullets))

        # Look for bullets hitting the side of the screen.
        self._check_bullets_bottom()

    def _check_bullet_target_collisions(self):
        """Respond to bullet-target collisions."""
        # Remove any bullets that have collided with the target
        collisions = pygame.sprite.groupcollide(
                self.bullets, self.sideways_target, True, True)

    def _update_target(self):
        """
        Check if the target is at the edge,
            then update the position of the target
        """
        self._check_target_edges()
        self.sideways_target.update()

        # Look for bullet-target collisions.
        if pygame.sprite.spritecollideany(self.bullets, self.sideways_target):
            self._target_hit()

    def _target_hit(self):
        """Respond to the target being hit by a bullet."""
        if self.sideways_stats.targets_left > 0:
            # Decrement targets_left.
            self.sideways_stats.targets_left -= 1

            # Get rid of any remaining bullets.
            self.bullets.empty()

            # Center the ship.
            self.sideways_ship.center_ship()

            # Pause.
            sleep(1.5)
        else:
            self.sideways_stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_bullets_bottom(self):
        """Check if any bullets have reached the side of your screen."""
        screen_rect = self.screen.get_rect()
        for bullet in self.bullets.sprites():
            if bullet.rect.right >= screen_rect.right:
                # Treat this the same as if the target got hit.
                self.target_hit()
                break

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.sideways_settings.bg_color)
        self.sideways_ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.sideways_target.draw_target()

        # Draw the play button if the game is inactive.
        if not self.sideways_stats.game_active:
            self.sideways_play_button.draw_button()

        pygame.display.flip()

    def _check_target_edges(self):
        """Respond appropriately if the target has reached an edge."""
        if sideways_target.check_edges():
            self._change_target_direction()

    def _change_target_direction(self):
        """Change the target's direction."""
        self.sideways_settings.target_direction *= -1

if __name__ == '__main__':
    # Make a game instance, and run the game.
    ss = ShipShooter()
    ss.run_game()

File of the 2nd piece of code

import pygame
from pygame.sprite import Sprite

class Target:

    def __init__(self, ai_game):
        """Initialize target attributes."""
        self.screen = ai_game.screen
        self.screen_rect = self.screen.get_rect()

        # Set the dimensions and properties of the target
        self.width, self.height = 70, 300
        self.target_color = (0, 0, 0)

        # Build the target's rect object and center it.
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.midright = self.screen_rect.midright

        # Store the target's exact vertical position.
        self.y = float(self.rect.y)

    def check_edges(self):
        """Return True if target is at edge of screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.bottom >= screen_rect.bottom or self.rect.top <= 0:
            return True

    def update(self):
        """Move the target up or down."""
        self.y += (self.sideways_settings.target_speed *
                    self.sideways_settings.target_direction)
        self.rect.y = self.y

    def draw_target(self):
        # Draw the target to the screen
        pygame.draw.rect(self.screen, self.target_color, self.rect)