问:
Pycharm: ModuleNotFoundError: No module named 'distutils.cmd'
I'm trying to use opencv module with python.
I have Python3.10.

I installed the module and with the use of Python interpreter in the command line, writing "import cv2" it works fine.

Now, I want to use opencv inside PyCharm.
I went to "File->Settings->Project->Python Interpreter" and then I tried to add the module "opencv-python" but it returned:

```<code>"Error occurred when installing package 'opencv-python'. Details.."
</code>```

and clicking on Details, this is the command output:

```<code>Error: Traceback (most recent call last):
  File "/opt/pycharm-community-2022.3.1/plugins/python-ce/helpers/packaging_tool.py", line 73, in run_pip
runpy.run_module(module_name, run_name='__main__', alter_sys=True)
  File "/usr/lib/python3.9/runpy.py", line 210, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/usr/lib/python3.9/runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/__main__.py", line 29, in <module>
from pip._internal.cli.main import main as _main
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/main.py", line 9, in <module>
from pip._internal.cli.autocompletion import autocomplete
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py", line 10, in <module>
from pip._internal.cli.main_parser import create_main_parser
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py", line 9, in <module>
from pip._internal.build_env import get_runnable_pip
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/build_env.py", line 20, in <module>
from pip._internal.cli.spinners import open_spinner
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/spinners.py", line 9, in <module>
from pip._internal.utils.logging import get_indentation
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/utils/logging.py", line 29, in <module>
from pip._internal.utils.misc import ensure_dir
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/utils/misc.py", line 42, in <module>
from pip._internal.locations import get_major_minor_version
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/locations/__init__.py", line 67, in <module>
from . import _distutils
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/locations/_distutils.py", line 20, in <module>
from distutils.cmd import Command as DistutilsCommand

ModuleNotFoundError: No module named 'distutils.cmd'
</code>```

I didn't found any working solutions for the module distutils.

I tried to install and reinstall the module "python3.10-distutils" but it is already installed.

Someone knows how to solve the problem?
Thanks in advance,

Marco

Body:
I'm trying to use opencv module with python.
I have Python3.10.

I installed the module and with the use of Python interpreter in the command line, writing "import cv2" it works fine.

Now, I want to use opencv inside PyCharm.
I went to "File->Settings->Project->Python Interpreter" and then I tried to add the module "opencv-python" but it returned:

"Error occurred when installing package 'opencv-python'. Details.."

and clicking on Details, this is the command output:

Error: Traceback (most recent call last):
  File "/opt/pycharm-community-2022.3.1/plugins/python-ce/helpers/packaging_tool.py", line 73, in run_pip
runpy.run_module(module_name, run_name='__main__', alter_sys=True)
  File "/usr/lib/python3.9/runpy.py", line 210, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/usr/lib/python3.9/runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/__main__.py", line 29, in <module>
from pip._internal.cli.main import main as _main
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/main.py", line 9, in <module>
from pip._internal.cli.autocompletion import autocomplete
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py", line 10, in <module>
from pip._internal.cli.main_parser import create_main_parser
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py", line 9, in <module>
from pip._internal.build_env import get_runnable_pip
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/build_env.py", line 20, in <module>
from pip._internal.cli.spinners import open_spinner
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/cli/spinners.py", line 9, in <module>
from pip._internal.utils.logging import get_indentation
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/utils/logging.py", line 29, in <module>
from pip._internal.utils.misc import ensure_dir
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/utils/misc.py", line 42, in <module>
from pip._internal.locations import get_major_minor_version
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/locations/__init__.py", line 67, in <module>
from . import _distutils
  File "/home/user/Progetti/SottoProgettiPython/RiconoscimentoFacciale/venv/lib/python3.9/site-packages/pip/_internal/locations/_distutils.py", line 20, in <module>
from distutils.cmd import Command as DistutilsCommand

ModuleNotFoundError: No module named 'distutils.cmd'

I didn't found any working solutions for the module distutils.

I tried to install and reinstall the module "python3.10-distutils" but it is already installed.

Someone knows how to solve the problem?
Thanks in advance,

Marco


来源: stackexchange

问:
Expire S3 objects but prefix for the path is not standard and its changing
Trying to create lifecylce policy on the path such as

```<code>{UUID}/latest/{Run_id}/test_1.csv
</code>```

in the above path- UUID is always changing, latest folder remains same for each of the path, Run ID is also dynamic. How I should expire objects in this directories?

examples

```<code>1ewd7832fdfffdgdgfgfgfgfgfg92/latest/888/test_1.csv
5ewd7832fdfhhhwppafgfgfgfg92d/latest/913/test_1.csv
pquu27gfyt627832fdfhhhfgfg92d/latest/913/test_1.csv
</code>```

Like this I can have multiple paths starting with different UUID.

Can I use wildcard in prefix? such as */latest/

Currently I am trying to see if that works but not finidng any article which suggests that

ContentLicense: CC BY-SA 4.0

Body:
Trying to create lifecylce policy on the path such as

{UUID}/latest/{Run_id}/test_1.csv

in the above path- UUID is always changing, latest folder remains same for each of the path, Run ID is also dynamic. How I should expire objects in this directories?

examples

1ewd7832fdfffdgdgfgfgfgfgfg92/latest/888/test_1.csv
5ewd7832fdfhhhwppafgfgfgfg92d/latest/913/test_1.csv
pquu27gfyt627832fdfhhhfgfg92d/latest/913/test_1.csv

Like this I can have multiple paths starting with different UUID.

Can I use wildcard in prefix? such as */latest/

Currently I am trying to see if that works but not finidng any article which suggests that


问:
How to explicitly parse username and password in docker.withRegistry() method of the dockerhub plugin used in a Jenkins Declarative pipeline
I'm trying to push a Docker image from Jenkins to DockerHub using a declarative pipeline. The DockerHub's credentials are stored in Vault. And, I wish to use the Docker plugin in my pipeline's syntax.

My following tries were successful:

If I store Dockerhub's credentials in Jenkins, the pipeline works fine with the following code snippet:

```<code>stage('Publish the Docker Image on DockerHub')
{
    steps {
        script {
            docker.withRegistry('', 'dockerhub-credentials'){
                dockerImage.push()
            }
        }
    }
}
</code>```

If I store Dockerhub's credentials in Vault and use shell commands to login, then too the pipeline works successful with the code snippet as below:

```<code>stage('Publish the Docker Image on DockerHub')
{
    steps
    {
        withVault(
            configuration: \
            [
                timeout: 60,
                vaultCredentialId: 'vault-jenkins-approle-creds',
                vaultUrl: 'http://172.31.32.203:8200'
            ],
            vaultSecrets:
            [[
                engineVersion: 2,
                path: 'secret/credentials/dockerhub',
                secretValues:
                [
                    [envVar: 'DOCKERHUB_USERNAME', vaultKey: 'username'],
                    [envVar: 'DOCKERHUB_PASSWORD', vaultKey: 'password']
                ]
            ]]
        )
        {
            script
            {
                sh "docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD"
                sh "docker push <docker-hub-repo>"
            }
        }
    }
}
</code>```

Now, my query is how to parse the Username+Password credentials (obtained in 2) inside the docker.withRegistry() method (used in 1)?

Body:
I'm trying to push a Docker image from Jenkins to DockerHub using a declarative pipeline. The DockerHub's credentials are stored in Vault. And, I wish to use the Docker plugin in my pipeline's syntax.

My following tries were successful:

If I store Dockerhub's credentials in Jenkins, the pipeline works fine with the following code snippet:

stage('Publish the Docker Image on DockerHub')
{
    steps {
        script {
            docker.withRegistry('', 'dockerhub-credentials'){
                dockerImage.push()
            }
        }
    }
}

If I store Dockerhub's credentials in Vault and use shell commands to login, then too the pipeline works successful with the code snippet as below:

stage('Publish the Docker Image on DockerHub')
{
    steps
    {
        withVault(
            configuration: \
            [
                timeout: 60,
                vaultCredentialId: 'vault-jenkins-approle-creds',
                vaultUrl: 'http://172.31.32.203:8200'
            ],
            vaultSecrets:
            [[
                engineVersion: 2,
                path: 'secret/credentials/dockerhub',
                secretValues:
                [
                    [envVar: 'DOCKERHUB_USERNAME', vaultKey: 'username'],
                    [envVar: 'DOCKERHUB_PASSWORD', vaultKey: 'password']
                ]
            ]]
        )
        {
            script
            {
                sh "docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD"
                sh "docker push <docker-hub-repo>"
            }
        }
    }
}

Now, my query is how to parse the Username+Password credentials (obtained in 2) inside the docker.withRegistry() method (used in 1)?


问:
How to test if axios instance is called?
I'm trying to test if the axios instance "myApi" is being called

function code

```<code>const myApi = axios.create({
  baseURL
})

async function auth () {
    const request = await myApi.post('/authorization', {
      email,
      password
    })
    return request
}
</code>```

how can I access the "myApi" instance in the test?

Body:
I'm trying to test if the axios instance "myApi" is being called

function code

const myApi = axios.create({
  baseURL
})

async function auth () {
    const request = await myApi.post('/authorization', {
      email,
      password
    })
    return request
}

how can I access the "myApi" instance in the test?


问:
How to graph high resolution in Python?
I am trying to graph a bar graph in Python. The problem is that there are 85 different country names I am trying to label in the x-axis.

I tried making the names large enough to read using pyplot using a font of 16. I can zoom in on certain parts of the graph and see the whole names without overlapping, but without zoom the names are overlapping and unreadable. I also tried to make the names small enough to not overlap using a font size of 1, but it is unreadable at any zoom.

Title: How to graph high resolution in Python?


问:
Why WooCommerce checkout page show notice many times
I'm using WooCommerce with Divi theme. But when I custom checkout page with divi modules then It show validate errors for all module (not only billing form). And It require fullname even though fullname is not empty.

Do someone know why?

