问:
MUI TextField focus show difference iconbutton at endAdornment need to click twice
let me describe this situation. I want to implement a password input component. The requirement is needed when the user focuses on Input which needs to show a clear button Icon. if the user didn't type anything or user blur out of this input component. need to show the eyes button Icon.

The clear button can reset the user's typing content. so it's very convenient. The eyes button can show the password or hide the password as we often see this function.

I use a library base on document.activeElement to implement checking components whether be focus. but the weird thing always needs to click the clear button icon twice to reset input content.

The following link is a sample. I want to know why, thanks.

Codesandbox https://codesandbox.io/s/wired-input-ikihi4?file=/src/App.js


来源: stackexchange

问:
Authenticate Airflow APIs using Okta or OAuth2
I want to know if we can secure calls to Airflow APIs using Okta or OAuth2.

Example: curl -H "**Authorization: Bearer <okta_jwt_token**>" https://airflow//api/experimental/dags/<DAG_ID>/tasks/<TASK_ID>

Searching in the documentation, Airflow provides basic or kerberos authentication mode but not other like Okta or OAuth2.

Thanks a lot for your help.

Configure Airflow with OAuth2

```<code>curl -H "**Authorization: Bearer <okta_jwt_token**>" https://airflow//api/experimental/dags/<DAG_ID>/tasks/<TASK_ID>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to know if we can secure calls to Airflow APIs using Okta or OAuth2.

Example: curl -H "**Authorization: Bearer <okta_jwt_token**>" https://airflow//api/experimental/dags/<DAG_ID>/tasks/<TASK_ID>

Searching in the documentation, Airflow provides basic or kerberos authentication mode but not other like Okta or OAuth2.

Thanks a lot for your help.

Configure Airflow with OAuth2

curl -H "**Authorization: Bearer <okta_jwt_token**>" https://airflow//api/experimental/dags/<DAG_ID>/tasks/<TASK_ID>


问:
How can I check if a Value exists in a Concurrent Array/Map/List of Objects in order to prevent adding and link new to the existing one
I need to process Video, which is an object inside a Job object.There can only be one Job per original video. When a Video is processed, it is saved as another Video object inside that Job.       I want to be able to detect whether that Video is already being processed:
If it is:

It must not add it to the queue

Once the original Video is processed, the processed video must be sent to all who added or tried to add that same Video

If it is not:

Add it to the queue

```<code>public class Job {
    private Video o_video;
    private Video coded_video;

    public Job(Video v) {
        o_video = v;
        coded_video = null;
    }

    public Video extractOriginal() {
        return o_video;
    }
    public void addCodedVideo(Video vCod) {
        synchronized(this) {
            coded_video = vCod;
            this.notifyAll();
        }
        return;
    }
    public Video extractCodedVideo() throws InterruptedException {
        synchronized(this) {
            while(coded_video ==null) {
                this.wait();
            }
        }
        return coded_video;
    }
}
</code>```

Body:
I need to process Video, which is an object inside a Job object.There can only be one Job per original video. When a Video is processed, it is saved as another Video object inside that Job.       I want to be able to detect whether that Video is already being processed:
If it is:

It must not add it to the queue

Once the original Video is processed, the processed video must be sent to all who added or tried to add that same Video

If it is not:

Add it to the queue

public class Job {
    private Video o_video;
    private Video coded_video;

    public Job(Video v) {
        o_video = v;
        coded_video = null;
    }

    public Video extractOriginal() {
        return o_video;
    }
    public void addCodedVideo(Video vCod) {
        synchronized(this) {
            coded_video = vCod;
            this.notifyAll();
        }
        return;
    }
    public Video extractCodedVideo() throws InterruptedException {
        synchronized(this) {
            while(coded_video ==null) {
                this.wait();
            }
        }
        return coded_video;
    }
}


问:
Kafka consumer didn't read user id
Kafka consumer didn't read user id.

I have a Kafka consumer:

my_consumer = KafkaConsumer(
    'events.taxonomy',
    bootstrap_servers=['localhost:9092'],
    auto_offset_reset='earliest',
    enable_auto_commit=True,
    group_id='my-group',
    value_deserializer=lambda x: loads(x.decode('utf-8'))
)
```
<p>that reads messages from Kafka topic and adds dict to Postgres's database by SQLAlchemy:</p>
<pre class="lang-py prettyprint-override"><code>    for msg in my_consumer:
      kafka_record = msg.value
      res = json.loads(kafka_record)
      print(res)
      p = schemas.EventCreate(event_id=res['event_id'], type=res['type'],
      team_1=res['team_1'], team_2=res['team_1'], event_date=res['event_date'], score=res['score'], state=res['state'])
      Session.add(p)
      Session.commit()
</code>```

but when I add dict to database I have an error:

```<code>pydantic.error_wrappers.ValidationError: 1 validation error for EventCreate
event_id
field required (type=value_error.missing)
</code>```

When I pass message to Kafka topic dict have a key and value "user_id":

```<code>{"_sa_instance_state": "<not serializable>", "event_id": 1101, "type": "string", "team_1": "string", "team_2": "string", "event_date": 0, "score": "string", "state": "string"}
</code>```

But when consumer read message the key "user_id" is missing:

```<code>{'_sa_instance_state': '<not serializable>', 'type': 'string', 'team_1': 'string', 'team_2': 'string', 'event_date': 0, 'score': 'string', 'state': 'string'}
</code>```

Why does this happen and how should I fix it?

Title: Kafka consumer didn't read user id

Body:
Kafka consumer didn't read user id.

I have a Kafka consumer:

my_consumer = KafkaConsumer(
    'events.taxonomy',
    bootstrap_servers=['localhost:9092'],
    auto_offset_reset='earliest',
    enable_auto_commit=True,
    group_id='my-group',
    value_deserializer=lambda x: loads(x.decode('utf-8'))
)

that reads messages from Kafka topic and adds dict to Postgres's database by SQLAlchemy:

    for msg in my_consumer:
      kafka_record = msg.value
      res = json.loads(kafka_record)
      print(res)
      p = schemas.EventCreate(event_id=res['event_id'], type=res['type'],
      team_1=res['team_1'], team_2=res['team_1'], event_date=res['event_date'], score=res['score'], state=res['state'])
      Session.add(p)
      Session.commit()

but when I add dict to database I have an error:

pydantic.error_wrappers.ValidationError: 1 validation error for EventCreate
event_id
field required (type=value_error.missing)

When I pass message to Kafka topic dict have a key and value "user_id":

{"_sa_instance_state": "<not serializable>", "event_id": 1101, "type": "string", "team_1": "string", "team_2": "string", "event_date": 0, "score": "string", "state": "string"}

But when consumer read message the key "user_id" is missing:

{'_sa_instance_state': '<not serializable>', 'type': 'string', 'team_1': 'string', 'team_2': 'string', 'event_date': 0, 'score': 'string', 'state': 'string'}

Why does this happen and how should I fix it?


问:
DeserializationException handeling in RequestResponseTemplate
I am having trouble understanding how to handle deserialization exceptions during the use of RequestResponseTemplate. I create this RequestResponseTemplate by configuring DefaultKafkaProducerFactory & KafkaMessageListenerContainer(StringDeserializer, CustomDeserializer)

Problem:
Handle the deserialization error during deserilization of the value (thrown by the CustomDeserializer) by logging and moving to the next record.

Solution (tried and failed):

setCommonErrorHandler(new CommonLoggingErrorHandler()) on KafkaMessageListenerContainer
I thought this class would commit the offset of the failed record as isAckAfterHandle being set to true by default. However the offset is not commited and consumer.poll() enters into an loop.

Question: How to handle deserialization exceptions similar to LogAndContinue manner in spring cloud streams?

Stacktrace:

```<code>"@timestamp":"2022-12-13 13:23:19.726","@version":"1","message":"Error occurred while not processing records",
"logger": org.springframework.kafka.listener.CommonLoggingErrorHandler,"thread":"Container-C-1","level":"ERROR",
"stacktrace": org.apache.kafka.common.errors.RecordDeserializationException : Error deserializing key/value for partition politie.sensing.sys.melding-waarneming-response.0-0 at offset 5.
If needed, please seek past the record to continue consumption.\r\n

