问:
Firestore emulator gets document form cache after document write that is rejected due to security rule
I have Flutter mobile application in the front end and Firebase in the backend.  I am currently running Firebase emulator.  I am using Firestore for storing data.

I have a QUERY that is supposed to fetch a document and a WRITE that is supposed to update the document.  When I run both the QUERY and WRITE in the following order I see a bug.  Is there a solution.

Run the QUERY to read the document from Firestore.

Run the WRITE to update the document in Firestore. The WRITE fails because of a security rule which is what I expect.  The document in Firestore is not updated also as expected.

Run the QUERY to read the document from Firestore.  This time, the value read is the value in step 2 even though the write has failed.  When printing the Metadata over here, I find that isFromCache is false but hasPendingWrites is true.

It seems to me that the write in step 2 updated the cache and the read in step 3 read the doc from the cache giving me wrong results.

Any idea if this is a bug in Firestore emulator or if I should be doing something else?

This is the WRITE code:

```<code>await _firestore.doc(PathService.boosts(uid)).update({
      'boosting': true,
      'boosts': FieldValue.increment(-1),
      'endedAt': Timestamp.fromDate(
        DateTime.now().add(const Duration(hours: 1)),
      ),
      'ttl': Timestamp.fromDate(
        DateTime.now().add(const Duration(days: 7 * 365)),
      ),
    });
</code>```

Here is the code for the READ.  I tried to use Source.server hoping to force the READ from server instead from cache but did not work:

```<code>    _firestore
        .doc(PathService.boosts(uid))
        .withConverter<MyProfileBoosts>(
          fromFirestore: (snapshot, _) {
            return MyProfileBoosts.fromJson(snapshot.data()!);
          },
          toFirestore: (myProfileBoosts, _) => myProfileBoosts.toJson(),
        )
        .get(const GetOptions(source: Source.server));
</code>```

As for the Firestore security rules, all you need is simple rule that makes the write fails.

Body:
I have Flutter mobile application in the front end and Firebase in the backend.  I am currently running Firebase emulator.  I am using Firestore for storing data.

I have a QUERY that is supposed to fetch a document and a WRITE that is supposed to update the document.  When I run both the QUERY and WRITE in the following order I see a bug.  Is there a solution.

Run the QUERY to read the document from Firestore.

Run the WRITE to update the document in Firestore. The WRITE fails because of a security rule which is what I expect.  The document in Firestore is not updated also as expected.

Run the QUERY to read the document from Firestore.  This time, the value read is the value in step 2 even though the write has failed.  When printing the Metadata over here, I find that isFromCache is false but hasPendingWrites is true.

It seems to me that the write in step 2 updated the cache and the read in step 3 read the doc from the cache giving me wrong results.

Any idea if this is a bug in Firestore emulator or if I should be doing something else?

This is the WRITE code:

await _firestore.doc(PathService.boosts(uid)).update({
      'boosting': true,
      'boosts': FieldValue.increment(-1),
      'endedAt': Timestamp.fromDate(
        DateTime.now().add(const Duration(hours: 1)),
      ),
      'ttl': Timestamp.fromDate(
        DateTime.now().add(const Duration(days: 7 * 365)),
      ),
    });

Here is the code for the READ.  I tried to use Source.server hoping to force the READ from server instead from cache but did not work:

    _firestore
        .doc(PathService.boosts(uid))
        .withConverter<MyProfileBoosts>(
          fromFirestore: (snapshot, _) {
            return MyProfileBoosts.fromJson(snapshot.data()!);
          },
          toFirestore: (myProfileBoosts, _) => myProfileBoosts.toJson(),
        )
        .get(const GetOptions(source: Source.server));

As for the Firestore security rules, all you need is simple rule that makes the write fails.


来源: stackexchange

问:
Resolve by ID interface Graphql federation (Apollo)
I am trying to resolve an interface by ID with netflix-dgs and Apollo federation. But the DgsEntityFetcher does not seem to be registered for interfaces.
I also tried declaring entity resolvers for types B and C and still null result.

Here is a sample:

```<code>interface A @key(fields:"id"){
  id: ID!
  ...
}
type B implements A {...}
type C implements A {...}
//This type can appear in multiple services/subgraphs
type SomeObject @key(fields:"id"){
      id: ID!
      aTypeField: A @provides(fields: "id")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to resolve an interface by ID with netflix-dgs and Apollo federation. But the DgsEntityFetcher does not seem to be registered for interfaces.
I also tried declaring entity resolvers for types B and C and still null result.

Here is a sample:

interface A @key(fields:"id"){
  id: ID!
  ...
}
type B implements A {...}
type C implements A {...}
//This type can appear in multiple services/subgraphs
type SomeObject @key(fields:"id"){
      id: ID!
      aTypeField: A @provides(fields: "id")
}


问:
can not split window in default terminal of vscode
I use vscode on mac. I want to split the terminal window in vscode. Still, when I split, vscode gives an error like this: The terminal process failed to launch: Starting directory (cwd) "/Users/username/Library/CloudStorage/OneDrive-ä¸ªäºº/codeSet/cppCode" does not exist.

The actual path is: /Users/username/Library/CloudStorage/OneDrive-个人/codeSet/cppCode. And it is the terminal's current work directory.

I think this is a character encoding problem, but I do not know how to solve it. Can someone help me solve this problem or provide some valuable suggestions? I would be grateful for any help you can provide.


问:
Is there a way to have intuitive saving using the System.IO reference in ASP.NET Web Forms?
I'm trying to have an intuitive saving process. This will allow clients to save their reports without specifying a name. As an example, the default name will be 'GenerateNotice.pdf'. On a second save, I would like it to automatically detect the original report and automatically populate the name as 'GenerateNotice1.pdf'. On the third save, it would automatically populate 'GenerateNotice2.pdf', etc, etc.

This is what I'm currently using:

```<code>static void ThreadMethodReport(List<Notice> notices, string template, bool reprint)
        {
            XtraReport report = CreateReport(notices, template, reprint);
            PdfExportOptions pdfExportOptions = SetExportOptions();
            SaveFileDialog save = SetSaveFileDialogOptions();

            DialogResult dialogResult = save.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string saveLocation;
                using (FileStream stream = (FileStream)save.OpenFile())
                {
                    saveLocation = stream.Name;
                }
                report.ExportToPdf(saveLocation, pdfExportOptions);
            }
        }

private static SaveFileDialog SetSaveFileDialogOptions()
        {
            string fileNameInitial = @"GenerateNotice.pdf";
            string fileNameCurrent = fileNameInitial;
            int count = 0;
            while (File.Exists(fileNameCurrent))
            {
                count++;
                fileNameCurrent = Path.GetFileNameWithoutExtension(fileNameInitial)
                     + count.ToString()
                     + Path.GetExtension(fileNameInitial);
            }
            return new SaveFileDialog()
            {
                Filter = "PDF Format|*.pdf",
                Title = "Save infraction as",
                FileName = fileNameCurrent
            };
        }
</code>```

However, it will only ever identify the initial file and no subsequent ones.

Does this have something to do with me using IIS and it expecting the files to be saved somewhere in the IIS root directory?

Body:
I'm trying to have an intuitive saving process. This will allow clients to save their reports without specifying a name. As an example, the default name will be 'GenerateNotice.pdf'. On a second save, I would like it to automatically detect the original report and automatically populate the name as 'GenerateNotice1.pdf'. On the third save, it would automatically populate 'GenerateNotice2.pdf', etc, etc.

This is what I'm currently using:

static void ThreadMethodReport(List<Notice> notices, string template, bool reprint)
        {
            XtraReport report = CreateReport(notices, template, reprint);
            PdfExportOptions pdfExportOptions = SetExportOptions();
            SaveFileDialog save = SetSaveFileDialogOptions();

            DialogResult dialogResult = save.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string saveLocation;
                using (FileStream stream = (FileStream)save.OpenFile())
                {
                    saveLocation = stream.Name;
                }
                report.ExportToPdf(saveLocation, pdfExportOptions);
            }
        }

private static SaveFileDialog SetSaveFileDialogOptions()
        {
            string fileNameInitial = @"GenerateNotice.pdf";
            string fileNameCurrent = fileNameInitial;
            int count = 0;
            while (File.Exists(fileNameCurrent))
            {
                count++;
                fileNameCurrent = Path.GetFileNameWithoutExtension(fileNameInitial)
                     + count.ToString()
                     + Path.GetExtension(fileNameInitial);
            }
            return new SaveFileDialog()
            {
                Filter = "PDF Format|*.pdf",
                Title = "Save infraction as",
                FileName = fileNameCurrent
            };
        }

However, it will only ever identify the initial file and no subsequent ones.

Does this have something to do with me using IIS and it expecting the files to be saved somewhere in the IIS root directory?


问:
Unable to open file in target "XpensioRn" when run react native app
When I trying to start ios app I get the following error. Does anybody have idea why this happens?


问:
unable to execute a function side package.json
[enter image description here](https://i.stack.imgur.com/qvo8O.png)

unable to run a function inside package.json

same things runs on mac but not windows


问:
Gitlab Runner network configuration for communication of container started during job
I got a bit stuck with the configuration of gitlab ci for my test setup:

I have a python application using a database (postgresql) and test it with pytest.
For easing development I designed a fixture spinning up a local database for testing with a real database (goal was no mocking but actual resource usage).

This works very nicely if just on my local machine (MacBook with M2 & docker running).
Yet, if trying to run it with gitlab ci/runner I can't get the container running the tests (spawned by the runner) to communicate with the created database.

It would be so lovely if one of you knew the trick I am missing here...

an abstracted conftest.py file:

```<code>import time

