问:
My VDHL code runs incorrectly - square root in vhdl
```<code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity RaccinCarreSequentielle is

generic(
    N: natural:= 16
    );
port(
    X: unsigned(2*N-1 downto 0);
    reset : in std_logic; --clear signal
    clk : in std_logic;
    state_done :  in std_logic; --start
    result_done : out std_logic;
    result :      out unsigned(2*N-1 downto 0)
    );
end entity;

architecture state_machine_raccincarre_arc of RaccinCarreSequentielle is
    type state is (s0_wait,s1_init,s2_calcul,s3_fini);
    signal pre_state,next_state: state;
begin
    state_register:process(reset,clk)
    begin
        if reset = '1' then
            pre_state <= s0_wait;
        elsif rising_edge(clk) then
            pre_state <= next_state;
        end if;
    end process state_register;

state_machine: process(pre_state,state_done)
    variable rx,rz,rv : unsigned(2*N-1 downto 0);
    variable ri: unsigned(N-1 downto 0);
begin
    case pre_state is
        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            else
                next_state <= s0_wait;
            end if;
        when s1_init =>
            next_state <= s2_calcul;
            rx := x;
            rz := (others => '0');
            rv := (2*N-2 => '1', others => '0');
            ri := to_unsigned(N-1,N);
        when s2_calcul =>
            if ri > 0 then
                    ri := ri - 1;
                    rz := rz + rv;
                    if rx > rz then
                         rx := rx - rz;
                         rz := rz + rv;
                    else
                         rz := rz - rv;
                    end if;
                    rz := '0' & rz(2*N-1 downto 1);
                    rv := "00" & rv(2*N-1 downto 2);
                    next_state <= s2_calcul;
                 else
                    next_state <= s3_fini;
            end if;
        when s3_fini =>
            result <= rz;
            if state_done = '0' then
                next_state <= s0_wait;
            else
                next_state <= s3_fini;
            end if;
        when others =>
            null;
    end case;
end process state_machine;

result_proc: process(pre_state)
begin
    if pre_state = s3_fini then
        result_done <= '1';
    else
        result_done <= '0';
    end if;
end process result_proc;
end architecture;
</code>```

When i use the for loop inside state2, my code will run correctly and my result is good. For example when i want to find the square root of 255, i will have 15. But when I dont want to use For loop in state2_calcul as you see. So i did a if statement to reduce the variable RI each time i go to state2 like below. I did a simulation but the state always stops at state2, it can not go through like my link.

```<code>when s2_calcul =>
    if ri > 0 then
            ri := ri - 1;
            rz := rz + rv;
            if rx > rz then
                 rx := rx - rz;
                 rz := rz + rv;
            else
                 rz := rz - rv;
            end if;
            rz := '0' & rz(2*N-1 downto 1);
            rv := "00" & rv(2*N-1 downto 2);
            next_state <= s2_calcul;
         else
            next_state <= s3_fini;
    end if;
</code>```

I think that problem is the nested IF, but when i change that, nothing change. Could someone helps me explain that problem and how can i solve it. thanks

答:
You cannot memorize anything in a combinatorial part of your design. So you need registers for ri, rx, rv and rz. These registers are somehow part of your global state which is indeed a combination of them, and of the pre_state register.

Let's continue with the style you already use: one synchronous process for the registers, another for the combinatorial part, and a next_xxx signal for the input of each xxx register.

architecture state_machine_raccincarre_arc of RaccinCarreSequentielle is
    type state is (s0_wait, s1_init, s2_calcul, s3_fini);
    signal pre_state, next_state: state;
    signal rx, rz, rv, next_rx, next_rz, next_rv: unsigned(2*N-1 downto 0);
    signal ri, next_ri: unsigned(N-1 downto 0);
begin
    state_register:process(reset,clk)
    begin
        if reset = '1' then
            pre_state <= s0_wait;
            rx <= (others => '0');
            rz <= (others => '0');
            ri <= (others => '0');
            rv <= (others => '0');
        elsif rising_edge(clk) then
            pre_state <= next_state;
            rx <= next_rx;
            rz <= next_rz;
            ri <= next_ri;
            rv <= next_rv;
        end if;
    end process state_register;

    state_machine: process(pre_state, state_done, x, rx, rz, rv, ri)
        variable tmpz : unsigned(2*N-1 downto 0);
    begin
        next_state <= pre_state;
        next_rx    <= rx;
        next_rz    <= rz;
        next_rv    <= rv;
        next_ri    <= ri;
        tmpz       := (others => '0');
        case pre_state is
            when s0_wait =>
                if state_done = '1' then
                    next_state <= s1_init;
                end if;
            when s1_init =>
                next_state <= s2_calcul;
                next_rx <= x;
                next_rz <= (others => '0');
                next_rv <= (others => '0');
                next_rv(2*N-2) <= '1';
                next_ri <= to_unsigned(N-1,N);
            when s2_calcul =>
                if ri > 0 then
                    next_ri <= ri - 1;
                    tmpz := rz + rv;
                    if rx > tmpz then
                        next_rx <= rx - tmpz;
                        tmpz := tmpz + rv;
                    else
                        tmpz := tmpz - rv;
                    end if;
                    next_rz <= '0' & tmpz(2*N-1 downto 1);
                    next_rv <= "00" & rv(2*N-1 downto 2);
                else
                    next_state <= s3_fini;
                end if;
            when s3_fini =>
                if state_done = '0' then
                    next_state <= s0_wait;
                end if;
        end case;
    end process state_machine;

    result <= rz;
    result_done <= '1' when pre_state = s3_fini else '0';
end architecture;
```
<p>See? The sensitivity list of the combinatorial process contains <strong>all</strong> signals that the process reads, the signals it assigns are always assigned (thanks to the default assignments at the very beginning), and the only variable is always assigned before it is used (thanks also to the default assignment at the very beginning).</p>
<p>Note that, thanks to the default assignments at the very beginning, there is no risk to get latches at synthesis. By default these:</p>
<pre class="lang-vhdl prettyprint-override"><code>next_xxx <= xxx;
</code>```

assignments say that by default the xxx register shall not change. An interesting side effect is that you do not need any more some of your else statements. You can replace:

        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            else
                next_state <= s0_wait;
            end if;
```
<p>by:</p>
<pre class="lang-vhdl prettyprint-override"><code>        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            end if;
</code>```

because the else clause is already what happens by default.

Of course, it could be that it does not work exactly as you would like because the structure is totally different. But at least this should be a good starting point for your debugging. Just remember the main principles of combinatorial processes for synthesis:

the sensitivity list must contain all signals that the process reads (the all keyword of the VHDL 2008 standard is helpful, if your tools support it),

the signals it assigns (its outputs) must be assigned each time the process resumes (default assignments at the very beginning can be handy for beginners),

the variables must always be assigned before they are used (default assignments at the very beginning can be handy for beginners).

Be careful, these 3 golden rules are not that easy to check, especially in complicated nested if and case statements. This is why I always suggest to beginners to use the trick of default assignments at the very beginning. Rules #2 and #3 become trivial. For rule #1, if your tools support the all keyword of the VHDL 2008 standard, use it for all combinatorial processes (not for synchronous processes):

