问:
“sldnfdraw” pack Swi-Prolog how to use
Good afternoon. I am intending to use a program that generates LaTex text to visualize search trees. Although there are instructions in Swi-Prolog’s website, they tell me to write “:-sldnf” in the terminal to initialize the library and start using the program, but the terminal says that it could not correct goal. Does anyone know how to solve this problem?

I tried reinstalling the pack “sldnfdraw”, which I downloaded from GitHub (the user’s name is Marco Gavanelli), but it is already installed. It recognizes its’ presence, but does not initialize the library.

Title: “sldnfdraw” pack Swi-Prolog how to use


来源: stackexchange

问:
What is the benefit of IA-32e mode guest of the vm-enter?
Regarding Intel VMX, I found that there is IA-32e mode guest bit field in vm-entry controls.

Based on the Intel manual, when this bit is set, the VM entries start from IA-32e mode.

What is the benefit of starting VCPU from ia-32e mode?

Is it just one of VM optimization to fast-forward some initial boot steps of VCPU?

Also, if this bit has not been set, what is the default mode of the VCPU when it initially enters to the VM?

ContentLicense: CC BY-SA 4.0


问:
How to create a custom progress bar with numbers in Swiper
I have a progressbar in my Swiper slider. I need to make it so that the maximum number of slides is displayed on the right, and "01" on the left. When scrolling, they should not change, just static numbers for the minimum and maximum slides. How can i do this?

  const swiper = new Swiper("mySlider", {
    centeredSlides: true,
    allowTouchMove: true,
    navigation: {
      nextEl: ".my-arrow__next",
      prevEl: ".my-arrow__prev",
    },
    pagination: {
      el: "my-pagination",
      type: "progressbar",
    },
  });```


问:
Google Analytics 4 cookies not being removed when opting-in and then opting-out with Osano (Consent Management Platform)
I'm using Osano Developer plan to integrate a Cookie Consent Manager in my website. My website only has essential cookies and analytics (Google Analytics 4 - GA4) cookies. Initially, the Cookie Consent is working and GA4 cookies are not set until the user opts-in. However, after the opt-in, if the user opts-out I don't see the cookies being removed (I check them at: Google Chrome -> Developer Tools -> Application tab -> Cookies). I was expecting them to be removed or at least a change in the "Expires / Max Age" field.

Another thing I don't understand from "Osano dashboard -> Cookie Management -> Cookies tab", is that GA4 cookies were discovered and I managed them. But in the Osano "Storage Preference Drawer", under the Analytics section it doesn't show the GA4 cookies which is strange (not in my website nor within Osano Storage Preference Drawer preview).

Osano->Consent Management->Customization->Show Drawer, but also not being shown analytics cookies in the website:
Consent Management->Customization->Show Drawer, but also not being shown analytics cookies in the website" />

Chrome->Developer Tools->GA4 cookies after opt-in and then opt-out:
Developer Tools->GA4 cookies after opt-in and opt-out" />


问:
How to ignore cases in SQLite within Python script?
I am trying to get User_ID from database with the help of username without considering the case of the username.

I want something like this:

```<code>query="Select User_ID from Users where username LIKE '%?%'"
cursor.execute(query,(username,))

rows = cursor.fetchall()
</code>```

For example:

```<code>Username - Elon_Musk

User_ID - 101
</code>```

In my code, the username gets converted to elon_musk. If I get data using this (elon_musk) username, I get empty result.

How can I solve this? Thank You.

Body:
I am trying to get User_ID from database with the help of username without considering the case of the username.

I want something like this:

query="Select User_ID from Users where username LIKE '%?%'"
cursor.execute(query,(username,))

rows = cursor.fetchall()

For example:

Username - Elon_Musk

User_ID - 101

In my code, the username gets converted to elon_musk. If I get data using this (elon_musk) username, I get empty result.

How can I solve this? Thank You.


问:
what happens if i changed the currentversion
Currently it at 6.1 it wanted to change to 10.0 because it want to upgrade to windows 10, but I’m scared because of windows crash. Can someone tell what happen what happens if we change the current version if it were expecting to crash my windows?</p>


问:
Microsoft.Graph and Microsoft.Graph.beta in parallel
I need to use Microsoft.Graph and Microsoft.Graph.Beta Nuget packages in paralell and referenced them like this in my csproj-File:

```<code><PackageReference Include="Microsoft.Identity.Web.MicrosoftGraphBeta" Version="1.25.10" Aliases="MSGraphBeta"/>
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.25.10"/>
</code>```

Within my existing code, only the Graph SDK should be used, so I set no alias there. This means I import it with:

```<code>using Microsoft.Graph;
</code>```

Never the less, I still get the following error:

```<code>The type 'GraphServiceClient' exists in both 'Microsoft.Graph.Beta, Version=4.50.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'Microsoft.Graph, Version=4.34.0.0,
</code>```

I'm working with asp.net core, targetFramework is net7.0.
What am I missing to use both SDKs in parallel?

Body:
I need to use Microsoft.Graph and Microsoft.Graph.Beta Nuget packages in paralell and referenced them like this in my csproj-File:

<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraphBeta" Version="1.25.10" Aliases="MSGraphBeta"/>
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.25.10"/>

Within my existing code, only the Graph SDK should be used, so I set no alias there. This means I import it with:

using Microsoft.Graph;

Never the less, I still get the following error:

The type 'GraphServiceClient' exists in both 'Microsoft.Graph.Beta, Version=4.50.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'Microsoft.Graph, Version=4.34.0.0,

I'm working with asp.net core, targetFramework is net7.0.
What am I missing to use both SDKs in parallel?


问:
Sort Specific Category by Price ASC and DESC - Using API calls from MySQL
I'm making an e-commerce website using React and MySQL as by Database with products.  This code is from my products navigation bar.
I was able to fetch the items by category. However, I want to sort each category by ascending and descending order and I haven't been able to do that, if I am already in the a specific category.

NAVIGATION BAR CODE

```<code>import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Products } from './Products';
import { DropDownPrice } from './DropDownPrice';
import { useState } from 'react';

