问:
Postgresql [42P01] ERROR: relation does not exist during trigger function
I am trying to write a trigger that stores previous versions of a row in a table named audit_tablename given a table named tablename.

Here is the the code...

```<code>CREATE OR REPLACE FUNCTION process_ui_audit()
RETURNS TRIGGER AS
$$
DECLARE

    audit_table_name   text := TG_TABLE_SCHEMA || '.audit_' || TG_TABLE_NAME;
    audit_table_schema text := TG_TABLE_SCHEMA;

BEGIN

    IF (TG_OP = 'UPDATE')
    THEN

        EXECUTE FORMAT('INSERT INTO %1$I SELECT NEXTVAL(''$1.hibernate_sequence''),now(), user, ($1).*',
                       audit_table_name, audit_table_schema)
            USING OLD;

        NEW.version = OLD.version + 1;

        RETURN NEW;
    ELSIF (TG_OP = 'INSERT')
    THEN
        NEW.version = 1;
        RETURN NEW;
    END IF;
END;
</code>```

When I try to update a row the trigger runs and I get errors like this....

[42P01] ERROR: relation "webapp.audit_portal_user" does not exist

  Where: PL/pgSQL function webapp.process_ui_audit() line 13 at EXECUTE

I am wonderin am I formatting table names incorrectly or something? The table name webapp.audit_portal_user definetly exists.

答:
It works without specifying schema name.

Here is a simplified example:

```<code>create table portal_user(
uid     int,
uname   text
);
CREATE TABLE

create table audit_portal_user(
uid      int,
uname    text,
who      text,
what     text,
ts       timestamp
);
CREATE TABLE

create or replace function process_ui_audit()
returns trigger as
$$
declare
audit_table_name   text := 'audit_' || tg_table_name;
begin
 if (tg_op = 'UPDATE')
 then
    execute format('insert into %I values($1.*, user, %L, now())',
                    audit_table_name, 'UPDATE') using new;
    return null;
 end if;
end;
$$
language plpgsql;
CREATE FUNCTION

create trigger audit
after update on portal_user
for each row
execute function process_ui_audit();
CREATE TRIGGER

insert into portal_user values(12, 'titi');
INSERT 0 1

select * from portal_user;
 uid | uname
-----+-------
  12 | titi
(1 row)

update portal_user set uname='toto' where uid=12;
UPDATE 1

select * from portal_user;
 uid | uname
-----+-------
  12 | toto
(1 row)

select * from audit_portal_user;
 uid | uname |   who    |  what  |             ts
-----+-------+----------+--------+----------------------------
  12 | toto  | postgres | UPDATE | 2020-06-01 10:20:36.549257
(1 row)
</code>```

Body:
I am trying to write a trigger that stores previous versions of a row in a table named audit_tablename given a table named tablename.

Here is the the code...

CREATE OR REPLACE FUNCTION process_ui_audit()
RETURNS TRIGGER AS
$$
DECLARE

    audit_table_name   text := TG_TABLE_SCHEMA || '.audit_' || TG_TABLE_NAME;
    audit_table_schema text := TG_TABLE_SCHEMA;

BEGIN

    IF (TG_OP = 'UPDATE')
    THEN

        EXECUTE FORMAT('INSERT INTO %1$I SELECT NEXTVAL(''$1.hibernate_sequence''),now(), user, ($1).*',
                       audit_table_name, audit_table_schema)
            USING OLD;

        NEW.version = OLD.version + 1;

        RETURN NEW;
    ELSIF (TG_OP = 'INSERT')
    THEN
        NEW.version = 1;
        RETURN NEW;
    END IF;
END;

When I try to update a row the trigger runs and I get errors like this....

[42P01] ERROR: relation "webapp.audit_portal_user" does not exist

  Where: PL/pgSQL function webapp.process_ui_audit() line 13 at EXECUTE

I am wonderin am I formatting table names incorrectly or something? The table name webapp.audit_portal_user definetly exists.

Body:
It works without specifying schema name.

Here is a simplified example:

create table portal_user(
uid     int,
uname   text
);
CREATE TABLE

create table audit_portal_user(
uid      int,
uname    text,
who      text,
what     text,
ts       timestamp
);
CREATE TABLE

create or replace function process_ui_audit()
returns trigger as
$$
declare
audit_table_name   text := 'audit_' || tg_table_name;
begin
 if (tg_op = 'UPDATE')
 then
    execute format('insert into %I values($1.*, user, %L, now())',
                    audit_table_name, 'UPDATE') using new;
    return null;
 end if;
end;
$$
language plpgsql;
CREATE FUNCTION

create trigger audit
after update on portal_user
for each row
execute function process_ui_audit();
CREATE TRIGGER

insert into portal_user values(12, 'titi');
INSERT 0 1

select * from portal_user;
 uid | uname
-----+-------
  12 | titi
(1 row)

update portal_user set uname='toto' where uid=12;
UPDATE 1

select * from portal_user;
 uid | uname
-----+-------
  12 | toto
(1 row)

select * from audit_portal_user;
 uid | uname |   who    |  what  |             ts
-----+-------+----------+--------+----------------------------
  12 | toto  | postgres | UPDATE | 2020-06-01 10:20:36.549257
(1 row)


来源: stackexchange

问:
Is there any way to force django run some finishing code before exit?
I am running a server program with django,
I want to run some code before and after the server running.
Where can I put those code?

```<code><run function a here>
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C
<run function b here>
</code>```

I have tried to a print('hello') in app/__init__.py, but found that it runs for twice. Why?

答:
You can provide your own runserver command and override django's. Assuming your app is named polls like in the Django tutorial, then you need to create this structure:

```<code>polls/
    ...
    |management/
        |__init__.py
        |commands/
             |__init__.py
             |runserver.py
</code>```

This creates the python modules "polls.management" and "polls.management.commands", which is where Django is looking for management commands.

# Put in polls/management/commands/runserver.py
from django.core.management.commands.runserver import Command as RunServer

class Command(RunServer):
    def inner_run(self, *args, **options):
        self.pre_start()
        super().inner_run(*args, **options)
        self.pre_quit()

    def pre_start(self):
        # do your stuff

    def pre_quit(self):
        # do your stuff
```

<p>If you have <code>django.contrib.staticfiles</code> in <code>INSTALLED_APPS</code>, you need to put your app before <code>django.contrib.staticfiles</code> and change the import:</p>

<pre class="lang-py prettyprint-override"><code>from django.contrib.staticfiles.management.commands.runserver import Command as RunServer
</code>```

So if your app is polls INSTALLED_APPS in settings.py should become:

INSTALLED_APPS = [
    # other apps
    "polls",
    "django.contrib.staticfiles",
    # other apps
]
```

ContentLicense: CC BY-SA 4.0

Body:
I am running a server program with django,
I want to run some code before and after the server running.
Where can I put those code?

<run function a here>
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C
<run function b here>

I have tried to a print('hello') in app/__init__.py, but found that it runs for twice. Why?

Body:
You can provide your own runserver command and override django's. Assuming your app is named polls like in the Django tutorial, then you need to create this structure:

polls/
    ...
    |management/
        |__init__.py
        |commands/
             |__init__.py
             |runserver.py

This creates the python modules "polls.management" and "polls.management.commands", which is where Django is looking for management commands.

# Put in polls/management/commands/runserver.py
from django.core.management.commands.runserver import Command as RunServer

class Command(RunServer):
    def inner_run(self, *args, **options):
        self.pre_start()
        super().inner_run(*args, **options)
        self.pre_quit()

    def pre_start(self):
        # do your stuff

    def pre_quit(self):
        # do your stuff

If you have django.contrib.staticfiles in INSTALLED_APPS, you need to put your app before django.contrib.staticfiles and change the import:

from django.contrib.staticfiles.management.commands.runserver import Command as RunServer

So if your app is polls INSTALLED_APPS in settings.py should become:

INSTALLED_APPS = [
    # other apps
    "polls",
    "django.contrib.staticfiles",
    # other apps
]


问:
Error while updating a table with sequence
I have table Hash_emp and a sequence as below

Sequence:

```<code>CREATE SEQUENCE Increment_bY_1
START WITH 1
INCREMENT BY 1
NOMAXVALUE NOCYCLE
CACHE 10;
</code>```

When I am updating the Employee_id with the For loop, it is throwing an error. Can someone explain what went wrong?

```<code>declare
i number;
begin
for i in 2..29
update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where rownum=i;
end loop;
end;
</code>```

Error

PLS-00103: Encountered the symbol "UPDATE" when expecting one of the following:

& - + / at loop mod remainder rem  ||

  multiset

  The symbol "loop" was substituted for "UPDATE" to continue.

00000 -  "line %s, column %s:\n%s"

  *Cause:    Usually a PL/SQL compilation error. --------------

答:
As the other answer points out, the FOR LOOP is not needed. But just for completeness, this is why you got the error in the first place. The actual error is cause by a syntax error in the FOR LOOP statement. The syntax for a FOR LOOP is:

```<code>
FOR index IN lower_bound .. upper_bound LOOP
  statement;