import pytest
import docker
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base

client = docker.from_env()
Base = declarative_base()

def create_engine_and_session(host):
    engine = create_engine(
        f"postgresql://username:password@{host}:5432/default_database",
        echo=True,
    )

    session = sessionmaker(bind=engine)()
    return engine, session

@pytest.fixture(scope="session")
def database(env_variables):

    database_container = client.containers.run(
        "postgres:latest",
        environment=env_variables,
        ports={"5432": 5432},
        detach=True,
    )
    time.sleep(5)
    try:
        # what is host?
        # neither localhost, 127.0.0.1, container.name nor container.id worked
        # only the IP of the node running docker returned a result - but this can't be right...
        host=???

        engine, session = create_engine_and_session(host)
        Base.metadata.create_all(engine)   # communicates with the database but fails
        yield engine, session
    finally:
        database_container.kill()
        database_container.remove()
</code>```

the relevant gitlab-ci.yaml:

```<code>stages:
  - test

test:
  stage:
    test
  image: $test_container   ### Dockerfile: FROM python:3.9-alpine && RUN apk add docker
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  before_script:
    - pip install -r requirements.txt
  script:
    - python -m pytest
</code>```

the local docker configuration of my gitlab-runner (executor: docker):

```<code>[runners.docker]
    tls_verify = false
    image = "alpine"
    privileged = true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/var/run/docker.sock:/var/run/docker.sock", "/cache"]
    shm_size = 0
</code>```

Body:
I got a bit stuck with the configuration of gitlab ci for my test setup:

I have a python application using a database (postgresql) and test it with pytest.
For easing development I designed a fixture spinning up a local database for testing with a real database (goal was no mocking but actual resource usage).

This works very nicely if just on my local machine (MacBook with M2 & docker running).
Yet, if trying to run it with gitlab ci/runner I can't get the container running the tests (spawned by the runner) to communicate with the created database.

It would be so lovely if one of you knew the trick I am missing here...

an abstracted conftest.py file:

import time

import pytest
import docker
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base

client = docker.from_env()
Base = declarative_base()

def create_engine_and_session(host):
    engine = create_engine(
        f"postgresql://username:password@{host}:5432/default_database",
        echo=True,
    )

    session = sessionmaker(bind=engine)()
    return engine, session

@pytest.fixture(scope="session")
def database(env_variables):

    database_container = client.containers.run(
        "postgres:latest",
        environment=env_variables,
        ports={"5432": 5432},
        detach=True,
    )
    time.sleep(5)
    try:
        # what is host?
        # neither localhost, 127.0.0.1, container.name nor container.id worked
        # only the IP of the node running docker returned a result - but this can't be right...
        host=???

        engine, session = create_engine_and_session(host)
        Base.metadata.create_all(engine)   # communicates with the database but fails
        yield engine, session
    finally:
        database_container.kill()
        database_container.remove()

the relevant gitlab-ci.yaml:

stages:
  - test

test:
  stage:
    test
  image: $test_container   ### Dockerfile: FROM python:3.9-alpine && RUN apk add docker
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  before_script:
    - pip install -r requirements.txt
  script:
    - python -m pytest

the local docker configuration of my gitlab-runner (executor: docker):

[runners.docker]
    tls_verify = false
    image = "alpine"
    privileged = true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/var/run/docker.sock:/var/run/docker.sock", "/cache"]
    shm_size = 0


问:
Embedding "Dolby Digital Plus with Dolby Atmos" into MP4 using ffmpeg
How can I encode Dolby Atmos into MP4? I am using this command ffmpeg -i input.mp4 -i input.ec3 -map 0:v -map 1:a -c:v copy -c:a copy -disposition:a default -metadata:s:a:0 complexity_index=16 -metadata:s:a:0 title="Dolby Atmos" output_test.mp4 I have to provide every single piece of data that is inside this EC3 file. I have noticed that when I am running this command the MP4 file contains actual Dolby Atmos stream but it's missing complexity index. Raw EC3 file has Complexity Index set to 16 but after adding it to MP4 file the complexity index is not present and this MP4 is not identified as a video with proper Dolby Atmos stream

I thought that after using this command, complexity index will be added correctly. I don't want to use MKV but it looks like I will have to do that.


问:
Importing different rows from a CSV based on a filter selected in a GUI
I have a GUI that imports data from CSV.
There are different subjects, but also for the same subject more than one row.
So for example:

Subj ID , Admission Date , Reason , ....

1111111 , 11.11.11       ,3 months follow up

1111111 , 11.11.11       , 6 months follow up

2222222 , 22.22.22       , 3 months follow up

2222222 , 22.22.22   , 6 months follow up,

The Gui displays the data from one subject, based on their ID.
Now i have a drop-down menu in the GUI, where i can choose the Reason (3 or 6 months) follow up. So when I choose a reason, the same Subject (same ID) should be imported, but the row with the corresponding Reason.
I can't get this to work.
The data is imported before choosing a reason, but when I change the reason i get an error, that the dataframe i want to import the data from seems to be empty

```<code>import sys
from PyQt5.QtWidgets import QApplication, QComboBox, QDialog, QVBoxLayout

class PostoperativeDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Postoperative Information')

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # Create ComboBox
        self.combo_box = QComboBox()
        layout.addWidget(self.combo_box)

        # Add items to ComboBox
        self.combo_box.addItems(['Please select', 'Enter data', 'Option 1', 'Option 2'])

        # Connect signal to update_content slot
        self.combo_box.currentTextChanged.connect(self.update_content)

   def read_content_csv(self):
        """dummy part of update text that served only to make it run; all parts of [update_text_notworking] should be
        moved here"""
        print('updating content ...')
        df_subj = General.import_dataframe(f"{self.date}.csv", separator_csv=',')
        if df_subj.empty:
            return
        df_subj = df_subj[df_subj['Reason_postop'] == self.comboBox.currentText()]
        if df_subj.empty:
            return
        df_subj = df_subj[df_subj['PID'] == General.read_current_subj().pid[0]]
        if df_subj.empty:
            return

self.lineEditAdmission_Nch.setText(str(df_subj["Admission_NCh_postop"][0])) \
            if str(df_subj["Admission_NCh_postop"][0]) != 'nan' else self.lineEditAdmission_Nch.setText('')

    def update_content(self):
         if self.lineEditreason.currentText() == 'Please select':
            pass
        elif self.lineEditreason.currentText() == 'Enter data':
            Output.open_input_dialog_postoperative(self)
            data_frame = General.import_dataframe(f"{self.date}.csv", separator_csv=',')
            subj_details = General.read_current_subj()

            data_frame.loc[len(data_frame), ['ID', 'PID', 'Reason_postop']] =
            [subj_details.id[0], subj_details.pid[0],

            self.postoperative_date]
            data_frame = data_frame.replace(['nan', ''], [np.nan, np.nan])
            data_frame = data_frame.applymap(lambda x: str(x).replace(';', ' -'))
            data_frame.to_csv(FILEDIR / f"{self.date}.csv", index=False)

            self.lineEditreason.clear()
            self.fill_combobox()
            self.read_content_csv()
        else:
            self.postoperative_date = self.lineEditreason.currentText()
            self.read_content_csv()
            print('something should happen here')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    postop_dialog = PostoperativeDialog()
    postop_dialog.show()
    sys.exit(app.exec_())

