问:
Razor Views with same relative path within class libraries are picked up wrongly
I have a project which consists of a ASP.NET Core MVC project and two Razor Class Library projects being referenced by the MVC project.

Everything works fine with regard to Controllers and Views.

However, if two Views have the same relative path (e.g. Views/Home/Index.cshtml, it happens that the View from the wrong library gets picked up and rendered.

How can this be avoided (aside from having a unique relative path)?


来源: stackexchange

问:
Graphql - what constitutes an operation having a unique name?
I am having trouble making my code generator run. The reason given is that Not all operations have an unique name: AllIssueGroups.

I am not clear on what an "operation" is exactly.

I have a single issueGroup.resolver, a single issueGroup.service and then more than one component in the front end that tries to read from AllIssueGroups, using the following gql:

```<code>const _ = gql`
  query AllIssueGroups {
      allIssueGroups {
        id
        title
        description
        issues
      }
    }
</code>```

In each react component, I only define this const once, but I'm wondering if graphql thinks each of those is an "operation".

My resolver has:

```<code>@Query(() => [IssueGroup])
        async allIssueGroups() {
            return await this.issueGroupService.getAllIssueGroups()
        }

</code>```

My service has:

```<code>async getAllIssueGroups() {
    return (await prisma.issueGroup.findMany({orderBy: {title: 'asc'}}))
  }
</code>```

Each of the service and resolver is defined once, only.

Where can I find the definition of "operation" for graphql's purposes? I can't figure out why it thinks it is not uniquely defined.

In my graphql.tsx, the AllIssueGroup entries are not duplicated.

How can I find what is causing the codegen to think that it is not uniquely named?

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble making my code generator run. The reason given is that Not all operations have an unique name: AllIssueGroups.

I am not clear on what an "operation" is exactly.

I have a single issueGroup.resolver, a single issueGroup.service and then more than one component in the front end that tries to read from AllIssueGroups, using the following gql:

const _ = gql`
  query AllIssueGroups {
      allIssueGroups {
        id
        title
        description
        issues
      }
    }

In each react component, I only define this const once, but I'm wondering if graphql thinks each of those is an "operation".

My resolver has:

@Query(() => [IssueGroup])
        async allIssueGroups() {
            return await this.issueGroupService.getAllIssueGroups()
        }

My service has:

async getAllIssueGroups() {
    return (await prisma.issueGroup.findMany({orderBy: {title: 'asc'}}))
  }

Each of the service and resolver is defined once, only.

Where can I find the definition of "operation" for graphql's purposes? I can't figure out why it thinks it is not uniquely defined.

In my graphql.tsx, the AllIssueGroup entries are not duplicated.

How can I find what is causing the codegen to think that it is not uniquely named?


问:
Inconsistent night mode value depending on the source
Currently working on an issue in our application where a dependency is reading the state of night mode from the Activity (i.e. activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK). The Activity in question is configured with android:configChanges="uiMode" and I am seeing that the state of night mode never changes from light when reading from the Activity.

However the value is correct when reading from the Application (i.e. activity.getApplicationContext().getResources().getConfiguration().uiMode) and it is also correct in the Configuration object passed to onConfigurationChanged.

Unfortunately since its a dependency that is using the night mode value fixing my issue by simply using either of the objects that give the expected value isn't the simplest solution, so I would prefer to fix the root cause. Kind of at a loss for what is going wrong and I haven't been able to find why these values are differing.


问:
Use Dependabot to check Dependencies in Bash scripts and Dockerfiles
I would like some notifications from Dependabot when new versions are available. These are my two scenarios:

#1 I'm starting a docker container in a bash script like this.

local DOCKER_IMAGE="hashcorp/terraform:1.3.6"

docker run --rm \
  --volume /etc/passwd:/etc/passwd:ro \
  --volume /etc/group:/etc/group:ro \
  --user "$(id -u):$(id -g)" \
  --volume /etc/timezone:/etc/timezone:ro \
  --volume /etc/localtime:/etc/localtime:ro \
  --volume "$(pwd):$(pwd)" \
  --workdir "$(pwd)" \
  --env "GITHUB_TOKEN=$TOKEN" \
  --env "TF_VAR_bw_client_id=$BW_CLIENT_ID" \
  --env "TF_VAR_bw_client_secret=$BW_CLIENT_SECRET" \
  --env "TF_VAR_bw_password=$BW_MASTER_PASS" \
  "$DOCKER_IMAGE" "$@"
```
<p>For other Dependencies like Docker Images I use Dependabot to raise a PR when I should update my base image. Is there a way to have Dependabot inspect bash scripts like the above snippet as well? I'd like a notification when there is a new terraform version.</p>
<p><strong>#2 I'm installing Bitwarden CLI into a custom terraform image (needed for the Bitwarden Provider</strong>. This works fine. But since I pin the Bitwarden CLI version in my Dockerfile I would like Dependabot to raise PR for the Bitwarden CLI as well.</p>
```FROM hashicorp/terraform:1.3.6
LABEL maintainer="sebastian@sommerfeld.io"

# Install basics
RUN apk update \
    && apk --no-cache add curl=7.86.0-r1 \
    && apk --no-cache add unzip=6.0-r13

# Install Bitwarden CLI + dependencies
ARG BW_VERSION="2022.11.0"
RUN apk --no-cache add libc6-compat=1.2.3-r4 \
    && apk --no-cache add gcompat=1.1.0-r0 \
    && apk --no-cache add libgcc=12.2.1_git20220924-r4 \
    && apk --no-cache add libstdc++=12.2.1_git20220924-r4 \
    && rm -rf /var/cache/apk/* \
    && curl -sL https://github.com/bitwarden/clients/releases/download/cli-v${BW_VERSION}/bw-linux-${BW_VERSION}.zip -o bw.zip \
    && unzip bw.zip \
    && chmod +rx bw \
    && rm bw.zip \
    && mv bw /usr/local/bin
```

Is it possible to use Dependabot for these scenarios as well?

Body:
I would like some notifications from Dependabot when new versions are available. These are my two scenarios:

#1 I'm starting a docker container in a bash script like this.

local DOCKER_IMAGE="hashcorp/terraform:1.3.6"

docker run --rm \
  --volume /etc/passwd:/etc/passwd:ro \
  --volume /etc/group:/etc/group:ro \
  --user "$(id -u):$(id -g)" \
  --volume /etc/timezone:/etc/timezone:ro \
  --volume /etc/localtime:/etc/localtime:ro \
  --volume "$(pwd):$(pwd)" \
  --workdir "$(pwd)" \
  --env "GITHUB_TOKEN=$TOKEN" \
  --env "TF_VAR_bw_client_id=$BW_CLIENT_ID" \
  --env "TF_VAR_bw_client_secret=$BW_CLIENT_SECRET" \
  --env "TF_VAR_bw_password=$BW_MASTER_PASS" \
  "$DOCKER_IMAGE" "$@"

For other Dependencies like Docker Images I use Dependabot to raise a PR when I should update my base image. Is there a way to have Dependabot inspect bash scripts like the above snippet as well? I'd like a notification when there is a new terraform version.

#2 I'm installing Bitwarden CLI into a custom terraform image (needed for the Bitwarden Provider. This works fine. But since I pin the Bitwarden CLI version in my Dockerfile I would like Dependabot to raise PR for the Bitwarden CLI as well.

FROM hashicorp/terraform:1.3.6
LABEL maintainer="sebastian@sommerfeld.io"

# Install basics
RUN apk update \
    && apk --no-cache add curl=7.86.0-r1 \
    && apk --no-cache add unzip=6.0-r13

# Install Bitwarden CLI + dependencies
ARG BW_VERSION="2022.11.0"
RUN apk --no-cache add libc6-compat=1.2.3-r4 \
    && apk --no-cache add gcompat=1.1.0-r0 \
    && apk --no-cache add libgcc=12.2.1_git20220924-r4 \
    && apk --no-cache add libstdc++=12.2.1_git20220924-r4 \
    && rm -rf /var/cache/apk/* \
    && curl -sL https://github.com/bitwarden/clients/releases/download/cli-v${BW_VERSION}/bw-linux-${BW_VERSION}.zip -o bw.zip \
    && unzip bw.zip \
    && chmod +rx bw \
    && rm bw.zip \
    && mv bw /usr/local/bin

Is it possible to use Dependabot for these scenarios as well?


问:
Setup logging of Celery in Django correctly - how?
Setting up celery on our production server seems to be more complicated than it should be - and the problem is logging.
Our setup is like this:

Server is Ubuntu 20.04.5 LTS

We run Django 3.2.8 in it's own user and group named "django"

The Celery process also has it's own user and group named "celery".

Celery is set up as a service and logs to /var/log/celery

In celery.py we have set djangoConf pointing to the main settings.py

On startup Celery tries to touch a django-logfile and - missing the permissions to do so - returns an error:

```<code>Dec 16 10:57:27 h2989788 celery[128418]: Usage: celery [OPTIONS] COMMAND [ARGS]...
Dec 16 10:57:27 h2989788 celery[128418]: Try 'celery --help' for help.
Dec 16 10:57:27 h2989788 celery[128418]: Error: Invalid value for '-A' / '--app':
Dec 16 10:57:27 h2989788 celery[128418]: Unable to load celery application.
Dec 16 10:57:27 h2989788 celery[128418]: While trying to load the module theApp the following error occurred:
Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last):
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/config.py", line 563, in configure
Dec 16 10:57:27 h2989788 celery[128418]:     handler = self.configure_handler(handlers[name])
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/config.py", line 744, in configure_handler
Dec 16 10:57:27 h2989788 celery[128418]:     result = factory(**kwargs)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/handlers.py", line 148, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/handlers.py", line 55, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     logging.FileHandler.__init__(self, filename, mode, encoding, delay)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/__init__.py", line 1147, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     StreamHandler.__init__(self, self._open())
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/__init__.py", line 1176, in _open
Dec 16 10:57:27 h2989788 celery[128418]:     return open(self.baseFilename, self.mode, encoding=self.encoding)
Dec 16 10:57:27 h2989788 celery[128418]: PermissionError: [Errno 13] Permission denied: '/home/django/FLY/logs/myrate.log'
Dec 16 10:57:27 h2989788 celery[128418]: The above exception was the direct cause of the following exception:
Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last):
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name
Dec 16 10:57:27 h2989788 celery[128418]:     module = imp(module_name, package=package, **kwargs)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/celery/utils/imports.py", line 105, in import_from_cwd
Dec 16 10:57:27 h2989788 celery[128418]:     return imp(module, package=package)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
Dec 16 10:57:27 h2989788 celery[128418]:     return _bootstrap._gcd_import(name[level:], package, level)
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 991, in _find_and_load
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap_external>", line 848, in exec_module
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
Dec 16 10:57:27 h2989788 systemd[1]: celery.service: Control process exited, code=exited, status=2/INVALIDARGUMENT
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/FLY/theApp/__init__.py", line 1, in <module>
Dec 16 10:57:27 h2989788 celery[128418]:     from .celery import app as celery_app
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/FLY/theApp/celery.py", line 18, in <module>
Dec 16 10:57:27 h2989788 celery[128418]:     configurations.setup()
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/configurations/__init__.py", line 31, in setup
</code>```

Workaround: change the permissions of the log file, which belongs to user django, so that user celery can write to it. But as we're using a rotating logger, this only helps until the next log-file is created.

Solutions we thought of:

Changing the access-rights of the file every time a new log-file is created: probably the worst way of handling this

Using the same user for the django- and celery-processes: smells like the last resort

Creating a specific run-configuration in settings.py overwriting the logging handlers like so:

```<code>class CeleryProd(Prod):
    def __init__(self) -> None:
        super().__init__()
        self.LOGGING['handlers']={}
</code>```

But somehow every of these solutions seems like a workaround to me - even the last one seems a bit clumsy. Mustn't there be a way of doing it right?
How have you done it?

Body:
Setting up celery on our production server seems to be more complicated than it should be - and the problem is logging.
Our setup is like this:

Server is Ubuntu 20.04.5 LTS

We run Django 3.2.8 in it's own user and group named "django"

The Celery process also has it's own user and group named "celery".

Celery is set up as a service and logs to /var/log/celery

In celery.py we have set djangoConf pointing to the main settings.py

On startup Celery tries to touch a django-logfile and - missing the permissions to do so - returns an error:

Dec 16 10:57:27 h2989788 celery[128418]: Usage: celery [OPTIONS] COMMAND [ARGS]...
Dec 16 10:57:27 h2989788 celery[128418]: Try 'celery --help' for help.
Dec 16 10:57:27 h2989788 celery[128418]: Error: Invalid value for '-A' / '--app':
Dec 16 10:57:27 h2989788 celery[128418]: Unable to load celery application.
Dec 16 10:57:27 h2989788 celery[128418]: While trying to load the module theApp the following error occurred:
Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last):
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/config.py", line 563, in configure
Dec 16 10:57:27 h2989788 celery[128418]:     handler = self.configure_handler(handlers[name])
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/config.py", line 744, in configure_handler
Dec 16 10:57:27 h2989788 celery[128418]:     result = factory(**kwargs)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/handlers.py", line 148, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/handlers.py", line 55, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     logging.FileHandler.__init__(self, filename, mode, encoding, delay)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/__init__.py", line 1147, in __init__
Dec 16 10:57:27 h2989788 celery[128418]:     StreamHandler.__init__(self, self._open())
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/logging/__init__.py", line 1176, in _open
Dec 16 10:57:27 h2989788 celery[128418]:     return open(self.baseFilename, self.mode, encoding=self.encoding)
Dec 16 10:57:27 h2989788 celery[128418]: PermissionError: [Errno 13] Permission denied: '/home/django/FLY/logs/myrate.log'
Dec 16 10:57:27 h2989788 celery[128418]: The above exception was the direct cause of the following exception:
Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last):
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name
Dec 16 10:57:27 h2989788 celery[128418]:     module = imp(module_name, package=package, **kwargs)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/celery/utils/imports.py", line 105, in import_from_cwd
Dec 16 10:57:27 h2989788 celery[128418]:     return imp(module, package=package)
Dec 16 10:57:27 h2989788 celery[128418]:   File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
Dec 16 10:57:27 h2989788 celery[128418]:     return _bootstrap._gcd_import(name[level:], package, level)
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 991, in _find_and_load
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap_external>", line 848, in exec_module
Dec 16 10:57:27 h2989788 celery[128418]:   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
Dec 16 10:57:27 h2989788 systemd[1]: celery.service: Control process exited, code=exited, status=2/INVALIDARGUMENT
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/FLY/theApp/__init__.py", line 1, in <module>
Dec 16 10:57:27 h2989788 celery[128418]:     from .celery import app as celery_app
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/FLY/theApp/celery.py", line 18, in <module>
Dec 16 10:57:27 h2989788 celery[128418]:     configurations.setup()
Dec 16 10:57:27 h2989788 celery[128418]:   File "/home/django/env/lib/python3.8/site-packages/configurations/__init__.py", line 31, in setup

Workaround: change the permissions of the log file, which belongs to user django, so that user celery can write to it. But as we're using a rotating logger, this only helps until the next log-file is created.

Solutions we thought of:

Changing the access-rights of the file every time a new log-file is created: probably the worst way of handling this

Using the same user for the django- and celery-processes: smells like the last resort

Creating a specific run-configuration in settings.py overwriting the logging handlers like so:

class CeleryProd(Prod):
    def __init__(self) -> None:
        super().__init__()
        self.LOGGING['handlers']={}

But somehow every of these solutions seems like a workaround to me - even the last one seems a bit clumsy. Mustn't there be a way of doing it right?
How have you done it?


问:
simplifying getting root directory
I have the following folder structure

```<code>public
source
  client
    config
      webpack.common.js
</code>```

inside the weback.common.js I want to reference the public folder

```<code>path.resolve(__dirname, '../', '../', '../', 'public')
</code>```

it works but it's very annoying and long, is there is a better way to reference this folder ?

Title: simplifying getting root directory

Body:
I have the following folder structure

public
source
  client
    config
      webpack.common.js

inside the weback.common.js I want to reference the public folder

path.resolve(__dirname, '../', '../', '../', 'public')

it works but it's very annoying and long, is there is a better way to reference this folder ?


问:
Docker container automatically stopping after running command docker run
I'm trying to dockerize MySQL and Spring Boot application however whenever I try to run my docker container and connect my docker image to the network the container automatically stops running.I'm new to docker so any help well is appreciated.

```<code>C:\Users\shawn>docker run --name mysqldb --network springboot -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=passion -e MYSQL_USER=root -e MYSQL_PASSWORD=password -d mysql:5.7
54d2a7c0ec819ec5e8e550ad61f55e8aabc7783ffad12d1ae04e79e7925d8064

C:\Users\shawn>docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
</code>```

I've tried using docker starting and using docker run with a specific port but still getting the same error.

Body:
I'm trying to dockerize MySQL and Spring Boot application however whenever I try to run my docker container and connect my docker image to the network the container automatically stops running.I'm new to docker so any help well is appreciated.

C:\Users\shawn>docker run --name mysqldb --network springboot -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=passion -e MYSQL_USER=root -e MYSQL_PASSWORD=password -d mysql:5.7
54d2a7c0ec819ec5e8e550ad61f55e8aabc7783ffad12d1ae04e79e7925d8064

C:\Users\shawn>docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

I've tried using docker starting and using docker run with a specific port but still getting the same error.


问:
Installation erro tesseract ubuntu
I am using ubuntu 20.04 I am installing tesseract via the following command
pip install tesseract and I come up with the following errors.

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion
    crit = self.state.criteria[name]
KeyError: 'tesseract'

During handling of the above exception, another exception occurred:
</code>```

I also do
sudo pip install tesseract got the same error.

Title: Installation erro tesseract ubuntu

Body:
I am using ubuntu 20.04 I am installing tesseract via the following command
pip install tesseract and I come up with the following errors.

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion
    crit = self.state.criteria[name]
KeyError: 'tesseract'

During handling of the above exception, another exception occurred:

I also do
sudo pip install tesseract got the same error.


问:
Gradle - How To Copy Only Files From Subdirectories
I have an output directory from an Android build like the following:

```<code>outputs
  - bundle
    - prodBundle
        - my-prod-bundle.aab
    - debugBundle
        - my-debug-bundle.aab
</code>```

I have an output directory that I've defined as outputDir.

The two tasks I have created to create the output directory and copy the files are:

```<code>task buildOutputDir {
        doLast {
            mkdir "build/bundles"
        }
    }

    task copyAabs(type: Copy, dependsOn: [bundle, buildOutputDir]) {
        def bundlePath = fileTree("$buildDir/outputs/bundle") {
            include '**/*'
        }
        def outputPath = "build/bundles"
        from bundlePath
        into outputPath
    }