END LOOP;
</code>```

In your case the first "LOOP" is missing.

Body:
I have table Hash_emp and a sequence as below

Sequence:

CREATE SEQUENCE Increment_bY_1
START WITH 1
INCREMENT BY 1
NOMAXVALUE NOCYCLE
CACHE 10;

When I am updating the Employee_id with the For loop, it is throwing an error. Can someone explain what went wrong?

declare
i number;
begin
for i in 2..29
update hash_emp set EMPLOYEE_ID=INCREMENT_BY_1.nextval where rownum=i;
end loop;
end;

Error

PLS-00103: Encountered the symbol "UPDATE" when expecting one of the following:

& - + / at loop mod remainder rem  ||

  multiset

  The symbol "loop" was substituted for "UPDATE" to continue.

00000 -  "line %s, column %s:\n%s"

  *Cause:    Usually a PL/SQL compilation error. --------------

Body:
As the other answer points out, the FOR LOOP is not needed. But just for completeness, this is why you got the error in the first place. The actual error is cause by a syntax error in the FOR LOOP statement. The syntax for a FOR LOOP is:

FOR index IN lower_bound .. upper_bound LOOP
  statement;
END LOOP;

In your case the first "LOOP" is missing.


问:
How to use a proxy with html2canvas (latest version)
I'm trying to capture a screenshot of a bing map with html2canvas. From what I can see I need to use a proxy to allow external images to be captured. I see this suggested use. But I really don't see any suggestion on how it could be used (like an example). Anyone have an example? I'm using the latest version with promises. Thanks!</p>

答:
Hi im working in this problem, in my situation the map work perfect, for configure the proxy just add this line in the html2canvas script:

```<code>        function makeScreenshot()
        {
            html2canvas(document.getElementById("bingMap"), {
                proxy:'',
                type: 'view',
                logging: true,
                userCORS: true,
                ignoreElements:(showDashboard)=>{return false},
                Timeout:(5000)
            })
            .then(canvas =>
            {
                canvas.id = "canvasID";
                var main = document.getElementById("main");
                //while (main.firstChild) { main.removeChild(main.firstChild); }
                setTimeout(function(){main.appendChild(canvas);},5000);
            });
        }

        document.getElementById("a-make").addEventListener('click', function()
        {
            document.getElementById("a-make").style.display = "none";
            makeScreenshot();
            document.getElementById("a-download").style.display = "inline";
        }, false);

        document.getElementById("a-download").addEventListener('click', function()
        {
            this.href = document.getElementById("canvasID").toDataURL();
            this.download = "canvas-map.png";
        }, false);
</code>```

the "proxy" can be in blank, or read this(html2canvas php proxy), in the script of bing maps u need enable CORS:

```<code>    var loc = new Microsoft.Maps.Location(urlatmap, urlngmap)
    mapOptions = {
        credentials: bingkey,
        center: loc,
        zoom: 16,
        mapTypeId: Microsoft.Maps.MapTypeId.aerial,
        showDashboard: false,
        enableCORS: true//for canvas img
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi im working in this problem, in my situation the map work perfect, for configure the proxy just add this line in the html2canvas script:

        function makeScreenshot()
        {
            html2canvas(document.getElementById("bingMap"), {
                proxy:'',
                type: 'view',
                logging: true,
                userCORS: true,
                ignoreElements:(showDashboard)=>{return false},
                Timeout:(5000)
            })
            .then(canvas =>
            {
                canvas.id = "canvasID";
                var main = document.getElementById("main");
                //while (main.firstChild) { main.removeChild(main.firstChild); }
                setTimeout(function(){main.appendChild(canvas);},5000);
            });
        }

        document.getElementById("a-make").addEventListener('click', function()
        {
            document.getElementById("a-make").style.display = "none";
            makeScreenshot();
            document.getElementById("a-download").style.display = "inline";
        }, false);

        document.getElementById("a-download").addEventListener('click', function()
        {
            this.href = document.getElementById("canvasID").toDataURL();
            this.download = "canvas-map.png";
        }, false);

the "proxy" can be in blank, or read this(html2canvas php proxy), in the script of bing maps u need enable CORS:

    var loc = new Microsoft.Maps.Location(urlatmap, urlngmap)
    mapOptions = {
        credentials: bingkey,
        center: loc,
        zoom: 16,
        mapTypeId: Microsoft.Maps.MapTypeId.aerial,
        showDashboard: false,
        enableCORS: true//for canvas img
    }


问:
How to insert arbitrary JSON response to mongodb collection in Laravel?
I have described the model in the following way:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    protected $collection = 'feeds';
    protected $connection = 'mongodb';
    protected $appends = ['id'];
    protected $hidden = ['_id'];
    protected $fillable = ['feed_content'];
    public $timestamps = true;
}
</code>```

I want to save the content of the API response in database logs:

```<code>    $feed_info = $driver->getAdvertiserFeed();
    $feed_id = new Feed;
    $feed_id->feed_content = $feed_info;
    $feed_id->save();
</code>```

The connection to MongoDB is configured in this way:

```<code>    'mongodb' => [
        'driver' => 'mongodb',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE', 'feeds'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'test'),
        'options' => [
            'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
        ],
    ],
</code>```

But when I try to execute the second piece of code, I get this error:

```<code>Symfony\Component\Debug\Exception\FatalThrowableError:
Argument 1 passed to Illuminate\Database\Grammar::parameterize()
must be of the type array, string given, called in
/home/pavel/Projects/axonite/vendor/laravel/framework/
  src/Illuminate/Database/Query/Grammars/Grammar.php on line 853

at /home/pavel/Projects/axonite/vendor/laravel/framework/src/Illuminate/Database/Grammar.php:138
    134|      *
    135|      * @param  array   $values
    136|      * @return string
    137|      */
  > 138|     public function parameterize(array $values)
    139|     {
    140|         return implode(', ', array_map([$this, 'parameter'], $values));
    141|     }
    142|