org.apache.kafka.clients.consumer.internals.Fetcher.parseRecord(Fetcher.java:1448)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.access$3400(Fetcher.java
:135)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.fetchRecords(Fetcher.java:1671)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.access$1900(Fetcher.java:1507)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.fetchRecords(Fetcher.jav
a:733)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.fetchedRecords(Fetcher.java:684)\r\n
org.apache.kafka.clients.consumer.KafkaConsumer.pollForFetches(KafkaConsumer.java:1277)\r\n
org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1238)\r\n\tat
org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1211)\r\n\tat
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollConsumer(KafkaMessageListenerContainer.java:1529)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doPoll(KafkaMessageListenerContainer.java:1519)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:1343)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:1255)\r\n
java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)\r\n
java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n
java.base/java.lang.Thread.run(Thread.java:832)\r\nCaused by: java.lang.IllegalArgumentException: Can't deserialize data [[..content is redacted..]]\r\n
my.library.common.kafka.serializer.JsonDeserializer.deserialize(JsonDeserializer.java:77)\r\n
org.apache.kafka.common.serialization.Deserializer.deserialize(Deserializer.java:60)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher.parseRecord(Fetcher.java:1439)\r\n
... 15 common frames omitted\r\n","application":"my-micro-sens-service"
</code>```

Body:
I am having trouble understanding how to handle deserialization exceptions during the use of RequestResponseTemplate. I create this RequestResponseTemplate by configuring DefaultKafkaProducerFactory & KafkaMessageListenerContainer(StringDeserializer, CustomDeserializer)

Problem:
Handle the deserialization error during deserilization of the value (thrown by the CustomDeserializer) by logging and moving to the next record.

Solution (tried and failed):

setCommonErrorHandler(new CommonLoggingErrorHandler()) on KafkaMessageListenerContainer
I thought this class would commit the offset of the failed record as isAckAfterHandle being set to true by default. However the offset is not commited and consumer.poll() enters into an loop.

Question: How to handle deserialization exceptions similar to LogAndContinue manner in spring cloud streams?

Stacktrace:

"@timestamp":"2022-12-13 13:23:19.726","@version":"1","message":"Error occurred while not processing records",
"logger": org.springframework.kafka.listener.CommonLoggingErrorHandler,"thread":"Container-C-1","level":"ERROR",
"stacktrace": org.apache.kafka.common.errors.RecordDeserializationException : Error deserializing key/value for partition politie.sensing.sys.melding-waarneming-response.0-0 at offset 5.
If needed, please seek past the record to continue consumption.\r\n

org.apache.kafka.clients.consumer.internals.Fetcher.parseRecord(Fetcher.java:1448)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.access$3400(Fetcher.java
:135)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.fetchRecords(Fetcher.java:1671)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.access$1900(Fetcher.java:1507)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.fetchRecords(Fetcher.jav
a:733)\r\n
org.apache.kafka.clients.consumer.internals.Fetcher.fetchedRecords(Fetcher.java:684)\r\n
org.apache.kafka.clients.consumer.KafkaConsumer.pollForFetches(KafkaConsumer.java:1277)\r\n
org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1238)\r\n\tat
org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1211)\r\n\tat
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollConsumer(KafkaMessageListenerContainer.java:1529)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doPoll(KafkaMessageListenerContainer.java:1519)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:1343)\r\n
org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:1255)\r\n
java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)\r\n
java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)\r\n
java.base/java.lang.Thread.run(Thread.java:832)\r\nCaused by: java.lang.IllegalArgumentException: Can't deserialize data [[..content is redacted..]]\r\n
my.library.common.kafka.serializer.JsonDeserializer.deserialize(JsonDeserializer.java:77)\r\n
org.apache.kafka.common.serialization.Deserializer.deserialize(Deserializer.java:60)\r\n\tat org.apache.kafka.clients.consumer.internals.Fetcher.parseRecord(Fetcher.java:1439)\r\n
... 15 common frames omitted\r\n","application":"my-micro-sens-service"


问:
Validation on range of dates
I have a lookup table as follows:

StartDate
EndDate
Name

01/01/2022
31/01/2022
Custom Name 1

01/02/2022
28/02/2022
Custom Name 2

etc.

On another sheet I have a date column and a name column. I want to autopopulate the name from this lookup table based on the date being between one of the start and end dates.

What validation formula do I need to apply to get this to work?

Title: Validation on range of dates


问:
Vite and Vue Behave Differently with vite VS vite build
I switched to vite a while back to increase performance when developing and I have been happy for the most part but I do have some issues that I never had before with webPack.

Every month or so I face an issue where a bug pops up in the vite build that is not present when running vite. When I find the error it is normally obvious what needs to be fixed, but I would like the frontend to throw the same error and break when developing so that it is easier to track down.

When the error is found in the production build its much harder to track down.

These are not build errors, but the frontend breaks only in the production build.

Is there some way I can force Vue3 to behave the same with Vite in both the development runtime and the final build?


问:
NextJS unhandledRejection: TypeError: Failed to parse URL for Nginx proxied API
I have NextJS in Docker container. I don't use native Nexts APIs but I have Nginx reverse proxy all requests to /api/... proxied to my app.

BUT what works with React (tried in the same container) doesn't with Next.

```<code>error - unhandledRejection: TypeError: Failed to parse URL from /api/Chk/init
nextapp_1    |     at Object.fetch (node:internal/deps/undici/undici:14294:11) {
nextapp_1    |   [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
nextapp_1    |       at new NodeError (node:internal/errors:393:5)
nextapp_1    |       at URL.onParseError (node:internal/url:565:9)
nextapp_1    |       at new URL (node:internal/url:645:5)
nextapp_1    |       at new Request (node:internal/deps/undici/undici:7023:25)
nextapp_1    |       at fetch2 (node:internal/deps/undici/undici:13460:25)
nextapp_1    |       at Object.fetch (node:internal/deps/undici/undici:14292:18)
nextapp_1    |       at fetch (node:internal/process/pre_execution:238:25)
nextapp_1    |       at CAPI.__fetch (webpack-internal:///./node_modules/myapp/dist/myapp.js:136:16)
nextapp_1    |       at CAPI.post (webpack-internal:///./node_modules/myapp/dist/myapp.js:118:21)
nextapp_1    |       at __props.preparing.Promise.finally.__props.authenticated (webpack-internal:///./node_modules/myapp/dist/myapp.js:68:18) {
nextapp_1    |     input: '/api/Chk/init',
nextapp_1    |     code: 'ERR_INVALID_URL'
nextapp_1    |   }
nextapp_1    | }
</code>```

So it replaces Fetch with Nexts version of Fetch but fails, I suppose because Nginx (and the whole app) is running on port 8000, but the Next app is on 3000 and tries to reach API with (I guess) p80.

I use fetch relative to the domain root fetch('/api/xyz')

And this is my next.config.js:

// next.config.js
const withTM = require('next-transpile-modules')(['renette-api']); // pass the modules you would like to see transpiled

// parameter to use with NextJS are argument to withTM
module.exports = withTM({
  reactStrictMode: true,
  output: 'standalone',
  swcMinify: true,
  experimental: {
    externalDir: true,
  },
  async rewrites(){
    return [
      {
        source: "/api*",
        destination: "http://localhost:8000/api/",
      },
    ];
  }
});
```

I suppose I need to switch off URL check in Next Fetch or proxy all /api/* requests in NextJS too, is it possible?

Body:
I have NextJS in Docker container. I don't use native Nexts APIs but I have Nginx reverse proxy all requests to /api/... proxied to my app.

BUT what works with React (tried in the same container) doesn't with Next.

error - unhandledRejection: TypeError: Failed to parse URL from /api/Chk/init
nextapp_1    |     at Object.fetch (node:internal/deps/undici/undici:14294:11) {
nextapp_1    |   [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
nextapp_1    |       at new NodeError (node:internal/errors:393:5)
nextapp_1    |       at URL.onParseError (node:internal/url:565:9)
nextapp_1    |       at new URL (node:internal/url:645:5)
nextapp_1    |       at new Request (node:internal/deps/undici/undici:7023:25)
nextapp_1    |       at fetch2 (node:internal/deps/undici/undici:13460:25)
nextapp_1    |       at Object.fetch (node:internal/deps/undici/undici:14292:18)
nextapp_1    |       at fetch (node:internal/process/pre_execution:238:25)
nextapp_1    |       at CAPI.__fetch (webpack-internal:///./node_modules/myapp/dist/myapp.js:136:16)
nextapp_1    |       at CAPI.post (webpack-internal:///./node_modules/myapp/dist/myapp.js:118:21)
nextapp_1    |       at __props.preparing.Promise.finally.__props.authenticated (webpack-internal:///./node_modules/myapp/dist/myapp.js:68:18) {
nextapp_1    |     input: '/api/Chk/init',
nextapp_1    |     code: 'ERR_INVALID_URL'
nextapp_1    |   }
nextapp_1    | }

So it replaces Fetch with Nexts version of Fetch but fails, I suppose because Nginx (and the whole app) is running on port 8000, but the Next app is on 3000 and tries to reach API with (I guess) p80.

I use fetch relative to the domain root fetch('/api/xyz')

And this is my next.config.js:

// next.config.js
const withTM = require('next-transpile-modules')(['renette-api']); // pass the modules you would like to see transpiled

// parameter to use with NextJS are argument to withTM
module.exports = withTM({
  reactStrictMode: true,
  output: 'standalone',
  swcMinify: true,
  experimental: {
    externalDir: true,
  },
  async rewrites(){
    return [
      {
        source: "/api*",
        destination: "http://localhost:8000/api/",
      },
    ];
  }
});

I suppose I need to switch off URL check in Next Fetch or proxy all /api/* requests in NextJS too, is it possible?


问:
when submit button is click the input data has been disappear how can I rectify?
when submit button is clicked the input data is disappear in html How can I rectify the problem?</p>
```<code><html>
  <head>
    <title>hhhh</title>
  </head>
  <body>
    <form id="form">
      <input type="text" id="username" placeholder="username" />
      <input type="submit" id="btn" />
    </form>
  </body>
  <script>

    var a = document.getElementById("username");
    var b = document.getElementById("btn");

    b.addEventListener("click", () => {
      console.log(a.value);

    });
  </script>
</html>

</code>```

Body:
when submit button is clicked the input data is disappear in html How can I rectify the problem?

    <title>hhhh</title>

    <form id="form">
      <input type="text" id="username" placeholder="username" />
      <input type="submit" id="btn" />
    </form>


问:
How to toggle class in react, but one component at once(all with the same classes)
let me explain my situation.

I am building a MERN project to my portfolio and I am trying to make a button toggle between the name of an item and a inputfield. So when the user click the pen (edit), it will add a class with the displain:none; in the div with the text coming from the MongoDB data base to hide it and will remove it from the div with the input. I could manage to do it. BUT since the amount of items can inscrease, clicking in one of them cause the toggle in all of them.

It was ok until I send some useState as props to the component.

This is my code from the App.jsx

```<code>import React, {useState, useEffect} from "react";
import Axios from "axios";

import "./App.css";
import ListItem from "./components/ListItem";

function App() {
//here are the use states
    const [foodName, setFoodName] = useState("");
    const [days, setDays] = useState(0);
    const [newFoodName, setNewFoodName] = useState("");
    const [foodList, setFoodList] = useState([]);
//here is just the compunication with the DB of a form that I have above those components

    useEffect(() => {
        Axios.get("http://localhost:3001/read").then((response) => {
            setFoodList(response.data);
        });
    }, []);

    const addToList = () => {
        Axios.post("http://localhost:3001/insert", {
            foodName: foodName,
            days: days,
        });
    };

    const updateFood = (id) => {
        Axios.put("http://localhost:3001/update", {
            id: id,
            newFoodName: newFoodName,
        });
    };

    return (
        <div className="App">
//Here it starts the app with the form and everything
            <h1>CRUD app with MERN</h1>
            <div className="container">
                <h3 className="container__title">Favorite Food Database</h3>
                <label>Food name:</label>
                <input
                    type="text"
                    onChange={(event) => {
                        setFoodName(event.target.value);
                    }}
                />
                <label>Days since you ate it:</label>
                <input
                    type="number"
                    onChange={(event) => {
                        setDays(event.target.value);
                    }}
                />
                <button onClick={addToList}>Add to list</button>
            </div>
//Here the form finishes and now it starts the components I showed in the images.
            <div className="listContainer">
                <hr />
                <h3 className="listContainer__title">Food List</h3>
                {foodList.map((val, key) => {
                    return (
//This is the component and its props
                        <ListItem
                            val={val}
                            key={key}
                            functionUpdateFood={updateFood(val._id)}
                            newFoodName={newFoodName}
                            setNewFoodName={setNewFoodName}
                        />
                    );
                })}
            </div>
        </div>
    );
}

export default App;

</code>```

Now the component code:

```<code>import React from "react";
//Material UI Icon imports
import CancelIcon from "@mui/icons-material/Cancel";
import EditIcon from "@mui/icons-material/Edit";
//import CheckIcon from "@mui/icons-material/Check";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";

//App starts here, I destructured the props

function ListItem({val, key, functionUpdateFood, newFoodName, setNewFoodName}) {
    //const [foodList, setFoodList] = useState([]);

//Here I have the handleToggle function that will be used ahead.
    const handleToggle = () => {
        setNewFoodName(!newFoodName);
    };

    return (
        <div
            className="foodList__item"
            key={key}>
            <div className="foodList__item-group">
                <h3
//As you can see, I toggle the classes with this conditional statement
//I use the same classes for all items I want to toggle with one click
//Here it will toggle the Food Name
                    className={
                        newFoodName
                            ? "foodList__item-newName-delete"
                            : "foodList__name"
                    }>
                    {val.foodName}
                </h3>
                <div
                    className={
                        newFoodName
                            ? "foodList__item-newName-group"
                            : "foodList__item-newName-delete"
                    }>
//Here is the input that will replace the FoodName
                    <input
                        type="text"
                        placeholder="The new food name..."
                        className="foodList__item-newName"
                        onChange={(event) => {
                            setNewFoodName(event.target.value);
                        }}
                    />
//Here it will confirm the update and toggle back
//Didn't implement this yet
                    <div className="foodList__icons-confirm-group">
                        <CheckCircleIcon
                            className="foodList__icons-confirm"
                            onClick={functionUpdateFood}
                        />
                        <small>Update?</small>
                    </div>
                </div>
            </div>
//here it will also desappear on the same toggle
            <p
                className={
                    newFoodName
                        ? "foodList__item-newName-delete"
                        : "foodList__day"
                }>
                {val.daysSinceIAte} day(s) ago
            </p>
            <div
                className={
                    newFoodName
                        ? "foodList__item-newName-delete"
                        : "foodList__icons"
                }>
//Here it will update, and it's the button that toggles

                <EditIcon
                    className="foodList__icons-edit"
                    onClick={handleToggle}
                />
                <CancelIcon className="foodList__icons-delete" />
            </div>
        </div>
    );
}

export default ListItem;

</code>```

I saw a solution that used different id's for each component. But this is dynamic, so if I have 1000 items on the data base, it would display all of them, so I can't add all this id's.

I am sorry for the very long explanation. It seems simple, but since I am starting, I spent the day on it + searched and tested several ways.
:|

Body:
let me explain my situation.

I am building a MERN project to my portfolio and I am trying to make a button toggle between the name of an item and a inputfield. So when the user click the pen (edit), it will add a class with the displain:none; in the div with the text coming from the MongoDB data base to hide it and will remove it from the div with the input. I could manage to do it. BUT since the amount of items can inscrease, clicking in one of them cause the toggle in all of them.

It was ok until I send some useState as props to the component.

This is my code from the App.jsx

import React, {useState, useEffect} from "react";
import Axios from "axios";

import "./App.css";
import ListItem from "./components/ListItem";

function App() {
//here are the use states
    const [foodName, setFoodName] = useState("");
    const [days, setDays] = useState(0);
    const [newFoodName, setNewFoodName] = useState("");
    const [foodList, setFoodList] = useState([]);
//here is just the compunication with the DB of a form that I have above those components

    useEffect(() => {
        Axios.get("http://localhost:3001/read").then((response) => {
            setFoodList(response.data);
        });
    }, []);

    const addToList = () => {
        Axios.post("http://localhost:3001/insert", {
            foodName: foodName,
            days: days,
        });
    };

    const updateFood = (id) => {
        Axios.put("http://localhost:3001/update", {
            id: id,
            newFoodName: newFoodName,
        });
    };

    return (

//Here it starts the app with the form and everything

CRUD app with MERN

Favorite Food Database

                Food name:
                <input
                    type="text"
                    onChange={(event) => {
                        setFoodName(event.target.value);
                    }}
                />
                Days since you ate it:
                <input
                    type="number"
                    onChange={(event) => {
                        setDays(event.target.value);
                    }}
                />
                <button onClick={addToList}>Add to list</button>

//Here the form finishes and now it starts the components I showed in the images.

Food List

                {foodList.map((val, key) => {
                    return (
//This is the component and its props
                        <ListItem
                            val={val}
                            key={key}
                            functionUpdateFood={updateFood(val._id)}
                            newFoodName={newFoodName}
                            setNewFoodName={setNewFoodName}
                        />
                    );
                })}

    );
}

export default App;

Now the component code:

import React from "react";
//Material UI Icon imports
import CancelIcon from "@mui/icons-material/Cancel";
import EditIcon from "@mui/icons-material/Edit";
//import CheckIcon from "@mui/icons-material/Check";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";

//App starts here, I destructured the props

function ListItem({val, key, functionUpdateFood, newFoodName, setNewFoodName}) {
    //const [foodList, setFoodList] = useState([]);

//Here I have the handleToggle function that will be used ahead.
    const handleToggle = () => {
        setNewFoodName(!newFoodName);
    };

    return (

                    {val.foodName}

//Here is the input that will replace the FoodName
                    <input
                        type="text"
                        placeholder="The new food name..."
                        className="foodList__item-newName"
                        onChange={(event) => {
                            setNewFoodName(event.target.value);
                        }}
                    />
//Here it will confirm the update and toggle back
//Didn't implement this yet

                        <CheckCircleIcon
                            className="foodList__icons-confirm"
                            onClick={functionUpdateFood}
                        />
                        Update?

//here it will also desappear on the same toggle

                {val.daysSinceIAte} day(s) ago

//Here it will update, and it's the button that toggles

                <EditIcon
                    className="foodList__icons-edit"
                    onClick={handleToggle}
                />
                <CancelIcon className="foodList__icons-delete" />

    );
}

export default ListItem;

I saw a solution that used different id's for each component. But this is dynamic, so if I have 1000 items on the data base, it would display all of them, so I can't add all this id's.

I am sorry for the very long explanation. It seems simple, but since I am starting, I spent the day on it + searched and tested several ways.
:|


问:
My automations are tagged in system manager AWS, but I can't find them
My automations are tagged when I call the method StartAutomationExecution of the "System Simple Manager" SDK.

With the provided methods or even in AWS Dashboard, I cannot see them.

Where can I find the tags I created?


问:
C# ListView move to next object when i click button
I have a little problem. When I click the button, I want the ListView to move to the next object. Also, when it moves to the new object, it needs to get the address of the new object.

The program will switch to the new picture in the ListView every time the save button is clicked.

button click codes:

```<code>
int next=Convert.ToInt32(listView1.FocusedItem.Index) + 1;

listView1.Items[next].Selected = true;

degisken = secilen.SubItems[sayac].Text;

</code>```

listbox1 SelectedIndexChanged codes:

```<code>
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    secilen = listView1.FocusedItem;

    degisken = secilen.SubItems[sayac].Text;

    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

    string alan = degisken;
    pictureBox1.ImageLocation = yol + "/" + alan;
}

</code>```

The program will switch to the new picture in the listview every time the save button is clicked.

Body:
I have a little problem. When I click the button, I want the ListView to move to the next object. Also, when it moves to the new object, it needs to get the address of the new object.

The program will switch to the new picture in the ListView every time the save button is clicked.

button click codes:

int next=Convert.ToInt32(listView1.FocusedItem.Index) + 1;

listView1.Items[next].Selected = true;

degisken = secilen.SubItems[sayac].Text;

listbox1 SelectedIndexChanged codes:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    secilen = listView1.FocusedItem;

    degisken = secilen.SubItems[sayac].Text;

    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

    string alan = degisken;
    pictureBox1.ImageLocation = yol + "/" + alan;
}

The program will switch to the new picture in the listview every time the save button is clicked.


问:
Next.js trying to push data from input value into json, but onSubmit doesn't work at all
I'm trying to put input value into json file, but submit button doesn't work, can you help me with it?

```<code>import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";

export default function adminPcos() {

    // const CreateMePanel = () => {
        const [title, setTitle] = useState(PcosData["pcos-first"].title);
        const [time, setTime] = useState(PcosData["pcos-first"].time);

        const handleSubmit = (e) => {
            PcosData["pcos-first"].title = title;
            PcosData["pcos-first"].time = time;

        }

    return (
        <div>
            <h1>hello world</h1>

            {PcosData["pcos-first"].map((pcosdata) => (
                <form onSubmit={handleSubmit} key={ pcosdata.id } method="post">
                    <input type="text" name={title} defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>
                    <input type="text" name={time} defaultValue={pcosdata.time} onChange={(e) => setTime({text: e.target.value})}/>
                    <input type="submit" value="submit"/>
                </form>
            ))}

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

i checked all of the functions, variables, but didn't find any errors

Body:
I'm trying to put input value into json file, but submit button doesn't work, can you help me with it?

import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";

export default function adminPcos() {

    // const CreateMePanel = () => {
        const [title, setTitle] = useState(PcosData["pcos-first"].title);
        const [time, setTime] = useState(PcosData["pcos-first"].time);

        const handleSubmit = (e) => {
            PcosData["pcos-first"].title = title;
            PcosData["pcos-first"].time = time;

        }

    return (

hello world

            {PcosData["pcos-first"].map((pcosdata) => (
                <form onSubmit={handleSubmit} key={ pcosdata.id } method="post">
                    <input type="text" name={title} defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>
                    <input type="text" name={time} defaultValue={pcosdata.time} onChange={(e) => setTime({text: e.target.value})}/>
                    <input type="submit" value="submit"/>
                </form>
            ))}

    )
}

i checked all of the functions, variables, but didn't find any errors


问:
Problem facing while doing pipe refresh and causing load failure in snowflake instance
while doing select * from internal stage I am facing

```<code>Invalid data encountered during decompression for file:   compression type used: 'GZIP', cause: 'data error'.
</code>```

I want to fetch the rows of the files from the stage . The file format type I used is json and compression is 'gzip'.

But when i keep the compression as none i am facing other error

```<code>invalid character outside of a string: '\37' File line 1, character 1 Row 0, column $1
</code>```

while using the put command its being used as gzip => true

Body:
while doing select * from internal stage I am facing

Invalid data encountered during decompression for file:   compression type used: 'GZIP', cause: 'data error'.

I want to fetch the rows of the files from the stage . The file format type I used is json and compression is 'gzip'.

But when i keep the compression as none i am facing other error

invalid character outside of a string: '\37' File line 1, character 1 Row 0, column $1

while using the put command its being used as gzip => true


问:
How to make cargo use another path to compile instead of /tmp (No space left on device (os error 28))
I'm on Debian 11 with a LUKS encrypted SSD, my /tmp, /var and /home folders are in separated partitions (I don't know why I did this when Installing it)

I tried installing deno using cargo and it throws me this error No space left on device (os error 28) which is due to my /tmp partition being full (it's only 1.7GB)

I've tried changing the $CARGO_TARGET_DIR variable, $TMPDIR variable and linking another folder with the same name as the folder cargo was using to build (cargo-installA5Ssau at that time) and none worked

Is there a way I can make cargo use another directory other than /tmp or increase the size of /tmp (this one is my second choice as I guess it'll be harder)?


问:
Executing system calls in a C program via strings?
I have an strace log and want to execute the system calls line by line in a C program. Of course these system calls would be in the form of strings.

For example:
"openat(AT_FDCWD, "filename", O_RDONLY|O_CLOEXEC) = 4"

^This is one of the lines in my strace log. And I want to execute lines like these as system calls in my C program.
Is there a way to execute them? And also get the return values?


问:
getting renderflexoverflowed error between two children of column
getting error renderoverflow by 29 pixel below the edit profile button

```<code>Widget build(BuildContext context) {
  return Row(children: [
    Container(
        width: 35,
        height: 35,
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: const BorderRadius.all(Radius.circular(30)),
          image: DecorationImage(
            fit: BoxFit.fill,
            image: NetworkImage(img),
          ),
        )),
    //  const Spacer(flex: 2),
    Column(

      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Padding(
            padding: const EdgeInsets.only(left: 5),
            child: Text('Hi $userName',
                textAlign: TextAlign.left,
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ))),

        Padding(
          padding: const EdgeInsets.only(left: 5),
          child: TextButton(
            onPressed:(){
              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>const UserProfiles()));
            },
              child: const Text('  Edit Profile',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 13,
                color: Colors.purple,
              ))),
        ),
      ],
    )
  ]);
}
</code>```

Body:
getting error renderoverflow by 29 pixel below the edit profile button

Widget build(BuildContext context) {
  return Row(children: [
    Container(
        width: 35,
        height: 35,
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: const BorderRadius.all(Radius.circular(30)),
          image: DecorationImage(
            fit: BoxFit.fill,
            image: NetworkImage(img),
          ),
        )),
    //  const Spacer(flex: 2),
    Column(

      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Padding(
            padding: const EdgeInsets.only(left: 5),
            child: Text('Hi $userName',
                textAlign: TextAlign.left,
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ))),

        Padding(
          padding: const EdgeInsets.only(left: 5),
          child: TextButton(
            onPressed:(){
              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>const UserProfiles()));
            },
              child: const Text('  Edit Profile',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 13,
                color: Colors.purple,
              ))),
        ),
      ],
    )
  ]);
}


问:
focusin triggered before mousedown/touchstart (when switching between mouse and touch)
I want to have an observable, that tells how a focus on a button was initiated.
I distinguish between keyboard, mouse and touch. Additionally I want to know if a focus happend without keyboard touch or mouse. This is an exercise for learning RxJs. I do not want to discuss the sense of this task here.

this is the code of the Directive. I have created Observables to listen to touchstart,  mousedown, focusin and keydown (filtered to only emit if Tab was pressed, because thats how you change focus with the Keyboard).
I combine those using race to only emit the first value to arrive.
Since the Button should be focusable again, I made it repeat. The repeat would result in 'script' being emitted after every other Event (mouse keyboard, touch). Thats why I implemented throttleTime(100).

```<code>export type FocusType
  = 'keyboard' | 'mouse' | 'touch' | 'script' | 'blur';
@Directive({
  selector: '[focusType]'
})
export class FocusTypeDirective {

  @Output()  //output of this Observable alters the style of the button
  readonly focusType: Observable<FocusType> = of('blur');
  constructor(elRef: ElementRef) {
    const nativeElement = elRef.nativeElement;
    const keyboard$ = fromEvent<KeyboardEvent>(document, 'keydown').pipe(
      filter(x => x.code == 'Tab'),
      map(():FocusType => 'keyboard'),
      take(1),
      tap(x => console.log(x)),
    );
    const mouse$ = fromEvent(nativeElement, 'mousedown').pipe(
      map(():FocusType => 'mouse'),
      take(1),
      tap(x => console.log(x)),
    );
    const touch$ = fromEvent(nativeElement, 'touchstart').pipe(
      map(():FocusType => 'touch'),
      take(1),
      tap(x => console.log(x)),
    );
    const focus$ = fromEvent(nativeElement, 'focusin').pipe(
      map(():FocusType => 'script'),
      take(1),
      tap(x => console.log(x)),
    );

    this.focusType.pipe(
      switchMap(():Observable<FocusType> => race(keyboard$, mouse$, touch$, focus$).pipe(repeat())),
      throttleTime(100),
      tap(x => console.log('result: ',x)),
    ).subscribe()
  }

}
</code>```

Here is the strange behaviour:
When I touch the Button the observable emits 'touch'.
If I then click the button the observable emits 'script', because the focusin Event fires before the mousedown Event does.

This is also happening if i first click and then touch the button.

Here is my console, after clicking for the first time:

Here is my console, after I touched the button:

Am I missing something? The focusin event  should not fire before mousedown, should it?

Body:
I want to have an observable, that tells how a focus on a button was initiated.
I distinguish between keyboard, mouse and touch. Additionally I want to know if a focus happend without keyboard touch or mouse. This is an exercise for learning RxJs. I do not want to discuss the sense of this task here.

this is the code of the Directive. I have created Observables to listen to touchstart,  mousedown, focusin and keydown (filtered to only emit if Tab was pressed, because thats how you change focus with the Keyboard).
I combine those using race to only emit the first value to arrive.
Since the Button should be focusable again, I made it repeat. The repeat would result in 'script' being emitted after every other Event (mouse keyboard, touch). Thats why I implemented throttleTime(100).

export type FocusType
  = 'keyboard' | 'mouse' | 'touch' | 'script' | 'blur';
@Directive({
  selector: '[focusType]'
})
export class FocusTypeDirective {

  @Output()  //output of this Observable alters the style of the button
  readonly focusType: Observable<FocusType> = of('blur');
  constructor(elRef: ElementRef) {
    const nativeElement = elRef.nativeElement;
    const keyboard$ = fromEvent<KeyboardEvent>(document, 'keydown').pipe(
      filter(x => x.code == 'Tab'),
      map(():FocusType => 'keyboard'),
      take(1),
      tap(x => console.log(x)),
    );
    const mouse$ = fromEvent(nativeElement, 'mousedown').pipe(
      map(():FocusType => 'mouse'),
      take(1),
      tap(x => console.log(x)),
    );
    const touch$ = fromEvent(nativeElement, 'touchstart').pipe(
      map(():FocusType => 'touch'),
      take(1),
      tap(x => console.log(x)),
    );
    const focus$ = fromEvent(nativeElement, 'focusin').pipe(
      map(():FocusType => 'script'),
      take(1),
      tap(x => console.log(x)),
    );

    this.focusType.pipe(
      switchMap(():Observable<FocusType> => race(keyboard$, mouse$, touch$, focus$).pipe(repeat())),
      throttleTime(100),
      tap(x => console.log('result: ',x)),
    ).subscribe()
  }

}

Here is the strange behaviour:
When I touch the Button the observable emits 'touch'.
If I then click the button the observable emits 'script', because the focusin Event fires before the mousedown Event does.

This is also happening if i first click and then touch the button.

Here is my console, after clicking for the first time:

Here is my console, after I touched the button:

Am I missing something? The focusin event  should not fire before mousedown, should it?


问:
How to add grammarly plugin in laravel forms?
I have this file

```<code>@section('content')

    <form method="post" action="{{ route('member.articles.store') }}" enctype="multipart/form-data"
          onSubmit="submit.disabled=true; submit.value='{{ __('Submitting ...') }}'; return true;">
        @csrf

        <div class="card bg-light">
            <div class="card-header">{{ __('Add Article') }}</div>
            <div class="card-body">

                <div class="form-group">
                    {{ Form::label('title', __('Title')) }}
                    {{ Form::text('title', old('title'), ['class' => 'form-control', 'required' => true, 'maxlength' => 190]) }}
                </div>

                <div class="form-group" style="display: none">
                    {{ Form::label('slug', __('Slug(URL Key)')) }}
                    {{ Form::text('slug', old('slug'), ['class' => 'form-control', 'maxlength' => 190]) }}
                </div>

                <div class="form-group">
                    {{ Form::label('category', __('Category')) }}
                    {{ Form::select('category', $categories, old('category'),
                        ['class' => 'form-control select2', 'required' => true]) }}
                </div>

                <div class="form-group">
                    {{ Form::label('content', __('Content')) }}
                    {{ Form::textarea('content', old('content'), ['class' => 'form-control text-editor'])}}
                </div>
</code>```

And i want to add grammarly plugin in content area.

FYI: https://developer.grammarly.com/docs/api/editor-sdk/

I tried this but not working:-

```<code><div class="form-group">
    {{ Form::label('content', __('Content')) }}
    <grammarly-editor-plugin>

        {{ Form::textarea('content', old('content'), ['class' => 'form-control text-editor'])}}

    </grammarly-editor-plugin>
</div>
</code>```

Body:
I have this file

@section('content')

    <form method="post" action="{{ route('member.articles.store') }}" enctype="multipart/form-data"
          onSubmit="submit.disabled=true; submit.value='{{ __('Submitting ...') }}'; return true;">
        @csrf

{{ __('Add Article') }}

                    {{ Form::label('title', __('Title')) }}
                    {{ Form::text('title', old('title'), ['class' => 'form-control', 'required' => true, 'maxlength' => 190]) }}

                    {{ Form::label('slug', __('Slug(URL Key)')) }}
                    {{ Form::text('slug', old('slug'), ['class' => 'form-control', 'maxlength' => 190]) }}

                    {{ Form::label('category', __('Category')) }}
                    {{ Form::select('category', $categories, old('category'),
                        ['class' => 'form-control select2', 'required' => true]) }}

                    {{ Form::label('content', __('Content')) }}
                    {{ Form::textarea('content', old('content'), ['class' => 'form-control text-editor'])}}

And i want to add grammarly plugin in content area.

FYI: https://developer.grammarly.com/docs/api/editor-sdk/

I tried this but not working:-

    {{ Form::label('content', __('Content')) }}
    <grammarly-editor-plugin>

        {{ Form::textarea('content', old('content'), ['class' => 'form-control text-editor'])}}

    </grammarly-editor-plugin>


问:
Artifactory trash contains lots of empty folders
We have a mechanism in place that deletes artifacts from Artifactory (Cloud) on a regular basis meaning our trash is quite big. It uses 33% of our total storage.

The retention policy of the trash is set to 14 days. When I look at the trash can I notice a lot of empty folders. I assume they are empty because nothings is visible when I expand them in the UI and when I use the REST call https://<my_organization>.jfrog.io/artifactory/api/storage/auto-trashcan?list&deep=1&listFolders=1&mdTimestamps=1&includeRootPath=1 the sizes shows as -1.

I have more than 100k "empty" folders in the trash.

Why are they here and should I worry about those?


问:
In my java servlet application ThreadPool is not working properly with AsyncHttpClient
BoundRequestBuilder boundRequestBuilder = asyncHttpClient.preparePost(url); //making the bound request builder using AsyncHttpClient and then creating task
Runnable pzeonThreadPoolExecutor = new PzeonThreadPoolExecutor(this.event, this.boundRequestBuilder);
pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);//this is created within a static block so that only once the pool will be created
pool.execute(pzeonThreadPoolExecutor);
//by overriding run method i am calling execute(); method to execute the post request
boundRequestBuilder.execute().get();
do anyone have solution why my ThreadPool blockingQueue is not working.

I am expecting that the blocking queue of ThreadPoolExecutor should block the Asynchrounous request if all the threads are busy in processing previous 2 requests


问:
how to determine USN_RECORD version for usn journal?
I want to learn the principle of everything, and use usn logs to monitor the addition and deletion of system files.
I wrote a piece of code under windows11, VS2019, Platform Toolset= (v142).
But I found that record->Reason (USN_RECORD) always returns 0; also, if I delete a file, I monitor that it is a garbled file name with $. For example, if I delete the file "ABC.TXT", I monitor and detect that a file name like "$1a2f5.txt" is returned. After I googled, I found that it is because USN_RECORD has multiple versions, V2, V3, V4, but I don't know how to detect the version number.
Here is the code:</p>
```<code>#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN        // 从 Windows 头中排除极少使用的资料
#endif

#include <Windows.h>

#include <stdio.h>
#include <string>
#include <iostream>
#include "usn_test.h"

//#define BUFFER_SIZE (1024 * 1024)
constexpr auto BUFFER_SIZE = sizeof(USN) + 0x100000;
HANDLE drive;
USN maxusn;
DWORDLONG gUsnJournalID;
void delete_usn()
{
    DELETE_USN_JOURNAL_DATA dujd;
    dujd.UsnJournalID = gUsnJournalID;
    dujd.DeleteFlags = USN_DELETE_FLAG_DELETE;
    DWORD br;

    if (DeviceIoControl(drive,
        FSCTL_DELETE_USN_JOURNAL,
        &dujd,
        sizeof(dujd),
        nullptr,
        0,
        &br,
        nullptr)
        )
    {
        CloseHandle(drive);
        return;
    }
    CloseHandle(drive);
    return;
}

template<typename _T_USN_RECORD>
void check_record(_T_USN_RECORD* record)
{

    WCHAR szName[MAX_PATH];

    CopyMemory(szName,
        ((PBYTE)record) + record->FileNameOffset,
        record->FileNameLength);

    szName[record->FileNameLength / sizeof(WCHAR)] = 0;
    std::wcout << szName << L",Reason:" << record->Reason << std::endl;

}

template<>
void check_record(USN_RECORD_V4* record)
{
    WCHAR szName[MAX_PATH];

    CopyMemory(szName,
        ((PBYTE)record) + record->Extents->Offset,
        record->Extents->Length);
    // Let's zero-terminate it
    szName[record->Extents->Length / sizeof(WCHAR)] = 0;
    std::wcout << szName << L",Reason:" << record->Reason << std::endl;
}
bool create_usn()
{
    CREATE_USN_JOURNAL_DATA cujd{};
    cujd.MaximumSize = 0; // 0表示使用默认值
    cujd.AllocationDelta = 0; // 0表示使用默认值

    DWORD br;
    if (
        DeviceIoControl(drive, // handle to volume
            FSCTL_CREATE_USN_JOURNAL, // dwIoControlCode
            &cujd, // input buffer
            sizeof(cujd), // size of input buffer
            nullptr, // lpOutBuffer
            0, // nOutBufferSize
            &br, // number of bytes returned
            nullptr) // OVERLAPPED structure
        )
    {
        return true;
    }
    auto&& info = "create usn error. Error code: " + std::to_string(GetLastError());
    fprintf(stderr, "fileSearcherUSN: %s\n", info.c_str());
    return false;
}

template<typename _T_USN_RECORD>
void read_record(DWORDLONG& nextid, void* buffer, _T_USN_RECORD*& record, _T_USN_RECORD*& recordend, const DWORD& bytecount)
{
    nextid = *((DWORDLONG*)buffer);
    //      printf("Next ID: %lu\n", nextid);

    record = (_T_USN_RECORD*)((USN*)buffer + 1);
    recordend = (_T_USN_RECORD*)(((BYTE*)buffer) + bytecount);

    while (record < recordend)
    {
        check_record(record);
        record = (_T_USN_RECORD*)(((BYTE*)record) + record->RecordLength);
    }
}
template<>
void read_record(DWORDLONG& nextid, void* buffer, USN_RECORD_V4*& record, USN_RECORD_V4*& recordend, const DWORD& bytecount)
{
    nextid = *((DWORDLONG*)buffer);
    //      printf("Next ID: %lu\n", nextid);

    record = (USN_RECORD_V4*)((USN*)buffer + 1);
    recordend = (USN_RECORD_V4*)(((BYTE*)buffer) + bytecount);

    while (record < recordend)
    {
        //check_record(record);
        record = (USN_RECORD_V4*)(((BYTE*)record) + record->Header.RecordLength);
    }
}
int main(int argc, char** argv)
{
    //typedef USN_JOURNAL_DATA_V2 USN_JOURNAL_DATA;
#define FILE_END 38
    //typedef MFT_ENUM_DATA MFT_ENUM_DATA_V1;
    MFT_ENUM_DATA mft_enum_data;
    DWORD bytecount = 1;
    void* buffer;
    USN_RECORD_V3* recordV3;
    USN_RECORD_V3* recordendV3;
    USN_RECORD_V4* recordV4;
    USN_RECORD_V4* recordendV4;
    USN_JOURNAL_DATA* journal;
    DWORDLONG nextid{};

    buffer = new BYTE[BUFFER_SIZE];
    if (buffer == NULL)
    {
        printf("VirtualAlloc: %u\n", GetLastError());
        return 0;
    }

    printf("Opening volume.\n");

    drive = CreateFile(L"\\\\?\\h:", GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_FLAG_NO_BUFFERING, NULL);

    if (drive == INVALID_HANDLE_VALUE)
    {
        printf("CreateFile: %u\n", GetLastError());
        return 0;
    }
    if (!create_usn())
    {
        return -1;
    }
    printf("Calling FSCTL_QUERY_USN_JOURNAL\n");

    if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
    {
        printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
        return 0;
    }
    // delete_usn();

    journal = (USN_JOURNAL_DATA*)buffer;
    gUsnJournalID = journal->UsnJournalID;
    printf("UsnJournalID: %lu\n", journal->UsnJournalID);
    printf("FirstUsn: %lu\n", journal->FirstUsn);
    printf("NextUsn: %lu\n", journal->NextUsn);

    maxusn = journal->MaxUsn;

    mft_enum_data.StartFileReferenceNumber = 0;
    mft_enum_data.LowUsn = 0;
    mft_enum_data.HighUsn = maxusn;
    mft_enum_data.MaxMajorVersion = journal->MaxSupportedMajorVersion;
    mft_enum_data.MinMajorVersion = journal->MinSupportedMajorVersion;

    for (;;)
    {
        //      printf("=================================================================\n");
        //      printf("Calling FSCTL_ENUM_USN_DATA\n");

        if (!DeviceIoControl(drive, FSCTL_ENUM_USN_DATA, &mft_enum_data, sizeof(mft_enum_data), buffer, BUFFER_SIZE, &bytecount, NULL))
        {
            auto bRet = GetLastError();
            if (bRet != 38)
            {
                delete_usn();
                break;
            }
            if (bRet == 38)//file to end
            {
                //   break;
                Sleep(1000);//wait for new file change
                auto oldNextUsn = journal->NextUsn;
                if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
                {
                    printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
                    return 0;
                }
                journal = (USN_JOURNAL_DATA*)buffer;
                if (journal->NextUsn > oldNextUsn)//new file have changed
                {
                    mft_enum_data.StartFileReferenceNumber = 0;
                    mft_enum_data.LowUsn = oldNextUsn;
                    mft_enum_data.HighUsn = journal->MaxUsn;
                    mft_enum_data.MaxMajorVersion = journal->MaxSupportedMajorVersion;
                    mft_enum_data.MinMajorVersion = journal->MinSupportedMajorVersion;
                }
                continue;
            }

        }
        //      printf("Bytes returned: %u\n", bytecount);
        if(mft_enum_data.MinMajorVersion == 4)//it's wrong if i determine version by mft_enum_data.MaxMajorVersion
            read_record(nextid, buffer, recordV4, recordendV4, bytecount);
        else
            read_record(nextid, buffer, recordV3, recordendV3, bytecount);

        mft_enum_data.StartFileReferenceNumber = nextid;
    }
    delete[] buffer;
    delete_usn();
}

</code>```
```<code>

I have spent 2 weeks for this.google and write a test.day and day.
</code>```

Body:
I want to learn the principle of everything, and use usn logs to monitor the addition and deletion of system files.
I wrote a piece of code under windows11, VS2019, Platform Toolset= (v142).
But I found that record->Reason (USN_RECORD) always returns 0; also, if I delete a file, I monitor that it is a garbled file name with $. For example, if I delete the file "ABC.TXT", I monitor and detect that a file name like "$1a2f5.txt" is returned. After I googled, I found that it is because USN_RECORD has multiple versions, V2, V3, V4, but I don't know how to detect the version number.
Here is the code:

#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN        // 从 Windows 头中排除极少使用的资料
#endif

#include <Windows.h>

#include <stdio.h>
#include <string>
#include <iostream>
#include "usn_test.h"

//#define BUFFER_SIZE (1024 * 1024)
constexpr auto BUFFER_SIZE = sizeof(USN) + 0x100000;
HANDLE drive;
USN maxusn;
DWORDLONG gUsnJournalID;
void delete_usn()
{
    DELETE_USN_JOURNAL_DATA dujd;
    dujd.UsnJournalID = gUsnJournalID;
    dujd.DeleteFlags = USN_DELETE_FLAG_DELETE;
    DWORD br;

    if (DeviceIoControl(drive,
        FSCTL_DELETE_USN_JOURNAL,
        &dujd,
        sizeof(dujd),
        nullptr,
        0,
        &br,
        nullptr)
        )
    {
        CloseHandle(drive);
        return;
    }
    CloseHandle(drive);
    return;
}

template<typename _T_USN_RECORD>
void check_record(_T_USN_RECORD* record)
{

    WCHAR szName[MAX_PATH];

    CopyMemory(szName,
        ((PBYTE)record) + record->FileNameOffset,
        record->FileNameLength);

    szName[record->FileNameLength / sizeof(WCHAR)] = 0;
    std::wcout << szName << L",Reason:" << record->Reason << std::endl;

}

template<>
void check_record(USN_RECORD_V4* record)
{
    WCHAR szName[MAX_PATH];

    CopyMemory(szName,
        ((PBYTE)record) + record->Extents->Offset,
        record->Extents->Length);
    // Let's zero-terminate it
    szName[record->Extents->Length / sizeof(WCHAR)] = 0;
    std::wcout << szName << L",Reason:" << record->Reason << std::endl;
}
bool create_usn()
{
    CREATE_USN_JOURNAL_DATA cujd{};
    cujd.MaximumSize = 0; // 0表示使用默认值
    cujd.AllocationDelta = 0; // 0表示使用默认值

    DWORD br;
    if (
        DeviceIoControl(drive, // handle to volume
            FSCTL_CREATE_USN_JOURNAL, // dwIoControlCode
            &cujd, // input buffer
            sizeof(cujd), // size of input buffer
            nullptr, // lpOutBuffer
            0, // nOutBufferSize
            &br, // number of bytes returned
            nullptr) // OVERLAPPED structure
        )
    {
        return true;
    }
    auto&& info = "create usn error. Error code: " + std::to_string(GetLastError());
    fprintf(stderr, "fileSearcherUSN: %s\n", info.c_str());
    return false;
}

template<typename _T_USN_RECORD>
void read_record(DWORDLONG& nextid, void* buffer, _T_USN_RECORD*& record, _T_USN_RECORD*& recordend, const DWORD& bytecount)
{
    nextid = *((DWORDLONG*)buffer);
    //      printf("Next ID: %lu\n", nextid);

    record = (_T_USN_RECORD*)((USN*)buffer + 1);
    recordend = (_T_USN_RECORD*)(((BYTE*)buffer) + bytecount);

    while (record < recordend)
    {
        check_record(record);
        record = (_T_USN_RECORD*)(((BYTE*)record) + record->RecordLength);
    }
}
template<>
void read_record(DWORDLONG& nextid, void* buffer, USN_RECORD_V4*& record, USN_RECORD_V4*& recordend, const DWORD& bytecount)
{
    nextid = *((DWORDLONG*)buffer);
    //      printf("Next ID: %lu\n", nextid);

    record = (USN_RECORD_V4*)((USN*)buffer + 1);
    recordend = (USN_RECORD_V4*)(((BYTE*)buffer) + bytecount);

    while (record < recordend)
    {
        //check_record(record);
        record = (USN_RECORD_V4*)(((BYTE*)record) + record->Header.RecordLength);
    }
}
int main(int argc, char** argv)
{
    //typedef USN_JOURNAL_DATA_V2 USN_JOURNAL_DATA;
#define FILE_END 38
    //typedef MFT_ENUM_DATA MFT_ENUM_DATA_V1;
    MFT_ENUM_DATA mft_enum_data;
    DWORD bytecount = 1;
    void* buffer;
    USN_RECORD_V3* recordV3;
    USN_RECORD_V3* recordendV3;
    USN_RECORD_V4* recordV4;
    USN_RECORD_V4* recordendV4;
    USN_JOURNAL_DATA* journal;
    DWORDLONG nextid{};

    buffer = new BYTE[BUFFER_SIZE];
    if (buffer == NULL)
    {
        printf("VirtualAlloc: %u\n", GetLastError());
        return 0;
    }

    printf("Opening volume.\n");

    drive = CreateFile(L"\\\\?\\h:", GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_FLAG_NO_BUFFERING, NULL);

    if (drive == INVALID_HANDLE_VALUE)
    {
        printf("CreateFile: %u\n", GetLastError());
        return 0;
    }
    if (!create_usn())
    {
        return -1;
    }
    printf("Calling FSCTL_QUERY_USN_JOURNAL\n");

    if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
    {
        printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
        return 0;
    }
    // delete_usn();

    journal = (USN_JOURNAL_DATA*)buffer;
    gUsnJournalID = journal->UsnJournalID;
    printf("UsnJournalID: %lu\n", journal->UsnJournalID);
    printf("FirstUsn: %lu\n", journal->FirstUsn);
    printf("NextUsn: %lu\n", journal->NextUsn);

    maxusn = journal->MaxUsn;

    mft_enum_data.StartFileReferenceNumber = 0;
    mft_enum_data.LowUsn = 0;
    mft_enum_data.HighUsn = maxusn;
    mft_enum_data.MaxMajorVersion = journal->MaxSupportedMajorVersion;
    mft_enum_data.MinMajorVersion = journal->MinSupportedMajorVersion;

    for (;;)
    {
        //      printf("=================================================================\n");
        //      printf("Calling FSCTL_ENUM_USN_DATA\n");

        if (!DeviceIoControl(drive, FSCTL_ENUM_USN_DATA, &mft_enum_data, sizeof(mft_enum_data), buffer, BUFFER_SIZE, &bytecount, NULL))
        {
            auto bRet = GetLastError();
            if (bRet != 38)
            {
                delete_usn();
                break;
            }
            if (bRet == 38)//file to end
            {
                //   break;
                Sleep(1000);//wait for new file change
                auto oldNextUsn = journal->NextUsn;
                if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
                {
                    printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
                    return 0;
                }
                journal = (USN_JOURNAL_DATA*)buffer;
                if (journal->NextUsn > oldNextUsn)//new file have changed
                {
                    mft_enum_data.StartFileReferenceNumber = 0;
                    mft_enum_data.LowUsn = oldNextUsn;
                    mft_enum_data.HighUsn = journal->MaxUsn;
                    mft_enum_data.MaxMajorVersion = journal->MaxSupportedMajorVersion;
                    mft_enum_data.MinMajorVersion = journal->MinSupportedMajorVersion;
                }
                continue;
            }

        }
        //      printf("Bytes returned: %u\n", bytecount);
        if(mft_enum_data.MinMajorVersion == 4)//it's wrong if i determine version by mft_enum_data.MaxMajorVersion
            read_record(nextid, buffer, recordV4, recordendV4, bytecount);
        else
            read_record(nextid, buffer, recordV3, recordendV3, bytecount);

        mft_enum_data.StartFileReferenceNumber = nextid;
    }
    delete[] buffer;
    delete_usn();
}

I have spent 2 weeks for this.google and write a test.day and day.


问:
Failed to find manifest in GitLab cicd pipeline
In the CICD pipeline, I'm trying to push an image to ECR.

The job fails with a "Failed to find manifest" message.

What is a manifest and what does this error message mean? I've google it and was honestly surprised to come up with no quality results.


问:
python: prevent discarding of the function return value
There's a common error in the code where people write something like:

```<code>if (id):
    query.filter(row.id == id)
</code>```

instead of

```<code>if (id):
    query = query.filter(row.id == id)
</code>```

The code looks "valid" and it's very hard to spot these by hand. In C++ there's the [[nodiscard]] function attribute that effectively prevents this mistake by enforcing the usage of the return value. I wasn't able to find anything similar in Python, does it exist?

UPD A similar question: How to make pylint report unused return values

I've checked pylint and mypy, apparently neither of them catch this as of today.

UPD2 A pylint feature request: https://github.com/PyCQA/pylint/issues/7935

Body:
There's a common error in the code where people write something like:

if (id):
    query.filter(row.id == id)

instead of

if (id):
    query = query.filter(row.id == id)

The code looks "valid" and it's very hard to spot these by hand. In C++ there's the [[nodiscard]] function attribute that effectively prevents this mistake by enforcing the usage of the return value. I wasn't able to find anything similar in Python, does it exist?

UPD A similar question: How to make pylint report unused return values

I've checked pylint and mypy, apparently neither of them catch this as of today.

UPD2 A pylint feature request: https://github.com/PyCQA/pylint/issues/7935


问:
How to build prediction models with selected features after performing feature selection?
I'm trying to perfrom LassoCV feature selection on my miRNA expression dataset and after finding out the 100 best features(miRNAs in this case) I want to build some classification models (like SVM, RF,KNN etc.) for prediction using those 100 miRNAs. I can use the following code for my data without any problems if I don't do train-test splitting.

```<code>from sklearn.linear_model import LassoCV
from sklearn.feature_selection import SelectFromModel
feature_names = df.columns[0:2565]
clf = LassoCV().fit(X, y)
importance = np.abs(clf.coef_)
idx_third = importance.argsort()[-3]
threshold = importance[idx_third] + 0.01
idx_features = (-importance).argsort()[:100]
name_features = np.array(feature_names)[idx_features]
print('Selected features: {}'.format(name_features))
sfm = SelectFromModel(clf, threshold=threshold)
sfm.fit(X, y)
X = sfm.transform(X)
</code>```

But my goal is to select features after the split. And I think I'm having trouble identifying the x_train and X_test after applying LassoCV. Here's the code after train_test_split:

```<code>clf = LassoCV().fit(X_train, y_train)
importance = np.abs(clf.coef_)
idx_third = importance.argsort()[-3]
threshold = importance[idx_third] + 0.01
idx_features = (-importance).argsort()[:100]
name_features = np.array(feature_names)[idx_features]
print('Selected features: {}'.format(name_features))

sfm = SelectFromModel(clf, threshold=threshold)
sfm.fit(X_train, y_train)
</code>```

and the output:

```<code>Selected features: ['MIMAT0019071' 'MIMAT0019947' 'MIMAT0005951' 'MIMAT0025458'
 'MIMAT0019710' 'MIMAT0005880' 'MIMAT0004810' 'MIMAT0026481'
 'MIMAT0016904' 'MIMAT0003340' 'MIMAT0016851' 'MIMAT0019033'
 'MIMAT0004508' 'MIMAT0024615' 'MIMAT0022478' 'MIMAT0019004'
 'MIMAT0004948' 'MIMAT0005898' 'MIMAT0000064' 'MIMAT0015087'
 'MIMAT0005942' 'MIMAT0004602' 'MIMAT0027666' 'MIMAT0003250'
 'MIMAT0022289' 'MIMAT0005866' 'MIMAT0004903' 'MIMAT0004592'
 'MIMAT0021040' 'MIMAT0003237' 'MIMAT0018954' 'MIMAT0019858'
 'MIMAT0003270' 'MIMAT0030416' 'MIMAT0019361' 'MIMAT0018083'
 'MIMAT0000440' 'MIMAT0018070' 'MIMAT0016863' 'MIMAT0015066'
 'MIMAT0027576' 'MIMAT0017997' 'MIMAT0000421' 'MIMAT0003165'
 'MIMAT0027587' 'MIMAT0004603' 'MIMAT0003330' 'MIMAT0019948'
 'MIMAT0004978' 'MIMAT0018951' 'MIMAT0016872' 'MIMAT0019203'
 'MIMAT0015005' 'MIMAT0003319' 'MIMAT0003316' 'MIMAT0022265'
 'MIMAT0011159' 'MIMAT0016898' 'MIMAT0003240' 'MIMAT0004925'
 'MIMAT0027580' 'MIMAT0019067' 'MIMAT0018121' 'MIMAT0028112'
 'MIMAT0019714' 'MIMAT0000685' 'MIMAT0019742' 'MIMAT0027627'
 'MIMAT0003277' 'MIMAT0019737' 'MIMAT0003284' 'MIMAT0020925'
 'MIMAT0022929' 'MIMAT0022938' 'MIMAT0020924' 'MIMAT0020603'
 'MIMAT0020602' 'MIMAT0020956' 'MIMAT0020601' 'MIMAT0020600'
 'MIMAT0022719' 'MIMAT0020300' 'MIMAT0022939' 'MIMAT0022940'
 'MIMAT0019984' 'MIMAT0019983' 'MIMAT0019982' 'MIMAT0019981'
 'MIMAT0019980' 'MIMAT0019979' 'MIMAT0019978' 'MIMAT0019977'
 'MIMAT0019976' 'MIMAT0022941' 'MIMAT0020541' 'MIMAT0019985'
 'MIMAT0020958' 'MIMAT0019975' 'MIMAT0021036' 'MIMAT0021037']
SelectFromModel(estimator=LassoCV(), threshold=0.041810456987634005)
</code>```

So, no problems until here and we can see the 100 miRNAs to be selected. I try to select these features by applying X = sfm.transform(X) to the split dataset like this:

```<code>X_train = sfm.transform(X_train)
X_test = sfm.transform(X_test)
</code>```

But when I check the X_train.shape and X_test.shape the output is like this:

```<code>((164, 0), (55, 0))
</code>```

So, of course when I try to train my model:

```<code>from sklearn.svm import SVC
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train, y_train)
</code>```

it gives me this error:

```<code>ValueError: Found array with 0 feature(s) (shape=(164, 0)) while a minimum of 1 is required.
</code>```

I'm new to machine learning especially feature selection bit. If anyone can tell me how to develope models with the selected features in this particular case, I would greatly appreciate it.

Body:
I'm trying to perfrom LassoCV feature selection on my miRNA expression dataset and after finding out the 100 best features(miRNAs in this case) I want to build some classification models (like SVM, RF,KNN etc.) for prediction using those 100 miRNAs. I can use the following code for my data without any problems if I don't do train-test splitting.

from sklearn.linear_model import LassoCV
from sklearn.feature_selection import SelectFromModel
feature_names = df.columns[0:2565]
clf = LassoCV().fit(X, y)
importance = np.abs(clf.coef_)
idx_third = importance.argsort()[-3]
threshold = importance[idx_third] + 0.01
idx_features = (-importance).argsort()[:100]
name_features = np.array(feature_names)[idx_features]
print('Selected features: {}'.format(name_features))
sfm = SelectFromModel(clf, threshold=threshold)
sfm.fit(X, y)
X = sfm.transform(X)

But my goal is to select features after the split. And I think I'm having trouble identifying the x_train and X_test after applying LassoCV. Here's the code after train_test_split:

clf = LassoCV().fit(X_train, y_train)
importance = np.abs(clf.coef_)
idx_third = importance.argsort()[-3]
threshold = importance[idx_third] + 0.01
idx_features = (-importance).argsort()[:100]
name_features = np.array(feature_names)[idx_features]
print('Selected features: {}'.format(name_features))

sfm = SelectFromModel(clf, threshold=threshold)
sfm.fit(X_train, y_train)

and the output:

Selected features: ['MIMAT0019071' 'MIMAT0019947' 'MIMAT0005951' 'MIMAT0025458'
 'MIMAT0019710' 'MIMAT0005880' 'MIMAT0004810' 'MIMAT0026481'
 'MIMAT0016904' 'MIMAT0003340' 'MIMAT0016851' 'MIMAT0019033'
 'MIMAT0004508' 'MIMAT0024615' 'MIMAT0022478' 'MIMAT0019004'
 'MIMAT0004948' 'MIMAT0005898' 'MIMAT0000064' 'MIMAT0015087'
 'MIMAT0005942' 'MIMAT0004602' 'MIMAT0027666' 'MIMAT0003250'
 'MIMAT0022289' 'MIMAT0005866' 'MIMAT0004903' 'MIMAT0004592'
 'MIMAT0021040' 'MIMAT0003237' 'MIMAT0018954' 'MIMAT0019858'
 'MIMAT0003270' 'MIMAT0030416' 'MIMAT0019361' 'MIMAT0018083'
 'MIMAT0000440' 'MIMAT0018070' 'MIMAT0016863' 'MIMAT0015066'
 'MIMAT0027576' 'MIMAT0017997' 'MIMAT0000421' 'MIMAT0003165'
 'MIMAT0027587' 'MIMAT0004603' 'MIMAT0003330' 'MIMAT0019948'
 'MIMAT0004978' 'MIMAT0018951' 'MIMAT0016872' 'MIMAT0019203'
 'MIMAT0015005' 'MIMAT0003319' 'MIMAT0003316' 'MIMAT0022265'
 'MIMAT0011159' 'MIMAT0016898' 'MIMAT0003240' 'MIMAT0004925'
 'MIMAT0027580' 'MIMAT0019067' 'MIMAT0018121' 'MIMAT0028112'
 'MIMAT0019714' 'MIMAT0000685' 'MIMAT0019742' 'MIMAT0027627'
 'MIMAT0003277' 'MIMAT0019737' 'MIMAT0003284' 'MIMAT0020925'
 'MIMAT0022929' 'MIMAT0022938' 'MIMAT0020924' 'MIMAT0020603'
 'MIMAT0020602' 'MIMAT0020956' 'MIMAT0020601' 'MIMAT0020600'
 'MIMAT0022719' 'MIMAT0020300' 'MIMAT0022939' 'MIMAT0022940'
 'MIMAT0019984' 'MIMAT0019983' 'MIMAT0019982' 'MIMAT0019981'
 'MIMAT0019980' 'MIMAT0019979' 'MIMAT0019978' 'MIMAT0019977'
 'MIMAT0019976' 'MIMAT0022941' 'MIMAT0020541' 'MIMAT0019985'
 'MIMAT0020958' 'MIMAT0019975' 'MIMAT0021036' 'MIMAT0021037']
SelectFromModel(estimator=LassoCV(), threshold=0.041810456987634005)

So, no problems until here and we can see the 100 miRNAs to be selected. I try to select these features by applying X = sfm.transform(X) to the split dataset like this:

X_train = sfm.transform(X_train)
X_test = sfm.transform(X_test)

But when I check the X_train.shape and X_test.shape the output is like this:

((164, 0), (55, 0))

So, of course when I try to train my model:

from sklearn.svm import SVC
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train, y_train)

it gives me this error:

ValueError: Found array with 0 feature(s) (shape=(164, 0)) while a minimum of 1 is required.

I'm new to machine learning especially feature selection bit. If anyone can tell me how to develope models with the selected features in this particular case, I would greatly appreciate it.


问:
Updating and restarting the current running Windows Service in C#
I have a .NET 6 application compiled as a standalone executable that runs as a Windows service. What I want to add is a way to update and restart the service when it detects that a new version is available. The problem is that I can't find a way to actually restart a service with a single command in a way that can be triggered from C#.

The sc.exe can be used to create, modify, start and stop a service. But it does not have a restart command. My original plan was to modify the service and point it to the new binary, and then restart it using sc.exe, but then I noticed that it doesn't actually have a real restart command.

The Powershell cmdlet Restart-Service does what I want, but the C# Powershell integration seems to have some severe issues and bugs when the C# application is compiled as a standalone executable. It simply does not work at all for me.

I'm triggering the update from the running Windows service itself, so I can't just execute a stop command and then try to execute the start command, as my application won't be running anymore at that point.

One option might be to execute both sc.exe stop and sc.exe start in a way that isn't interrupted when the calling process is stopped, but I'm not sure which method would work reliably here. Another idea would be to slightly misuse the auto-restart on failure mechanism for Windows services. But I'm not sure I can trigger that without creating superfluous error messages in the Windows Event logs.

What options do I have to reliably restart a running Windows service from the running C# application itself?


问:
How to edit request parameters received by post in SpringBoot in a handler method
In a SpringBoot controller, is there a way to edit request parameters received in post in a handler method and forward them to another handler method?

sample.html

```<code><form id="sample" method="post" th:action="@{/methodA}">
     <input type="submit" name="dummykey" value="param_A" class="button" form="sample" />
</form>
</code>```

Controller

```<code>// Handler Method A
@RequestMapping(value = "/methodA", params = "dummykey=param_A")
  public String methodA(){
  /* edit RequestParameter: dummykey = param_B */
  return "forward:/methodB";
}

// Handler Method B
@RequestMapping(value = "/methodB", params = "dummykey=param_B")
  public String methodB(){
    ...
  }
</code>```

Body:
In a SpringBoot controller, is there a way to edit request parameters received in post in a handler method and forward them to another handler method?

sample.html

<form id="sample" method="post" th:action="@{/methodA}">
     <input type="submit" name="dummykey" value="param_A" class="button" form="sample" />
</form>

Controller

// Handler Method A
@RequestMapping(value = "/methodA", params = "dummykey=param_A")
  public String methodA(){
  /* edit RequestParameter: dummykey = param_B */
  return "forward:/methodB";
}

// Handler Method B
@RequestMapping(value = "/methodB", params = "dummykey=param_B")
  public String methodB(){
    ...
  }


问:
Change QWidget color by changing SpinBox values
I'm making a color picker.

I have a ui file and I have loaded the ui file with uic.loadUi.

And I have a QWidget with a QWidget called QW3 and several SpinBoxes.
I want to change the color of QW3 by putting values in SpinBoxes.
The names of SpinBoxes are R_value, G_value, and B_value.
So, I connected the SpinBoxes to a function like this:

```<code>self.layout.R_value.valueChanged.connect(self.Rchange)
self.layout.G_value.valueChanged.connect(self.Gchange)
self.layout.B_value.valueChanged.connect(self.Bchange)
</code>```

And then, I don't know how to change the color of QWidget.

Body:
I'm making a color picker.

I have a ui file and I have loaded the ui file with uic.loadUi.

And I have a QWidget with a QWidget called QW3 and several SpinBoxes.
I want to change the color of QW3 by putting values in SpinBoxes.
The names of SpinBoxes are R_value, G_value, and B_value.
So, I connected the SpinBoxes to a function like this:

self.layout.R_value.valueChanged.connect(self.Rchange)
self.layout.G_value.valueChanged.connect(self.Gchange)
self.layout.B_value.valueChanged.connect(self.Bchange)

And then, I don't know how to change the color of QWidget.


问:
What are the networking requirements for reverse proxy tunneling on a self hosted vscode-server instance?
I recently moved over from coder/code-server to microsoft's implementation of a code server. Included in this is the ability to set up tunnels to the remote host, however i can't seem to get it to work. I'm using nginx to forward to the code-server service as a reverse proxy which works just fine for the most part. Since the documentation doesn't include a list of networking requirements for hosting a code-server i'd like to know if there are any ports that should be open and forwarded or any additional configuration?

I've configured nginx to forward all requests to the code-server instance, but this isn't enough to get tunnels working. I can connect to it through the domain i'm listening for.


问:
Qt 6 NetworkAccessManager error "Host requires Authentication" what can cause this error?
Everytime i make a POST request it tells me that "host requires authentication" but the API
I am trying to use is a public api in laravel. GET requests are working fine and the POST request is also working fine in postman. can anyone point out my mistake?

```<code>#include "base_request.h"

BaseRequest::BaseRequest(QObject *parent) : QObject(parent)
{
    this->networkManager = new QNetworkAccessManager(this);
    connect(this->networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleFinished(QNetworkReply*)));
    // set HTTP headers
    headers["User-Agent"] = "RequestManager 1.0";
    headers["Accept"] = "application/json";
    headers["Content-Type"] = "application/x-www-form-urlencoded";
    headers["Content-Length"] = 0;
}

void BaseRequest::HEAD(const QString hostName)

    QNetworkRequest request = this->constructNetworkRequest(hostName, this->headers);
    this->networkManager->head(request);
}