state_machine: process(all)
```

Body:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity RaccinCarreSequentielle is

generic(
    N: natural:= 16
    );
port(
    X: unsigned(2*N-1 downto 0);
    reset : in std_logic; --clear signal
    clk : in std_logic;
    state_done :  in std_logic; --start
    result_done : out std_logic;
    result :      out unsigned(2*N-1 downto 0)
    );
end entity;

architecture state_machine_raccincarre_arc of RaccinCarreSequentielle is
    type state is (s0_wait,s1_init,s2_calcul,s3_fini);
    signal pre_state,next_state: state;
begin
    state_register:process(reset,clk)
    begin
        if reset = '1' then
            pre_state <= s0_wait;
        elsif rising_edge(clk) then
            pre_state <= next_state;
        end if;
    end process state_register;

state_machine: process(pre_state,state_done)
    variable rx,rz,rv : unsigned(2*N-1 downto 0);
    variable ri: unsigned(N-1 downto 0);
begin
    case pre_state is
        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            else
                next_state <= s0_wait;
            end if;
        when s1_init =>
            next_state <= s2_calcul;
            rx := x;
            rz := (others => '0');
            rv := (2*N-2 => '1', others => '0');
            ri := to_unsigned(N-1,N);
        when s2_calcul =>
            if ri > 0 then
                    ri := ri - 1;
                    rz := rz + rv;
                    if rx > rz then
                         rx := rx - rz;
                         rz := rz + rv;
                    else
                         rz := rz - rv;
                    end if;
                    rz := '0' & rz(2*N-1 downto 1);
                    rv := "00" & rv(2*N-1 downto 2);
                    next_state <= s2_calcul;
                 else
                    next_state <= s3_fini;
            end if;
        when s3_fini =>
            result <= rz;
            if state_done = '0' then
                next_state <= s0_wait;
            else
                next_state <= s3_fini;
            end if;
        when others =>
            null;
    end case;
end process state_machine;

result_proc: process(pre_state)
begin
    if pre_state = s3_fini then
        result_done <= '1';
    else
        result_done <= '0';
    end if;
end process result_proc;
end architecture;

When i use the for loop inside state2, my code will run correctly and my result is good. For example when i want to find the square root of 255, i will have 15. But when I dont want to use For loop in state2_calcul as you see. So i did a if statement to reduce the variable RI each time i go to state2 like below. I did a simulation but the state always stops at state2, it can not go through like my link.

when s2_calcul =>
    if ri > 0 then
            ri := ri - 1;
            rz := rz + rv;
            if rx > rz then
                 rx := rx - rz;
                 rz := rz + rv;
            else
                 rz := rz - rv;
            end if;
            rz := '0' & rz(2*N-1 downto 1);
            rv := "00" & rv(2*N-1 downto 2);
            next_state <= s2_calcul;
         else
            next_state <= s3_fini;
    end if;

I think that problem is the nested IF, but when i change that, nothing change. Could someone helps me explain that problem and how can i solve it. thanks

Body:
You cannot memorize anything in a combinatorial part of your design. So you need registers for ri, rx, rv and rz. These registers are somehow part of your global state which is indeed a combination of them, and of the pre_state register.

Let's continue with the style you already use: one synchronous process for the registers, another for the combinatorial part, and a next_xxx signal for the input of each xxx register.

architecture state_machine_raccincarre_arc of RaccinCarreSequentielle is
    type state is (s0_wait, s1_init, s2_calcul, s3_fini);
    signal pre_state, next_state: state;
    signal rx, rz, rv, next_rx, next_rz, next_rv: unsigned(2*N-1 downto 0);
    signal ri, next_ri: unsigned(N-1 downto 0);
begin
    state_register:process(reset,clk)
    begin
        if reset = '1' then
            pre_state <= s0_wait;
            rx <= (others => '0');
            rz <= (others => '0');
            ri <= (others => '0');
            rv <= (others => '0');
        elsif rising_edge(clk) then
            pre_state <= next_state;
            rx <= next_rx;
            rz <= next_rz;
            ri <= next_ri;
            rv <= next_rv;
        end if;
    end process state_register;

    state_machine: process(pre_state, state_done, x, rx, rz, rv, ri)
        variable tmpz : unsigned(2*N-1 downto 0);
    begin
        next_state <= pre_state;
        next_rx    <= rx;
        next_rz    <= rz;
        next_rv    <= rv;
        next_ri    <= ri;
        tmpz       := (others => '0');
        case pre_state is
            when s0_wait =>
                if state_done = '1' then
                    next_state <= s1_init;
                end if;
            when s1_init =>
                next_state <= s2_calcul;
                next_rx <= x;
                next_rz <= (others => '0');
                next_rv <= (others => '0');
                next_rv(2*N-2) <= '1';
                next_ri <= to_unsigned(N-1,N);
            when s2_calcul =>
                if ri > 0 then
                    next_ri <= ri - 1;
                    tmpz := rz + rv;
                    if rx > tmpz then
                        next_rx <= rx - tmpz;
                        tmpz := tmpz + rv;
                    else
                        tmpz := tmpz - rv;
                    end if;
                    next_rz <= '0' & tmpz(2*N-1 downto 1);
                    next_rv <= "00" & rv(2*N-1 downto 2);
                else
                    next_state <= s3_fini;
                end if;
            when s3_fini =>
                if state_done = '0' then
                    next_state <= s0_wait;
                end if;
        end case;
    end process state_machine;

    result <= rz;
    result_done <= '1' when pre_state = s3_fini else '0';
end architecture;

See? The sensitivity list of the combinatorial process contains all signals that the process reads, the signals it assigns are always assigned (thanks to the default assignments at the very beginning), and the only variable is always assigned before it is used (thanks also to the default assignment at the very beginning).

Note that, thanks to the default assignments at the very beginning, there is no risk to get latches at synthesis. By default these:

next_xxx <= xxx;

assignments say that by default the xxx register shall not change. An interesting side effect is that you do not need any more some of your else statements. You can replace:

        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            else
                next_state <= s0_wait;
            end if;

by:

        when s0_wait =>
            if state_done = '1' then
                next_state <= s1_init;
            end if;

because the else clause is already what happens by default.

Of course, it could be that it does not work exactly as you would like because the structure is totally different. But at least this should be a good starting point for your debugging. Just remember the main principles of combinatorial processes for synthesis:

the sensitivity list must contain all signals that the process reads (the all keyword of the VHDL 2008 standard is helpful, if your tools support it),

the signals it assigns (its outputs) must be assigned each time the process resumes (default assignments at the very beginning can be handy for beginners),

the variables must always be assigned before they are used (default assignments at the very beginning can be handy for beginners).

Be careful, these 3 golden rules are not that easy to check, especially in complicated nested if and case statements. This is why I always suggest to beginners to use the trick of default assignments at the very beginning. Rules #2 and #3 become trivial. For rule #1, if your tools support the all keyword of the VHDL 2008 standard, use it for all combinatorial processes (not for synchronous processes):

state_machine: process(all)


来源: stackexchange

问:
Angular SignalR and Windows Authentication (NTLM)
My question is pretty straightforward. I am using Windows Authentication in .NET Core. On the front end part of the app (Angular) I have a HTTP interceptor which sets
widhcredentails: true
to the all HTTP requests.

This interceptor does not work with WebSocket, so I need a solution for adding the same code from Interceptor to the SignalR service.

Here is my interceptor code:

```<code>intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
{
    request = request.clone({ withCredentials: true });
    return next.handle(request);
}
</code>```

And here is my SignalR service:

```<code>  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));
</code>```

Keep in mind that interceptor is added in providers array in the app.module component :

```<code>providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: WinAuthInterceptor,
        multi: true
    }

],
</code>```

SignalR service is injected in the root.

```<code>@Injectable({
    providedIn: 'root'
})
</code>```

答:
I have found this in the Microsoft documentation:

If Windows authentication is configured in your app, SignalR can use
that identity to secure hubs. However, to send messages to individual
users, you need to add a custom User ID provider. The Windows
authentication system doesn't provide the "Name Identifier" claim.
SignalR uses the claim to determine the user name.

Add a new class that implements IUserIdProvider and retrieve one of
the claims from the user to use as the identifier. For example, to use
the "Name" claim (which is the Windows username in the form
[Domain][Username]), create the following class:

```<code>public class NameUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.Identity?.Name;
    }
}
</code>```

Rather than ClaimTypes.Name, you can use any value from the User (such
as the Windows SID identifier, and so on).

Note: The value you choose must be unique among all the users in your system. Otherwise, a message intended for one user could end up
going to a different user.

Register this component in your Startup.ConfigureServices method:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // ... other services ...

    services.AddSignalR();
    services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
}
</code>```

In the .NET Client, Windows Authentication must be enabled by setting
the UseDefaultCredentials property:

```<code>var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chathub", options =>
    {
        options.UseDefaultCredentials = true;
    })
    .Build();
</code>```

Windows authentication is supported in Internet Explorer and Microsoft
Edge, but not in all browsers. For example, in Chrome and Safari,
attempting to use Windows authentication and WebSockets fails. When
Windows authentication fails, the client attempts to fall back to
other transports which might work.

As mentioned, it is not supported by all browsers. IMO the best way to authenticate the signal R connections is using bearer tokens.

Adding the token to the connection is as easy as:

```<code>this.chatHubConnection = new signalR.HubConnectionBuilder()
  .withUrl(this.endpointsService.chatHubConnection(), {
    accessTokenFactory: () => this.getCurrentJwtToken(),
  })
  .configureLogging(signalR.LogLevel.Error)
  .withAutomaticReconnect([0, 2000, 5000, 5000, 5000, 5000, 10000])
  .build();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My question is pretty straightforward. I am using Windows Authentication in .NET Core. On the front end part of the app (Angular) I have a HTTP interceptor which sets
widhcredentails: true
to the all HTTP requests.

This interceptor does not work with WebSocket, so I need a solution for adding the same code from Interceptor to the SignalR service.

Here is my interceptor code:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
{
    request = request.clone({ withCredentials: true });
    return next.handle(request);
}

And here is my SignalR service:

  this.requestConnection = new HubConnectionBuilder().
        withUrl(`${environment.apiUrl}/request`).
        withAutomaticReconnect([0, 2000, 30000, 60000, null]).
        build();
    this.requestConnection.
        start().
        then(() => console.log('Connection started')).
        catch(err => console.log(`Error while starting connection: ${err}`));

Keep in mind that interceptor is added in providers array in the app.module component :

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: WinAuthInterceptor,
        multi: true
    }

],

SignalR service is injected in the root.

@Injectable({
    providedIn: 'root'
})

Body:
I have found this in the Microsoft documentation:

If Windows authentication is configured in your app, SignalR can use
that identity to secure hubs. However, to send messages to individual
users, you need to add a custom User ID provider. The Windows
authentication system doesn't provide the "Name Identifier" claim.
SignalR uses the claim to determine the user name.

Add a new class that implements IUserIdProvider and retrieve one of
the claims from the user to use as the identifier. For example, to use
the "Name" claim (which is the Windows username in the form
[Domain][Username]), create the following class:

public class NameUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.Identity?.Name;
    }
}

Rather than ClaimTypes.Name, you can use any value from the User (such
as the Windows SID identifier, and so on).

Note: The value you choose must be unique among all the users in your system. Otherwise, a message intended for one user could end up
going to a different user.

Register this component in your Startup.ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // ... other services ...

    services.AddSignalR();
    services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
}

In the .NET Client, Windows Authentication must be enabled by setting
the UseDefaultCredentials property:

var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chathub", options =>
    {
        options.UseDefaultCredentials = true;
    })
    .Build();

Windows authentication is supported in Internet Explorer and Microsoft
Edge, but not in all browsers. For example, in Chrome and Safari,
attempting to use Windows authentication and WebSockets fails. When
Windows authentication fails, the client attempts to fall back to
other transports which might work.

As mentioned, it is not supported by all browsers. IMO the best way to authenticate the signal R connections is using bearer tokens.

Adding the token to the connection is as easy as:

this.chatHubConnection = new signalR.HubConnectionBuilder()
  .withUrl(this.endpointsService.chatHubConnection(), {
    accessTokenFactory: () => this.getCurrentJwtToken(),
  })
  .configureLogging(signalR.LogLevel.Error)
  .withAutomaticReconnect([0, 2000, 5000, 5000, 5000, 5000, 10000])
  .build();


问:
Can't start a self managed node group through Terraform
I am trying to deploy a self managed node group through terraform, for days now. Deploying a non self managed one works out of the bat, however, I have the following issue with the self managed one. This is what my code looks like:

```<code>self_managed_node_groups = {
    self_mg_4 = {
      node_group_name        = "self-managed-ondemand"
      subnet_ids             = module.aws_vpc.private_subnets
      create_launch_template = true
      launch_template_os     = "amazonlinux2eks"
      custom_ami_id          = "xxx"
      public_ip              = false
      pre_userdata           = <<-EOT
            yum install -y amazon-ssm-agent \
            systemctl enable amazon-ssm-agent && systemctl start amazon-ssm-agent \
        EOT

      disk_size     = 5
      instance_type = "t2.small"
      desired_size  = 1
      max_size      = 5
      min_size      = 1
      capacity_type = ""

      k8s_labels = {
        Environment = "dev-test"
        Zone        = ""
        WorkerType  = "SELF_MANAGED_ON_DEMAND"
      }

      additional_tags = {
        ExtraTag    = "t2x-on-demand"
        Name        = "t2x-on-demand"
        subnet_type = "private"
      }
      create_worker_security_group = false
    }
  }
</code>```

This is the module I use: github.com/aws-samples/aws-eks-accelerator-for-terraform

And this is what Terraform throws after 10 mins:

Error: "Cluster": Waiting up to 10m0s: Need at least 1 healthy instances in ASG, have 0.

Cause: "At 2022-02-10T16:46:14Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1.", Description: "Launching a new EC2 instance. Status Reason: The requested configuration is currently not supported. Please check the documentation for supported configurations. Launching EC2 instance failed.", StatusCode: "Failed"

Full code:
https://pastebin.com/mtVGC8PP

答: The solution was actually changing my t2.small to t3.small. Turns out my AZS didn't support t2.</p>

Body:
I am trying to deploy a self managed node group through terraform, for days now. Deploying a non self managed one works out of the bat, however, I have the following issue with the self managed one. This is what my code looks like:

self_managed_node_groups = {
    self_mg_4 = {
      node_group_name        = "self-managed-ondemand"
      subnet_ids             = module.aws_vpc.private_subnets
      create_launch_template = true
      launch_template_os     = "amazonlinux2eks"
      custom_ami_id          = "xxx"
      public_ip              = false
      pre_userdata           = <<-EOT
            yum install -y amazon-ssm-agent \
            systemctl enable amazon-ssm-agent && systemctl start amazon-ssm-agent \
        EOT

      disk_size     = 5
      instance_type = "t2.small"
      desired_size  = 1
      max_size      = 5
      min_size      = 1
      capacity_type = ""

      k8s_labels = {
        Environment = "dev-test"
        Zone        = ""
        WorkerType  = "SELF_MANAGED_ON_DEMAND"
      }

      additional_tags = {
        ExtraTag    = "t2x-on-demand"
        Name        = "t2x-on-demand"
        subnet_type = "private"
      }
      create_worker_security_group = false
    }
  }

This is the module I use: github.com/aws-samples/aws-eks-accelerator-for-terraform

And this is what Terraform throws after 10 mins:

Error: "Cluster": Waiting up to 10m0s: Need at least 1 healthy instances in ASG, have 0.

Cause: "At 2022-02-10T16:46:14Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1.", Description: "Launching a new EC2 instance. Status Reason: The requested configuration is currently not supported. Please check the documentation for supported configurations. Launching EC2 instance failed.", StatusCode: "Failed"

Full code:
https://pastebin.com/mtVGC8PP


问:
Alternative solutions for Hibernate.Envers
i'm planning a historization for my java webapp (spring, hibernate).

By googling I found Hibernate.Envers, which seems to be the perfect solution for me.

Are there any comparable solutions?

Thanks a lot!
Jean

答:
Have a look at JaVers: https://javers.org/

It offers quite similar functionality, but with some different tweaks which make it better in some cases (and worse in others).

Here is a comparison of the two:
https://javers.org/blog/2017/12/javers-vs-envers-comparision.html

ContentLicense: CC BY-SA 2.5


问:
Python matplotlib not saving charts files
I have historic data on my stock holdings in a database. The object here is to create two charts and save each to png files. I read the data from the db into a pandas dataframe to build the charts. The code runs cleanly - no errors. I see the charts when I run it in Spyder, but nothing is saved. Here is a brief summary of what I'm doing:

```<code>fig1, ax1 = plt.subplots()
... some code
df['Price'].plot(ax=ax1, title=title1)
plt.savefig(figName1, bbox_inches='tight')
fig2, ax2 = plt.subplots()
... some code
df['% Price'].plot(ax=ax2, title=title2)
df['% S&P'].plot(ax=ax2)
plt.savefig(figName2, bbox_inches='tight')
</code>```

Is there something wrong with this approach? Thanks.

答: Fixed. There was nothing wrong with the code shown. The problem was with the format of the figName1 and figName2 addresses. Embarrassing.</p>

Body:
I have historic data on my stock holdings in a database. The object here is to create two charts and save each to png files. I read the data from the db into a pandas dataframe to build the charts. The code runs cleanly - no errors. I see the charts when I run it in Spyder, but nothing is saved. Here is a brief summary of what I'm doing:

fig1, ax1 = plt.subplots()
... some code
df['Price'].plot(ax=ax1, title=title1)
plt.savefig(figName1, bbox_inches='tight')
fig2, ax2 = plt.subplots()
... some code
df['% Price'].plot(ax=ax2, title=title2)
df['% S&P'].plot(ax=ax2)
plt.savefig(figName2, bbox_inches='tight')

Is there something wrong with this approach? Thanks.


问:
Google Calendar API not returning attendees when listing events
When retrieving events using the Google Calendar Api v3 the attendees array is not included in the results. I'm authenticating with a service account, so there should be no access restrictions on individual fields.

My request looks like this (authentication code omitted for brevity):

async function fetchEvents() {
  const calendar = google.calendar('v3')
  google.options({ auth: await auth() })

  return await calendar.events.list({
    calendarId:
      '<the-actual-calendar-id>@group.calendar.google.com',
    fields:
      'items(summary,description,attendees)',
    maxAttendees: 99,
    timeMin: new Date().toISOString(),
    maxResults: 5,
    singleEvents: true,
    orderBy: 'startTime'
  })
}
```

Omitting the fields parameter entirely also doesn't include the attendees although the field is part of the Events Resource.

