问:
Add a new API endpoint with Flask AppBuilder in Superset (through Flask Blueprints)
I am using Superset 2.0.0 and I saw that it was possible to extend the API (i.e. add new endpoints using Flask Blueprints).

I can add a simple endpoint with the code:

# superset_config.py
from greeting import greeting

BLUEPRINTS = [greeting]
```
<pre class="lang-py prettyprint-override"><code># greeting.py
from flask import Blueprint

greeting = Blueprint("greeting", __name__)

@greeting.route("/hello")
def health_status():
    return "Hello"
</code>```

But I would like to use endpoint protections that Superset uses so that my endpoint is only accessible after being authenticated (which means providing the JWT token generated using the /api/v1/security/login endpoint).

The Superset API is based on Flask Appbuilder so I tried this:

# superset_config.py
from greeting import GreetingApi

BLUEPRINTS = [GreetingApi]
```
<pre class="lang-py prettyprint-override"><code># greeting.py
from flask_appbuilder.api import BaseApi, expose, protect

class GreetingApi(BaseApi):
    csrf_exempt = False

    @protect
    @expose("/hello")
    def greeting(self):
        return self.response(200, message="Hello")
</code>```

But it does not register the blueprint and I don't know if this piece of code would be enough to ensure that this endpoint is not accessible to everyone.

Do you have any idea how to do this? I am a beginner on Flask...

Thanks a lot!

Nicolas

Body:
I am using Superset 2.0.0 and I saw that it was possible to extend the API (i.e. add new endpoints using Flask Blueprints).

I can add a simple endpoint with the code:

# superset_config.py
from greeting import greeting

BLUEPRINTS = [greeting]

# greeting.py
from flask import Blueprint

greeting = Blueprint("greeting", __name__)

@greeting.route("/hello")
def health_status():
    return "Hello"

But I would like to use endpoint protections that Superset uses so that my endpoint is only accessible after being authenticated (which means providing the JWT token generated using the /api/v1/security/login endpoint).

The Superset API is based on Flask Appbuilder so I tried this:

# superset_config.py
from greeting import GreetingApi

BLUEPRINTS = [GreetingApi]

# greeting.py
from flask_appbuilder.api import BaseApi, expose, protect

class GreetingApi(BaseApi):
    csrf_exempt = False

    @protect
    @expose("/hello")
    def greeting(self):
        return self.response(200, message="Hello")

But it does not register the blueprint and I don't know if this piece of code would be enough to ensure that this endpoint is not accessible to everyone.

Do you have any idea how to do this? I am a beginner on Flask...

Thanks a lot!

Nicolas


来源: stackexchange

问:
Why dp is looking different on 2 devices with same screen density?
As far as I know, dp is used to calculate how many pixels are needed to occupy the same space in different screen densities. The following image describes this:

According to the above information, for example if I have a ConstraintLayout and I am using Top and Bottom margin in an element of the ConstraintLayout (Imagine that Top and Bottom margin is 10dp). If now I test the app in two devices with the same screen density, why the margin is looking different in both devices although the screen density is the same? Shouldn't they have exactly the same px margin according to the definition of dp? Why the margin is looking different in 2 devices that have the same screen density?

Edit of the example:

I am using app:autoSizeTextType="uniform" in an AppCompatTextView to resize it according to its space (the AppCompatTextView has width and height = 0dp to fill completely respecting its constraints). So to resize it I am using Top and Bottom margin so that if the margin is higher the text is smaller as it will have less space to fill. As you can see in the following images, I am using 2 devices with same screen density but the text is looking different although the same margin should be applied:

1st device:

2nd device:

ContentLicense: CC BY-SA 4.0


问:
database design in nestjs microservices
I am working on an api backend following nestjs microservice architecture, basic structure is like:

each service send login request to authService, get token and user details; the authService also store user data in its own database;

UseGuards has been implemented via tcp by use a custom @MessagePattern({cmd:'check-user'}) in AuthService. So for ServiceA/B , routes is now under protection;

my question is : there are bunch of tables in ServiceA/B connect to user table in previous monolithic architecture (one-to-many, many-to-many,etc.). and now User table is  moved to authService , stored in different database. how can i design my database for ServiceA/B?

one idea I came realize that make copies of user tabel in ServiceA/B database, But I don't think it's a good solution for sure

what I have try:
1.each time when user login, get userid from authService, store it in ServiceA/B tables columns('userid') if the table is related to this user.(bad idea)

Title: database design in nestjs microservices


问:
Problem with Grafana behind Nginx Proxy called from IFrame
We have problems with a webpage that uses iFrame to display a Grafana dashboard that is located behind a Nginx reverse proxy located on the same server as the Grafana server.
The server is setup in a ec2 instance in AWS behind a ELB which offloads the TLS and redirects the call to the nginx proxy at port 80 on the same server as the Grafana server.

The error that is displayed when trying to execute the webpage is

```<code>If you're seeing this Grafana has failed to load its application files

1. This could be caused by your reverse proxy settings.

2. If you host grafana under subpath make sure your grafana.ini root_url setting includes subpath. If not using a reverse proxy make sure to set serve_from_sub_path to true.

3. If you have a local dev build make sure you build frontend using: yarn start, yarn start:hot, or yarn build

4. Sometimes restarting grafana-server can help

5. Check if you are using a non-supported browser. For more information, refer to the list of supported browsers.
</code>```

The webpage html

```<code><html>
<body>

<iframe width="2048" height="1200" ></iframe>
  <script>
    async function getSrc() {
      const res = await fetch("https://SERVERNAME/d/LYXrrYwZy/msk-prd-cluster-topics?orgId=5", {
        method: 'GET',
        headers: {
            "X-API-KEY":"OBFUSCATED",
            "Authorization":"Bearer OBFUSCATED"
        }
      });
      const blob = await res.blob();
      const urlObject = URL.createObjectURL(blob);
      document.querySelector('iframe').setAttribute("src", urlObject)
    }
    getSrc();
</script>

</body>
</html>
</code>```

The nginx server block is as follow

```<code>server {
       listen 80 default_server;
       listen [::]:80 default_server;

       root /var/www/html;
       index index.html
       server_name SERVERNAME;
       underscores_in_headers on;

       add_header 'Access-Control-Allow-Origin' '*' always;

       location / {
                if ($request_method = 'OPTIONS') {
                   add_header 'Access-Control-Allow-Origin' '*' always;
                   add_header 'Access-Control-Allow-Credentials' 'true';
                   add_header 'Access-Control-Allow-Headers' '*' always;
                   add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS' always;
                   return 200;
                }

        proxy_pass_header Authorization;
        proxy_pass_request_headers on;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:3000;
        proxy_pass_request_headers on;
        }

}
</code>```

The Bitnami Grafana config

```<code>app_mode = production
instance_name=127.0.0.1

[security]
admin_user=admin
admin_password=R8no3X1JMnVJ
secret_key=T0pS3cr3tK3y

[server]
protocol=http
http_addr=0.0.0.0
http_port=3000
domain=127.0.0.1
root_url=https://INTERNAL_SERVER_NAME
serve_from_sub_path=false
router_logging=true

[paths]
data=/opt/bitnami/grafana/data
logs=/var/log/grafana
plugins=/opt/bitnami/grafana/data/plugins
provisioning=/opt/bitnami/grafana/conf/provisioning

[metrics]
enabled=true

[log]
level=trace

[database]
type=sqlite3
max_open_conn=0
max_idle_conn=2
log_queries=false
path=grafana.db

[security]
allow_embedding=true
x_xss_protection=false

[auth.ldap]
enabled = true
config_file = /opt/bitnami/grafana/conf/ldap.toml
allow_sign_up = true

active_sync_enabled = true
skip_org_role_sync = false
</code>```

What could be the problem here.. If I access the SERVERNAME direct and adds the 2 required headers I am logged in directly to the dashboard in the Grafana server. But when using the exact same URL and headers from the iFrame the error from Grafana is displayed. NO errors appears in the grafana logs even if I use the DEBUG or TRACE logging.

Body:
We have problems with a webpage that uses iFrame to display a Grafana dashboard that is located behind a Nginx reverse proxy located on the same server as the Grafana server.
The server is setup in a ec2 instance in AWS behind a ELB which offloads the TLS and redirects the call to the nginx proxy at port 80 on the same server as the Grafana server.

The error that is displayed when trying to execute the webpage is

If you're seeing this Grafana has failed to load its application files

1. This could be caused by your reverse proxy settings.

2. If you host grafana under subpath make sure your grafana.ini root_url setting includes subpath. If not using a reverse proxy make sure to set serve_from_sub_path to true.

3. If you have a local dev build make sure you build frontend using: yarn start, yarn start:hot, or yarn build

4. Sometimes restarting grafana-server can help

5. Check if you are using a non-supported browser. For more information, refer to the list of supported browsers.

The webpage html

The nginx server block is as follow

server {
       listen 80 default_server;
       listen [::]:80 default_server;

       root /var/www/html;
       index index.html
       server_name SERVERNAME;
       underscores_in_headers on;

       add_header 'Access-Control-Allow-Origin' '*' always;

       location / {
                if ($request_method = 'OPTIONS') {
                   add_header 'Access-Control-Allow-Origin' '*' always;
                   add_header 'Access-Control-Allow-Credentials' 'true';
                   add_header 'Access-Control-Allow-Headers' '*' always;
                   add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS' always;
                   return 200;
                }

        proxy_pass_header Authorization;
        proxy_pass_request_headers on;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:3000;
        proxy_pass_request_headers on;
        }

}

The Bitnami Grafana config

app_mode = production
instance_name=127.0.0.1

[security]
admin_user=admin
admin_password=R8no3X1JMnVJ
secret_key=T0pS3cr3tK3y

[server]
protocol=http
http_addr=0.0.0.0
http_port=3000
domain=127.0.0.1
root_url=https://INTERNAL_SERVER_NAME
serve_from_sub_path=false
router_logging=true

[paths]
data=/opt/bitnami/grafana/data
logs=/var/log/grafana
plugins=/opt/bitnami/grafana/data/plugins
provisioning=/opt/bitnami/grafana/conf/provisioning

[metrics]
enabled=true

[log]
level=trace

[database]
type=sqlite3
max_open_conn=0
max_idle_conn=2
log_queries=false
path=grafana.db