</code>```

I don't understand why this isn't working.
I hope someone can help me.

Thank you guys!

Body:
I have a GUI that imports data from CSV.
There are different subjects, but also for the same subject more than one row.
So for example:

Subj ID , Admission Date , Reason , ....

1111111 , 11.11.11       ,3 months follow up

1111111 , 11.11.11       , 6 months follow up

2222222 , 22.22.22       , 3 months follow up

2222222 , 22.22.22   , 6 months follow up,

The Gui displays the data from one subject, based on their ID.
Now i have a drop-down menu in the GUI, where i can choose the Reason (3 or 6 months) follow up. So when I choose a reason, the same Subject (same ID) should be imported, but the row with the corresponding Reason.
I can't get this to work.
The data is imported before choosing a reason, but when I change the reason i get an error, that the dataframe i want to import the data from seems to be empty

import sys
from PyQt5.QtWidgets import QApplication, QComboBox, QDialog, QVBoxLayout

class PostoperativeDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Postoperative Information')

        layout = QVBoxLayout(self)
        self.setLayout(layout)

        # Create ComboBox
        self.combo_box = QComboBox()
        layout.addWidget(self.combo_box)

        # Add items to ComboBox
        self.combo_box.addItems(['Please select', 'Enter data', 'Option 1', 'Option 2'])

        # Connect signal to update_content slot
        self.combo_box.currentTextChanged.connect(self.update_content)

   def read_content_csv(self):
        """dummy part of update text that served only to make it run; all parts of [update_text_notworking] should be
        moved here"""
        print('updating content ...')
        df_subj = General.import_dataframe(f"{self.date}.csv", separator_csv=',')
        if df_subj.empty:
            return
        df_subj = df_subj[df_subj['Reason_postop'] == self.comboBox.currentText()]
        if df_subj.empty:
            return
        df_subj = df_subj[df_subj['PID'] == General.read_current_subj().pid[0]]
        if df_subj.empty:
            return

self.lineEditAdmission_Nch.setText(str(df_subj["Admission_NCh_postop"][0])) \
            if str(df_subj["Admission_NCh_postop"][0]) != 'nan' else self.lineEditAdmission_Nch.setText('')

    def update_content(self):
         if self.lineEditreason.currentText() == 'Please select':
            pass
        elif self.lineEditreason.currentText() == 'Enter data':
            Output.open_input_dialog_postoperative(self)
            data_frame = General.import_dataframe(f"{self.date}.csv", separator_csv=',')
            subj_details = General.read_current_subj()

            data_frame.loc[len(data_frame), ['ID', 'PID', 'Reason_postop']] =
            [subj_details.id[0], subj_details.pid[0],

            self.postoperative_date]
            data_frame = data_frame.replace(['nan', ''], [np.nan, np.nan])
            data_frame = data_frame.applymap(lambda x: str(x).replace(';', ' -'))
            data_frame.to_csv(FILEDIR / f"{self.date}.csv", index=False)

            self.lineEditreason.clear()
            self.fill_combobox()
            self.read_content_csv()
        else:
            self.postoperative_date = self.lineEditreason.currentText()
            self.read_content_csv()
            print('something should happen here')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    postop_dialog = PostoperativeDialog()
    postop_dialog.show()
    sys.exit(app.exec_())

I don't understand why this isn't working.
I hope someone can help me.

Thank you guys!


问:
Pyplot: legend for every row/column of subplots
I am using plt.subplots to create a figure where every column corresponds to a different set of parameters (or different tool/dataset in more realistic situation), but the rows correspond to different characteristics shown for the same parameters/tool/dataset. That is the legends for all plots in a row are the same, but they are different in different rows.

Questions:

I would like to have one legend for every row (or possibly column, if I decide to turn the plot)

I would like to place the legend outside of the subplots (on the right.)

My pedestrian solution is to plot the legend only for the last subplot in every row. I probably could also build upon it to address the second question. However, I wonder, if there is a more elegant way to do this, as, e.g., using fig.legend() to create a single legend for the whole figure (see the thread.)

Here is an example that I cooked up to facilitate the discussion:

```<code>import numpy as np
import matplotlib.pyplot as plt

xx = np.linspace(0., 2.*np.pi)
ff1 = [np.cos(n*xx) for n in np.arange(1, 5)]
ff2 = [np.sin(n*xx) for n in np.arange(1, 5)]
ff3 = [xx**2 / n for n in np.arange(1, 5)]

fig, axs = plt.subplots(2, 4, figsize=(12, 6))
for ax, f1, f2, f3 in zip(axs[0], ff1, ff2, ff3):
    ax.plot(xx, f1, label="cos")
    ax.plot(xx, f2, label="sin")
    ax.plot(xx, f3, label="x^2")
    ax.set_xlabel("x")
    ax.set_ylabel("f1, f2, f3")
    # ax.legend()
axs[0,-1].legend()

for ax, f1, f2, f3 in zip(axs[1], ff1, ff2, ff3):
    ax.plot(f3, f1, label="cos vs. x^2")
    ax.plot(f3, f2, label="sin vx. x^2")
    ax.set_xlabel("f3")
    ax.set_ylabel("f1, f2")
    # ax.legend()
axs[1,-1].legend()

plt.tight_layout()
plt.show()
</code>```

Body:
I am using plt.subplots to create a figure where every column corresponds to a different set of parameters (or different tool/dataset in more realistic situation), but the rows correspond to different characteristics shown for the same parameters/tool/dataset. That is the legends for all plots in a row are the same, but they are different in different rows.

Questions:

I would like to have one legend for every row (or possibly column, if I decide to turn the plot)

I would like to place the legend outside of the subplots (on the right.)

My pedestrian solution is to plot the legend only for the last subplot in every row. I probably could also build upon it to address the second question. However, I wonder, if there is a more elegant way to do this, as, e.g., using fig.legend() to create a single legend for the whole figure (see the thread.)

Here is an example that I cooked up to facilitate the discussion:

import numpy as np
import matplotlib.pyplot as plt

xx = np.linspace(0., 2.*np.pi)
ff1 = [np.cos(n*xx) for n in np.arange(1, 5)]
ff2 = [np.sin(n*xx) for n in np.arange(1, 5)]
ff3 = [xx**2 / n for n in np.arange(1, 5)]

fig, axs = plt.subplots(2, 4, figsize=(12, 6))
for ax, f1, f2, f3 in zip(axs[0], ff1, ff2, ff3):
    ax.plot(xx, f1, label="cos")
    ax.plot(xx, f2, label="sin")
    ax.plot(xx, f3, label="x^2")
    ax.set_xlabel("x")
    ax.set_ylabel("f1, f2, f3")
    # ax.legend()
axs[0,-1].legend()

for ax, f1, f2, f3 in zip(axs[1], ff1, ff2, ff3):
    ax.plot(f3, f1, label="cos vs. x^2")
    ax.plot(f3, f2, label="sin vx. x^2")
    ax.set_xlabel("f3")
    ax.set_ylabel("f1, f2")
    # ax.legend()
axs[1,-1].legend()

plt.tight_layout()
plt.show()


问:
Navigation Graph giving blank screen after click on blank screen
I have setup bottomNavigation with navcontroller

var navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_content_main) as NavHostFragment val navController: NavController = navHostFragment.navController setupWithNavController(binding.navigation, navController)

if i navigate deep in app from homeFragment and comeback to homeFragment via popUpto attribute of action tag in nav-graph its working fine

but if i navigate to another fragment with BottomNavigation and then will go to deep in app and trying to come back to homeFragment using Popupto attribute, it will come to homeFragment but fragment layout is blank and touch is working

For understanding please prefer video Link is below

click on this Video Link .

on HomeFragment onViewCreated i called requestLayout() method but still its not working


问:
Using OAuth2 for internal tool
I want to use OAuth2 for an internal tool in our company to log into the tool with Keycloak. Right now my workflow looks like this:

The user is sent to the client application where he logs in

The client application redirects the user with the authorization code

I extract the authorization code and try to get the access token

a) If getting the access token is successful the user can use the app

b) If getting the access token is unsuccessful we go back to 1.

Note that I don't need any data from Keycloak, I just want to use it for authorization. Also I don't need roles with different privileges, all users are allowed to use the full application.

I have no training in security so please tell me how to improve this process.

Also what would I have to change such that the user can refresh the page without having to login all the time?

Title: Using OAuth2 for internal tool


问:
Angularfire 7.5 queries, why I get undefined?
I'm working on a project with Angularfire 7.5, Angular 15.
I'm having difficulties understanding how Angularfire queries returns results.

I have a a "settings" collection with a document (ID: "settings") that has one reference field:

I'm trying to get the data from the document referenced in the collection "settings", so in my service I have this method:

```<code>getCurrentGroup(): void {
   this.firestore.collection<Settings>(this.collectionName).doc<Settings>('settings').valueChanges().pipe(take(1)).subscribe(data => {
       data?.currentGroup.get().then(res => { console.log(res.data()) });
   });
}
</code>```

Where from the collection "settings" I get the document reference then use the get() method to get its data, this is working fine, I get in the console the correct data.
But since I want to have the data in a component and not in the service, I change my service method to:

```<code>getCurrentGroup(): any {
    this.firestore.collection<Settings>(this.collectionName).doc<Settings>('settings').valueChanges().pipe(take(1)).subscribe(data => {
      if (data !== undefined) return data?.currentGroup.get();
      else return undefined;
    });
  }