Likewise, omitting maxAttendees also doesn't change anything.

Following the htmlLink returned from the API, I can verify that a particular event has a list of attendees.

答:
Sounds like you have not set up delegation properly.  When you delegate to the user in your workspace domain.  That user has access on the domain for the-actual-calendar-id>@group.calendar.google.com

Then you init impersonation with the with_subject .

```<code>from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

delegated_credentials = credentials.with_subject('user@example.org')
</code>```

Body:
When retrieving events using the Google Calendar Api v3 the attendees array is not included in the results. I'm authenticating with a service account, so there should be no access restrictions on individual fields.

My request looks like this (authentication code omitted for brevity):

async function fetchEvents() {
  const calendar = google.calendar('v3')
  google.options({ auth: await auth() })

  return await calendar.events.list({
    calendarId:
      '<the-actual-calendar-id>@group.calendar.google.com',
    fields:
      'items(summary,description,attendees)',
    maxAttendees: 99,
    timeMin: new Date().toISOString(),
    maxResults: 5,
    singleEvents: true,
    orderBy: 'startTime'
  })
}

Omitting the fields parameter entirely also doesn't include the attendees although the field is part of the Events Resource.

Likewise, omitting maxAttendees also doesn't change anything.

Following the htmlLink returned from the API, I can verify that a particular event has a list of attendees.

Body:
Sounds like you have not set up delegation properly.  When you delegate to the user in your workspace domain.  That user has access on the domain for the-actual-calendar-id>@group.calendar.google.com

Then you init impersonation with the with_subject .

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

delegated_credentials = credentials.with_subject('user@example.org')


问:
How to launch a function from a module so that it takes effect in the main program?
An example of what I want to get:

Main program:

```<code>from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():

    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=module.moduleFunction)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()
</code>```

Module:

```<code>from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction():

    child_window = Toplevel()

    def resetCanvasFromModule():

        # THE QUESTION!
        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)
</code>```

Obviously this doesn't work, since resetCanvas() isn't defined inside the module, but if I define it, it will try to destroy canvas, which isn't defined in the module, so it won't work either.

So, what would I have to do to get the effect I want?

P.S.: I have tried with 'global', without success.

答:
Can't you just pass the element?
like this
from tkinter import *</p>
```<code>canvas = None

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def ResetCanvasFromModule():
    global canvas
    canvas.forget()
    createCanvas()

button1 = Button(main_window, text="create canvas", command=createCanvas)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=ResetCanvas)
button2.grid(row=0, column=1)
</code>```

Body:
An example of what I want to get:

Main program:

from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():

    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=module.moduleFunction)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()

Module:

from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction():

    child_window = Toplevel()

    def resetCanvasFromModule():

        # THE QUESTION!
        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)

Obviously this doesn't work, since resetCanvas() isn't defined inside the module, but if I define it, it will try to destroy canvas, which isn't defined in the module, so it won't work either.

So, what would I have to do to get the effect I want?

P.S.: I have tried with 'global', without success.

Body:
Can't you just pass the element?
like this
from tkinter import *

canvas = None

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def ResetCanvasFromModule():
    global canvas
    canvas.forget()
    createCanvas()

button1 = Button(main_window, text="create canvas", command=createCanvas)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=ResetCanvas)
button2.grid(row=0, column=1)


问:
Unable to set_password using POST request
I'm trying to make a function which can reset user password of OTP matached to the stored value in user model.

I'm able to make a successful post request and JSON response I'm getting

```<code>{
    "detail": "Password have been changed"
}
</code>```

But problem is password in actual dosent change but remains the older one.
Can anybody identify what is the problem in my function.
My API view is :

```<code>@api_view(['POST'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']

    user = User.objects.get(email=email)
    if User.objects.filter(email=email).exists():
        otp_to_verify == user.otp #user model has a field name otp
        if new_password != '':
            # user.set_password(make_password(data['password']))
            user.set_password((data['password'])) #changed to this but dosnt work
            user.save()
            message = {
                'detail': 'Password have been changed'}
            return Response(message, status=status.HTTP_200_OK)
        else:
            message = {
                'detail': 'Something wrong'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
</code>```

So I'm not sure what might be the problem as it's passing silently without giving any errors but in the end password does not change.

EDIT:
using this method user password hash in database gets changed but unable to login with new password and older password also gets invalid
this error comes then .

```<code> Unauthorized: /api/v1/accounts/login/
    [11/Feb/2022 17:44:54] "POST /api/v1/accounts/login/ HTTP/1.1" 401 63
    Not Found: /jwt/refresh-token
    [11/Feb/2022 17:44:54] "POST /jwt/refresh-token HTTP/1.1" 404 2761
</code>```

答:
I think that user.set_password method dont need to use make_password function.

set_password hash plain text password by default

user.set_password(data['password'])

Using make_password

user.password = make_password(data['password'])

Body:
I'm trying to make a function which can reset user password of OTP matached to the stored value in user model.

I'm able to make a successful post request and JSON response I'm getting

{
    "detail": "Password have been changed"
}

But problem is password in actual dosent change but remains the older one.
Can anybody identify what is the problem in my function.
My API view is :