void BaseRequest::POST(const QString hostName, QMap<QString, QString> data)
{

    const QString link = BASE_URL + hostName;
    QNetworkRequest request = this->constructNetworkRequest(link, this->headers);
    QUrlQuery postData = this->constructPostData(data);
    this->networkManager->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
}

void BaseRequest::handleFinished(QNetworkReply *networkReply)
{
    networkReply->deleteLater();

    if (networkReply->error() == QNetworkReply::NoError)
    {
        qint32 httpStatusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        // 200
        if (httpStatusCode >= 200 && httpStatusCode < 300) // OK
        {
            emit this->sendSignal(networkReply->readAll());
        }
        else if (httpStatusCode >= 300 && httpStatusCode < 400) // 300 Redirect
        {
            QUrl relativeUrl = networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();

            QUrl redirectUrl = networkReply->url().resolved(relativeUrl);

            networkReply->manager()->get(QNetworkRequest(redirectUrl));

            return;
        }
        else if (httpStatusCode >= 400 && httpStatusCode < 500) // 400 Error
        {
            qDebug() << httpStatusCode << " Error!";
        }
        else if (httpStatusCode >= 500 && httpStatusCode < 600) // 500 Internal Server Error
        {
            qDebug() << httpStatusCode << " Error!";
        }
        else
        {
            qDebug() << "Status code invalid! " << httpStatusCode;
        }
    }
    else
    {
        qDebug() << "errorString: " << networkReply->errorString();
    }

    networkReply->manager()->deleteLater();
}