</code>```

Then in my component I use then() function to get the promise's result:

```<code>ngOnInit(): void {
    this.settingsService.getCurrentGroup().then(data => console.log(data));
 }
</code>```

But the result is: method getCurrentGroup() is undefined.

What can I do to solve this issue?

I know that probably there is A LOT wrong on how I'm writing this code but I'm a complete newbie on Angular and Firebase and I'm trying to understand how they work together and how Observable / Promises works.

Body:
I'm working on a project with Angularfire 7.5, Angular 15.
I'm having difficulties understanding how Angularfire queries returns results.

I have a a "settings" collection with a document (ID: "settings") that has one reference field:

I'm trying to get the data from the document referenced in the collection "settings", so in my service I have this method:

getCurrentGroup(): void {
   this.firestore.collection<Settings>(this.collectionName).doc<Settings>('settings').valueChanges().pipe(take(1)).subscribe(data => {
       data?.currentGroup.get().then(res => { console.log(res.data()) });
   });
}

Where from the collection "settings" I get the document reference then use the get() method to get its data, this is working fine, I get in the console the correct data.
But since I want to have the data in a component and not in the service, I change my service method to:

getCurrentGroup(): any {
    this.firestore.collection<Settings>(this.collectionName).doc<Settings>('settings').valueChanges().pipe(take(1)).subscribe(data => {
      if (data !== undefined) return data?.currentGroup.get();
      else return undefined;
    });
  }

Then in my component I use then() function to get the promise's result:

ngOnInit(): void {
    this.settingsService.getCurrentGroup().then(data => console.log(data));
 }

But the result is: method getCurrentGroup() is undefined.

What can I do to solve this issue?

I know that probably there is A LOT wrong on how I'm writing this code but I'm a complete newbie on Angular and Firebase and I'm trying to understand how they work together and how Observable / Promises works.


问:
I cant get best parameters from HyperparamBuilder (Tuning LightGBM model)
I am using HyperparamBuilder to tune a LightGBM model with synapseml. My problem is that I cannot get the best parameters of the model. I know these two commands: print(bestModel.getBestModelInfo())
print(bestModel.getBestModel()) but there is no info about the best model parameters. e.g maxDepth, numLeaves, etc.

I didnt find anything in their documentation.


问:
How to automate Gradle task running
The project I am working on is Java, Gradle based. So I want to create a plugin/script that will run a certain Gradle task whenever I made changes to one of the files from the project.

For example

There is A.xml file and a B Gradle task. Whenever I do changes to A.xml and save it I want the B Gradle task to be run.

I am using IntelliJ IDEA, and my initial thoughts are that it could be solved through plugins/scripts.

Can you suggest where to start? Should it be done through plugins? Maybe there are automatisation settings in IntelliJ that have file watchers or smth. Thanks.

I tried to search similiar plugins, and didn't find any. Read documentation for plugin creation, I think I can reach the result, but isn't it overhead?

Title: How to automate Gradle task running


问:
Can the default tvOS controller support also be used for the iOS and macOS version of an app/game?
I developed a small game for iOS, macOS and tvOS and just discovered that the tvOS version automatically supports for example the DualShock controller as it basically just uses the same inputs as on the Siri remote. (Moving left/right/up/down and pressing a button for selection) It's already pretty nice that this works just out of the box, but I was wondering, if this behaviour can also be mapped to the iOS/macOS version? Something like GCController -> Use the navigation of tvOS's focus engine.</p>


问:
Grafana loki - Bigtable - Requested column family not found
I installed Loki distributed helm chart in my GKE cluster which uses GCS and Bigtable.
When I check loki ingester pod, I have following error:

level=error ts=2023-01-06T13:01:59.107018356Z caller=flush.go:146 org_id=fake msg="failed to flush user" err="store put chunk: rpc error: code = NotFound desc = Error while mutating the row '08:fake:d19362:logs' (projects//instances/mybigtable/tables/loki_index_2766) : Requested column family not found.

I have followed the docs https://grafana.com/docs/loki/latest/upgrading/#240, accordingly prepared the configmap. Here is the file:

```<code>---
# Source: loki-distributed/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
data:
  config.yaml: |
    auth_enabled: false
    chunk_store_config:
      max_look_back_period: 672h
    compactor:
      retention_enabled: true
      shared_store: filesystem
    distributor:
      ring:
        kvstore:
          store: memberlist
    frontend:
      compress_responses: true
      log_queries_longer_than: 5s
      tail_proxy_url: http://loki-loki-distributed-querier:3100
    frontend_worker:
      frontend_address: loki-loki-distributed-query-frontend:9095
    ingester:
      chunk_block_size: 262144
      chunk_encoding: snappy
      chunk_idle_period: 30m
      chunk_retain_period: 1m
      lifecycler:
        ring:
          kvstore:
            store: memberlist
          replication_factor: 1
      max_transfer_retries: 0
      wal:
        dir: /var/loki/wal
    limits_config:
      enforce_metric_name: false
      retention_period: 30d
      max_cache_freshness_per_query: 10m
      reject_old_samples: true
      reject_old_samples_max_age: 168h
      split_queries_by_interval: 15m
    memberlist:
      join_members:
      - loki-loki-distributed-memberlist
    query_range:
      align_queries_with_step: true
      cache_results: true
      max_retries: 5
      results_cache:
        cache:
          enable_fifocache: true
          fifocache:
            max_size_items: 1024
            ttl: 24h
    ruler:
      alertmanager_url: https://alertmanager.xx
      external_url: https://alertmanager.xx
      ring:
        kvstore:
          store: memberlist
      rule_path: /tmp/loki/scratch
      storage:
        local:
          directory: /etc/loki/rules
        type: local
    runtime_config:
      file: /var/loki-distributed-runtime/runtime.yaml
    schema_config:
      configs:
      - from: 2023-01-01
        store: bigtable
        object_store: gcs
        schema: v12
        index:
          prefix: loki_index_
          period: 168h

    server:
      http_listen_port: 3100
    storage_config:
      gcs:
        bucket_name: gcs-logs
      bigtable:
        instance: loki-indexes
        project: myproject-id
      boltdb_shipper:
        active_index_directory: /loki/boltdb-shipper-active
        cache_location: /loki/boltdb-shipper-cache
        cache_ttl: 24h
        shared_store: gcs

        #active_index_directory: /var/loki/index
        #cache_location: /var/loki/cache
        #cache_ttl: 168h
        #shared_store: filesystem

      filesystem:
        directory: /var/loki/chunks
    table_manager:
      retention_deletes_enabled: true
      retention_period: 672h
</code>```

I am not able to push log index to bigtable. It seems table_manager needs to be updated but not sure with what?

The loki distributed service account is annotated with IAM service account, for workload identity rights to push towards object stores.

```<code>---
# Source: loki-distributed/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
  annotations:
    iam.gke.io/gcp-service-account: <iam-sa-account>@<project-id>.iam.gserviceaccount.com