@api_view(['POST'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']

    user = User.objects.get(email=email)
    if User.objects.filter(email=email).exists():
        otp_to_verify == user.otp #user model has a field name otp
        if new_password != '':
            # user.set_password(make_password(data['password']))
            user.set_password((data['password'])) #changed to this but dosnt work
            user.save()
            message = {
                'detail': 'Password have been changed'}
            return Response(message, status=status.HTTP_200_OK)
        else:
            message = {
                'detail': 'Something wrong'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

So I'm not sure what might be the problem as it's passing silently without giving any errors but in the end password does not change.

EDIT:
using this method user password hash in database gets changed but unable to login with new password and older password also gets invalid
this error comes then .

 Unauthorized: /api/v1/accounts/login/
    [11/Feb/2022 17:44:54] "POST /api/v1/accounts/login/ HTTP/1.1" 401 63
    Not Found: /jwt/refresh-token
    [11/Feb/2022 17:44:54] "POST /jwt/refresh-token HTTP/1.1" 404 2761


问:
(TS - Redux) How to initialize state property as null: Type 'UserData' is not assignable to type 'null'
I'm having this error: Type 'UserData' is not assignable to type 'null'.

I defined the user state property as user: UserData | null;... So i don't understand why it doesn't let me to initialize the property as null and then assign it a UserData like value:
Error Console

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";

interface AppState {
  user: UserData | null;
}

const appSlice = createSlice({
  name: 'app',
  initialState: { user: null },
  reducers: {
    loadUserIntoApp: {
      reducer(state, action: PayloadAction<UserData>) {
        state.user = action.payload; // This is the line with an error
      }
    }
  }
})```

答:
You should infer the AppState interface to the initialState

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";

interface AppState {
  user: UserData | null;
}

const appSlice = createSlice({
  name: 'app',
  initialState: AppState = { user: null },
  reducers: {
    loadUserIntoApp: {
      (state, action: PayloadAction<UserData>) => { //you should add the reducer like this
        state.user = action.payload;
       }
    }
  }
})```

go to decumetation for more info

Body:
You should infer the AppState interface to the initialState

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";

interface AppState {
  user: UserData | null;
}

const appSlice = createSlice({
  name: 'app',
  initialState: AppState = { user: null },
  reducers: {
    loadUserIntoApp: {
      (state, action: PayloadAction<UserData>) => { //you should add the reducer like this
        state.user = action.payload;
       }
    }
  }
})

go to decumetation for more info


问:
Detect if a string contains any numbers
This is the test.php file:

```<code>$string = 'A string with no numbers';

for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}

// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));

// function
function codeStyle($string) {
    return '<span style="background-color: #eee; font-weight: bold;">' . $string . '</span>';
}
</code>```

It splits the string character by character and checks if the character is a number or not.

Problem: Its output is always "This variable includes number(s)". Please help me to find the reason.
TIP: When I change range(0,9) to range(1,9) It works correctly (But it can't detect 0).

答:
It's kinda late to answer this question after about 9 years, but If you want to detect integers (and not floats) nothing is better than ctype_digit. Using this function to detect floats with decimal point or other types would results in returning false.

<?php
$number = "123";
$notNumber = "123abc";
var_dump(ctype_digit($number));
var_dump(ctype_digit($notNumber));
?>
```
<h3>Output</h3>
```bool(true)
bool(false)
```

Title: Detect if a string contains any numbers

Body:
This is the test.php file:

$string = 'A string with no numbers';

for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}

// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));

// function
function codeStyle($string) {
    return '' . $string . '';
}

It splits the string character by character and checks if the character is a number or not.

Problem: Its output is always "This variable includes number(s)". Please help me to find the reason.
TIP: When I change range(0,9) to range(1,9) It works correctly (But it can't detect 0).

Body:
It's kinda late to answer this question after about 9 years, but If you want to detect integers (and not floats) nothing is better than ctype_digit. Using this function to detect floats with decimal point or other types would results in returning false.

<?php
$number = "123";
$notNumber = "123abc";
var_dump(ctype_digit($number));
var_dump(ctype_digit($notNumber));
?>

Output

bool(true)
bool(false)


问:
Make persistent changes to listview items based on user selections
So I'm back to android programming after a few years and I'm struggling with something that I thought would be very simple. I'm populating a listview using a custom array adapter with a custom layout.
Basically, every item of the array list is a custom class (named Card) with 4 properties: (int)id, (String)name, (boolean)include,(int)deck (the idea is that the user selects which cards to include in each of 3 different decks).
I created a simple layout with 2 textviews, 1 checkbox and 1 radiogroup with 3 radio buttons inside (and a bunch of icons) (see below).
My problem is that although the listview gets populated and it is shown correctly, whenever I (the user) changes something (e.g. hit the checkbox or the radio buttons) and I scroll, everything is messed up (the selection I made gets copied to other rows). I tried, to no avail, setting listeners inside the getView()  method of the adapter and notifying data changes. I know views are recycled, but clearly I don't understand properly how. Any help would be greatly appreciated.

card_layout.xml

```<code><ImageView
    android:id="@+id/icon_eye"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_gravity="center_vertical"
    app:srcCompat="@drawable/eye" />

<TextView
    android:id="@+id/tv_card_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:layout_marginLeft="5dp"
    android:layout_weight="1"
    android:visibility="gone"
    android:text="" />

<TextView
    android:id="@+id/tv_card_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:layout_marginLeft="5dp"
    android:layout_weight="2"
    android:text="TextView" />

<CheckBox
    android:id="@+id/cb_include"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="10dp"
    android:checked="true"
    android:text="" />

<RadioGroup
    android:id="@+id/rbg_decks"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon_deck_1"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_1" />

    <RadioButton
        android:id="@+id/rb_deck_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        android:text="" />

    <ImageView
        android:id="@+id/icon_deck_2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_2" />

    <RadioButton
        android:id="@+id/rb_deck_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        android:text="" />

    <ImageView
        android:id="@+id/icon_deck_3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_3" />

    <RadioButton
        android:id="@+id/rb_deck_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</RadioGroup>
</code>```

Visual example:

This is the custom adapter

AdapterCard.xml

```<code>public class AdapterCard extends ArrayAdapter<Card> {

Activity context;
AdapterCard(Activity context, ArrayList<Card> list_cards)
{
    super(context, R.layout.card_layout, list_cards);
    this.context = context;
}

static class ViewHolder {
    private ImageView icon_eye,icon_deck_1,icon_deck_2,icon_deck_3;
    private TextView tv_card_name, tv_card_id;
    private CheckBox cb_include;
    private RadioGroup rbg_decks;
    private RadioButton rb_1,rb_2,rb_3;
}

public View getView(int position, View convertView, ViewGroup parent)
{

    ViewHolder mViewHolder = null;

    if(convertView == null){
        mViewHolder = new ViewHolder();
        LayoutInflater vi = context.getLayoutInflater();
        convertView = vi.inflate(R.layout.card_layout, parent, false);
        mViewHolder.icon_eye = (ImageView) convertView.findViewById(R.id.icon_eye);
        mViewHolder.icon_deck_1 = (ImageView) convertView.findViewById(R.id.icon_deck_1);
        mViewHolder.icon_deck_2 = (ImageView) convertView.findViewById(R.id.icon_deck_2);
        mViewHolder.icon_deck_3 = (ImageView) convertView.findViewById(R.id.icon_deck_3);
        mViewHolder.tv_card_name = (TextView) convertView.findViewById(R.id.tv_card_name);
        mViewHolder.tv_card_id = (TextView) convertView.findViewById(R.id.tv_card_id);
        mViewHolder.cb_include = (CheckBox) convertView.findViewById(R.id.cb_include);
        mViewHolder.rbg_decks = (RadioGroup) convertView.findViewById(R.id.rbg_decks);
        mViewHolder.rb_1 = (RadioButton) convertView.findViewById(R.id.rb_deck_1);
        mViewHolder.rb_2 = (RadioButton) convertView.findViewById(R.id.rb_deck_2);
        mViewHolder.rb_3 = (RadioButton) convertView.findViewById(R.id.rb_deck_3);
        convertView.setTag(mViewHolder);
    } else{
        mViewHolder =   (ViewHolder) convertView.getTag();
    }

    Card card_i = getItem(position);

    mViewHolder.tv_card_name.setText(card_i.name);
    mViewHolder.tv_card_id.setText(card_i.getStringId());

    // I would like to do this only ONCE to initialize the radiobuttons
    //with the card default deck data but as it is now,
    //every time I scroll, the radiobuttons are reset
    switch(card_i.deck) {
        case 1:
            mViewHolder.rb_1.setChecked(true);
            break;
        case 2:
            mViewHolder.rb_2.setChecked(true);
            break;
        case 3:
            mViewHolder.rb_3.setChecked(true);
            break;
        default:
            break;
    }

    mViewHolder.cb_include.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            card_i.include = isChecked;
            AdapterCard.this.notifyDataSetChanged();
        }
    });

    /*mViewHolder.rbg_decks.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            card_i.deck = checkedId;
            AdapterCard.this.notifyDataSetChanged();
        }
    });*/

    return convertView;
}
</code>```

}

And this is the part in the MainActivity where I set the adapter:

```<code>    ArrayList<Card> list = ... //populate the list
    listView = findViewById(R.id.lv_cards);
    AdapterCard adapter = new AdapterCard(this,list);
    listView.setAdapter(adapter);
</code>```

EDIT: I forgot to add that the final goal is to recover all the user selections by looping through the whole list. So far I have managed to get the Card object, but since the position changes when scrolling, it is not useful:

```<code>for(int i = 0; i < adapter.getCount(); i++){
    Card card_i = adapter.getItem(i);
    // retrieve card data to generate the decks
}
</code>```

答:
I finally managed to do it by simply storing the states I was interested on in boolean lists and listening to "clicks" and instead of changed states. The Adapter now looks:</p>
```<code>public class AdapterCard extends ArrayAdapter<Card> {

Activity context;
public List<Boolean> cb_include_state, cb_must_include_state, rb_deck_1_state, rb_deck_2_state, rb_deck_3_state;

AdapterCard(Activity context, ArrayList<Card> list_cards)
{
    super(context, R.layout.card_layout, list_cards);
    this.context = context;
    // Initialize states
    cb_include_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), true));
    cb_must_include_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_1_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_2_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_3_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    for (int i=0; i<list_cards.size(); i++) {
        Card card_i = list_cards.get(i);
        switch(card_i.deck) {
            case 1:
                rb_deck_1_state.set(i,true);
                break;
            case 2:
                rb_deck_2_state.set(i,true);
                break;
            case 3:
                rb_deck_3_state.set(i,true);
                break;
            default:
                break;
        }
    }
}

static class ViewHolder {
    private ImageView icon_eye,icon_deck_1,icon_deck_2,icon_deck_3;
    private TextView tv_card_name, tv_card_id;
    private CheckBox cb_include, cb_must_include;
    private RadioGroup rbg_decks;
    private RadioButton rb_1,rb_2,rb_3;
}