QUrlQuery BaseRequest::constructPostData(QMap<QString, QString> data)
{
    QUrlQuery postData;
    QMapIterator<QString, QString> iterator(data);

    while (iterator.hasNext()) {
        iterator.next();
        postData.addQueryItem(iterator.key(), iterator.value());
    }
    return postData;
}

QNetworkRequest BaseRequest::constructNetworkRequest(const QString hostName, QMap<QString, QString> headers)
{
    QNetworkRequest request;
    request.setUrl(QUrl(hostName));

    if (!headers.isEmpty()) {
        QMapIterator<QString, QString> iterator(headers);
        while (iterator.hasNext()) {
            iterator.next();
            request.setRawHeader(QByteArray::fromStdString(iterator.key().toStdString()), QByteArray::fromStdString(iterator.value().toStdString()));
        }
    }

    return request;
}
</code>```

main.cpp

```<code>int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    RequestManager manager(&a);
    QMap <QString, QString> data;
    QString hostName = "http://127.0.0.1:8000/api/login";
    data["name"] = "admin";
    data["password"] = "123";

    manager.POST(hostName, data);

    return a.exec();
}

</code>```

I tried using all HTTP methods on postman and all of it are working as expected.

Body:
Everytime i make a POST request it tells me that "host requires authentication" but the API
I am trying to use is a public api in laravel. GET requests are working fine and the POST request is also working fine in postman. can anyone point out my mistake?

#include "base_request.h"

BaseRequest::BaseRequest(QObject *parent) : QObject(parent)
{
    this->networkManager = new QNetworkAccessManager(this);
    connect(this->networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleFinished(QNetworkReply*)));
    // set HTTP headers
    headers["User-Agent"] = "RequestManager 1.0";
    headers["Accept"] = "application/json";
    headers["Content-Type"] = "application/x-www-form-urlencoded";
    headers["Content-Length"] = 0;
}

void BaseRequest::HEAD(const QString hostName)

    QNetworkRequest request = this->constructNetworkRequest(hostName, this->headers);
    this->networkManager->head(request);
}

void BaseRequest::POST(const QString hostName, QMap<QString, QString> data)
{

    const QString link = BASE_URL + hostName;
    QNetworkRequest request = this->constructNetworkRequest(link, this->headers);
    QUrlQuery postData = this->constructPostData(data);
    this->networkManager->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
}

void BaseRequest::handleFinished(QNetworkReply *networkReply)
{
    networkReply->deleteLater();

    if (networkReply->error() == QNetworkReply::NoError)
    {
        qint32 httpStatusCode = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        // 200
        if (httpStatusCode >= 200 && httpStatusCode < 300) // OK
        {
            emit this->sendSignal(networkReply->readAll());
        }
        else if (httpStatusCode >= 300 && httpStatusCode < 400) // 300 Redirect
        {
            QUrl relativeUrl = networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();

            QUrl redirectUrl = networkReply->url().resolved(relativeUrl);

            networkReply->manager()->get(QNetworkRequest(redirectUrl));

            return;
        }
        else if (httpStatusCode >= 400 && httpStatusCode < 500) // 400 Error
        {
            qDebug() << httpStatusCode << " Error!";
        }
        else if (httpStatusCode >= 500 && httpStatusCode < 600) // 500 Internal Server Error
        {
            qDebug() << httpStatusCode << " Error!";
        }
        else
        {
            qDebug() << "Status code invalid! " << httpStatusCode;
        }
    }
    else
    {
        qDebug() << "errorString: " << networkReply->errorString();
    }

    networkReply->manager()->deleteLater();
}

QUrlQuery BaseRequest::constructPostData(QMap<QString, QString> data)
{
    QUrlQuery postData;
    QMapIterator<QString, QString> iterator(data);

    while (iterator.hasNext()) {
        iterator.next();
        postData.addQueryItem(iterator.key(), iterator.value());
    }
    return postData;
}

QNetworkRequest BaseRequest::constructNetworkRequest(const QString hostName, QMap<QString, QString> headers)
{
    QNetworkRequest request;
    request.setUrl(QUrl(hostName));

    if (!headers.isEmpty()) {
        QMapIterator<QString, QString> iterator(headers);
        while (iterator.hasNext()) {
            iterator.next();
            request.setRawHeader(QByteArray::fromStdString(iterator.key().toStdString()), QByteArray::fromStdString(iterator.value().toStdString()));
        }
    }

    return request;
}

main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    RequestManager manager(&a);
    QMap <QString, QString> data;
    QString hostName = "http://127.0.0.1:8000/api/login";
    data["name"] = "admin";
    data["password"] = "123";

    manager.POST(hostName, data);

    return a.exec();
}

I tried using all HTTP methods on postman and all of it are working as expected.


问:
how can i stop memory leaks in rust FFI?
I'm trying to create some bindings from a C library for rust with bindgen and everything was going well until I realized that my program was having memory leak problems

Thanks to heaptrack I was able to identify the function that was causing these memory leaks,

this function CP56Time2a_createFromMsTimestamp creates a timestamp to then be added to another structure (InformationObject) before being sent, when this structure is sent a method is called that frees the memory of the structure (InformationObject_destroy) and I guess also the memory of the timestamp, in the library there is no method to free the memory of the timestamp

How can I deallocate or free this memory? The resulting structure of the function is a pointer *mut sCP56Time2a

minimal example of what I'm doing:

use iec60870::bindings;
use std::ffi::CString;

pub struct CP56Time2a;

impl CP56Time2a {
    pub fn create() -> *mut bindings::sCP56Time2a {
        unsafe {
            bindings::CP56Time2a_createFromMsTimestamp(
                std::ptr::null_mut(),
                bindings::Hal_getTimeInMs(),
            )
        }
    }
}

pub struct Slave {
    inner: bindings::CS104_Slave,
}

impl Slave {
    pub fn new(addr: &str, port: i32) -> Self {
        let inner = unsafe {
            let inner = bindings::CS104_Slave_create(100, 100);
            let address = CString::new(addr).unwrap().as_c_str().to_owned();
            bindings::CS104_Slave_setLocalAddress(inner, address.as_ptr());
            bindings::CS104_Slave_setLocalPort(inner, port);
            bindings::CS104_Slave_setServerMode(inner, 1);

            inner
        };

        Self { inner }
    }
}

fn main() {
    unsafe {
        let slave = Slave::new("127.0.0.1", 2404);
        let param = bindings::CS104_Slave_getAppLayerParameters(slave.inner);

        let asdu = bindings::CS101_ASDU_create(param, false, 3, 0, 1, false, false);
        let timestamp = CP56Time2a::create();

        let me = bindings::MeasuredValueScaledWithCP56Time2a_create(
            std::ptr::null_mut(),
            1000,
            20,
            0,
            timestamp,
        );

        bindings::CS101_ASDU_addInformationObject(asdu, me as bindings::InformationObject);
        // send asdu
        bindings::InformationObject_destroy(me as bindings::InformationObject);
        bindings::CS101_ASDU_destroy(asdu);
    }
}
```