automountServiceAccountToken: true
</code>```

Any suggestion?

Body:
I installed Loki distributed helm chart in my GKE cluster which uses GCS and Bigtable.
When I check loki ingester pod, I have following error:

level=error ts=2023-01-06T13:01:59.107018356Z caller=flush.go:146 org_id=fake msg="failed to flush user" err="store put chunk: rpc error: code = NotFound desc = Error while mutating the row '08:fake:d19362:logs' (projects//instances/mybigtable/tables/loki_index_2766) : Requested column family not found.

I have followed the docs https://grafana.com/docs/loki/latest/upgrading/#240, accordingly prepared the configmap. Here is the file:

---
# Source: loki-distributed/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
data:
  config.yaml: |
    auth_enabled: false
    chunk_store_config:
      max_look_back_period: 672h
    compactor:
      retention_enabled: true
      shared_store: filesystem
    distributor:
      ring:
        kvstore:
          store: memberlist
    frontend:
      compress_responses: true
      log_queries_longer_than: 5s
      tail_proxy_url: http://loki-loki-distributed-querier:3100
    frontend_worker:
      frontend_address: loki-loki-distributed-query-frontend:9095
    ingester:
      chunk_block_size: 262144
      chunk_encoding: snappy
      chunk_idle_period: 30m
      chunk_retain_period: 1m
      lifecycler:
        ring:
          kvstore:
            store: memberlist
          replication_factor: 1
      max_transfer_retries: 0
      wal:
        dir: /var/loki/wal
    limits_config:
      enforce_metric_name: false
      retention_period: 30d
      max_cache_freshness_per_query: 10m
      reject_old_samples: true
      reject_old_samples_max_age: 168h
      split_queries_by_interval: 15m
    memberlist:
      join_members:
      - loki-loki-distributed-memberlist
    query_range:
      align_queries_with_step: true
      cache_results: true
      max_retries: 5
      results_cache:
        cache:
          enable_fifocache: true
          fifocache:
            max_size_items: 1024
            ttl: 24h
    ruler:
      alertmanager_url: https://alertmanager.xx
      external_url: https://alertmanager.xx
      ring:
        kvstore:
          store: memberlist
      rule_path: /tmp/loki/scratch
      storage:
        local:
          directory: /etc/loki/rules
        type: local
    runtime_config:
      file: /var/loki-distributed-runtime/runtime.yaml
    schema_config:
      configs:
      - from: 2023-01-01
        store: bigtable
        object_store: gcs
        schema: v12
        index:
          prefix: loki_index_
          period: 168h

    server:
      http_listen_port: 3100
    storage_config:
      gcs:
        bucket_name: gcs-logs
      bigtable:
        instance: loki-indexes
        project: myproject-id
      boltdb_shipper:
        active_index_directory: /loki/boltdb-shipper-active
        cache_location: /loki/boltdb-shipper-cache
        cache_ttl: 24h
        shared_store: gcs

        #active_index_directory: /var/loki/index
        #cache_location: /var/loki/cache
        #cache_ttl: 168h
        #shared_store: filesystem

      filesystem:
        directory: /var/loki/chunks
    table_manager:
      retention_deletes_enabled: true
      retention_period: 672h

I am not able to push log index to bigtable. It seems table_manager needs to be updated but not sure with what?

The loki distributed service account is annotated with IAM service account, for workload identity rights to push towards object stores.

---
# Source: loki-distributed/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
  annotations:
    iam.gke.io/gcp-service-account: <iam-sa-account>@<project-id>.iam.gserviceaccount.com
automountServiceAccountToken: true

Any suggestion?


问:
Jquery problem when adding multiple questions and its options - Clone
I wrote the following code that should:

Add Questions: As displayed in the image below should clone whole #1

Add options: As displayed in the image below should clone the whole #2

Somehow it's not working as expected so the additional options button disappears from the first question when you click on add questions button.

 // add row
  $("#addRow").click(function() {
    var html = "";
    html += '
';
    html += '
';
    html += 'Enter Question';
    html += '<textarea class="form-control" id="question" rows="3"></textarea>';
    html += '
';
    html += '
';
    html += '<input type="text" name="options[]" class="form-control m-input" placeholder="Enter Option" autocomplete="off">';
    html += 'OR - Select Options';
    html += '<select class="form-control" id="select-options">';
    html += '<option value="">Select an option</option>';
    html += '<option value="strongly-agree">Strongly Agree</option>';
    html += '<option value="agree">Agree</option>';
    html += '<option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>';
    html += '<option value="disagree">Disagree</option>';
    html += '<option value="strongly-disagree">Strongly Disagree</option>';
    html += '<option value="not-applicable">Not Applicable</option>';
    html += '</select>';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
    html += '
';
    html += '
';

    $('#newRow').append(html);
  });

  // add row
  $("#addOptions").click(function() {
    var html = "";
    html += '
';
    html += '
';
    html += '<input type="text" name="options[]" class="form-control m-input" placeholder="Enter Option" autocomplete="off">';
    html += 'OR - Select Options';
    html += '<select class="form-control" id="select-options">';
    html += '<option value="">Select an option</option>';
    html += '<option value="strongly-agree">Strongly Agree</option>';
    html += '<option value="agree">Agree</option>';
    html += '<option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>';
    html += '<option value="disagree">Disagree</option>';
    html += '<option value="strongly-disagree">Strongly Disagree</option>';
    html += '<option value="not-applicable">Not Applicable</option>';
    html += '</select>';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
    html += '
';
    html += '
';

    $('#newQuestion').append(html);
  });

  // remove row
  $(document).on('click', '#removeRow', function() {
    $(this).closest('#inputFormRow').remove();
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Popup Button -->
<label for="survey-name">Add Question below</label>
  <form method="post" action="">
    <div class="row">
      <div class="col-lg-12">
      <!-- Question -->
        <div class="form-group">
          <label for="question">Enter Question</label>
          <textarea class="form-control" id="question" rows="3"></textarea>
        </div>
        <!-- Options -->
        <div id="inputFormRow">
          <div class="input-group mb-3">

            <input type="text" name="options[]" class="form-control m-input" placeholder="Enter options" autocomplete="off">
            <label for="select-options"> -OR - Select an option</label>
            <select class="form-control" id="select-options">
            <option value="0">Select an option</option>
            <option value="strongly-agree">Strongly Agree</option>
            <option value="agree">Agree</option>
            <option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>
            <option value="disagree">Disagree</option>
            <option value="strongly-disagree">Strongly Disagree</option>
            <option value="not-applicable">Not Applicable</option>
            </select>
            <div class="input-group-append">
              <button id="removeRow" type="button" class="btn btn-danger">Remove</button>
            </div>
          </div>
        </div>

        <div id="newRow"></div>
        <button id="addOptions" type="button" class="btn btn-info">Add Options</button><br>
        <div id="newQuestion"></div>
        <button id="addRow" type="button" class="btn btn-info">Add Questions</button>
      </div>
    </div>
  </form>
</div></code>```

Body:
I wrote the following code that should:

Add Questions: As displayed in the image below should clone whole #1

Add options: As displayed in the image below should clone the whole #2

Somehow it's not working as expected so the additional options button disappears from the first question when you click on add questions button.

 // add row
  $("#addRow").click(function() {
    var html = "";
    html += '
';
    html += '
';
    html += 'Enter Question';
    html += '<textarea class="form-control" id="question" rows="3"></textarea>';
    html += '
';
    html += '
';
    html += '<input type="text" name="options[]" class="form-control m-input" placeholder="Enter Option" autocomplete="off">';
    html += 'OR - Select Options';
    html += '<select class="form-control" id="select-options">';
    html += '<option value="">Select an option</option>';
    html += '<option value="strongly-agree">Strongly Agree</option>';
    html += '<option value="agree">Agree</option>';
    html += '<option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>';
    html += '<option value="disagree">Disagree</option>';
    html += '<option value="strongly-disagree">Strongly Disagree</option>';
    html += '<option value="not-applicable">Not Applicable</option>';
    html += '</select>';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
    html += '
';
    html += '
';

    $('#newRow').append(html);
  });

  // add row
  $("#addOptions").click(function() {
    var html = "";
    html += '
';
    html += '
';
    html += '<input type="text" name="options[]" class="form-control m-input" placeholder="Enter Option" autocomplete="off">';
    html += 'OR - Select Options';
    html += '<select class="form-control" id="select-options">';
    html += '<option value="">Select an option</option>';
    html += '<option value="strongly-agree">Strongly Agree</option>';
    html += '<option value="agree">Agree</option>';
    html += '<option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>';
    html += '<option value="disagree">Disagree</option>';
    html += '<option value="strongly-disagree">Strongly Disagree</option>';
    html += '<option value="not-applicable">Not Applicable</option>';
    html += '</select>';
    html += '
';
    html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
    html += '
';
    html += '
';

    $('#newQuestion').append(html);
  });

  // remove row
  $(document).on('click', '#removeRow', function() {
    $(this).closest('#inputFormRow').remove();
  });