</code>```

What exactly do I do wrong? How to fill JSON in a collection in a more correct manner with getting a document id back? I want to save it in the relational database for retrieving it later. Thanks!

答:
The answer is that MongoDB configuration was trying to get credentials for Mongo auth from MySQL settings in .env file:

```<code>'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'feeds'),
    'username' => env('DB_USERNAME', 'user'),
    'password' => env('DB_PASSWORD', 'test'),
    'options' => [
        'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
    ],
],
</code>```

Replacing it with static values has solved the problem:

```<code>'mongodb' => [
    'driver' => 'mongodb',
    'host' => '127.0.0.1',
    'port' =>  27017,
    'database' =>  'feeds',
    'username' => 'user',
    'password' => 'test',
    'options' => [
        'database' => env('DB_AUTHENTICATION_DATABASE', 'axonite'),
    ],
],
</code>```

Body:
I have described the model in the following way:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    protected $collection = 'feeds';
    protected $connection = 'mongodb';
    protected $appends = ['id'];
    protected $hidden = ['_id'];
    protected $fillable = ['feed_content'];
    public $timestamps = true;
}

I want to save the content of the API response in database logs:

    $feed_info = $driver->getAdvertiserFeed();
    $feed_id = new Feed;
    $feed_id->feed_content = $feed_info;
    $feed_id->save();

The connection to MongoDB is configured in this way:

    'mongodb' => [
        'driver' => 'mongodb',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE', 'feeds'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'test'),
        'options' => [
            'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
        ],
    ],

But when I try to execute the second piece of code, I get this error:

Symfony\Component\Debug\Exception\FatalThrowableError:
Argument 1 passed to Illuminate\Database\Grammar::parameterize()
must be of the type array, string given, called in
/home/pavel/Projects/axonite/vendor/laravel/framework/
  src/Illuminate/Database/Query/Grammars/Grammar.php on line 853

at /home/pavel/Projects/axonite/vendor/laravel/framework/src/Illuminate/Database/Grammar.php:138
    134|      *
    135|      * @param  array   $values
    136|      * @return string
    137|      */
  > 138|     public function parameterize(array $values)
    139|     {
    140|         return implode(', ', array_map([$this, 'parameter'], $values));
    141|     }
    142|

What exactly do I do wrong? How to fill JSON in a collection in a more correct manner with getting a document id back? I want to save it in the relational database for retrieving it later. Thanks!

Body:
The answer is that MongoDB configuration was trying to get credentials for Mongo auth from MySQL settings in .env file:

'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'feeds'),
    'username' => env('DB_USERNAME', 'user'),
    'password' => env('DB_PASSWORD', 'test'),
    'options' => [
        'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
    ],
],

Replacing it with static values has solved the problem:

'mongodb' => [
    'driver' => 'mongodb',
    'host' => '127.0.0.1',
    'port' =>  27017,
    'database' =>  'feeds',
    'username' => 'user',
    'password' => 'test',
    'options' => [
        'database' => env('DB_AUTHENTICATION_DATABASE', 'axonite'),
    ],
],


问:
managing parent frame from child frame on java swing
I have a jframe (parent) which creates an input frame (child) where I get some parameter.

In the "child" frame I have "ok" and "cancel" buttons.

When "ok" button is pressed, the parent frame needs to be updated with new data.

What is the best way to do that??

答:
As of Java 1.3</p>

```<code>public class MyPanel extends JPanel
{

  public MyPanel() {

    ....

    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // <<<< HERE'S THE INTERESTING BIT >>>>
          javax.swing.SwingUtilities.getWindowAncestor(MyPanel.this).dispose();
        }
      }
    );
    add(cancelButton);

    .....

  }

}
</code>```

OwnerDisplayName: GIANCARLO

ContentLicense: CC BY-SA 2.5

Body:
As of Java 1.3

public class MyPanel extends JPanel
{

  public MyPanel() {

    ....

    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // <<<< HERE'S THE INTERESTING BIT >>>>
          javax.swing.SwingUtilities.getWindowAncestor(MyPanel.this).dispose();
        }
      }
    );
    add(cancelButton);

    .....

  }

}


问:
Open the View over the other not as a subView?
I want to overlap view over the another view. I don't want to add it as a subView. The new view should be added with following rect size (280,400) on the super view of size (320,460).

Can any one suggest me the right way for doing this.

Thanks in advance

答:
Im not completely sure what you mean, but i will try...

Overlapping == Changing "z-index"

You can use the following to bring your view above the other views it shares its hierarchy with.

```<code>[yourview.superview bringSubviewToFront:yourview];
</code>```

Overlapping == adding to the superview

Then this should do the trick.

```<code>UIView *yourview = ???
yourview.frame = CGRectMake(?,?,280,400);
[self.view.superview addSubview:yourview];
</code>```

Any UIView or variation thereof can respond to the .superview. Its a global "where the heck am I ?"

If you want to go all the way to the uppermost layer, there is also :

```<code>[self.view.screen addSubview:yourview];
</code>```

You can't get much higher than that ;]

Body:
Im not completely sure what you mean, but i will try...

Overlapping == Changing "z-index"

You can use the following to bring your view above the other views it shares its hierarchy with.

[yourview.superview bringSubviewToFront:yourview];

Overlapping == adding to the superview

Then this should do the trick.

UIView *yourview = ???
yourview.frame = CGRectMake(?,?,280,400);
[self.view.superview addSubview:yourview];

Any UIView or variation thereof can respond to the .superview. Its a global "where the heck am I ?"

If you want to go all the way to the uppermost layer, there is also :

[self.view.screen addSubview:yourview];

You can't get much higher than that ;]


问:
How can I see the details of the "ASP.NET HTTP Modules" in a Stackify trace?

We use Stackify to monitor our SAAS application.
In a typical trace of a slow request we see that over 90% of the time is spent in "ASP.NET HTTP Modules".
It is nice to know, but we really do not know if there is a problem with the application, and if so what to do about it.

Is there a way or tool to drill in into the modules details using Stackify or some other tool?

答:
Here is the answer I received from Stackify support:

Jun 1, 2020, 12:25:11 AM CDT

Hi Dror,

Thank you for reaching out to Stackify Support! Unfortunately, we won't be able identify the root cause for this delay - we just are able to show that something/somewhere along the pipeline is taking so much time (e.g. loading a module, or the module itself). This could be due to performance issues with a specific HTTP module. For example, something like a session provider querying SQL that is slow or causing bottlenecks.

Our engineering team suggests that if this issue persists, you can try enabling Failed Request Tracing on the server in IIS. That enables pretty detailed tracing from the IIS pipeline steps that could help further troubleshoot the issue.

Sorry if this isn't the most ideal answer. Let us know if you have other questions!

Best Regards,

Mark Quevedo | Developer Support Engineer


问:
filebeat is not creating index with my name
I am using filebeat to send my application logs to Elasticsearch and directly connecting to my Elasticsearch for sending the logs.

My file beat configuration

```<code>filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
  - type: log
    paths:
      - "/var/log/*.log"
setup.ilm.enabled: false
setup.template.overwrite: true
output.elasticsearch:
  hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}
</code>```

Please note that in output.elasticsearch.index: I am giving myapp as prefix to my index name in Elasticsearch but filebeat is creating index with filebeat-7.7.0-2020.05.31 name ie using its own name filebeat as prefix which I don't want as I am having multiple applications and want to create a separate index for them.

答:
you need to set setup.template.name
and setup.template.pattern
as mentioned in the error message. Please add below extra lines in your filebeat.yml.

```<code>setup.template:
  name: 'myapp'
  pattern: 'myapp-*'
  enabled: false
</code>```

Now your complete filebeat.yml
should look like

filebeat.config:
modules:
path: $ {
path.config
}
/modules.d/ * .yml
reload.enabled: false

```<code>  filebeat.inputs:
    -type: log
  paths:
    -"/var/log/*.log"
  setup.ilm.enabled: false
  setup.template.overwrite: true
  output.elasticsearch:
    hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}

  setup.template:
    name: 'myapp'
    pattern: 'myapp-*'
    enabled: false
</code>```

Body:
I am using filebeat to send my application logs to Elasticsearch and directly connecting to my Elasticsearch for sending the logs.

My file beat configuration

filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
  - type: log
    paths:
      - "/var/log/*.log"
setup.ilm.enabled: false
setup.template.overwrite: true
output.elasticsearch:
  hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}

Please note that in output.elasticsearch.index: I am giving myapp as prefix to my index name in Elasticsearch but filebeat is creating index with filebeat-7.7.0-2020.05.31 name ie using its own name filebeat as prefix which I don't want as I am having multiple applications and want to create a separate index for them.

Body:
you need to set setup.template.name
and setup.template.pattern
as mentioned in the error message. Please add below extra lines in your filebeat.yml.

setup.template:
  name: 'myapp'
  pattern: 'myapp-*'
  enabled: false

Now your complete filebeat.yml
should look like

filebeat.config:
modules:
path: $ {
path.config
}
/modules.d/ * .yml
reload.enabled: false

  filebeat.inputs:
    -type: log
  paths:
    -"/var/log/*.log"
  setup.ilm.enabled: false
  setup.template.overwrite: true
  output.elasticsearch:
    hosts: ["aws-es:443"]
  output.elasticsearch.index: "myapp-%{[agent.version]}-%{+yyyy.MM.dd}"
  username: '${ELASTICSEARCH_USERNAME:}'
  password: '${ELASTICSEARCH_PASSWORD:}

  setup.template:
    name: 'myapp'
    pattern: 'myapp-*'
    enabled: false


问:
How to solve this error "setState() or markNeedsBuild() called during build."?
So I have a table in moor which is returning a Future<List<..>> with that data I am trying to make pie chart

```<code>
class Stats extends StatefulWidget {

  @override
  _StatsState createState() => _StatsState();
}

class _StatsState extends State<Stats> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildTaskList(context)

      ],
    );
  }
}

FutureBuilder<List<Account>> _buildTaskList(BuildContext context) {

  Map<String, double> dataMap = Map();
  dataMap.putIfAbsent("SNACKS", () => Provider.of<Amount>(context,listen: false).snack_amount);
  dataMap.putIfAbsent("ENTERTAINMENT", () => Provider.of<Amount>(context,listen: false).entertainment_amount);
  dataMap.putIfAbsent("STATIONARY", () => Provider.of<Amount>(context,listen: false).stationary_amount);
  dataMap.putIfAbsent("OTHERS", () => Provider.of<Amount>(context,listen: false).others_amount);

  final dao = Provider.of<AccountDao>(context);
  return FutureBuilder(
    future: dao.getAllAccounts(),
    builder: (context, AsyncSnapshot<List<Account>> snapshot) {
      final accounts = snapshot.data ?? List();

      Provider.of<Amount>(context,listen: false).add(Calculate(accounts, Type.SNACKS), Calculate(accounts, Type.ENTERTAINMENT),
          Calculate(accounts, Type.STATIONARY), Calculate(accounts, Type.OTHERS));

      if (accounts == null) {
        return Text('No Accounts Yet');
      } else {
        return  PieChart(
          dataMap: dataMap,
        );
      }
    },
  );
}

double Calculate(List<Account> list, Type type){

  double sum=0;
  for(int i=0;i<list.length;i++){
    if(list[i].type==type){
      sum=sum+list[i].amount;
    }
  }

  return sum;
}