问:
Why does OpenCV.js Mat.roi return sequential data instead of rectangular submat?
I'm using Opencv.js (specifically npm package opencv-bindings)

I'm trying to get a roi from a mat, but the method seems return wrong output.

I define a simple 3x3 array filled with numbers 1..9

Then I create ROI that starts at 1,1 and is of 2x2 size.

The output I'm getting is as if the function started at 1,1 and returned 4 numbers sequentially from the starting point, wrapping to the next row.

I would expect to get

1 2 3

4 5 6

7 8 9

But I get

1 2 3

4 5 6

7 8 9

What am I doing wrong?

Working repro:
https://codesandbox.io/s/opencv-js-getting-started-with-images-adapted-forked-exqsxo?file=/src/index.js

Code:

```<code>const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const numMat = new cv.matFromArray(3, 3, cv.CV_8UC1, data);
console.log(numMat.data, numMat.cols, numMat.rows);
// 1 2 3
// 4 5 6
// 7 8 9

const numRoi = numMat.roi(new cv.Rect(1, 1, 2, 2));
console.log(numRoi.data, numRoi.cols, numRoi.rows);
// expect:
// 5 6
// 8 9

// get:
// 5 6
// 7 8
</code>```

Body:
I'm using Opencv.js (specifically npm package opencv-bindings)

