问:
.filter defaulting to remove last array value instead of indexed value
Im wokring on code that was written by another dev and struggling to understand whats going on here so forgive me if I don't do a good job of explaining all that's going on.

I have this state that controls elements in a form and how they're displayed and an onRemove handle that removed the formik value that's stored in an object and a .filter that's supposed to filter the indexed element out of the state array. However when the remove handle is fired it correctly removed the formik value (had to do it manually since it appeared to not be doing it with how it was set up) and the filter removed the last value in the array. You can imagine the problems this causes when removing and reading an element with formik values stored to specific indexes being readded to fields that are supposed to be new.

This .filter was written by another dev so it may be set up wrong to being with and im not totally sure if this is a proper way to handle this with react but this is the initial state:

```<code>const [elements, setElements] = useState(() => {
    let eleArr = []
    item.questions.map((e, i) => {
      const key = Date.now() + i
      if (e.type === "checkbox" || e.type === "radio") {
        let optArr = []
        e.options.map((option, j) => {
          const oKey = Date.now() + i + j
          optArr.push({ value: "item", key: oKey })
        })
        eleArr.push({
          type: e.type,
          options: optArr,
          key: key
        })
      } else if (e.type === "content") {
        eleArr.push({
          type: e.type,
          options: [e.title],
          key: key
        })
      } else if (e.type === "rating"){
        eleArr.push({
          type: e.type,
          descHigh: e.descHigh,
          descLow: e.descLow,
          scaleDesc: e.scaleDesc,
          options: [],
          key: key
        })
      } else {
        eleArr.push({
          type: e.type,
          options: [],
          key: key
        })
      }
    })
    return eleArr
  })
</code>```

And this is the remove handle:

```<code>const handleRemove = (index, element) =>
{
console.log(index);
console.log(elements);
setElements(elements => elements.filter((e, i) => i !== index))

//remove formik value manually
}
</code>```

I can provide more code if need be but im really at a loss for why this wont work since the indexes and values are set up how they are supposed to. Any help is appreciated

Generate elements:

```<code>
{elements.map((e, i) => {

                if (e.type === "text" || e.type === "textarea" || e.type === "rating") {
                  return (
                    <AssessmentContent1 key={e.key} item={e} index={i} removeItem={() => handleRemove(i)} formik={formik} />
                  )
                } else if (e.type === "content") {
                  return (
                    <AssessmentContent3 key={e.key} item={e} addContent={(e) => addContent(e, i)} removeItem={() => handleRemove(i)} />
                  )
                } else {
                  return (
                    <AssessmentContent2 key={e.key} item={e} index={i} formik={formik} removeItem={() => handleRemove(i)} addSubItem={() => handleAddSubItem(i)} removeSubitem={(j) => handleRemoveSubItem(i, j)} />
                  )
                }
              }
              )}
</code>```

Remove button:

```<code><Grid item xs={1} sm={0.5} align="right">
        <RemoveIcon onClick={removeItem} style={{ background: "#E85E40", borderRadius: "50%", fill: "white", marginTop: "30px", cursor: "pointer" }} />
      </Grid>
</code>```

Basically remoteItem gets called which is tied to the handleRemove function and gets I passed to it inside of when the mapping occurs to initially generate the form

The if else jungle is mostly confusing because there's option fields which are stored within individual elements inside the element state so basically a map within a map. I could see that maybe causing problems but I wouldn't know where to begin to track down the problem if that's causing issues. Honestly, it seems like the code checks out when I look through all of it so I'm wondering if it may be some improper use of useState

Ive attempted different methods of removing specific items from the elements state and none of which work properly so any help would be appreciated

Body:
Im wokring on code that was written by another dev and struggling to understand whats going on here so forgive me if I don't do a good job of explaining all that's going on.

I have this state that controls elements in a form and how they're displayed and an onRemove handle that removed the formik value that's stored in an object and a .filter that's supposed to filter the indexed element out of the state array. However when the remove handle is fired it correctly removed the formik value (had to do it manually since it appeared to not be doing it with how it was set up) and the filter removed the last value in the array. You can imagine the problems this causes when removing and reading an element with formik values stored to specific indexes being readded to fields that are supposed to be new.

This .filter was written by another dev so it may be set up wrong to being with and im not totally sure if this is a proper way to handle this with react but this is the initial state:

const [elements, setElements] = useState(() => {
    let eleArr = []
    item.questions.map((e, i) => {
      const key = Date.now() + i
      if (e.type === "checkbox" || e.type === "radio") {
        let optArr = []
        e.options.map((option, j) => {
          const oKey = Date.now() + i + j
          optArr.push({ value: "item", key: oKey })
        })
        eleArr.push({
          type: e.type,
          options: optArr,
          key: key
        })
      } else if (e.type === "content") {
        eleArr.push({
          type: e.type,
          options: [e.title],
          key: key
        })
      } else if (e.type === "rating"){
        eleArr.push({
          type: e.type,
          descHigh: e.descHigh,
          descLow: e.descLow,
          scaleDesc: e.scaleDesc,
          options: [],
          key: key
        })
      } else {
        eleArr.push({
          type: e.type,
          options: [],
          key: key
        })
      }
    })
    return eleArr
  })

And this is the remove handle:

const handleRemove = (index, element) =>
{
console.log(index);
console.log(elements);
setElements(elements => elements.filter((e, i) => i !== index))

//remove formik value manually
}

I can provide more code if need be but im really at a loss for why this wont work since the indexes and values are set up how they are supposed to. Any help is appreciated

Generate elements:

{elements.map((e, i) => {

                if (e.type === "text" || e.type === "textarea" || e.type === "rating") {
                  return (
                    <AssessmentContent1 key={e.key} item={e} index={i} removeItem={() => handleRemove(i)} formik={formik} />
                  )
                } else if (e.type === "content") {
                  return (
                    <AssessmentContent3 key={e.key} item={e} addContent={(e) => addContent(e, i)} removeItem={() => handleRemove(i)} />
                  )
                } else {
                  return (
                    <AssessmentContent2 key={e.key} item={e} index={i} formik={formik} removeItem={() => handleRemove(i)} addSubItem={() => handleAddSubItem(i)} removeSubitem={(j) => handleRemoveSubItem(i, j)} />
                  )
                }
              }
              )}

Remove button:

<Grid item xs={1} sm={0.5} align="right">
        <RemoveIcon onClick={removeItem} style={{ background: "#E85E40", borderRadius: "50%", fill: "white", marginTop: "30px", cursor: "pointer" }} />
      </Grid>

Basically remoteItem gets called which is tied to the handleRemove function and gets I passed to it inside of when the mapping occurs to initially generate the form

The if else jungle is mostly confusing because there's option fields which are stored within individual elements inside the element state so basically a map within a map. I could see that maybe causing problems but I wouldn't know where to begin to track down the problem if that's causing issues. Honestly, it seems like the code checks out when I look through all of it so I'm wondering if it may be some improper use of useState

Ive attempted different methods of removing specific items from the elements state and none of which work properly so any help would be appreciated


来源: stackexchange

问:
How to resolve : AttributeError: 'SentenceTransformer' object has no attribute 'transform'
I have a code that is supposed to do these things:

Load already trained model
Load an unseen dataset
Create a pipeline which takes Bert encoder (SentenceTransformer('all-mpnet-base-v2')) and my trained model.
Then randomly choose a row from dataset, encode it, and predict it
Then ask if the prediction is correct. If not, then ask for the correct prediction and retrain the model with the right prediction

I am using this code:

```<code>import random
import numpy as np
from sentence_transformers import SentenceTransformer, models

# Load the trained model
multi_model = joblib.load(filename)

# Load the dataset

# Create a pipeline using the SentenceTransformer and the trained model
bert_model = SentenceTransformer('all-mpnet-base-v2')
pipeline = Pipeline([('encoder', bert_model), ('classifier', multi_model)])

# Choose a random row from the dataset
random_row = full_df.sample(1)
X = random_row[['mmgid', 'body','preprocessedBody']]  # select specific columns
article = np.random.choice(X['preprocessedBody'])
print("working")
# Encode the article and make a prediction
encoded_text = bert_model.encode([article])
print("working")

prediction = pipeline.predict([encoded_text])[0]
print("working")

print(X['mmgid'])
print(X['body'])
print(f"Prediction: {prediction}")

# Ask the user if the prediction is correct
response = input("Is this prediction correct? (yes/no)")

# If the prediction is incorrect, ask the user for the correct classification
if response.lower() == 'no':
    correct_classification = input("What is the correct classification for this article?")

    # Retrain the model using the original article and the correct classification
    pipeline.fit([(encoded_text)[0]], [correct_classification])

    # Test the updated model by classifying the same article again
    updated_prediction = pipeline.predict([encoded_text[0]])

    # Display the new prediction to the user
    print(f"The updated model predicts that this article belongs to the '{updated_prediction}' category.")
</code>```

However, I am getting this error:

```<code>AttributeError: 'SentenceTransformer' object has no attribute 'transform'
</code>```

How can I resolve it?

ContentLicense: CC BY-SA 4.0

Body:
I have a code that is supposed to do these things:

Load already trained model
Load an unseen dataset
Create a pipeline which takes Bert encoder (SentenceTransformer('all-mpnet-base-v2')) and my trained model.
Then randomly choose a row from dataset, encode it, and predict it
Then ask if the prediction is correct. If not, then ask for the correct prediction and retrain the model with the right prediction

I am using this code:

import random
import numpy as np
from sentence_transformers import SentenceTransformer, models

# Load the trained model
multi_model = joblib.load(filename)

# Load the dataset