</code>```

Now everytime  I am running this I am getting an error

**The following assertion was thrown while dispatching notifications for Amount:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope
  value: Instance of 'Amount'
  listening to value
The widget which was currently being built when the offending call was made was: FutureBuilder>
  dirty
  state: _FutureBuilderState>#37282
When the exception was thrown, this was the stack:

0      Element.markNeedsBuild. (package:flutter/src/widgets/framework.dart:4167:11)

1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4182:6)

2      _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:426:5)

3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:207:21)

4      Amount.add (package:moneymanager/main.dart:55:5)

...
The Amount sending notification was: Instance of 'Amount'

**

This is the Amount Class

```<code>class Amount extends ChangeNotifier {

  double snack_amount=0.0;
  double entertainment_amount=0.0;
  double stationary_amount=0.0;
  double  others_amount=0.0;

  void add(double snack,double entertainment,double stationary, double others){
    snack_amount=snack;
    entertainment_amount=entertainment;
    stationary_amount=stationary;
    others_amount=others;
    notifyListeners();
  }
}

</code>```

The function to get the Future<List<..>>

```Future> getAllAccounts()=>select(accounts).get();``</p>

<p><strong>EDIT</strong>
I edited my answer as suggested</p>

```return FutureBuilder(
    future: dao.getAllAccounts(),
    builder: (context, AsyncSnapshot<List<Account>> snapshot) {

      if(snapshot.connectionState==ConnectionState.done){

        final accounts = snapshot.data ?? List();

        if (accounts == null) {

          return Text('No Accounts Yet');
        } else {
          Provider.of<Amount>(context,listen: false).add(Calculate(accounts, Type.SNACKS), Calculate(accounts, Type.ENTERTAINMENT),
              Calculate(accounts, Type.STATIONARY), Calculate(accounts, Type.OTHERS));

          dataMap.putIfAbsent("SNACKS", () => Provider.of<Amount>(context,listen: false).snack_amount);
          dataMap.putIfAbsent("ENTERTAINMENT", () => Provider.of<Amount>(context,listen: false).entertainment_amount);
          dataMap.putIfAbsent("STATIONARY", () => Provider.of<Amount>(context,listen: false).stationary_amount);
          dataMap.putIfAbsent("OTHERS", () => Provider.of<Amount>(context,listen: false).others_amount);

          return  PieChart(
            dataMap: dataMap,
          );
        }

      }else if(snapshot.connectionState==ConnectionState.waiting){

        return Container();
      }else{
        return Container();
      }

    },

```

but still the same error

答:
The following assertion was thrown while dispatching notifications for Amount: setState() or markNeedsBuild() called during build.

This error means that you are calling setState during the build phase

And from you logs it explicitly states

A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase

you can implement ConnectionState.waiting  ConnectionState.done

Body:
So I have a table in moor which is returning a Future<List<..>> with that data I am trying to make pie chart

class Stats extends StatefulWidget {

  @override
  _StatsState createState() => _StatsState();
}

class _StatsState extends State<Stats> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildTaskList(context)

      ],
    );
  }
}

FutureBuilder<List<Account>> _buildTaskList(BuildContext context) {

  Map<String, double> dataMap = Map();
  dataMap.putIfAbsent("SNACKS", () => Provider.of<Amount>(context,listen: false).snack_amount);
  dataMap.putIfAbsent("ENTERTAINMENT", () => Provider.of<Amount>(context,listen: false).entertainment_amount);
  dataMap.putIfAbsent("STATIONARY", () => Provider.of<Amount>(context,listen: false).stationary_amount);
  dataMap.putIfAbsent("OTHERS", () => Provider.of<Amount>(context,listen: false).others_amount);

  final dao = Provider.of<AccountDao>(context);
  return FutureBuilder(
    future: dao.getAllAccounts(),
    builder: (context, AsyncSnapshot<List<Account>> snapshot) {
      final accounts = snapshot.data ?? List();

      Provider.of<Amount>(context,listen: false).add(Calculate(accounts, Type.SNACKS), Calculate(accounts, Type.ENTERTAINMENT),
          Calculate(accounts, Type.STATIONARY), Calculate(accounts, Type.OTHERS));

      if (accounts == null) {
        return Text('No Accounts Yet');
      } else {
        return  PieChart(
          dataMap: dataMap,
        );
      }
    },
  );
}

double Calculate(List<Account> list, Type type){

  double sum=0;
  for(int i=0;i<list.length;i++){
    if(list[i].type==type){
      sum=sum+list[i].amount;
    }
  }

  return sum;
}

Now everytime  I am running this I am getting an error

**The following assertion was thrown while dispatching notifications for Amount:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope
  value: Instance of 'Amount'
  listening to value
The widget which was currently being built when the offending call was made was: FutureBuilder>
  dirty
  state: _FutureBuilderState>#37282
When the exception was thrown, this was the stack:

0      Element.markNeedsBuild. (package:flutter/src/widgets/framework.dart:4167:11)

1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4182:6)

2      _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:426:5)

3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:207:21)

4      Amount.add (package:moneymanager/main.dart:55:5)

...
The Amount sending notification was: Instance of 'Amount'

**

This is the Amount Class

class Amount extends ChangeNotifier {

  double snack_amount=0.0;
  double entertainment_amount=0.0;
  double stationary_amount=0.0;
  double  others_amount=0.0;

  void add(double snack,double entertainment,double stationary, double others){
    snack_amount=snack;
    entertainment_amount=entertainment;
    stationary_amount=stationary;
    others_amount=others;
    notifyListeners();
  }
}

The function to get the Future<List<..>>

```Future> getAllAccounts()=>select(accounts).get();``

EDIT
I edited my answer as suggested

return FutureBuilder(
    future: dao.getAllAccounts(),
    builder: (context, AsyncSnapshot<List<Account>> snapshot) {

      if(snapshot.connectionState==ConnectionState.done){

        final accounts = snapshot.data ?? List();

        if (accounts == null) {

          return Text('No Accounts Yet');
        } else {
          Provider.of<Amount>(context,listen: false).add(Calculate(accounts, Type.SNACKS), Calculate(accounts, Type.ENTERTAINMENT),
              Calculate(accounts, Type.STATIONARY), Calculate(accounts, Type.OTHERS));

          dataMap.putIfAbsent("SNACKS", () => Provider.of<Amount>(context,listen: false).snack_amount);
          dataMap.putIfAbsent("ENTERTAINMENT", () => Provider.of<Amount>(context,listen: false).entertainment_amount);
          dataMap.putIfAbsent("STATIONARY", () => Provider.of<Amount>(context,listen: false).stationary_amount);
          dataMap.putIfAbsent("OTHERS", () => Provider.of<Amount>(context,listen: false).others_amount);

          return  PieChart(
            dataMap: dataMap,
          );
        }

      }else if(snapshot.connectionState==ConnectionState.waiting){

        return Container();
      }else{
        return Container();
      }

    },

but still the same error


问:
Program to print all the bits of one byte union without using bitwise operators
I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:</p>

```<code>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%hhu", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
    return 0;
}

</code>```

```<code>#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;

union bit {
    unsigned int i : 1;
}foo;
union bit_set
{
    union bit a[8];
    byte x;
}word;

#endif

</code>```

答:
Maybe the point of this task is to use arithmetic operations instead of the bitwise ones?
Here is an example:

```<code>void printByteBits(unsigned char num)
{
    const static int div[8] = {1, 2, 4, 8, 16, 32, 64, 128};

    for (int i = 0; i < sizeof(div)/sizeof(div[0]); i++)
    {
        printf("Bit %d: %d\n", i, (num / div[i]) % 2);
    }
}
</code>```

See the output here: https://godbolt.org/z/xUC663

Body:
I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%hhu", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
    return 0;
}

#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;

union bit {
    unsigned int i : 1;
}foo;
union bit_set
{
    union bit a[8];
    byte x;
}word;

#endif

Body:
Maybe the point of this task is to use arithmetic operations instead of the bitwise ones?
Here is an example:

void printByteBits(unsigned char num)
{
    const static int div[8] = {1, 2, 4, 8, 16, 32, 64, 128};

    for (int i = 0; i < sizeof(div)/sizeof(div[0]); i++)
    {
        printf("Bit %d: %d\n", i, (num / div[i]) % 2);
    }
}

See the output here: https://godbolt.org/z/xUC663


问:
Does declaring a vector with size offer any improvements over using push_back in C++
Let us say we know the size of a vector we will be needing, (say 'n').

Does using vector<int> Array(n); offer any improvements over using Array.push_back(element) one by one?

Which is recommended and why?

答:
The optiumum choice for efficiency is to reserve the required number of elements before using push_back or emplace_back. This guarantees that no reallocations will occur. It's also somewhat more flexible.

The alternative of creating the vector at the required size requires you to construct all the elements of the vector ahead of time and then assign to the already constructed objects.


问:
Better way of writing a long and simple if statement?
I am writing some custom values for a variable.
Is there a better way of writing this?</p>

```<code>if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20
</code>```

答:
Just write a loop, and increment by 5 if less than 5, and 4 if greater than 5. Then add the values to a dictionary.

```<code>counter = -20

result = {}
for number in range(1, 11):
    result[number] = counter

    if number < 5:
        counter += 5
    else:
        counter += 4