I'm trying to get a roi from a mat, but the method seems return wrong output.

I define a simple 3x3 array filled with numbers 1..9

Then I create ROI that starts at 1,1 and is of 2x2 size.

The output I'm getting is as if the function started at 1,1 and returned 4 numbers sequentially from the starting point, wrapping to the next row.

I would expect to get

1 2 3

4 5 6

7 8 9

But I get

1 2 3

4 5 6

7 8 9

What am I doing wrong?

Working repro:
https://codesandbox.io/s/opencv-js-getting-started-with-images-adapted-forked-exqsxo?file=/src/index.js

Code:

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const numMat = new cv.matFromArray(3, 3, cv.CV_8UC1, data);
console.log(numMat.data, numMat.cols, numMat.rows);
// 1 2 3
// 4 5 6
// 7 8 9

const numRoi = numMat.roi(new cv.Rect(1, 1, 2, 2));
console.log(numRoi.data, numRoi.cols, numRoi.rows);
// expect:
// 5 6
// 8 9

// get:
// 5 6
// 7 8


问:
AWS Amplify I want to redirect all directories to a specific location
When I am performing maintenance, I want to redirect all connections to the maintenance page.
However, I do not know how to do that.

Here is my redirect information

```<code>[
    {
        "source": "https://example.com",
        "target": "https://www.example.com",
        "status": "301",
        "condition": null
    }
    {
        "source": "https://www.example.com",
        "target": "https://www.example.com/maintenance",
        "status": "302",
        "condition": null
    }
    {
        "source": "/<*>",
        "target": "https://www.example.com/maintenance",
        "status": "404-200",
        "condition": null
    },
]
</code>```