Add Question below
  <form method="post" action="">

          Enter Question
          <textarea class="form-control" id="question" rows="3"></textarea>

            <input type="text" name="options[]" class="form-control m-input" placeholder="Enter options" autocomplete="off">
             -OR - Select an option
            <select class="form-control" id="select-options">
            <option value="0">Select an option</option>
            <option value="strongly-agree">Strongly Agree</option>
            <option value="agree">Agree</option>
            <option value="neither-agree-nor-disagree">Neither Agree nor Disagree</option>
            <option value="disagree">Disagree</option>
            <option value="strongly-disagree">Strongly Disagree</option>
            <option value="not-applicable">Not Applicable</option>
            </select>

              <button id="removeRow" type="button" class="btn btn-danger">Remove</button>

        <button id="addOptions" type="button" class="btn btn-info">Add Options</button>

        <button id="addRow" type="button" class="btn btn-info">Add Questions</button>

  </form>


问:
Firebase Database Structured Query
I am running this structured query and it keeps erroring, I can't figure out what's wrong?

```<code>{

"orderBy": [{
        "field": {
            "fieldPath": "firstname"
        },
        "direction": "DESCENDING"
    }]
 "where": {
        "fieldFilter": {
            "field": {
                "fieldPath": "MarketingAcceptance"
            },
            "op": "EQUAL",
            "value": {
                "stringValue": "true"
            }
        }
    }
}
</code>```

I would like it to orderby and then only pull the documents that have MarketingAcceptance "true"

Title: Firebase Database Structured Query

Body:
I am running this structured query and it keeps erroring, I can't figure out what's wrong?

{

"orderBy": [{
        "field": {
            "fieldPath": "firstname"
        },
        "direction": "DESCENDING"
    }]
 "where": {
        "fieldFilter": {
            "field": {
                "fieldPath": "MarketingAcceptance"
            },
            "op": "EQUAL",
            "value": {
                "stringValue": "true"
            }
        }
    }
}

I would like it to orderby and then only pull the documents that have MarketingAcceptance "true"


问:
draw an .obj file offscreen under android with processing
I am trying to draw an .obj file offscreen under Android.
The image should then be passed to OpenCV for further use as a matrix.

In 2D the whole thing already works without problems.

public class ObjDrawer extends PApplet {

    PGraphics buffer;
    PShape obj;
    int width;
    int height;

    public ObjDrawer(int width, int height) {
        this.width = width;
        this.height = height;
        setup();
    }

    @Override
    public void setup() {
        buffer = createGraphics(this.width, this.height, P3D);
        //obj = loadShape("Wuerfel_40mm.obj");
        noLoop();
    }

    public Mat testDraw() {
        buffer.beginDraw();
        buffer.background(255);
        buffer.ellipse(200, 200, 100, 100);
        //buffer.shape(obj);
        buffer.endDraw();
        return toMat(buffer.get());
    }

    Mat toMat(PImage image) {
        //source: https://gist.github.com/Spaxe/3543f0005e9f8f3c4dc5
        int w = image.width;
        int h = image.height;

        Mat mat = new Mat(h, w, CvType.CV_8UC4);
        byte[] data8 = new byte[w * h * 4];
        int[] data32 = new int[w * h];
        arrayCopy(image.pixels, data32);
        ByteBuffer bBuf = ByteBuffer.allocate(w * h * 4);
        IntBuffer iBuf = bBuf.asIntBuffer();
        iBuf.put(data32);
        bBuf.get(data8);
        mat.put(0, 0, data8);
        return mat;
    }

}
```
<p>When using 3D, I now get the following error message:</p>
```java.lang.NullPointerException: Attempt to invoke virtual method 'boolean processing.core.PGraphics.isGL()' on a null object reference
    at processing.core.PApplet.makeGraphics(PApplet.java:1584)
    at processing.core.PApplet.createGraphics(PApplet.java:1568)
    at Analyzer.ObjDrawer.setup(ObjDrawer.java:52)
    at Analyzer.ObjDrawer.<init>(ObjDrawer.java:45)
    at com.quickbirdstudios.opencvexample.MainActivity$cvCameraViewListener$1.onCameraFrame(MainActivity.kt:75)
    at org.opencv.android.CameraBridgeViewBase.deliverAndDrawFrame(CameraBridgeViewBase.java:392)
    at org.opencv.android.JavaCameraView$CameraWorker.run(JavaCameraView.java:373)
    at java.lang.Thread.run(Thread.java:920)
```

In my research I read about a3d, this is missing for me. Since all the stuff I found regarding a3d was about 10 years old: has anything changed in this regard or has it been replaced or do I need to include this separately?

I have included Processing as in the tutorial on https://android.processing.org/tutorials/android_studio/index.html

integrated. I use Android Mode for Processing 3 4.3.0, because the mode manager in Processing 4 is currently broken.

many thanks in advance!

Body:
I am trying to draw an .obj file offscreen under Android.
The image should then be passed to OpenCV for further use as a matrix.

In 2D the whole thing already works without problems.

public class ObjDrawer extends PApplet {

    PGraphics buffer;
    PShape obj;
    int width;
    int height;

    public ObjDrawer(int width, int height) {
        this.width = width;
        this.height = height;
        setup();
    }

    @Override
    public void setup() {
        buffer = createGraphics(this.width, this.height, P3D);
        //obj = loadShape("Wuerfel_40mm.obj");
        noLoop();
    }

    public Mat testDraw() {
        buffer.beginDraw();
        buffer.background(255);
        buffer.ellipse(200, 200, 100, 100);
        //buffer.shape(obj);
        buffer.endDraw();
        return toMat(buffer.get());
    }

    Mat toMat(PImage image) {
        //source: https://gist.github.com/Spaxe/3543f0005e9f8f3c4dc5
        int w = image.width;
        int h = image.height;

        Mat mat = new Mat(h, w, CvType.CV_8UC4);
        byte[] data8 = new byte[w * h * 4];
        int[] data32 = new int[w * h];
        arrayCopy(image.pixels, data32);
        ByteBuffer bBuf = ByteBuffer.allocate(w * h * 4);
        IntBuffer iBuf = bBuf.asIntBuffer();
        iBuf.put(data32);
        bBuf.get(data8);
        mat.put(0, 0, data8);
        return mat;
    }

}

When using 3D, I now get the following error message:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean processing.core.PGraphics.isGL()' on a null object reference
    at processing.core.PApplet.makeGraphics(PApplet.java:1584)
    at processing.core.PApplet.createGraphics(PApplet.java:1568)
    at Analyzer.ObjDrawer.setup(ObjDrawer.java:52)
    at Analyzer.ObjDrawer.<init>(ObjDrawer.java:45)
    at com.quickbirdstudios.opencvexample.MainActivity$cvCameraViewListener$1.onCameraFrame(MainActivity.kt:75)
    at org.opencv.android.CameraBridgeViewBase.deliverAndDrawFrame(CameraBridgeViewBase.java:392)
    at org.opencv.android.JavaCameraView$CameraWorker.run(JavaCameraView.java:373)
    at java.lang.Thread.run(Thread.java:920)

In my research I read about a3d, this is missing for me. Since all the stuff I found regarding a3d was about 10 years old: has anything changed in this regard or has it been replaced or do I need to include this separately?

I have included Processing as in the tutorial on https://android.processing.org/tutorials/android_studio/index.html

integrated. I use Android Mode for Processing 3 4.3.0, because the mode manager in Processing 4 is currently broken.

many thanks in advance!


问:
How to fix "borrowed value does not live long enough" issue in rust
I have been writing a brainf*ck interpreter in rust, and was stupid enough to not use a lexer.
I use recursion to tackle loops.

let mut ret = exec(i, file, tape, ptr);
i = &(ret.0);
file = &mut (ret.1);
tape = &mut (ret.2);
ptr = &(ret.3);
...
return (nw_i, (*file).to_owned(), (*tape).to_owned(), nw_ptr);
```
<p>This is the function declaration:</p>
<pre class="lang-rust prettyprint-override"><code>pub fn exec(mut i: &usize, mut file: &mut Vec<u8>, mut tape: &mut Vec<i32>, mut ptr: &usize) -> (usize, Vec<u8>, Vec<i32>, usize) {
</code>```

I get this error:

error[E0597]: `ret.0` does not live long enough
  --> src/lib.rs:19:10
   |
4  |     pub fn exec(mut i: &usize, mut file: &mut Vec<u8>, tape: &mut Vec<i32>, mut ptr: &usize) -> (usize, Vec<u8>, Vec<i32>, usize) {
   |                        - let's call the lifetime of this reference `'1`
...
19 |                     i = &(ret.0);
   |                     ----^^^^^^^^
   |                     |   |
   |                     |   borrowed value does not live long enough
   |                     assignment requires that `ret.0` is borrowed for `'1`
...
23 |                 }
   |