public View getView(int position, View convertView, ViewGroup parent)
{

    ViewHolder mViewHolder = null;

    if(convertView == null){
        mViewHolder = new ViewHolder();
        LayoutInflater vi = context.getLayoutInflater();
        convertView = vi.inflate(R.layout.card_layout, parent, false);
        mViewHolder.icon_eye = (ImageView) convertView.findViewById(R.id.icon_eye);
        mViewHolder.icon_deck_1 = (ImageView) convertView.findViewById(R.id.icon_deck_1);
        mViewHolder.icon_deck_2 = (ImageView) convertView.findViewById(R.id.icon_deck_2);
        mViewHolder.icon_deck_3 = (ImageView) convertView.findViewById(R.id.icon_deck_3);
        mViewHolder.tv_card_name = (TextView) convertView.findViewById(R.id.tv_card_name);
        mViewHolder.tv_card_id = (TextView) convertView.findViewById(R.id.tv_card_id);
        mViewHolder.cb_include = (CheckBox) convertView.findViewById(R.id.cb_include);
        mViewHolder.cb_must_include = (CheckBox) convertView.findViewById(R.id.cb_must_include);
        mViewHolder.rbg_decks = (RadioGroup) convertView.findViewById(R.id.rbg_decks);
        mViewHolder.rb_1 = (RadioButton) convertView.findViewById(R.id.rb_deck_1);
        mViewHolder.rb_2 = (RadioButton) convertView.findViewById(R.id.rb_deck_2);
        mViewHolder.rb_3 = (RadioButton) convertView.findViewById(R.id.rb_deck_3);
        convertView.setTag(mViewHolder);
    } else{
        mViewHolder =   (ViewHolder) convertView.getTag();
    }

    Card card_i = getItem(position);
    mViewHolder.tv_card_name.setText(card_i.name);
    mViewHolder.tv_card_id.setText(card_i.getStringId());
    mViewHolder.cb_include.setChecked(cb_include_state.get(position));
    mViewHolder.cb_must_include.setChecked(cb_must_include_state.get(position));
    mViewHolder.rb_1.setChecked(rb_deck_1_state.get(position));
    mViewHolder.rb_2.setChecked(rb_deck_2_state.get(position));
    mViewHolder.rb_3.setChecked(rb_deck_3_state.get(position));

    mViewHolder.cb_must_include.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v;
            String checked = cb.isChecked() ? "yes" : "no";
            cb_must_include_state.set(position,cb.isChecked());
            Log.e("onclick must include","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.cb_include.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v;
            String checked = cb.isChecked() ? "yes" : "no";
            cb_include_state.set(position,cb.isChecked());
            Log.e("onclick include","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,rb.isChecked());
            rb_deck_2_state.set(position,!rb.isChecked());
            rb_deck_3_state.set(position,!rb.isChecked());
            Log.e("onclick rb1","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,!rb.isChecked());
            rb_deck_2_state.set(position,rb.isChecked());
            rb_deck_3_state.set(position,!rb.isChecked());
            Log.e("onclick rb2","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,!rb.isChecked());
            rb_deck_2_state.set(position,!rb.isChecked());
            rb_deck_3_state.set(position,rb.isChecked());
            Log.e("onclick rb3","item i: " + position + " checked: " + checked);
        }
    });

    return convertView;
}
}
</code>```

Body:
So I'm back to android programming after a few years and I'm struggling with something that I thought would be very simple. I'm populating a listview using a custom array adapter with a custom layout.
Basically, every item of the array list is a custom class (named Card) with 4 properties: (int)id, (String)name, (boolean)include,(int)deck (the idea is that the user selects which cards to include in each of 3 different decks).
I created a simple layout with 2 textviews, 1 checkbox and 1 radiogroup with 3 radio buttons inside (and a bunch of icons) (see below).
My problem is that although the listview gets populated and it is shown correctly, whenever I (the user) changes something (e.g. hit the checkbox or the radio buttons) and I scroll, everything is messed up (the selection I made gets copied to other rows). I tried, to no avail, setting listeners inside the getView()  method of the adapter and notifying data changes. I know views are recycled, but clearly I don't understand properly how. Any help would be greatly appreciated.

card_layout.xml

<ImageView
    android:id="@+id/icon_eye"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_gravity="center_vertical"
    app:srcCompat="@drawable/eye" />

<TextView
    android:id="@+id/tv_card_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:layout_marginLeft="5dp"
    android:layout_weight="1"
    android:visibility="gone"
    android:text="" />

<TextView
    android:id="@+id/tv_card_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:layout_marginLeft="5dp"
    android:layout_weight="2"
    android:text="TextView" />

<CheckBox
    android:id="@+id/cb_include"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="10dp"
    android:checked="true"
    android:text="" />

<RadioGroup
    android:id="@+id/rbg_decks"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon_deck_1"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_1" />

    <RadioButton
        android:id="@+id/rb_deck_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        android:text="" />

    <ImageView
        android:id="@+id/icon_deck_2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_2" />

    <RadioButton
        android:id="@+id/rb_deck_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="30dp"
        android:layout_marginRight="30dp"
        android:text="" />

    <ImageView
        android:id="@+id/icon_deck_3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:clickable="false"
        android:focusable="false"
        app:srcCompat="@drawable/die_3" />

    <RadioButton
        android:id="@+id/rb_deck_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</RadioGroup>

Visual example:

This is the custom adapter

AdapterCard.xml

public class AdapterCard extends ArrayAdapter<Card> {

Activity context;
AdapterCard(Activity context, ArrayList<Card> list_cards)
{
    super(context, R.layout.card_layout, list_cards);
    this.context = context;
}

static class ViewHolder {
    private ImageView icon_eye,icon_deck_1,icon_deck_2,icon_deck_3;
    private TextView tv_card_name, tv_card_id;
    private CheckBox cb_include;
    private RadioGroup rbg_decks;
    private RadioButton rb_1,rb_2,rb_3;
}

public View getView(int position, View convertView, ViewGroup parent)
{

    ViewHolder mViewHolder = null;

    if(convertView == null){
        mViewHolder = new ViewHolder();
        LayoutInflater vi = context.getLayoutInflater();
        convertView = vi.inflate(R.layout.card_layout, parent, false);
        mViewHolder.icon_eye = (ImageView) convertView.findViewById(R.id.icon_eye);
        mViewHolder.icon_deck_1 = (ImageView) convertView.findViewById(R.id.icon_deck_1);
        mViewHolder.icon_deck_2 = (ImageView) convertView.findViewById(R.id.icon_deck_2);
        mViewHolder.icon_deck_3 = (ImageView) convertView.findViewById(R.id.icon_deck_3);
        mViewHolder.tv_card_name = (TextView) convertView.findViewById(R.id.tv_card_name);
        mViewHolder.tv_card_id = (TextView) convertView.findViewById(R.id.tv_card_id);
        mViewHolder.cb_include = (CheckBox) convertView.findViewById(R.id.cb_include);
        mViewHolder.rbg_decks = (RadioGroup) convertView.findViewById(R.id.rbg_decks);
        mViewHolder.rb_1 = (RadioButton) convertView.findViewById(R.id.rb_deck_1);
        mViewHolder.rb_2 = (RadioButton) convertView.findViewById(R.id.rb_deck_2);
        mViewHolder.rb_3 = (RadioButton) convertView.findViewById(R.id.rb_deck_3);
        convertView.setTag(mViewHolder);
    } else{
        mViewHolder =   (ViewHolder) convertView.getTag();
    }

    Card card_i = getItem(position);

    mViewHolder.tv_card_name.setText(card_i.name);
    mViewHolder.tv_card_id.setText(card_i.getStringId());

    // I would like to do this only ONCE to initialize the radiobuttons
    //with the card default deck data but as it is now,
    //every time I scroll, the radiobuttons are reset
    switch(card_i.deck) {
        case 1:
            mViewHolder.rb_1.setChecked(true);
            break;
        case 2:
            mViewHolder.rb_2.setChecked(true);
            break;
        case 3:
            mViewHolder.rb_3.setChecked(true);
            break;
        default:
            break;
    }

    mViewHolder.cb_include.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            card_i.include = isChecked;
            AdapterCard.this.notifyDataSetChanged();
        }
    });

    /*mViewHolder.rbg_decks.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            card_i.deck = checkedId;
            AdapterCard.this.notifyDataSetChanged();
        }
    });*/

    return convertView;
}

}

And this is the part in the MainActivity where I set the adapter:

    ArrayList<Card> list = ... //populate the list
    listView = findViewById(R.id.lv_cards);
    AdapterCard adapter = new AdapterCard(this,list);
    listView.setAdapter(adapter);

EDIT: I forgot to add that the final goal is to recover all the user selections by looping through the whole list. So far I have managed to get the Card object, but since the position changes when scrolling, it is not useful:

for(int i = 0; i < adapter.getCount(); i++){
    Card card_i = adapter.getItem(i);
    // retrieve card data to generate the decks
}

Body:
I finally managed to do it by simply storing the states I was interested on in boolean lists and listening to "clicks" and instead of changed states. The Adapter now looks:

public class AdapterCard extends ArrayAdapter<Card> {

Activity context;
public List<Boolean> cb_include_state, cb_must_include_state, rb_deck_1_state, rb_deck_2_state, rb_deck_3_state;

AdapterCard(Activity context, ArrayList<Card> list_cards)
{
    super(context, R.layout.card_layout, list_cards);
    this.context = context;
    // Initialize states
    cb_include_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), true));
    cb_must_include_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_1_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_2_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    rb_deck_3_state = new ArrayList<Boolean>(Collections.nCopies(list_cards.size(), false));
    for (int i=0; i<list_cards.size(); i++) {
        Card card_i = list_cards.get(i);
        switch(card_i.deck) {
            case 1:
                rb_deck_1_state.set(i,true);
                break;
            case 2:
                rb_deck_2_state.set(i,true);
                break;
            case 3:
                rb_deck_3_state.set(i,true);
                break;
            default:
                break;
        }
    }
}

static class ViewHolder {
    private ImageView icon_eye,icon_deck_1,icon_deck_2,icon_deck_3;
    private TextView tv_card_name, tv_card_id;
    private CheckBox cb_include, cb_must_include;
    private RadioGroup rbg_decks;
    private RadioButton rb_1,rb_2,rb_3;
}

public View getView(int position, View convertView, ViewGroup parent)
{

    ViewHolder mViewHolder = null;

    if(convertView == null){
        mViewHolder = new ViewHolder();
        LayoutInflater vi = context.getLayoutInflater();
        convertView = vi.inflate(R.layout.card_layout, parent, false);
        mViewHolder.icon_eye = (ImageView) convertView.findViewById(R.id.icon_eye);
        mViewHolder.icon_deck_1 = (ImageView) convertView.findViewById(R.id.icon_deck_1);
        mViewHolder.icon_deck_2 = (ImageView) convertView.findViewById(R.id.icon_deck_2);
        mViewHolder.icon_deck_3 = (ImageView) convertView.findViewById(R.id.icon_deck_3);
        mViewHolder.tv_card_name = (TextView) convertView.findViewById(R.id.tv_card_name);
        mViewHolder.tv_card_id = (TextView) convertView.findViewById(R.id.tv_card_id);
        mViewHolder.cb_include = (CheckBox) convertView.findViewById(R.id.cb_include);
        mViewHolder.cb_must_include = (CheckBox) convertView.findViewById(R.id.cb_must_include);
        mViewHolder.rbg_decks = (RadioGroup) convertView.findViewById(R.id.rbg_decks);
        mViewHolder.rb_1 = (RadioButton) convertView.findViewById(R.id.rb_deck_1);
        mViewHolder.rb_2 = (RadioButton) convertView.findViewById(R.id.rb_deck_2);
        mViewHolder.rb_3 = (RadioButton) convertView.findViewById(R.id.rb_deck_3);
        convertView.setTag(mViewHolder);
    } else{
        mViewHolder =   (ViewHolder) convertView.getTag();
    }

    Card card_i = getItem(position);
    mViewHolder.tv_card_name.setText(card_i.name);
    mViewHolder.tv_card_id.setText(card_i.getStringId());
    mViewHolder.cb_include.setChecked(cb_include_state.get(position));
    mViewHolder.cb_must_include.setChecked(cb_must_include_state.get(position));
    mViewHolder.rb_1.setChecked(rb_deck_1_state.get(position));
    mViewHolder.rb_2.setChecked(rb_deck_2_state.get(position));
    mViewHolder.rb_3.setChecked(rb_deck_3_state.get(position));

    mViewHolder.cb_must_include.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v;
            String checked = cb.isChecked() ? "yes" : "no";
            cb_must_include_state.set(position,cb.isChecked());
            Log.e("onclick must include","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.cb_include.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckBox cb = (CheckBox) v;
            String checked = cb.isChecked() ? "yes" : "no";
            cb_include_state.set(position,cb.isChecked());
            Log.e("onclick include","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,rb.isChecked());
            rb_deck_2_state.set(position,!rb.isChecked());
            rb_deck_3_state.set(position,!rb.isChecked());
            Log.e("onclick rb1","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,!rb.isChecked());
            rb_deck_2_state.set(position,rb.isChecked());
            rb_deck_3_state.set(position,!rb.isChecked());
            Log.e("onclick rb2","item i: " + position + " checked: " + checked);
        }
    });

    mViewHolder.rb_3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton rb = (RadioButton) v;
            String checked = rb.isChecked() ? "yes" : "no";
            rb_deck_1_state.set(position,!rb.isChecked());
            rb_deck_2_state.set(position,!rb.isChecked());
            rb_deck_3_state.set(position,rb.isChecked());
            Log.e("onclick rb3","item i: " + position + " checked: " + checked);
        }
    });

    return convertView;
}
}


问:
android.view.InflateException: Binary XML file: Error inflating class fragment
I have a very frustrating error that I cannot explain. I created an Android application that uses Android AppCompat to make it compatible with older versions. Here is my main activity layout file:

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->

    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.fragment.NavigationDrawerFragment" />

</android.support.v4.widget.DrawerLayout>
</code>```