# Create a pipeline using the SentenceTransformer and the trained model
bert_model = SentenceTransformer('all-mpnet-base-v2')
pipeline = Pipeline([('encoder', bert_model), ('classifier', multi_model)])

# Choose a random row from the dataset
random_row = full_df.sample(1)
X = random_row[['mmgid', 'body','preprocessedBody']]  # select specific columns
article = np.random.choice(X['preprocessedBody'])
print("working")
# Encode the article and make a prediction
encoded_text = bert_model.encode([article])
print("working")

prediction = pipeline.predict([encoded_text])[0]
print("working")

print(X['mmgid'])
print(X['body'])
print(f"Prediction: {prediction}")

# Ask the user if the prediction is correct
response = input("Is this prediction correct? (yes/no)")

# If the prediction is incorrect, ask the user for the correct classification
if response.lower() == 'no':
    correct_classification = input("What is the correct classification for this article?")

    # Retrain the model using the original article and the correct classification
    pipeline.fit([(encoded_text)[0]], [correct_classification])

    # Test the updated model by classifying the same article again
    updated_prediction = pipeline.predict([encoded_text[0]])

    # Display the new prediction to the user
    print(f"The updated model predicts that this article belongs to the '{updated_prediction}' category.")

However, I am getting this error:

AttributeError: 'SentenceTransformer' object has no attribute 'transform'

How can I resolve it?


问:
Tail of List is always empty
I have a list of which i gotta extract Size items and that makes up the Group.
The remaining items in the list are the Persons_Rest.

My code is working perfectly fine so far, only that I have a empty tail in my Group, so the first variable.

I know it is, because the parameters of my accumulator method is [Head|Tail]. But I cant find out how to avoid the empty tail.

```<code>make_one_group(Group, All_Persons, Persons_rest, Size):-
    make_one_group_acc(Group, All_Persons, All_Persons, Persons_rest, 0, Size).

make_one_group_acc(Group, All_Persons, Persons_rest, Persons_rest, Size, Size).

make_one_group_acc([H_group|T_group], All_Persons, Persons_rest_acc, Persons_rest, Counter, Size) :-
    ReplaceCounter is Counter+1,
    make_one_group_acc(T_group, All_Persons, New_Persons_rest, Persons_rest, ReplaceCounter, Size),
    my_select(H_group, Persons_rest_acc, New_Persons_rest).

my_select(Elem, [Elem|T], T).

my_select(Elem, [H|T], [H|T2]) :-
    my_select(Elem, T, T2).

</code>```

Title: Tail of List is always empty

Body:
I have a list of which i gotta extract Size items and that makes up the Group.
The remaining items in the list are the Persons_Rest.

My code is working perfectly fine so far, only that I have a empty tail in my Group, so the first variable.

I know it is, because the parameters of my accumulator method is [Head|Tail]. But I cant find out how to avoid the empty tail.

make_one_group(Group, All_Persons, Persons_rest, Size):-
    make_one_group_acc(Group, All_Persons, All_Persons, Persons_rest, 0, Size).

make_one_group_acc(Group, All_Persons, Persons_rest, Persons_rest, Size, Size).

make_one_group_acc([H_group|T_group], All_Persons, Persons_rest_acc, Persons_rest, Counter, Size) :-
    ReplaceCounter is Counter+1,
    make_one_group_acc(T_group, All_Persons, New_Persons_rest, Persons_rest, ReplaceCounter, Size),
    my_select(H_group, Persons_rest_acc, New_Persons_rest).

my_select(Elem, [Elem|T], T).

my_select(Elem, [H|T], [H|T2]) :-
    my_select(Elem, T, T2).


问:
Django DJFile encoding
I'm trying to save .txt files with utf-8 text inside. There are sometimes emojis or chars like "ü","ä","ö", etc.

Opening the file like this:

```<code>with file.open(mode='rb') as f:
      print(f.readlines())
      newMessageObject.attachment = DJFile(f, name=file.name)
      sha256 = get_checksum(attachment, algorithm="SHA256")
      newMessageObject.media_sha256 = sha256
      newMessageObject.save()
      logger.debug(f"[FILE][{messageId}] Added file to database")
</code>```

Readlines is binary, but the file that is created with DJFile is not utf-8 encoded. How can I do that?

Title: Django DJFile encoding

Body:
I'm trying to save .txt files with utf-8 text inside. There are sometimes emojis or chars like "ü","ä","ö", etc.

Opening the file like this:

with file.open(mode='rb') as f:
      print(f.readlines())
      newMessageObject.attachment = DJFile(f, name=file.name)
      sha256 = get_checksum(attachment, algorithm="SHA256")
      newMessageObject.media_sha256 = sha256
      newMessageObject.save()
      logger.debug(f"[FILE][{messageId}] Added file to database")

Readlines is binary, but the file that is created with DJFile is not utf-8 encoded. How can I do that?


问:
Pulling a git submodule with private access from a Github action
I'm trying to pull a git submodule during my 'push' github action. The submodule is a private repository.

I've created a PAT with read-only access to my repositories. And I've added the contents of that PAT as a secret in the git repo (not the submodule).

This is my github action file:

```<code>name: Java CI

on: [ push ]

env:
  SUBMODULE_ACCESS: ${{ secrets.SUBMODULE_ACCESS }}

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Update submodules
        run: |
          git config --global url."https://${SUBMODULE_ACCESS}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
          git submodule update --init --recursive
      - name: Set up JDK 19
        uses: actions/setup-java@v2
        with:
          java-version: '19'
          distribution: 'adopt'
      - name: Cache local .m2
        uses: actions/cache@v2
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**.pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-maven-
      - name: Run lints and test with Maven
        run: mvn clean install -Dall
</code>```

When I run this, I see the following error:

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.

But that link just mentions PATs, which I think I've set up?

Body:
I'm trying to pull a git submodule during my 'push' github action. The submodule is a private repository.

I've created a PAT with read-only access to my repositories. And I've added the contents of that PAT as a secret in the git repo (not the submodule).

This is my github action file:

name: Java CI

on: [ push ]

env:
  SUBMODULE_ACCESS: ${{ secrets.SUBMODULE_ACCESS }}

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - name: Update submodules
        run: |
          git config --global url."https://${SUBMODULE_ACCESS}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
          git submodule update --init --recursive
      - name: Set up JDK 19
        uses: actions/setup-java@v2
        with:
          java-version: '19'
          distribution: 'adopt'
      - name: Cache local .m2
        uses: actions/cache@v2
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**.pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-maven-
      - name: Run lints and test with Maven
        run: mvn clean install -Dall

When I run this, I see the following error:

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.

But that link just mentions PATs, which I think I've set up?


问:
Trying to loop through different polygons, and find the points within those polygons
I have 2 datasets:

admin_area.shp - contains  polygon district data which has index, names, geometry
point_data.shp - contains point data which has index, lat, lon, geometry

I want to loop through each polygon within admin_area, then for each area identify if any of my points intersect with that polygon.

I've tried this:

```<code># initialise an instance of an rtree Index object
idx = Index()

# loop through each row in the district dataset and extract the geometry of each one
for id, district in admin_areas.iterrows():
    idx.insert(id, district.geometry.bounds)

    # loop through each row in the point dataset and load into the spatial index
    for id, point in point_data.iterrows():
        idx.insert(id, point.geometry.bounds)

    # get the polygon of each district
    polygon = admin_areas.geometry.iloc[0]

    # how many rows are we starting with?
    print(f"boundaries: {len(admin_areas.index)}")

    # get the indexes of points that intersect bounds of the admin_areas
    possible_matches_index = list(idx.intersection(polygon.bounds))

    # use those indexes to extract the possible matches from the GeoDataFrame
    possible_matches = point_data.iloc[possible_matches_index]

    # how many points intersect the area?
    print(f"Filtered points: {len(possible_matches.index)}")

    # then search the possible matches for precise matches using the slower but more precise method
    precise_matches = possible_matches.loc[possible_matches.within(polygon)]
    print(precise_matches.geometry)

    # how many points itersect the area now?
    print(f"precise points: {len(precise_matches.index)}")
</code>```

It's resulted in this:

```<code>boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9
</code>```
```<code>boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9
</code>```
```<code>boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9
</code>```

where it seems to be replicated for just one district, but i want it to go through each district. Does anyone know why? Thank you

Body:
I have 2 datasets:

admin_area.shp - contains  polygon district data which has index, names, geometry
point_data.shp - contains point data which has index, lat, lon, geometry

I want to loop through each polygon within admin_area, then for each area identify if any of my points intersect with that polygon.

I've tried this:

# initialise an instance of an rtree Index object
idx = Index()

# loop through each row in the district dataset and extract the geometry of each one
for id, district in admin_areas.iterrows():
    idx.insert(id, district.geometry.bounds)

    # loop through each row in the point dataset and load into the spatial index
    for id, point in point_data.iterrows():
        idx.insert(id, point.geometry.bounds)

    # get the polygon of each district
    polygon = admin_areas.geometry.iloc[0]

    # how many rows are we starting with?
    print(f"boundaries: {len(admin_areas.index)}")

    # get the indexes of points that intersect bounds of the admin_areas
    possible_matches_index = list(idx.intersection(polygon.bounds))

    # use those indexes to extract the possible matches from the GeoDataFrame
    possible_matches = point_data.iloc[possible_matches_index]

    # how many points intersect the area?
    print(f"Filtered points: {len(possible_matches.index)}")

    # then search the possible matches for precise matches using the slower but more precise method
    precise_matches = possible_matches.loc[possible_matches.within(polygon)]
    print(precise_matches.geometry)

    # how many points itersect the area now?
    print(f"precise points: {len(precise_matches.index)}")