print(result)
</code>```

Output:

```<code>{1: -20, 2: -15, 3: -10, 4: -5, 5: 0, 6: 4, 7: 8, 8: 12, 9: 16, 10: 20}
</code>```

Then if you want to get the values from the dictionary, you can do result[key] as shown in the other answers.

Body:
I am writing some custom values for a variable.
Is there a better way of writing this?

if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20

Body:
Just write a loop, and increment by 5 if less than 5, and 4 if greater than 5. Then add the values to a dictionary.

counter = -20

result = {}
for number in range(1, 11):
    result[number] = counter

    if number < 5:
        counter += 5
    else:
        counter += 4

print(result)

Output:

{1: -20, 2: -15, 3: -10, 4: -5, 5: 0, 6: 4, 7: 8, 8: 12, 9: 16, 10: 20}

Then if you want to get the values from the dictionary, you can do result[key] as shown in the other answers.


问:
sort array of objects with more than one criteria
Lets say that I have an array of objects:

```<code>let updatedEvents = [
{
 "code": "3894",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "1976",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0482",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0408",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
];
</code>```

If I want to sort them by event date and if event date is the same in any event then sort them by code in ascending order then the following would be correct? :

```<code>const sortedEventsByDateUniqueCode = updatedEvents.sort((eventOne, eventTwo) => {
 if (eventOne.date === eventTwo.date) {
  return -1;
 }
 if (eventOne.code > eventTwo.code) return 1;
 if (eventOne.code < eventTwo.code) return -1;
});
</code>```

Body:
Lets say that I have an array of objects:

let updatedEvents = [
{
 "code": "3894",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "1976",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0482",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0408",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
];

If I want to sort them by event date and if event date is the same in any event then sort them by code in ascending order then the following would be correct? :

const sortedEventsByDateUniqueCode = updatedEvents.sort((eventOne, eventTwo) => {
 if (eventOne.date === eventTwo.date) {
  return -1;
 }
 if (eventOne.code > eventTwo.code) return 1;
 if (eventOne.code < eventTwo.code) return -1;
});

Body:
You can put an or condition in sort:

var updatedEvents = [{ "code": "3894", "date": "2020-06-01T20:00:00+0300", "timestamp": 1591030800},{ "code": "1976", "date": "2020-06-01T20:00:00+0300", "timestamp": 1591030800},{ "code": "0482", "date": "2020-06-01T20:00:00+0300", "timestamp": 1591030800},{ "code": "0408", "date": "2020-06-01T20:00:00+0300", "timestamp": 1591030800},{ "code": "0482", "date": "2020-06-02T20:00:00+0300", "timestamp": 1591030800},{ "code": "03", "date": "2020-06-02T20:00:00+0300", "timestamp": 1591030800}];

var result = updatedEvents.sort((a,b)=>{
  return (new Date(a.date)- new Date(b.date)) || (a.code - b.code)
});

console.log(result);


问:
Java heap space error while creating ArrayList of large number of objects?
I have created an ArrayList (Java) of my custom class objects with a size around 3000.
But when I run my code it gets the error "Heap space error".

I want to keep thousands of objects in an ArrayList at runtime without getting out of heap space.

How can the heap space error be avoided?

答:
Increase the Java heap size with the <code>-Xmx</code> Java system property. For example, give it as </p>

```<code>java -Xmx1024m Main
</code>```

Body:
Increase the Java heap size with the -Xmx Java system property. For example, give it as

java -Xmx1024m Main


问:
How to restrict a command to a role in another server | Discord JS
I'm trying to make it so that a user needs a role in another server to use a specific command.

I know how to restrict a command to a role in the server the command was used in but no idea how to make it out of server.

Could I get some help or at-least a step in the right direction

答:
You can fetch the server the role they need is in and check if the user has it there. Keep in mind that the client needs to be in both servers.

```<code>// Guild the user needs to have the role in
let guildA = client.guilds.cache.get("GUILD ID");

// Role that the user needs
let requiredRole = guildA.roles.cache.get("ROLE ID");

// Member object of the user in guildA
let member = guildA.members.cache.get(message.author.id);

// Check if they have the role
if (member.roles.cache.has(requiredRole.id)) {
    message.channel.send("You have the required role.");
} else {
    message.channel.send("You do not have the required role");
};
</code>```

'ROLE ID' and 'GUILD ID' are the ID's of the role the user needs, and the server the role is in.

EDIT: This code is for discord.js v12. Anything lower and you have to remove all instances of 'cache', e.g guildA.members.cache.get -> guildA.members.get

Body:
You can fetch the server the role they need is in and check if the user has it there. Keep in mind that the client needs to be in both servers.

// Guild the user needs to have the role in
let guildA = client.guilds.cache.get("GUILD ID");

// Role that the user needs
let requiredRole = guildA.roles.cache.get("ROLE ID");

// Member object of the user in guildA
let member = guildA.members.cache.get(message.author.id);

// Check if they have the role
if (member.roles.cache.has(requiredRole.id)) {
    message.channel.send("You have the required role.");
} else {
    message.channel.send("You do not have the required role");
};

'ROLE ID' and 'GUILD ID' are the ID's of the role the user needs, and the server the role is in.

EDIT: This code is for discord.js v12. Anything lower and you have to remove all instances of 'cache', e.g guildA.members.cache.get -> guildA.members.get


问:
forRevisionsOfEntity is slow
I'm doing a query for all revisions of a class that are greater than a timestamp using:

```<code>AuditReaderFactory
    .get(emf.createEntityManager())
    .createQuery().forRevisionsOfEntity(clazz, false, true)
    .add(AuditEntity.revisionProperty("timestamp").gt(existingIndex.lastModified()))
    .getResultList();
</code>```

This is recreating a @ManyToOne referenced object using the query:

```<code>select <audit cols for this type>
from <audit table>
where DTYPE IN (<class type>)
and REV=(
   SELECT max(REV)
   FROM <audit table>
   where TYPE IN (<class type>)
   and REV <= <maximum revision in revision entity table>
   and <subquery>.id=<query>.id
)
and REVTYPE<>2
AND <audit table>.id=<id of entity being restored>
</code>```

This query is incredibly slow and takes well over 100 minutes just for one entity (in fact, as I'm writing this it's still going). Why is it getting the last revision of the entity (minus DEL revisions)? It's much faster to use a ORDER BY REV LIMIT 1 (or similar for databases that don't have LIMIT). I'm almost wanting to just go straight SQL since this is way too slow. It could also be sped up by using the id straight inside the subquery instead of references the query's table id. I have indexes on DTYPE, REV and REVTYPE, and a unique key on id, REV so it isn't an indexing issue.

I'm not sure why it's using the above query to recreate the referenced object and would appreciate any insight. This is on a MySQL 5.1 database on a Pentium 4 machine, but also takes considerable time on a dual core machine too.

答:
The performance have been dramatically improved in 3.6.0 version of hibernate. What you should  do is using ValidityAuditStrategy. Add this to your persistence.xml:

```<code>    <property name="org.hibernate.envers.audit_strategy"
              value="org.hibernate.envers.strategy.ValidityAuditStrategy"/>
</code>```

This will add REVEND column to your audited table so no inner selects are required. Read more here.

Title: forRevisionsOfEntity is slow

Body:
I'm doing a query for all revisions of a class that are greater than a timestamp using:

AuditReaderFactory
    .get(emf.createEntityManager())
    .createQuery().forRevisionsOfEntity(clazz, false, true)
    .add(AuditEntity.revisionProperty("timestamp").gt(existingIndex.lastModified()))
    .getResultList();

This is recreating a @ManyToOne referenced object using the query:

select <audit cols for this type>
from <audit table>
where DTYPE IN (<class type>)
and REV=(
   SELECT max(REV)
   FROM <audit table>
   where TYPE IN (<class type>)
   and REV <= <maximum revision in revision entity table>
   and <subquery>.id=<query>.id
)
and REVTYPE<>2
AND <audit table>.id=<id of entity being restored>

This query is incredibly slow and takes well over 100 minutes just for one entity (in fact, as I'm writing this it's still going). Why is it getting the last revision of the entity (minus DEL revisions)? It's much faster to use a ORDER BY REV LIMIT 1 (or similar for databases that don't have LIMIT). I'm almost wanting to just go straight SQL since this is way too slow. It could also be sped up by using the id straight inside the subquery instead of references the query's table id. I have indexes on DTYPE, REV and REVTYPE, and a unique key on id, REV so it isn't an indexing issue.

I'm not sure why it's using the above query to recreate the referenced object and would appreciate any insight. This is on a MySQL 5.1 database on a Pentium 4 machine, but also takes considerable time on a dual core machine too.

Body:
The performance have been dramatically improved in 3.6.0 version of hibernate. What you should  do is using ValidityAuditStrategy. Add this to your persistence.xml:

    <property name="org.hibernate.envers.audit_strategy"
              value="org.hibernate.envers.strategy.ValidityAuditStrategy"/>

This will add REVEND column to your audited table so no inner selects are required. Read more here.


问:
How to update NavBar component in React upon successful log-in and before logging in
I am trying to modify the Navbar contents before and after logging in so that before logging in, it shows Login and Register and after logging in, it shows other tabs apart from those two.
I have an Auth.js with a function called isAuthenticated() which returns true if the user is logged in or false otherwise. Initially, isAuthenticated() returns false, so the Navbar shows register and login. However, once the user logs in, isAuthenticated() becomes true but that is not reflected in Navbar. How can I change that to ensure that it shows different things upon login/logout.

PS - I havent completed navigation but I can conditionally render it to show different things if isLoggedin is true or false.

App.js

```<code>import ProtectedRoute from './protectedroute'
import Auth from './Auth'

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
     const isAuthenticated = Auth.isAuthenticated()
     console.log(isAuthenticated)
  return (
      <Router>
        <div>
          <NavigationBar isLoggedin={isAuthenticated}/>
          <Switch>
            <Route exact path = '/'
              component = {LandingPage}
            />
            <Route exact path = '/register'
              component = {Register}
            />
            <ProtectedRoute exact path = '/Success'
              component = {Success}
            />
            <Route path="*" component = {() => "404 NOT FOUND"}/>
          </Switch>
        </div>
      </Router>
  );
}
}