Thanks in advances.


问:
How to write an npm package that uses crypto in browser but falls back to node:crypto on server
I maintain a package called react-querybuilder that generates unique identifiers using crypto.getRandomValues().

When used in the browser, this is not a problem as crypto is available pretty much everywhere now. But react-querybuilder can be used on the server for query processing (including generating IDs) as well as server-side rendering, which means the crypto package must either be polyfilled with crypto-browserify or loaded manually (something like globalThis.crypto = require('node:crypto')).

Some build setups require the polyfill even if they don't do SSR, e.g. Create React App v5 since it uses Webpack v5 (which doesn't automatically include polyfills like v4 did). CRA v4 doesn't have the issue.

How can I write the package to use window.crypto when running in the browser, but load node:crypto and use that instead when running on the server? Ideally the setup would avoid requiring anything extra of the end user (polyfills, config, etc.).

This is the current implementation at time of writing (comments removed):

```<code>let cryptoModule = globalThis.crypto;

if (!cryptoModule && typeof require === "function") {
  cryptoModule = require("crypto").webcrypto;
}

const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
const position19vals = ["8", "9", "a", "b"];
const re = /[xy]/g;
const container = new Uint32Array(32);

export const generateID = () => {
  cryptoModule.getRandomValues(container);
  let i = -1;
  return template.replaceAll(re, (char) => {
    i++;
    return char === "y"
      ? position19vals[container[i] % 4]
      : (container[i] % 16).toString(16);
  });
};
</code>```

FWIW, I'm not opposed to having separate builds for client and server if that makes it easier to implement (for me and the end user, but mostly the end user).

Body:
I maintain a package called react-querybuilder that generates unique identifiers using crypto.getRandomValues().

When used in the browser, this is not a problem as crypto is available pretty much everywhere now. But react-querybuilder can be used on the server for query processing (including generating IDs) as well as server-side rendering, which means the crypto package must either be polyfilled with crypto-browserify or loaded manually (something like globalThis.crypto = require('node:crypto')).

Some build setups require the polyfill even if they don't do SSR, e.g. Create React App v5 since it uses Webpack v5 (which doesn't automatically include polyfills like v4 did). CRA v4 doesn't have the issue.

How can I write the package to use window.crypto when running in the browser, but load node:crypto and use that instead when running on the server? Ideally the setup would avoid requiring anything extra of the end user (polyfills, config, etc.).

This is the current implementation at time of writing (comments removed):

let cryptoModule = globalThis.crypto;

if (!cryptoModule && typeof require === "function") {
  cryptoModule = require("crypto").webcrypto;
}

const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
const position19vals = ["8", "9", "a", "b"];
const re = /[xy]/g;
const container = new Uint32Array(32);

export const generateID = () => {
  cryptoModule.getRandomValues(container);
  let i = -1;
  return template.replaceAll(re, (char) => {
    i++;
    return char === "y"
      ? position19vals[container[i] % 4]
      : (container[i] % 16).toString(16);
  });
};

FWIW, I'm not opposed to having separate builds for client and server if that makes it easier to implement (for me and the end user, but mostly the end user).


问:
Create Page object - Spring boot
I'm trying to create a page object from a repository query, when return the data to a List works fine, but if i try to return the data to a Page object the query fails, getting this error

```<code>[nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [17]
2023-01-05 12:34:09.327  WARN 20644 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2023-01-05 12:34:09.331 ERROR 20644 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near "WHERE"
</code>```

What am i doing wrong?

LIST WAY (WORKS FINE)

Query

```<code>@Query(value ="SELECT field1 as idSolicitud, field2 as numeroRadicado, "
        + "field3 as tipoTramite, field4 as nombreTramite "
        + "FROM myTable WHERE field5 = :paramet", nativeQuery = true)
List<SolicitudesInterfaceDTO> buscarSolicitudes(@Param("paramet") Long paramet);
</code>```

DTO (Interface)

```<code>public interface SolicitudesInterfaceDTO {

    Long getidSolicitud();
    String getnumeroRadicado();
    String gettipoTramite();
    String getnombreTramite();
    String getestado();
}
</code>```

Execute query

```<code>List<SolicitudesInterfaceDTO> solicitudesUsuario = solicitudesRepository.buscarSolicitudes(idUsuario);
</code>```