However, this method will cause the redirect to loop.

Body:
When I am performing maintenance, I want to redirect all connections to the maintenance page.
However, I do not know how to do that.

Here is my redirect information

[
    {
        "source": "https://example.com",
        "target": "https://www.example.com",
        "status": "301",
        "condition": null
    }
    {
        "source": "https://www.example.com",
        "target": "https://www.example.com/maintenance",
        "status": "302",
        "condition": null
    }
    {
        "source": "/<*>",
        "target": "https://www.example.com/maintenance",
        "status": "404-200",
        "condition": null
    },
]

However, this method will cause the redirect to loop.


问:
EAP 7.4.8 jboss-client.jar throws NoClassDefFoundError
```<code>Exception in thread "Thread-3" java.lang.NoClassDefFoundError: org/jboss/modules/ModuleLoadException
        at org.jboss.ejb.client.EJBClientContext.getDefault(EJBClientContext.java:110)
        at org.wildfly.common.context.ContextManager.getPrivileged(ContextManager.java:286)
        at org.jboss.ejb.client.EJBClientContext.getCurrent(EJBClientContext.java:861)
        at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:165)
        at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:116)
        at com.sun.proxy.$Proxy2.sendResponse(Unknown Source)
        at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.ClassNotFoundException: org.jboss.modules.ModuleLoadException
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 9 more
</code>```

Hello, after updating the Jboss to newer version, it started to throw above error. obviously it cannot find jboss-client.jar but i do not understand why?  any hint will be much appreciated.

Thanks in advance

Body:
Exception in thread "Thread-3" java.lang.NoClassDefFoundError: org/jboss/modules/ModuleLoadException
        at org.jboss.ejb.client.EJBClientContext.getDefault(EJBClientContext.java:110)
        at org.wildfly.common.context.ContextManager.getPrivileged(ContextManager.java:286)
        at org.jboss.ejb.client.EJBClientContext.getCurrent(EJBClientContext.java:861)
        at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:165)
        at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:116)
        at com.sun.proxy.$Proxy2.sendResponse(Unknown Source)
        at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.ClassNotFoundException: org.jboss.modules.ModuleLoadException
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 9 more

Hello, after updating the Jboss to newer version, it started to throw above error. obviously it cannot find jboss-client.jar but i do not understand why?  any hint will be much appreciated.

Thanks in advance