</code>```

This works, but it copies the bundle directories as well, so my output looks like:

```<code>build
  - bundles
    - prodBundle
        - my-prod-bundle.aab
    - debugBundle
        - my-debug-bundle.aab
</code>```

What I am looking for is:

```<code>build
  - bundles
    - my-prod-bundle.aab
    - my-debug-bundle.aab
</code>```

What's the best way of doing that? I thought the include **/* would work, but it doesn't seem to do what I want.

Body:
I have an output directory from an Android build like the following:

outputs
  - bundle
    - prodBundle
        - my-prod-bundle.aab
    - debugBundle
        - my-debug-bundle.aab

I have an output directory that I've defined as outputDir.

The two tasks I have created to create the output directory and copy the files are:

task buildOutputDir {
        doLast {
            mkdir "build/bundles"
        }
    }

    task copyAabs(type: Copy, dependsOn: [bundle, buildOutputDir]) {
        def bundlePath = fileTree("$buildDir/outputs/bundle") {
            include '**/*'
        }
        def outputPath = "build/bundles"
        from bundlePath
        into outputPath
    }

This works, but it copies the bundle directories as well, so my output looks like:

build
  - bundles
    - prodBundle
        - my-prod-bundle.aab
    - debugBundle
        - my-debug-bundle.aab

What I am looking for is:

build
  - bundles
    - my-prod-bundle.aab
    - my-debug-bundle.aab

What's the best way of doing that? I thought the include **/* would work, but it doesn't seem to do what I want.


问:
Is there a way to count number of statements in sqs policy in Terraform?
According to AWS SQS Docs the policy for a queue should have a limit of 20 statements. Is there a way to count the number of statements for SQS policy in Terraform?

I have the following scenario:

I'm using the aws_iam_policy_document data source to combine two policies:

```<code>data "aws_iam_policy_document" "combined" {
  source_policy_documents = [
    data.aws_iam_policy_document.source_one.json,
    data.aws_iam_policy_document.source_two.json
  ]
}
</code>```

But as the SQS has a limitation on the size of the policy, I want to have a way to get the total number of statements from the previous data source so I can produce a new policy with wildcards. because, for example, if the size of the total SQS policy exceeds 20 statements, then Terraform should produce an error while applying.
The following is just a pseudocode:

```<code>resource "aws_sqs_queue_policy" "test" {
  queue_url = aws_sqs_queue.q.id

  policy = (if the statements are less than 20 statements from combined.json then I will take the merged policy) ?data.aws_iam_policy_document.combined.json) : (otherwise I if it is greater than 20 then I will create a new policy with wildcards)
}
</code>```

Body:
According to AWS SQS Docs the policy for a queue should have a limit of 20 statements. Is there a way to count the number of statements for SQS policy in Terraform?

I have the following scenario:

I'm using the aws_iam_policy_document data source to combine two policies:

data "aws_iam_policy_document" "combined" {
  source_policy_documents = [
    data.aws_iam_policy_document.source_one.json,
    data.aws_iam_policy_document.source_two.json
  ]
}

But as the SQS has a limitation on the size of the policy, I want to have a way to get the total number of statements from the previous data source so I can produce a new policy with wildcards. because, for example, if the size of the total SQS policy exceeds 20 statements, then Terraform should produce an error while applying.
The following is just a pseudocode:

resource "aws_sqs_queue_policy" "test" {
  queue_url = aws_sqs_queue.q.id

  policy = (if the statements are less than 20 statements from combined.json then I will take the merged policy) ?data.aws_iam_policy_document.combined.json) : (otherwise I if it is greater than 20 then I will create a new policy with wildcards)
}


问:
How to setup ResponseType (Net Core 6) based on JSON Schema
I have a large number of APIs, each without a strong class definition for output, like this

Return Ok(New With {
    .ServerDecryptPass = ServerDecryptPass,
    .VmConnectionAdminDecryptPass = VmConnectionAdminDecryptPass,
    .DockerHubDecryptPass = DockerHubDecryptPass,
    .DockerRegistryDecryptPass = DockerRegistryDecryptPass,
    .VmConnectionUserDecryptPass = VmConnectionUserDecryptPass
})
```
<p>Swagger, of course, doesn't see anything for response type in this case</p>
<p><img src="https://i.stack.imgur.com/sdzXU.png" alt="JSON result" /></p>
<p>The simplest way to formalize this JSON result is creating a JSON schema, for example in this case it looks like</p>
<pre class="lang-json prettyprint-override"><code>    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "type": "object",
      "properties": {
        "serverDecryptPass": {
          "type": "object",
          "properties": {
            "item1": {
              "type": "array",
              "items": {
                "type": "number"
              }
            },
            "item2": {
              "type": "null"
            }
          }
        },
        "vmConnectionAdminDecryptPass": {
    ...
    }
</code>```

I have a hundreds of APIs and I am searching for a simple way to formalize the output of the APIs in order to generate a frontend automatically from this backend API. I searched for a simple way to setup the attribute, ProducesResponseType, based on XML schema or maybe even an example of an API result.

What is a possible solution?

Body:
I have a large number of APIs, each without a strong class definition for output, like this

Return Ok(New With {
    .ServerDecryptPass = ServerDecryptPass,
    .VmConnectionAdminDecryptPass = VmConnectionAdminDecryptPass,
    .DockerHubDecryptPass = DockerHubDecryptPass,
    .DockerRegistryDecryptPass = DockerRegistryDecryptPass,
    .VmConnectionUserDecryptPass = VmConnectionUserDecryptPass
})

Swagger, of course, doesn't see anything for response type in this case

The simplest way to formalize this JSON result is creating a JSON schema, for example in this case it looks like

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "type": "object",
      "properties": {
        "serverDecryptPass": {
          "type": "object",
          "properties": {
            "item1": {
              "type": "array",
              "items": {
                "type": "number"
              }
            },
            "item2": {
              "type": "null"
            }
          }
        },
        "vmConnectionAdminDecryptPass": {
    ...
    }

I have a hundreds of APIs and I am searching for a simple way to formalize the output of the APIs in order to generate a frontend automatically from this backend API. I searched for a simple way to setup the attribute, ProducesResponseType, based on XML schema or maybe even an example of an API result.

What is a possible solution?


问:
Owncloud behind netscaler and nginx proxy: PR_CONNECT_RESET_ERROR
I try to install a dockerized owncloud instance behind a nginx server (on the same virtual machine). The whole vm-server (redhat8) is behind a netscaler (type unknown, managed by my company) which handles the ssl handshake via wildcard certificate. The nginx server is reached only via port 80 http.
My nginx-conf:

```<code>server {

    listen 80;
    server_name cloud.mydomain.com;

    location / {

        client_max_body_size    16000m;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect  off;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8082/;

    }

}
</code>```

The docker-compose.yml in use:

```<code>version: "3"

services:
  owncloud:
    image: owncloud/server
    container_name: owncloud_server
    restart: unless-stopped
    depends_on:
      - mariadb
      - redis
    ports:
      - "8082:8080"
    environment:
      - OWNCLOUD_DOMAIN=cloud.mydomain.com
      - OWNCLOUD_DB_TYPE=mysql
      - OWNCLOUD_DB_NAME=owncloud
      - OWNCLOUD_DB_USERNAME=owncloud
      - OWNCLOUD_DB_PASSWORD=owncloud
      - OWNCLOUD_DB_HOST=mariadb
      - OWNCLOUD_ADMIN_USERNAME=admin
      - OWNCLOUD_ADMIN_PASSWORD=********
      - OWNCLOUD_MYSQL_UTF8MB4=true
      - OWNCLOUD_REDIS_ENABLED=true
      - OWNCLOUD_REDIS_HOST=redis
      - OWNCLOUD_OVERWRITE_CLI_URL=https://cloud.mydomain.com
      - OWNCLOUD_OVERWRITE_PROTOCOL=https
      - OWNCLOUD_OVERWRITE_HOST=cloud.mydomain.com
      - OWNCLOUD_TRUSTED_PROXIES=0.0.0.0/16
      - OWNCLOUD_DEFAULT_LANGUAGE=de
   healthcheck:
      test: ["CMD", "/usr/bin/healthcheck"]
      interval: 30s
      timeout: 10s
      retries: 5
    volumes:
      - ./files:/mnt/data
    networks:
      - default
  mariadb:
    image: mariadb:10.6
    container_name: owncloud_mariadb
    restart: unless-stopped
    environment:
      - MYSQL_ROOT_PASSWORD=owncloud
      - MYSQL_USER=owncloud
      - MYSQL_PASSWORD=owncloud
      - MYSQL_DATABASE=owncloud
    command: ["--max-allowed-packet=128M", "--innodb-log-file-size=64M"]
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-u", "root", "--password=owncloud"]
      interval: 10s
      timeout: 5s
      retries: 5
    volumes:
      - ./mysql:/var/lib/mysql
    networks:
      - default

  redis:
    image: redis:6
    container_name: owncloud_redis
    restart: unless-stopped
    command: ["--databases", "1"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    volumes:
      - ./redis:/data
    networks:
      - default
</code>```

This happens: a request to https://cloud.mydomain.com returns a correct redirect to https://cloud.mydomain.com/login. But this page shows on Chrome a ERR_CONNECTION_RESET, under firefox a PR_CONNECT_RESET_ERROR. The owncloud server log shows multiple GET /login HTTP/1.0" 200  entries.

I play with the configuration now for days and ran out of ideas. Any help appreciated. Thanks.

Body:
I try to install a dockerized owncloud instance behind a nginx server (on the same virtual machine). The whole vm-server (redhat8) is behind a netscaler (type unknown, managed by my company) which handles the ssl handshake via wildcard certificate. The nginx server is reached only via port 80 http.
My nginx-conf:

server {

    listen 80;
    server_name cloud.mydomain.com;

    location / {

        client_max_body_size    16000m;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect  off;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8082/;

    }

}

The docker-compose.yml in use:

version: "3"

services:
  owncloud:
    image: owncloud/server
    container_name: owncloud_server
    restart: unless-stopped
    depends_on:
      - mariadb
      - redis
    ports:
      - "8082:8080"
    environment:
      - OWNCLOUD_DOMAIN=cloud.mydomain.com
      - OWNCLOUD_DB_TYPE=mysql
      - OWNCLOUD_DB_NAME=owncloud
      - OWNCLOUD_DB_USERNAME=owncloud
      - OWNCLOUD_DB_PASSWORD=owncloud
      - OWNCLOUD_DB_HOST=mariadb
      - OWNCLOUD_ADMIN_USERNAME=admin
      - OWNCLOUD_ADMIN_PASSWORD=********
      - OWNCLOUD_MYSQL_UTF8MB4=true
      - OWNCLOUD_REDIS_ENABLED=true
      - OWNCLOUD_REDIS_HOST=redis
      - OWNCLOUD_OVERWRITE_CLI_URL=https://cloud.mydomain.com
      - OWNCLOUD_OVERWRITE_PROTOCOL=https
      - OWNCLOUD_OVERWRITE_HOST=cloud.mydomain.com
      - OWNCLOUD_TRUSTED_PROXIES=0.0.0.0/16
      - OWNCLOUD_DEFAULT_LANGUAGE=de
   healthcheck:
      test: ["CMD", "/usr/bin/healthcheck"]
      interval: 30s
      timeout: 10s
      retries: 5
    volumes:
      - ./files:/mnt/data
    networks:
      - default
  mariadb:
    image: mariadb:10.6
    container_name: owncloud_mariadb
    restart: unless-stopped
    environment:
      - MYSQL_ROOT_PASSWORD=owncloud
      - MYSQL_USER=owncloud
      - MYSQL_PASSWORD=owncloud
      - MYSQL_DATABASE=owncloud
    command: ["--max-allowed-packet=128M", "--innodb-log-file-size=64M"]
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-u", "root", "--password=owncloud"]
      interval: 10s
      timeout: 5s
      retries: 5
    volumes:
      - ./mysql:/var/lib/mysql
    networks:
      - default

  redis:
    image: redis:6
    container_name: owncloud_redis
    restart: unless-stopped
    command: ["--databases", "1"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    volumes:
      - ./redis:/data
    networks:
      - default

This happens: a request to https://cloud.mydomain.com returns a correct redirect to https://cloud.mydomain.com/login. But this page shows on Chrome a ERR_CONNECTION_RESET, under firefox a PR_CONNECT_RESET_ERROR. The owncloud server log shows multiple GET /login HTTP/1.0" 200  entries.

I play with the configuration now for days and ran out of ideas. Any help appreciated. Thanks.


问:
Why do none of these methods of sending data over UDP socket show a significant difference in speed/efficiency? FULL MRE AT BOTTOM
I have to send a large amount of data (enough to saturate a gigabit link) out over a UDP socket from an embedded system running (peta)Linux to arbitrary devices. Performance in terms of speed (time spent in socket system calls/copying data esp) and efficiency (CPU time/percentage use) are critical here, so I have been attempting different methods of achieving this, each of which I would expect to be faster according to my research. When I attempt to benchmark this performance, the differences between methods seem to be almost negligible for the most part so I wonder if I am missing anything obvious (like caching playing a part in my benchmark results?) or if I am expecting too much improvement between methods.

Method 1: Copy header and data into buffer, send buffer with sendto().
I had expected this to be the slowest by a margin because of the overhead involved with copying all of the data before each send.

Method 2: Gather buffers with sendmsg() to avoid copying
This is where I expected to see improvements start as copying (in my userspace application at least) had been basically eliminated.

Method 3: Use sendmmsg to avoid overhead of many calls to sendmsg() The man page for this call implies that cutting back on system calls ((~1500 * ~5 * 30)/sec for previous 2 methods) can have performance benefits.

Method 4: Any of the previous + using connect() on the sockets before hand I had seen some suggestions (another) that this could improve performance, again prefaced with a 'maybe':

Connected sockets can save route lookup on each packet by employing a clever optimization — Linux can save a route lookup result on a connection struct. Depending on the specifics of the setup this might save some CPU cycles.

Indeed, this seemed to yield a small benefit on my laptop when writing the MVE, EXCLUSIVELY when using in conjunction with sendmmsg() (25ms average to send 3.5MB 'image' vs ~28.15ms avg ± 0.1ms for all previous methods, including conncet() with sendto() or sendmsg()). This improvement does not seem to have transferred over to the embedded system however (perhaps this connection struct is not impl in that version of the kernel? Something I will look into after posting this, although kernel socket code is not something I pull apart often).

I am hoping anyone can do any of the following:

Answer my main question as to why I do not see much improvement like
I would expect (from eliminating userspace copying and system
call/kernel overhead)

Run the MVE a few ways and let me know if they get similar results/spot any issues
with it

Maybe even point me to a more efficient method compatible with my MVE if
one exists, as I think connect() with sendmmsg() are my best
attempt and I am still not super satisfied. I have seen MSG_ZEROCOPY flag and
options regarding blocking but am not sure if they will make other parts of this more
difficult, and do not want to spend time impl. and testing them before understanding
my current issue

What follows is a 'table' of results from my benchmarking as well as the MVE

```<code>sysCall    | connected | Time(μS)
sento()    |    no     | 28119
sendmsg()  |    no     | 28340
sendmmsg() |    no     | 28367
sento()    |    yes    | 28109
sendmsg()  |    yes    | 28341
sendmmsg() |    yes    | 25021
</code>```

C++ (I apologize in advance, hacked together from a much larger experiment, but should compile and run with some quick tweaks to inet addrs) I use -O3:

```<code>#include <netinet/in.h>
#include <sys/socket.h>
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <string.h>
#include <random>
using namespace std;
void randomize_sim_buf();

uint8_t send_buf[9000], sim_buf[10][1920*1200*3/2], sim_header[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};

int main(int argc, char const *argv[])
{
    int socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    struct sockaddr_in socket_bind, socket_destination;
    int return_stat = 0;
    uint8_t * p;
    iovec iov[2];
    msghdr message_hdr;
    iovec iovs[1024][2];
    mmsghdr mmsg[1024];

    socket_bind.sin_family = socket_destination.sin_family = AF_INET;
    socket_bind.sin_addr.s_addr = htonl(0x0A42AB01);
    socket_destination.sin_addr.s_addr = htonl(0x0A42AB15);
    socket_bind.sin_port = htons(0xF3D4);
    socket_destination.sin_port = htons(0xF4D4);

    return_stat = bind(socket_fd, (sockaddr *)&socket_bind, sizeof(sockaddr_in));
    bool connected = false;
    cout << "Connect socket?\n";
    cin >> connected;
    if (connected){
        return_stat = connect(socket_fd, (sockaddr *)&socket_destination, sizeof(sockaddr_in));
        cout << "Socket connect() returned " << return_stat << endl;
    }
    string send_type = "";
    int packet_size = 1500;
    cout << "{sendto|sendmsg|sendmmsg} [packet size]?\n";
    cin >> send_type >> packet_size;

    uint64_t duration_cnt = 0;
    for (int i = 0; i < 1000; i++){
        int msg_idx = 0;
        auto start = chrono::high_resolution_clock::now();
        for (uint j = 0; j < (1920*1200*3/2); j+= packet_size){
            uint datalen = (((1920*1200*3/2) - j) >= packet_size) ? packet_size : ((1920*1200*3/2) - j);
            p = sim_buf[i % 10];
            if (send_type == "sendto"){
                memcpy(send_buf, &sim_header, 20);
                memcpy(send_buf + 20, &p[j], datalen);
                sendto(socket_fd, send_buf, datalen, 0, (sockaddr*)&socket_destination, sizeof(sockaddr_in));
            } else if (send_type == "sendmsg"){
                iov[0].iov_base = &sim_header;
                iov[0].iov_len = 20;
                iov[1].iov_base = &p[j];
                iov[1].iov_len = datalen;
                message_hdr.msg_controllen = 0;
                message_hdr.msg_flags = 0;
                message_hdr.msg_iov = iov;
                message_hdr.msg_iovlen = 2;
                message_hdr.msg_name = &socket_destination;
                message_hdr.msg_namelen = sizeof(sockaddr_in);
                sendmsg(socket_fd, &message_hdr, 0);
            } else if (send_type == "sendmmsg"){
                iovs[msg_idx][0].iov_base = &sim_header;
                iovs[msg_idx][0].iov_len = 20;
                iovs[msg_idx][1].iov_base = &p[j];
                iovs[msg_idx][1].iov_len = datalen;
                mmsg[msg_idx].msg_hdr.msg_controllen = 0;
                mmsg[msg_idx].msg_hdr.msg_flags = 0;
                mmsg[msg_idx].msg_hdr.msg_name = &socket_destination;
                mmsg[msg_idx].msg_hdr.msg_namelen = sizeof(sockaddr_in);
                mmsg[msg_idx].msg_hdr.msg_iov = iovs[msg_idx];
                mmsg[msg_idx].msg_hdr.msg_iovlen = 2;
                msg_idx++;
                if (msg_idx == 1024){
                    sendmmsg(socket_fd, mmsg, msg_idx, 0);
                    msg_idx = 0;
                }
            } else {
                cout << "Invalid send type supplied\n";
                return -1;
            }
        }
        if (send_type == "sendmmsg")
            sendmmsg(socket_fd, mmsg, msg_idx, 0);
        auto stop = chrono::high_resolution_clock::now();
        duration_cnt += std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
        randomize_sim_buf();
        usleep(15000);
    }

    cout << "Average duration to send a buffer: " << (duration_cnt / 1000) << endl;
    return 0;
}

void randomize_sim_buf(){
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < (1920*1200*3/2); j++){
            sim_buf[i][j] = rand() % 255;
        }
    }
}
</code>```

Body:
I have to send a large amount of data (enough to saturate a gigabit link) out over a UDP socket from an embedded system running (peta)Linux to arbitrary devices. Performance in terms of speed (time spent in socket system calls/copying data esp) and efficiency (CPU time/percentage use) are critical here, so I have been attempting different methods of achieving this, each of which I would expect to be faster according to my research. When I attempt to benchmark this performance, the differences between methods seem to be almost negligible for the most part so I wonder if I am missing anything obvious (like caching playing a part in my benchmark results?) or if I am expecting too much improvement between methods.

Method 1: Copy header and data into buffer, send buffer with sendto().
I had expected this to be the slowest by a margin because of the overhead involved with copying all of the data before each send.

Method 2: Gather buffers with sendmsg() to avoid copying
This is where I expected to see improvements start as copying (in my userspace application at least) had been basically eliminated.

Method 3: Use sendmmsg to avoid overhead of many calls to sendmsg() The man page for this call implies that cutting back on system calls ((~1500 * ~5 * 30)/sec for previous 2 methods) can have performance benefits.

Method 4: Any of the previous + using connect() on the sockets before hand I had seen some suggestions (another) that this could improve performance, again prefaced with a 'maybe':

Connected sockets can save route lookup on each packet by employing a clever optimization — Linux can save a route lookup result on a connection struct. Depending on the specifics of the setup this might save some CPU cycles.

Indeed, this seemed to yield a small benefit on my laptop when writing the MVE, EXCLUSIVELY when using in conjunction with sendmmsg() (25ms average to send 3.5MB 'image' vs ~28.15ms avg ± 0.1ms for all previous methods, including conncet() with sendto() or sendmsg()). This improvement does not seem to have transferred over to the embedded system however (perhaps this connection struct is not impl in that version of the kernel? Something I will look into after posting this, although kernel socket code is not something I pull apart often).

I am hoping anyone can do any of the following:

Answer my main question as to why I do not see much improvement like
I would expect (from eliminating userspace copying and system
call/kernel overhead)

Run the MVE a few ways and let me know if they get similar results/spot any issues
with it

Maybe even point me to a more efficient method compatible with my MVE if
one exists, as I think connect() with sendmmsg() are my best
attempt and I am still not super satisfied. I have seen MSG_ZEROCOPY flag and
options regarding blocking but am not sure if they will make other parts of this more
difficult, and do not want to spend time impl. and testing them before understanding
my current issue

What follows is a 'table' of results from my benchmarking as well as the MVE

sysCall    | connected | Time(μS)
sento()    |    no     | 28119
sendmsg()  |    no     | 28340
sendmmsg() |    no     | 28367
sento()    |    yes    | 28109
sendmsg()  |    yes    | 28341
sendmmsg() |    yes    | 25021

C++ (I apologize in advance, hacked together from a much larger experiment, but should compile and run with some quick tweaks to inet addrs) I use -O3:

#include <netinet/in.h>
#include <sys/socket.h>
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <string.h>
#include <random>
using namespace std;
void randomize_sim_buf();

uint8_t send_buf[9000], sim_buf[10][1920*1200*3/2], sim_header[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};

int main(int argc, char const *argv[])
{
    int socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    struct sockaddr_in socket_bind, socket_destination;
    int return_stat = 0;
    uint8_t * p;
    iovec iov[2];
    msghdr message_hdr;
    iovec iovs[1024][2];
    mmsghdr mmsg[1024];

    socket_bind.sin_family = socket_destination.sin_family = AF_INET;
    socket_bind.sin_addr.s_addr = htonl(0x0A42AB01);
    socket_destination.sin_addr.s_addr = htonl(0x0A42AB15);
    socket_bind.sin_port = htons(0xF3D4);
    socket_destination.sin_port = htons(0xF4D4);

    return_stat = bind(socket_fd, (sockaddr *)&socket_bind, sizeof(sockaddr_in));
    bool connected = false;
    cout << "Connect socket?\n";
    cin >> connected;
    if (connected){
        return_stat = connect(socket_fd, (sockaddr *)&socket_destination, sizeof(sockaddr_in));
        cout << "Socket connect() returned " << return_stat << endl;
    }
    string send_type = "";
    int packet_size = 1500;
    cout << "{sendto|sendmsg|sendmmsg} [packet size]?\n";
    cin >> send_type >> packet_size;

    uint64_t duration_cnt = 0;
    for (int i = 0; i < 1000; i++){
        int msg_idx = 0;
        auto start = chrono::high_resolution_clock::now();
        for (uint j = 0; j < (1920*1200*3/2); j+= packet_size){
            uint datalen = (((1920*1200*3/2) - j) >= packet_size) ? packet_size : ((1920*1200*3/2) - j);
            p = sim_buf[i % 10];
            if (send_type == "sendto"){
                memcpy(send_buf, &sim_header, 20);
                memcpy(send_buf + 20, &p[j], datalen);
                sendto(socket_fd, send_buf, datalen, 0, (sockaddr*)&socket_destination, sizeof(sockaddr_in));
            } else if (send_type == "sendmsg"){
                iov[0].iov_base = &sim_header;
                iov[0].iov_len = 20;
                iov[1].iov_base = &p[j];
                iov[1].iov_len = datalen;
                message_hdr.msg_controllen = 0;
                message_hdr.msg_flags = 0;
                message_hdr.msg_iov = iov;
                message_hdr.msg_iovlen = 2;
                message_hdr.msg_name = &socket_destination;
                message_hdr.msg_namelen = sizeof(sockaddr_in);
                sendmsg(socket_fd, &message_hdr, 0);
            } else if (send_type == "sendmmsg"){
                iovs[msg_idx][0].iov_base = &sim_header;
                iovs[msg_idx][0].iov_len = 20;
                iovs[msg_idx][1].iov_base = &p[j];
                iovs[msg_idx][1].iov_len = datalen;
                mmsg[msg_idx].msg_hdr.msg_controllen = 0;
                mmsg[msg_idx].msg_hdr.msg_flags = 0;
                mmsg[msg_idx].msg_hdr.msg_name = &socket_destination;
                mmsg[msg_idx].msg_hdr.msg_namelen = sizeof(sockaddr_in);
                mmsg[msg_idx].msg_hdr.msg_iov = iovs[msg_idx];
                mmsg[msg_idx].msg_hdr.msg_iovlen = 2;
                msg_idx++;
                if (msg_idx == 1024){
                    sendmmsg(socket_fd, mmsg, msg_idx, 0);
                    msg_idx = 0;
                }
            } else {
                cout << "Invalid send type supplied\n";
                return -1;
            }
        }
        if (send_type == "sendmmsg")
            sendmmsg(socket_fd, mmsg, msg_idx, 0);
        auto stop = chrono::high_resolution_clock::now();
        duration_cnt += std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
        randomize_sim_buf();
        usleep(15000);
    }

    cout << "Average duration to send a buffer: " << (duration_cnt / 1000) << endl;
    return 0;
}

void randomize_sim_buf(){
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < (1920*1200*3/2); j++){
            sim_buf[i][j] = rand() % 255;
        }
    }
}


问:
Ag-Grid: add a placeholder text in agSelectCellEditor dynamic dropdown options list
I am using Ag-Grid for displaying tabular data, is there a way we can add a placeholder in the dropdown options which are displayed in a column where we have an agSelectCellEditor?

Problem Statement:

```<code>Sample Code:
for(const [key,value] of countryCodes ) {
if (key !== ' ') {
   countryNames.push([value.countriesCd]);
 }
}