It's resulted in this:

boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9

boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9

boundaries: 9
Filtered points: 111
647    POINT (371053.697 410002.844)
194    POINT (371053.697 410002.844)
21     POINT (371053.697 410002.844)
189    POINT (371053.697 410002.844)
640    POINT (371053.697 410002.844)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 110, dtype: geometry
precise points: 110
boundaries: 9
Filtered points: 222
188    POINT (371848.442 409174.713)
214    POINT (371848.442 409174.713)
245    POINT (371848.442 409174.713)
246    POINT (371848.442 409174.713)
252    POINT (371848.442 409174.713)

973    POINT (371848.442 409174.713)
982    POINT (371848.442 409174.713)
989    POINT (371848.442 409174.713)
990    POINT (371848.442 409174.713)
995    POINT (371848.442 409174.713)
Name: geometry, Length: 220, dtype: geometry
precise points: 220
boundaries: 9

where it seems to be replicated for just one district, but i want it to go through each district. Does anyone know why? Thank you


问:
How can I use Tailwind CSS Classes in the ngClass directive of Angular?
I am trying to add dynamic classes to an element in my Angular template based on some condition, and I would like to use the styles provided by tailwind CSS. However, I am not sure how to properly incorporate tailwind into the ngClass directive.

Here is an example of what I am trying to do:

HTML

```<code><div [ngClass]="getBorderType()">Hello World</div>
</code>```

TypeScript

```<code>getBorderColour(): string {
  const type = {
    Animal,
    Human,
    Doctor,
    Alien
  }[this.type];
  return `border-custom-${type}`;
}
</code>```

Since the class name provided in the run time, the purgeCss have splice the custom classes I have declared in tailwind.config.js.

Obviously, I can make it something like

```<code><div [ngClass]="{
    'border-custom-Animal': someCondition,
    'border-custom-Doctor': someCondition,
    'border-custom-Human': someCondition,
    ...
}">Hello World</div>
</code>```

But it is repetitive and harder to maintain. I would like to know if there's an elegant way to handle this?

Body:
I am trying to add dynamic classes to an element in my Angular template based on some condition, and I would like to use the styles provided by tailwind CSS. However, I am not sure how to properly incorporate tailwind into the ngClass directive.

Here is an example of what I am trying to do:

HTML

Hello World

TypeScript

getBorderColour(): string {
  const type = {
    Animal,
    Human,
    Doctor,
    Alien
  }[this.type];
  return `border-custom-${type}`;
}

Since the class name provided in the run time, the purgeCss have splice the custom classes I have declared in tailwind.config.js.

Obviously, I can make it something like

Hello World

But it is repetitive and harder to maintain. I would like to know if there's an elegant way to handle this?


问:
existing transform matrix: adjust/modify rotation and save adjusted matrix
(python, cv2, warpaffine)

I have an existing transform matrix that crops a face from a larger picture.

The transform matrix does an ok job aligning the face to be aligned upright, but sometimes I need to fine-tune the matrix for better alignment.

I would like to make manual adjustments (mostly fine-tune rotation), and save the revised matrix, but I'm not sure how to do this.

```<code>cropped_face = cv2.warpaffine(frame, transform_matrix, (512,512))

# example, I want to rotate the cropped face an additional 45 degrees, and save the adjusted_matrix
adjusted_matrix = ????

save_matrix(adjusted_matrix)

adjusted_face = cv2.warpaffine(frame, adjusted_matrix, (512,512))
</code>```

I tried adding the matrix produced from cv2.getRotationMatrix2D(center=center, angle=45, scale=1) to the original transform_matrix, but it returned something unexpected, cropped completely wrong.

Body:
(python, cv2, warpaffine)

I have an existing transform matrix that crops a face from a larger picture.

The transform matrix does an ok job aligning the face to be aligned upright, but sometimes I need to fine-tune the matrix for better alignment.

I would like to make manual adjustments (mostly fine-tune rotation), and save the revised matrix, but I'm not sure how to do this.

cropped_face = cv2.warpaffine(frame, transform_matrix, (512,512))

# example, I want to rotate the cropped face an additional 45 degrees, and save the adjusted_matrix
adjusted_matrix = ????

save_matrix(adjusted_matrix)

adjusted_face = cv2.warpaffine(frame, adjusted_matrix, (512,512))

I tried adding the matrix produced from cv2.getRotationMatrix2D(center=center, angle=45, scale=1) to the original transform_matrix, but it returned something unexpected, cropped completely wrong.


问:
How to make window and all its elements resizable
I have looked at QVBox and QHBox layouts as well as QGrid and QBox and I am attempting to have it so that it does not have restrictions so that I can set a button to any height or with a multiple of 2,5,10.

I am trying to have a window like so:

The only way I can think of is to maybe have a QGrid with each column and row 10pc thick or something like that and have 2,000 to 3,000 rows and columns, is there a better way to do this.


问:
It is possible to detect the maximum size a Flutter app can take on the screen?
I have a Flutter app and I need to detect whether the app is running on Full screen or not to check if Split view or Stage manager (IOS) is enabled and if the window gets resized.

The app will be used in a test situation where the user is not supposed to cheat, so the app must know if it takes up the whole screen.

The app detects if the metrics change with this function:

```<code>@override
  void didChangeMetrics() {
    sizeDidChange = true;
  }
</code>```

but the problem here is that you could enter the "test situation" with an app window that is already resized so that another app can fit on the screen.

I also get the current height and width by

```<code>double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
</code>```

but I need to compare it to the complete size of the screen to know if its in full screen or not.

I also know if the app has moved to the background or not with

```<code>@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        setState(() {
          inBackground = false;
        });
        break;
      case AppLifecycleState.inactive:
        setState(() {
          inBackground = true;
        });
        break;
      case AppLifecycleState.paused:
        setState(() {
          inBackground = true;
        });
        break;
      case AppLifecycleState.detached:
        setState(() {
          inBackground = true;
        });
        break;
    }
  }
</code>```

but that does not detect stage manager or slide over

Body:
I have a Flutter app and I need to detect whether the app is running on Full screen or not to check if Split view or Stage manager (IOS) is enabled and if the window gets resized.

The app will be used in a test situation where the user is not supposed to cheat, so the app must know if it takes up the whole screen.

The app detects if the metrics change with this function:

@override
  void didChangeMetrics() {
    sizeDidChange = true;
  }

but the problem here is that you could enter the "test situation" with an app window that is already resized so that another app can fit on the screen.

I also get the current height and width by

double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;

but I need to compare it to the complete size of the screen to know if its in full screen or not.

I also know if the app has moved to the background or not with

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        setState(() {
          inBackground = false;
        });
        break;
      case AppLifecycleState.inactive:
        setState(() {
          inBackground = true;
        });
        break;
      case AppLifecycleState.paused:
        setState(() {
          inBackground = true;
        });
        break;
      case AppLifecycleState.detached:
        setState(() {
          inBackground = true;
        });
        break;
    }
  }

but that does not detect stage manager or slide over


问:
Is there a way to return data with a string like the given query?
I'm coding a search function, with users having a username that you can find by searching. I can get users that completely match the string query, but I want to get all users whose username contains the query string I entered.
Here's what I have so far:

paths:
  /user:
    description: get and create users
    get:
      description: Get user
      parameters:
        # something here to get all users whose name includes the query
        - in: query
          name: studentname
          required: true
          schema:
            type: string
            example: Jeffery
      responses:
        200:
          description: Successful!
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/students'
```


问:
Calculating upper margin in Azure Anomaly Detector Service,
In Azure Anomaly Detector service, why is the upper boundary calculated as

```<code>upperBoundary = expectedValue + (100 - marginScale) * upperMargin
</code>```

any not

```<code>upperBoundary = expectedValue + upperMargin
</code>```

Body:
In Azure Anomaly Detector service, why is the upper boundary calculated as

upperBoundary = expectedValue + (100 - marginScale) * upperMargin

any not

upperBoundary = expectedValue + upperMargin


问:
tmux: (how) can I close a pane or window without closing the window selection tree or the containing terminal
Title says it:

open a terminal

Ctrl-b w

observe you can walk through open windows/panes through the selection tree

Now I can close the selected pane or window with Ctrl-b &/w, but it closes the whole terminal. What I want instead, is to close the window that is selected in the tree, but keep the tree and the containing terminal open. (Which means that (implicitly) I'd want tmux to close the selected window/pane but jump to the next one and update the view without actually closing the containing terminal window.)

How to achieve this?


问:
Android 13 New notification appears after old one notification clear
Android 13 New notification appears after old one notification clear. When first notification show then new notification received on onMessageReceived method but it will display if i have old notifiction cleared form notification bar. otherwise it will not showing on notification bar.

My FirebaseMessageingService class as below

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                //scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        sendRegistrationToServer(token);
    }

    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    private void sendNotification(String title,String messageBody) {
        int uniqueCode=Prefs.getUniqueCode(getApplicationContext());
        if(uniqueCode==1000){
            uniqueCode=0;
        }
        Log.d("uniqueCode",uniqueCode+"");
        Intent intent
                = new Intent(this, LoginActivity.class);
        // Assign channel ID
        String channel_id = "Default";

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent
                = PendingIntent.getActivity(
                this, uniqueCode, intent,
                PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
        Prefs.setUniqueCode(getApplicationContext(),uniqueCode+1);
        NotificationCompat.Builder builder
                = new NotificationCompat
                .Builder(getApplicationContext(),
                channel_id)
                .setSmallIcon(R.drawable.applogo)
                .setAutoCancel(true)
                .setVibrate(new long[]{1000, 1000, 1000,
                        1000, 1000})
                .setOnlyAlertOnce(true)
                .setContentIntent(pendingIntent);

            builder = builder.setContentTitle(title)
                    .setContentText(messageBody)
                    .setSmallIcon(R.drawable.applogo)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody));
        NotificationManager notificationManager
                = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT
                >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel
                    = new NotificationChannel(
                    channel_id, "Default channel",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(
                    notificationChannel);
        }

        notificationManager.notify(0, builder.build());

    }
}
</code>```