[security]
allow_embedding=true
x_xss_protection=false

[auth.ldap]
enabled = true
config_file = /opt/bitnami/grafana/conf/ldap.toml
allow_sign_up = true

active_sync_enabled = true
skip_org_role_sync = false

What could be the problem here.. If I access the SERVERNAME direct and adds the 2 required headers I am logged in directly to the dashboard in the Grafana server. But when using the exact same URL and headers from the iFrame the error from Grafana is displayed. NO errors appears in the grafana logs even if I use the DEBUG or TRACE logging.


问:
ModuleNotFoundError: No module named 'pyvim'
I am Trying to use module pyVim for "import connect" but it's not working for me.

I tried using pip3 install pyVmomi, Also i tried to use pip3 install pyVim


问:
Academic edition CPLEX and docplex
I have two questions. First, even I upgrade my CPLEX from trial to academic version still in my IBM page it is shown as trial edition. Second, related to this (I guess) I am getting error while trying to solve my model with Python. Can someone give me the instructions what should I do regarding to this? Please see error below regarding python.

```<code>-- cannot find parameters matching version: , using: 22.1.1.0
Traceback (most recent call last):
  File "C:\Users\karaba02\PycharmProjects\ergoModel\random_data_generator.py", line 179, in <module>
    output = ergonomic_operator_assignment.ergonomic_math_model_solver(data_name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\ergonomic_operator_assignment.py", line 148, in ergonomic_math_model_solver
    erg_model.print()
  File "C:\Users\karaba02\PycharmProjects\ergoModel\ergonomic_operator_assignment.py", line 112, in print
    self.solution = self.ergoModel.solve(log_output=True)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\model.py", line 4835, in solve
    return self.fatal("Cannot solve model: no CPLEX runtime found.")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\model.py", line 1080, in fatal
    self._error_handler.fatal(msg, args)
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\error_handler.py", line 210, in fatal
    raise DOcplexException(resolved_message)
docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found.

</code>```

I have tried upgrade the academic version of CPLEX and make connection with python. It seems something related to enviroment but I don't know how I can solve this.

Title: Academic edition CPLEX and docplex

Body:
I have two questions. First, even I upgrade my CPLEX from trial to academic version still in my IBM page it is shown as trial edition. Second, related to this (I guess) I am getting error while trying to solve my model with Python. Can someone give me the instructions what should I do regarding to this? Please see error below regarding python.