console.log(this.countryNames) =  [['France'], ['Belgium'], ['USA'], ['UAE']]

For eg: The column filed  = 'country'

country.cellEditor = 'agSelectCellEditor',
country.singleClickEdit = true,
country.cellEditorParams = {

  values.countryNames,
}
</code>```

When clicking on the country column, it shows the select dropdown with the countryNames list and without making any selection it defaults the dropdown to France, its confusing for the users as an option is displayed in the editorCell without selection

Body:
I am using Ag-Grid for displaying tabular data, is there a way we can add a placeholder in the dropdown options which are displayed in a column where we have an agSelectCellEditor?

Problem Statement:

Sample Code:
for(const [key,value] of countryCodes ) {
if (key !== ' ') {
   countryNames.push([value.countriesCd]);
 }
}

console.log(this.countryNames) =  [['France'], ['Belgium'], ['USA'], ['UAE']]

For eg: The column filed  = 'country'

country.cellEditor = 'agSelectCellEditor',
country.singleClickEdit = true,
country.cellEditorParams = {

  values.countryNames,
}

When clicking on the country column, it shows the select dropdown with the countryNames list and without making any selection it defaults the dropdown to France, its confusing for the users as an option is displayed in the editorCell without selection


问:
Can Python data structures, other than string, be passed using Format Specification Mini-Language?
When I define a custom formatting for a class, e.g.:

```<code>  def __format__(self, spec):
    match spec:
      case 'verbose':
        lines = np.where(self.shape[0], '8', '.').view(f'<U{self.shape[0].shape[-1]}').flat
        return f'\n{lines[0]}  id={self.id} color={self.color}, origin={self.pos}, area={self.area}\n' + '\n'.join(lines[1:])
      case 'terse':
        return f'{self.id}'