```
<p>How do i make the borrowed value live long enough for me to copy it.</p>
<p>Full code:</p>
<pre class="lang-rust prettyprint-override"><code>pub fn exec(
    mut i: &usize,
    mut file: &mut Vec<u8>,
    mut tape: &mut Vec<i32>,
    mut ptr: &usize,
) -> (usize, Vec<u8>, Vec<i32>, usize) {
    let char = file[*i];
    let mut nw_ptr: usize = *ptr;
    let mut nw_i: usize = *i;
    if char == ("[".as_bytes()[0]) {
        let mut j = 1;
        let mut lcl_char = file[*i];
        while tape[*ptr] != 0 {
            while j <= 0 {
                if lcl_char == ("]".as_bytes()[0]) {
                    j = j - 1;
                } else if lcl_char == ("]".as_bytes()[0]) {
                    j = j + 1;
                }
                let mut ret = exec(i, file, tape, ptr);
                i = &(ret.0);
                file = &mut (ret.1);
                tape = &mut (ret.2);
                ptr = &(ret.3);
            }
        }
    } else if char == (">".as_bytes()[0]) {
        nw_ptr = ptr + 1;
        if ptr > &(tape.len() - 1) {
            tape.push(0);
        }
    } else if char == ("<".as_bytes()[0]) {
        nw_ptr = ptr - 1;
    } else if char == (".".as_bytes()[0]) {
        let crnt = tape[*ptr];
        let out = ascii_converter::decimals_to_string(&vec![crnt.try_into().unwrap()]).unwrap();
        println!("{}", out);
    } else if char == ("+".as_bytes()[0]) {
        tape[*ptr] += 1;
    } else if char == ("-".as_bytes()[0]) {
        tape[*ptr] = tape[*ptr] - 1;
    }
    nw_i = i + 1;
    (nw_i, (*file).to_owned(), (*tape).to_owned(), nw_ptr)
}

</code>```

I already tried dereferencing it as i saw people online using it:

let mut *ret = exec(i, file, tape, ptr);
i = &(ret.0);
file = &mut (ret.1);
tape = &mut (ret.2);
ptr = &(ret.3);
```
<p>But this gave this error:</p>
<pre class="lang-none prettyprint-override"><code>error: expected identifier, found `*`
  --> src/lib.rs:18:13
   |
18 |                 let mut *ret = exec(i, file, tape, ptr);
   |                         ^ expected identifier
</code>```

Body:
I have been writing a brainf*ck interpreter in rust, and was stupid enough to not use a lexer.
I use recursion to tackle loops.

let mut ret = exec(i, file, tape, ptr);
i = &(ret.0);
file = &mut (ret.1);
tape = &mut (ret.2);
ptr = &(ret.3);
...
return (nw_i, (*file).to_owned(), (*tape).to_owned(), nw_ptr);

This is the function declaration:

pub fn exec(mut i: &usize, mut file: &mut Vec<u8>, mut tape: &mut Vec<i32>, mut ptr: &usize) -> (usize, Vec<u8>, Vec<i32>, usize) {

I get this error:

error[E0597]: `ret.0` does not live long enough
  --> src/lib.rs:19:10
   |
4  |     pub fn exec(mut i: &usize, mut file: &mut Vec<u8>, tape: &mut Vec<i32>, mut ptr: &usize) -> (usize, Vec<u8>, Vec<i32>, usize) {
   |                        - let's call the lifetime of this reference `'1`
...
19 |                     i = &(ret.0);
   |                     ----^^^^^^^^
   |                     |   |
   |                     |   borrowed value does not live long enough
   |                     assignment requires that `ret.0` is borrowed for `'1`
...
23 |                 }
   |

How do i make the borrowed value live long enough for me to copy it.

Full code:

pub fn exec(
    mut i: &usize,
    mut file: &mut Vec<u8>,
    mut tape: &mut Vec<i32>,
    mut ptr: &usize,
) -> (usize, Vec<u8>, Vec<i32>, usize) {
    let char = file[*i];
    let mut nw_ptr: usize = *ptr;
    let mut nw_i: usize = *i;
    if char == ("[".as_bytes()[0]) {
        let mut j = 1;
        let mut lcl_char = file[*i];
        while tape[*ptr] != 0 {
            while j <= 0 {
                if lcl_char == ("]".as_bytes()[0]) {
                    j = j - 1;
                } else if lcl_char == ("]".as_bytes()[0]) {
                    j = j + 1;
                }
                let mut ret = exec(i, file, tape, ptr);
                i = &(ret.0);
                file = &mut (ret.1);
                tape = &mut (ret.2);
                ptr = &(ret.3);
            }
        }
    } else if char == (">".as_bytes()[0]) {
        nw_ptr = ptr + 1;
        if ptr > &(tape.len() - 1) {
            tape.push(0);
        }
    } else if char == ("<".as_bytes()[0]) {
        nw_ptr = ptr - 1;
    } else if char == (".".as_bytes()[0]) {
        let crnt = tape[*ptr];
        let out = ascii_converter::decimals_to_string(&vec![crnt.try_into().unwrap()]).unwrap();
        println!("{}", out);
    } else if char == ("+".as_bytes()[0]) {
        tape[*ptr] += 1;
    } else if char == ("-".as_bytes()[0]) {
        tape[*ptr] = tape[*ptr] - 1;
    }
    nw_i = i + 1;
    (nw_i, (*file).to_owned(), (*tape).to_owned(), nw_ptr)
}

I already tried dereferencing it as i saw people online using it:

let mut *ret = exec(i, file, tape, ptr);
i = &(ret.0);
file = &mut (ret.1);
tape = &mut (ret.2);
ptr = &(ret.3);

But this gave this error:

error: expected identifier, found `*`
  --> src/lib.rs:18:13
   |
18 |                 let mut *ret = exec(i, file, tape, ptr);
   |                         ^ expected identifier


问:
Environmet variables set to root container user instead of postgres container user by default
Everytime I start a new instance of a container from the PostgreSQL docker hub's official image, the environment variables are defined and exported in the root user of the shell created by the container instead of being defined and export in the postgres user.

For example, when I input the env command through root user:

```<code>PWD=/
HOME=/root
LANG=en_US.utf8
GOSU_VERSION=1.14
PG_MAJOR=15
PG_VERSION=15.1-1.pgdg110+1
TERM=xterm
SHLVL=1
POSTGRES_USER=postgres
PGDATA=/var/lib/postgresql/data
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/15/bin
_=/usr/bin/env
</code>```

Using the same command but through postgres user:

```<code>SHELL=/bin/bash
PWD=/var/lib/postgresql/data
LOGNAME=postgres
HOME=/var/lib/postgresql
TERM=xterm
USER=postgres
SHLVL=1
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
MAIL=/var/mail/postgres
OLDPWD=/var/lib/postgresql/data/base
_=/usr/bin/env
</code>```

Why is this happening? I've read the documentation but I found nothing. Is there a way to set these variables in postgres user instead of root by default?

Body:
Everytime I start a new instance of a container from the PostgreSQL docker hub's official image, the environment variables are defined and exported in the root user of the shell created by the container instead of being defined and export in the postgres user.

For example, when I input the env command through root user:

PWD=/
HOME=/root
LANG=en_US.utf8
GOSU_VERSION=1.14
PG_MAJOR=15
PG_VERSION=15.1-1.pgdg110+1
TERM=xterm
SHLVL=1
POSTGRES_USER=postgres
PGDATA=/var/lib/postgresql/data
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/15/bin
_=/usr/bin/env

Using the same command but through postgres user:

SHELL=/bin/bash
PWD=/var/lib/postgresql/data
LOGNAME=postgres
HOME=/var/lib/postgresql
TERM=xterm
USER=postgres
SHLVL=1
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
MAIL=/var/mail/postgres
OLDPWD=/var/lib/postgresql/data/base
_=/usr/bin/env

Why is this happening? I've read the documentation but I found nothing. Is there a way to set these variables in postgres user instead of root by default?


问:
How to change a sticky element's height dynamically?
I have two divs, one is a sticky element and the other is a footer at the bottom. The site has enough height so that it's scrollable and the footer is not visible intially. What I need to achieve is, when I scroll down and the sticky element meets the footer, the height of the sticky element should be dynamically reduced in such a way that it still touches the footer but doesn't cover it up. When the sticky element's height gets too small and the content overflows, a scrollbar should appear. Is it possible to achieve this with pure CSS?

This is my current code:
https://jsfiddle.net/co7dty0p/


问:
Getting location permssion in Android WebView
I have a react web app, and in one of the pages I need to get the geo-location from the user. If user opens the website in the browser directly, then user is able to provide the geo-location permission.

However, there is a scenario where the link is openeded from an App. In this case, the page is opended in the Webview of the app. Although the user is getting a prompt to enable location permission, but fetching the location is failing. The only way location works, is if the parent app (from where the website was opened), is given the location permission (from Settings).

Is thre any workaround for this? Is there a way to prompt the location permission for the parent app from my site in the WebView?


问:
How can i make prettier format jsx attribute indentation same level as their tag?
I want to make my jsx attributes indentation is same level as their tag.
My current prettier result:

```<code><Form.Item
    label="Contact Person Name"
    name={["metadata", "cpName"]}
>
    <Input />
</Form.Item>
</code>```

I want it look like this:

```<code><Form.Item
label="Contact Person Name"
name={["metadata", "cpName"]}
>
    <Input />
</Form.Item>
</code>```

it is possible?

I've alredy try several config from prettier like: proseWrap, jsxBracketSameLine, jsxBracketSpacing.. It is not what i need.
My current prettier config:

```<code>module.exports = {
    trailingComma: "es5",
    tabWidth: 4,
    useTabs: true,
    singleAttributePerLine: true,
    resolveGlobalModules: true,
    printWidth: 120,
};

</code>```

Body:
I want to make my jsx attributes indentation is same level as their tag.
My current prettier result:

<Form.Item
    label="Contact Person Name"
    name={["metadata", "cpName"]}
>
    <Input />
</Form.Item>

I want it look like this:

<Form.Item
label="Contact Person Name"
name={["metadata", "cpName"]}
>
    <Input />
</Form.Item>

it is possible?

I've alredy try several config from prettier like: proseWrap, jsxBracketSameLine, jsxBracketSpacing.. It is not what i need.
My current prettier config:

module.exports = {
    trailingComma: "es5",
    tabWidth: 4,
    useTabs: true,
    singleAttributePerLine: true,
    resolveGlobalModules: true,
    printWidth: 120,
};


问:
How can I highlight specific keywords on every appended paragraph?
enter image description here

```<code>     $(` <tr class="key-empty" id="${id}" >
                                            <td   colspan="3" class="text-left keyword-td " >
                                              <div class="td_div">
                                              ${sentence.map((val, i) => `<div class="d-flex shadow_"><i class="fa fa-circle mt-1 " style="font-size: 10px;"></i>    <span class="m-0 text-gray font-14 fw-400 keyword-para" id="key_${i}" > ${val} </span></div>`).join("<br>")
                              }
                                              </div>
                                            </td>
                                 </tr>
                                    `).insertAfter(row);
                                   var search = keyword;

                                    $(".keyword-para:contains("+search+")").each(function () {
                                var regex3 = new RegExp("([' ]|^)"+search+"(?=[ ]|$|,|')", 'g');

                              $(this).html($(this).text().replaceAll(regex3,  `<span class='text-red'> ${search} </span>`));

                            });
</code>```

I wat to change color of all keywords that is appear on text
In jquery on api response I append the paragraphs, I want to highlight specific  keyword on every appended paragraph , but it can not work on all keyword what mistake i did on it

Body:
enter image description here

     $(`

                                              ${sentence.map((val, i) => `<div class="d-flex shadow_"><i class="fa fa-circle mt-1 " style="font-size: 10px;"></i>    <span class="m-0 text-gray font-14 fw-400 keyword-para" id="key_${i}" > ${val} </span></div>`).join("
")
                              }

                                    `).insertAfter(row);
                                   var search = keyword;

                                    $(".keyword-para:contains("+search+")").each(function () {
                                var regex3 = new RegExp("([' ]|^)"+search+"(?=[ ]|$|,|')", 'g');

                              $(this).html($(this).text().replaceAll(regex3,  `<span class='text-red'> ${search} </span>`));

                            });

I wat to change color of all keywords that is appear on text
In jquery on api response I append the paragraphs, I want to highlight specific  keyword on every appended paragraph , but it can not work on all keyword what mistake i did on it


问:
AttributeError: text in django
This error appears to me, and I don't know why

I am programming a web-application using Django framework that uses the API from OpenAI ChatGPT-3
and this is my code:-

in views:

```<code>from django.shortcuts import render
import openai

# Create your views here.

def chatbot_view(request):
    # Get the user's input from the request
    user_input = request.POST.get("user_input")
    # Use the OpenAI library to generate a response
    openai.api_key = "MY-API"
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=user_input,
        max_tokens=1024,
        temperature=0.7,
    )
    chatbot_response = response.text

    # Render the response in a template
    return render(request, 'chat/index.html', {"chatbot_response": chatbot_response})
</code>```

in url for app:

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.chatbot_view, name="chatbot")
]

</code>```

in urls for project:

```<code>from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('chat.url'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

in HTMl:

```<code>{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <title>Chat-Bot</title>
</head>
<body>
    <section>
        <p>{{ chatbot_response }}</p>
    </section>
    <form action="{% url 'chatbot' %} "method="post">
        {% csrf_token %}
        <input required class="text" type="text" name="user_input" placeholder="How Can I Help You?">
        <p>THIS WEBSITE MADE BY <a class="link" href="https://www.facebook.com/samuel.kamal.56" target="_blank">SAMUEL KAMAL</a></p>
    </form>
</body>
</html>
</code>```

but it's not working and give me this error:

but if I remove .text from views in this line of code:
chatbot_response = response.text
it works but not correctly this is an image for what I mean:

and the response be inside it

Title: AttributeError: text in django

Body:
This error appears to me, and I don't know why

I am programming a web-application using Django framework that uses the API from OpenAI ChatGPT-3
and this is my code:-

in views:

from django.shortcuts import render
import openai

# Create your views here.

def chatbot_view(request):
    # Get the user's input from the request
    user_input = request.POST.get("user_input")
    # Use the OpenAI library to generate a response
    openai.api_key = "MY-API"
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=user_input,
        max_tokens=1024,
        temperature=0.7,
    )
    chatbot_response = response.text

    # Render the response in a template
    return render(request, 'chat/index.html', {"chatbot_response": chatbot_response})

in url for app:

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.chatbot_view, name="chatbot")
]

in urls for project:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('chat.url'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

in HTMl:

{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <title>Chat-Bot</title>

{{ chatbot_response }}

    <form action="{% url 'chatbot' %} "method="post">
        {% csrf_token %}
        <input required class="text" type="text" name="user_input" placeholder="How Can I Help You?">

THIS WEBSITE MADE BY SAMUEL KAMAL

    </form>

but it's not working and give me this error:

but if I remove .text from views in this line of code:
chatbot_response = response.text
it works but not correctly this is an image for what I mean:

and the response be inside it