Body:
Android 13 New notification appears after old one notification clear. When first notification show then new notification received on onMessageReceived method but it will display if i have old notifiction cleared form notification bar. otherwise it will not showing on notification bar.

My FirebaseMessageingService class as below

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                //scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        sendRegistrationToServer(token);
    }

    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    private void sendNotification(String title,String messageBody) {
        int uniqueCode=Prefs.getUniqueCode(getApplicationContext());
        if(uniqueCode==1000){
            uniqueCode=0;
        }
        Log.d("uniqueCode",uniqueCode+"");
        Intent intent
                = new Intent(this, LoginActivity.class);
        // Assign channel ID
        String channel_id = "Default";

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent
                = PendingIntent.getActivity(
                this, uniqueCode, intent,
                PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
        Prefs.setUniqueCode(getApplicationContext(),uniqueCode+1);
        NotificationCompat.Builder builder
                = new NotificationCompat
                .Builder(getApplicationContext(),
                channel_id)
                .setSmallIcon(R.drawable.applogo)
                .setAutoCancel(true)
                .setVibrate(new long[]{1000, 1000, 1000,
                        1000, 1000})
                .setOnlyAlertOnce(true)
                .setContentIntent(pendingIntent);

            builder = builder.setContentTitle(title)
                    .setContentText(messageBody)
                    .setSmallIcon(R.drawable.applogo)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody));
        NotificationManager notificationManager
                = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT
                >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel
                    = new NotificationChannel(
                    channel_id, "Default channel",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(
                    notificationChannel);
        }

        notificationManager.notify(0, builder.build());

    }
}


问:
Stopping multithreading through selection or a specific job
It's been a week, and I still can't figure out how to stop a multithread using threading.event. But is there any way to stop multithreading using the selection function? I'd like to stop a specific function firstJob(), secondJob(), and thirdJob(). example I have the first job saved on dict, and I only want to stop this function.</p>
```<code>import threading
import time
threads = {}

def worker(number, event):
   new_event = event
   i = 0

while not new_event.is_set():
    """thread worker function"""
    print(f"{i}Worker: {number}\n" )
    i += 1
    time.sleep(2)

event = threading.Event()
events = [event for _ in range(5)]

for i in range(5):
   t = threading.Thread(target=worker , args=(i,event,))
   threads[i] = t
threads[1].start()
threads[3].start()
threads[4].start()

print(threads)
</code>```

Body:
It's been a week, and I still can't figure out how to stop a multithread using threading.event. But is there any way to stop multithreading using the selection function? I'd like to stop a specific function firstJob(), secondJob(), and thirdJob(). example I have the first job saved on dict, and I only want to stop this function.

import threading
import time
threads = {}

def worker(number, event):
   new_event = event
   i = 0

while not new_event.is_set():
    """thread worker function"""
    print(f"{i}Worker: {number}\n" )
    i += 1
    time.sleep(2)

event = threading.Event()
events = [event for _ in range(5)]

for i in range(5):
   t = threading.Thread(target=worker , args=(i,event,))
   threads[i] = t
threads[1].start()
threads[3].start()
threads[4].start()

print(threads)


问:
How do I assort scanned text From OCR Scanner into multiple rows? (Java in Android Studio)
I am making an app in which the user needs to scan the text on the bill then each item on the bill is assorted in a new row. Each row contains a CheckBox, TextView for the food name and another TextView for the price of the food. But I am a little bit stuck on implementing this feature. I don't know how to separate each food attribute into separate TextViews and each food item into a separate row. Any ideas?

This image shows and example of what I am talking about

I though a bout using a Entity Extractor but there isn't a processing algorithm for food names. That means if I went this route I would need to hardcode every single food, which isn't optimal.


问:
Raylib-rs error: method `resize` modifies its receiver in-place, what to do?
I'm trying to make a very simple game, using Raylib bindings for Rust. I'm new to Rust, but I've been learning it for a couple of months and already made several simple projects that work as intended.

In this case I got to the point where I need to apply textures, and first I'm loading the file into an Image struct, so I can do some stuff with it before passing it to GPU.

After loading, I want to resize the image to the desired resolution, and this is when I get this error message.

Here's the relevant code (two variants):

```<code>fn get_image (filename: &str) -> Image {
    Image::load_image(filename)
        .expect("Couldn't load image from file")
        .resize(256, 256)
}
</code>```

or

```<code>fn get_image (filename: &str) -> Image {
    let mut image = Image::load_image(filename)
        .expect("Couldn't load image from file");

    image.resize(256, 256)
}
</code>```

In both cases I get the same error message:

```<code>mismatched types

instead of the `()` output of method `resize`

object_rend.rs(9, 34): expected `raylib::prelude::Image` because of return type

method `resize` modifies its receiver in-place
</code>```

The problem here is the method "resize", without it, just loading, the function works. But I really want to pack at least resizing into it, and in any case, I will need to resize this image later.

The method source code is here.

I understand what the problem is: this function/method doesn't return anything, but isn't that how all methods work, they just modify the existing value. So how do I fix this?

There's hardly any information online about Raylib for Rust specifically. As far as I get from the source code, it's all just the original Raylib C functions, wrapped in Unsafe blocks. I guess, one solution would be to pick another Rust engine, like ggez, but I really like how Raylib works.

Body:
I'm trying to make a very simple game, using Raylib bindings for Rust. I'm new to Rust, but I've been learning it for a couple of months and already made several simple projects that work as intended.

In this case I got to the point where I need to apply textures, and first I'm loading the file into an Image struct, so I can do some stuff with it before passing it to GPU.

After loading, I want to resize the image to the desired resolution, and this is when I get this error message.

Here's the relevant code (two variants):

fn get_image (filename: &str) -> Image {
    Image::load_image(filename)
        .expect("Couldn't load image from file")
        .resize(256, 256)
}

or

fn get_image (filename: &str) -> Image {
    let mut image = Image::load_image(filename)
        .expect("Couldn't load image from file");

    image.resize(256, 256)
}

In both cases I get the same error message:

mismatched types

instead of the `()` output of method `resize`

object_rend.rs(9, 34): expected `raylib::prelude::Image` because of return type

method `resize` modifies its receiver in-place

The problem here is the method "resize", without it, just loading, the function works. But I really want to pack at least resizing into it, and in any case, I will need to resize this image later.

The method source code is here.

I understand what the problem is: this function/method doesn't return anything, but isn't that how all methods work, they just modify the existing value. So how do I fix this?

There's hardly any information online about Raylib for Rust specifically. As far as I get from the source code, it's all just the original Raylib C functions, wrapped in Unsafe blocks. I guess, one solution would be to pick another Rust engine, like ggez, but I really like how Raylib works.


问:
Custom Authorization in ASP.NET Core 6.0
I'm looking for some guidance on where/how best to implement custom Authorization logic in an Asp.Net Core 6.0 API app.

I have some very custom authorization logic to implement, including sometimes needing to get data needed to make authorization decisions from the DB.

All the reading I've done seems to be telling me I should either implement a custom subclass of AuthorizeAttribute or implement a custom policy.  The  overhead involved in understanding these two options and then comparing them seems ... significant.  And even then, anyone on my team who is going to work on authorization will need the same level of understanding.  This feels like a pretty big lift and ongoing tax for something that seems like it could be done pretty simply.

The simple solution I'm talking about is to simply make a function call to check authorization as the first line in the controller code and return 4xx. Something like this:

```<code>public class MyController : Controller {
    public string Edit() {
        if(!IsAuthorizedToEdit()) return 4xx response;
        //Continue with functional logic
    }
}
</code>```

My question is - what am I losing by taking this simple (also easily understandable and maintainable) approach ? What are the risks and what problems might I run into? I'm not overly experienced with Asp.net, so any guidance would be appreciated.

Body:
I'm looking for some guidance on where/how best to implement custom Authorization logic in an Asp.Net Core 6.0 API app.

I have some very custom authorization logic to implement, including sometimes needing to get data needed to make authorization decisions from the DB.

All the reading I've done seems to be telling me I should either implement a custom subclass of AuthorizeAttribute or implement a custom policy.  The  overhead involved in understanding these two options and then comparing them seems ... significant.  And even then, anyone on my team who is going to work on authorization will need the same level of understanding.  This feels like a pretty big lift and ongoing tax for something that seems like it could be done pretty simply.

The simple solution I'm talking about is to simply make a function call to check authorization as the first line in the controller code and return 4xx. Something like this:

public class MyController : Controller {
    public string Edit() {
        if(!IsAuthorizedToEdit()) return 4xx response;
        //Continue with functional logic
    }
}

My question is - what am I losing by taking this simple (also easily understandable and maintainable) approach ? What are the risks and what problems might I run into? I'm not overly experienced with Asp.net, so any guidance would be appreciated.


问:
Python ncurses program stops working when resizing command prompt to mininimum size
I'm currently facing a problem where my program seems to work fine when the windows cmd has a height of at least 3 rows. However when the cmd is resized smaller than that, ncurses stops updating the cmd dimensions (self.x, self.y) which breaks my program even when the cmd is resized to a 'normal' size afterwards.