</code>```

the spec parameter seems always to be a string. Is there a way to pass a non-string data structure inside spec? For example, a pair of strings?

Body:
When I define a custom formatting for a class, e.g.:

  def __format__(self, spec):
    match spec:
      case 'verbose':
        lines = np.where(self.shape[0], '8', '.').view(f'<U{self.shape[0].shape[-1]}').flat
        return f'\n{lines[0]}  id={self.id} color={self.color}, origin={self.pos}, area={self.area}\n' + '\n'.join(lines[1:])
      case 'terse':
        return f'{self.id}'

the spec parameter seems always to be a string. Is there a way to pass a non-string data structure inside spec? For example, a pair of strings?


问:
OcrMyPdf Python: Permission denied: 'unpaper'
I'm trying to use ocrMyPdf library and here is my code:

```<code>ocrmypdf.ocr("input/mypdf.pdf",
             "input/mypdf_ocr.pdf",
              skip_text=False,
              force_ocr=True,
              deskew=True,
              rotate_pages=True,
              remove_background=False,
              rotate_pages_threshold=3,
              pages="1,72",
              max_image_mpixels=1_000_000_000,
              keep_temporary_files=False,
              pdf_renderer="sandwich",
              unpaper_args="",
              clean=True,
              progress_bar=False,)