export const ProductNavBarFilter = (props) => {
    // ------------- DISPLAYING PRODUCTS BY CATEGORY ---------------
    const searchByCategory=(category)=>{
    const fetchByCategory = async()=>{
        try {
            const res= await axios.get(`http://localhost:8800/productslist/${category}`)
                    props.setProducts(res.data)
                    console.log(res);
                } catch(err){
                console.log(err);
                }
            };
            fetchByCategory();
        };

        const [isOpen, setOpen] = useState(false);

        const handleDropDown = () => {
          setOpen(!isOpen);
        };
     // ------------- DISPLAYING PRODUCTS BY CATEGORY AND PRICE ASC ---------------
     const sortByPriceAsc=(category)=>{
        const fetchByPriceAsc = async()=>{
            try {
                const res= await axios.get(`http://localhost:8800/productslist/priceasc/${category}`)
                        props.setProducts(res.data)
                        console.log(res);
                    } catch(err){
                    console.log(err);
                    }
                };
                fetchByPriceAsc();
     }
    // ------------- DISPLAYING PRODUCTS BY CATEGORY AND PRICE DESC ---------------

     const sortByPriceDesc=(category)=>{
        const fetchByPriceDesc = async()=>{
            try {
                const res= await axios.get(`http://localhost:8800/productslist/pricedesc/${category}`)
                        props.setProducts(res.data)
                        console.log(res);
                    } catch(err){
                    console.log(err);
                    }
                };
                fetchByPriceDesc();
            }

    return (
      <div className="relative flex flex-wrap items-center justify-between px-2 py-3 bg-slate-500 mb-3">
        <div className="container px-4 mx-auto flex flex-wrap items-center justify-between">
          <div className="w-full relative flex justify-between lg:w-auto  px-4 lg:static lg:block lg:justify-start">
            <Link className="text-sm font-bold leading-relaxed inline-block mr-4 py-2 whitespace-nowrap uppercase text-white" to="Products" element={<Products/>} >
             All Items
            </Link>
            <button className="cursor-pointer text-xl leading-none px-3 py-1 border border-solid border-transparent rounded bg-transparent block lg:hidden outline-none focus:outline-none" type="button">
              <span className="block relative w-6 h-px rounded-sm bg-white"></span>
              <span className="block relative w-6 h-px rounded-sm bg-white mt-1"></span>
              <span className="block relative w-6 h-px rounded-sm bg-white mt-1"></span>
            </button>
          </div>
          <div className="lg:flex flex-grow items-center" id="example-navbar-warning">
            <ul className="flex flex-col lg:flex-row list-none mr-auto">
              <li className="nav-item">
                <a className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" href="#">
                  <i className="fab fa-facebook-square text-lg leading-lg text-white opacity-75" />
                </a>
              </li>
              <li className="nav-item">
                <button onClick={() =>  searchByCategory (`Tops`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                  <i className=" text-lg leading-lg text-white opacity-75" /> <span className="ml-2">Tops</span>
                </button>
              </li>
              <li className="nav-item">
                <button onClick={() =>  searchByCategory (`Bottoms`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                  <i className=" text-lg leading-lg text-white opacity-75" /> <span className="ml-2">Bottoms</span>
                </button>
              </li>
              <li className="nav-item">
                <button onClick={() =>  searchByCategory (`Dresses`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                  <i className=" text-lg leading-lg text-white opacity-75" /> <span className="ml-2">Dresses</span>
                </button>
              </li>
            </ul>
          </div>
          {/* DROPDOWN MENU */}
          <section className="dropdown">
        <button
          className="text-white bg-slate-700 hover:bg-slate-800 focus:ring-4 focus:outline-none focus:ring-slate-300 font-medium rounded-lg text-sm px-4 py-2.5 text-center inline-flex items-center"
          onClick={handleDropDown}
        >
          Sort By: (Price)
          <svg
            className="ml-2 w-4 h-4"
            aria-hidden="true"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              d="M19 9l-7 7-7-7"
            ></path>
          </svg>
        </button>

        <div
          id="dropdown"
          className={`z-10 w-44 bg-white rounded divide-y divide-gray-100 shadow ${
            isOpen ? "block" : "hidden"
          }`}
        >
          <ul className=" z-10 w-44 bg-white rounded divide-y divide-gray-100 shadow ">
              <li
              >
                <button onClick={() =>  sortByPriceAsc(``)} className="block py-2 px-4 hover:bg-gray-100">
                  Low to High
                </button>
              </li>
              <li
              >
                <button onClick={() =>  sortByPriceDesc(``)}  className="block py-2 px-4 hover:bg-gray-100">
                  High to Low
                </button>
              </li>
          </ul>
        </div>
      </section>
          {/* <DropDownPrice/> */}
        </div>

     </div>
  )
}

</code>```

API REQUESTS

```<code>//---------------------SORT PRODUCTS BY CATEGORY---------------------------

app.get("/productslist/:category", (req, res) => {
    const category = req.params.category;
    // console.log(category)
    const q = `SELECT * FROM products WHERE category = '${category}'`;
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });

//-------------------SORT PRODUCTS BY PRICE---------------------------------

app.get("/productslist/priceasc/:category", (req, res) => {
    const category = req.params.category;
    const q = `SELECT * FROM products WHERE category = '${category}' ORDER BY price ASC;`
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });

  app.get("/productslist/pricedesc/:category", (req, res) => {
    const category = req.params.category;
    const q = `SELECT * FROM products WHERE category = '${category}' ORDER BY price DESC;`
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });
</code>```

I tried by writing the specific category, but it didn't display any products and even if it did, I would have to create a specific sort by price button for every category which is not what I want.

```<code><button onClick={() =>  sortByPriceAsc(`Tops`)} className="block py-2 px-4 hover:bg-gray-100"> Low to High </button>
</code>```

Body:
I'm making an e-commerce website using React and MySQL as by Database with products.  This code is from my products navigation bar.
I was able to fetch the items by category. However, I want to sort each category by ascending and descending order and I haven't been able to do that, if I am already in the a specific category.

NAVIGATION BAR CODE

import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Products } from './Products';
import { DropDownPrice } from './DropDownPrice';
import { useState } from 'react';

export const ProductNavBarFilter = (props) => {
    // ------------- DISPLAYING PRODUCTS BY CATEGORY ---------------
    const searchByCategory=(category)=>{
    const fetchByCategory = async()=>{
        try {
            const res= await axios.get(`http://localhost:8800/productslist/${category}`)
                    props.setProducts(res.data)
                    console.log(res);
                } catch(err){
                console.log(err);
                }
            };
            fetchByCategory();
        };

        const [isOpen, setOpen] = useState(false);

        const handleDropDown = () => {
          setOpen(!isOpen);
        };
     // ------------- DISPLAYING PRODUCTS BY CATEGORY AND PRICE ASC ---------------
     const sortByPriceAsc=(category)=>{
        const fetchByPriceAsc = async()=>{
            try {
                const res= await axios.get(`http://localhost:8800/productslist/priceasc/${category}`)
                        props.setProducts(res.data)
                        console.log(res);
                    } catch(err){
                    console.log(err);
                    }
                };
                fetchByPriceAsc();
     }
    // ------------- DISPLAYING PRODUCTS BY CATEGORY AND PRICE DESC ---------------

     const sortByPriceDesc=(category)=>{
        const fetchByPriceDesc = async()=>{
            try {
                const res= await axios.get(`http://localhost:8800/productslist/pricedesc/${category}`)
                        props.setProducts(res.data)
                        console.log(res);
                    } catch(err){
                    console.log(err);
                    }
                };
                fetchByPriceDesc();
            }

    return (

            <Link className="text-sm font-bold leading-relaxed inline-block mr-4 py-2 whitespace-nowrap uppercase text-white" to="Products" element={<Products/>} >
             All Items
            </Link>
            <button className="cursor-pointer text-xl leading-none px-3 py-1 border border-solid border-transparent rounded bg-transparent block lg:hidden outline-none focus:outline-none" type="button">

            </button>

                <button onClick={() =>  searchByCategory (`Tops`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                   Tops
                </button>

                <button onClick={() =>  searchByCategory (`Bottoms`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                   Bottoms
                </button>

                <button onClick={() =>  searchByCategory (`Dresses`)} className="px-3 py-2 flex items-center text-xs uppercase font-bold leading-snug text-white hover:opacity-75" >
                   Dresses
                </button>

          {/* DROPDOWN MENU */}

        <button
          className="text-white bg-slate-700 hover:bg-slate-800 focus:ring-4 focus:outline-none focus:ring-slate-300 font-medium rounded-lg text-sm px-4 py-2.5 text-center inline-flex items-center"
          onClick={handleDropDown}
        >
          Sort By: (Price)
          <svg
            className="ml-2 w-4 h-4"
            aria-hidden="true"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              d="M19 9l-7 7-7-7"
            ></path>
          </svg>
        </button>

                <button onClick={() =>  sortByPriceAsc(``)} className="block py-2 px-4 hover:bg-gray-100">
                  Low to High
                </button>

                <button onClick={() =>  sortByPriceDesc(``)}  className="block py-2 px-4 hover:bg-gray-100">
                  High to Low
                </button>

          {/* <DropDownPrice/> */}

  )
}

API REQUESTS

//---------------------SORT PRODUCTS BY CATEGORY---------------------------

app.get("/productslist/:category", (req, res) => {
    const category = req.params.category;
    // console.log(category)
    const q = `SELECT * FROM products WHERE category = '${category}'`;
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });

//-------------------SORT PRODUCTS BY PRICE---------------------------------

app.get("/productslist/priceasc/:category", (req, res) => {
    const category = req.params.category;
    const q = `SELECT * FROM products WHERE category = '${category}' ORDER BY price ASC;`
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });

  app.get("/productslist/pricedesc/:category", (req, res) => {
    const category = req.params.category;
    const q = `SELECT * FROM products WHERE category = '${category}' ORDER BY price DESC;`
    db.query(q, (err, data) => {
      if (err) return res.json(err);
      return res.json(data);
    });
  });

I tried by writing the specific category, but it didn't display any products and even if it did, I would have to create a specific sort by price button for every category which is not what I want.

<button onClick={() =>  sortByPriceAsc(`Tops`)} className="block py-2 px-4 hover:bg-gray-100"> Low to High </button>


问:
How to get the contents of a triangular shaped div to fill its shape?
I have got a triangle shaped div containing text

It is within a body and section header.
It fits a triangle shape but cuts off most the text and I can't get the text to fill the width of the triangle and cut off appropriately.

I'm not sure if the problem is needing the contents to fit the div, or the div to change to the contents, I've been experimenting with white-space, display, and overflow but can't figure it out.

body { background-color: grey; }
.text-wrapper {
  display: block;
  width: 100%;
  height: 100%;
  border-width: 50% 0 50% 100%;
  border-color: transparent transparent transparent red;
  clip-path: polygon(0 0, 100% 0, 50% 100%);
  text-align: center;
  color: white;
  white-space: pre-wrap;
  overflow: auto;
  line-height: 1;
}

.main-header {
  color: #256D85;
  font-size: 7.5rem;
  font-family: "Montserrat", sans-serif;
  font-weight: 600;
}

.sub-header {
  color: #26B6E8;
  background-color: #06283D;
  font-size: 6rem;
  font-family: "Montserrat", sans-serif;
  font-weight: 600;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="text-wrapper">
  <p class="main-header">Text header</p>
  <p class="sub-header">Text sub-header</p>
  <p>description here</p>
</div></code>```

Body:
I have got a triangle shaped div containing text

It is within a body and section header.
It fits a triangle shape but cuts off most the text and I can't get the text to fill the width of the triangle and cut off appropriately.

I'm not sure if the problem is needing the contents to fit the div, or the div to change to the contents, I've been experimenting with white-space, display, and overflow but can't figure it out.

body { background-color: grey; }
.text-wrapper {
  display: block;
  width: 100%;
  height: 100%;
  border-width: 50% 0 50% 100%;
  border-color: transparent transparent transparent red;
  clip-path: polygon(0 0, 100% 0, 50% 100%);
  text-align: center;
  color: white;
  white-space: pre-wrap;
  overflow: auto;
  line-height: 1;
}

.main-header {
  color: #256D85;
  font-size: 7.5rem;
  font-family: "Montserrat", sans-serif;
  font-weight: 600;
}

.sub-header {
  color: #26B6E8;
  background-color: #06283D;
  font-size: 6rem;
  font-family: "Montserrat", sans-serif;
  font-weight: 600;
}

Text header

Text sub-header

description here


问:
How do I run NPM start on MAC?
I tried to setup everything I need to do REACT programming on a MAC computer OS HiSierra version 10.13.6 but after downloading Node I got this error below when doing NPM start:

xxxxxxx-iMac:linked-in-REACT-master Elizabeth$ npm start
dyld: lazy symbol binding failed: Symbol not found: ____chkstk_darwin
  Referenced from: /usr/local/bin/node (which was built for Mac OS X  10.15)
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: ____chkstk_darwin
  Referenced from: /usr/local/bin/node (which was built for Mac OS X 10.15)
  Expected in: /usr/lib/libSystem.B.dylib
```

I tried downloading the latest Node package.

Title: How do I run NPM start on MAC?

Body:
I tried to setup everything I need to do REACT programming on a MAC computer OS HiSierra version 10.13.6 but after downloading Node I got this error below when doing NPM start:

xxxxxxx-iMac:linked-in-REACT-master Elizabeth$ npm start
dyld: lazy symbol binding failed: Symbol not found: ____chkstk_darwin
  Referenced from: /usr/local/bin/node (which was built for Mac OS X  10.15)
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: ____chkstk_darwin
  Referenced from: /usr/local/bin/node (which was built for Mac OS X 10.15)
  Expected in: /usr/lib/libSystem.B.dylib

I tried downloading the latest Node package.


问:
loop not iterating in c
I have recently started coding and was trying to write a program to find the inverse of a matrix using Gauss Jordan method. I try to transform the given matrix to an identity matrix by using ro transformations and apply the same to corresponding elements of identity matrix.

```<code>#include <stdio.h>
void main()
{
    float a[5][5],b[5][5]={};
    int n,i,j,k,m,o,p,q;
    printf("Enter order n of square matrix : ");
    scanf("%d",&n);
    printf("Enter %d elements : ",n*n);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%f",&a[i][j]);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%10f",a[i][j]);
        printf("\n");
    }
    if(n>=3)
    {
        for(i=0;i<n;i++)
            b[i][i]=1;
        for(i=0;i<n-1;i++)
        {
                if(a[i][i]==0)
                    for(m=i+1;m<n;m++)
                        if(a[m][i]!=0)
                        {
                            for(o=0;o<n;o++)
                            {
                                a[m][o]+=a[m][o]+a[i][o];
                                a[i][o]=a[m][o]-a[i][o];
                                a[m][o]=a[m][o]-a[i][o];
                                b[m][o]+=b[m][o]+b[i][o];
                                b[i][o]=b[m][o]-b[i][o];
                                b[m][o]=b[m][o]-b[i][o];
                            }
                            break;
                        }
            for(j=i+1;j<n;j++)
                {if(a[j][i]!=0)
                {
                    for(k=0;k<n;k++)
                    {
                        b[j][k]=b[j][k]*a[i][i]-a[j][i]*b[i][k];
                        a[j][k]=a[j][k]*a[i][i]-a[j][i]*a[i][k];
                    }
                }
                for(p=0;p<n;p++)
                {
                    for(q=0;q<n;q++)
                        printf("%10f",a[p][q]);
                    printf("\t\t");
                    for(q=0;q<n;q++)
                        printf("%10f",b[p][q]);
                    printf("\n");
                }}
        }
            for(i=n-1;i>0;i--)
                for(j=i-1;j>=0;j--)
                    if(a[j][i]!=0)
                    {
                        for(k=0;k<n;k++)
                        {
                            b[j][k]=b[j][k]*a[i][i]-a[j][i]*b[i][k];
                            a[j][k]=a[j][k]*a[i][i]-a[j][i]*a[i][k];
                        }
                    }
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
                b[i][j]=(b[i][j])/(a[i][i]);
        printf("\n\n\n");
        for(i=0;i<n;i++)
        {
        for(j=0;j<n;j++)
        printf("%10f",b[i][j]);
        printf("\n");
        }
    }
}

</code>```

It is not giving the required output(correct inverse) and so i tried to print the two matrices after each row transformation(for the beginning part). Then i found that one of the loops was not iterating(the k variableloop) and loop was only running for k=0.I can't seem to find what is wrong.
the input which i was using was 3 , 1 2 3 4 5 6 7 8 8

Title: loop not iterating in c

Body:
I have recently started coding and was trying to write a program to find the inverse of a matrix using Gauss Jordan method. I try to transform the given matrix to an identity matrix by using ro transformations and apply the same to corresponding elements of identity matrix.

#include <stdio.h>
void main()
{
    float a[5][5],b[5][5]={};
    int n,i,j,k,m,o,p,q;
    printf("Enter order n of square matrix : ");
    scanf("%d",&n);
    printf("Enter %d elements : ",n*n);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%f",&a[i][j]);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
            printf("%10f",a[i][j]);
        printf("\n");
    }
    if(n>=3)
    {
        for(i=0;i<n;i++)
            b[i][i]=1;
        for(i=0;i<n-1;i++)
        {
                if(a[i][i]==0)
                    for(m=i+1;m<n;m++)
                        if(a[m][i]!=0)
                        {
                            for(o=0;o<n;o++)
                            {
                                a[m][o]+=a[m][o]+a[i][o];
                                a[i][o]=a[m][o]-a[i][o];
                                a[m][o]=a[m][o]-a[i][o];
                                b[m][o]+=b[m][o]+b[i][o];
                                b[i][o]=b[m][o]-b[i][o];
                                b[m][o]=b[m][o]-b[i][o];
                            }
                            break;
                        }
            for(j=i+1;j<n;j++)
                {if(a[j][i]!=0)
                {
                    for(k=0;k<n;k++)
                    {
                        b[j][k]=b[j][k]*a[i][i]-a[j][i]*b[i][k];
                        a[j][k]=a[j][k]*a[i][i]-a[j][i]*a[i][k];
                    }
                }
                for(p=0;p<n;p++)
                {
                    for(q=0;q<n;q++)
                        printf("%10f",a[p][q]);
                    printf("\t\t");
                    for(q=0;q<n;q++)
                        printf("%10f",b[p][q]);
                    printf("\n");
                }}
        }
            for(i=n-1;i>0;i--)
                for(j=i-1;j>=0;j--)
                    if(a[j][i]!=0)
                    {
                        for(k=0;k<n;k++)
                        {
                            b[j][k]=b[j][k]*a[i][i]-a[j][i]*b[i][k];
                            a[j][k]=a[j][k]*a[i][i]-a[j][i]*a[i][k];
                        }
                    }
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
                b[i][j]=(b[i][j])/(a[i][i]);
        printf("\n\n\n");
        for(i=0;i<n;i++)
        {
        for(j=0;j<n;j++)
        printf("%10f",b[i][j]);
        printf("\n");
        }
    }
}

It is not giving the required output(correct inverse) and so i tried to print the two matrices after each row transformation(for the beginning part). Then i found that one of the loops was not iterating(the k variableloop) and loop was only running for k=0.I can't seem to find what is wrong.
the input which i was using was 3 , 1 2 3 4 5 6 7 8 8


问:
I would like to save my crop image to my django database called model filed file
I have the following models.py

```<code>class Imageo(models.Model):
    file = models.ImageField(upload_to='cropped_images')
    uploaded = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)
</code>```

I would like to savemy file into my Imageo models but it is saving into my database some other folder, please look at the views.py file.

```<code>def con(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = Image.open(form.cleaned_data['file'])
            image = image.resize((200, 200), PIL.Image.ANTIALIAS)
            image = image.convert('RGB')
            dt = image.save('resize.jpg')
            # i would like to save resize.jpg into my models name called file
            return HttpResponse('done')
    else:
        form = ImageForm()

    img = Imageo.objects.latest('id')
    return render(request, 'NEC/imgCon.html', {'form': form, 'img': img})
</code>```

Body:
I have the following models.py

class Imageo(models.Model):
    file = models.ImageField(upload_to='cropped_images')
    uploaded = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)

I would like to savemy file into my Imageo models but it is saving into my database some other folder, please look at the views.py file.

def con(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = Image.open(form.cleaned_data['file'])
            image = image.resize((200, 200), PIL.Image.ANTIALIAS)
            image = image.convert('RGB')
            dt = image.save('resize.jpg')
            # i would like to save resize.jpg into my models name called file
            return HttpResponse('done')
    else:
        form = ImageForm()

    img = Imageo.objects.latest('id')
    return render(request, 'NEC/imgCon.html', {'form': form, 'img': img})


问:
Error in setting up Laravel sail with docker
Working on setup for a php class, and I keep running into an error when trying to setup the example windows laravel app from the docs (https://laravel.com/docs/9.x/installation#getting-started-on-windows). After entering:

```<code>curl -s https://laravel.build/example-app | bash
</code>```

I get the following error:

```<code>
Processing fstab with mount -a failed.

<3>WSL (17) ERROR: CreateProcessEntryCommon:358: getpwuid(0) failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:362: getpwuid(0) failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:570: execvpe /bin/bash failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:579: Create process not expected to return
</code>```

As far as I know, I have docker and wsl2 installed correctly so I am unsure as to what is causing this error. I have Ubuntu installed as well, but unless I misunderstood the docs, I should just be able to punch the curl straight into cmd prompt to build it in the desired directory.

Body:
Working on setup for a php class, and I keep running into an error when trying to setup the example windows laravel app from the docs (https://laravel.com/docs/9.x/installation#getting-started-on-windows). After entering:

curl -s https://laravel.build/example-app | bash

I get the following error:

Processing fstab with mount -a failed.

<3>WSL (17) ERROR: CreateProcessEntryCommon:358: getpwuid(0) failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:362: getpwuid(0) failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:570: execvpe /bin/bash failed 2
<3>WSL (17) ERROR: CreateProcessEntryCommon:579: Create process not expected to return

As far as I know, I have docker and wsl2 installed correctly so I am unsure as to what is causing this error. I have Ubuntu installed as well, but unless I misunderstood the docs, I should just be able to punch the curl straight into cmd prompt to build it in the desired directory.


问:
List column names used by a custom function using a panda DataFrame as input
I am currently building a small app to post-process more easily data stored in HDF5 files (generated by a  1D simulation proprietary software, the output being basically a very large table with ~10k variables, y-axis corresponding to time). I want the user to be able to write custom functions generating series from the data (for plotting). My problem is that the HDF5 file can be quite large and I would like to open it a single time and extract only the necessary data for performance reasons. Column names to load depend on the user-defined functions, so I need to inspect them and collect the calls to 'df.loc' and 'df.getitem()' to list the columns to extract. I am looking for the best way to do that.

Below is a simplified example of my current implementation, using a 'spy' object wrapping a dummy dataframe and listing the keys used when 'get_item' is called. Something similar could be done for pandas 'loc' dataframe method.

```<code>import pandas as pd
from scipy import integrate

# Data for the example
data = {
    'TIME': [0,1,2,3,4,5],
    'frac[air]': [0,0,0,0,0,0],
    'frac[water]': [0.5,0.4,0.2,0,0,0],
    'frac[oil]': [0.5,0.6,0.8,1,1,1],
    'flowrate': [9999,0,0.1,0.2,0,0],
}

def read_data(var_names, loc_filter=None):
    """Simple table reading here, but in real application I am
    reading a large hdf5 file. The filter is typicaly used to
    select time slices (or slices corresponding to some states
    of the system described by the dataframe) through pandas
    dataframe loc method"""
    if loc_filter is None:
        df = pd.DataFrame(data=data)
    else:
        df = pd.DataFrame(data=data).loc[loc_filter]
    return df[var_names]

# User-defined functions using only a few columns of the large dataframe
# Constraint: new functions can be defined by the user ! 2 Examples below
def grp_liq (df, var_name):
    """Summing fractions corresponding to liquids"""
    return df[var_name+'[water]'] + df[var_name+'[oil]']
def integ (df, var_name):
    """Cumulative integration of a variable over time"""
    return pd.Series(integrate.cumtrapz(df[var_name], df['TIME']))

# Creation of a 'spy' object wrapping a dummy dataframe to be able to
# inspect functions
class DFProxyGetItemSpy:
    def __init__(self):
        self._var_names = []
        self._df_dum = pd.DataFrame({'dum':[1]})

    # __getitem__ defined to list used var_names
    def __getitem__(self, key):
        if key not in self._var_names:
            self._var_names.append(key)
        # Returning a dummy series to limit the risk of error raising
        #  if a DataFrame-specific attribute/method is used in the function
        return self._df_dum['dum']

    # __getattr__ defined to pass any attribute to the dummy DataFrame
    def __getattr__(self, name):
        return self._df_dum.__getattribute__(name)

    # Function to reset spy object
    def reset(self):
        self._var_names = []

    @property
    def var_names(self):
        return self._var_names

##################
# DATA REQUEST 1 #
##################

# Spying a user function to list the variables used
spy = DFProxyGetItemSpy()
grp_liq(spy,'frac')
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df = read_data(spy.var_names)
print(grp_liq(df,'frac'))

##################
# DATA REQUEST 2 #
##################
spy.reset()

# Spying a second user function, but this time we also want to
# set a filter --> this function needs to be spyied too ...
spy = DFProxyGetItemSpy()
integ(spy,'flowrate')
my_filter = lambda df: df['TIME']>0
my_filter(spy)
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df2 = read_data(spy.var_names, loc_filter=my_filter)
print(integ(df2,'flowrate'))
</code>```

I find this approach inelegant and I am looking for a better way to do that. I have been looking a bit in dask documentation to see if information about the keys used in a function could be extracted from the graph, but I was not successful. To formalize my question: what would be a good way to allow a user to define custom functions to manipulate a dataframe (using any function from pandas), and list the necessary keys to limit the amount of data to load ?

Thanks in advance for any answer, any advice is welcome too !

Body:
I am currently building a small app to post-process more easily data stored in HDF5 files (generated by a  1D simulation proprietary software, the output being basically a very large table with ~10k variables, y-axis corresponding to time). I want the user to be able to write custom functions generating series from the data (for plotting). My problem is that the HDF5 file can be quite large and I would like to open it a single time and extract only the necessary data for performance reasons. Column names to load depend on the user-defined functions, so I need to inspect them and collect the calls to 'df.loc' and 'df.getitem()' to list the columns to extract. I am looking for the best way to do that.

Below is a simplified example of my current implementation, using a 'spy' object wrapping a dummy dataframe and listing the keys used when 'get_item' is called. Something similar could be done for pandas 'loc' dataframe method.

import pandas as pd
from scipy import integrate

# Data for the example
data = {
    'TIME': [0,1,2,3,4,5],
    'frac[air]': [0,0,0,0,0,0],
    'frac[water]': [0.5,0.4,0.2,0,0,0],
    'frac[oil]': [0.5,0.6,0.8,1,1,1],
    'flowrate': [9999,0,0.1,0.2,0,0],
}

def read_data(var_names, loc_filter=None):
    """Simple table reading here, but in real application I am
    reading a large hdf5 file. The filter is typicaly used to
    select time slices (or slices corresponding to some states
    of the system described by the dataframe) through pandas
    dataframe loc method"""
    if loc_filter is None:
        df = pd.DataFrame(data=data)
    else:
        df = pd.DataFrame(data=data).loc[loc_filter]
    return df[var_names]

# User-defined functions using only a few columns of the large dataframe
# Constraint: new functions can be defined by the user ! 2 Examples below
def grp_liq (df, var_name):
    """Summing fractions corresponding to liquids"""
    return df[var_name+'[water]'] + df[var_name+'[oil]']
def integ (df, var_name):
    """Cumulative integration of a variable over time"""
    return pd.Series(integrate.cumtrapz(df[var_name], df['TIME']))

# Creation of a 'spy' object wrapping a dummy dataframe to be able to
# inspect functions
class DFProxyGetItemSpy:
    def __init__(self):
        self._var_names = []
        self._df_dum = pd.DataFrame({'dum':[1]})

    # __getitem__ defined to list used var_names
    def __getitem__(self, key):
        if key not in self._var_names:
            self._var_names.append(key)
        # Returning a dummy series to limit the risk of error raising
        #  if a DataFrame-specific attribute/method is used in the function
        return self._df_dum['dum']

    # __getattr__ defined to pass any attribute to the dummy DataFrame
    def __getattr__(self, name):
        return self._df_dum.__getattribute__(name)

    # Function to reset spy object
    def reset(self):
        self._var_names = []

    @property
    def var_names(self):
        return self._var_names

##################
# DATA REQUEST 1 #
##################

# Spying a user function to list the variables used
spy = DFProxyGetItemSpy()
grp_liq(spy,'frac')
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df = read_data(spy.var_names)
print(grp_liq(df,'frac'))

##################
# DATA REQUEST 2 #
##################
spy.reset()

# Spying a second user function, but this time we also want to
# set a filter --> this function needs to be spyied too ...
spy = DFProxyGetItemSpy()
integ(spy,'flowrate')
my_filter = lambda df: df['TIME']>0
my_filter(spy)
print(spy.var_names)

# Now that we know what variables to extract, we can actualy
# read the data and do our operations
df2 = read_data(spy.var_names, loc_filter=my_filter)
print(integ(df2,'flowrate'))

I find this approach inelegant and I am looking for a better way to do that. I have been looking a bit in dask documentation to see if information about the keys used in a function could be extracted from the graph, but I was not successful. To formalize my question: what would be a good way to allow a user to define custom functions to manipulate a dataframe (using any function from pandas), and list the necessary keys to limit the amount of data to load ?

Thanks in advance for any answer, any advice is welcome too !


问:
Problems with SearchView (items appearing and dissapearing when a button is clicked)
I have a list of items on a Recyclerview, and I also have a SearchView to filther those items.

Every item has a favourite button, so when you click, the item adds to favorite table.

The problem is that, when I filter something and I start clicking those buttons, odd things happens: some items dissapear from the filtered list. It doesn't happen always, only sometimes. How can I fix this?

My code:

My class:

```<code>class CoasterFragment : Fragment() {

    private val myAdapter by lazy { CoasterRecyclerViewAdapter(CoasterListenerImpl(requireContext(), viewModel),requireContext()) }
     private lateinit var searchView: SearchView
     private var _binding: FragmentCoasterBinding? = null
     private val binding get() = _binding!!

     private val viewModel: CoastersViewModel by viewModels()
     override fun onCreateView(
             inflater: LayoutInflater,
             container: ViewGroup?,
             savedInstanceState: Bundle?

         ): View {
         _binding = FragmentCoasterBinding.inflate(inflater, container, false)
         val root: View = binding.root
         val recyclerView = binding.recyclerCoaster
         recyclerView.adapter = myAdapter
         recyclerView.layoutManager = LinearLayoutManager(requireContext())

         viewModel.coasters().observe(viewLifecycleOwner){myAdapter.setData(it)}

         searchView = binding.search
         searchView.clearFocus()
         searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
             override fun onQueryTextSubmit(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                     searchView.clearFocus()
                 }
                 return true
             }
             override fun onQueryTextChange(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                 }
                 return true
             }
         })

         return root
     }

     fun searchDatabase(query: String) {
         val searchQuery = "%$query%"

         viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { myAdapter.setData(it)
         }
     }

     override fun onDestroyView() {
         super.onDestroyView()
         _binding = null
     }
 }
</code>```

Here is my adapter code:

```<code>class  CoasterRecyclerViewAdapter( val listener: CoasterListener,
                                  val context: Context  )  : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){

    private var coasterList = emptyList<CoasterFavorito>()

    class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
                                         private val context: Context): RecyclerView.ViewHolder(binding.root){

        companion object{
            fun crearViewHolder(parent: ViewGroup, listener: CoasterListener,  context: Context):ViewHolder{
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding, listener, context )
            }
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, context)
    override fun onBindViewHolder(holder: ViewHolder, position: Int){
        holder.binding.nombre.text = coasterList[position].coaster.nombre
        holder.binding.parque.text = coasterList[position].coaster.parque
        holder.binding.ciudad.text = coasterList[position].coaster.ciudad
        holder.binding.provincia.text = coasterList[position].coaster.provincia
        holder.binding.comunidad.text = coasterList[position].coaster.comunidadAutonoma
        Glide
            .with(context)
            .load(coasterList[position].coaster.imagen)
            .centerCrop()
            .into(holder.binding.imagen)

        holder.binding.check.isChecked = coasterList[position].favorito
        holder.binding.check.setOnClickListener{
            if (coasterList[position].favorito) {
                listener.delFavorito(coasterList[position].coaster.id)
                holder.binding.check.isChecked = false

            } else {
                listener.addFavorito(coasterList[position].coaster.id)

                holder.binding.check.isChecked = true

            }
        }
    }
    override fun getItemCount(): Int{
        return coasterList.size
    }
    fun setData(coaster: List<CoasterFavorito>){
        coasterList = coaster
        notifyDataSetChanged()
    }
}

interface CoasterListener {
    fun addFavorito(id: Long)
    fun delFavorito(id: Long)
}
</code>```

The search Query:

```<code>@Query ("SELECT c.*,  " + "EXISTS (SELECT * from montarse where usuario_id=:id and coaster_id = c.id) as favorito " + "FROM coasters c " + "WHERE nombre LIKE :searchQuery OR parque LIKE :searchQuery OR ciudad LIKE :searchQuery OR comunidadAutonoma LIKE :searchQuery OR provincia LIKE :searchQuery")
    fun searchCoaster(id: Long, searchQuery: String): Flow<List<CoasterFavorito>>
</code>```

My viewModel:

```<code>fun searchDatabase( searchQuery: String): LiveData<List<CoasterFavorito>> {
        return coasterDao.searchCoaster( App.getUsuario()!!.id, searchQuery).asLiveData()
    }

    fun addFavorito( coasterId: Long) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                usuarioCoasterDao.create(UsuarioCoaster(App.getUsuario()!!.id, coasterId, null, null))
            }
        }
    }

fun coasters(): LiveData<List<CoasterFavorito>> {
        return  coasterDao.findAllFav(App.getUsuario()!!.id).asLiveData()

        }
</code>```

my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.coaster.HomeCoasterFragment">

    <androidx.appcompat.widget.SearchView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:id="@+id/search"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:iconifiedByDefault="false"
        app:searchHintIcon="@null"
        android:queryHint="Buscar..."
        android:focusable="false"
        />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerCoaster"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginBottom="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/search"
        tools:listitem="@layout/coaster_item" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I tried changind the clear focus().

Also I added some if else (for example, if the searchView is Empty, then load the list from the adapter as normal. If it is not empty, use the SearchView code to filter and load the list.

Body:
I have a list of items on a Recyclerview, and I also have a SearchView to filther those items.

Every item has a favourite button, so when you click, the item adds to favorite table.

The problem is that, when I filter something and I start clicking those buttons, odd things happens: some items dissapear from the filtered list. It doesn't happen always, only sometimes. How can I fix this?

My code:

My class:

class CoasterFragment : Fragment() {

    private val myAdapter by lazy { CoasterRecyclerViewAdapter(CoasterListenerImpl(requireContext(), viewModel),requireContext()) }
     private lateinit var searchView: SearchView
     private var _binding: FragmentCoasterBinding? = null
     private val binding get() = _binding!!

     private val viewModel: CoastersViewModel by viewModels()
     override fun onCreateView(
             inflater: LayoutInflater,
             container: ViewGroup?,
             savedInstanceState: Bundle?

         ): View {
         _binding = FragmentCoasterBinding.inflate(inflater, container, false)
         val root: View = binding.root
         val recyclerView = binding.recyclerCoaster
         recyclerView.adapter = myAdapter
         recyclerView.layoutManager = LinearLayoutManager(requireContext())

         viewModel.coasters().observe(viewLifecycleOwner){myAdapter.setData(it)}

         searchView = binding.search
         searchView.clearFocus()
         searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
             override fun onQueryTextSubmit(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                     searchView.clearFocus()
                 }
                 return true
             }
             override fun onQueryTextChange(query: String?): Boolean {
                 if(query != null){
                     searchDatabase(query)
                 }
                 return true
             }
         })

         return root
     }

     fun searchDatabase(query: String) {
         val searchQuery = "%$query%"

         viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { myAdapter.setData(it)
         }
     }

     override fun onDestroyView() {
         super.onDestroyView()
         _binding = null
     }
 }

Here is my adapter code:

class  CoasterRecyclerViewAdapter( val listener: CoasterListener,
                                  val context: Context  )  : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){

    private var coasterList = emptyList<CoasterFavorito>()

    class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
                                         private val context: Context): RecyclerView.ViewHolder(binding.root){

        companion object{
            fun crearViewHolder(parent: ViewGroup, listener: CoasterListener,  context: Context):ViewHolder{
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding, listener, context )
            }
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, context)
    override fun onBindViewHolder(holder: ViewHolder, position: Int){
        holder.binding.nombre.text = coasterList[position].coaster.nombre
        holder.binding.parque.text = coasterList[position].coaster.parque
        holder.binding.ciudad.text = coasterList[position].coaster.ciudad
        holder.binding.provincia.text = coasterList[position].coaster.provincia
        holder.binding.comunidad.text = coasterList[position].coaster.comunidadAutonoma
        Glide
            .with(context)
            .load(coasterList[position].coaster.imagen)
            .centerCrop()
            .into(holder.binding.imagen)

        holder.binding.check.isChecked = coasterList[position].favorito
        holder.binding.check.setOnClickListener{
            if (coasterList[position].favorito) {
                listener.delFavorito(coasterList[position].coaster.id)
                holder.binding.check.isChecked = false

            } else {
                listener.addFavorito(coasterList[position].coaster.id)

                holder.binding.check.isChecked = true

            }
        }
    }
    override fun getItemCount(): Int{
        return coasterList.size
    }
    fun setData(coaster: List<CoasterFavorito>){
        coasterList = coaster
        notifyDataSetChanged()
    }
}

interface CoasterListener {
    fun addFavorito(id: Long)
    fun delFavorito(id: Long)
}

The search Query:

@Query ("SELECT c.*,  " + "EXISTS (SELECT * from montarse where usuario_id=:id and coaster_id = c.id) as favorito " + "FROM coasters c " + "WHERE nombre LIKE :searchQuery OR parque LIKE :searchQuery OR ciudad LIKE :searchQuery OR comunidadAutonoma LIKE :searchQuery OR provincia LIKE :searchQuery")
    fun searchCoaster(id: Long, searchQuery: String): Flow<List<CoasterFavorito>>

My viewModel:

fun searchDatabase( searchQuery: String): LiveData<List<CoasterFavorito>> {
        return coasterDao.searchCoaster( App.getUsuario()!!.id, searchQuery).asLiveData()
    }

    fun addFavorito( coasterId: Long) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                usuarioCoasterDao.create(UsuarioCoaster(App.getUsuario()!!.id, coasterId, null, null))
            }
        }
    }

fun coasters(): LiveData<List<CoasterFavorito>> {
        return  coasterDao.findAllFav(App.getUsuario()!!.id).asLiveData()

        }

my XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.coaster.HomeCoasterFragment">

    <androidx.appcompat.widget.SearchView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:id="@+id/search"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:iconifiedByDefault="false"
        app:searchHintIcon="@null"
        android:queryHint="Buscar..."
        android:focusable="false"
        />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerCoaster"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginBottom="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/search"
        tools:listitem="@layout/coaster_item" />

</androidx.constraintlayout.widget.ConstraintLayout>

I tried changind the clear focus().

Also I added some if else (for example, if the searchView is Empty, then load the list from the adapter as normal. If it is not empty, use the SearchView code to filter and load the list.


问:
Weird error Matlab with piecewise elements in matrix
I'm trying to solve a differential equation that has the form Y'(t)=A(t)*Y(t), where Y and Y' is a column with 4 elements, A is a 4x4 matrix. In the A(t) matrix I'm using the functions m(t) and f(t) to compute each value of the matrix. However, when I put a simple value to m(t) and f(t) (ex: a constant value or a t^2...) the function  solvedPmWithTime returns a 4x1 matrix, which is what I expect, but when I use the m(t) and /or function f(t) that I want, which is computed by the compute_m_and_f function, it returns a 1x1 matrix. I can't find my error. If someone could help it would be very much appreciated :). Here are the codes of the functions and the code of the live script that I use to compute the differential equation:

```<code>function [m,f] = compute_m_and_f()
    syms m(t) f(t)
    Bm =600000;
    sigmam =2.5;
    tm =6;
    tf =6;
    sigmaf = 2;
    Bf = 600000;

    eqnM = diff(m,t) == Bm / sqrt(2*pi*sigmam^2)*exp(-((t-tm)^2)/(2*sigmam^2));
    condM = m(0)==0;

    eqnF = diff(f,t) == Bf / sqrt(2*pi*sigmaf^2)*exp(-((t-tf)^2)/(2*sigmaf^2));
    condF = f(0)==0;

    M(t) = dsolve(eqnM, condM);
    F(t) = dsolve(eqnF, condF);

    taum = 4;
    tauf = 5;

    m(t) = piecewise(t>taum, M(t)-M(t-taum),M(t));
    f(t) = piecewise(t>tauf, F(t)-F(t-taum),F(t));
end
</code>```
```<code>function solvedPmWithTime= solvedPmWithTime(~, y)

    [m, f] = compute_m_and_f;

    alpha = 480;
    beta = 0.0011;

    sigma = 0.0634;
    epsilon = 0.0725;

    a = (alpha * (f + m)) / (1 + alpha * beta * (f + m));

    b11 =- (1 - (m / (f + m)) ^ sigma);
    b12 = (1 - (f / (f + m)) ^ epsilon);
    b13 = (1 - (f / (f + m)) ^ epsilon);
    b14 = (1 - (f / (f + m)) ^ epsilon);

    b21 = (1 - (m / (f + m)) ^ sigma);
    b22 = -1;
    b23 = 0;
    b24 = 0;

    b31 = 0;
    b32 = (f / (f + m)) ^ epsilon;
    b33 = -1;
    b34 = 0;

    b41 = 0;
    b42 = 0;
    b43 = (f / (f + m)) ^ epsilon;
    b44 =- (1 - (f / (f + m)) ^ epsilon);

    b = [b11, b12, b13, b14; b21, b22, b23, b24; b31, b32, b33, b34; b41, b42, b43, b44];
    A = a * b;
    solvedPmWithTime = A * y;
end

</code>```
```<code>clear all
rho = 6;
Bf = 600000;

Pm1_0 = 0;
Pm2_0 = 0;
Pm3_0 = 0;
Pf_0 = 3600;
[t, Pm] = ode45(@solvedPmWithTime, [0, 100], [Pm1_0; Pm2_0; Pm3_0; Pf_0]); %this returns an error because the size of the matrix is not 4x1

Pm1 = Pm(:, 1);
Pm2 = Pm(:, 2);
Pm3 = Pm(:, 3);
Pf = Pm(:, 4);
hold off
plot(t, Pm1, t, Pm2, t, Pm3, t, Pf)
legend('Pm1', 'Pm2', 'Pm3', 'Pf')

n = solvedPmWithTime([0, 100], [Pm1_0; Pm2_0; Pm3_0; Pf_0]);
size(n)
</code>```

Body:
I'm trying to solve a differential equation that has the form Y'(t)=A(t)*Y(t), where Y and Y' is a column with 4 elements, A is a 4x4 matrix. In the A(t) matrix I'm using the functions m(t) and f(t) to compute each value of the matrix. However, when I put a simple value to m(t) and f(t) (ex: a constant value or a t^2...) the function  solvedPmWithTime returns a 4x1 matrix, which is what I expect, but when I use the m(t) and /or function f(t) that I want, which is computed by the compute_m_and_f function, it returns a 1x1 matrix. I can't find my error. If someone could help it would be very much appreciated :). Here are the codes of the functions and the code of the live script that I use to compute the differential equation:

function [m,f] = compute_m_and_f()
    syms m(t) f(t)
    Bm =600000;
    sigmam =2.5;
    tm =6;
    tf =6;
    sigmaf = 2;
    Bf = 600000;

    eqnM = diff(m,t) == Bm / sqrt(2*pi*sigmam^2)*exp(-((t-tm)^2)/(2*sigmam^2));
    condM = m(0)==0;

    eqnF = diff(f,t) == Bf / sqrt(2*pi*sigmaf^2)*exp(-((t-tf)^2)/(2*sigmaf^2));
    condF = f(0)==0;

    M(t) = dsolve(eqnM, condM);
    F(t) = dsolve(eqnF, condF);

    taum = 4;
    tauf = 5;

    m(t) = piecewise(t>taum, M(t)-M(t-taum),M(t));
    f(t) = piecewise(t>tauf, F(t)-F(t-taum),F(t));
end

function solvedPmWithTime= solvedPmWithTime(~, y)

    [m, f] = compute_m_and_f;

    alpha = 480;
    beta = 0.0011;

    sigma = 0.0634;
    epsilon = 0.0725;

    a = (alpha * (f + m)) / (1 + alpha * beta * (f + m));

    b11 =- (1 - (m / (f + m)) ^ sigma);
    b12 = (1 - (f / (f + m)) ^ epsilon);
    b13 = (1 - (f / (f + m)) ^ epsilon);
    b14 = (1 - (f / (f + m)) ^ epsilon);

    b21 = (1 - (m / (f + m)) ^ sigma);
    b22 = -1;
    b23 = 0;
    b24 = 0;

    b31 = 0;
    b32 = (f / (f + m)) ^ epsilon;
    b33 = -1;
    b34 = 0;

    b41 = 0;
    b42 = 0;
    b43 = (f / (f + m)) ^ epsilon;
    b44 =- (1 - (f / (f + m)) ^ epsilon);

    b = [b11, b12, b13, b14; b21, b22, b23, b24; b31, b32, b33, b34; b41, b42, b43, b44];
    A = a * b;
    solvedPmWithTime = A * y;
end

clear all
rho = 6;
Bf = 600000;

Pm1_0 = 0;
Pm2_0 = 0;
Pm3_0 = 0;
Pf_0 = 3600;
[t, Pm] = ode45(@solvedPmWithTime, [0, 100], [Pm1_0; Pm2_0; Pm3_0; Pf_0]); %this returns an error because the size of the matrix is not 4x1

Pm1 = Pm(:, 1);
Pm2 = Pm(:, 2);
Pm3 = Pm(:, 3);
Pf = Pm(:, 4);
hold off
plot(t, Pm1, t, Pm2, t, Pm3, t, Pf)
legend('Pm1', 'Pm2', 'Pm3', 'Pf')

n = solvedPmWithTime([0, 100], [Pm1_0; Pm2_0; Pm3_0; Pf_0]);
size(n)


问:
coroutine was never awaited in async-mqtt
I have a problem with asyncio, in this program I use asyncua that is for OPC protocol and asyncio_mqtt, my program should wait for connection to broker even if any problem occurred in broker side, it should wait until get connected again but this error happened:

```<code>Closing Loop
Reconnect to Server in 3 ...
Reconnect to Server in 2 ...
Traceback (most recent call last):
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 310, in <module>
    main(server_state)
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 300, in main
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 324, in <module>
    asyncio.run(main(server_state))
                ^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 300, in main
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.
Reconnect to Server in 1 ...
sys:1: RuntimeWarning: coroutine 'test' was never awaited

Process finished with exit code 1
</code>```

Here is some part of program, in main function, test function called and run async-mqtt:

```<code>import asyncio
import json
import logging
import time

from dataStructure import *
from opcConnection import *
from asyncua.ua import ObjectIds
from asyncua.ua.uatypes import NodeId
from asyncua import Client, Node, ua
from asyncio_mqtt import Client as ClientM
from asyncio_mqtt import MqttError
from asyncer import asyncify

async def test() -> None:
    structPad = set_structure('>8sh')
    structData = set_structure('<hffbb')
    firstTime = True
    timeSync = None
    dataDict = {}
    try:

        logger.info("Connecting to MQTT")
        async with ClientM(hostname="192.168.1.51", port=1883, client_id="OPC_client") as clientMqtt:
            logger.info("Connection to MQTT open")
            async with clientMqtt.unfiltered_messages() as messages:
                await clientMqtt.subscribe(mqttTopic)
                async for message in messages:
                    if message.topic == "TimeSync":
                        timeSync = message.payload
                        print(timeSync)
                    if firstTime:
                        await clientMqtt.publish("ready_to_Receive_opc_topic", payload="")
                        firstTime = False
                    if message.topic == "send_opc_tag":
                        print(message.payload.decode("UTF-8"))
                        dataBase, opcServers = await create_database(message)
                        dataDict, client = await create_dataDict(dataBase)
                        print(dataDict)
                        logger.info(
                            "Message %s %s", message.topic, message.payload
                        )
                    if message.topic == "Receive_OPC_Server":
                        bMessage = message.payload.decode('UTF-8')
                        # dataBase = json.loads(bMessage["send_opc_tag"])
                        client_rec = await opcConnection(bMessage)
                        if client_rec != 0:
                            nodesTree = await catchNodes(client_rec)
                            await clientMqtt.publish('OPC_Server_Tree', nodesTree)
                            print("Tree Cached")
                        else:
                            clientMqtt.publish('OPC_Server_Tree', "")
                            print("Not Tree")
                    if dataDict != {}:
                        dataDict = await get_values(dataDict, client)

                        value = []
                        percentt = []
                        id = []
                        for i in dataDict:
                            id.append(i)
                            if dataDict[i]["nodeList"] != []:
                                if dataDict[i]["values"][0] is None:
                                    value.append(00.00)
                                    dataDict[i]["percent"] = 00.00
                                    percentt.append(0.0)
                                else:
                                    value.append(dataDict[i]["values"][0])
                                    dataDict[i]["percent"] = percentage(dataDict[i]["VMX"], dataDict[i]["VMN"],
                                                                        dataDict[i]["values"])
                                    percentt.append(dataDict[i]["percent"][0])
                                dataDict[i]["timeStamp"] = timeSync
                                dataDict[i]['bufferSize'] = buffer_data_get_padding(structPad, dataDict[i]["bufferSize"], 0,
                                                                                timeSync, 1)

                        values = {
                            "id": id,
                            "values": value,
                            "percent": percentt,
                            "buffer": estimate_buffer_size(len(value))
                        }
                        buffer = values["buffer"]
                        buffer_data_get_padding(structPad, buffer, 0, timeSync, len(value))
                        buffer_data_get(structData, buffer, values)

                        print(values["values"])
                        await clientMqtt.publish("live_OPC_tags_value", payload=buffer)

    except MqttError as e:
        logger.error("Connection to MQTT closed: " + str(e))
    except Exception:
        logger.exception("Connection to MQTT closed")
    await asyncio.sleep(3)

clientMqtt = None
server_state = True

def main(server_state):
    mqttTopic = [("send_opc_tag", QOS_1), ("TimeSync", QOS_1), ("Receive_OPC_Server", QOS_1)]
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))

if __name__ == "__main__":
    try:
        set_connection = True

        main(server_state)

    except KeyboardInterrupt:
        pass
    finally:
        print("Closing Loop")
        for i in range(3):
            time.sleep(1)
            print(f"Reconnect to Server in {3 - i} ...")
        asyncio.run(main(server_state))
</code>```

Body:
I have a problem with asyncio, in this program I use asyncua that is for OPC protocol and asyncio_mqtt, my program should wait for connection to broker even if any problem occurred in broker side, it should wait until get connected again but this error happened:

Closing Loop
Reconnect to Server in 3 ...
Reconnect to Server in 2 ...
Traceback (most recent call last):
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 310, in <module>
    main(server_state)
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 300, in main
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 324, in <module>
    asyncio.run(main(server_state))
                ^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\PycharmProjects\OpcProject\final_main.py", line 300, in main
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\O.Fathi\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.
Reconnect to Server in 1 ...
sys:1: RuntimeWarning: coroutine 'test' was never awaited

Process finished with exit code 1

Here is some part of program, in main function, test function called and run async-mqtt:

import asyncio
import json
import logging
import time

from dataStructure import *
from opcConnection import *
from asyncua.ua import ObjectIds
from asyncua.ua.uatypes import NodeId
from asyncua import Client, Node, ua
from asyncio_mqtt import Client as ClientM
from asyncio_mqtt import MqttError
from asyncer import asyncify

async def test() -> None:
    structPad = set_structure('>8sh')
    structData = set_structure('<hffbb')
    firstTime = True
    timeSync = None
    dataDict = {}
    try:

        logger.info("Connecting to MQTT")
        async with ClientM(hostname="192.168.1.51", port=1883, client_id="OPC_client") as clientMqtt:
            logger.info("Connection to MQTT open")
            async with clientMqtt.unfiltered_messages() as messages:
                await clientMqtt.subscribe(mqttTopic)
                async for message in messages:
                    if message.topic == "TimeSync":
                        timeSync = message.payload
                        print(timeSync)
                    if firstTime:
                        await clientMqtt.publish("ready_to_Receive_opc_topic", payload="")
                        firstTime = False
                    if message.topic == "send_opc_tag":
                        print(message.payload.decode("UTF-8"))
                        dataBase, opcServers = await create_database(message)
                        dataDict, client = await create_dataDict(dataBase)
                        print(dataDict)
                        logger.info(
                            "Message %s %s", message.topic, message.payload
                        )
                    if message.topic == "Receive_OPC_Server":
                        bMessage = message.payload.decode('UTF-8')
                        # dataBase = json.loads(bMessage["send_opc_tag"])
                        client_rec = await opcConnection(bMessage)
                        if client_rec != 0:
                            nodesTree = await catchNodes(client_rec)
                            await clientMqtt.publish('OPC_Server_Tree', nodesTree)
                            print("Tree Cached")
                        else:
                            clientMqtt.publish('OPC_Server_Tree', "")
                            print("Not Tree")
                    if dataDict != {}:
                        dataDict = await get_values(dataDict, client)

                        value = []
                        percentt = []
                        id = []
                        for i in dataDict:
                            id.append(i)
                            if dataDict[i]["nodeList"] != []:
                                if dataDict[i]["values"][0] is None:
                                    value.append(00.00)
                                    dataDict[i]["percent"] = 00.00
                                    percentt.append(0.0)
                                else:
                                    value.append(dataDict[i]["values"][0])
                                    dataDict[i]["percent"] = percentage(dataDict[i]["VMX"], dataDict[i]["VMN"],
                                                                        dataDict[i]["values"])
                                    percentt.append(dataDict[i]["percent"][0])
                                dataDict[i]["timeStamp"] = timeSync
                                dataDict[i]['bufferSize'] = buffer_data_get_padding(structPad, dataDict[i]["bufferSize"], 0,
                                                                                timeSync, 1)

                        values = {
                            "id": id,
                            "values": value,
                            "percent": percentt,
                            "buffer": estimate_buffer_size(len(value))
                        }
                        buffer = values["buffer"]
                        buffer_data_get_padding(structPad, buffer, 0, timeSync, len(value))
                        buffer_data_get(structData, buffer, values)

                        print(values["values"])
                        await clientMqtt.publish("live_OPC_tags_value", payload=buffer)

    except MqttError as e:
        logger.error("Connection to MQTT closed: " + str(e))
    except Exception:
        logger.exception("Connection to MQTT closed")
    await asyncio.sleep(3)

clientMqtt = None
server_state = True

def main(server_state):
    mqttTopic = [("send_opc_tag", QOS_1), ("TimeSync", QOS_1), ("Receive_OPC_Server", QOS_1)]
    clientMqtt = asyncio.SelectorEventLoop().run_until_complete(asyncio.wait([test()]))

if __name__ == "__main__":
    try:
        set_connection = True

        main(server_state)

    except KeyboardInterrupt:
        pass
    finally:
        print("Closing Loop")
        for i in range(3):
            time.sleep(1)
            print(f"Reconnect to Server in {3 - i} ...")
        asyncio.run(main(server_state))


问:
Want to install requests for pyton but getting path WARNING
This is my python location
/usr/bin/python3

after pip3 install requests
I am getting

Requirement already satisfied: idna<4,>=2.5 in ./Library/Python/3.9/lib/python/site-packages (from requests) (3.4)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in ./Library/Python/3.9/lib/python/site-packages (from requests) (1.26.13)
Requirement already satisfied: certifi>=2017.4.17 in ./Library/Python/3.9/lib/python/site-packages (from requests) (2022.12.7)
Collecting charset-normalizer<3,>=2
Downloading charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Installing collected packages: charset-normalizer, requests

WARNING: The script normalizer is installed in '/Users/X/Library/Python/3.9/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
NOTE: The current PATH contains path(s) starting with ~, which may not be expanded by all applications.
Successfully installed charset-normalizer-2.1.1 requests-2.28.1

How can I add this directory to my path?

Fixing PATH for Python libraries using Bash

from here

i think i need to change some from this line
export PATH=/Users//Library/Python/3.8/bin:$PATH
but im not sure which part and libraly name..


问:
Exception Value: badly formed hexadecimal UUID string
models.py

```<code>import uuid
from django.db import models

class Book(models.Model):
    id = models.UUIDField(
         primary_key=True,
         default=uuid.uuid4,
         editable=False
    )
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title

    def get_absolute_url(self): # new
        return reverse('book_detail', args=[str(self.id)])
</code>```

"-----------------------------------------------------------------------"

?

I want try for better id in models but i had this erorr...

who can help me?

Body:
models.py

import uuid
from django.db import models

class Book(models.Model):
    id = models.UUIDField(
         primary_key=True,
         default=uuid.uuid4,
         editable=False
    )
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title

    def get_absolute_url(self): # new
        return reverse('book_detail', args=[str(self.id)])

"-----------------------------------------------------------------------"

?

I want try for better id in models but i had this erorr...

who can help me?


问:
Using HttpListener.GetContextAsync() to process requests in parallel
I am trying to get a HttpListener to accept multiple requests in a parallel manner, using an async - await technique. I am aware that in this case "parallel" execution may be limited to "waiting" time, not "processing" time - and this is OK in this case.

The listener itself is managed within a BackgroundService class. At the heart of the logic there is a listening loop as follows (simplified and with a lot of logging removed):

```<code>protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    ...
    while (true)
    {
        var context = await listener.GetContextAsync();
        var processTask = ProcessRequestAsync(context);
    }
    ...
}
</code>```

The processing function looks like this (simplified and with a lot of logging removed):

```<code>private async Task ProcessRequestAsync(HttpListenerContext context)
{
    await Task.Delay(5000);
    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    context.Response.Close();
}
</code>```

As of my current understanding, within the loop the first line should block until there is a request to process, while the second line should not block, instead the processing function in executed until the await is reached, then execution continues, and the loop is repeated with GetContextAsync() being called again.

I would expect that a second request, received within the 5 seconds of waiting by the first request, would be executed immediately (until its own 5 seconds of waiting). If the two requests are made within a second, processing both would thus take ~6 seconds.

What happens instead: the second call to GetContextAsync() occurs timely as expected, but await-ing it blocks until the response of the HttpListenerContext returned by the first call is closed. This causes the two requests to be processed in sequence, taking 10 seconds instead of 6.

This behavior is suggested by another test I did: by moving the await Task.Delay() below Response.Close() , the second await GetContextAsync() no longer blocks, that is it returns immediately as the request is received. This suggests that blocking is not task-related (the duration of the task is identical in the two cases), but rather HttpListenerContext-related.

However, I could not find this behavior documented anywhere...

Has anyone come across this problem? I found a few other similar questions on SO and several solutions suggested - from basic to very sophisticated - but in the end all seem to follow the same principle as the above code - which does not work.

In the past I solved this problem with explicit threading management (and sadly said, it seemed easier) but I am specifically interested whether this can be done with async - await.

A few end notes:

Some posters suggested using .configureAwait(false), which I tried but made no difference.

I logged the thread used by the processing functions and it is the same. However, I don't know whether this is the cause of the problem or its effect (once the 2 calls are scheduled sequentially, there is no harm in executing both on the same thread).

UPDATES

I did more tests and it keeps getting worse, it looks more and more like a hard limitation of the listener class. To be sure of the results, I splitted the waiting time into halves, 5 seconds before the HTTP response is closed and 5 seconds after that. As a result, two "parallel" request processing operations are overlapped by 5 seconds, meaning that request #2 can only be processed after response #1 was closed.

I got this same result:

With the code above, including the suggested improvement using Task.Run()

With the older approach to asynchronous processing (BeginGetContext - EndGetContext)

With a Thread-based implementation (each context being processed in a different thread)

With the code sample included in a related but very old discussion here which was UI-based but I converted it to console app.

All tests were included in very basic console apps, thus the original program being part of a BackgroundService is probably not related to this problem.

As everything seems to revolve around the listener and the listener context (processing of context #2 being processed only after processing of context #1 completes), the problem boils down to whether there is any way to "unlock" context #1 so that context #2 can be processed. I tried - and failed - to achieve this in two naive (and not necessarily usable in production environment) approaches:

Closing the HttpListener.Request.InputStream => no changes at all

Having the requests served by multiple listeners => failed to start listening on same port (but I suspect this would have gone around the original problem)

Body:
I am trying to get a HttpListener to accept multiple requests in a parallel manner, using an async - await technique. I am aware that in this case "parallel" execution may be limited to "waiting" time, not "processing" time - and this is OK in this case.

The listener itself is managed within a BackgroundService class. At the heart of the logic there is a listening loop as follows (simplified and with a lot of logging removed):

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    ...
    while (true)
    {
        var context = await listener.GetContextAsync();
        var processTask = ProcessRequestAsync(context);
    }
    ...
}

The processing function looks like this (simplified and with a lot of logging removed):

private async Task ProcessRequestAsync(HttpListenerContext context)
{
    await Task.Delay(5000);
    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    context.Response.Close();
}

As of my current understanding, within the loop the first line should block until there is a request to process, while the second line should not block, instead the processing function in executed until the await is reached, then execution continues, and the loop is repeated with GetContextAsync() being called again.

I would expect that a second request, received within the 5 seconds of waiting by the first request, would be executed immediately (until its own 5 seconds of waiting). If the two requests are made within a second, processing both would thus take ~6 seconds.

What happens instead: the second call to GetContextAsync() occurs timely as expected, but await-ing it blocks until the response of the HttpListenerContext returned by the first call is closed. This causes the two requests to be processed in sequence, taking 10 seconds instead of 6.

This behavior is suggested by another test I did: by moving the await Task.Delay() below Response.Close() , the second await GetContextAsync() no longer blocks, that is it returns immediately as the request is received. This suggests that blocking is not task-related (the duration of the task is identical in the two cases), but rather HttpListenerContext-related.

However, I could not find this behavior documented anywhere...

Has anyone come across this problem? I found a few other similar questions on SO and several solutions suggested - from basic to very sophisticated - but in the end all seem to follow the same principle as the above code - which does not work.

In the past I solved this problem with explicit threading management (and sadly said, it seemed easier) but I am specifically interested whether this can be done with async - await.

A few end notes:

Some posters suggested using .configureAwait(false), which I tried but made no difference.

I logged the thread used by the processing functions and it is the same. However, I don't know whether this is the cause of the problem or its effect (once the 2 calls are scheduled sequentially, there is no harm in executing both on the same thread).

UPDATES

I did more tests and it keeps getting worse, it looks more and more like a hard limitation of the listener class. To be sure of the results, I splitted the waiting time into halves, 5 seconds before the HTTP response is closed and 5 seconds after that. As a result, two "parallel" request processing operations are overlapped by 5 seconds, meaning that request #2 can only be processed after response #1 was closed.

I got this same result:

With the code above, including the suggested improvement using Task.Run()

With the older approach to asynchronous processing (BeginGetContext - EndGetContext)

With a Thread-based implementation (each context being processed in a different thread)

With the code sample included in a related but very old discussion here which was UI-based but I converted it to console app.

All tests were included in very basic console apps, thus the original program being part of a BackgroundService is probably not related to this problem.

As everything seems to revolve around the listener and the listener context (processing of context #2 being processed only after processing of context #1 completes), the problem boils down to whether there is any way to "unlock" context #1 so that context #2 can be processed. I tried - and failed - to achieve this in two naive (and not necessarily usable in production environment) approaches:

Closing the HttpListener.Request.InputStream => no changes at all

Having the requests served by multiple listeners => failed to start listening on same port (but I suspect this would have gone around the original problem)


问:
How to develop a custom schema resolver for openapi code generation?
Our JSON schemas use URNs for schema IDs. Ideally we would like to use URNs when specifying a $ref. URNs of course do not resolve to file system locations or URLs.

A custom schema resolver could be developed which does map URNs to locations according to config information.

Before I take the plunge, I would like to ask the community for any advice such as recommended approach or even if this is feasible. Any thoughts? Thanks!

I have made a pass through the openapi generator source and identified classes which could be starting points (e.g., ModelUtils) for developing schema resolution.


问:
Execute a query after state change
I am using the Fluent UI React module to develop a custom pivot component as follows:

```<code>export type PivotHeaderProps = {
  selectedPivotKey: string;
  pivotItemHeaders: string[];
  pivotKeys: string[];
  setSelectedPivotKey: React.Dispatch<React.SetStateAction<string>>;
  handleLinkClick?: (item?: PivotItem) => void;
};

export const PivotHeader = (props: PivotHeaderProps): JSX.Element => {
  const handleLinkClick = (item?: PivotItem) => {
    if (props.handleLinkClick) {
      props.handleLinkClick(item);
    }

    if (item) {
      props.setSelectedPivotKey(item.props.itemKey || '');
    }
  };

  return (
    <div>
      <Pivot selectedKey={props.selectedPivotKey} onLinkClick={handleLinkClick} headersOnly={true}>
        {props.pivotItemHeaders.map((pivotHeader, index) => (
          <PivotItem headerText={pivotHeader} itemKey={props.pivotKeys?.[index]} key={props.pivotKeys?.[index]} />
        ))}
      </Pivot>
    </div>
  );
};
</code>```

I use this custom component to render pivot items:

```<code><PivotHeader selectedPivotKey={selectedKey} setSelectedPivotKey={setSelectedKey} pivotItemHeaders={pivotHeaders} pivotKeys={pivotKeys} handleLinkClick={handleLinkClick} />
</code>```

Whenever a pivot item is clicked, based on the selected key, I need to render a component with a specific data based on the key. For example:

```<code>// Component: Items

const [selectedKey, setSelectedKey] = useState<string>('');

// Data being fetched.

const handleLinkClick = (item?: PivotItem) => {
  if (item) { sessionStorage.setItem("ItemKey", item.props.itemKey) };
};

// Pivot header and other components.
{selectedKey === "Value1" && (<ShimmeredDetailsList items={modifiedItemsForValue1} columns={columns}  enableShimmer={isLoadingItemsForValue1}/>)}
{selectedKey === "Value2" && (<ShimmeredDetailsList items={modifiedItemsForValue2} columns={columns} enableShimmer={isLoadingItemsForValue2}/>)}
// ... and so on.
</code>```

The value lists are populated using the REST API queries executed with the help of useQuery hook.

```<code>const { data: itemsForValue1, isLoading: isLoadingItemsForValue1 } = useQuery({
    itemQueries.getByKey("Value1"),
    enabled: selectedKey === "Value1",
  });

const modifiedItemsForValue1 = itemsForValue1?.map(
  // custom mapping function
) || [];
// ... and so on.

// The corresponding itemQueries.ts can be visualized as:
export const itemQueries = {
  getByKey(key: string): UseQueryOptions<ItemResult[]> => ({
    queryKey: [key],
    queryFn: // make the service call that uses the key value from session storage for request header.
  }),
} as const;
</code>```

Initially, the page loads under Value1 key of the pivot. Now, the issue I am facing here is that:

When I switch to the second key, Value2 of the pivot, handleLinkClick function is triggered of the PivotHeader component.

But, before the selectedKey changes, the Items component renders again and the useQuery hook to fetch the items is invoked.

This activates the first query for key Value1 as well, because for a moment the selected key value has not changed.

But, by the time the call reaches the queryFn for the same and service call is made, the custom handleLinkClick function gets evaluated and item key value changes, leading to Value2 to be sent as the header in the request.

This overwrites the itemForValues1 list and correspondingly also changes the modifiedItemsForValue1 list. So, next time I switch back to Value1 pivot tab, the list shown corresponds to Value2 rather than Value1. It does a refetch automatically, but for few seconds I do see a wrong list of values.

Now, the request header logic is centrally encompassed in the application as an interceptor and I cannot overwrite that logic. So, I was thinking, how I can execute the useQuery call only after the state change of the selectedKey variable (this indirectly implies that first the session storage key value would have changed as it occurs synchronously before calling setSelectedKey function in PivotHeader). Because the setSelectedKey call happens asynchronously, I was thinking to use a useEffect hook, but unable to identify how I can manage the modified list along with the same, before rendering it.

Any pointers would be really helpful.

Title: Execute a query after state change

Body:
I am using the Fluent UI React module to develop a custom pivot component as follows:

export type PivotHeaderProps = {
  selectedPivotKey: string;
  pivotItemHeaders: string[];
  pivotKeys: string[];
  setSelectedPivotKey: React.Dispatch<React.SetStateAction<string>>;
  handleLinkClick?: (item?: PivotItem) => void;
};

export const PivotHeader = (props: PivotHeaderProps): JSX.Element => {
  const handleLinkClick = (item?: PivotItem) => {
    if (props.handleLinkClick) {
      props.handleLinkClick(item);
    }

    if (item) {
      props.setSelectedPivotKey(item.props.itemKey || '');
    }
  };

  return (

      <Pivot selectedKey={props.selectedPivotKey} onLinkClick={handleLinkClick} headersOnly={true}>
        {props.pivotItemHeaders.map((pivotHeader, index) => (
          <PivotItem headerText={pivotHeader} itemKey={props.pivotKeys?.[index]} key={props.pivotKeys?.[index]} />
        ))}
      </Pivot>

  );
};

I use this custom component to render pivot items:

<PivotHeader selectedPivotKey={selectedKey} setSelectedPivotKey={setSelectedKey} pivotItemHeaders={pivotHeaders} pivotKeys={pivotKeys} handleLinkClick={handleLinkClick} />

Whenever a pivot item is clicked, based on the selected key, I need to render a component with a specific data based on the key. For example:

// Component: Items

const [selectedKey, setSelectedKey] = useState<string>('');

// Data being fetched.

const handleLinkClick = (item?: PivotItem) => {
  if (item) { sessionStorage.setItem("ItemKey", item.props.itemKey) };
};

// Pivot header and other components.
{selectedKey === "Value1" && (<ShimmeredDetailsList items={modifiedItemsForValue1} columns={columns}  enableShimmer={isLoadingItemsForValue1}/>)}
{selectedKey === "Value2" && (<ShimmeredDetailsList items={modifiedItemsForValue2} columns={columns} enableShimmer={isLoadingItemsForValue2}/>)}
// ... and so on.

The value lists are populated using the REST API queries executed with the help of useQuery hook.

const { data: itemsForValue1, isLoading: isLoadingItemsForValue1 } = useQuery({
    itemQueries.getByKey("Value1"),
    enabled: selectedKey === "Value1",
  });

const modifiedItemsForValue1 = itemsForValue1?.map(
  // custom mapping function
) || [];
// ... and so on.

// The corresponding itemQueries.ts can be visualized as:
export const itemQueries = {
  getByKey(key: string): UseQueryOptions<ItemResult[]> => ({
    queryKey: [key],
    queryFn: // make the service call that uses the key value from session storage for request header.
  }),
} as const;

Initially, the page loads under Value1 key of the pivot. Now, the issue I am facing here is that:

When I switch to the second key, Value2 of the pivot, handleLinkClick function is triggered of the PivotHeader component.

But, before the selectedKey changes, the Items component renders again and the useQuery hook to fetch the items is invoked.

This activates the first query for key Value1 as well, because for a moment the selected key value has not changed.

But, by the time the call reaches the queryFn for the same and service call is made, the custom handleLinkClick function gets evaluated and item key value changes, leading to Value2 to be sent as the header in the request.

This overwrites the itemForValues1 list and correspondingly also changes the modifiedItemsForValue1 list. So, next time I switch back to Value1 pivot tab, the list shown corresponds to Value2 rather than Value1. It does a refetch automatically, but for few seconds I do see a wrong list of values.

Now, the request header logic is centrally encompassed in the application as an interceptor and I cannot overwrite that logic. So, I was thinking, how I can execute the useQuery call only after the state change of the selectedKey variable (this indirectly implies that first the session storage key value would have changed as it occurs synchronously before calling setSelectedKey function in PivotHeader). Because the setSelectedKey call happens asynchronously, I was thinking to use a useEffect hook, but unable to identify how I can manage the modified list along with the same, before rendering it.

Any pointers would be really helpful.


问:
how to send timeframe.period and plots as json keys in tradingview alert message webhook?
I want to send some float values as plot and timeframe period to the specific URL.

how can I set them in alert message body ?

and how can I write the plots in indicator ?

thanks


问:
Error trying to create an image classifier for the RSNA Screening Mammography competition on Kaggle
I would appreciate any help anybody can offer with the issue descibed here

Error creating image classifier

Many thanks in advance

Julian