If been having quite a bit of resizing problems with ncurses in Python besides this one. Is this a known problem or am I missing something here?

```<code>
    def run(self):
        self.update_screen()

        while True:
            c = self.stdscr.getch()

            if c == ord('q'):
                break
            elif c == curses.KEY_RESIZE:
                try:
                    self.resize()
                    self.update_screen()
                except Exception as e:
                    print(e)

    def resize(self):
        self.y, self.x = self.stdscr.getmaxyx()
        ... # Windows that will get resized based on the new y and x.
</code>```

I can't seem to find an answer on google that fixes this problem.

Pastebin: https://pastebin.com/F7aYnMBP

Body:
I'm currently facing a problem where my program seems to work fine when the windows cmd has a height of at least 3 rows. However when the cmd is resized smaller than that, ncurses stops updating the cmd dimensions (self.x, self.y) which breaks my program even when the cmd is resized to a 'normal' size afterwards.

If been having quite a bit of resizing problems with ncurses in Python besides this one. Is this a known problem or am I missing something here?

    def run(self):
        self.update_screen()

        while True:
            c = self.stdscr.getch()

            if c == ord('q'):
                break
            elif c == curses.KEY_RESIZE:
                try:
                    self.resize()
                    self.update_screen()
                except Exception as e:
                    print(e)

    def resize(self):
        self.y, self.x = self.stdscr.getmaxyx()
        ... # Windows that will get resized based on the new y and x.

I can't seem to find an answer on google that fixes this problem.

Pastebin: https://pastebin.com/F7aYnMBP


问:
Ignis Error: Failed to unmount temporary volume; Error: exit status 1
I am trying to run ignis clean in a repository. It asks for the super user password and then gives error: Failed to unmount temporary volume; Error: exit status 1

I have tried this command in a fresh terminal session and have also restarted Docker.

I want know if this is a harmless log or if not, how can I resolve it.

Thanks in advance.


问:
Powershell new-pssession works on each -hostname individually, but access denied when trying both at once
I have tested

```<code>New-PSSession -HostName server01 -UserName myname
</code>```

and

```<code>New-PSSession -HostName server02 -UserName myname
</code>```

and both commands prompt for the password and then connect to each server without issue.
However, when I attempt

```<code>New-PSSession -HostName server01,server02 -UserName myname
</code>```

the prompt returned is

```<code>Enter server01's password: Enter server02's password:
</code>```

and although it is the same for both machines, I am receiving an access denied error every time I enter the password.

I have tried entering the password twice, comma separated, and colon separated. I am trying to follow examples given in a book that uses the same format for the command - multiple hostnames, and the username parameter. The prompt for the first server's password appears, and before I can begin typing, the second server password prompt appears on the same line. I expected one password prompt, since both machines use the same username/password credentials. I am not attempting a double hop.

Body:
I have tested

New-PSSession -HostName server01 -UserName myname

and

New-PSSession -HostName server02 -UserName myname

and both commands prompt for the password and then connect to each server without issue.
However, when I attempt

New-PSSession -HostName server01,server02 -UserName myname

the prompt returned is

Enter server01's password: Enter server02's password:

and although it is the same for both machines, I am receiving an access denied error every time I enter the password.

I have tried entering the password twice, comma separated, and colon separated. I am trying to follow examples given in a book that uses the same format for the command - multiple hostnames, and the username parameter. The prompt for the first server's password appears, and before I can begin typing, the second server password prompt appears on the same line. I expected one password prompt, since both machines use the same username/password credentials. I am not attempting a double hop.


问:
Read a JSON file and extract a specific value when my app starts in Electron
I am building an app using Electron. When the app starts, I want to 1) read a JSON file named db.json, 2) extract the value of a property named "progress" in the JSON file, and then 3) use that value to construct the index.html page that will load into the main window. In other words, the value of "progress" (possible values: 0, 1, 2, 3, or 4) will determine which HTML elements are visible on the screen when the app starts. I need the code to do this.

I have tried calling a JavaScript function in the index.js using the [body onload()] event. No success. I am new to Electron, so I know there is more to it than that. I just can't figure out the code needed to connect the different processes.


问:
Skia - blur shader
I'm trying to port the code from this article https://www.pushing-pixels.org/2022/04/09/shader-based-render-effects-in-compose-desktop-with-skia.html

My goal is to just make a blur under the rectangle

But I'm stuck at this point, I just don't know how to do it in skiasharp

```<code>Canvas(
    modifier = Modifier.fillMaxSize(1.0f)
        .graphicsLayer(
            renderEffect = ImageFilter.makeRuntimeShader(
                runtimeShaderBuilder = compositeShaderBuilder,
                shaderNames = arrayOf("content", "blur"),
                inputs = arrayOf(
                    null, ImageFilter.makeBlur(
                        sigmaX = 20.0f,
                        sigmaY = 20.0f,
                        mode = FilterTileMode.DECAL
                    )
                )
            ).asComposeRenderEffect(),
        )
) {
... the circle drawing commands as before
}
</code>```

That's what I have now

```<code>var imageInfo = new SKImageInfo(800, 500);
var surface = SKSurface.Create(imageInfo);
var canvas = surface.Canvas;

var compositeSksl = @"
    uniform shader content;
    uniform shader blur;

    uniform vec4 rectangle;
    uniform float radius;

    // Simplified version of SDF (signed distance function) for a rounded box
    // from https://www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm
    float roundedRectangleSDF(vec2 position, vec2 box, float radius) {
        vec2 q = abs(position) - box + vec2(radius);
        return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - radius;
    }

    vec4 main(vec2 coord) {
        vec2 shiftRect = (rectangle.zw - rectangle.xy) / 2.0;
        vec2 shiftCoord = coord - rectangle.xy;
        float distanceToClosestEdge = roundedRectangleSDF(
            shiftCoord - shiftRect, shiftRect, radius);

        vec4 c = content.eval(coord);
        if (distanceToClosestEdge > 0.0) {
            // We're outside of the filtered area
            return c;
        }

        vec4 b = blur.eval(coord);
        return b;
    }
}";

canvas.DrawCircle(375, 125, 100, new() {
    IsAntialias = true,
    Shader = SKShader.CreateLinearGradient(
        new(450, 60),
        new(290, 190),
        new SKColor[] {new(0xFF7A26D9),  new(0xFFE444E1)},
        SKShaderTileMode.Clamp
    )
});
canvas.DrawCircle(100, 265, 55, new() {
    IsAntialias = true,
    Color = new(0xFFEA357C)
});
canvas.DrawCircle(205, 125, 25, new() {
    IsAntialias= true,
    Shader = SKShader.CreateLinearGradient(
        new(180, 125),
        new(230, 125),
        new SKColor[] { new(0xFFEA334C), new(0xFFEC6051) },
        SKShaderTileMode.Clamp
    )
});

using var effect = SKRuntimeEffect.Create(compositeSksl, out var errorText);
var children = new SKRuntimeEffectChildren(effect) { };

// create actual shader
using var shader = effect.ToShader(true, new SKRuntimeEffectUniforms(effect) {
    ["rectangle"] = new float[] { 85.0f, 110.0f, 405.0f, 290.0f },
    ["radius"] = 20.0f
}, children);
</code>```

I will be glad of any help

Title: Skia - blur shader

Body:
I'm trying to port the code from this article https://www.pushing-pixels.org/2022/04/09/shader-based-render-effects-in-compose-desktop-with-skia.html

My goal is to just make a blur under the rectangle

But I'm stuck at this point, I just don't know how to do it in skiasharp

Canvas(
    modifier = Modifier.fillMaxSize(1.0f)
        .graphicsLayer(
            renderEffect = ImageFilter.makeRuntimeShader(
                runtimeShaderBuilder = compositeShaderBuilder,
                shaderNames = arrayOf("content", "blur"),
                inputs = arrayOf(
                    null, ImageFilter.makeBlur(
                        sigmaX = 20.0f,
                        sigmaY = 20.0f,
                        mode = FilterTileMode.DECAL
                    )
                )
            ).asComposeRenderEffect(),
        )
) {
... the circle drawing commands as before
}

That's what I have now

var imageInfo = new SKImageInfo(800, 500);
var surface = SKSurface.Create(imageInfo);
var canvas = surface.Canvas;

var compositeSksl = @"
    uniform shader content;
    uniform shader blur;

    uniform vec4 rectangle;
    uniform float radius;

    // Simplified version of SDF (signed distance function) for a rounded box
    // from https://www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm
    float roundedRectangleSDF(vec2 position, vec2 box, float radius) {
        vec2 q = abs(position) - box + vec2(radius);
        return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - radius;
    }

    vec4 main(vec2 coord) {
        vec2 shiftRect = (rectangle.zw - rectangle.xy) / 2.0;
        vec2 shiftCoord = coord - rectangle.xy;
        float distanceToClosestEdge = roundedRectangleSDF(
            shiftCoord - shiftRect, shiftRect, radius);

        vec4 c = content.eval(coord);
        if (distanceToClosestEdge > 0.0) {
            // We're outside of the filtered area
            return c;
        }

        vec4 b = blur.eval(coord);
        return b;
    }
}";

canvas.DrawCircle(375, 125, 100, new() {
    IsAntialias = true,
    Shader = SKShader.CreateLinearGradient(
        new(450, 60),
        new(290, 190),
        new SKColor[] {new(0xFF7A26D9),  new(0xFFE444E1)},
        SKShaderTileMode.Clamp
    )
});
canvas.DrawCircle(100, 265, 55, new() {
    IsAntialias = true,
    Color = new(0xFFEA357C)
});
canvas.DrawCircle(205, 125, 25, new() {
    IsAntialias= true,
    Shader = SKShader.CreateLinearGradient(
        new(180, 125),
        new(230, 125),
        new SKColor[] { new(0xFFEA334C), new(0xFFEC6051) },
        SKShaderTileMode.Clamp
    )
});