export default App;
</code>```

Auth.js

```<code>class Auth {
    constructor() {
        this.authenticated = false;
    }

    login() {
        this.authenticated = true;
    }

    logout() {
        this.authenticated = false;
    }

    isAuthenticated() {
        return this.authenticated;
    }
}

export default new Auth();
</code>```

NavigationBar.js

```<code>import React from 'react'
import { Button, Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import { Link } from 'react-router-dom'

class NavigationBar extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const isLoggedin = this.props.isLoggedin
    console.log(isLoggedin)
    return (
      <Navbar expand="lg">
        <Navbar.Brand >hello</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="ml-auto">
            <Nav.Link><Link to='/'>Login</Link></Nav.Link>
            <Nav.Link><Link to='/register'>Register</Link></Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Navbar>
    )
  }
}

export default NavigationBar
</code>```

答:
First, you will need to render your navbar based on your session. i.e. If there is a change in a session like a user is logged in or logged out, the navbar needs to render.

For simplicity, to accomplish the above task, we will keep the isAuthenticated as an App state property and will pass the isAuthenticated as a prop of NavigationBar. Now any change of isAuthenticated will result in a render of the NavigationBar component.

Code example, in App.js:

```<code>constructor(props) {
  super(props);
  this.state = { isAuthenticated: false };
}

render() {
  const { isAuthenticated } = this.state;
  .
  .
  .
</code>```

instead

```<code>const isAuthenticated = Auth.isAuthenticated()
</code>```

Now, since we removed the Auth.js file and we do require methods like login and logout, we will add such methods in the App component.

Example:

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
  }

  login = () => {
    this.setState({ isAuthenticated: true });
  }

  logout = () => {
    this.setState({ isAuthenticated: false });
  }

  render() { ...
</code>```

And we will need to call these methods depending on the user's activity. Like if a user signs in successfully, we will call the login method. Now, it is important to note that you need to pass these methods as props to child components who will call these. For example, your NavigationBar may need to call the logout and so you pass the method like

```<code><NavigationBar isLoggedin={isAuthenticated} logout={this.logout}/>
</code>```

Finally, now, based on isLoggedin in NavigationBar, you can render the conditional items.

For example, in NavigationBar.js file,

```<code><Nav className="ml-auto">
  {isLoggedin && (<Nav.Link><Link to='/logout'>Logout</Link></Nav.Link>)}
  {!isLoggedin && (<Nav.Link><Link to='/'>Login</Link></Nav.Link>)}
  {!isLoggedin && (<Nav.Link><Link to='/register'>Register</Link></Nav.Link>)}
</Nav>
</code>```

The above code will render login and register items if a user is not signed in and vice versa.

Now, all through the walkthrough, we start and maintain the user session in the react component state only. This is not ideal since whenever a user refreshes the page, the session will be lost. To mitigate the issue, you will need to use local storage or any other approach that you may find suitable.

Body:
I am trying to modify the Navbar contents before and after logging in so that before logging in, it shows Login and Register and after logging in, it shows other tabs apart from those two.
I have an Auth.js with a function called isAuthenticated() which returns true if the user is logged in or false otherwise. Initially, isAuthenticated() returns false, so the Navbar shows register and login. However, once the user logs in, isAuthenticated() becomes true but that is not reflected in Navbar. How can I change that to ensure that it shows different things upon login/logout.

PS - I havent completed navigation but I can conditionally render it to show different things if isLoggedin is true or false.

App.js

import ProtectedRoute from './protectedroute'
import Auth from './Auth'

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
     const isAuthenticated = Auth.isAuthenticated()
     console.log(isAuthenticated)
  return (
      <Router>

          <NavigationBar isLoggedin={isAuthenticated}/>
          <Switch>
            <Route exact path = '/'
              component = {LandingPage}
            />
            <Route exact path = '/register'
              component = {Register}
            />
            <ProtectedRoute exact path = '/Success'
              component = {Success}
            />
            <Route path="*" component = {() => "404 NOT FOUND"}/>
          </Switch>

      </Router>
  );
}
}

export default App;

Auth.js

class Auth {
    constructor() {
        this.authenticated = false;
    }

    login() {
        this.authenticated = true;
    }

    logout() {
        this.authenticated = false;
    }

    isAuthenticated() {
        return this.authenticated;
    }
}

export default new Auth();

NavigationBar.js

import React from 'react'
import { Button, Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import { Link } from 'react-router-dom'

class NavigationBar extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const isLoggedin = this.props.isLoggedin
    console.log(isLoggedin)
    return (
      <Navbar expand="lg">
        <Navbar.Brand >hello</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">

            <Link to='/'>Login</Link>
            <Link to='/register'>Register</Link>

        </Navbar.Collapse>
      </Navbar>
    )
  }
}

export default NavigationBar

Body:
First, you will need to render your navbar based on your session. i.e. If there is a change in a session like a user is logged in or logged out, the navbar needs to render.

For simplicity, to accomplish the above task, we will keep the isAuthenticated as an App state property and will pass the isAuthenticated as a prop of NavigationBar. Now any change of isAuthenticated will result in a render of the NavigationBar component.

Code example, in App.js:

constructor(props) {
  super(props);
  this.state = { isAuthenticated: false };
}