</code>```

Above call is throwing PermissionError: [Errno 13] Permission denied: 'unpaper'. Not sure where to debug the cause of the error.

I'm using WSL2 (Ubuntu 20.4) on Windows 11.

Here is the full trace from jupyter notebook:

```<code>---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 ocrmypdf.ocr("input/mypdf.pdf",
      2              "input/mypdf_ocr.pdf",
      3               skip_text=False,
      4               force_ocr=True,
      5               deskew=True,
      6               rotate_pages=True,
      7               remove_background=False,
      8               rotate_pages_threshold=3,
      9               pages="1,72",
     10               max_image_mpixels=1_000_000_000,
     11               keep_temporary_files=False,
     12               pdf_renderer="sandwich",
     13               unpaper_args="",
     14               clean=True,
     15               progress_bar=False)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/api.py:339, in ocr(input_file, output_file, language, image_dpi, output_type, sidecar, jobs, use_threads, title, author, subject, keywords, rotate_pages, remove_background, deskew, clean, clean_final, unpaper_args, oversample, remove_vectors, force_ocr, skip_text, redo_ocr, skip_big, optimize, jpg_quality, png_quality, jbig2_lossy, jbig2_page_group_size, pages, max_image_mpixels, tesseract_config, tesseract_pagesegmode, tesseract_oem, tesseract_thresholding, pdf_renderer, tesseract_timeout, rotate_pages_threshold, pdfa_image_compression, user_words, user_patterns, fast_web_view, plugins, plugin_manager, keep_temporary_files, progress_bar, **kwargs)
    336     warn("ocrmypdf.ocr(verbose=) is ignored. Use ocrmypdf.configure_logging().")
    338 options = create_options(**create_options_kwargs)
--> 339 check_options(options, plugin_manager)
    340 return run_pipeline(options=options, plugin_manager=plugin_manager, api=True)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:245, in check_options(options, plugin_manager)
    244 def check_options(options: Namespace, plugin_manager: PluginManager) -> None:
--> 245     _check_plugin_invariant_options(options)
    246     _check_plugin_options(options, plugin_manager)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:232, in _check_plugin_invariant_options(options)
    230 check_options_output(options)
    231 check_options_sidecar(options)