using var effect = SKRuntimeEffect.Create(compositeSksl, out var errorText);
var children = new SKRuntimeEffectChildren(effect) { };

// create actual shader
using var shader = effect.ToShader(true, new SKRuntimeEffectUniforms(effect) {
    ["rectangle"] = new float[] { 85.0f, 110.0f, 405.0f, 290.0f },
    ["radius"] = 20.0f
}, children);

I will be glad of any help


问:
Typescript error on a JSON object returned from a database
```<code>interface IUser {
  id: number;
  name: string;
  username: string;
  city_of_birth: string;
}

function users({ users: IUser[] }) {
  return (
    <div>
      {users.map((user) => {
        return <div>{user.name}</div>;
      })}
    </div>
  );
}
</code>```

I'm getting the error on IUser[] -- Binding element 'IUser' implicitly has an 'any'

I don't understand. I've defined the container and have no idea what it wants at this point.

ANSWER:

```<code>interface IUser {
  id: number;
  name: string;
  username: string;
  city_of_birth: string;
}

const users = ({ users }: { users: IUser[] }) => {
  return (
    <div>
      {users.map((user) => {
        return <div>{user.name}</div>;
      })}
    </div>
  );
};
</code>```

Body:
interface IUser {
  id: number;
  name: string;
  username: string;
  city_of_birth: string;
}

function users({ users: IUser[] }) {
  return (

      {users.map((user) => {
        return
{user.name}
;
      })}

  );
}

I'm getting the error on IUser[] -- Binding element 'IUser' implicitly has an 'any'

I don't understand. I've defined the container and have no idea what it wants at this point.

ANSWER:

interface IUser {
  id: number;
  name: string;
  username: string;
  city_of_birth: string;
}

const users = ({ users }: { users: IUser[] }) => {
  return (

      {users.map((user) => {
        return
{user.name}
;
      })}

  );
};


问:
The `getServletNames()` method returns empty, how do I get the actual list/enumeration?
The getBeanDefinitionNames() method returns a list of beans. Similarly, I'm trying to get a list of Servlets.

Here is the code

```<code>@RestController
public class HomeController {
    @Autowired
    ServletContext context;

    @GetMapping
    int home(){
        Enumeration<String> servletNames = context.getServletNames();
        while (servletNames.hasMoreElements()) {
          String servletName = servletNames.nextElement();
            System.out.println(servletName);
        }
        return 200;
    }
}
</code>```

However, the above code gets me nothing, as the doc says

this method always returns an empty Enumeration

How do I get the actual list/enumeration?

Env: spring boot 2.7.7 + jdk 1.8.0_352

Body:
The getBeanDefinitionNames() method returns a list of beans. Similarly, I'm trying to get a list of Servlets.

Here is the code

@RestController
public class HomeController {
    @Autowired
    ServletContext context;

    @GetMapping
    int home(){
        Enumeration<String> servletNames = context.getServletNames();
        while (servletNames.hasMoreElements()) {
          String servletName = servletNames.nextElement();
            System.out.println(servletName);
        }
        return 200;
    }
}

However, the above code gets me nothing, as the doc says

this method always returns an empty Enumeration

How do I get the actual list/enumeration?

Env: spring boot 2.7.7 + jdk 1.8.0_352


问:
Pinescript automated bot
So I’ve coded a trading bot for trading view however when i try to use it i receive a compilation error.

Below is the code:

```<code>code
// This strategy will enter a long position if a bullish candlestick pattern is detected,
// and it will exit the position if a bearish candlestick pattern is detected.

// First, we will define the bullish and bearish candlestick patterns that we want to detect
bullish_patterns = [    "engulfing_bar",    "morning_star",    "hammer",    "harami",    "tweezer_bottom"]
bearish_patterns = [    "engulfing_bar",    "evening_star",    "shooting_star",    "harami",    "tweezer_top"]
neutral_patterns = [    "doji",    "dragonfly_doji",    "gravestone_doji"]

// Next, we will use the `security()` function to get the current bar's open, high, low, and close prices
open = security(tickerid, 'D', open)
high = security(tickerid, 'D', high)
low = security(tickerid, 'D', low)
close = security(tickerid, 'D', close)

// Now, we will use the `candlestick()` function to detect the candlestick patterns
is_bullish = candlestick(open, high, low, close, bullish_patterns)
is_bearish = candlestick(open, high, low, close, bearish_patterns)
is_neutral = candlestick(open, high, low, close, neutral_patterns)

// If a bullish candlestick pattern is detected, we will enter a long position
if is_bullish
    strategy.entry("Long", strategy.long)

// If a bearish candlestick pattern is detected, we will exit any open positions
if is_bearish
    strategy.close("Close")

// If a neutral candlestick pattern is detected, we will do nothing
if is_neutral
    strategy.close("Close")

</code>```

I hope this can benefit a lot of people once it’s ready.

i tried entering this on tradingview pinescript and it didn’t work.

Title: Pinescript automated bot

Body:
So I’ve coded a trading bot for trading view however when i try to use it i receive a compilation error.

Below is the code:

code
// This strategy will enter a long position if a bullish candlestick pattern is detected,
// and it will exit the position if a bearish candlestick pattern is detected.

// First, we will define the bullish and bearish candlestick patterns that we want to detect
bullish_patterns = [    "engulfing_bar",    "morning_star",    "hammer",    "harami",    "tweezer_bottom"]
bearish_patterns = [    "engulfing_bar",    "evening_star",    "shooting_star",    "harami",    "tweezer_top"]
neutral_patterns = [    "doji",    "dragonfly_doji",    "gravestone_doji"]

// Next, we will use the `security()` function to get the current bar's open, high, low, and close prices
open = security(tickerid, 'D', open)
high = security(tickerid, 'D', high)
low = security(tickerid, 'D', low)
close = security(tickerid, 'D', close)

// Now, we will use the `candlestick()` function to detect the candlestick patterns
is_bullish = candlestick(open, high, low, close, bullish_patterns)
is_bearish = candlestick(open, high, low, close, bearish_patterns)
is_neutral = candlestick(open, high, low, close, neutral_patterns)

// If a bullish candlestick pattern is detected, we will enter a long position
if is_bullish
    strategy.entry("Long", strategy.long)

// If a bearish candlestick pattern is detected, we will exit any open positions
if is_bearish
    strategy.close("Close")

// If a neutral candlestick pattern is detected, we will do nothing
if is_neutral
    strategy.close("Close")

I hope this can benefit a lot of people once it’s ready.

i tried entering this on tradingview pinescript and it didn’t work.


问:
Flask migrate error - Error: Directory migrations already exists and is not empty
I'm working on a flask application project and it incorporates usage of tools such as docker, adminer and redis.

I have a migration.py file that looks like this:

```<code>from flask import Flask
from configuration import Configuration
from flask_migrate import Migrate, init, migrate, upgrade
from models import database, Role, User, UserRole
from sqlalchemy_utils import database_exists, create_database, drop_database

application = Flask(__name__)
application.config.from_object(Configuration)

migrateObject = Migrate(application, database)

done = False

while not done:
try:
    if not database_exists(application.config['SQLALCHEMY_DATABASE_URI']):
        create_database(application.config['SQLALCHEMY_DATABASE_URI'])

    if database_exists(application.config["SQLALCHEMY_DATABASE_URI"]):
        drop_database(application.config["SQLALCHEMY_DATABASE_URI"])
        create_database(application.config["SQLALCHEMY_DATABASE_URI"])

    database.init_app(application)

    with application.app_context() as context:
        init()
        migrate(message="Initial migration")
        upgrade()

        adminRole = Role(name="admin")
        customerRole = Role(name="customer")
        warehouseworkerRole = Role(name="warehouseworker")

        database.session.add(adminRole)
        database.session.add(customerRole)
        database.session.add(warehouseworkerRole)
        database.session.commit()

        admin = User(email="admin@admin.com", password="1", forename="admin", surname="admin")

        database.session.add(admin)
        database.session.commit()

        userRole = UserRole(userId=admin.id, roleId=adminRole.id)

        database.session.add(userRole)
        database.session.commit()

        done = True
except Exception as error:
    application.logger.debug(error)
</code>```

It is beeing executed in a docker container and that file looks like this:

```<code>FROM python:3

RUN mkdir -p /opt/src/authentication
WORKDIR /opt/src/authentication

COPY authentication/migrate.py ./migrate.py
COPY authentication/configuration.py ./configuration.py
COPY authentication/models.py ./models.py
COPY authentication/requirements.txt ./requirements.txt

RUN pip install -r ./requirements.txt

ENTRYPOINT ["python", "./migrate.py"]
</code>```

After the first run everything works fine. But if I want to rerun this migration I get an error saying:

```<code>Error: Directory migrations already exists and is not empty
</code>```

I've been going arround circles for the whole day and I'd really appreciate the assistance. I've tried deleting the alembic version in adminer but I don't even see it there.

What should I do?

Body:
I'm working on a flask application project and it incorporates usage of tools such as docker, adminer and redis.

I have a migration.py file that looks like this:

from flask import Flask
from configuration import Configuration
from flask_migrate import Migrate, init, migrate, upgrade
from models import database, Role, User, UserRole
from sqlalchemy_utils import database_exists, create_database, drop_database