render() {
  const { isAuthenticated } = this.state;
  .
  .
  .

instead

const isAuthenticated = Auth.isAuthenticated()

Now, since we removed the Auth.js file and we do require methods like login and logout, we will add such methods in the App component.

Example:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  login = () => {
    this.setState({ isAuthenticated: true });
  }

  logout = () => {
    this.setState({ isAuthenticated: false });
  }

  render() { ...

And we will need to call these methods depending on the user's activity. Like if a user signs in successfully, we will call the login method. Now, it is important to note that you need to pass these methods as props to child components who will call these. For example, your NavigationBar may need to call the logout and so you pass the method like

<NavigationBar isLoggedin={isAuthenticated} logout={this.logout}/>

Finally, now, based on isLoggedin in NavigationBar, you can render the conditional items.

For example, in NavigationBar.js file,

<Nav className="ml-auto">
  {isLoggedin && (<Nav.Link><Link to='/logout'>Logout</Link></Nav.Link>)}
  {!isLoggedin && (<Nav.Link><Link to='/'>Login</Link></Nav.Link>)}
  {!isLoggedin && (<Nav.Link><Link to='/register'>Register</Link></Nav.Link>)}
</Nav>

The above code will render login and register items if a user is not signed in and vice versa.

Now, all through the walkthrough, we start and maintain the user session in the react component state only. This is not ideal since whenever a user refreshes the page, the session will be lost. To mitigate the issue, you will need to use local storage or any other approach that you may find suitable.


问:
Notched corner rectangles in React Native
I've been trying to figure out a way to create notched/clipped corners in React Native all night.  It seems like something that would be super easy to do but it's apparently not.  I'm guessing SVG is maybe the right call.  Would love to control the corners independently.  How can I make this happen?

答:
Check the below example which enables you to control the corners independently. But for that, you have to wrap four different View inside your button.

```<code>import * as React from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";

export default function App() {
  return (
    <TouchableOpacity
      onPress={() => console.log("Button Clicked")}
      style={styles.buttonStyle}
    >
      <View style={styles.cutOffTopLeft} />
      <View style={styles.cutOffTopRight} />
      <View style={styles.cutOffBottomLeft} />
      <View style={styles.cutOffBottomRight} />
      <Text style={styles.textStyle}>START 30-DAY FREE TRIAL</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  buttonStyle: {
    backgroundColor: "red",
    alignItems: "center",
    justifyContent: "center",
    margin: 20,
  },
  textStyle: {
    color: "#FFFFFF",
    marginVertical: 13,
  },
  cutOffTopLeft: {
    position: "absolute",
    left: 0,
    top: 0,
    borderRightWidth: 10,
    borderTopWidth: 10,
    borderTopColor: "white",
    borderRightColor: "transparent",
  },
  cutOffTopRight: {
    position: "absolute",
    right: 0,
    top: 0,
    borderLeftWidth: 10,
    borderTopWidth: 10,
    borderTopColor: "white",
    borderLeftColor: "transparent",
  },
  cutOffBottomLeft: {
    position: "absolute",
    left: 0,
    bottom: 0,
    borderRightWidth: 10,
    borderBottomWidth: 10,
    borderBottomColor: "white",
    borderRightColor: "transparent",
  },
  cutOffBottomRight: {
    position: "absolute",
    right: 0,
    bottom: 0,
    borderLeftWidth: 10,
    borderBottomWidth: 10,
    borderBottomColor: "white",
    borderLeftColor: "transparent",
  },
});
</code>```

This may not be the optimal solution.

Hope this helps you. Feel free for doubts

Body:
Check the below example which enables you to control the corners independently. But for that, you have to wrap four different View inside your button.

import * as React from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";

export default function App() {
  return (
    <TouchableOpacity
      onPress={() => console.log("Button Clicked")}
      style={styles.buttonStyle}
    >
      <View style={styles.cutOffTopLeft} />
      <View style={styles.cutOffTopRight} />
      <View style={styles.cutOffBottomLeft} />
      <View style={styles.cutOffBottomRight} />
      <Text style={styles.textStyle}>START 30-DAY FREE TRIAL</Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  buttonStyle: {
    backgroundColor: "red",
    alignItems: "center",
    justifyContent: "center",
    margin: 20,
  },
  textStyle: {
    color: "#FFFFFF",
    marginVertical: 13,
  },
  cutOffTopLeft: {
    position: "absolute",
    left: 0,
    top: 0,
    borderRightWidth: 10,
    borderTopWidth: 10,
    borderTopColor: "white",
    borderRightColor: "transparent",
  },
  cutOffTopRight: {
    position: "absolute",
    right: 0,
    top: 0,
    borderLeftWidth: 10,
    borderTopWidth: 10,
    borderTopColor: "white",
    borderLeftColor: "transparent",
  },
  cutOffBottomLeft: {
    position: "absolute",
    left: 0,
    bottom: 0,
    borderRightWidth: 10,
    borderBottomWidth: 10,
    borderBottomColor: "white",
    borderRightColor: "transparent",
  },
  cutOffBottomRight: {
    position: "absolute",
    right: 0,
    bottom: 0,
    borderLeftWidth: 10,
    borderBottomWidth: 10,
    borderBottomColor: "white",
    borderLeftColor: "transparent",
  },
});

This may not be the optimal solution.

Hope this helps you. Feel free for doubts


问:
Spring Boot Redis store a list of POJOs as values
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

```<code>@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}
</code>```

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

```<code>1) "schools::ABC"
</code>```

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.

答:
Your Redis configuration seems fine but you didn't mention the type of your storing procedure. Maybe you have to use another way of storing your data. For example, you can try</p>

```<code>redisTemplate.opsForHash().put('yourKey','yourHashKey', objectValue);
</code>```

Body:
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

1) "schools::ABC"

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.

Body:
Your Redis configuration seems fine but you didn't mention the type of your storing procedure. Maybe you have to use another way of storing your data. For example, you can try

redisTemplate.opsForHash().put('yourKey','yourHashKey', objectValue);


问:
Unable to import image in Reactjs returning error Module not found: Can't resolve
I have the following component located in "projectfolder/src/pages/Home.js":-

```<code>import React from "react";
import MenuButton from "../components/Home/MenuButton";
import menuicon from "images/menuicon.png";

export default function Home() {
  return (
    <div className="container">
      <div className="row">
        <MenuButton title="home ">
          <img src={menuicon} />
        </MenuButton>
        <MenuButton title="account" />
        <MenuButton title="create new" />
      </div>
      <div className="row">
        <div className="col-md-12">
          <div className="signin-btns"></div>
        </div>
      </div>
    </div>
  );
}
</code>```

I am trying to import an image file "menu-icon.png" which is located in "projectfolder/public/images".

I tried to import it using the following imports :-

import menuicon from "images/menu-icon.png" returned the following error :-

./src/pages/Home.js Module not found: Can't resolve
  'images/menu-icon.png' in 'C:\Users\AHMAD\project\src\pages'

import menuicon from "/images/menu-icon.png";

./src/pages/Home.js Module not found: You attempted to import
  /images/menu-icon.png which falls outside of the project src/
  directory. Relative imports outside of src/ are not supported.

import menuicon from "../../images/menu-icon.png";

./src/pages/Home.js Module not found: You attempted to import
  ../../images/menu-icon.png which falls outside of the project src/
  directory. Relative imports outside of src/ are not supported.

I am using the ReactJS version : "^16.13.1" with "react-router-dom": "^5.1.2"

Body:
I have the following component located in "projectfolder/src/pages/Home.js":-

import React from "react";
import MenuButton from "../components/Home/MenuButton";
import menuicon from "images/menuicon.png";

export default function Home() {
  return (

        <MenuButton title="home ">

        </MenuButton>
        <MenuButton title="account" />
        <MenuButton title="create new" />

  );
}

I am trying to import an image file "menu-icon.png" which is located in "projectfolder/public/images".

I tried to import it using the following imports :-

import menuicon from "images/menu-icon.png" returned the following error :-

./src/pages/Home.js Module not found: Can't resolve
  'images/menu-icon.png' in 'C:\Users\AHMAD\project\src\pages'

import menuicon from "/images/menu-icon.png";

./src/pages/Home.js Module not found: You attempted to import
  /images/menu-icon.png which falls outside of the project src/
  directory. Relative imports outside of src/ are not supported.

import menuicon from "../../images/menu-icon.png";

./src/pages/Home.js Module not found: You attempted to import
  ../../images/menu-icon.png which falls outside of the project src/
  directory. Relative imports outside of src/ are not supported.

I am using the ReactJS version : "^16.13.1" with "react-router-dom": "^5.1.2"

Body:
By putting the image in projectfolder/public/images it is outside your src directory. You won't be able to import it that way. You could do either of the following to resolve this:

Move your image into projectfolder/src/images and import menuicon from './images/menu-icon.png'

Leave it in public and remove the import statement. Instead use it like this: <img src='images/menu-icon.png' />


问:
C# encrypt to Java Decrypt
I am using a C# "encrypt" and need a Java "decrypt" method. I need help in java that i can't replicate C# decryption on java and it is not explicit Padding on C# , i don't know what use in java and my key size I think is different but I am not sure. I'm very confused.

know that i need change Java Policy , and did it ! and Change Key size JAVA to 32 bytes.

C#

```<code>
    using System;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using Voa.Cross.Util.Extensions;

    namespace Voa.Core.Safeties
    {
        public class Security
        {
            private readonly string _defaultKey = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
            private readonly int _divisionKey = 4;
            private readonly byte[] _iv = new byte[16] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
            private byte[] _key;

            public Security() => _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(_defaultKey));

            public string Encrypt(string data, string key)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    CustomKey(key);
                }

                var encryptor = Aes.Create();

                encryptor.Mode = CipherMode.CBC;

                // Set key and IV
                var aesKey = new byte[32];
                Array.Copy(_key, 0, aesKey, 0, 32);
                encryptor.Key = aesKey;
                encryptor.IV = _iv;

                var memoryStream = new MemoryStream();

                var aesEncryptor = encryptor.CreateEncryptor();

                var cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

                var plainBytes = Encoding.ASCII.GetBytes(data);

                cryptoStream.Write(plainBytes, 0, plainBytes.Length);

                cryptoStream.FlushFinalBlock();

                var cipherBytes = memoryStream.ToArray();

                memoryStream.Close();
                cryptoStream.Close();

                var cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

                return cipherText;
            }

            public string Decrypt(string data, string key)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    CustomKey(key);
                }

                var encryptor = Aes.Create();

                encryptor.Mode = CipherMode.CBC;

                var aesKey = new byte[32];
                Array.Copy(_key, 0, aesKey, 0, 32);
                encryptor.Key = aesKey;
                encryptor.IV = _iv;

                var memoryStream = new MemoryStream();

                var aesDecryptor = encryptor.CreateDecryptor();

                var cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

                var plainText = string.Empty;

                try
                {
                    var cipherBytes = Convert.FromBase64String(data);

                    cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

                    cryptoStream.FlushFinalBlock();

                    var plainBytes = memoryStream.ToArray();

                    plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
                }
                finally
                {
                    memoryStream.Close();
                    cryptoStream.Close();
                }

                return plainText;
            }

            private void CustomKey(string key)
            {
                var blockSize = key.Length / _divisionKey;
                var splitKey = key.CutString(blockSize).ToList();
                var splitDefaultKey = _defaultKey.CutString(blockSize).ToList();
                var newKey = string.Concat(splitDefaultKey.Intertwine(splitKey).ToList());

                _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(newKey));
            }
        }
    }

</code>```

JAVA test...

```<code>import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecurityAESEncryption {

    private static final String _key = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
    private static final char[] initCharArray = new char[]  {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
    private static final byte[] initVector =  SecurityAESEncryption.charToByteArray(initCharArray);

    //private static final String initArray = "26dcff00aded7aeec5fe07af4d08223c";
    //private static final byte[] ivValue = SecurityAESEncryption.hexStringToByteArray(initArray);
    //private static final byte[] key = DigestUtils.sha256(_key.getBytes(StandardCharsets.US_ASCII)).;
    private static final byte[] key = SecurityAESEncryption.computeHash(_key);

    public static String encrypt(String value) {
        try {
            System.out.println(key.length);
            System.out.println(Base64.decodeBase64(key).length);
            byte[] aesKey = new byte[32];
            System.arraycopy(key, 0, aesKey, 0, 32);
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(initVector);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encrypted) {
        try {
            byte[] encryptedBytes = Base64.decodeBase64(encrypted);
            System.out.println(key.length);
            System.out.println(Base64.decodeBase64(key).length);
            byte[] aesKey = new byte[32];
            System.arraycopy(key, 0, aesKey, 0, 32);
            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            //byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
            byte[] original = cipher.doFinal(encryptedBytes);

            return new String(original,StandardCharsets.US_ASCII);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static byte[] charToByteArray(char[] x)
    {
        final byte[] res = new byte[x.length];
        for (int i = 0; i < x.length; i++)
        {
            res[i] = (byte) x[i];
        }
        return res;
    }

    public static byte[] computeHash(String input)  {
        try {
        // Static getInstance method is called with hashing SHA
        MessageDigest md = MessageDigest.getInstance("SHA-256");
            return md.digest(input.getBytes(StandardCharsets.US_ASCII));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
        String originalString = "123456!@#";
        System.out.println("Original String to encrypt - " + originalString);
        String encryptedString = encrypt(originalString);

        System.out.println("Encrypted String - " + encryptedString);
        String decryptedString = decrypt("Ci10C7ZjUPoEnitdh7QkEw==");
        System.out.println("After decryption - " + decryptedString);
    }

</code>```

答:
Your edited Java prog now successfully encrypts the string "123456!@#" to this (Base64 encoded) string "LnZV0Vph+eUeJLT2Gst0kw==" using a String as input to a SHA-256 digest, so the real key used for en-/decryption is
(hex) "07c3491eaa6a6289ca91b7b0f290d60688538860b44753f1cf9617977985d2db".

Using this encoded string as input for your decrypt method returns the original string but when using the encoded/encrypted
string "Ci10C7ZjUPoEnitdh7QkEw==" I'm running into this exception:

```<code>javax.crypto.BadPaddingException: Given final block not properly padded.
Such issues can arise if a bad key is used during decryption.
</code>```

Imho this indicates that the key your're using on Java-side is not the same as on C#-side (we don't see the real input
to Encrypt and I don't know what "CustomKey" is doing :-).

Could you please print out
the aeskey and -iv from your C#-Encrypt method directly after you setup them in encryptor-inits and share them here,
that might be usefull for us to help.

```<code>public string Encrypt(string data, string key)
...
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
==> print aesKey & _iv
...
</code>```

Title: C# encrypt to Java Decrypt

Body:
I am using a C# "encrypt" and need a Java "decrypt" method. I need help in java that i can't replicate C# decryption on java and it is not explicit Padding on C# , i don't know what use in java and my key size I think is different but I am not sure. I'm very confused.

know that i need change Java Policy , and did it ! and Change Key size JAVA to 32 bytes.

C#

    using System;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using Voa.Cross.Util.Extensions;

    namespace Voa.Core.Safeties
    {
        public class Security
        {
            private readonly string _defaultKey = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
            private readonly int _divisionKey = 4;
            private readonly byte[] _iv = new byte[16] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
            private byte[] _key;

            public Security() => _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(_defaultKey));

            public string Encrypt(string data, string key)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    CustomKey(key);
                }

                var encryptor = Aes.Create();

                encryptor.Mode = CipherMode.CBC;

                // Set key and IV
                var aesKey = new byte[32];
                Array.Copy(_key, 0, aesKey, 0, 32);
                encryptor.Key = aesKey;
                encryptor.IV = _iv;

                var memoryStream = new MemoryStream();

                var aesEncryptor = encryptor.CreateEncryptor();

                var cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

                var plainBytes = Encoding.ASCII.GetBytes(data);

                cryptoStream.Write(plainBytes, 0, plainBytes.Length);

                cryptoStream.FlushFinalBlock();

                var cipherBytes = memoryStream.ToArray();

                memoryStream.Close();
                cryptoStream.Close();

                var cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

                return cipherText;
            }

            public string Decrypt(string data, string key)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    CustomKey(key);
                }

                var encryptor = Aes.Create();

                encryptor.Mode = CipherMode.CBC;

                var aesKey = new byte[32];
                Array.Copy(_key, 0, aesKey, 0, 32);
                encryptor.Key = aesKey;
                encryptor.IV = _iv;

                var memoryStream = new MemoryStream();

                var aesDecryptor = encryptor.CreateDecryptor();

                var cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

                var plainText = string.Empty;

                try
                {
                    var cipherBytes = Convert.FromBase64String(data);

                    cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

                    cryptoStream.FlushFinalBlock();

                    var plainBytes = memoryStream.ToArray();

                    plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
                }
                finally
                {
                    memoryStream.Close();
                    cryptoStream.Close();
                }

                return plainText;
            }

            private void CustomKey(string key)
            {
                var blockSize = key.Length / _divisionKey;
                var splitKey = key.CutString(blockSize).ToList();
                var splitDefaultKey = _defaultKey.CutString(blockSize).ToList();
                var newKey = string.Concat(splitDefaultKey.Intertwine(splitKey).ToList());

                _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(newKey));
            }
        }
    }