-- cannot find parameters matching version: , using: 22.1.1.0
Traceback (most recent call last):
  File "C:\Users\karaba02\PycharmProjects\ergoModel\random_data_generator.py", line 179, in <module>
    output = ergonomic_operator_assignment.ergonomic_math_model_solver(data_name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\ergonomic_operator_assignment.py", line 148, in ergonomic_math_model_solver
    erg_model.print()
  File "C:\Users\karaba02\PycharmProjects\ergoModel\ergonomic_operator_assignment.py", line 112, in print
    self.solution = self.ergoModel.solve(log_output=True)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\model.py", line 4835, in solve
    return self.fatal("Cannot solve model: no CPLEX runtime found.")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\model.py", line 1080, in fatal
    self._error_handler.fatal(msg, args)
  File "C:\Users\karaba02\PycharmProjects\ergoModel\venv\Lib\site-packages\docplex\mp\error_handler.py", line 210, in fatal
    raise DOcplexException(resolved_message)
docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found.

I have tried upgrade the academic version of CPLEX and make connection with python. It seems something related to enviroment but I don't know how I can solve this.


问:
Cannot reference a struct variable inside another variable of the same struct, using one initialisation function in Rust
i'm pretty new to Rust and am trying to make a simple Sdl2 game-engine using it as my first proper project. I got the renderer and audio system working on their own, and am trying to integrate it with the Engine when I ran into the problem described below. At first I initialised the renderer and sound system in seperate functions, but that was only for testing and was not the solution I was happy with. Ideally, this is how the code will end up but I cannot seem to get it working. I understand the error message, but I do not know how to fix it without having to make compromises.

```<code>fn new() -> Result<Engine<'a>, String> {
    // The SDL2 context is required to get the video and audio subsystems
    let context: Sdl = sdl2::init()?;
    // Renderer takes a &Sdl as the first parameter
    let renderer = Renderer::new(&context, "Sdl2 Engine", 800, 600)?;
    // Sound also take &Sdl as the first parameter
    let sound = Sound::new(&context)?;

    Ok(Engine { context, renderer, sound })
}
</code>```

When I try to compile this code, I receive the error: cannot return value referencing local variable context
returns a value referencing data owned by the current function
I tried wrapping the context in aBox` but that made no difference. And although putting the initialisation of the video and audio system into seperate functions did work, it is not the solution I intended to use, and required me to wrap the systems in a refCell and option, which considering how often these values will be accessed, would end up being a performance issue in the future. Any help would be greatly appreciated.

Body:
i'm pretty new to Rust and am trying to make a simple Sdl2 game-engine using it as my first proper project. I got the renderer and audio system working on their own, and am trying to integrate it with the Engine when I ran into the problem described below. At first I initialised the renderer and sound system in seperate functions, but that was only for testing and was not the solution I was happy with. Ideally, this is how the code will end up but I cannot seem to get it working. I understand the error message, but I do not know how to fix it without having to make compromises.

fn new() -> Result<Engine<'a>, String> {
    // The SDL2 context is required to get the video and audio subsystems
    let context: Sdl = sdl2::init()?;
    // Renderer takes a &Sdl as the first parameter
    let renderer = Renderer::new(&context, "Sdl2 Engine", 800, 600)?;
    // Sound also take &Sdl as the first parameter
    let sound = Sound::new(&context)?;

    Ok(Engine { context, renderer, sound })
}

When I try to compile this code, I receive the error: cannot return value referencing local variable context
returns a value referencing data owned by the current function
I tried wrapping the context in aBox` but that made no difference. And although putting the initialisation of the video and audio system into seperate functions did work, it is not the solution I intended to use, and required me to wrap the systems in a refCell and option, which considering how often these values will be accessed, would end up being a performance issue in the future. Any help would be greatly appreciated.


问:
URL redirecting Issue in Razor Page (C#)
So basically I want to redirect the website.com/blog to website.com/blogs. When I did the redirecting on localhost it's working fine but when I push it to the staging level for validation it throws the error "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."

```<code> if (currentHost.Host.StartsWith("www."))
{

    context.HttpContext.Response.Redirect("https://website.com"+path);
    context.Result = RuleResult.EndResponse;
}
 var url = context.HttpContext.Request.Path.Value.ToLower();

if (url.EndsWith("/blog"))
{
    context.HttpContext.Response.Redirect("/blogs");
    context.Result = RuleResult.EndResponse;
    return;
}
</code>```

This is the condition that I'm using

Need to redirect website.com/blog page to website.com/blogs ,with above mention logic it works fine on localhost but not on staging and website is hosted on azure

Body:
So basically I want to redirect the website.com/blog to website.com/blogs. When I did the redirecting on localhost it's working fine but when I push it to the staging level for validation it throws the error "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."

 if (currentHost.Host.StartsWith("www."))
{

    context.HttpContext.Response.Redirect("https://website.com"+path);
    context.Result = RuleResult.EndResponse;
}
 var url = context.HttpContext.Request.Path.Value.ToLower();

if (url.EndsWith("/blog"))
{
    context.HttpContext.Response.Redirect("/blogs");
    context.Result = RuleResult.EndResponse;
    return;
}

This is the condition that I'm using

Need to redirect website.com/blog page to website.com/blogs ,with above mention logic it works fine on localhost but not on staging and website is hosted on azure


问:
File is not being completely updated on S3
I have the following function that upload a file to a S3:

```<code>import {
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";

const client = new S3Client({
  endpoint: "https://fra1.digitaloceanspaces.com",
  region: "fra1",
  credentials: {
    accessKeyId: Env.get("BUCKET_KEY"),
    secretAccessKey: Env.get("BUCKET_SECRET"),
  },
});

const Bucket = "customers-space";

const Key = "customers.csv";

export const saveFileInSpace = async (path: string) => {
  const Body = fs.createReadStream(path);
  await client.send(
    new PutObjectCommand({
      Bucket,
      Key,
      ACL: "private",
      Body,
    })
  );
};
</code>```

My file will be quite big (only ~50MB now, but will increase) so I used streams like the aws example.

However the call fails with the following:

```<code>MissingContentLength: UnknownError
     at throwDefaultError (/workspace/node_modules/@aws-sdk/smithy-client/dist-cjs/default-error-handler.js:8:22)
     at deserializeAws_restXmlPutObjectCommandError (/workspace/node_modules/@aws-sdk/client-s3/dist-cjs/protocols/Aws_restXml.js:5782:43)
     at runMicrotasks (<anonymous>)
     at processTicksAndRejections (node:internal/process/task_queues:96:5)
     at /workspace/node_modules/@aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:7:24
     at /workspace/node_modules/@aws-sdk/middleware-signing/dist-cjs/middleware.js:14:20
     at StandardRetryStrategy.retry (/workspace/node_modules/@aws-sdk/middleware-retry/dist-cjs/StandardRetryStrategy.js:51:46)
     at /workspace/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/flexibleChecksumsMiddleware.js:56:20
     at /workspace/node_modules/@aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:6:22
     at saveFileInSpace (/workspace/build/index.js:37579:3)
     at exportCsv (/workspace/build/index.js:39452:5)
     at processResults (/workspace/build/index.js:39709:8)
     at bulkFetchCustomers (/workspace/build/index.js:39759:7)
     at Worker.Queue.lockDuration [as processFn] (/workspace/build/index.js:39738:7)
     at Worker.processJob (/workspace/node_modules/bullmq/src/classes/worker.ts:644:22)
     at Worker.retryIfFailed (/workspace/node_modules/bullmq/src/classes/worker.ts:774:16)
     at Worker.run (/workspace/node_modules/bullmq/src/classes/worker.ts:370:34) {
   '$fault': 'client',
   '$metadata': {
     httpStatusCode: 411,
     requestId: undefined,
     extendedRequestId: undefined,
     cfId: undefined,
     attempts: 1,
     totalRetryDelay: 0
   },
   Code: 'MissingContentLength',
   BucketName: 'customers-space',
   RequestId: '...',
   HostId: '...'
}
</code>```

From the examples I found online no one used the ContentLength parameters.

I also use a stream, that does not have idea of his size.

Version of the sdk:

"dependencies": {
  "@aws-sdk/client-s3": "3.218.0",
  ...
}
```

What am I doing wrong?

Body:
I have the following function that upload a file to a S3:

import {
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";

const client = new S3Client({
  endpoint: "https://fra1.digitaloceanspaces.com",
  region: "fra1",
  credentials: {
    accessKeyId: Env.get("BUCKET_KEY"),
    secretAccessKey: Env.get("BUCKET_SECRET"),
  },
});

const Bucket = "customers-space";

const Key = "customers.csv";

export const saveFileInSpace = async (path: string) => {
  const Body = fs.createReadStream(path);
  await client.send(
    new PutObjectCommand({
      Bucket,
      Key,
      ACL: "private",
      Body,
    })
  );
};

My file will be quite big (only ~50MB now, but will increase) so I used streams like the aws example.

However the call fails with the following:

MissingContentLength: UnknownError
     at throwDefaultError (/workspace/node_modules/@aws-sdk/smithy-client/dist-cjs/default-error-handler.js:8:22)
     at deserializeAws_restXmlPutObjectCommandError (/workspace/node_modules/@aws-sdk/client-s3/dist-cjs/protocols/Aws_restXml.js:5782:43)
     at runMicrotasks (<anonymous>)
     at processTicksAndRejections (node:internal/process/task_queues:96:5)
     at /workspace/node_modules/@aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:7:24
     at /workspace/node_modules/@aws-sdk/middleware-signing/dist-cjs/middleware.js:14:20
     at StandardRetryStrategy.retry (/workspace/node_modules/@aws-sdk/middleware-retry/dist-cjs/StandardRetryStrategy.js:51:46)
     at /workspace/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/flexibleChecksumsMiddleware.js:56:20
     at /workspace/node_modules/@aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:6:22
     at saveFileInSpace (/workspace/build/index.js:37579:3)
     at exportCsv (/workspace/build/index.js:39452:5)
     at processResults (/workspace/build/index.js:39709:8)
     at bulkFetchCustomers (/workspace/build/index.js:39759:7)
     at Worker.Queue.lockDuration [as processFn] (/workspace/build/index.js:39738:7)
     at Worker.processJob (/workspace/node_modules/bullmq/src/classes/worker.ts:644:22)
     at Worker.retryIfFailed (/workspace/node_modules/bullmq/src/classes/worker.ts:774:16)
     at Worker.run (/workspace/node_modules/bullmq/src/classes/worker.ts:370:34) {
   '$fault': 'client',
   '$metadata': {
     httpStatusCode: 411,
     requestId: undefined,
     extendedRequestId: undefined,
     cfId: undefined,
     attempts: 1,
     totalRetryDelay: 0
   },
   Code: 'MissingContentLength',
   BucketName: 'customers-space',
   RequestId: '...',
   HostId: '...'
}

From the examples I found online no one used the ContentLength parameters.

I also use a stream, that does not have idea of his size.

Version of the sdk:

"dependencies": {
  "@aws-sdk/client-s3": "3.218.0",
  ...
}

What am I doing wrong?


问:
Pandas-On-Spark with Spark UDF: sparkcontext should only be created and accessed on the driver udf
I do have a function parse_report which produces a Pandas-on-Spark dataframe. I would like to use it with a UDF, such as:

```<code>#input_schema is a StructType of StructField list
data_schema = ArrayType(StructType.fromJson(input_schema), False)
S_SCHEMA = StructType([
                      StructField('validation_result', BooleanType()),
                      StructField('parsed_content', data_schema),
                      StructField('year_month', IntegerType()),]
                     )

parse_udf = F.udf(lambda x, y, z: parse_report(x, y, z, **properties), S_SCHEMA)

#PARSE_REPORT --> Pyspark.Pandas
df = df.withColumn('p', parse_paramhis_report_udf(F.col('testx'), F.col('testy'), F.col('testz')))

</code>```

As a result, I am having this error: (I also tried to set the spark session/context, throwed the same error). I wanted to use Pandas UDF, but saw that the nested StructType isn't supported.

```<code>SparkContext should only be created and accessed on the driver udf

</code>```

Body:
I do have a function parse_report which produces a Pandas-on-Spark dataframe. I would like to use it with a UDF, such as:

#input_schema is a StructType of StructField list
data_schema = ArrayType(StructType.fromJson(input_schema), False)
S_SCHEMA = StructType([
                      StructField('validation_result', BooleanType()),
                      StructField('parsed_content', data_schema),
                      StructField('year_month', IntegerType()),]
                     )

parse_udf = F.udf(lambda x, y, z: parse_report(x, y, z, **properties), S_SCHEMA)

#PARSE_REPORT --> Pyspark.Pandas
df = df.withColumn('p', parse_paramhis_report_udf(F.col('testx'), F.col('testy'), F.col('testz')))

As a result, I am having this error: (I also tried to set the spark session/context, throwed the same error). I wanted to use Pandas UDF, but saw that the nested StructType isn't supported.

SparkContext should only be created and accessed on the driver udf


问:
Anylogic NullPointer Jar file has no attachment
My road traffic model is throwing null pointers with a very cryptic stacktrace:

```<code>Exception during discrete event execution:
NullPointerException
java.lang.NullPointerException
    at com.anylogic.libraries.road.Car_xjal.g(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.al(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.a(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.on_SegmentEndEvent_xjal(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal$SegmentEndEvent.execute(Unknown Source)
    at com.anylogic.engine.Engine.n(Unknown Source)
    at com.anylogic.engine.Engine.cl(Unknown Source)
    at com.anylogic.engine.Engine$n.run(Unknown Source)
</code>```

The null pointer also doesn't happen immediately, I am able to see the model run for varying lengths of time(60-800 model seconds).

When a breakpoint is created, it says the following:

```<code>The JAR file C:\Program Files\AnyLogic 8.8 Professional\plugins\com.anylogic.road_traffic_library_8.8.1.202210270952\lib\RoadTrafficLibrary.jar
 has no source attachment. You can attach a source by clicking Attach Source below
</code>```

It also occasionally throws the same error, but citing a different path("C:\Program Files\AnyLogic 8.8 Professional\jre\lib\jrt-fs.jar") as having no source attachment instead.

Any help is appreciated.

Body:
My road traffic model is throwing null pointers with a very cryptic stacktrace:

Exception during discrete event execution:
NullPointerException
java.lang.NullPointerException
    at com.anylogic.libraries.road.Car_xjal.g(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.al(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.a(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal.on_SegmentEndEvent_xjal(Unknown Source)
    at com.anylogic.libraries.road.Car_xjal$SegmentEndEvent.execute(Unknown Source)
    at com.anylogic.engine.Engine.n(Unknown Source)
    at com.anylogic.engine.Engine.cl(Unknown Source)
    at com.anylogic.engine.Engine$n.run(Unknown Source)

The null pointer also doesn't happen immediately, I am able to see the model run for varying lengths of time(60-800 model seconds).

When a breakpoint is created, it says the following:

The JAR file C:\Program Files\AnyLogic 8.8 Professional\plugins\com.anylogic.road_traffic_library_8.8.1.202210270952\lib\RoadTrafficLibrary.jar
 has no source attachment. You can attach a source by clicking Attach Source below

It also occasionally throws the same error, but citing a different path("C:\Program Files\AnyLogic 8.8 Professional\jre\lib\jrt-fs.jar") as having no source attachment instead.

Any help is appreciated.


问:
pgsql function with postgis function to return all points from polygon within radius and point
i have a table with those columns job_name, layer_name, polygon which is public.geometry and has many points in it. i want to create a function that gets 2 arguments: point and radius and will return for each job+layer all the points that all the polygon's points exists in the distance from the given point ordered by the distance . do it using postgresql with postgis functions. polygon has many points in it and for each layer+job i want all the points from all the polygons so it need to iterate through all the polygon from the same layer and job . return this as json like this

```<code>{
   "job":"<JOB NAME>",
   "layer":"<LAYER NAME>",
   "defects":[
      {
         "items":[
            {
               polygon_point_1,
               "distance":<DISTANCE1>
            },
            {
               polygon_point_2,
               "distance":<DISTANCE2>
            },
            "…"
         ]
      },
      "..."

</code>```

my code so far is like this:

```<code>SELECT
    JSON_BUILD_OBJECT(
        'job', job_name,
        'layer', layer_name,
        'defects', JSON_AGG(
            JSON_BUILD_OBJECT(
                'items', JSON_BUILD_OBJECT(
                    'polygon_point', polygon_point,
                    'distance', ST_Distance(polygon_point, ST_GeomFromText(polygon_point, 4326))
                )
            )
        )
    ) AS result
FROM (
    SELECT
        job_name,
        layer_name,
        (ST_DumpPoints(polygon)).geom as polygon_point
    FROM cam_data_step_items
    WHERE ST_DWithin(polygon, ST_GeomFromText(polygon_point, 4326), radius)
) t
GROUP BY job_name, layer_name

</code>```

error im getting when running the following:

```<code>SELECT get_polygons_by_distance('POINT(1 1)', 1);

</code>```
```<code>
SQL Error [XX000]: ERROR: parse error - invalid geometry
  Hint: "01" <-- parse error at position 2 within geometry
  Where: parallel worker
SQL function "get_polygons_by_distance" statement 1
</code>```

can someone help please?

Body:
i have a table with those columns job_name, layer_name, polygon which is public.geometry and has many points in it. i want to create a function that gets 2 arguments: point and radius and will return for each job+layer all the points that all the polygon's points exists in the distance from the given point ordered by the distance . do it using postgresql with postgis functions. polygon has many points in it and for each layer+job i want all the points from all the polygons so it need to iterate through all the polygon from the same layer and job . return this as json like this

{
   "job":"<JOB NAME>",
   "layer":"<LAYER NAME>",
   "defects":[
      {
         "items":[
            {
               polygon_point_1,
               "distance":<DISTANCE1>
            },
            {
               polygon_point_2,
               "distance":<DISTANCE2>
            },
            "…"
         ]
      },
      "..."

my code so far is like this:

SELECT
    JSON_BUILD_OBJECT(
        'job', job_name,
        'layer', layer_name,
        'defects', JSON_AGG(
            JSON_BUILD_OBJECT(
                'items', JSON_BUILD_OBJECT(
                    'polygon_point', polygon_point,
                    'distance', ST_Distance(polygon_point, ST_GeomFromText(polygon_point, 4326))
                )
            )
        )
    ) AS result
FROM (
    SELECT
        job_name,
        layer_name,
        (ST_DumpPoints(polygon)).geom as polygon_point
    FROM cam_data_step_items
    WHERE ST_DWithin(polygon, ST_GeomFromText(polygon_point, 4326), radius)
) t
GROUP BY job_name, layer_name

error im getting when running the following:

SELECT get_polygons_by_distance('POINT(1 1)', 1);

SQL Error [XX000]: ERROR: parse error - invalid geometry
  Hint: "01" <-- parse error at position 2 within geometry
  Where: parallel worker
SQL function "get_polygons_by_distance" statement 1

can someone help please?


问:
Can't align a flex box next to a table even though they are in the same div
I can't work out how to align one item to the right hand side another element, one is a table and the other is a flex box. I've made sure they are in a div together but I just cant get them to line up next to each other. I've tried using a grid but cannot get that to work correctly.

I'm trying to line up my main rail element to the right hand side of game modes and factions like a side bar.

I've made sure they are in a div together but I just cant get them to line up next to each other. I've tried using a grid but cannot get that to work correctly, the grid just moves elements off screen and I just cant work it out.

float right only moves it to the right of the end of the factions element
vertical align seemed to do nothing?

body {
  background-color: #2f2f2f;
  color: white;
}

.box {
  border: solid;
}

.header-text {
  font-family: 'Philosopher';
  font-size: 35px;
}

.subheading-text {
  font-family: 'Roboto';
  font-size: 20px;
}

.sub-heading {
  text-align: center;
  font-family: 'Roboto';
  font-size: 25px;
  font-weight: bold;
}

.page-content :is(h4) .mw-headline {
  font-family: 'Philosopher';
  font-size: 35px;
  border-bottom: solid 5px;
  border-top: solid 5px;
  padding-top: 20px;
  padding-bottom: 20px;
  width: 100%;
}

.subtext {
  text-align: center;
  font-family: 'Roboto';
  font-size: 10px;
  font-weight: bold;
}

.titles {
  font-family: 'Philosopher', sans-serif;
  font-size: 35px;
  height: 2px;
  text-align: center;
  line-height: 0.5;
  vertical-align: top right;
}

.main-rail {
  display: inline-flex;
  flex-flow: column wrap;
  justify-content: right;
  width: 20%;
}

.main-rail>div {
  text-align: center;
  border: solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div>
    <div class="game-modes">
      <table style="display:flex; justify-content:center;">
        <tr>
          <td><img src="./images/Border.png" alt=""></td>
        </tr>
        <tr>
          <td class="titles">Game Modes</td>
        </tr>
        <tr>
          <td><img src="./images/Border.png" alt=""></td>
        </tr>
      </table>
      <p></p>
      <div style="display:flex; flex-wrap:wrap; flex-direction:row; justify-content:center;">
        <div style="flex-basis:96px"><img src="./images/Casual_Full_Size.webp" width="200px" height="179px" alt="">
          <div class="sub-heading">CASUAL<br /></div>
        </div>
        <div style="flex-basis:96px"><img src="./images/Game_Mod_Ranked_200px.webp" width="200px" height="179px" alt="">
          <div class="sub-heading">RANKED<br /></div>
        </div>
        <div style="flex-basis:96px"><img src="./images/Game_Mod_Custom_200px.webp" width="200px" height="179px" alt="">
          <div class="sub-heading">CUSTOM<br /></div>
        </div>
      </div>
    </div>
    <div>
      <div class="factions">
        <table style="display:flex; justify-content:center;">
          <tr>
            <td><img src="./images/Border.png" alt=""></td>
          </tr>
          <tr>
            <td class="titles">Factions</td>
          </tr>
          <tr>
            <td><img src="./images/Border.png" alt=""></td>
          </tr>
        </table>
        <p></p>

        <div style="display:flex; flex-wrap:wrap; flex-direction:row; justify-content:center;">

          <div style="flex-basis:96px"><img src="./images/Emblem_Vestige.webp" width="209px" height="209px" alt="">
            <div class="sub-heading">VESTIGE<br /></div>
          </div>

          <div style="flex-basis:96px"><img src="./images/Emblem_Drakkorith.webp" width="209px" height="209px" alt="">
            <div class="sub-heading">DRAKKORITH<br /></div>
          </div>

          <div style="flex-basis:96px"><img src="./images/Emblem_Ascended.webp" width="209px" height="209px" alt="">
            <div class="sub-heading">ASCENDED<br /></div>
          </div>

          <div style="flex-basis:96px"><img src="./images/Emblem_Oblivion.webp" width="209px" height="209px" alt="">
            <div class="sub-heading">OBLIVION<br /></div>
          </div>

          <div style="flex-basis:96px"><img src="./images/Emblem_Neutral.webp" width="209px" height="209px" alt="">
            <div class="sub-heading">NEUTRAL
              <div class="subtext"><br />(Not a playable Faction)</div>
            </div>
          </div>
        </div>
        <div>
          <div class="main-rail">
            <div><img src="./images/Site-background-dark.webp" alt=""></div>
            <div>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Molestiae quos sapiente accusantium ipsam rem corporis aliquam quam temporibus voluptatibus id non labore maiores unde, illo earum facere, deleniti magnam reprehenderit?</div>
            <div>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Molestiae quos sapiente accusantium ipsam rem corporis aliquam quam temporibus voluptatibus id non labore maiores unde, illo earum facere, deleniti magnam reprehenderit?</div>
          </div>
        </div>

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

Body:
I can't work out how to align one item to the right hand side another element, one is a table and the other is a flex box. I've made sure they are in a div together but I just cant get them to line up next to each other. I've tried using a grid but cannot get that to work correctly.

I'm trying to line up my main rail element to the right hand side of game modes and factions like a side bar.

I've made sure they are in a div together but I just cant get them to line up next to each other. I've tried using a grid but cannot get that to work correctly, the grid just moves elements off screen and I just cant work it out.

float right only moves it to the right of the end of the factions element
vertical align seemed to do nothing?

body {
  background-color: #2f2f2f;
  color: white;
}

.box {
  border: solid;
}

.header-text {
  font-family: 'Philosopher';
  font-size: 35px;
}

.subheading-text {
  font-family: 'Roboto';
  font-size: 20px;
}

.sub-heading {
  text-align: center;
  font-family: 'Roboto';
  font-size: 25px;
  font-weight: bold;
}

.page-content :is(h4) .mw-headline {
  font-family: 'Philosopher';
  font-size: 35px;
  border-bottom: solid 5px;
  border-top: solid 5px;
  padding-top: 20px;
  padding-bottom: 20px;
  width: 100%;
}

.subtext {
  text-align: center;
  font-family: 'Roboto';
  font-size: 10px;
  font-weight: bold;
}

.titles {
  font-family: 'Philosopher', sans-serif;
  font-size: 35px;
  height: 2px;
  text-align: center;
  line-height: 0.5;
  vertical-align: top right;
}

.main-rail {
  display: inline-flex;
  flex-flow: column wrap;
  justify-content: right;
  width: 20%;
}

.main-rail>div {
  text-align: center;
  border: solid;
}

          Game Modes

CASUAL

RANKED

CUSTOM

            Factions

VESTIGE

DRAKKORITH

ASCENDED

OBLIVION

NEUTRAL

(Not a playable Faction)

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Molestiae quos sapiente accusantium ipsam rem corporis aliquam quam temporibus voluptatibus id non labore maiores unde, illo earum facere, deleniti magnam reprehenderit?

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Molestiae quos sapiente accusantium ipsam rem corporis aliquam quam temporibus voluptatibus id non labore maiores unde, illo earum facere, deleniti magnam reprehenderit?


问:
C# Socket - How to get the number of times the client connects to the server per minutes?
I am writing a socket server and I need to know how many times a user connects to my socket (server) per minute.
I tried for about 2 days to look for information on the various forums, unfortunately I could not find anything, I hope this community can help me with this, if my question is not clear, then please write about it in the comments.

```<code>if (Core.OnlineUsers.FindAll((Predicate<Client>) (x => x.IPAddress == IP)).Count > 10)
        {
          _Socket.Dispose();
        }
</code>```

I need to do this so that the socket is not dropped from the connections, because if there are too many connections, can not connect to it.

Body:
I am writing a socket server and I need to know how many times a user connects to my socket (server) per minute.
I tried for about 2 days to look for information on the various forums, unfortunately I could not find anything, I hope this community can help me with this, if my question is not clear, then please write about it in the comments.

if (Core.OnlineUsers.FindAll((Predicate<Client>) (x => x.IPAddress == IP)).Count > 10)
        {
          _Socket.Dispose();
        }

I need to do this so that the socket is not dropped from the connections, because if there are too many connections, can not connect to it.


问:
CKEditor5 Mention color is not getting applied

We provide specialized Knowledge based process and business services for Line of Business and Revenue collection functions. Our processes are established for 24×7 operational models and cater to multiple geographies, industries and organizations

The above text if color is applied is not getting applied.
Span with mention class is not taking any styles to be applied.

our requirement is to change the color of the selected text of mention feeds.

We provide specialized Knowledge based process and business services for Line of Business and Revenue collection functions. Our processes are established for 24×7 operational models and cater to multiple geographies, industries and organizations


问:
MapReduce internal error during partial document size
I'm looking to get the document size from certain collection documents, they have a validTo field that I'm using for segregation. However, when trying to run the query below I get the also mentioned error. Any hints on this? It's strange as even removing the functions and using lambdas, I still get the same error quoting a an unexpected keyword "function".

I'm using IntelliJ's Query console.

Query:

```<code>db.runCommand({
mapReduce: "myCollection",
map: function(){
    emit(this._id, this)
},
reduce: function(key, values) {
    var ret = { count: 1, totalSizeBytes: bsonsize(values[0]), maxId: values[0]._id, minId: values[0]._id };
    var max = ret.totalSizeBytes;
    var min = ret.totalSizeBytes;
    for (var i = 1; i < values.length; i++) {
        var doc = values[i];
        var size = bsonsize(doc);
        ret.totalSizeBytes += size;
        ret.count++;
        if (size > max) { max = size; ret.maxId = doc._id }
        if (size < min) { min = size; ret.minId = doc._id }
    }
    return ret;
},
query: {"validTo": {$lt: new Date(2021,10,10)}},
out: { inline: 1 }
});
</code>```

Error:

```<code>Command failed with error 139 (JSInterpreterFailure):
  'MapReduce internal error :: caused by ::
    SyntaxError: unexpected token: keyword 'function'' on server voucherservice-shard-00-01.5egqz.mongodb.net:27017.
  The full response is
    {
      "ok": 0.0,
      "errmsg": "MapReduce internal error :: caused by :: SyntaxError: unexpected token: keyword 'function'",
      "code": 139,
      "codeName": "JSInterpreterFailure",
      "$clusterTime": {
        "clusterTime": {
          "$timestamp": {"t": 1671633783, "i": 438}
        },
        "signature": {
          "hash": {
            "$binary": {
              "base64": "Wj42UxI0paKLUqhhvx1WijmrUxA=",
              "subType": "00"
            }
          },
          "keyId": 7119429745099407365
        }
      },
      "operationTime": {"$timestamp": {"t": 1671633783, "i": 438}}
    }
</code>```

Body:
I'm looking to get the document size from certain collection documents, they have a validTo field that I'm using for segregation. However, when trying to run the query below I get the also mentioned error. Any hints on this? It's strange as even removing the functions and using lambdas, I still get the same error quoting a an unexpected keyword "function".

I'm using IntelliJ's Query console.

Query:

db.runCommand({
mapReduce: "myCollection",
map: function(){
    emit(this._id, this)
},
reduce: function(key, values) {
    var ret = { count: 1, totalSizeBytes: bsonsize(values[0]), maxId: values[0]._id, minId: values[0]._id };
    var max = ret.totalSizeBytes;
    var min = ret.totalSizeBytes;
    for (var i = 1; i < values.length; i++) {
        var doc = values[i];
        var size = bsonsize(doc);
        ret.totalSizeBytes += size;
        ret.count++;
        if (size > max) { max = size; ret.maxId = doc._id }
        if (size < min) { min = size; ret.minId = doc._id }
    }
    return ret;
},
query: {"validTo": {$lt: new Date(2021,10,10)}},
out: { inline: 1 }
});

Error:

Command failed with error 139 (JSInterpreterFailure):
  'MapReduce internal error :: caused by ::
    SyntaxError: unexpected token: keyword 'function'' on server voucherservice-shard-00-01.5egqz.mongodb.net:27017.
  The full response is
    {
      "ok": 0.0,
      "errmsg": "MapReduce internal error :: caused by :: SyntaxError: unexpected token: keyword 'function'",
      "code": 139,
      "codeName": "JSInterpreterFailure",
      "$clusterTime": {
        "clusterTime": {
          "$timestamp": {"t": 1671633783, "i": 438}
        },
        "signature": {
          "hash": {
            "$binary": {
              "base64": "Wj42UxI0paKLUqhhvx1WijmrUxA=",
              "subType": "00"
            }
          },
          "keyId": 7119429745099407365
        }
      },
      "operationTime": {"$timestamp": {"t": 1671633783, "i": 438}}
    }


问:
.NET Maui: How to show an external image in webview
How can I achieve that eg. the following HTML code displays an image in a Maui webview in the Android emulation?

```<code><!DOCTYPE html><HTML>
<BODY>
<H1>.NET MAUI</H1>
<P>Welcome to Yahoo.</P>
<img src="https://s.yimg.com/rz/p/yahoo_homepage_en-US_s_f_p_bestfit_homepage.png" alt="Yahoo Image">
</BODY>
</HTML>
</code>```

Are there any settings to be made to the webview?

Body:
How can I achieve that eg. the following HTML code displays an image in a Maui webview in the Android emulation?

<!DOCTYPE html>

.NET MAUI

Welcome to Yahoo.

Are there any settings to be made to the webview?


问:
MAUI/Xamarin Create Web API on mobile platform
majority of mobile users consume some sort of web API. I want create web API on android, NOT consume, and then connect let's say 192.168.16.6:3000 to configure my program through this endpoint. Is it possible ?</p>


问:
Tokenize Review wise for sentiment analysis
In this Amazon dataset I've Product_Description , Product_Type & Sentiment column where I want to build classification model. keeping Product_Description & Product_Type as X and Sentiment as Y. but i receive few error still not able to find the solution. I want the sentence itself to be tokenize for tfidf not different words.

```<code>> amazon.head()
</code>```

Link to data example

```<code>> `Z = amazon["Product_Description"]
> Y = amazon["Sentiment"]
> tfidf = TfidfVectorizer()
> tf = pd.DataFrame(tfidf.fit_transform(Z),columns = ["Product_Description"])
> X = pd.concat((tf,amazon["Product_Type"]),axis = 1)
> X.drop(X[X["Product_Description"].isnull()].index, inplace = True)
> test_size = 0.2
> seed = 45
> X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = test_size, random_state = seed)
> X_train.shape,X_test.shape # [((5081, 2), (1271, 2))] is the output
> model = LogisticRegression(max_iter = 500)
>
> rfe = RFE(model, n_features_to_select = 2)
> fit = rfe.fit(X, Y)
>
> fit.n_features_
> fit.support_
> fit.ranking_`
</code>```
```<code>TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'csr_matrix'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Input In [57], in <cell line: 7>()
      4 model = LogisticRegression(max_iter = 500)
      6 rfe = RFE(model, n_features_to_select = 2)
----> 7 fit = rfe.fit(X, Y)
      9 fit.n_features_
     10 fit.support_
```ValueError: setting an array element with a sequence.
```

Body:
In this Amazon dataset I've Product_Description , Product_Type & Sentiment column where I want to build classification model. keeping Product_Description & Product_Type as X and Sentiment as Y. but i receive few error still not able to find the solution. I want the sentence itself to be tokenize for tfidf not different words.

> amazon.head()

Link to data example

> `Z = amazon["Product_Description"]
> Y = amazon["Sentiment"]
> tfidf = TfidfVectorizer()
> tf = pd.DataFrame(tfidf.fit_transform(Z),columns = ["Product_Description"])
> X = pd.concat((tf,amazon["Product_Type"]),axis = 1)
> X.drop(X[X["Product_Description"].isnull()].index, inplace = True)
> test_size = 0.2
> seed = 45
> X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = test_size, random_state = seed)
> X_train.shape,X_test.shape # [((5081, 2), (1271, 2))] is the output
> model = LogisticRegression(max_iter = 500)
>
> rfe = RFE(model, n_features_to_select = 2)
> fit = rfe.fit(X, Y)
>
> fit.n_features_
> fit.support_
> fit.ranking_`

TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'csr_matrix'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Input In [57], in <cell line: 7>()
      4 model = LogisticRegression(max_iter = 500)
      6 rfe = RFE(model, n_features_to_select = 2)
----> 7 fit = rfe.fit(X, Y)
      9 fit.n_features_
     10 fit.support_
```ValueError: setting an array element with a sequence.


问:
Data sorting approach
I have three rigs for motor testing, their output gets saved in three folders, one rig per folder and every rig outputs thousands of .txt files with parameters which later I'll plot, and other information like motor number, motor load and date. I would like to sort these .txt files in folders, after the motor load and motor number, like Motor 1 -> Motor load x -> all the .txt files that have test parameters of the motor 1 on load x. What would it be the fastest approach?

I have to mention that I am a beginner in programming, and I do not expect a fully coded algorithm, but rather some generic methods to adapt and apply. Thanks!

Title: Data sorting approach


问:
How to have a new instance of a view when a new item is created (swiftui)?
I was not sure how to word the question. I am making a simple notes app and am using a three column view. I want the user to create a new folder which is initially empty but they can add notes to it. My problem is that every folder goes to the same notes. If a new note is created in one folder, you see it in all the others.

Example (yes I know both folders are generically set to "New Folder", I'm working on trying to let the user set names):

I know the general problem is that when a new folder is created, they all go to the "NoteView". But I want a newly created folder to go to a different VERSION of the "NoteView" that is initially empty. Like you see in any Notes app, I want each folders' notes to be different, not them all referencing the same notes.

My code is below. Sidebar is where the folders are displayed. NoteView is where the corresponding notes are supposed to be displayed.

```<code>struct ContentView: View {
    var body: some View {
        NavigationView{
            Sidebar()
            Text("No folder selected")
            Text("No note selected")

        }
    }
}

struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {
        List(folders, selection: $selectedFoldersIds){folder in
            NavigationLink(folder.folderName, destination:NoteView()) //each folder created navigates to NoteView() which stores all created notes. But I want each folder to have empty notes until one is added.
        }
        .listStyle(SidebarListStyle())
        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: createFolder){
                    Label("Create Quick Note", systemImage: "square.and.pencil")
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func createFolder(){
         createFolder(name: "New Folder")

    }
    private func createFolder(name: String) {
        withAnimation {
            let folder = Folder(context: viewContext)
            folder.folderId = UUID()
            folder.folderName = name

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }

        }

    }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

struct NoteView: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List(notes, selection: $selectedNotesIds){ note in
            NavigationLink(note.name, destination: NoteEditor(note: note ))
        }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: createNote){
                    Label("Create Quick Note", systemImage: "square.and.pencil")
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    private func createNote(){
         createNote(name: "New note", text: "")

    }
    private func createNote(name: String, text: String) {
        withAnimation {
            let note = Note(context: viewContext)
            note.id = UUID()
            note.name = name
            note.text = text

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }

        }

    }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}

</code>```

Body:
I was not sure how to word the question. I am making a simple notes app and am using a three column view. I want the user to create a new folder which is initially empty but they can add notes to it. My problem is that every folder goes to the same notes. If a new note is created in one folder, you see it in all the others.

Example (yes I know both folders are generically set to "New Folder", I'm working on trying to let the user set names):

I know the general problem is that when a new folder is created, they all go to the "NoteView". But I want a newly created folder to go to a different VERSION of the "NoteView" that is initially empty. Like you see in any Notes app, I want each folders' notes to be different, not them all referencing the same notes.

My code is below. Sidebar is where the folders are displayed. NoteView is where the corresponding notes are supposed to be displayed.

struct ContentView: View {
    var body: some View {
        NavigationView{
            Sidebar()
            Text("No folder selected")
            Text("No note selected")

        }
    }
}

struct Sidebar: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Folder.folderName, ascending: true)])
    var folders: FetchedResults<Folder>

    @State private var selectedFoldersIds: Set<Folder.ID> = []

    private var selectedFolder: Folder?{
        guard let selectedFolderId = selectedFoldersIds.first,
              let selectedFolder = folders.filter ({$0.id == selectedFolderId}).first else{
                  return nil
              }
        return selectedFolder
    }
    var body: some View {
        List(folders, selection: $selectedFoldersIds){folder in
            NavigationLink(folder.folderName, destination:NoteView()) //each folder created navigates to NoteView() which stores all created notes. But I want each folder to have empty notes until one is added.
        }
        .listStyle(SidebarListStyle())
        .onDeleteCommand(perform: deleteSelectedFolders)
        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: createFolder){
                    Label("Create Quick Note", systemImage: "square.and.pencil")
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedFolders){
                    Label("Delete note", systemImage: "trash")
                }
            }
        }

}

    private func createFolder(){
         createFolder(name: "New Folder")

    }
    private func createFolder(name: String) {
        withAnimation {
            let folder = Folder(context: viewContext)
            folder.folderId = UUID()
            folder.folderName = name

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }

        }

    }

    private func deleteSelectedFolders(){
        withAnimation{
            let selectedFolders = folders.filter {selectedFoldersIds.contains($0.id)}
            deleteFolders(folders: selectedFolders)
        }

    }

    private func deleteFolders(folders: [Folder]){
        viewContext.perform{ folders.forEach(viewContext.delete)}
    }
}

struct NoteView: View {

    @Environment(\.managedObjectContext) private var viewContext
    @State private var isPresented: Bool = false

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Note.name, ascending: true)])
    var notes: FetchedResults<Note>

    @State private var selectedNotesIds: Set<Note.ID> = []

    private var selectedNote: Note?{
        guard let selectedNoteId = selectedNotesIds.first,
              let selectedNote = notes.filter ({$0.id == selectedNoteId}).first else{
                  return nil
              }
        return selectedNote
    }
    var body: some View {
        List(notes, selection: $selectedNotesIds){ note in
            NavigationLink(note.name, destination: NoteEditor(note: note ))
        }

        .toolbar{
            ToolbarItem(placement: .primaryAction){
                Button(action: createNote){
                    Label("Create Quick Note", systemImage: "square.and.pencil")
                }
            }

            ToolbarItem(placement: .primaryAction){
                Button(action: deleteSelectedNotes){
                    Label("Delete note", systemImage: "trash")
                }
            }

        }

    }

    private func createNote(){
         createNote(name: "New note", text: "")

    }
    private func createNote(name: String, text: String) {
        withAnimation {
            let note = Note(context: viewContext)
            note.id = UUID()
            note.name = name
            note.text = text

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }

        }

    }

    private func deleteSelectedNotes(){
        withAnimation{
            let selectedNotes = notes.filter {selectedNotesIds.contains($0.id)}
            deleteNotes(notes: selectedNotes)
        }

    }

    private func deleteNotes(notes: [Note]){
        viewContext.perform{ notes.forEach(viewContext.delete)}
    }
}


Title: How can I draw the polygon using these coordinates?

Body:
I am trying to draw the polygons using these coordinates and it is just showing single line which is not correct, what i am doing wrong , My code is shown below:

import PIL.ImageDraw as ImageDraw
import PIL.Image as Image
%matplotlib inline
plt.figure(figsize=(16,16))
plt.axis('off')

df_dict__ = {}
df_dict__['data'] = [{"x":1821,"y":689},{"x":1819,"y":689},{"x":1819,"y":692},{"x":1819,"y":700},
    {"x":1819,"y":705},{"x":1821,"y":713},{"x":1821,"y":716},{"x":1821,"y":721},{"x":1824,
    "y":729},{"x":1824,"y":734},{"x":1824,"y":740},{"x":1824,"y":745},{"x":1824,"y":748},
    {"x":1824,"y":753},{"x":1824,"y":758},{"x":1824,"y":761},{"x":1824,"y":769},{"x":1824,
    "y":774},{"x":1826,"y":782},{"x":1826,"y":795},{"x":1826,"y":798},{"x":1826,"y":801},
    {"x":1826,"y":803},{"x":1826,"y":808},{"x":1830,"y":814},{"x":1830,"y":822},{"x":1830,
    "y":824},{"x":1830,"y":827},{"x":1830,"y":830},{"x":1833,"y":835},{"x":1833,"y":838},
    {"x":1833,"y":843},{"x":1833,"y":848},{"x":1835,"y":851},{"x":1835,"y":853},{"x":1835,
    "y":856},{"x":1835,"y":861},{"x":1835,"y":864},{"x":1835,"y":867},{"x":1835,"y":875},
    {"x":1837,"y":880},{"x":1837,"y":888},{"x":1837,"y":893},{"x":1837,"y":896},{"x":1842,
    "y":901},{"x":1842,"y":904},{"x":1842,"y":906}]

convertedDict = df_dict__
length = len(convertedDict['data'])
image = Image.new("RGB", (2400, 1600))
draw = ImageDraw.Draw(image)
x = []
y = []
for j in range(length):  #put each x and y for each row in seperate array
    x.append(convertedDict['data'][j]['x'])
    y.append(convertedDict['data'][j]['y'])
points = tuple(zip(x, y))
draw.polygon((points), fill=200)
plt.imshow(image)
plt.show()

I have tried with above code but not working


问:
1.on websphere server getting java.lang.ClassCastException: org.jboss.seam.web.ContextFilter incompatible with javax.servlet.Filter
1.on websphere server getting java.lang.ClassCastException: org.jboss.seam.web.ContextFilter incompatible with javax.servlet.Filter

2.it is working on jboss app server.

3.ContextFilter is a filter applied to /* in web.xml
hence when applications is accessed , error is shown.

3.class hierarchy of ContextFilter

ContextFilter  extends AbstractFilter

AbstractFilter implements javax.servlet.Filter

4.but still while application is accessed from it is showing "not a filter"

5.ContextFilter is a class in jar   : jboss-seam.jar
this jar file and class file in present in web-inf/lib

6.complete stack trace :
12/20/22 13:10:23:075 IST] 0000006b webapp    E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor]: java.lang.ClassCastException: org.jboss.seam.web.ContextFilter incompatible with javax.servlet.Filter
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager._loadFilter(WebAppFilterManager.java:572)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.loadFilter(WebAppFilterManager.java:514)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterInstanceWrapper(WebAppFilterManager.java:319)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterChain(WebAppFilterManager.java:392)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:931)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1107)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4047)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1016)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:213)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture$1.run(AsyncChannelFuture.java:205)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)


问:
Error: Couldn't find a navigation object. Is your component inside NavigationContainer?
I went through the other answers to this question but none has worked for me i'm trying to do a button in the LoginScreen that navigates to the RegisterScreen but get the error

This is what my App.js returns

```<code>
<NavigationContainer>
      <StatusBar hidden />

        <Stack.Navigator initialRouteName="Login">
          <Stack.Screen name ="Login" component={LoginScreen}/>
          <Stack.Screen name ="Register" component={RegisterScreen}/>
        </Stack.Navigator>

        <Tab.Navigator
          activeColor="black"
          inactiveColor="gray"
          initialRouteName="Home"
        >
          <Tab.Screen
            name="Home"
            component={Home}
            options={{
              tabBarLabel: "",
              tabBarIcon: ({ color }) => (
                <MaterialCommunityIcons name="home" color={color} size={33} />
              ),
            }}
          />

          <Tab.Screen
            name="Calendrier"
            component={Calendrier}
            options={{
              tabBarLabel: "",
              tabBarIcon: ({ color }) => (
                <MaterialCommunityIcons
                  name="calendar-month-outline"
                  color={color}
                  size={30}
                />
              ),
            }}
          />
        </Tab.Navigator>
    </NavigationContainer>

</code>```

And this is where is want to use the navigation.navigate but get the error (line 2)

```<code>
export default function LoginScreen ()  {
    const navigation = useNavigation();
    return(
    <View style={{flex:1, backgroundColor:'mistyrose'}}>
               <View style={{justifyContent:'flex-start', alignItems:"flex-end"}}>
    <Button color ='mistyrose' onPress={()=> navigation.navigate("Register")} title='abaabab'></Button>
</View>

            <ConnectButton/>
        </View>
</code>```

I tried using export default fuction LoginScreen({navigation}){
//code... } but it didn't work either, I checked my imports and i'm pretty sure they're the good ones. Please Help!!

Body:
I went through the other answers to this question but none has worked for me i'm trying to do a button in the LoginScreen that navigates to the RegisterScreen but get the error

This is what my App.js returns

<NavigationContainer>
      <StatusBar hidden />

        <Stack.Navigator initialRouteName="Login">
          <Stack.Screen name ="Login" component={LoginScreen}/>
          <Stack.Screen name ="Register" component={RegisterScreen}/>
        </Stack.Navigator>

        <Tab.Navigator
          activeColor="black"
          inactiveColor="gray"
          initialRouteName="Home"
        >
          <Tab.Screen
            name="Home"
            component={Home}
            options={{
              tabBarLabel: "",
              tabBarIcon: ({ color }) => (
                <MaterialCommunityIcons name="home" color={color} size={33} />
              ),
            }}
          />

          <Tab.Screen
            name="Calendrier"
            component={Calendrier}
            options={{
              tabBarLabel: "",
              tabBarIcon: ({ color }) => (
                <MaterialCommunityIcons
                  name="calendar-month-outline"
                  color={color}
                  size={30}
                />
              ),
            }}
          />
        </Tab.Navigator>
    </NavigationContainer>

And this is where is want to use the navigation.navigate but get the error (line 2)

export default function LoginScreen ()  {
    const navigation = useNavigation();
    return(
    <View style={{flex:1, backgroundColor:'mistyrose'}}>
               <View style={{justifyContent:'flex-start', alignItems:"flex-end"}}>
    <Button color ='mistyrose' onPress={()=> navigation.navigate("Register")} title='abaabab'></Button>
</View>

            <ConnectButton/>
        </View>

I tried using export default fuction LoginScreen({navigation}){
//code... } but it didn't work either, I checked my imports and i'm pretty sure they're the good ones. Please Help!!


问:
How to make event-triggered or time-triggered based email using react and js?
I want to make a notification system that can send emails based on time or events using react and js. Could anyone give me some suggestions on how to send emails based on time or events? Any APIs or tutorials would be OK. Thank you so much.</p>


问:
difficulty with NA in ifelse
I've read previous posts on this but still dont understand what is happening with my code and why. In other scenarios is seems comparison of NA with other values can cause an issue but I am not doing that here (I dont think).
So,

I have this Data frame

```<code>library(dplyr)
df<-data.frame(x=sample(c(1,0,NA),20,replace=TRUE),
               y=sample(c(1,0,NA),20,replace=TRUE))
</code>```

which give me data that looks like this:

```<code>    x  y
1  NA NA
2   1  0
3   0  0
4  NA NA
5  NA NA
6   1 NA
</code>```

I want a third variable to be 1 if either x or y is 1, zero if either x or y is zero but not 1, and NA otherwise.

I've tried nesting an ifelse like so:

```<code>df_new<-df %>% mutate(var=ifelse(x==1|y==1,1,
                ifelse(x==0|y==0,0,NA)))
</code>```

which give me:

```<code>16 NA NA  NA
17  1  1   1
18  0 NA  NA
19 NA  1   1
20  0  1   1
</code>```

but as you can see in line 18 where the new variable should be 0, it is NA. Can someone explain why this is happening and how to fix the code I've written?

Title: difficulty with NA in ifelse

Body:
I've read previous posts on this but still dont understand what is happening with my code and why. In other scenarios is seems comparison of NA with other values can cause an issue but I am not doing that here (I dont think).
So,

I have this Data frame

library(dplyr)
df<-data.frame(x=sample(c(1,0,NA),20,replace=TRUE),
               y=sample(c(1,0,NA),20,replace=TRUE))

which give me data that looks like this:

    x  y
1  NA NA
2   1  0
3   0  0
4  NA NA
5  NA NA
6   1 NA

I want a third variable to be 1 if either x or y is 1, zero if either x or y is zero but not 1, and NA otherwise.

I've tried nesting an ifelse like so:

df_new<-df %>% mutate(var=ifelse(x==1|y==1,1,
                ifelse(x==0|y==0,0,NA)))

which give me:

16 NA NA  NA
17  1  1   1
18  0 NA  NA
19 NA  1   1
20  0  1   1

but as you can see in line 18 where the new variable should be 0, it is NA. Can someone explain why this is happening and how to fix the code I've written?


问:
Best data structure for storing a multivector
I'm working on a library for doing computations with multivectors and I'm trying to figure out how to properly store the data.

Very quickly, a multivector is the sum of blades, each containing zero or more bases. For example, V = 1 + 2x + 3yz - 4xz is a multivector.

In Python, the structure I settled on was a mapping of tuples of basis indices to scalars; in type syntax that's TermDict = Dict[Tuple[int, ...], float] - V above would be stored as {(): 1.0, (0,): 2.0, (1, 2): 3.0, (0, 2): -4.0}

However I'm now attempting to port this to C++ and getting uncomfortable. Currently what I have for the purpose is:

// Adapted from https://stackoverflow.com/a/53283994/6605349
struct SetHasher {
    int operator()(const std::set<unsigned int>& V) const {
        int hash = V.size();
        for (auto &i : V) {
            hash ^= i + 0x9e3779b9 + (hash << 6) + (hash >> 2);
        }
        return hash;
    }
};
typedef std::unordered_map<std::set<unsigned int>, double, SetHasher> TermDict;
```

which I believe just emulates the Python behavior. However, with apologies to Chirag, I have a lot less faith in a random SO answer than in the CPython tuple.__hash__ implementation, so I'm wondering if there's a better way to go about this that can avoid the need to hash a collection of indices. I could possibly apply this to the Python implementation too. What might there be? Or have I got the best idea after all?

Body:
I'm working on a library for doing computations with multivectors and I'm trying to figure out how to properly store the data.

Very quickly, a multivector is the sum of blades, each containing zero or more bases. For example, V = 1 + 2x + 3yz - 4xz is a multivector.

In Python, the structure I settled on was a mapping of tuples of basis indices to scalars; in type syntax that's TermDict = Dict[Tuple[int, ...], float] - V above would be stored as {(): 1.0, (0,): 2.0, (1, 2): 3.0, (0, 2): -4.0}

However I'm now attempting to port this to C++ and getting uncomfortable. Currently what I have for the purpose is:

// Adapted from https://stackoverflow.com/a/53283994/6605349
struct SetHasher {
    int operator()(const std::set<unsigned int>& V) const {
        int hash = V.size();
        for (auto &i : V) {
            hash ^= i + 0x9e3779b9 + (hash << 6) + (hash >> 2);
        }
        return hash;
    }
};
typedef std::unordered_map<std::set<unsigned int>, double, SetHasher> TermDict;

which I believe just emulates the Python behavior. However, with apologies to Chirag, I have a lot less faith in a random SO answer than in the CPython tuple.__hash__ implementation, so I'm wondering if there's a better way to go about this that can avoid the need to hash a collection of indices. I could possibly apply this to the Python implementation too. What might there be? Or have I got the best idea after all?


问:
router.navigate doesn't redirect no error either
I have this code:

```<code>        console.log('aa');
        let loc = '/' + this.config.AppTree.PApp.STModule.List.Path.toString();
        console.log('loc = ' + loc);
        this.router.navigate([loc], { state: { data: { abc: 1 } } });
        console.log('done, why no move?');

</code>```

I added the console log, to see everything is all right, and I can see all 3 logs displayed, the screen never gets redirected.

loc variable is displayed correctly, just how it should look like

I tried to change some code around, and for example if I use this.config.AppTree.DApp.OtherModule.List.Path instead of this.config.AppTree.PApp.STModule.List.Path, then it works.

But to make it more confusing, some PApp paths work, some don't, and some DApp paths work, some don't.

I tried to add try catch, nothing happens.

Browser does not display any info, any error, and I find it odd that I get displayed the console log, and the redirect between them is handles like if it was a comment

PApp and DApp have 50+ module each inside, and redirecting with router.navigate usually works fine.

As I am new to Angular, what can I try? How can I make it display any warning or error, anything that will help me figure out why is the no navigation? Thanks

ng version info:

Angular CLI: 12.2.11
Node 16.13.0
Package manager: npm. 8.1.0
OS: win32 x64

Server side is .net Core

Body:
I have this code:

        console.log('aa');
        let loc = '/' + this.config.AppTree.PApp.STModule.List.Path.toString();
        console.log('loc = ' + loc);
        this.router.navigate([loc], { state: { data: { abc: 1 } } });
        console.log('done, why no move?');

I added the console log, to see everything is all right, and I can see all 3 logs displayed, the screen never gets redirected.

loc variable is displayed correctly, just how it should look like

I tried to change some code around, and for example if I use this.config.AppTree.DApp.OtherModule.List.Path instead of this.config.AppTree.PApp.STModule.List.Path, then it works.

But to make it more confusing, some PApp paths work, some don't, and some DApp paths work, some don't.

I tried to add try catch, nothing happens.

Browser does not display any info, any error, and I find it odd that I get displayed the console log, and the redirect between them is handles like if it was a comment

PApp and DApp have 50+ module each inside, and redirecting with router.navigate usually works fine.

As I am new to Angular, what can I try? How can I make it display any warning or error, anything that will help me figure out why is the no navigation? Thanks

ng version info:

Angular CLI: 12.2.11
Node 16.13.0
Package manager: npm. 8.1.0
OS: win32 x64

Server side is .net Core


问:
Changing the text color while finding a value in npm json-query
I am using json-query package in part of my application to find a value from a table. However, I'd like to know if this package is capable of changing the colour of matched letters while finding the value.
The photo below shows what I mean:

And here is the code:

```<code> let data
    data = { colorCodes: this.specialData.dataCodes };
    return jsonQuery(
      `${this.specialData.code}[*${this.specialData.key}:contains(${this.searchCode})]`,
      {
        data: data,
        locals: helpers,
      }
    ).value;
</code>```

I'd like to know if anybody knows how to make this functionality happen.

Body:
I am using json-query package in part of my application to find a value from a table. However, I'd like to know if this package is capable of changing the colour of matched letters while finding the value.
The photo below shows what I mean:

And here is the code:

 let data
    data = { colorCodes: this.specialData.dataCodes };
    return jsonQuery(
      `${this.specialData.code}[*${this.specialData.key}:contains(${this.searchCode})]`,
      {
        data: data,
        locals: helpers,
      }
    ).value;

I'd like to know if anybody knows how to make this functionality happen.


问:
I have IaaS REST API to create and destroy service, how to call those API's in terraform to create and destroy the service on resources?
Not able to create the service using terraform template</p>
```<code>resource "null_resource" "rest-db"
{
     provisioner "local-exec" {
         inline = [
            "call the REST API here using CLI tools",
         ]
     }
}
</code>```

Body:
Not able to create the service using terraform template

resource "null_resource" "rest-db"
{
     provisioner "local-exec" {
         inline = [
            "call the REST API here using CLI tools",
         ]
     }
}


问:
Create python colorbar without plot
I used opencv colormaps on grayscale images. Now i need to show a colorbar, that represents the colormaps used in the colored image. As far as i know you can only create colorbars with plots. Is there any way to display a colorbar on a tkinter canvas without a plot?

I tried to create a plot and make it not visible but there is always some empty white space where the plot should be, when turned visible.

Title: Create python colorbar without plot


问:
Using ZendAMF inside a Codeigniter controller
Not sure if I am going the best way about this, I am trying to implement ZENDAMF with codeigniter. One of the problems I have had is that I want to be able to check if the user is logged in before allowing them  to make any requests to the servrices behind the zendamf gateway. I did ask a previous question about how to get it to do the check in the construct, but I found out that was not possible.

My next line of thought was to create the gateway as a controller that way I would be able to access my authentication library before the request was posted to the zend amf server. But when I make a call to the service is is not recognizing any of the CodeIgniter methods.

at the moment I am not doing the logged in check as I want to get the amf server working first, so the example I have choosen is to try and return my UserDetails.

here is my gateway.php controller

```<code><?php
// Set up debug
class Gateway extends CI_Controller
{

    function __construct()
    {
        parent::__construct();

        error_reporting(E_ALL | E_STRICT);
        ini_set("display_errors", "on");

        ini_set("include_path",
        ini_get('include_path') . ':'
                        . '/Applications/MAMP/htdocs/app/application/libraries/');
        require_once("Zend/Amf/Server.php");
        // Start Server
        $server = new Zend_Amf_Server();

        // Zend_Amf_Server require.
        // Require the ZendAmfServiceBrowser class
        require_once("Zend/browser/ZendAmfServiceBrowser.php");
        // Class requires.
        require_once("services/Testservice.php");
        //require_once( "services/ReturnTests.php" );

        // Register Demo Classes
        $server->setClass("Testservice");
        //$server->setClass( "ReturnTests" );
        //$server->setResponse('test');
        // Add the ZamfBrowser service class so ZamfBrowser can retrieve method information.
        $server->setClass("ZendAmfServiceBrowser");
        // Set a reference to the Zend_Amf_Server object so ZendAmfServiceBrowser class can retrieve method information.
        ZendAmfServiceBrowser::$ZEND_AMF_SERVER = $server;
         $server->setProduction(false);

        // Handle ZendAMF request
        echo ($server->handle());
         redirect(base_url().'Gateway');

    }
}
</code>```

and this is my testservice

```<code><?php

class Testservice extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }

function UserDetails()
    {
        $this->load->model('users_model');

        // Grab user info
        $user_id = 3;//$this->session->userdata('user_id');
        $this->user = $this->users_model->get_user_by_id($user_id);
        $this->data['user'] = $this->user;

        return $this->data;
    }
}
</code>```

when I implement all of this I get the following response:

```<code><h4>A PHP Error was encountered</h4>

<p>Severity: Notice</p>
<p>Message:  Undefined property: Testservice::$users_model</p>
<p>Filename: services/Testservice.php</p>
<p>Line Number: 90</p>
</code>```

If I am extending CI_Controller I would have though that it should allow me to access all my models.

Any ideas I am really stumped on this now.

Thanks In Advance

ContentLicense: CC BY-SA 3.0

Body:
Not sure if I am going the best way about this, I am trying to implement ZENDAMF with codeigniter. One of the problems I have had is that I want to be able to check if the user is logged in before allowing them  to make any requests to the servrices behind the zendamf gateway. I did ask a previous question about how to get it to do the check in the construct, but I found out that was not possible.

My next line of thought was to create the gateway as a controller that way I would be able to access my authentication library before the request was posted to the zend amf server. But when I make a call to the service is is not recognizing any of the CodeIgniter methods.

at the moment I am not doing the logged in check as I want to get the amf server working first, so the example I have choosen is to try and return my UserDetails.

here is my gateway.php controller

<?php
// Set up debug
class Gateway extends CI_Controller
{

    function __construct()
    {
        parent::__construct();

        error_reporting(E_ALL | E_STRICT);
        ini_set("display_errors", "on");

        ini_set("include_path",
        ini_get('include_path') . ':'
                        . '/Applications/MAMP/htdocs/app/application/libraries/');
        require_once("Zend/Amf/Server.php");
        // Start Server
        $server = new Zend_Amf_Server();

        // Zend_Amf_Server require.
        // Require the ZendAmfServiceBrowser class
        require_once("Zend/browser/ZendAmfServiceBrowser.php");
        // Class requires.
        require_once("services/Testservice.php");
        //require_once( "services/ReturnTests.php" );

        // Register Demo Classes
        $server->setClass("Testservice");
        //$server->setClass( "ReturnTests" );
        //$server->setResponse('test');
        // Add the ZamfBrowser service class so ZamfBrowser can retrieve method information.
        $server->setClass("ZendAmfServiceBrowser");
        // Set a reference to the Zend_Amf_Server object so ZendAmfServiceBrowser class can retrieve method information.
        ZendAmfServiceBrowser::$ZEND_AMF_SERVER = $server;
         $server->setProduction(false);

        // Handle ZendAMF request
        echo ($server->handle());
         redirect(base_url().'Gateway');

    }
}

and this is my testservice

<?php

class Testservice extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }

function UserDetails()
    {
        $this->load->model('users_model');

        // Grab user info
        $user_id = 3;//$this->session->userdata('user_id');
        $this->user = $this->users_model->get_user_by_id($user_id);
        $this->data['user'] = $this->user;

        return $this->data;
    }
}

when I implement all of this I get the following response:

A PHP Error was encountered

Severity: Notice

Message:  Undefined property: Testservice::$users_model

Filename: services/Testservice.php

Line Number: 90

If I am extending CI_Controller I would have though that it should allow me to access all my models.

Any ideas I am really stumped on this now.

Thanks In Advance


问:
MySQL dump import bug
I tried to import mysql dump of 3GB at that point my C:\ drive had 70GB free space. Once I started my dump gradually C:\ drive became full and import also failed. I am using maria db 10.9 version. Can any one help me to fix this issue.

This is my.ini file

```<code>[mysqld]
datadir=C:/Program Files/MariaDB 10.9/data
port=3306
innodb_buffer_pool_size=2019M
max_allowed_packet=10G
innodb_file_per_table
[client]
port=3306
plugin-dir=C:\Program Files\MariaDB 10.9/lib/plugin
</code>```

Title: MySQL dump import bug

Body:
I tried to import mysql dump of 3GB at that point my C:\ drive had 70GB free space. Once I started my dump gradually C:\ drive became full and import also failed. I am using maria db 10.9 version. Can any one help me to fix this issue.

This is my.ini file

[mysqld]
datadir=C:/Program Files/MariaDB 10.9/data
port=3306
innodb_buffer_pool_size=2019M
max_allowed_packet=10G
innodb_file_per_table
[client]
port=3306
plugin-dir=C:\Program Files\MariaDB 10.9/lib/plugin


问:
ADO - How do I call different parameters for a script depending on the context? / RUN THE SAME SCRIPT w/Dynamic Parameters according to the context
AZURE ADO
I am working currently on a script to automate clean up unused storage accounts from Azure. This script would run on a Runbook. There are 4  subscriptions specifically created to contain storage accounts for each tenant, LAB and PRD, 2 each. So what I need is that THE SAME SCRIPT automatically runs with the subscription that corresponds to the Tenant that it belongs. There are 2 subscriptions for DEV and 2 for PRD. I would need to create an array for calling both of them at the same time depending on the context. I don't know how exactly I should parametrize the Subscription that will be called. Should I create a different file .json file with all the parameters? Note that also the same script should run at different times according to the tenant. That's why I created a schedule for LAB (THAT SHOULD RUN THE SCRIPT WITH THE BOTH LAB SUBS) and another Schedule for PRD (THAT SHOULD RUN THE SCRIPT WITH THE BOTH LAB SUBS)

```<code>Param(
    [Parameter(Mandatory)]
    [string]$SubscriptionFL
    )
Connect-AzAccount -Identity
</code>```

I don't know how exactly I should proceed with this. The script itself works perfectly and does what's needed. My problem is that I'm pretty new in this and I'm figuring out stuff. I don't know how to make the script dynamic and be the most generic it can be, so that we would run the same script with different variables according to the context (LAB or PRD)

Body:
AZURE ADO
I am working currently on a script to automate clean up unused storage accounts from Azure. This script would run on a Runbook. There are 4  subscriptions specifically created to contain storage accounts for each tenant, LAB and PRD, 2 each. So what I need is that THE SAME SCRIPT automatically runs with the subscription that corresponds to the Tenant that it belongs. There are 2 subscriptions for DEV and 2 for PRD. I would need to create an array for calling both of them at the same time depending on the context. I don't know how exactly I should parametrize the Subscription that will be called. Should I create a different file .json file with all the parameters? Note that also the same script should run at different times according to the tenant. That's why I created a schedule for LAB (THAT SHOULD RUN THE SCRIPT WITH THE BOTH LAB SUBS) and another Schedule for PRD (THAT SHOULD RUN THE SCRIPT WITH THE BOTH LAB SUBS)

Param(
    [Parameter(Mandatory)]
    [string]$SubscriptionFL
    )
Connect-AzAccount -Identity

I don't know how exactly I should proceed with this. The script itself works perfectly and does what's needed. My problem is that I'm pretty new in this and I'm figuring out stuff. I don't know how to make the script dynamic and be the most generic it can be, so that we would run the same script with different variables according to the context (LAB or PRD)


问:
Uncaught TypeError: __webpack_require__(...).context is not a function
I've seen the suggested links from SO but all of them mention using literals as props to the context variable.

```<code>const cache: any = {};
function importAll(r: __WebpackModuleApi.RequireContext) {
  r.keys().forEach((key: string) => (cache[key] = r(key)));
}
importAll(require.context('./services/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./components/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./directives/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./filters/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./native-extensions/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./prototypes/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./views/', true, /(?<!spec)\.[j|t]s$/));

import './index.config';
import './index.run';
import './index.route';

importAll(require.context('./', true, /\.jade$/));
</code>```

As you can see I'm using literals only yet I still get the error: ncaught TypeError: __webpack_require__(...).context is not a function

Body:
I've seen the suggested links from SO but all of them mention using literals as props to the context variable.

const cache: any = {};
function importAll(r: __WebpackModuleApi.RequireContext) {
  r.keys().forEach((key: string) => (cache[key] = r(key)));
}
importAll(require.context('./services/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./components/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./directives/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./filters/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./native-extensions/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./prototypes/', true, /(?<!spec)\.[j|t]s$/));
importAll(require.context('./views/', true, /(?<!spec)\.[j|t]s$/));

import './index.config';
import './index.run';
import './index.route';

importAll(require.context('./', true, /\.jade$/));

As you can see I'm using literals only yet I still get the error: ncaught TypeError: __webpack_require__(...).context is not a function