application = Flask(__name__)
application.config.from_object(Configuration)

migrateObject = Migrate(application, database)

done = False

while not done:
try:
    if not database_exists(application.config['SQLALCHEMY_DATABASE_URI']):
        create_database(application.config['SQLALCHEMY_DATABASE_URI'])

    if database_exists(application.config["SQLALCHEMY_DATABASE_URI"]):
        drop_database(application.config["SQLALCHEMY_DATABASE_URI"])
        create_database(application.config["SQLALCHEMY_DATABASE_URI"])

    database.init_app(application)

    with application.app_context() as context:
        init()
        migrate(message="Initial migration")
        upgrade()

        adminRole = Role(name="admin")
        customerRole = Role(name="customer")
        warehouseworkerRole = Role(name="warehouseworker")

        database.session.add(adminRole)
        database.session.add(customerRole)
        database.session.add(warehouseworkerRole)
        database.session.commit()

        admin = User(email="admin@admin.com", password="1", forename="admin", surname="admin")

        database.session.add(admin)
        database.session.commit()

        userRole = UserRole(userId=admin.id, roleId=adminRole.id)

        database.session.add(userRole)
        database.session.commit()

        done = True
except Exception as error:
    application.logger.debug(error)

It is beeing executed in a docker container and that file looks like this:

FROM python:3

RUN mkdir -p /opt/src/authentication
WORKDIR /opt/src/authentication

COPY authentication/migrate.py ./migrate.py
COPY authentication/configuration.py ./configuration.py
COPY authentication/models.py ./models.py
COPY authentication/requirements.txt ./requirements.txt

RUN pip install -r ./requirements.txt

ENTRYPOINT ["python", "./migrate.py"]

After the first run everything works fine. But if I want to rerun this migration I get an error saying:

Error: Directory migrations already exists and is not empty

I've been going arround circles for the whole day and I'd really appreciate the assistance. I've tried deleting the alembic version in adminer but I don't even see it there.

What should I do?


问:
Chrome DevTools, Javascript Debugger Weird behaviour
When debugging this page
https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1

I get the following error message:

```<code>Uncaught TypeError: d3.forceSimulation().nodes(...).links is not a function
    drawCluster https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1 line 11 > injectedScript:208
    success https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1 line 11 > injectedScript:218
    jQuery 4
    <anonymous> javascript:alert('Validation Successful'):1
</code>```

The first strange thing is that it says line 11 > injectedScript. It's the first time I see that message.

If I click on the the error (in the console tab) I get redirected to a minified page (the debug attribute in the GET request should prevent the minification).

In D3 version 2 the code was:

```<code> force = d3.layout.force()
        .nodes(nodeSetApp)
        .links(linkSetApp)
</code>```

In D3 version 4 it should be

```<code>force = d3.forceSimulation()
        .nodes(nodeSetApp)
        .links(linkSetApp)
</code>```

but it doesn't seem to work.

Body:
When debugging this page
https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1

I get the following error message:

Uncaught TypeError: d3.forceSimulation().nodes(...).links is not a function
    drawCluster https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1 line 11 > injectedScript:208
    success https://www.tematichedigenere.com/wiki/Speciale:SemanticMediaWikiGraph?debug=1 line 11 > injectedScript:218
    jQuery 4
    <anonymous> javascript:alert('Validation Successful'):1

The first strange thing is that it says line 11 > injectedScript. It's the first time I see that message.

If I click on the the error (in the console tab) I get redirected to a minified page (the debug attribute in the GET request should prevent the minification).

In D3 version 2 the code was:

 force = d3.layout.force()
        .nodes(nodeSetApp)
        .links(linkSetApp)

In D3 version 4 it should be

force = d3.forceSimulation()
        .nodes(nodeSetApp)
        .links(linkSetApp)

but it doesn't seem to work.


问:
how efficient KEDA when we use azure app insight as trigger?
There is always some delay in the app logs to be captured in the azure application insight, how come KEDA (Kubernetes Event-driven Autoscaling) will be able to auto scale the container based on the logs which are not real time?. Right now the logs are logged in Azure app insight, if azure application insight trigger for KEDA is not effective then i may need to go with Prometheus.</p>


问:
How to run Selenium on another PC without IDE
is it possible to run Selenium script on another computer that doesn't have IDE installed? (the other PC only has Python installed)
How do I do that?
Or is it mandatory to use IDE?

I tried to run the Selenium script on another computer without the IDE installed... It identifies that it is Selenium but cannot actually enter a web page.


问:
List of started chats with firebase in flutter
I'm building a chat app with firebase in Flutter and I used a way to create a chatroom through a list of users (you click on one of the users of the app and it creates a chatroom). Actually Its very simple, in my fire base database there is a list of chatrooms named with the uid of the current user and the uid of the peer (exemple: currentuseruid - peeruid, or peeruid - currentuseruid) However, I want to display the list of all the chatrooms of my current user on the home screen. As Im not quite the expert in flutter I don't know much. Do you have any hints ?

Here's is my code if it can help :

My route generator:

```<code>class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
            builder: (context) => const SplashScreenWrapper());
      case '/chat':
        var arguments = settings.arguments;
        if (arguments != null) {
          return PageRouteBuilder(
              pageBuilder: (context, animation, secondaryAnimation) =>
                  ChatScreen(chatParams: arguments as ChatParams),
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) {
                animation =
                    CurvedAnimation(curve: Curves.ease, parent: animation);
                return FadeTransition(
                  opacity: animation,
                  child: child,
                );
              });
        } else {
          return pageNotFound();
        }
      default:
        return pageNotFound();
    }
  }
</code>```

chat_params.dart:

```<code>class ChatParams {
  final String? userUid;
  final AppUserData peer;

  ChatParams(this.userUid, this.peer);

  String getChatGroupId() {
    if (userUid.hashCode <= peer.uid.hashCode) {
      return '$userUid-${peer.uid}';
    } else {
      return '${peer.uid}-$userUid';
    }
  }
}
</code>```

How I create a chatoom:

```<code>onTap: () {
      if (currentuser.uid == users.uid) {
        return;
      }
      Navigator.pushNamed(context, '/chat',
          arguments: ChatParams(currentuser.uid, users));
    },
</code>```

And here's my firebase database so you understand better:

Thank you in advance.

Body:
I'm building a chat app with firebase in Flutter and I used a way to create a chatroom through a list of users (you click on one of the users of the app and it creates a chatroom). Actually Its very simple, in my fire base database there is a list of chatrooms named with the uid of the current user and the uid of the peer (exemple: currentuseruid - peeruid, or peeruid - currentuseruid) However, I want to display the list of all the chatrooms of my current user on the home screen. As Im not quite the expert in flutter I don't know much. Do you have any hints ?

Here's is my code if it can help :

My route generator:

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
            builder: (context) => const SplashScreenWrapper());
      case '/chat':
        var arguments = settings.arguments;
        if (arguments != null) {
          return PageRouteBuilder(
              pageBuilder: (context, animation, secondaryAnimation) =>
                  ChatScreen(chatParams: arguments as ChatParams),
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) {
                animation =
                    CurvedAnimation(curve: Curves.ease, parent: animation);
                return FadeTransition(
                  opacity: animation,
                  child: child,
                );
              });
        } else {
          return pageNotFound();
        }
      default:
        return pageNotFound();
    }
  }

chat_params.dart:

class ChatParams {
  final String? userUid;
  final AppUserData peer;

  ChatParams(this.userUid, this.peer);

  String getChatGroupId() {
    if (userUid.hashCode <= peer.uid.hashCode) {
      return '$userUid-${peer.uid}';
    } else {
      return '${peer.uid}-$userUid';
    }
  }
}

How I create a chatoom:

onTap: () {
      if (currentuser.uid == users.uid) {
        return;
      }
      Navigator.pushNamed(context, '/chat',
          arguments: ChatParams(currentuser.uid, users));
    },

And here's my firebase database so you understand better:

Thank you in advance.


问:
Error adding iOS Service Extensions using OneSignal and Capacitor 4
I'm migrating my Ionic + Capacitor 2 app to Capacitor 4 but I'm having trouble configuring the iOS Service Extensions using OneSignal.

I'm following all the steps described in https://documentation.onesignal.com/docs/ionic-sdk-setup#step-5-configure-your-xcode-project-ios-only however, Xcode always shows the error 'OneSignal/OneSignal.h' file not found.

After each failed attempt, I deleted the iOS platform folder and recreated it using ionic capacitor add ios to be able to redo the attempts in a completely clean code and thus avoid possible conflicts, but I always get the same problem.

These are exactly the steps I'm doing:

ionic capacitor add ios (recreating the iOS project after deleting it)

xed ios/App to open the iOS project in Xcode

Enable Push Notifications and Remote Notifications (inside of Background Modes) in Signing & Capabilities

Go to File > New > Target..., insert the name OneSignalNotificationServiceExtension, select Objective-C as language and then click on Finish and then Cancel