And here is main code of my activity :

```<code>public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }
}
</code>```

The main problem here is : above code run smoothly on almost devices (stimulated device, or some real devices). But when I run it on Samsung S3. It notices this error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4856)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
            at android.app.Activity.setContentView(Activity.java:1901)
            at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
            at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)
</code>```

Please tell me how to fix error, thanks :)

答:
After 2 hours of struggle, I Found that my one drawable file was in v24 but I was testing app on Api 23 device. To Solve that crash Follow these steps:

Make sure you have your files in res>drawable folder. instead of res>drawable-v24.

Sometimes your android studio not showing drawable-24 folder and your file in res>drawable folder with v24 tag.

Remove that file and re-add it.

ContentLicense: CC BY-SA 3.0

Body:
I have a very frustrating error that I cannot explain. I created an Android application that uses Android AppCompat to make it compatible with older versions. Here is my main activity layout file:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.fragment.NavigationDrawerFragment" />

</android.support.v4.widget.DrawerLayout>

And here is main code of my activity :

public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }
}

The main problem here is : above code run smoothly on almost devices (stimulated device, or some real devices). But when I run it on Samsung S3. It notices this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4856)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
            at android.app.Activity.setContentView(Activity.java:1901)
            at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
            at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)

Please tell me how to fix error, thanks :)


问:
The input element's type ('email') does not support selection, Ionic v6
i have this error that triggers as soon as there is a change in my ion-input.

I can change the type with 'text' to fix the problem but then the autocomplete email is not functional.

Thank you for your answers !

Error:

```<code>index-06cd27b1.js:1986 DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('email') does not support selection.
    at Input.valueChanged (http://localhost:4200/node_modules_ionic_core_dist_esm_ion-input_entry_js.js:236:24)
</code>```

Code :

```<code>     <ion-item>
            <ion-label position="floating">
              <ion-icon name="mail-outline"></ion-icon>
              Your email</ion-label
            >
            <ion-input
              type="email"
              autocomplete="email"
              placeholder="my-mail@gmail.com"
              [formControlName]="'email'"
            >
            </ion-input>
          </ion-item>
</code>```

Version:
"@ionic/angular": "6.0.7",
Angular : "^13.1.4"

答:
I had the same issue starting today: @ionic/angular@6.0.2, Angular@13.2.2.

This is a known bug, you can check out the issue here. As stated in the thread, there's a dev version of the package you can use as a temp fix before 6.0.8 is released. It worked perfectly for me.

```<code>@ionic/angular@6.0.8-dev.1644430127.1b9bb92
</code>```

Body:
i have this error that triggers as soon as there is a change in my ion-input.

I can change the type with 'text' to fix the problem but then the autocomplete email is not functional.

Thank you for your answers !

Error:

index-06cd27b1.js:1986 DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('email') does not support selection.
    at Input.valueChanged (http://localhost:4200/node_modules_ionic_core_dist_esm_ion-input_entry_js.js:236:24)

Code :

     <ion-item>
            <ion-label position="floating">
              <ion-icon name="mail-outline"></ion-icon>
              Your email</ion-label
            >
            <ion-input
              type="email"
              autocomplete="email"
              placeholder="my-mail@gmail.com"
              [formControlName]="'email'"
            >
            </ion-input>
          </ion-item>

Version:
"@ionic/angular": "6.0.7",
Angular : "^13.1.4"

Body:
I had the same issue starting today: @ionic/angular@6.0.2, Angular@13.2.2.

This is a known bug, you can check out the issue here. As stated in the thread, there's a dev version of the package you can use as a temp fix before 6.0.8 is released. It worked perfectly for me.

@ionic/angular@6.0.8-dev.1644430127.1b9bb92


问:
How to implement a nonblocking future processor in Java in order to retrieve processed results later
I am using an external library that has the code from below.  I am sending a lot of commands and am interesed in the result for statistics to check how many calls failed and how many succeeded

```<code>public Future<CommandResult> sendCommand(Command command) {
    return command.execute();
}
CommandResult can be success or failure
</code>```

However, if I use client.sendCommand(command).get(); then, I am waiting for the result synchronously, meanwhile the app is being blocked.

I would like to check only later (after 30 seconds which calls succeded and which failed). I am guaranteed to get an answer in 10 seconds.
The problem is that the app waits for the computation to complete, and then retrieves its result.

I was thinking about this approach based on the answers:

```<code>List<Future< CommandResult >> futures = new ArrayList<>();
for(Command command: commands) {
   futures.add(client.sendCommand(command));
}

//in a scheduler, 30+ seconds later
for (Future<Boolean> future : futures) {
   saveResult(future.get());
}
</code>```

答:
Future is a legacy java feature which does not allow for reactive non blocking functionalities. The CompletableFuture is a later enhancement in Java in order to allow such reactive non blocking functionalities.

You can based on this previous SO answer try to convert your Future into a CompletableFuture and then you will have methods exposed to take advantage of non blocking execution.

Check the following example and modify accordingly.

```<code>public class Application {

    public static void main(String[] args) throws ParseException {

        Future future =  new SquareCalculator().calculate(10);
        CompletableFuture<Integer> completableFuture = makeCompletableFuture(future);
        System.out.println("before apply");
        completableFuture.thenApply(s -> {
            System.out.println(s);
            return s;
        });
        System.out.println("after apply method");
    }

    public static <T> CompletableFuture<T> makeCompletableFuture(Future<T> future) {
        if (future.isDone())
            return transformDoneFuture(future);
        return CompletableFuture.supplyAsync(() -> {
            try {
                if (!future.isDone())
                    awaitFutureIsDoneInForkJoinPool(future);
                return future.get();
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                // Normally, this should never happen inside ForkJoinPool
                Thread.currentThread().interrupt();
                // Add the following statement if the future doesn't have side effects
                // future.cancel(true);
                throw new RuntimeException(e);
            }
        });
    }

    private static <T> CompletableFuture<T> transformDoneFuture(Future<T> future) {
        CompletableFuture<T> cf = new CompletableFuture<>();
        T result;
        try {
            result = future.get();
        } catch (Throwable ex) {
            cf.completeExceptionally(ex);
            return cf;
        }
        cf.complete(result);
        return cf;
    }

    private static void awaitFutureIsDoneInForkJoinPool(Future<?> future)
            throws InterruptedException {
        ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() {
            @Override public boolean block() throws InterruptedException {
                try {
                    future.get();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }
                return true;
            }
            @Override public boolean isReleasable() {
                return future.isDone();
            }
        });
    }
}
</code>```

And then the class to create an example Future

```<code>public class SquareCalculator {

    private ExecutorService executor
            = Executors.newSingleThreadExecutor();

    public Future<Integer> calculate(Integer input) {
        return executor.submit(() -> {
            Thread.sleep(1000);
            return input * input;
        });
    }
}
</code>```

Will result into

Body:
I am using an external library that has the code from below.  I am sending a lot of commands and am interesed in the result for statistics to check how many calls failed and how many succeeded

public Future<CommandResult> sendCommand(Command command) {
    return command.execute();
}
CommandResult can be success or failure

However, if I use client.sendCommand(command).get(); then, I am waiting for the result synchronously, meanwhile the app is being blocked.

I would like to check only later (after 30 seconds which calls succeded and which failed). I am guaranteed to get an answer in 10 seconds.
The problem is that the app waits for the computation to complete, and then retrieves its result.

I was thinking about this approach based on the answers:

List<Future< CommandResult >> futures = new ArrayList<>();
for(Command command: commands) {
   futures.add(client.sendCommand(command));
}

//in a scheduler, 30+ seconds later
for (Future<Boolean> future : futures) {
   saveResult(future.get());
}

Body:
Future is a legacy java feature which does not allow for reactive non blocking functionalities. The CompletableFuture is a later enhancement in Java in order to allow such reactive non blocking functionalities.

You can based on this previous SO answer try to convert your Future into a CompletableFuture and then you will have methods exposed to take advantage of non blocking execution.

Check the following example and modify accordingly.

public class Application {

    public static void main(String[] args) throws ParseException {

        Future future =  new SquareCalculator().calculate(10);
        CompletableFuture<Integer> completableFuture = makeCompletableFuture(future);
        System.out.println("before apply");
        completableFuture.thenApply(s -> {
            System.out.println(s);
            return s;
        });
        System.out.println("after apply method");
    }

    public static <T> CompletableFuture<T> makeCompletableFuture(Future<T> future) {
        if (future.isDone())
            return transformDoneFuture(future);
        return CompletableFuture.supplyAsync(() -> {
            try {
                if (!future.isDone())
                    awaitFutureIsDoneInForkJoinPool(future);
                return future.get();
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                // Normally, this should never happen inside ForkJoinPool
                Thread.currentThread().interrupt();
                // Add the following statement if the future doesn't have side effects
                // future.cancel(true);
                throw new RuntimeException(e);
            }
        });
    }

    private static <T> CompletableFuture<T> transformDoneFuture(Future<T> future) {
        CompletableFuture<T> cf = new CompletableFuture<>();
        T result;
        try {
            result = future.get();
        } catch (Throwable ex) {
            cf.completeExceptionally(ex);
            return cf;
        }
        cf.complete(result);
        return cf;
    }

    private static void awaitFutureIsDoneInForkJoinPool(Future<?> future)
            throws InterruptedException {
        ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() {
            @Override public boolean block() throws InterruptedException {
                try {
                    future.get();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }
                return true;
            }
            @Override public boolean isReleasable() {
                return future.isDone();
            }
        });
    }
}

And then the class to create an example Future

public class SquareCalculator {

    private ExecutorService executor
            = Executors.newSingleThreadExecutor();

    public Future<Integer> calculate(Integer input) {
        return executor.submit(() -> {
            Thread.sleep(1000);
            return input * input;
        });
    }
}

Will result into


问:
Sending Attachment to SAP B1 remote Service Layer
In a C# application, I want to send files to "remote SAP B1 service layer". I have tried many ways to send an attachment to this remote service layer, using their b1s/v1/Attachments2 endpoint, but I continuously receive an error "A file with this name already exists.  [Attachments2_Lines.FileName][line: 1], ". Even this file does not exists in the service layer shared directory.
Moreover, I do have the read/write permissions in the destination path.

Any Kind of help will be highly appreciated.

答:
I had a similiar issue when adding attachments to a document. Try to send a GET and retrieve all records for /Attachments2. If the file was added before there might already exist a record having the same filename.

To add it again, you need to call a DELETE on the specific ID first, then POST it again.


问:
Do ASP.NET Core and MSAL handle “state” or “nonce” parameters or must developers handle them manually?
I am learning that there is a big emphasis on “state” or “nonce” parameters:

Difference between OAuth 2.0 "state" and OpenID "nonce" parameter? Why state could not be reused?

At the same time, I understand that Microsoft recommend using MSAL and ASP.NET Core that properly and securely handle Azure AD and B2C protocols.

Do ASP.NET Core and MSAL handles “state” or “nonce” parameters or must developers handle them manually?

I am asking since I don't want to spend efforts to do something that is done better in MSAL.

答: They are automatically handled, by all our supported platforms (.net, java, ios, android, javascript, xamarin).</p>


问:
Azure Java SDK - how to retrieve RBAC roles of an User
We have a requirement to check the Authorization permissions of an User before executing business logic. I am not able to find an example or tutorial to retrieve the Roles of an User, using Azure Java SDK.</p>

答:
We have Rest API by which we can retrieve all roles assigned to a subscription. Using HTTP request we can retrieve all the role assignments and then we can search for user

Code:

```<code>String api = "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01" ;
// Here substitute the SubstriptionID
System._out_.println( "Hello World!" );
HttpClient client = HttpClient._newHttpClient_();
HttpRequest request = HttpRequest._newBuilder_()
.GET()
.uri(URI._create_(api))
.build();
HttpResponse<String> response = client.send(request , HttpResponse.BodyHandlers._ofString_());
System._out_.print(response.body());

// The following the has to parsed to find whether the user is present or not
</code>```

Here are the few related Microsoft Documents for complete information.

Role Assignments - List - REST API (Azure Authorization) | Microsoft Docs

Use the Azure SDK for Java | Microsoft Docs

Body:
We have Rest API by which we can retrieve all roles assigned to a subscription. Using HTTP request we can retrieve all the role assignments and then we can search for user

Code:

String api = "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01" ;
// Here substitute the SubstriptionID
System._out_.println( "Hello World!" );
HttpClient client = HttpClient._newHttpClient_();
HttpRequest request = HttpRequest._newBuilder_()
.GET()
.uri(URI._create_(api))
.build();
HttpResponse<String> response = client.send(request , HttpResponse.BodyHandlers._ofString_());
System._out_.print(response.body());

// The following the has to parsed to find whether the user is present or not

Here are the few related Microsoft Documents for complete information.

Role Assignments - List - REST API (Azure Authorization) | Microsoft Docs

Use the Azure SDK for Java | Microsoft Docs