--> 232 check_options_preprocessing(options)
    233 check_options_ocr_behavior(options)
    234 check_options_advanced(options)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:132, in check_options_preprocessing(options)
    130     raise BadArgsError("--clean is required for --unpaper-args")
    131 if options.clean:
--> 132     check_external_program(
    133         program='unpaper',
    134         package='unpaper',
    135         version_checker=unpaper.version,
    136         need_version='6.1',
    137         required_for=['--clean, --clean-final'],
    138     )
    139     try:
    140         if options.unpaper_args:

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:331, in check_external_program(program, package, version_checker, need_version, required_for, recommended, version_parser)
    329 try:
    330     if callable(version_checker):
--> 331         found_version = version_checker()
    332     else:  # deprecated
    333         found_version = version_checker

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_exec/unpaper.py:69, in version()
     68 def version() -> str:
---> 69     return get_version('unpaper')

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:157, in get_version(program, version_arg, regex, env)
    155 args_prog = [program, version_arg]
    156 try:
--> 157     proc = run(
    158         args_prog,
    159         close_fds=True,
    160         text=True,
    161         stdout=PIPE,
    162         stderr=STDOUT,
    163         check=True,
    164         env=env,
    165     )
    166     output: str = proc.stdout
    167 except FileNotFoundError as e:

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:58, in run(args, env, logs_errors_to_stdout, check, **kwargs)
     56 stderr_name = 'stderr' if not logs_errors_to_stdout else 'stdout'
     57 try:
---> 58     proc = subprocess_run(args, env=env, check=check, **kwargs)
     59 except CalledProcessError as e:
     60     stderr = getattr(e, stderr_name, None)

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:489, in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    486     kwargs['stdout'] = PIPE
    487     kwargs['stderr'] = PIPE
--> 489 with Popen(*popenargs, **kwargs) as process:
    490     try:
    491         stdout, stderr = process.communicate(input, timeout=timeout)

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:854, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    850         if self.text_mode:
    851             self.stderr = io.TextIOWrapper(self.stderr,
    852                     encoding=encoding, errors=errors)
--> 854     self._execute_child(args, executable, preexec_fn, close_fds,
    855                         pass_fds, cwd, env,
    856                         startupinfo, creationflags, shell,
    857                         p2cread, p2cwrite,
    858                         c2pread, c2pwrite,
    859                         errread, errwrite,
    860                         restore_signals, start_new_session)
    861 except:
    862     # Cleanup if the child failed starting.
    863     for f in filter(None, (self.stdin, self.stdout, self.stderr)):

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:1702, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1700     if errno_num != 0:
   1701         err_msg = os.strerror(errno_num)
-> 1702     raise child_exception_type(errno_num, err_msg, err_filename)
   1703 raise child_exception_type(err_msg)

PermissionError: [Errno 13] Permission denied: 'unpaper'
</code>```

Body:
I'm trying to use ocrMyPdf library and here is my code:

ocrmypdf.ocr("input/mypdf.pdf",
             "input/mypdf_ocr.pdf",
              skip_text=False,
              force_ocr=True,
              deskew=True,
              rotate_pages=True,
              remove_background=False,
              rotate_pages_threshold=3,
              pages="1,72",
              max_image_mpixels=1_000_000_000,
              keep_temporary_files=False,
              pdf_renderer="sandwich",
              unpaper_args="",
              clean=True,
              progress_bar=False,)

Above call is throwing PermissionError: [Errno 13] Permission denied: 'unpaper'. Not sure where to debug the cause of the error.

I'm using WSL2 (Ubuntu 20.4) on Windows 11.

Here is the full trace from jupyter notebook:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 ocrmypdf.ocr("input/mypdf.pdf",
      2              "input/mypdf_ocr.pdf",
      3               skip_text=False,
      4               force_ocr=True,
      5               deskew=True,
      6               rotate_pages=True,
      7               remove_background=False,
      8               rotate_pages_threshold=3,
      9               pages="1,72",
     10               max_image_mpixels=1_000_000_000,
     11               keep_temporary_files=False,
     12               pdf_renderer="sandwich",
     13               unpaper_args="",
     14               clean=True,
     15               progress_bar=False)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/api.py:339, in ocr(input_file, output_file, language, image_dpi, output_type, sidecar, jobs, use_threads, title, author, subject, keywords, rotate_pages, remove_background, deskew, clean, clean_final, unpaper_args, oversample, remove_vectors, force_ocr, skip_text, redo_ocr, skip_big, optimize, jpg_quality, png_quality, jbig2_lossy, jbig2_page_group_size, pages, max_image_mpixels, tesseract_config, tesseract_pagesegmode, tesseract_oem, tesseract_thresholding, pdf_renderer, tesseract_timeout, rotate_pages_threshold, pdfa_image_compression, user_words, user_patterns, fast_web_view, plugins, plugin_manager, keep_temporary_files, progress_bar, **kwargs)
    336     warn("ocrmypdf.ocr(verbose=) is ignored. Use ocrmypdf.configure_logging().")
    338 options = create_options(**create_options_kwargs)
--> 339 check_options(options, plugin_manager)
    340 return run_pipeline(options=options, plugin_manager=plugin_manager, api=True)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:245, in check_options(options, plugin_manager)
    244 def check_options(options: Namespace, plugin_manager: PluginManager) -> None:
--> 245     _check_plugin_invariant_options(options)
    246     _check_plugin_options(options, plugin_manager)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:232, in _check_plugin_invariant_options(options)
    230 check_options_output(options)
    231 check_options_sidecar(options)
--> 232 check_options_preprocessing(options)
    233 check_options_ocr_behavior(options)
    234 check_options_advanced(options)

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_validation.py:132, in check_options_preprocessing(options)
    130     raise BadArgsError("--clean is required for --unpaper-args")
    131 if options.clean:
--> 132     check_external_program(
    133         program='unpaper',
    134         package='unpaper',
    135         version_checker=unpaper.version,
    136         need_version='6.1',
    137         required_for=['--clean, --clean-final'],
    138     )
    139     try:
    140         if options.unpaper_args:

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:331, in check_external_program(program, package, version_checker, need_version, required_for, recommended, version_parser)
    329 try:
    330     if callable(version_checker):
--> 331         found_version = version_checker()
    332     else:  # deprecated
    333         found_version = version_checker

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/_exec/unpaper.py:69, in version()
     68 def version() -> str:
---> 69     return get_version('unpaper')

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:157, in get_version(program, version_arg, regex, env)
    155 args_prog = [program, version_arg]
    156 try:
--> 157     proc = run(
    158         args_prog,
    159         close_fds=True,
    160         text=True,
    161         stdout=PIPE,
    162         stderr=STDOUT,
    163         check=True,
    164         env=env,
    165     )
    166     output: str = proc.stdout
    167 except FileNotFoundError as e:

File ~/AI/nexus/aps-esg-data-scraper/venv/lib/python3.8/site-packages/ocrmypdf/subprocess/__init__.py:58, in run(args, env, logs_errors_to_stdout, check, **kwargs)
     56 stderr_name = 'stderr' if not logs_errors_to_stdout else 'stdout'
     57 try:
---> 58     proc = subprocess_run(args, env=env, check=check, **kwargs)
     59 except CalledProcessError as e:
     60     stderr = getattr(e, stderr_name, None)

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:489, in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    486     kwargs['stdout'] = PIPE
    487     kwargs['stderr'] = PIPE
--> 489 with Popen(*popenargs, **kwargs) as process:
    490     try:
    491         stdout, stderr = process.communicate(input, timeout=timeout)

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:854, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    850         if self.text_mode:
    851             self.stderr = io.TextIOWrapper(self.stderr,
    852                     encoding=encoding, errors=errors)
--> 854     self._execute_child(args, executable, preexec_fn, close_fds,
    855                         pass_fds, cwd, env,
    856                         startupinfo, creationflags, shell,
    857                         p2cread, p2cwrite,
    858                         c2pread, c2pwrite,
    859                         errread, errwrite,
    860                         restore_signals, start_new_session)
    861 except:
    862     # Cleanup if the child failed starting.
    863     for f in filter(None, (self.stdin, self.stdout, self.stderr)):

File ~/.pyenv/versions/3.8.3/lib/python3.8/subprocess.py:1702, in Popen._execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1700     if errno_num != 0:
   1701         err_msg = os.strerror(errno_num)
-> 1702     raise child_exception_type(errno_num, err_msg, err_filename)
   1703 raise child_exception_type(err_msg)

PermissionError: [Errno 13] Permission denied: 'unpaper'


问:
how to get youtube url from iframe api and parameters...... used javascript
srript used is somewhat looks like this question
How to register one of two possible event handlers with onYoutubeiframeAPIReady event on WordPress site
some images of code i could see
enter image description here
enter image description here

i dont know coding but i just want to see video in youtube...  for quality problem....


问:
how can I run a formula on multidimensional knapsack problem
I solve the knapsack algorithm in Python, for instance:

```<code>weights = [3, 5, 1, 1, 1, 5, 3, 3, 3, 5]
profits = [0, 2, 10, 5, 7, 7, 3, 6, 10, 9]