With OneSignalNotificationServiceExtension selected in the target list, I select the Deployment Target as iOS 13 (just like I'm using in the Main Application Target)

Open the NotificationService.m file inside the newly created OneSignalNotificationServiceExtension folder and then replace all its contents with Objective-C code

Select the OneSignalNotificationServiceExtension target, enter the Build Settings tab and make sure that the values of Debug and Release within Code Signing Entitlements are already blank

Close Xcode

Open ios/App/Podfile

Include the following code at the end of Podfile:

```<code>target 'OneSignalNotificationServiceExtension' do
    pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
end
</code>```

Return to the terminal and then pod repo update and pod install, which returns the following:

```<code>Analyzing dependencies
Downloading dependencies
Installing OneSignalXCFramework 3.12.3
Generating Pods project
Integrating client project
Pod installation complete! There are 23 dependencies from the Podfile and 33 total pods installed.
</code>```

xed ios/App and wait for Xcode to open and index files

Keep getting the error 'OneSignal/OneSignal.h' file not found

As I already said I've followed every single step in https://documentation.onesignal.com/docs/ionic-sdk-setup#step-5-configure-your-xcode-project-ios-only and redone these steps numerous times until I came to the conclusion that I didn't make any mistakes and followed all the steps as recommended, so how can I resolve this?

Thanks!

Body:
I'm migrating my Ionic + Capacitor 2 app to Capacitor 4 but I'm having trouble configuring the iOS Service Extensions using OneSignal.

I'm following all the steps described in https://documentation.onesignal.com/docs/ionic-sdk-setup#step-5-configure-your-xcode-project-ios-only however, Xcode always shows the error 'OneSignal/OneSignal.h' file not found.

After each failed attempt, I deleted the iOS platform folder and recreated it using ionic capacitor add ios to be able to redo the attempts in a completely clean code and thus avoid possible conflicts, but I always get the same problem.

These are exactly the steps I'm doing:

ionic capacitor add ios (recreating the iOS project after deleting it)

xed ios/App to open the iOS project in Xcode

Enable Push Notifications and Remote Notifications (inside of Background Modes) in Signing & Capabilities

Go to File > New > Target..., insert the name OneSignalNotificationServiceExtension, select Objective-C as language and then click on Finish and then Cancel

With OneSignalNotificationServiceExtension selected in the target list, I select the Deployment Target as iOS 13 (just like I'm using in the Main Application Target)

Open the NotificationService.m file inside the newly created OneSignalNotificationServiceExtension folder and then replace all its contents with Objective-C code

Select the OneSignalNotificationServiceExtension target, enter the Build Settings tab and make sure that the values of Debug and Release within Code Signing Entitlements are already blank

Close Xcode

Open ios/App/Podfile

Include the following code at the end of Podfile:

target 'OneSignalNotificationServiceExtension' do
    pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
end

Return to the terminal and then pod repo update and pod install, which returns the following:

Analyzing dependencies
Downloading dependencies
Installing OneSignalXCFramework 3.12.3
Generating Pods project
Integrating client project
Pod installation complete! There are 23 dependencies from the Podfile and 33 total pods installed.

xed ios/App and wait for Xcode to open and index files

Keep getting the error 'OneSignal/OneSignal.h' file not found

As I already said I've followed every single step in https://documentation.onesignal.com/docs/ionic-sdk-setup#step-5-configure-your-xcode-project-ios-only and redone these steps numerous times until I came to the conclusion that I didn't make any mistakes and followed all the steps as recommended, so how can I resolve this?

Thanks!


问:
How can I cache results from playwright so the next time the same URL is called, it can pull directly from cache?
I'm running playwright in a react app. My goal is to return results right away for cached results.

The following is able to set and get cache. But the next time the same URL is requested, it acts like it's not saved in cache. What am I missing?

```<code>const { chromium } = require('playwright');
const LRU = require('lru-cache');

const cache = new LRU({
  max: 500,  // Max number of entries in the cache
  ttl: 86400 // Time to live for an entry in the cache, in milliseconds
});

async function fetchHTML(url) {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  page.setDefaultTimeout(10000);
  // Check if the URL is in the cache
  let html = cache.get(url);
  if (html) {
    // This is NEVER called.
    console.log('Retrieved HTML from cache');
  } else {
    await page.goto(url);
    // html = await page.content();
    html = await page.evaluate(() => document.body.innerHTML);
    console.log('Setting cache for ' + url);
    cache.set(url, html);

    let cachedHtml = cache.get(url);
    //  This works though.
    console.log('Cached HTML length: ' + cachedHtml.length); // Returns: Cached HTML length: 1234
  }
  await browser.close();
  return html;
}

let url = 'https://example.com';
let html = fetchHTML(url); // successful fetch!
console.log(html.length); // Returns: 1234
// but is it cached?
let cachedHtml = fetchHTML(url); // this also fetches, but not from cache. Why?
console.log(cachedHtml.length);

</code>```

Body:
I'm running playwright in a react app. My goal is to return results right away for cached results.

The following is able to set and get cache. But the next time the same URL is requested, it acts like it's not saved in cache. What am I missing?

const { chromium } = require('playwright');
const LRU = require('lru-cache');

const cache = new LRU({
  max: 500,  // Max number of entries in the cache
  ttl: 86400 // Time to live for an entry in the cache, in milliseconds
});

async function fetchHTML(url) {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  page.setDefaultTimeout(10000);
  // Check if the URL is in the cache
  let html = cache.get(url);
  if (html) {
    // This is NEVER called.
    console.log('Retrieved HTML from cache');
  } else {
    await page.goto(url);
    // html = await page.content();
    html = await page.evaluate(() => document.body.innerHTML);
    console.log('Setting cache for ' + url);
    cache.set(url, html);

    let cachedHtml = cache.get(url);
    //  This works though.
    console.log('Cached HTML length: ' + cachedHtml.length); // Returns: Cached HTML length: 1234
  }
  await browser.close();
  return html;
}

let url = 'https://example.com';
let html = fetchHTML(url); // successful fetch!
console.log(html.length); // Returns: 1234
// but is it cached?
let cachedHtml = fetchHTML(url); // this also fetches, but not from cache. Why?
console.log(cachedHtml.length);


问:
How to perform migrations on Mac with EF6
I am trying to move an MVC 5 app from Windows to Mac. I need to connect it to my SQL Server database (hosted inside a Docker container). The app is building and starting, but it throws this error every time it tries to perform a database action.

```<code>The model backing the context has changed since the database was created. Consider using Code First Migrations to update the database.
</code>```

So I used this post to enable migrations. But now when I try to run dotnet ef migrations add initial It throws the below error.

/Users/cy/Projects/CallNote 2 Web/CallNote 2 Web.csproj(526,3): error MSB4019: The imported project "/usr/local/share/dotnet/sdk/7.0.100/Microsoft/VisualStudio/v17.0/WebApplications/Microsoft.WebApplication.targets" was not found. Confirm that the expression in the Import declaration "/usr/local/share/dotnet/sdk/7.0.100/Microsoft/VisualStudio/v17.0/WebApplications/Microsoft.WebApplication.targets" is correct, and that the file exists on disk.
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

But according to this, I understand that running migrations in this way is only available for EF Core. But my project is not SDK-style. It is ASP.Net MVC 5 targeting Framework 4.7.2 with EF6.

Question 1: How can I run migrations on this project?

Question 2: Why is this project running at all since here it says it is not possible to develop a ASP.Net MVC 5 app on Mac?

Body:
I am trying to move an MVC 5 app from Windows to Mac. I need to connect it to my SQL Server database (hosted inside a Docker container). The app is building and starting, but it throws this error every time it tries to perform a database action.

The model backing the context has changed since the database was created. Consider using Code First Migrations to update the database.

So I used this post to enable migrations. But now when I try to run dotnet ef migrations add initial It throws the below error.

/Users/cy/Projects/CallNote 2 Web/CallNote 2 Web.csproj(526,3): error MSB4019: The imported project "/usr/local/share/dotnet/sdk/7.0.100/Microsoft/VisualStudio/v17.0/WebApplications/Microsoft.WebApplication.targets" was not found. Confirm that the expression in the Import declaration "/usr/local/share/dotnet/sdk/7.0.100/Microsoft/VisualStudio/v17.0/WebApplications/Microsoft.WebApplication.targets" is correct, and that the file exists on disk.
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

But according to this, I understand that running migrations in this way is only available for EF Core. But my project is not SDK-style. It is ASP.Net MVC 5 targeting Framework 4.7.2 with EF6.

Question 1: How can I run migrations on this project?

Question 2: Why is this project running at all since here it says it is not possible to develop a ASP.Net MVC 5 app on Mac?


问:
MoviePy, How to add blank left padding to TextClip?
I am working on my free time on a project that uses:

MoviePy latest release (1.0.3)

ImageMagick 7.1.0-53

Python >=3.8,<4

Windows 10

My goal is to concatenate clips and for each, I want to show a text at the top left of the screen.

textclip: TextClip = TextClip(
   "     " + some_text, # same output with fstring :>5, ljust(5) or (" " * 5)
   method="caption",
   align="center",
   fontsize=60,
   color="white",
)
```

I am struggling to add padding to my textclips. I thought I could begin the text with whitespaces but it seems like they are removed even inside the text. The resulting content is sometimes stripped, sometimes splitted in rows.

I was thinking maybe the font is responsible for this ? I don't see any evidence of this issue in the MoviePy TextClip code. Or maybe there is a hacky way to add margin to my texts ??

Body:
I am working on my free time on a project that uses:

MoviePy latest release (1.0.3)

ImageMagick 7.1.0-53

Python >=3.8,<4

Windows 10

My goal is to concatenate clips and for each, I want to show a text at the top left of the screen.

textclip: TextClip = TextClip(
   "     " + some_text, # same output with fstring :>5, ljust(5) or (" " * 5)
   method="caption",
   align="center",
   fontsize=60,
   color="white",
)

I am struggling to add padding to my textclips. I thought I could begin the text with whitespaces but it seems like they are removed even inside the text. The resulting content is sometimes stripped, sometimes splitted in rows.

I was thinking maybe the font is responsible for this ? I don't see any evidence of this issue in the MoviePy TextClip code. Or maybe there is a hacky way to add margin to my texts ??