PAGE WAY (Doesn't work)

Query

```<code>@Query(value ="SELECT field1 as idSolicitud, field2 as numeroRadicado, "
        + "field3 as tipoTramite, field4 as nombreTramite "
        + "FROM myTable WHERE field5 = :paramet", nativeQuery = true)
Page<SolicitudesInterfaceDTO> buscarSolicitudesPaginado(@Param("paramet") Long paramet, Pageable pageable);
</code>```

Execute query

```<code>Page<SolicitudesInterfaceDTO> paginaSolicitudesUsuario = solicitudesRepository.buscarSolicitudesPaginado(idUsuario, pageable);
</code>```

Title: Create Page object - Spring boot

Body:
I'm trying to create a page object from a repository query, when return the data to a List works fine, but if i try to return the data to a Page object the query fails, getting this error

[nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [17]
2023-01-05 12:34:09.327  WARN 20644 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2023-01-05 12:34:09.331 ERROR 20644 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near "WHERE"

What am i doing wrong?

LIST WAY (WORKS FINE)

Query

@Query(value ="SELECT field1 as idSolicitud, field2 as numeroRadicado, "
        + "field3 as tipoTramite, field4 as nombreTramite "
        + "FROM myTable WHERE field5 = :paramet", nativeQuery = true)
List<SolicitudesInterfaceDTO> buscarSolicitudes(@Param("paramet") Long paramet);

DTO (Interface)

public interface SolicitudesInterfaceDTO {

    Long getidSolicitud();
    String getnumeroRadicado();
    String gettipoTramite();
    String getnombreTramite();
    String getestado();
}

Execute query

List<SolicitudesInterfaceDTO> solicitudesUsuario = solicitudesRepository.buscarSolicitudes(idUsuario);

PAGE WAY (Doesn't work)

Query

@Query(value ="SELECT field1 as idSolicitud, field2 as numeroRadicado, "
        + "field3 as tipoTramite, field4 as nombreTramite "
        + "FROM myTable WHERE field5 = :paramet", nativeQuery = true)
Page<SolicitudesInterfaceDTO> buscarSolicitudesPaginado(@Param("paramet") Long paramet, Pageable pageable);

Execute query

Page<SolicitudesInterfaceDTO> paginaSolicitudesUsuario = solicitudesRepository.buscarSolicitudesPaginado(idUsuario, pageable);


问:
Is there a way to get metaStyles when converting docx to markdown with pandoc?
Is there a way to get word paragraphs with metaStyles (Title, Subtitle, Author, Date, Abstract) converted to markdown with custom-style attribute?

To reproduce it:

A word document with a single paragraph "MyTitle" styled with "Title"

Without the --standalone option the metaStyles are ignored.
When using the --standalone option the metaStyles are exported to meta data in markdown as follows:

```<code>---
title: MyTitle
---
</code>```

What I need is to get the following in markdown (for Title, Subtitle etc.):

```<code>::: {custom-style="Title"}
MyTitle
:::
</code>```

I'd expect it when using -f docx+styles but this is only the case when the word document starts with a non-metaStyle paragraph!

To reproduce it:

A word document with two paragraphs:

First paragraph "std" styled with "Standard"

Second paragraph "MyTitle" styled with "Title"

Body:
Is there a way to get word paragraphs with metaStyles (Title, Subtitle, Author, Date, Abstract) converted to markdown with custom-style attribute?

To reproduce it:

A word document with a single paragraph "MyTitle" styled with "Title"

Without the --standalone option the metaStyles are ignored.
When using the --standalone option the metaStyles are exported to meta data in markdown as follows:

---
title: MyTitle
---

What I need is to get the following in markdown (for Title, Subtitle etc.):

::: {custom-style="Title"}
MyTitle
:::

I'd expect it when using -f docx+styles but this is only the case when the word document starts with a non-metaStyle paragraph!

To reproduce it:

A word document with two paragraphs:

First paragraph "std" styled with "Standard"

Second paragraph "MyTitle" styled with "Title"


问:
CGAL exact predicate inexact constructions
I know that it is possible to get exact comparison results without constructing the objects exactly by using exact_predicate_inexact_constructions kernel in CGAL. The thing that I wonder is upto which degree I can use the inexact objects to get an exact result. To be more clear, let me give an example: I want to compare two distances, distance between the points p and q1 and distance between the points p and q2. The problem is, both q1 and q2 are not computed yet, they will be found after a few intersection/projection operations. Moreover, for those geometrical operations, there is need to do some vector/direction computations. At the final, I do not need to know none of those interstep objects (none of the vectors, intersection lines, even q1 and q2). The only thing I want to reach is which distance is less than the other. If I define each object with the above kernel and find each interstep object with projection/intersection operation of that kernel and call the comparison function of the same kernel also, would the result that I reach be exact?


问:
Dart Web Request and Response as a Stream of data
I have been trying to setup an HTTP connection from a Dart client to a Dart Server using the HttpServer and HttpClient classes respectively.

I want to use this connection to transmit event updates to the client whenever the server feels necessary, so the connection needs to be continuous and the response needs to be sent in chunks, not buffered.

I tried this approach using two different server configurations (once with HttpServer, once with Shelf), but both times the response awaited closing and then the data was printed by the client.

Here is my server code:

```<code>var httpsServer = await io.HttpServer.bind("127.0.0.1", 4001);
httpsServer.listen((request) {
    request.response.bufferOutput = false;
    request.response.headers.add("Content-Type", "text/event-stream");
    request.response.headers.add("Cache-Control", "no-cache");
    request.response.headers.add("Connection", "keep-alive");

    // asynchronously write "Hello" every 100 ms
    Timer.periodic(Duration(milliseconds: 100), (Timer timer) {
      try {
        request.response.write("Hello\n");
      } catch (_) {
        timer.cancel();
      }
    });
    await Future.delayed(Duration(seconds: 3));
    request.response.close();
});
</code>```

And another using shelf:

```<code>{
    var handler = const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest);
    var server = await serve(handler, '127.0.0.1', 4000);
    server.autoCompress = true;
}

FutureOr<Response> _echoRequest(Request request) {
  Stream<List<int>> stream = Stream.periodic(Duration(milliseconds: 100), (int i) {
    return utf8.encode("Hello\n");
  }).take(10);
  return Response.ok(stream);
}
</code>```

However, on the client, I only receive the data once the connection has been closed:

```<code>HttpClient client = HttpClient()..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
  HttpClientRequest request = await client.postUrl(Uri.parse('https://---/'));
  request.headers.add('Content-Type', 'text/event-stream');
  HttpClientResponse response = await request.close();
  // use startChunkConversion to convert the stream of bytes to a stream of strings
  Stream<String> stream = response.transform(utf8.decoder).transform(const LineSplitter());
  await for (String line in stream) {
    print(line);
  }
</code>```

Am I doing something wrong or would I be better off with a different library / approach?

Body:
I have been trying to setup an HTTP connection from a Dart client to a Dart Server using the HttpServer and HttpClient classes respectively.

I want to use this connection to transmit event updates to the client whenever the server feels necessary, so the connection needs to be continuous and the response needs to be sent in chunks, not buffered.

I tried this approach using two different server configurations (once with HttpServer, once with Shelf), but both times the response awaited closing and then the data was printed by the client.

Here is my server code:

var httpsServer = await io.HttpServer.bind("127.0.0.1", 4001);
httpsServer.listen((request) {
    request.response.bufferOutput = false;
    request.response.headers.add("Content-Type", "text/event-stream");
    request.response.headers.add("Cache-Control", "no-cache");
    request.response.headers.add("Connection", "keep-alive");

    // asynchronously write "Hello" every 100 ms
    Timer.periodic(Duration(milliseconds: 100), (Timer timer) {
      try {
        request.response.write("Hello\n");
      } catch (_) {
        timer.cancel();
      }
    });
    await Future.delayed(Duration(seconds: 3));
    request.response.close();
});

And another using shelf:

{
    var handler = const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest);
    var server = await serve(handler, '127.0.0.1', 4000);
    server.autoCompress = true;
}

FutureOr<Response> _echoRequest(Request request) {
  Stream<List<int>> stream = Stream.periodic(Duration(milliseconds: 100), (int i) {
    return utf8.encode("Hello\n");
  }).take(10);
  return Response.ok(stream);
}

However, on the client, I only receive the data once the connection has been closed:

HttpClient client = HttpClient()..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
  HttpClientRequest request = await client.postUrl(Uri.parse('https://---/'));
  request.headers.add('Content-Type', 'text/event-stream');
  HttpClientResponse response = await request.close();
  // use startChunkConversion to convert the stream of bytes to a stream of strings
  Stream<String> stream = response.transform(utf8.decoder).transform(const LineSplitter());
  await for (String line in stream) {
    print(line);
  }

Am I doing something wrong or would I be better off with a different library / approach?


问:
Knitting a Markdown pdf with only a few modifications
I have an R Markdown script that takes more than two hours to run.

Sometimes I just want to make a small modification and knit it again to a pdf, but it seems like a waste of time to run the whole script for hours just for that little change.

Is there any way I can "save" what I've already knitted, so that when I knit again with a small change, it can knit only the part where it's changed?


问:
How to access the Always free Apex Instance through Public IP
OCI Always Free Apex Application Created.
Public IP is available to the instance.
How to access Application using Public IP.
How to add Public IP in Apex Application?</p>


问:
How to stop maven-remote-resources-plugin from overwritting resources
in my application i have many modules with resources.

```<code>project
|
└───moduleA
|   |
│   └───resources
│       │
│       └───fileA
|
└───moduleB
|   |
│   └───resources
│
└───moduleC
|   |
|   └───resources
|       │
|       |───fileA
|       └───fileB
|
...
</code>```

In moduleA and moduleB i use maven-remote-resources plugin to include resources (fileA and fileB) from moduleC. If the file with a given name exists in a moduleA or B, it should not be overwritten with the one from moduleC. Files get overwritten by default. How to configure the plugin to avoid that?

Body:
in my application i have many modules with resources.

project
|
└───moduleA
|   |
│   └───resources
│       │
│       └───fileA
|
└───moduleB
|   |
│   └───resources
│
└───moduleC
|   |
|   └───resources
|       │
|       |───fileA
|       └───fileB
|
...

In moduleA and moduleB i use maven-remote-resources plugin to include resources (fileA and fileB) from moduleC. If the file with a given name exists in a moduleA or B, it should not be overwritten with the one from moduleC. Files get overwritten by default. How to configure the plugin to avoid that?


问:
Creating support for JSON payload protocol in scapy
I am working to create a new scapy protocol which will have raw json load packed into UDP datagram
This protocol works on a specific udp dport(say 12445) and sport(say 12446)

In order to bind these layers - created following scapy layer file with simple protocol definition and binding as shown below (using bind_layers(UDP, SomeJSONProtocol, dport=12445, sport=12446))

```<code>from scapy.packet import *
from scapy.sendrecv import srp

class Type1(Raw):
    name = "Type1"

class Type2(Raw):
    name = "Type2"

class SomeJSONProtocol(Raw):
    name = "Some JSON protocol"

    def guess_payload_class(self, payload):
        print('Guessing Payload')
        try:
            base_dict = loads(self.load.decode('latin-1', errors='replace')).get('base_key')
        except:
            pass
        else:
            if base_dict.get('Type') == "Type1":
                return Type1
            elif base_dict.get('Type') == "Type2":
                return Type2
        return Raw.guess_payload_class(self, payload)

    def answers(self, other):
        if not isinstance(other, SomeJSONProtocol):
            return 0
        return 1

bind_layers(UDP, SomeJSONProtocol, dport=12445, sport=12446)
</code>```

Then I tried to test it but I am unable to capture any answers - although I am detecting correct udp packets received in wireshark. Following is the code used to detect the answers

pkt = Ether(
src=<iface_mac>,
dst=<broadcast_mac>,
type=<protocol_type>
) / IP(
src=<if_ip_address>,
dst=<broadcast_ip>
) / UDP(
sport=12446,
dport=12445
) / SomeJSONProtocol(
load=json.dumps(
{
"base_key": {
"Type": "Type1",
}
}
)
)

```<code>from scapy.all import conf
iface = conf.route.route(<iface_ip>)[0]

ans, unans = srp(pkt, iface=iface, timeout=10)
if ans:
    #print(ans)
    if ans[0][1]:
        #ans[0][1].show()
        return ErrorCodes.OK, {}
return ErrorCodes.ERROR, {}
</code>```

But I am not receiving any answers detected by scapy

I also tried to override the post_build method to check if that is being called - and I detected that the call to post_build was made. So I am not sure why its not guessing the correct payload class. Any support here would be really appreciated.

Thanks

Body:
I am working to create a new scapy protocol which will have raw json load packed into UDP datagram
This protocol works on a specific udp dport(say 12445) and sport(say 12446)

In order to bind these layers - created following scapy layer file with simple protocol definition and binding as shown below (using bind_layers(UDP, SomeJSONProtocol, dport=12445, sport=12446))

from scapy.packet import *
from scapy.sendrecv import srp

class Type1(Raw):
    name = "Type1"

class Type2(Raw):
    name = "Type2"

class SomeJSONProtocol(Raw):
    name = "Some JSON protocol"

    def guess_payload_class(self, payload):
        print('Guessing Payload')
        try:
            base_dict = loads(self.load.decode('latin-1', errors='replace')).get('base_key')
        except:
            pass
        else:
            if base_dict.get('Type') == "Type1":
                return Type1
            elif base_dict.get('Type') == "Type2":
                return Type2
        return Raw.guess_payload_class(self, payload)

    def answers(self, other):
        if not isinstance(other, SomeJSONProtocol):
            return 0
        return 1

bind_layers(UDP, SomeJSONProtocol, dport=12445, sport=12446)

Then I tried to test it but I am unable to capture any answers - although I am detecting correct udp packets received in wireshark. Following is the code used to detect the answers

pkt = Ether(
src=<iface_mac>,
dst=<broadcast_mac>,
type=<protocol_type>
) / IP(
src=<if_ip_address>,
dst=<broadcast_ip>
) / UDP(
sport=12446,
dport=12445
) / SomeJSONProtocol(
load=json.dumps(
{
"base_key": {
"Type": "Type1",
}
}
)
)

from scapy.all import conf
iface = conf.route.route(<iface_ip>)[0]

ans, unans = srp(pkt, iface=iface, timeout=10)
if ans:
    #print(ans)
    if ans[0][1]:
        #ans[0][1].show()
        return ErrorCodes.OK, {}
return ErrorCodes.ERROR, {}

But I am not receiving any answers detected by scapy

I also tried to override the post_build method to check if that is being called - and I detected that the call to post_build was made. So I am not sure why its not guessing the correct payload class. Any support here would be really appreciated.

Thanks


问:
Wrong output value Using C# in VSCode (warning: CS7022)
I'm currently new to C# and busy learning the basics and discovered this problem when starting: C# Beginner Code
But the output is Hello, World!: Hello, World!

Before Anyone asks did I remember to save changes when changing the text: Yes...I pressed CTRL + S.

(PS: If anyone could also help me fix the "warning: CS7022" Error I am Getting, it may be the problem for the wrong output problem I am facing.)

(Additional Information: Working on C:/ but storing data on E:/, Installed .NET SDK for VSCode (LTS version), Installed C# Extension and Code Runner on VSCode, Windows 11)

I copied the Error/Warning text and googled it but nothing really came up. I also searched "Wrong output C#" but nothing also.


问:
Best way to finish a while loop for api request?
So i realized after printing my data to json that my api call isnt finishing, how can i go about creating a count down timer? I am using the cursor value which doesnt really change and i cannot use the rel links, if im able to get the totalPages, can i count down based off the variable or is there a better way to end the python api requests?

my current method doesnt really work since there's always a cursor, but it works as far as never ending the while loop

i thought i could do count = totalpage -1 but that isnt working either, this is what i have so far

```<code>
from curses import raw, reset_shell_mode
from http import server
from turtle import pd
import requests, sys
import urllib3
from pathlib import Path
import json
from datetime import datetime
from requests import Session
from typing import Any, List, Tuple, Dict
import pandas as pd
from requests.adapters import HTTPAdapter, Retry
from collections import Counter

# disable urllib3 warnings for SSL
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sys.path.append('/Users/s153152/Documents/Workspace/kpi/rapid7')

def _headers():
    headers = {
            'X-Api-Key': 'key',
            'Content-type':'application/json',
            'Accept':'*/*'
            }
    return headers

def _request():

    third_party_patching_filer = {
    "asset": "asset.tags IN ['osswin'] && asset.os.vendor CONTAINS 'microsoft' && asset.agentKey IS NOT NULL",
    "vulnerability" : "vulnerability.categories NOT IN ['microsoft patch']"}

    headers = _headers()
    print(headers)
    url1 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets?&size=50"
    resp = requests.post(url=url1, headers=headers, json=third_party_patching_filer, verify=False).json()

    has_next_cursor = True
    nextKey = ""
    totalpage = resp["metadata"]
    print(totalpage)

    total_server_ip_addresses = []
    osname_server1 = []
    total_critical_vul_osswin = []
    results = []

    with requests.Session() as session:
        url2 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets?&size=50&cursor={nextKey}"

        while has_next_cursor:

            s = requests.Session()
            backoff_factor=0.3
            retries = Retry(total=10, backoff_factor=backoff_factor, status_forcelist=[ 502, 503, 504 ])
            s.mount(url2, HTTPAdapter(max_retries=retries))
            s = s.post(url=url2, headers=headers, json=third_party_patching_filer, verify=False)
            print(s.status_code)
            s = s.json()

            rel_last = s["metadata"]
            cursor = s["metadata"]

            if "cursor" in cursor:

                nextKey = cursor["cursor"]
                totalResources = cursor["totalResources"]
                count = totalpage -1

                print(f"next key {nextKey}, total resourcs {totalResources}")
                print(f"{count}")
                #print(desktop_support)

                for data in s["data"]:
                    for tags in data['tags']:

                        if tags["name"] == 'OSSWIN':
                            try:
                                osname_server = data['host_name']
                                server_host_ip_address = data['ip']
                                critical_vuln_osswin = data['critical_vulnerabilities']
                                os_type = data['os_type']
                                data = {
                                    'ip_address': server_host_ip_address,
                                    'os_name': osname_server,
                                    'critical_vuln': critical_vuln_osswin,
                                    'os_type': os_type
                                }
                                results.append(data)
                            except Exception as e:
                                f"Possibly no ip address, error {e}"
                            #print(f"Server asset: {osname_server1}, {total_server_ip_addresses}")

                            with open('server_info.json', 'w') as f:
                                json.dump(results, f, indent=2)

                            #print(data['host_name'])

        else:
            has_next_cursor = False

    return total_server_ip_addresses, sum(total_server_ip_addresses)

def smart_filter():
    test = _request()
    print(test)

smart_filter()
</code>```

count down from variable to finish the api call

Body:
So i realized after printing my data to json that my api call isnt finishing, how can i go about creating a count down timer? I am using the cursor value which doesnt really change and i cannot use the rel links, if im able to get the totalPages, can i count down based off the variable or is there a better way to end the python api requests?

my current method doesnt really work since there's always a cursor, but it works as far as never ending the while loop

i thought i could do count = totalpage -1 but that isnt working either, this is what i have so far

from curses import raw, reset_shell_mode
from http import server
from turtle import pd
import requests, sys
import urllib3
from pathlib import Path
import json
from datetime import datetime
from requests import Session
from typing import Any, List, Tuple, Dict
import pandas as pd
from requests.adapters import HTTPAdapter, Retry
from collections import Counter

# disable urllib3 warnings for SSL
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sys.path.append('/Users/s153152/Documents/Workspace/kpi/rapid7')

def _headers():
    headers = {
            'X-Api-Key': 'key',
            'Content-type':'application/json',
            'Accept':'*/*'
            }
    return headers

def _request():

    third_party_patching_filer = {
    "asset": "asset.tags IN ['osswin'] && asset.os.vendor CONTAINS 'microsoft' && asset.agentKey IS NOT NULL",
    "vulnerability" : "vulnerability.categories NOT IN ['microsoft patch']"}

    headers = _headers()
    print(headers)
    url1 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets?&size=50"
    resp = requests.post(url=url1, headers=headers, json=third_party_patching_filer, verify=False).json()

    has_next_cursor = True
    nextKey = ""
    totalpage = resp["metadata"]
    print(totalpage)

    total_server_ip_addresses = []
    osname_server1 = []
    total_critical_vul_osswin = []
    results = []

    with requests.Session() as session:
        url2 = f"https://us.api.insight.rapid7.com/vm/v4/integration/assets?&size=50&cursor={nextKey}"

        while has_next_cursor:

            s = requests.Session()
            backoff_factor=0.3
            retries = Retry(total=10, backoff_factor=backoff_factor, status_forcelist=[ 502, 503, 504 ])
            s.mount(url2, HTTPAdapter(max_retries=retries))
            s = s.post(url=url2, headers=headers, json=third_party_patching_filer, verify=False)
            print(s.status_code)
            s = s.json()

            rel_last = s["metadata"]
            cursor = s["metadata"]

            if "cursor" in cursor:

                nextKey = cursor["cursor"]
                totalResources = cursor["totalResources"]
                count = totalpage -1

                print(f"next key {nextKey}, total resourcs {totalResources}")
                print(f"{count}")
                #print(desktop_support)

                for data in s["data"]:
                    for tags in data['tags']:

                        if tags["name"] == 'OSSWIN':
                            try:
                                osname_server = data['host_name']
                                server_host_ip_address = data['ip']
                                critical_vuln_osswin = data['critical_vulnerabilities']
                                os_type = data['os_type']
                                data = {
                                    'ip_address': server_host_ip_address,
                                    'os_name': osname_server,
                                    'critical_vuln': critical_vuln_osswin,
                                    'os_type': os_type
                                }
                                results.append(data)
                            except Exception as e:
                                f"Possibly no ip address, error {e}"
                            #print(f"Server asset: {osname_server1}, {total_server_ip_addresses}")

                            with open('server_info.json', 'w') as f:
                                json.dump(results, f, indent=2)

                            #print(data['host_name'])

        else:
            has_next_cursor = False

    return total_server_ip_addresses, sum(total_server_ip_addresses)

def smart_filter():
    test = _request()
    print(test)

smart_filter()

count down from variable to finish the api call


问:
Google App Script to paste cell value to another spreadsheet based on column A and column header
I have 2 spreadsheets, source and destination. I need to paste the value from source to destination based on Column A and column header, much like a matrix lookup but will not affect the other existing data in the destination unless matches from the source and also will ignore blanks from the source

example

source:

```<code>| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  |          | 245      |          |
| Apple    |          | 600      | 500      |
</code>```

destination:

```<code>| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  | 100      |          | 900      |
| Apple    | 45       |          |          |
</code>```

final output in destination:

```<code>| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  | 100      |  245     | 900      |
| Apple    | 45       |  600     | 500      |
</code>```

EDIT:

This is not similar to this question: copy data from one sheet to another in google app script and append a row, one small issue

in my case, the destination is has data already, and the data from source will just update/add the existing data in the destination spreadsheet, and this can be in the anywhere in the spreadsheet, thus it should look for the specific criteria in column A and in column header. This has been told in the original question already

Body:
I have 2 spreadsheets, source and destination. I need to paste the value from source to destination based on Column A and column header, much like a matrix lookup but will not affect the other existing data in the destination unless matches from the source and also will ignore blanks from the source

example

source:

| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  |          | 245      |          |
| Apple    |          | 600      | 500      |

destination:

| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  | 100      |          | 900      |
| Apple    | 45       |          |          |

final output in destination:

| Column A | Header 1 | Header 2 | Header 3 |
| -------- | -------- | -------- | -------- |
| Pumpkin  | 100      |  245     | 900      |
| Apple    | 45       |  600     | 500      |

EDIT:

This is not similar to this question: copy data from one sheet to another in google app script and append a row, one small issue

in my case, the destination is has data already, and the data from source will just update/add the existing data in the destination spreadsheet, and this can be in the anywhere in the spreadsheet, thus it should look for the specific criteria in column A and in column header. This has been told in the original question already


问:
Autocompletion of import statements in VS code for Java
Whenever I am creating a new java file in Intelij, all the import statement are handled by the IDE itself. Is there any way to get this feature in vs code(any extensions or setting I can toggle)

I have installed the Microsoft extensions for java but that doesn't seem to do the trick out of the box.


问:
Create DataFrame having trouble
I'm trying to convert views_dict[2017] to a dataframe. Using jupyter notebook. If I use variable of views_dict I have numerous years in dictionary format.

views_dict[2017]

[2102206,
1331781,
925375,
382331,
321960,
278439,
231613,
206570,
179082,
173855,
137089,
123836,
122077,
120140,
114837,
108279,
103176,
93963,
79388,
72907]

df = pd.DataFrame(list(zip(views_dict)), columns = ['views'])
df

NameError                                 Traceback (most recent call last)
Input In [27], in <cell line: 1>()
----> 1 df = pd.DataFrame(list(zip(views_dict)), columns = ['views'])
2 df

NameError: name 'pd' is not defined

Title: Create DataFrame having trouble


问:
error in Flask-Admin while extending template "admin/master.html"
I'm new to Flask and while following some youtube tutorials for Flask-Admin, I came across the fact that we need to create the admin panel by extending the template in "admin/index.html"

The instructor said that the 'admin/master.html' is an implicit file and we don't need to create it but do need to extend it.

But I'm getting a error message that says that the template "admin/master.html" couldn't be found.

How do I work this problem out?

This is the error log

```<code>[2023-01-05 23:13:42,958] ERROR in app: Exception on /admin/ [GET]
Traceback (most recent call last):
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/SSD_Data/DevFile/AayushPokharel/app/admin/routes.py", line 7, in adminRoute
    return render_template("admin/index.html")
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 147, in render_template
    return _render(app, template, context)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 130, in _render
    rv = template.render(context)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "/SSD_Data/DevFile/AayushPokharel/app/templates/admin/index.html", line 1, in top-level template code
    {% extends 'admin/master.html' %} {% block body %}
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 62, in get_source
    return self._get_source_fast(environment, template)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 98, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: admin/master.html
127.0.0.1 - - [05/Jan/2023 23:13:42] "GET /admin/ HTTP/1.1" 500 -
</code>```

This is my admin template

```<code><!--app/templates/admin/index.html-->

{% extends 'admin/master.html' %} {% block body %}
<p>This is Admin Page</p>
{% endblock %}
</code>```

my admin init blueprint

```<code># app/admin/__init__.py

from flask import Blueprint
from flask_admin.contrib.sqla import ModelView
from app.extensions import admin, db
from app.models.user import User

bp = Blueprint("admin", __name__)

admin.add_view(ModelView(User, db.session))

from app.admin import routes
</code>```

my admin routes

```<code># app/admin/routes.py
from flask import render_template
from app.admin import bp

@bp.route("/")
def adminRoute():
    return render_template("admin/index.html")
</code>```

my  main app file

```<code># app/__init__.py

# Regular Imports
from flask import Flask

# Config Import
from config import Config

# Extensions' Imports
from app.extensions import db
from app.extensions import login_manager

# Blueprints' Imports
from app.main import bp as main_bp
from app.admin import bp as admin_bp

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Initialize Flask extensions here
    db.init_app(app)
    login_manager.init_app(app)

    # Register blueprints here
    app.register_blueprint(main_bp)
    app.register_blueprint(admin_bp, url_prefix="/admin")

    # Returning created App Instance
    return app
</code>```

Body:
I'm new to Flask and while following some youtube tutorials for Flask-Admin, I came across the fact that we need to create the admin panel by extending the template in "admin/index.html"

The instructor said that the 'admin/master.html' is an implicit file and we don't need to create it but do need to extend it.

But I'm getting a error message that says that the template "admin/master.html" couldn't be found.

How do I work this problem out?

This is the error log

[2023-01-05 23:13:42,958] ERROR in app: Exception on /admin/ [GET]
Traceback (most recent call last):
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/SSD_Data/DevFile/AayushPokharel/app/admin/routes.py", line 7, in adminRoute
    return render_template("admin/index.html")
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 147, in render_template
    return _render(app, template, context)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 130, in _render
    rv = template.render(context)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
    self.environment.handle_exception()
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "/SSD_Data/DevFile/AayushPokharel/app/templates/admin/index.html", line 1, in top-level template code
    {% extends 'admin/master.html' %} {% block body %}
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 62, in get_source
    return self._get_source_fast(environment, template)
  File "/SSD_Data/DevFile/AayushPokharel/env/lib/python3.10/site-packages/flask/templating.py", line 98, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: admin/master.html
127.0.0.1 - - [05/Jan/2023 23:13:42] "GET /admin/ HTTP/1.1" 500 -

This is my admin template

{% extends 'admin/master.html' %} {% block body %}

This is Admin Page

{% endblock %}

my admin init blueprint

# app/admin/__init__.py

from flask import Blueprint
from flask_admin.contrib.sqla import ModelView
from app.extensions import admin, db
from app.models.user import User

bp = Blueprint("admin", __name__)

admin.add_view(ModelView(User, db.session))

from app.admin import routes

my admin routes

# app/admin/routes.py
from flask import render_template
from app.admin import bp

@bp.route("/")
def adminRoute():
    return render_template("admin/index.html")

my  main app file

# app/__init__.py

# Regular Imports
from flask import Flask

# Config Import
from config import Config

# Extensions' Imports
from app.extensions import db
from app.extensions import login_manager

# Blueprints' Imports
from app.main import bp as main_bp
from app.admin import bp as admin_bp

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Initialize Flask extensions here
    db.init_app(app)
    login_manager.init_app(app)

    # Register blueprints here
    app.register_blueprint(main_bp)
    app.register_blueprint(admin_bp, url_prefix="/admin")

    # Returning created App Instance
    return app


问:
How to configure Davx5 over adb?
The DAVx5 manual says the configuration of davdroid can be done using a davdroid-config.json file using either:

Android Enterprise (recommended)

network configuration: fixed URL (QR code)

network configuration: unicast DNS

network configuration: Zeroconf (DNS-SD)

So in case of the fixed URL, I assume the device goes to the url and then gets and processes that davdroid-config.json file. How could one feed the DAVx5 app this davdroid-config.json file over adb?

I have tried manually creating a valid DAVx5 configuration and searching the device for the configuration values, and I found them in the:

```<code>data/data/at.bitfire.davdroid/no_backup/androidx.work.workdb-wal
</code>```

File, in an encrypted/illegible fashion:

```<code>

�
 �
�z��
�
 �)�Uhttps://some_onion.onion/remote.php/dav/addressbooks/users/some_username/z-app-generated--contactsinteraction--recent/
https://some_onion.onion/remote.php/dav/addressbooks/users/some_username/contacts/  x�shttps://some_onion.onion/remote.php/dav/calendars/some_username/workx�s��e
������3�
        syncstats
                 omeset!collection
</code>```

However, I am not able to generate such a file myself, nor is it the condensed davdroid-config.json that DAVx5 expects.

Title: How to configure Davx5 over adb?

Body:
The DAVx5 manual says the configuration of davdroid can be done using a davdroid-config.json file using either:

Android Enterprise (recommended)

network configuration: fixed URL (QR code)

network configuration: unicast DNS

network configuration: Zeroconf (DNS-SD)

So in case of the fixed URL, I assume the device goes to the url and then gets and processes that davdroid-config.json file. How could one feed the DAVx5 app this davdroid-config.json file over adb?

I have tried manually creating a valid DAVx5 configuration and searching the device for the configuration values, and I found them in the:

data/data/at.bitfire.davdroid/no_backup/androidx.work.workdb-wal

File, in an encrypted/illegible fashion:

�
 �
�z��
�
 �)�Uhttps://some_onion.onion/remote.php/dav/addressbooks/users/some_username/z-app-generated--contactsinteraction--recent/
https://some_onion.onion/remote.php/dav/addressbooks/users/some_username/contacts/  x�shttps://some_onion.onion/remote.php/dav/calendars/some_username/workx�s��e
������3�
        syncstats
                 omeset!collection

However, I am not able to generate such a file myself, nor is it the condensed davdroid-config.json that DAVx5 expects.


问:
Rapids CUML Random Forest Regression Model doesn't return the scoring function value
I used the code below to tune the model and search for the best combination using the grid search algorithm. However, the model does not evaluate and return the score value of each combination.

I used the same thing with the SVM regressor model and it return the score during the training.

Here is the code:

```<code>from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, mean_squared_error
param_grid2 = {

    'bootstrap': [True, False],
    'max_depth': [16, 30, 50, 80, 90, 100 ],
    'max_features': ['auto', 'sqrt', 'log2'],
    'min_samples_leaf': [1, 3, 4, 5],
    'min_samples_split': [2,4, 8, 10, 12],
    'n_estimators': [100, 200, 300, 400 ,500]
    }

from cuml.ensemble import RandomForestRegressor

# Create a based model
rfr_cu = RandomForestRegressor() # remove the output_type. Check this link for more details: https://docs.rapids.ai/api/cuml/stable/api.html#output-data-type-configuration

# Instantiate the grid search model
rfr_tune_cu = GridSearchCV(estimator = rfr_cu, param_grid = param_grid2, scoring='neg_mean_squared_error',
                           cv = 3, n_jobs = -1, verbose = 3, error_score= 'raise',  return_train_score =True )

</code>```

The output message

```<code>RuntimeError                              Traceback (most recent call last)
Input In [80], in <cell line: 2>()
      1 # Fit the grid search to the data
----> 2 rfr_tune_cu.fit(cu_X_train, cu_y_train)

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:875, in BaseSearchCV.fit(self, X, y, groups, **fit_params)
    869     results = self._format_results(
    870         all_candidate_params, n_splits, all_out, all_more_results
    871     )
    873     return results
--> 875 self._run_search(evaluate_candidates)
    877 # multimetric is determined here because in the case of a callable
    878 # self.scoring the return type is only known after calling
    879 first_test_score = all_out[0]["test_scores"]

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:1375, in GridSearchCV._run_search(self, evaluate_candidates)
   1373 def _run_search(self, evaluate_candidates):
   1374     """Search all candidates in param_grid"""
-> 1375     evaluate_candidates(ParameterGrid(self.param_grid))

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:822, in BaseSearchCV.fit.<locals>.evaluate_candidates(candidate_params, cv, more_results)
    814 if self.verbose > 0:
    815     print(
    816         "Fitting {0} folds for each of {1} candidates,"
    817         " totalling {2} fits".format(
    818             n_splits, n_candidates, n_candidates * n_splits
    819         )
    820     )
--> 822 out = parallel(
    823     delayed(_fit_and_score)(
    824         clone(base_estimator),
    825         X,
    826         y,
    827         train=train,
    828         test=test,
    829         parameters=parameters,
    830         split_progress=(split_idx, n_splits),
    831         candidate_progress=(cand_idx, n_candidates),
    832         **fit_and_score_kwargs,
    833     )
    834     for (cand_idx, parameters), (split_idx, (train, test)) in product(
    835         enumerate(candidate_params), enumerate(cv.split(X, y, groups))
    836     )
    837 )
    839 if len(out) < 1:
    840     raise ValueError(
    841         "No fits were performed. "
    842         "Was the CV iterator empty? "
    843         "Were there no candidates?"
    844     )

File /usr/local/lib/python3.9/dist-packages/joblib/parallel.py:1056, in Parallel.__call__(self, iterable)
   1053     self._iterating = False
   1055 with self._backend.retrieval_context():
-> 1056     self.retrieve()
   1057 # Make sure that we get a last message telling us we are done
   1058 elapsed_time = time.time() - self._start_time

File /usr/local/lib/python3.9/dist-packages/joblib/parallel.py:935, in Parallel.retrieve(self)
    933 try:
    934     if getattr(self._backend, 'supports_timeout', False):
--> 935         self._output.extend(job.get(timeout=self.timeout))
    936     else:
    937         self._output.extend(job.get())

File /usr/local/lib/python3.9/dist-packages/joblib/_parallel_backends.py:542, in LokyBackend.wrap_future_result(future, timeout)
    539 """Wrapper for Future.result to implement the same behaviour as
    540 AsyncResults.get from multiprocessing."""
    541 try:
--> 542     return future.result(timeout=timeout)
    543 except CfTimeoutError as e:
    544     raise TimeoutError from e

File /usr/lib/python3.9/concurrent/futures/_base.py:446, in Future.result(self, timeout)
    444     raise CancelledError()
    445 elif self._state == FINISHED:
--> 446     return self.__get_result()
    447 else:
    448     raise TimeoutError()

File /usr/lib/python3.9/concurrent/futures/_base.py:391, in Future.__get_result(self)
    389 if self._exception:
    390     try:
--> 391         raise self._exception
    392     finally:
    393         # Break a reference cycle with the exception in self._exception
    394         self = None

RuntimeError: CUDA error encountered at: file=/project/cpp/src/decisiontree/batched-levelalgo/quantiles.cuh line=52: call='cub::DeviceRadixSort::SortKeys( nullptr, temp_storage_bytes, data, sorted_column.data(), n_rows, 0, 8 * sizeof(T), stream)', Reason=cudaErrorInvalidDeviceFunction:invalid device function
</code>```

Body:
I used the code below to tune the model and search for the best combination using the grid search algorithm. However, the model does not evaluate and return the score value of each combination.

I used the same thing with the SVM regressor model and it return the score during the training.

Here is the code:

from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, mean_squared_error
param_grid2 = {

    'bootstrap': [True, False],
    'max_depth': [16, 30, 50, 80, 90, 100 ],
    'max_features': ['auto', 'sqrt', 'log2'],
    'min_samples_leaf': [1, 3, 4, 5],
    'min_samples_split': [2,4, 8, 10, 12],
    'n_estimators': [100, 200, 300, 400 ,500]
    }

from cuml.ensemble import RandomForestRegressor

# Create a based model
rfr_cu = RandomForestRegressor() # remove the output_type. Check this link for more details: https://docs.rapids.ai/api/cuml/stable/api.html#output-data-type-configuration

# Instantiate the grid search model
rfr_tune_cu = GridSearchCV(estimator = rfr_cu, param_grid = param_grid2, scoring='neg_mean_squared_error',
                           cv = 3, n_jobs = -1, verbose = 3, error_score= 'raise',  return_train_score =True )

The output message

RuntimeError                              Traceback (most recent call last)
Input In [80], in <cell line: 2>()
      1 # Fit the grid search to the data
----> 2 rfr_tune_cu.fit(cu_X_train, cu_y_train)

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:875, in BaseSearchCV.fit(self, X, y, groups, **fit_params)
    869     results = self._format_results(
    870         all_candidate_params, n_splits, all_out, all_more_results
    871     )
    873     return results
--> 875 self._run_search(evaluate_candidates)
    877 # multimetric is determined here because in the case of a callable
    878 # self.scoring the return type is only known after calling
    879 first_test_score = all_out[0]["test_scores"]

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:1375, in GridSearchCV._run_search(self, evaluate_candidates)
   1373 def _run_search(self, evaluate_candidates):
   1374     """Search all candidates in param_grid"""
-> 1375     evaluate_candidates(ParameterGrid(self.param_grid))

File /usr/local/lib/python3.9/dist-packages/sklearn/model_selection/_search.py:822, in BaseSearchCV.fit.<locals>.evaluate_candidates(candidate_params, cv, more_results)
    814 if self.verbose > 0:
    815     print(
    816         "Fitting {0} folds for each of {1} candidates,"
    817         " totalling {2} fits".format(
    818             n_splits, n_candidates, n_candidates * n_splits
    819         )
    820     )
--> 822 out = parallel(
    823     delayed(_fit_and_score)(
    824         clone(base_estimator),
    825         X,
    826         y,
    827         train=train,
    828         test=test,
    829         parameters=parameters,
    830         split_progress=(split_idx, n_splits),
    831         candidate_progress=(cand_idx, n_candidates),
    832         **fit_and_score_kwargs,
    833     )
    834     for (cand_idx, parameters), (split_idx, (train, test)) in product(
    835         enumerate(candidate_params), enumerate(cv.split(X, y, groups))
    836     )
    837 )
    839 if len(out) < 1:
    840     raise ValueError(
    841         "No fits were performed. "
    842         "Was the CV iterator empty? "
    843         "Were there no candidates?"
    844     )

File /usr/local/lib/python3.9/dist-packages/joblib/parallel.py:1056, in Parallel.__call__(self, iterable)
   1053     self._iterating = False
   1055 with self._backend.retrieval_context():
-> 1056     self.retrieve()
   1057 # Make sure that we get a last message telling us we are done
   1058 elapsed_time = time.time() - self._start_time

File /usr/local/lib/python3.9/dist-packages/joblib/parallel.py:935, in Parallel.retrieve(self)
    933 try:
    934     if getattr(self._backend, 'supports_timeout', False):
--> 935         self._output.extend(job.get(timeout=self.timeout))
    936     else:
    937         self._output.extend(job.get())

File /usr/local/lib/python3.9/dist-packages/joblib/_parallel_backends.py:542, in LokyBackend.wrap_future_result(future, timeout)
    539 """Wrapper for Future.result to implement the same behaviour as
    540 AsyncResults.get from multiprocessing."""
    541 try:
--> 542     return future.result(timeout=timeout)
    543 except CfTimeoutError as e:
    544     raise TimeoutError from e

File /usr/lib/python3.9/concurrent/futures/_base.py:446, in Future.result(self, timeout)
    444     raise CancelledError()
    445 elif self._state == FINISHED:
--> 446     return self.__get_result()
    447 else:
    448     raise TimeoutError()

File /usr/lib/python3.9/concurrent/futures/_base.py:391, in Future.__get_result(self)
    389 if self._exception:
    390     try:
--> 391         raise self._exception
    392     finally:
    393         # Break a reference cycle with the exception in self._exception
    394         self = None

RuntimeError: CUDA error encountered at: file=/project/cpp/src/decisiontree/batched-levelalgo/quantiles.cuh line=52: call='cub::DeviceRadixSort::SortKeys( nullptr, temp_storage_bytes, data, sorted_column.data(), n_rows, 0, 8 * sizeof(T), stream)', Reason=cudaErrorInvalidDeviceFunction:invalid device function


问:
max() and min() functions are returning the maximum and minimum index of a list instead of values in Python
I created a list of lengths using the len() function, and it returned a list like this: {0: 101, 1: 101, 2: 101, 3: 100 ... }.
When I use the max() and min() functions to find the index of the list, it simply returns the maximum and mininum index values (0 and n).

I created my lengths list in this way:

```<code>n = len(df.index)
lengths = {}

for i in range(0,n):

    lengths[i] = len(df.at[i,'col'])
</code>```

To find the maximum and minimum I used:

```<code>maximum = max(lengths)

minimum = min(lengths)
</code>```

which produces an incorrect result.

When I append the list lengths as a column to my dataframe, and use

```<code>minimum = min(df.loc[:,'lengths'])
</code>```

the result is correct.

What is wrong about my list method?

Body:
I created a list of lengths using the len() function, and it returned a list like this: {0: 101, 1: 101, 2: 101, 3: 100 ... }.
When I use the max() and min() functions to find the index of the list, it simply returns the maximum and mininum index values (0 and n).

I created my lengths list in this way:

n = len(df.index)
lengths = {}

for i in range(0,n):

    lengths[i] = len(df.at[i,'col'])

To find the maximum and minimum I used:

maximum = max(lengths)

minimum = min(lengths)

which produces an incorrect result.

When I append the list lengths as a column to my dataframe, and use

minimum = min(df.loc[:,'lengths'])

the result is correct.

What is wrong about my list method?


问:
How could I merge two 30 fps videos into single 60 fps video, using alternating frames from both videos?
I have two 30fps videos, and I would like to create an output video, in 60fps, where every other frame in the video is alternated between the videos. For example, if I have video A and video B, the frames of the resulting video would be:

```<code>A1 B1 A2 B2 A3 B3 ...etc
</code>```

I could recreate this effect by exporting all of the frames from both videos, renaming them, and then compiling them back into a video, but that takes a lot of storage and is very slow. I've also seen questions about doing the opposite thing, turning 60fps into 30fps video, using the mod function to choose every other frame, but haven't seen anything about the opposite.

Body:
I have two 30fps videos, and I would like to create an output video, in 60fps, where every other frame in the video is alternated between the videos. For example, if I have video A and video B, the frames of the resulting video would be:

A1 B1 A2 B2 A3 B3 ...etc

I could recreate this effect by exporting all of the frames from both videos, renaming them, and then compiling them back into a video, but that takes a lot of storage and is very slow. I've also seen questions about doing the opposite thing, turning 60fps into 30fps video, using the mod function to choose every other frame, but haven't seen anything about the opposite.


问:
Hello, I would like to filter my searched record in list view in vb.net. I am still beginner in vb.net
When I search for the record in the list view, it highlights the searched record but does not filter only the required record. I want only the search records to be displayed in the list. please help me. my list view name is lvRoom, the textbox name is txtsearch and the button name is btnfind

This is my code.

```<code>Private Sub btnfind_Click(sender As Object, e As EventArgs) Handles btnfind.Click

        Dim searchrecord As String = txtsearch.Text
        lvRoom.SelectedIndices.Clear()

        For Each lvr As ListViewItem In lvRoom.Items

            For Each lvrsub As ListViewItem.ListViewSubItem In lvr.SubItems

                If lvrsub.Text = searchrecord Then

                    lvRoom.SelectedIndices.Add(lvr.Index)

                    Exit For
                End If
            Next
        Next
        lvRoom.Focus()
End Sub
</code>```

Body:
When I search for the record in the list view, it highlights the searched record but does not filter only the required record. I want only the search records to be displayed in the list. please help me. my list view name is lvRoom, the textbox name is txtsearch and the button name is btnfind

This is my code.

Private Sub btnfind_Click(sender As Object, e As EventArgs) Handles btnfind.Click

        Dim searchrecord As String = txtsearch.Text
        lvRoom.SelectedIndices.Clear()

        For Each lvr As ListViewItem In lvRoom.Items

            For Each lvrsub As ListViewItem.ListViewSubItem In lvr.SubItems

                If lvrsub.Text = searchrecord Then

                    lvRoom.SelectedIndices.Add(lvr.Index)

                    Exit For
                End If
            Next
        Next
        lvRoom.Focus()
End Sub


问:
ImportError about Numpy when using Manim
I want to try Manim.
So I installed (using pip) and created a project with the Quickstart tutorial.

RuntimeError, ImportError

But when running it, a bunch of errors show up:

```<code>RuntimeError: module compiled against API version 0xf but this version of NumPy is 0xe
Traceback (most recent call last):
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\Scripts\manim.exe\__main__.py", line 4, in <module>
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\__init__.py", line 24, in <module>
    from .animation.animation import *
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\animation\animation.py", line 6, in <module>
    from manim.mobject.opengl.opengl_mobject import OpenGLMobject
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\mobject\opengl\opengl_mobject.py", line 17, in <module>
    from manim.utils.bezier import integer_interpolate, interpolate
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\utils\bezier.py", line 28, in <module>
    from scipy import linalg
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\__init__.py", line 217, in __getattr__
    return _importlib.import_module(f'scipy.{name}')
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\__init__.py", line 197, in <module>
    from ._misc import *
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\_misc.py", line 3, in <module>
    from .blas import get_blas_funcs
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\blas.py", line 213, in <module>
    from scipy.linalg import _fblas
ImportError: numpy.core.multiarray failed to import
</code>```

I've already tried reinstalling/upgrading the newest version.

How do I solve this and get it running?

Body:
I want to try Manim.
So I installed (using pip) and created a project with the Quickstart tutorial.

RuntimeError, ImportError

But when running it, a bunch of errors show up:

RuntimeError: module compiled against API version 0xf but this version of NumPy is 0xe
Traceback (most recent call last):
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\Scripts\manim.exe\__main__.py", line 4, in <module>
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\__init__.py", line 24, in <module>
    from .animation.animation import *
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\animation\animation.py", line 6, in <module>
    from manim.mobject.opengl.opengl_mobject import OpenGLMobject
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\mobject\opengl\opengl_mobject.py", line 17, in <module>
    from manim.utils.bezier import integer_interpolate, interpolate
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\manim\utils\bezier.py", line 28, in <module>
    from scipy import linalg
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\__init__.py", line 217, in __getattr__
    return _importlib.import_module(f'scipy.{name}')
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\__init__.py", line 197, in <module>
    from ._misc import *
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\_misc.py", line 3, in <module>
    from .blas import get_blas_funcs
  File "C:\Users\mitja\AppData\Local\Programs\Python\Python310\lib\site-packages\scipy\linalg\blas.py", line 213, in <module>
    from scipy.linalg import _fblas
ImportError: numpy.core.multiarray failed to import

I've already tried reinstalling/upgrading the newest version.

How do I solve this and get it running?


问:
Problem using getElementByClassName in JavaScript
I have recently started learning javascript and I am trying to do an exercise in which I have to hide a span element with a class inside a paragraph.

But I'm having trouble understanding how I can change the properties and if I'm using the correct method to get the element by its class.

Im getting the next error in console:
Uncaught TypeError: Cannot set properties of undefined (setting 'visibility')
at muestra (Ej3.js:5:24)
at HTMLAnchorElement.onclick (VM28 Ej3.html:17:67)

This my code:

```<code>function muestra(){
    var x = document.getElementsByClassName("adicional oculto");
    console.log(x);
    x.style.visibility = "hidden";
}
</code>```

Body:
I have recently started learning javascript and I am trying to do an exercise in which I have to hide a span element with a class inside a paragraph.

But I'm having trouble understanding how I can change the properties and if I'm using the correct method to get the element by its class.

Im getting the next error in console:
Uncaught TypeError: Cannot set properties of undefined (setting 'visibility')
at muestra (Ej3.js:5:24)
at HTMLAnchorElement.onclick (VM28 Ej3.html:17:67)

This my code:

function muestra(){
    var x = document.getElementsByClassName("adicional oculto");
    console.log(x);
    x.style.visibility = "hidden";
}


问:
Is hibernate executing additional update while persisting using @Convert annotation?
When I'm trying to save a simple entity in hibernate with field marked with @Convert annotation insert is always followed by update with the same parameters as in insert.

Entity to save

@Entity
public class Building {

    @Id
    @GeneratedValue
    private Long id;

    @Convert(converter = AddressConverter.class)
    private Address address;
    ...
```
<p>Object that is converted to String</p>
<pre class="lang-java prettyprint-override"><code>public class Address {

    private String street;

    private String city;
    ...
</code>```

Converter

@Converter
class AddressConverter implements AttributeConverter<Address, String> {

    @Override
    public String convertToDatabaseColumn(Address attribute) {
        return attribute.getStreet() + " " + attribute.getCity();
    }

    @Override
    public Address convertToEntityAttribute(String dbData) {
        String[] data = dbData.split(" ");
        Address address = new Address();
        address.setStreet(data[0]);
        address.setCity(data[1]);
        return address;
    }
}

```
<p>It should work like that, and if it should, why? I don't see at first glance any reason to make this additional query.</p>
<p>Logs looks like this:</p>
<pre class="lang-java prettyprint-override"><code>18:52:14.959 [main] DEBUG org.hibernate.SQL - insert into building (address, id) values (?, ?)
18:52:14.960 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [1] as [VARCHAR] - [test-street test-city]
18:52:14.961 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [2] as [BIGINT] - [1]
18:52:14.962 [main] DEBUG org.hibernate.SQL - update building set address=? where id=?
18:52:14.964 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [1] as [VARCHAR] - [test-street test-city]
18:52:14.964 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [2] as [BIGINT] - [1]
</code>```

I've made proof, so you can check it here: https://gitlab.com/Piterowsky/demo-insert-update-convert-annotation/-/tree/master/src/main/java/com/example/demo

Body:
When I'm trying to save a simple entity in hibernate with field marked with @Convert annotation insert is always followed by update with the same parameters as in insert.

Entity to save

@Entity
public class Building {

    @Id
    @GeneratedValue
    private Long id;

    @Convert(converter = AddressConverter.class)
    private Address address;
    ...

Object that is converted to String

public class Address {

    private String street;

    private String city;
    ...

Converter

@Converter
class AddressConverter implements AttributeConverter<Address, String> {

    @Override
    public String convertToDatabaseColumn(Address attribute) {
        return attribute.getStreet() + " " + attribute.getCity();
    }

    @Override
    public Address convertToEntityAttribute(String dbData) {
        String[] data = dbData.split(" ");
        Address address = new Address();
        address.setStreet(data[0]);
        address.setCity(data[1]);
        return address;
    }
}

It should work like that, and if it should, why? I don't see at first glance any reason to make this additional query.

Logs looks like this:

18:52:14.959 [main] DEBUG org.hibernate.SQL - insert into building (address, id) values (?, ?)
18:52:14.960 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [1] as [VARCHAR] - [test-street test-city]
18:52:14.961 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [2] as [BIGINT] - [1]
18:52:14.962 [main] DEBUG org.hibernate.SQL - update building set address=? where id=?
18:52:14.964 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [1] as [VARCHAR] - [test-street test-city]
18:52:14.964 [main] TRACE org.hibernate.orm.jdbc.bind - binding parameter [2] as [BIGINT] - [1]

I've made proof, so you can check it here: https://gitlab.com/Piterowsky/demo-insert-update-convert-annotation/-/tree/master/src/main/java/com/example/demo


问:
How to upload a file from client side in chunks using Javascript?
Basically my application has three components:- frontend (website using html and js), backend and a aws S3 bucket.
What i am planning to achieve is that the client sends a file upload in chunks using javascript
in binary form, i will receive them in backend and upload those chunks to aws S3 using multipart  upload, the reason i want to do this is because i shouldn't store full client upload in the backend and then transfer it to S3 ( because that would not scale well? )

I have already figured out how to send client upload in chunks by reading the file object in Int8Array objects and sending them one by one to the backend where they will be uploaded to S3 using multipart

My question is whether this is the right approach or is there any better way to achieve this.

below is the toy code that is somewhat working for what i am planning to do.

```<code><script>
var buffer;

var int8Array;
var byteArr1;
var byteArr2;

var transferFlag;

document.getElementById('submitButton').addEventListener("click", function(){

    int8Array = new Int8Array(buffer);

    let totalBufferLen = int8Array.length;
    console.log("total file length is -")
    console.log(totalBufferLen)

    let partOneLen = totalBufferLen/2;
    let partTwoLen;

    //just diving total length in two
    if(Number.isInteger(partOneLen)){
            partTwoLen = totalBufferLen - partOneLen;
    }else{
            partOneLen = partOneLen + 0.5;
            partTwoLen = totalBufferLen - partOneLen;
    }

     byteArr1 = int8Array.slice(0, partOneLen);
     byteArr2 = int8Array.slice(partOneLen, totalBufferLen);

    //send first part

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/testingByteData", true);
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Content-Type", "octet-stream");

    xhr.onload = function(){
        if(xhr.responseText === "dataReceived"){

            console.log("part 1 successfully sent, sending part 2");
             var xhr2 = new XMLHttpRequest();

             xhr2.open("POST", "/testingByteData", true);
             xhr2.setRequestHeader("Accept", "application/json");
             xhr2.setRequestHeader("Content-Type", "octet-stream");

             xhr2.onload = function() {
                if(xhr2.responseText === "dataReceived"){
                    console.log("part 2 successfully sent")
                }
             }

             xhr2.send(byteArr2);
        }
    }
    xhr.send(byteArr1);
    console.log("byte1arr len ---")
    console.log(byteArr1.length)

})

document.querySelector('input').addEventListener('change', async (event) => {
  buffer = await event.target.files[0].arrayBuffer()

}, false)
</code>```

Here is the spring boot controller that is receiving the data

```<code>@PostMapping("/testingByteData")
    public synchronized String  bytePrint(InputStream is) throws IOException, InterruptedException {

    File file = new File("file");
    OutputStream os = new FileOutputStream(file, true);

         //appending bytes to the file
        System.out.println(is.transferTo(os) + " bytes appended to the file");

    is.close();
    os.close();

     fileAppendFlag = false;
     return "dataReceived";
    }
    }
 }
</code>```


问:
In Java, is there any way to convert TensorProto to TensorContent?
When I use tensorflow's grpc client to request tf serving in Java, many TensorProto are built. In a batch request, a large number of TensorProto are duplicated. I found that the comments of setTensorContent say "avoiding serialization of many repeated small items", and I want to use TensorContent data to build repeated TensorProto.
Is there any way to generate TensorContent from TensorProto or an array of raw data?

I searched for information about the AsProtoTensorContent function and found that only tensorflow's C++ implementation can call it. Hope to have a solution in Java.

I only found a way to convert float to byte[] and then use ByteString.copyFrom to get TensorContent. Did not find any relevant documentation for this code.

```<code>public static byte[] float2byte(float f) {

    int fbit = Float.floatToIntBits(f);

    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
        b[i] = (byte) (fbit >> (24 - i * 8));
    }

    int len = b.length;
    byte[] dest = new byte[len];
    System.arraycopy(b, 0, dest, 0, len);
    byte temp;
    for (int i = 0; i < len / 2; ++i) {
        temp = dest[i];
        dest[i] = dest[len - i - 1];
        dest[len - i - 1] = temp;
    }
    return dest;
}
</code>```

Body:
When I use tensorflow's grpc client to request tf serving in Java, many TensorProto are built. In a batch request, a large number of TensorProto are duplicated. I found that the comments of setTensorContent say "avoiding serialization of many repeated small items", and I want to use TensorContent data to build repeated TensorProto.
Is there any way to generate TensorContent from TensorProto or an array of raw data?

I searched for information about the AsProtoTensorContent function and found that only tensorflow's C++ implementation can call it. Hope to have a solution in Java.

I only found a way to convert float to byte[] and then use ByteString.copyFrom to get TensorContent. Did not find any relevant documentation for this code.

public static byte[] float2byte(float f) {

    int fbit = Float.floatToIntBits(f);

    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++) {
        b[i] = (byte) (fbit >> (24 - i * 8));
    }

    int len = b.length;
    byte[] dest = new byte[len];
    System.arraycopy(b, 0, dest, 0, len);
    byte temp;
    for (int i = 0; i < len / 2; ++i) {
        temp = dest[i];
        dest[i] = dest[len - i - 1];
        dest[len - i - 1] = temp;
    }
    return dest;
}


问:
How to add "swing" style to the music21 output for MuseScore
I'm writing jazz pieces using music21, and then exporting them to MuseScore with stream.show().  Before playing the song, I use the Text palette in MuseScore to add "Swing" over the first note, and then the playback has a swing feel to it.  I was wondering if I could add this directly using music21.

Saving the modified musicXML file, I noticed that the first measure contains a  block with the information needed for swing style, but I haven't found a mechanism that allows me to add this using music21.  Here's what the musicXML file looks like with the needed elements for swing style:

```<code><Measure>
    <voice>
      <Clef>
        <concertClefType>G</concertClefType>
        <transposingClefType>G</transposingClefType>
        </Clef>
      <TimeSig>
        <sigN>4</sigN>
        <sigD>4</sigD>
        </TimeSig>
      <Tempo>
        <tempo>2.66667</tempo>
        <followText>1</followText>
        <text><sym>metNoteHalfUp</sym> = 80</text>
        </Tempo>
      <SystemText>
        <swing unit="eighth" ratio="60"/>
        <style>tempo</style>
        <text>Swing</text>
        </SystemText>

</code>```

Body:
I'm writing jazz pieces using music21, and then exporting them to MuseScore with stream.show().  Before playing the song, I use the Text palette in MuseScore to add "Swing" over the first note, and then the playback has a swing feel to it.  I was wondering if I could add this directly using music21.

Saving the modified musicXML file, I noticed that the first measure contains a  block with the information needed for swing style, but I haven't found a mechanism that allows me to add this using music21.  Here's what the musicXML file looks like with the needed elements for swing style:

<Measure>
    <voice>
      <Clef>
        <concertClefType>G</concertClefType>
        <transposingClefType>G</transposingClefType>
        </Clef>
      <TimeSig>
        <sigN>4</sigN>
        <sigD>4</sigD>
        </TimeSig>
      <Tempo>
        <tempo>2.66667</tempo>
        <followText>1</followText>
        <text><sym>metNoteHalfUp</sym> = 80</text>
        </Tempo>
      <SystemText>
        <swing unit="eighth" ratio="60"/>

        <text>Swing</text>
        </SystemText>


问:
Woocommerce - Add extra content to email depending on if variations/add ons purchased
I want to add some text to the processing email sent to customers if that customer has purchased an add-on or certain product variation. I am using the Woocommerce email customiser plugin and that lets me drop a hook like woocommerce_email_order_meta on a certain email. So I added this to the processing order mail.

In fuctions.php I started by adding any text to the hook woocommerce_email_order_meta so it would appear on the mail. And this worked. I change this text to display the contents of wc_display_item_meta and this worked. I then tried to add code to check if a certain phase (Installation Service) is contained in the wc_display_item_meta and echo something if it’s there and something else if it’s not. And this didn’t work. The result was it echo’s the contents of wc_display_item_meta and always says no addon include, even when Installation Service text is showing in the output of the wc_display_item_meta on the mauk.

So I am thinking am going wrong where I try to find the text in wc_display_item_meta or am I trying to get a value from wc_display_item_meta before it’s there?

```<code>function add_message_to_email( $order, $sent_to_admin, $plain_text, $email ) {
    $output = ""; // Declare the output variable

    foreach ( $order->get_items() as $key => $item ) :
        $product = $order->get_product_from_item($item);
        $variant_name = ($item['variation_id']) ? wc_get_product($item['variation_id']) : '';
        $item_meta = wc_display_item_meta( $item );

        // Concatenate the output to the variable
        $output .= $item_meta;
    endforeach;

    // Check if "Installation Service" is present in the output variable
    if ( stripos( $output, 'Installation Service' ) !== false ) {
        // "Installation Service" was found, so display the "addon included" message
        echo "addon included";
    } else {
        // "Installation Service" was not found, so display the "no addon include" message
        echo "no addon include";
    }
}
add_action( 'woocommerce_email_order_meta', 'add_message_to_email', 10, 4 );```
```

Body:
I want to add some text to the processing email sent to customers if that customer has purchased an add-on or certain product variation. I am using the Woocommerce email customiser plugin and that lets me drop a hook like woocommerce_email_order_meta on a certain email. So I added this to the processing order mail.

In fuctions.php I started by adding any text to the hook woocommerce_email_order_meta so it would appear on the mail. And this worked. I change this text to display the contents of wc_display_item_meta and this worked. I then tried to add code to check if a certain phase (Installation Service) is contained in the wc_display_item_meta and echo something if it’s there and something else if it’s not. And this didn’t work. The result was it echo’s the contents of wc_display_item_meta and always says no addon include, even when Installation Service text is showing in the output of the wc_display_item_meta on the mauk.

So I am thinking am going wrong where I try to find the text in wc_display_item_meta or am I trying to get a value from wc_display_item_meta before it’s there?

function add_message_to_email( $order, $sent_to_admin, $plain_text, $email ) {
    $output = ""; // Declare the output variable

    foreach ( $order->get_items() as $key => $item ) :
        $product = $order->get_product_from_item($item);
        $variant_name = ($item['variation_id']) ? wc_get_product($item['variation_id']) : '';
        $item_meta = wc_display_item_meta( $item );

        // Concatenate the output to the variable
        $output .= $item_meta;
    endforeach;

    // Check if "Installation Service" is present in the output variable
    if ( stripos( $output, 'Installation Service' ) !== false ) {
        // "Installation Service" was found, so display the "addon included" message
        echo "addon included";
    } else {
        // "Installation Service" was not found, so display the "no addon include" message
        echo "no addon include";
    }
}
add_action( 'woocommerce_email_order_meta', 'add_message_to_email', 10, 4 );```