knapsacks_capacity = [15, 14, 13]
</code>```

for this sample I got this result:

```<code># knapsack capacity: [[weights],[profits]]
"knapsack 15: [[5, 1, 1, 1, 5], [2, 10, 5, 7, 7]]"
"knapsack 14: [[3, 3, 3, 5], [3, 6, 10, 9]]"
"knapsack 13: [[], []]"
</code>```

every thing is OK :) but I want to calculate this formula for the items:

How can I do this?
Has any library for this?

Body:
I solve the knapsack algorithm in Python, for instance:

weights = [3, 5, 1, 1, 1, 5, 3, 3, 3, 5]
profits = [0, 2, 10, 5, 7, 7, 3, 6, 10, 9]

knapsacks_capacity = [15, 14, 13]

for this sample I got this result:

# knapsack capacity: [[weights],[profits]]
"knapsack 15: [[5, 1, 1, 1, 5], [2, 10, 5, 7, 7]]"
"knapsack 14: [[3, 3, 3, 5], [3, 6, 10, 9]]"
"knapsack 13: [[], []]"

every thing is OK :) but I want to calculate this formula for the items:

How can I do this?
Has any library for this?


问:
compair navbar href to iframe href
I am trying to compair the navbar href to my iframe href, in order to determine which navbar li is active. A helping hand would be greatly appreciated as it does not currently work.

I tried the following javascript on this domain: development.beeldenfabriek.nl/viewer. This domain has an iframe which loads a series of links.

```<code>document.querySelectorAll('.nav-link').forEach(link => {
  console.log(link.href)
  if(link.href === document.getElementById("iFrames").contentWindow.location.href {
    link.setAttribute('aria-current', 'page')
  }
})
</code>```

I expect the bottom border to highlight the current navbar li.

```<code><!doctype html>
<html class="no-js" lang="">

  <head>
    <meta charset="utf-8">
    <title>Viewer</title>
    <meta name="description" content="Description">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:title" content="">
    <meta property="og:type" content="">
    <meta property="og:url" content="">
    <meta property="og:image" content="">
    <link rel="stylesheet" href="stylesheet.css">
  </head>

  <body>
    <div class="topnav" id="myTopnav">
      <ul role="menubar" class="nav-links">
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/impression/" target="iFrames">Impressie</a></li>
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/cinemagraph/" target="iFrames">Cinemagraph</a>
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/animation/" target="iFrames">Animatie</a>
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/woningzoeker/" target="iFrames">Woningzoeker</a>
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/vr/" target="iFrames">VR</a>
        <li><a class="nav-link" href="https://development.beeldenfabriek.nl/visualstory/" target="iFrames">Visual Story</a>
        <li><a class="nav-link" href="https://bf-virtual-experience-elzenhagen.s3.eu-west-2.amazonaws.com/tour.html/" target="iFrames">Spotlight</a>
        <li><a class="projectPagina" href="https://development.beeldenfabriek.nl/template-website" target="_blank">Projectpagina</a>
      </ul>
    </div>
    <section class="embedPages">
      <iframe id="iFrames" name="iFrames" src="https://development.beeldenfabriek.nl/woningzoeker/" width="100%" height="100%" frameBorder="0"></iframe>
    </section>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>
</code>```
```<code>.nav-link[aria-current="page"] {
border-bottom: 3px solid rgba(226, 220, 72, 1.0);
}
</code>```

Title: compair navbar href to iframe href

Body:
I am trying to compair the navbar href to my iframe href, in order to determine which navbar li is active. A helping hand would be greatly appreciated as it does not currently work.

I tried the following javascript on this domain: development.beeldenfabriek.nl/viewer. This domain has an iframe which loads a series of links.

document.querySelectorAll('.nav-link').forEach(link => {
  console.log(link.href)
  if(link.href === document.getElementById("iFrames").contentWindow.location.href {
    link.setAttribute('aria-current', 'page')
  }
})

I expect the bottom border to highlight the current navbar li.

<!doctype html>

    <meta charset="utf-8">
    <title>Viewer</title>
    <meta name="description" content="Description">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:title" content="">
    <meta property="og:type" content="">
    <meta property="og:url" content="">
    <meta property="og:image" content="">
    <link rel="stylesheet" href="stylesheet.css">

Impressie

Cinemagraph

Animatie

Woningzoeker

VR

Visual Story

Spotlight

Projectpagina

.nav-link[aria-current="page"] {
border-bottom: 3px solid rgba(226, 220, 72, 1.0);
}


问:
How to efficiently resize presented child view controller?
This seems like a basic question, but I haven't found a suitable answer on the internet on how to efficiently resize a child view controller presented using .presentAsSheet() on macOS/AppKit. My goal is to have the presented child view controller resize whenever the presenting (i.e. parent) view controller is being resized (through dragging).

With my current implementation below, I experience very unsmooth resizing of the presented NSHostingController. It looks quite laggy in the simulator if you resize the parent window fast enoug.

Is there a better (i.e. more performant/smooth) way to dynamically resize the presented view controller when the parent view controller is resized by the user?

In my presented view controller, I have the following code:

public final class MySwiftUIViewController: NSHostingController<SomeSwiftUIView> {
    private var presentingController: NSViewController? = nil

    public init(configuration: SomeSwiftUIViewConfiguration) {
        super.init(rootView: SomeSwiftUIView(configuration: configuration))

        // General container view config
        self.view.layer?.backgroundColor = .clear
    }

    public func present(in viewController: NSViewController) { // called by the presenting view controller
        self.presentingController = viewController
        viewController.presentAsSheet(self)
    }

    public override func updateViewConstraints() { // resizing happens here
        guard let presentingController = presentingController else { return }
        self.preferredContentSize = NSSize(width: presentingController.view.frame.width * 0.8, height: presentingController.view.frame.height * 0.8)

        super.updateViewConstraints()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Not implemented")
    }
}
```

In above code, the presenting view controller calls the present(in:) function of MySwiftUIViewController which triggers display of the NSHostingController on screen.

I am not sure if this is the right way and it's just the simulator showing an unsmooth resizing operation, or if there's an actual better way to handle the dynamic resizing?

Body:
This seems like a basic question, but I haven't found a suitable answer on the internet on how to efficiently resize a child view controller presented using .presentAsSheet() on macOS/AppKit. My goal is to have the presented child view controller resize whenever the presenting (i.e. parent) view controller is being resized (through dragging).

With my current implementation below, I experience very unsmooth resizing of the presented NSHostingController. It looks quite laggy in the simulator if you resize the parent window fast enoug.

Is there a better (i.e. more performant/smooth) way to dynamically resize the presented view controller when the parent view controller is resized by the user?

In my presented view controller, I have the following code:

public final class MySwiftUIViewController: NSHostingController<SomeSwiftUIView> {
    private var presentingController: NSViewController? = nil

    public init(configuration: SomeSwiftUIViewConfiguration) {
        super.init(rootView: SomeSwiftUIView(configuration: configuration))

        // General container view config
        self.view.layer?.backgroundColor = .clear
    }

    public func present(in viewController: NSViewController) { // called by the presenting view controller
        self.presentingController = viewController
        viewController.presentAsSheet(self)
    }

    public override func updateViewConstraints() { // resizing happens here
        guard let presentingController = presentingController else { return }
        self.preferredContentSize = NSSize(width: presentingController.view.frame.width * 0.8, height: presentingController.view.frame.height * 0.8)

        super.updateViewConstraints()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("Not implemented")
    }
}

In above code, the presenting view controller calls the present(in:) function of MySwiftUIViewController which triggers display of the NSHostingController on screen.

I am not sure if this is the right way and it's just the simulator showing an unsmooth resizing operation, or if there's an actual better way to handle the dynamic resizing?


问:
Keycloak account console email field not visible if email is not set
By default, our users does not have email. But we want to allow users to set / update their emails from account management console.

We have noticed the following issue. When the user does not have an email already set, the email field is not visible from "Personal Info" tab of account management console.

However if we set an email from admin console -> realm -> users, the email field is visible and editable for the user from account management console.

before setting an email for the user (email is null)

after setting an email for the user (without changing any other settings)

Does this mean that users cannot set an email if their email is not already set?

Is there any way we can allow users to set an email themselves?

Note that we don't want to force a user to set their email. It is optional.

If we assign "Update Profile" as a Required user action for user, they are shown our custom theme profile update UI. currently we are manually assigning "Update Profile" Required user action upon request from the user which is not ideal.

We also haven't modified the account management console theme.

Keycloak version: 20.0.1

We have tried switching different options from "Realm Settings" -> "Login" tab. doesn't work

Expecting users to be able to set an email from account management console even when they don't already have an email set


问:
Specify sub-ordinate database name to connect to through Bookshelf model
```<code>## Issue Description

I could not specify a sub-db under the main-db to make query calls as bookshelf does not provide an option to mention a sub-db in its model. I have a db structure like below :

-mainDB
    - sub-db-1
        - table-1
        - table-2
    - sub-db-2
        - table-1
        - table-2
    - sub-db-3
        - table-1
        - table-2

</code>```

Expected Behavior

I would like to mention a sub-db in bookshelf model after connecting to the main-db then make query calls to tables inside the sub-db.

Body:
## Issue Description

I could not specify a sub-db under the main-db to make query calls as bookshelf does not provide an option to mention a sub-db in its model. I have a db structure like below :

-mainDB
    - sub-db-1
        - table-1
        - table-2
    - sub-db-2
        - table-1
        - table-2
    - sub-db-3
        - table-1
        - table-2

Expected Behavior

I would like to mention a sub-db in bookshelf model after connecting to the main-db then make query calls to tables inside the sub-db.


问:
JaxB interfaces / generic object using between different projects
I have different projects:

SharedProject
-> This project is like a .jar. I can use this .jar in several projects. This project is not aware about classes from Project1, Project2....

Project1, Project2, Project3....
-> This project can use classes from "SharedProject"

In Project1, Project2, Project3 I have different "ActionTypes", like "sendEmail", "sendNotification". The information about those actions are stored in XML.
This classes are standalone are not known in any other projects.

I have a XML structure, like this:

```<code> <ActionComponent>
  <Action1>...</Action1>
</ActionComponent>
<ActionComponent>
  <Action2>...</Action2>
</ActionComponent>
</code>```

"Action1" could be "sendEmail", "Action2" could be "sendNotification" etc.
This issue is for me, "SharedProject" is not aware about the classes "Action1" and "Action2", therefore I cannot easily use it like this, otherwise it is working.

```<code>@XmlElements({
            @XmlElement(name = "Action1", type = Action1.class),
            @XmlElement(name = "Action2", type = Action2.class),
    })
    private ActionComponentInterface actionComponentInterface;
</code>```

All classes (Action1, Action2...) are implements the interface "ActionComponentInterface". ActionComponentInterface is part from SharedProject.

What I need is something like a placeholder in the "ActionComponent":

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ActionComponent  {

    // ActionComponentInterface
    private ActionComponentInterface actionComponentInterface;
</code>```

But this code is not working, because I have to specify my classes.

Any idea, how I can solve this?

Body:
I have different projects:

SharedProject
-> This project is like a .jar. I can use this .jar in several projects. This project is not aware about classes from Project1, Project2....

Project1, Project2, Project3....
-> This project can use classes from "SharedProject"

In Project1, Project2, Project3 I have different "ActionTypes", like "sendEmail", "sendNotification". The information about those actions are stored in XML.
This classes are standalone are not known in any other projects.

I have a XML structure, like this:

 <ActionComponent>
  <Action1>...</Action1>
</ActionComponent>
<ActionComponent>
  <Action2>...</Action2>
</ActionComponent>

"Action1" could be "sendEmail", "Action2" could be "sendNotification" etc.
This issue is for me, "SharedProject" is not aware about the classes "Action1" and "Action2", therefore I cannot easily use it like this, otherwise it is working.

@XmlElements({
            @XmlElement(name = "Action1", type = Action1.class),
            @XmlElement(name = "Action2", type = Action2.class),
    })
    private ActionComponentInterface actionComponentInterface;

All classes (Action1, Action2...) are implements the interface "ActionComponentInterface". ActionComponentInterface is part from SharedProject.

What I need is something like a placeholder in the "ActionComponent":

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ActionComponent  {

    // ActionComponentInterface
    private ActionComponentInterface actionComponentInterface;

But this code is not working, because I have to specify my classes.

Any idea, how I can solve this?


问:
Angular Material Chips Field Not Submitting in Form
Problem:

I have a form, inside the form all fields are submitted correctly, however, the chips(aka tags in other frameworks) field(for technologies) does not get submitted.

HTML:

```<code><!--MAIN CONTAINER-->
<div class="container">
    <div class="row">
        <div class="col">
            <!--RESUME FORM-->
            <mat-card class="">
                <mat-card-content>
                    <form #resumeForm="ngForm" (ngSubmit)="submit(resumeForm)" class="m-3">
                        <mat-form-field>
                            <mat-label>Full Name</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.fullname" name="fullname" disabled="true">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Current Role</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.currentRole" name="currentRole">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Email</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.email" name="email" disabled="true">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Description</mat-label>
                            <textarea matInput [(ngModel)]="resume.description" name="description"></textarea>
                        </mat-form-field>

                        <!--TECHNOLOGIES FIELD-->
                        <mat-form-field>
                            <mat-label>Technologies</mat-label>
                            <mat-chip-grid #chipGridTech>
                                <mat-chip-row *ngFor="let tech of techs" (removed)="removeTech(tech)">
                                    {{ tech }}
                                    <button matChipRemove>
                                        <mat-icon>cancel</mat-icon>
                                    </button>
                                </mat-chip-row>
                            </mat-chip-grid>
                            <input #techInput matInput type="text" [(ngModel)]="resume.technologies"
                                placeholder="add new technology..." [formControl]="techControl"
                                [matAutocomplete]="autoComplete" [matChipInputFor]="chipGridTech"
                                [matChipInputSeparatorKeyCodes]="separatorKeysCodesTech"
                                (matChipInputTokenEnd)="addTech($event)" name="technologies" />
                            <mat-autocomplete #autoComplete (optionSelected)="selectTech($event)">
                                <mat-option *ngFor="let tech of filteredTechs | async">
                                    {{ tech }}
                                </mat-option>
                            </mat-autocomplete>
                        </mat-form-field>

                        <!--CERTIFICATIONS FIELD-->
                        <mat-form-field>
                            <mat-label>Certifications</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.certifications" name="certifications">
                        </mat-form-field>

                        <!--WORK EXPERIENCE FIELD-->
                        <mat-form-field>
                            <mat-label>Work Experience</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.workExperience" name="workExperience">
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Education</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.education" name="education">
                        </mat-form-field>
                        <button mat-raised-button color="primary">Submit</button>
                    </form>
                </mat-card-content>
            </mat-card>
        </div>
    </div>
</div>
</code>```

Submit function:

```<code>  submit(resumeForm: any) {
    console.log(resumeForm);
  }
</code>```

Console Log:

I tried:

Adding/Removing matInput

Adding/Removing [(ngModel)]="resume.technologies"

Adding/Removing name="technologies"

Also I get this warning:

Body:
Problem:

I have a form, inside the form all fields are submitted correctly, however, the chips(aka tags in other frameworks) field(for technologies) does not get submitted.

HTML:

            <mat-card class="">
                <mat-card-content>
                    <form #resumeForm="ngForm" (ngSubmit)="submit(resumeForm)" class="m-3">
                        <mat-form-field>
                            <mat-label>Full Name</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.fullname" name="fullname" disabled="true">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Current Role</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.currentRole" name="currentRole">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Email</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.email" name="email" disabled="true">
                        </mat-form-field>
                        <mat-form-field>
                            <mat-label>Description</mat-label>
                            <textarea matInput [(ngModel)]="resume.description" name="description"></textarea>
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Technologies</mat-label>
                            <mat-chip-grid #chipGridTech>
                                <mat-chip-row *ngFor="let tech of techs" (removed)="removeTech(tech)">
                                    {{ tech }}
                                    <button matChipRemove>
                                        <mat-icon>cancel</mat-icon>
                                    </button>
                                </mat-chip-row>
                            </mat-chip-grid>
                            <input #techInput matInput type="text" [(ngModel)]="resume.technologies"
                                placeholder="add new technology..." [formControl]="techControl"
                                [matAutocomplete]="autoComplete" [matChipInputFor]="chipGridTech"
                                [matChipInputSeparatorKeyCodes]="separatorKeysCodesTech"
                                (matChipInputTokenEnd)="addTech($event)" name="technologies" />
                            <mat-autocomplete #autoComplete (optionSelected)="selectTech($event)">
                                <mat-option *ngFor="let tech of filteredTechs | async">
                                    {{ tech }}
                                </mat-option>
                            </mat-autocomplete>
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Certifications</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.certifications" name="certifications">
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Work Experience</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.workExperience" name="workExperience">
                        </mat-form-field>

                        <mat-form-field>
                            <mat-label>Education</mat-label>
                            <input matInput type="text" [(ngModel)]="resume.education" name="education">
                        </mat-form-field>
                        <button mat-raised-button color="primary">Submit</button>
                    </form>
                </mat-card-content>
            </mat-card>

Submit function:

  submit(resumeForm: any) {
    console.log(resumeForm);
  }

Console Log:

I tried:

Adding/Removing matInput

Adding/Removing [(ngModel)]="resume.technologies"

Adding/Removing name="technologies"

Also I get this warning:


问:
Service log only works with breakpoints
I have a function to call a service in Android Kotlin.

I was debugging this service because is not showing in logcat, but when I add a breakpoint in the code works fine. I don't know why is not calling without breakpoint.

```<code>saveNotificationTokenUseCase(someData)
.subscribeOn(Schedulers.io())
.subscribe({}, {})
.dispose() //Works only when I add a breakpoint here
</code>```

///

```<code>class SaveNotificationUseCase @Inject constructor(
 @Services private val uploadNotificationApi: UploadNotificationApi
) {
 operator fun invoke (userData: UserData) : Completable =
 with(userData) {
  return uploadNotificationApi.addToken(userData)
 }
}
</code>```

///

```<code>fun addToken (userData: UserData) {
 /// data...
 return uploadNotificationService.saveToken(data)
}
</code>```

///

```<code>interface UploadNotificationService {
 @POST("endpoint")
 fun saveToken(
  /// body, headers, etc.
 ):Completable
}
</code>```

Title: Service log only works with breakpoints

Body:
I have a function to call a service in Android Kotlin.

I was debugging this service because is not showing in logcat, but when I add a breakpoint in the code works fine. I don't know why is not calling without breakpoint.

saveNotificationTokenUseCase(someData)
.subscribeOn(Schedulers.io())
.subscribe({}, {})
.dispose() //Works only when I add a breakpoint here

///

class SaveNotificationUseCase @Inject constructor(
 @Services private val uploadNotificationApi: UploadNotificationApi
) {
 operator fun invoke (userData: UserData) : Completable =
 with(userData) {
  return uploadNotificationApi.addToken(userData)
 }
}

///

fun addToken (userData: UserData) {
 /// data...
 return uploadNotificationService.saveToken(data)
}

///

interface UploadNotificationService {
 @POST("endpoint")
 fun saveToken(
  /// body, headers, etc.
 ):Completable
}


问:
way to add an html element to my textarea automatically and add the counter in it
I am already using code to resize my javascript textarea,

like this

```<code>var tx = document.getElementsByTagName('textarea');
                    for (var i = 0; i < tx.length; i++) {
                        tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
                        tx[i].addEventListener("input", OnInput, false);
                }

                function OnInput(e) {
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight) + 'px';
                }
</code>```

i am trying to add some functionality to it, like create the span element with javascript just underneath it automatically and start counting the characters. There is no limit on entry, but just keep counting.

and if nothing is entered just showing 0 characters entered

Body:
I am already using code to resize my javascript textarea,

like this

var tx = document.getElementsByTagName('textarea');
                    for (var i = 0; i < tx.length; i++) {
                        tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
                        tx[i].addEventListener("input", OnInput, false);
                }

                function OnInput(e) {
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight) + 'px';
                }

i am trying to add some functionality to it, like create the span element with javascript just underneath it automatically and start counting the characters. There is no limit on entry, but just keep counting.

and if nothing is entered just showing 0 characters entered


问:
Laravel queue:work prints unreadable charachters in cli
I just upgraded from laravel 8 to laravel 9 and when running queue:work i get gibberish characters as shown in the image below:

Then for test i installed a fresh laravel 9 an get the same result.
What can i do to get cli printing like before?

Thanks in advance


问:
Unable to create volume by external provisioner in GKE via Argo pipeline
I have an application in GKE that has been working fine until lately. Now Argo CI pipeline is not working well, it is not creating pod in GKE and throwing the following error in PVC.

```<code>waiting for a volume to be created, either by external provisioner "pd.csi.storage.gke.io" or manually created by system administrator

External provisioner is provisioning volume for claim "argo/build-workspace"
</code>```

It would be great if anyone could help me in figuring this out.

Thanks in advance.

Body:
I have an application in GKE that has been working fine until lately. Now Argo CI pipeline is not working well, it is not creating pod in GKE and throwing the following error in PVC.

waiting for a volume to be created, either by external provisioner "pd.csi.storage.gke.io" or manually created by system administrator

External provisioner is provisioning volume for claim "argo/build-workspace"

It would be great if anyone could help me in figuring this out.

Thanks in advance.