JAVA test...

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecurityAESEncryption {

    private static final String _key = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
    private static final char[] initCharArray = new char[]  {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
    private static final byte[] initVector =  SecurityAESEncryption.charToByteArray(initCharArray);

    //private static final String initArray = "26dcff00aded7aeec5fe07af4d08223c";
    //private static final byte[] ivValue = SecurityAESEncryption.hexStringToByteArray(initArray);
    //private static final byte[] key = DigestUtils.sha256(_key.getBytes(StandardCharsets.US_ASCII)).;
    private static final byte[] key = SecurityAESEncryption.computeHash(_key);

    public static String encrypt(String value) {
        try {
            System.out.println(key.length);
            System.out.println(Base64.decodeBase64(key).length);
            byte[] aesKey = new byte[32];
            System.arraycopy(key, 0, aesKey, 0, 32);
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(initVector);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encrypted) {
        try {
            byte[] encryptedBytes = Base64.decodeBase64(encrypted);
            System.out.println(key.length);
            System.out.println(Base64.decodeBase64(key).length);
            byte[] aesKey = new byte[32];
            System.arraycopy(key, 0, aesKey, 0, 32);
            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            //byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
            byte[] original = cipher.doFinal(encryptedBytes);

            return new String(original,StandardCharsets.US_ASCII);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static byte[] charToByteArray(char[] x)
    {
        final byte[] res = new byte[x.length];
        for (int i = 0; i < x.length; i++)
        {
            res[i] = (byte) x[i];
        }
        return res;
    }

    public static byte[] computeHash(String input)  {
        try {
        // Static getInstance method is called with hashing SHA
        MessageDigest md = MessageDigest.getInstance("SHA-256");
            return md.digest(input.getBytes(StandardCharsets.US_ASCII));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
        String originalString = "123456!@#";
        System.out.println("Original String to encrypt - " + originalString);
        String encryptedString = encrypt(originalString);

        System.out.println("Encrypted String - " + encryptedString);
        String decryptedString = decrypt("Ci10C7ZjUPoEnitdh7QkEw==");
        System.out.println("After decryption - " + decryptedString);
    }

Body:
Your edited Java prog now successfully encrypts the string "123456!@#" to this (Base64 encoded) string "LnZV0Vph+eUeJLT2Gst0kw==" using a String as input to a SHA-256 digest, so the real key used for en-/decryption is
(hex) "07c3491eaa6a6289ca91b7b0f290d60688538860b44753f1cf9617977985d2db".

Using this encoded string as input for your decrypt method returns the original string but when using the encoded/encrypted
string "Ci10C7ZjUPoEnitdh7QkEw==" I'm running into this exception:

javax.crypto.BadPaddingException: Given final block not properly padded.
Such issues can arise if a bad key is used during decryption.

Imho this indicates that the key your're using on Java-side is not the same as on C#-side (we don't see the real input
to Encrypt and I don't know what "CustomKey" is doing :-).

Could you please print out
the aeskey and -iv from your C#-Encrypt method directly after you setup them in encryptor-inits and share them here,
that might be usefull for us to help.

public string Encrypt(string data, string key)
...
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
==> print aesKey & _iv
...