问:
paintComponent() and paint() - drawing JButton with decorator pattern
I found a decorator pattern example with Swing component. The following code is drawing three buttons on a JFrame. One of the button has slash on it and implemented with Decorator pattern. The original one has paint() method, but I replaced paint() with paintComponent(Graphics g), then it fails to draw lines on the button. Is it impossible to use paintComponent() instead of paint()? If possible how to do that? What is the problem of this trial? What I am missing?

Original code link is Decorator pattern in Java.

```<code>public class DecoWindow extends JFrame implements ActionListener {
    JButton Quit;

    public DecoWindow() {
        super("Deco Button");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel jp = new JPanel();

        getContentPane().add(jp);
        jp.add(new CoolDDecorator(new JButton("Cbutton")));
        jp.add(new SlashDDecorator(new CoolDDecorator(new JButton("Dbutton"))));
        jp.add(Quit = new JButton("Quit"));
        Quit.addActionListener(this);
        setSize(new Dimension(200, 100));
        setVisible(true);
        Quit.requestFocus();
    }

    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }

    public static void main(String argv[]) {
        new DecoWindow();
    }
}

class DDecorator extends JComponent {
    public DDecorator(JComponent c) {
        setLayout(new BorderLayout());
        add("Center", c);
    }
}

class SlashDDecorator extends DDecorator {
    int x1, y1, w1, h1;

    public SlashDDecorator(JComponent c) {
        super(c);
    }

    public void setBounds(int x, int y, int w, int h) {
          x1 = x; y1 = y;
          w1 = w; h1 = h;
          super.setBounds(x, y, w, h);
    }

    public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g;
          g2d.setColor(Color.red);
          g2d.drawLine(0, 0, w1, h1);
    }
}

class CoolDDecorator extends DDecorator {
    boolean mouse_over; //true when mose over button

    JComponent thisComp;

    public CoolDDecorator(JComponent c) {
        super(c);
        mouse_over = false;
        thisComp = this; //save this component
        //catch mouse movements in inner class
        c.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                mouse_over = true; //set flag when mouse over
                thisComp.repaint();
            }

            public void mouseExited(MouseEvent e) {
                mouse_over = false; //clear flag when mouse not over
                thisComp.repaint();
            }
        });
    }

    //paint the button
    public void paintComponent(Graphics g) {
        super.paintComponent(g); //first draw the parent button
        Graphics2D g2d = (Graphics2D) g;

        //if the mouse is not over the button
        //erase the borders
        if (!mouse_over) {
            Dimension size = super.getSize();
            g2d.setColor(Color.lightGray);
            g2d.drawRect(0, 0, size.width - 1, size.height - 1);
            g2d.drawLine(size.width - 2, 0, size.width - 2, size.height - 1);
            g2d.drawLine(0, size.height - 2, size.width - 2, size.height - 2);
        }
    }
}
</code>```

答:
paint() calls paintComponent() then paintChildren(). Your component is painting the slash and returning from paintComponent(). Then the default paint() implementation moves on, eventually painting the children, which are those buttons, which then just paint right ontop of your slash.

Your IDE should let you place a breakpoint in your paint code. You can check the callstack to see what's going on. If you aren't using an IDE, you can look at what Swing is doing by looking at JComponent.java in src.zip within your JDK.

Why do you want to use paintComponent() anyway?

Body:
I found a decorator pattern example with Swing component. The following code is drawing three buttons on a JFrame. One of the button has slash on it and implemented with Decorator pattern. The original one has paint() method, but I replaced paint() with paintComponent(Graphics g), then it fails to draw lines on the button. Is it impossible to use paintComponent() instead of paint()? If possible how to do that? What is the problem of this trial? What I am missing?

Original code link is Decorator pattern in Java.

public class DecoWindow extends JFrame implements ActionListener {
    JButton Quit;

    public DecoWindow() {
        super("Deco Button");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel jp = new JPanel();

        getContentPane().add(jp);
        jp.add(new CoolDDecorator(new JButton("Cbutton")));
        jp.add(new SlashDDecorator(new CoolDDecorator(new JButton("Dbutton"))));
        jp.add(Quit = new JButton("Quit"));
        Quit.addActionListener(this);
        setSize(new Dimension(200, 100));
        setVisible(true);
        Quit.requestFocus();
    }

    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }

    public static void main(String argv[]) {
        new DecoWindow();
    }
}

class DDecorator extends JComponent {
    public DDecorator(JComponent c) {
        setLayout(new BorderLayout());
        add("Center", c);
    }
}

class SlashDDecorator extends DDecorator {
    int x1, y1, w1, h1;

    public SlashDDecorator(JComponent c) {
        super(c);
    }

    public void setBounds(int x, int y, int w, int h) {
          x1 = x; y1 = y;
          w1 = w; h1 = h;
          super.setBounds(x, y, w, h);
    }

    public void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2d = (Graphics2D) g;
          g2d.setColor(Color.red);
          g2d.drawLine(0, 0, w1, h1);
    }
}

class CoolDDecorator extends DDecorator {
    boolean mouse_over; //true when mose over button

    JComponent thisComp;

    public CoolDDecorator(JComponent c) {
        super(c);
        mouse_over = false;
        thisComp = this; //save this component
        //catch mouse movements in inner class
        c.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                mouse_over = true; //set flag when mouse over
                thisComp.repaint();
            }

            public void mouseExited(MouseEvent e) {
                mouse_over = false; //clear flag when mouse not over
                thisComp.repaint();
            }
        });
    }

    //paint the button
    public void paintComponent(Graphics g) {
        super.paintComponent(g); //first draw the parent button
        Graphics2D g2d = (Graphics2D) g;

        //if the mouse is not over the button
        //erase the borders
        if (!mouse_over) {
            Dimension size = super.getSize();
            g2d.setColor(Color.lightGray);
            g2d.drawRect(0, 0, size.width - 1, size.height - 1);
            g2d.drawLine(size.width - 2, 0, size.width - 2, size.height - 1);
            g2d.drawLine(0, size.height - 2, size.width - 2, size.height - 2);
        }
    }
}


来源: stackexchange

问:
if database table exists then delete it, and create one new with custom fields
step by step i try to write my VBA program in .net

there are one short description of how program run,
the user selects one folder with some files with the goods stock from inventory (usually he can find 3 files, one for each the last 3 year, but is possible that the year file was 2).
the xls file has 4 columns (article code, description, quantity, total value)

In VBA I add one sheet and I copy the contents off each file into
this new sheet starting from column 2 ("B") in the 1st column ("A") I
write the corresponding year.

In .net I already wrote the code to import each file, in this case I've one mdf database and one specific table.

then in the second case I've one table with 5 fields year, codart, descr, quantity, value.

so:

in VBA I count DISTINCT year and with ADODB I create one dynamic across query, I use codart,descr as table rows and alla year found like a columns (quantity + yr, value + yr) then this is result:

In .net I know how to count number of years imported, so I need a table with the necessary fields. I googled, asked Here and everywhere about how to do it, but each example that I find is how to add one mdf table from Visual Studio (Sql Server Object explorer) but I need to crete this new table by code programmatically.

can someone guide me to do this?

答:
Take the table test in LocalDatabase as an example:

The result:

You can try my code as follows:

```<code>Imports System.Data.SqlClient

Public Class Form1
    Public constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= D:\Database\Local Database\julietest0602.mdf"
    Public conn As SqlConnection
    Public sda As SqlDataAdapter
    Public cmd As SqlCommand
    Public dt As New DataTable
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using conn = New SqlConnection(constr)
            conn.Open()
            cmd = New SqlCommand("IF EXISTS(Select * From sysobjects Where Name='test') drop table test", conn)
            cmd.ExecuteNonQuery()
            MsgBox("Delete OK!")

            cmd = New SqlCommand("CREATE TABLE test
                    ([CODPRO] NVARCHAR (50) Not NULL, [DESPRO] NVARCHAR (90) NOT NULL,
                    [2017quantity] FLOAT(53) NOT NULL, [2017value] FLOAT(53) NOT NULL,
                    [2018quantity] FLOAT(53) NOT NULL, [2018value] FLOAT(53) NOT NULL,
                    [2019quantity] FLOAT(53) NOT NULL, [2019value] FLOAT(53) NOT NULL)", conn)
            cmd.ExecuteNonQuery()
            MsgBox("Create OK!")

            cmd = New SqlCommand("Select * from test ", conn)
            sda = New SqlDataAdapter(cmd)
            Dim dt1 As New DataTable
            sda.Fill(dt1)
            DataGridView1.DataSource = dt1

        End Using
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Using conn = New SqlConnection(constr)
            conn.Open()
            cmd = New SqlCommand("Select * from test ", conn)
            sda = New SqlDataAdapter(cmd)
            Dim dt1 As New DataTable
            sda.Fill(dt1)
            DataGridView1.DataSource = dt1

        End Using
    End Sub
End Class
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Take the table test in LocalDatabase as an example:

The result:

You can try my code as follows:

Imports System.Data.SqlClient

Public Class Form1
    Public constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= D:\Database\Local Database\julietest0602.mdf"
    Public conn As SqlConnection
    Public sda As SqlDataAdapter
    Public cmd As SqlCommand
    Public dt As New DataTable
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using conn = New SqlConnection(constr)
            conn.Open()
            cmd = New SqlCommand("IF EXISTS(Select * From sysobjects Where Name='test') drop table test", conn)
            cmd.ExecuteNonQuery()
            MsgBox("Delete OK!")

            cmd = New SqlCommand("CREATE TABLE test
                    ([CODPRO] NVARCHAR (50) Not NULL, [DESPRO] NVARCHAR (90) NOT NULL,
                    [2017quantity] FLOAT(53) NOT NULL, [2017value] FLOAT(53) NOT NULL,
                    [2018quantity] FLOAT(53) NOT NULL, [2018value] FLOAT(53) NOT NULL,
                    [2019quantity] FLOAT(53) NOT NULL, [2019value] FLOAT(53) NOT NULL)", conn)
            cmd.ExecuteNonQuery()
            MsgBox("Create OK!")

            cmd = New SqlCommand("Select * from test ", conn)
            sda = New SqlDataAdapter(cmd)
            Dim dt1 As New DataTable
            sda.Fill(dt1)
            DataGridView1.DataSource = dt1

        End Using
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Using conn = New SqlConnection(constr)
            conn.Open()
            cmd = New SqlCommand("Select * from test ", conn)
            sda = New SqlDataAdapter(cmd)
            Dim dt1 As New DataTable
            sda.Fill(dt1)
            DataGridView1.DataSource = dt1

        End Using
    End Sub
End Class


问:
Showing "Forbidden" message when creating meetings MS Teams
I am trying to integrate ms teams API to my project. I have created an app in the Azure portal.I have added permissions User.ReadWriteAll and Meetings.ReadWriteAll.I can create a user through API but I am not able to create a meeting. Is there anything else I need to do for creating a meeting using API.

UPDATE
I gave delegated permission for creating the meeting,but unable to create the meeting.
Error Message

```<code>{code:"Forbidden",message:"Forbidden",innerError:{"request-id":"e1abb815-09d3-4b78-5063-39b0236c0968","Date":"2020-06-09T04:14:39"}}
</code>```

Permissions
Screenshot of permission

答:
It depends on whether there is user interaction.

If you are get access on behalf of a userhere,follow this way app-user,just add delegated permission OnlineMeetings.ReadWrite.please check

If you get access without a userhere,follow this way app-only,just add application permission OnlineMeetings.ReadWrite.All.(Please note that this  method can only use beta version  https://graph.microsot.com/beta).please check beta version

Update:

Body:
I am trying to integrate ms teams API to my project. I have created an app in the Azure portal.I have added permissions User.ReadWriteAll and Meetings.ReadWriteAll.I can create a user through API but I am not able to create a meeting. Is there anything else I need to do for creating a meeting using API.

UPDATE
I gave delegated permission for creating the meeting,but unable to create the meeting.
Error Message

{code:"Forbidden",message:"Forbidden",innerError:{"request-id":"e1abb815-09d3-4b78-5063-39b0236c0968","Date":"2020-06-09T04:14:39"}}

Permissions
Screenshot of permission


问:
Blazor server side - redirecting if unauthenticated before the page starts loading
Might be trying to solve this the wrong way, but here's the situation.

I have a component designed to redirect to login if the user trying to access it isn't authenticated, and display not found if they aren't authorized for the page requested.

```<code><AuthorizeViewWithPermissions RequiredPermission="RequiredPermission">
    <Authorized>
        @ChildContent
    </Authorized>
    <NotAuthenticated>
        <LoginRedirect />
    </NotAuthenticated>
    <NotAuthorized>
        <NotFoundRedirect />
    </NotAuthorized>
</AuthorizeViewWithPermissions>

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter] public Permissions RequiredPermission { get; set; }

    protected override void OnInitialized()
    {

    }
}
</code>```

LoginRedirect is this:

```<code>    public class LoginRedirect : ComponentBase
    {
        [Inject] protected NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            NavigationManager.NavigateTo("/Login", true);
        }
    }
</code>```

internals of AuthorizeViewWithPermissions:

```<code>    /// <summary>
    /// Largely borrowed from the original AuthorizeView, but cut up a bit to use custom permissions and cut out a lot of stuff that isn't needed.
    /// </summary>
    public class AuthorizeViewWithPermissions : ComponentBase
    {
        private AuthenticationState _currentAuthenticationState;

        private bool _isAuthorized;

        private bool _isAuthenticated;

        /// <summary>
        /// The permission type required to display the content
        /// </summary>
        [Parameter] public Permissions RequiredPermission { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is authorized.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> ChildContent { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is not authorized.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> NotAuthorized { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is not authenticated.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> NotAuthenticated { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is authorized.
        /// If you specify a value for this parameter, do not also specify a value for <see cref="ChildContent"/>.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> Authorized { get; set; }

        /// <summary>
        /// The content that will be displayed while asynchronous authorization is in progress.
        /// </summary>
        [Parameter] public RenderFragment Authorizing { get; set; }

        /// <summary>
        /// The resource to which access is being controlled.
        /// </summary>
        [Parameter] public object Resource { get; set; }

        [CascadingParameter] private Task<AuthenticationState> AuthenticationState { get; set; }

        /// <inheritdoc />
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            // We're using the same sequence number for each of the content items here
            // so that we can update existing instances if they are the same shape
            if (_currentAuthenticationState == null)
            {
                builder.AddContent(0, Authorizing);
            }
            else if (_isAuthorized)
            {
                var authorized = Authorized ?? ChildContent;
                builder.AddContent(0, authorized?.Invoke(_currentAuthenticationState));
            }
            else if (!_isAuthenticated)
            {
                builder.AddContent(0, NotAuthenticated?.Invoke(_currentAuthenticationState));
            }
            else
            {
                builder.AddContent(0, NotAuthorized?.Invoke(_currentAuthenticationState));
            }
        }

        /// <inheritdoc />
        protected override async Task OnParametersSetAsync()
        {
            // We allow 'ChildContent' for convenience in basic cases, and 'Authorized' for symmetry
            // with 'NotAuthorized' in other cases. Besides naming, they are equivalent. To avoid
            // confusion, explicitly prevent the case where both are supplied.
            if (ChildContent != null && Authorized != null)
            {
                throw new InvalidOperationException($"Do not specify both '{nameof(Authorized)}' and '{nameof(ChildContent)}'.");
            }

            if (AuthenticationState == null)
            {
                throw new InvalidOperationException($"Authorization requires a cascading parameter of type Task<{nameof(AuthenticationState)}>. Consider using {typeof(CascadingAuthenticationState).Name} to supply this.");
            }

            // First render in pending state
            // If the task has already completed, this render will be skipped
            _currentAuthenticationState = null;

            // Then render in completed state
            // Importantly, we *don't* call StateHasChanged between the following async steps,
            // otherwise we'd display an incorrect UI state while waiting for IsAuthorizedAsync
            _currentAuthenticationState = await AuthenticationState;
            SetAuthorizedAndAuthenticated(_currentAuthenticationState.User);
        }

        private void SetAuthorizedAndAuthenticated(ClaimsPrincipal user)
        {
            var userWithData = SessionHelper.GetCurrentUser(user);

            _isAuthenticated = userWithData != null;
            _isAuthorized = userWithData?.Permissions.Any(p => p == RequiredPermission || p == Permissions.SuperAdmin) ?? false;
        }
    }
</code>```

The authentication and authorization checks are working perfectly fine, but the issue is that the page OnInitializedAsync or OnParametersSetAsync fire before the LoginRedirect OnInitialized.

I'm kicking off my calls for data (to an API, that uses a token stored on the logged in user's data) in OnInitializedAsync which results in it attempting to load the data (with no auth token) instead of just redirecting.  If I comment out the data call the redirect works as expected without issue, so it's just a timing/sequence of events issue.

Is there a solution to this? Should I just be changing my api client code to silently fail instead of throwing an unauthorized exception if the auth token is missing?

This is also my app.razor component:

```<code>CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <LoginRedirect />
                </NotAuthorized>
                <Authorizing>
                    <p>Checking authorization...</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>These aren't the droids you're looking for.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
</code>```

答:
Simply check if you have a user before the call to the api:

@inject AuthenticationStateProvider AuthenticationStateProvider

...

@code {
    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (!user.Identity.IsAuthenticated)
        {
            return;
        }
    }
}
```

doc

Body:
Might be trying to solve this the wrong way, but here's the situation.

I have a component designed to redirect to login if the user trying to access it isn't authenticated, and display not found if they aren't authorized for the page requested.

<AuthorizeViewWithPermissions RequiredPermission="RequiredPermission">
    <Authorized>
        @ChildContent
    </Authorized>
    <NotAuthenticated>
        <LoginRedirect />
    </NotAuthenticated>
    <NotAuthorized>
        <NotFoundRedirect />
    </NotAuthorized>
</AuthorizeViewWithPermissions>

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter] public Permissions RequiredPermission { get; set; }

    protected override void OnInitialized()
    {

    }
}

LoginRedirect is this:

    public class LoginRedirect : ComponentBase
    {
        [Inject] protected NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            NavigationManager.NavigateTo("/Login", true);
        }
    }

internals of AuthorizeViewWithPermissions:

    ///
    /// Largely borrowed from the original AuthorizeView, but cut up a bit to use custom permissions and cut out a lot of stuff that isn't needed.
    ///
    public class AuthorizeViewWithPermissions : ComponentBase
    {
        private AuthenticationState _currentAuthenticationState;

        private bool _isAuthorized;

        private bool _isAuthenticated;

        ///
        /// The permission type required to display the content
        ///
        [Parameter] public Permissions RequiredPermission { get; set; }

        ///
        /// The content that will be displayed if the user is authorized.
        ///
        [Parameter] public RenderFragment<AuthenticationState> ChildContent { get; set; }

        ///
        /// The content that will be displayed if the user is not authorized.
        ///
        [Parameter] public RenderFragment<AuthenticationState> NotAuthorized { get; set; }

        ///
        /// The content that will be displayed if the user is not authenticated.
        ///
        [Parameter] public RenderFragment<AuthenticationState> NotAuthenticated { get; set; }

        ///
        /// The content that will be displayed if the user is authorized.
        /// If you specify a value for this parameter, do not also specify a value for <see cref="ChildContent"/>.
        ///
        [Parameter] public RenderFragment<AuthenticationState> Authorized { get; set; }

        ///
        /// The content that will be displayed while asynchronous authorization is in progress.
        ///
        [Parameter] public RenderFragment Authorizing { get; set; }

        ///
        /// The resource to which access is being controlled.
        ///
        [Parameter] public object Resource { get; set; }

        [CascadingParameter] private Task<AuthenticationState> AuthenticationState { get; set; }

        /// <inheritdoc />
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            // We're using the same sequence number for each of the content items here
            // so that we can update existing instances if they are the same shape
            if (_currentAuthenticationState == null)
            {
                builder.AddContent(0, Authorizing);
            }
            else if (_isAuthorized)
            {
                var authorized = Authorized ?? ChildContent;
                builder.AddContent(0, authorized?.Invoke(_currentAuthenticationState));
            }
            else if (!_isAuthenticated)
            {
                builder.AddContent(0, NotAuthenticated?.Invoke(_currentAuthenticationState));
            }
            else
            {
                builder.AddContent(0, NotAuthorized?.Invoke(_currentAuthenticationState));
            }
        }

        /// <inheritdoc />
        protected override async Task OnParametersSetAsync()
        {
            // We allow 'ChildContent' for convenience in basic cases, and 'Authorized' for symmetry
            // with 'NotAuthorized' in other cases. Besides naming, they are equivalent. To avoid
            // confusion, explicitly prevent the case where both are supplied.
            if (ChildContent != null && Authorized != null)
            {
                throw new InvalidOperationException($"Do not specify both '{nameof(Authorized)}' and '{nameof(ChildContent)}'.");
            }

            if (AuthenticationState == null)
            {
                throw new InvalidOperationException($"Authorization requires a cascading parameter of type Task<{nameof(AuthenticationState)}>. Consider using {typeof(CascadingAuthenticationState).Name} to supply this.");
            }

            // First render in pending state
            // If the task has already completed, this render will be skipped
            _currentAuthenticationState = null;

            // Then render in completed state
            // Importantly, we *don't* call StateHasChanged between the following async steps,
            // otherwise we'd display an incorrect UI state while waiting for IsAuthorizedAsync
            _currentAuthenticationState = await AuthenticationState;
            SetAuthorizedAndAuthenticated(_currentAuthenticationState.User);
        }

        private void SetAuthorizedAndAuthenticated(ClaimsPrincipal user)
        {
            var userWithData = SessionHelper.GetCurrentUser(user);

            _isAuthenticated = userWithData != null;
            _isAuthorized = userWithData?.Permissions.Any(p => p == RequiredPermission || p == Permissions.SuperAdmin) ?? false;
        }
    }

The authentication and authorization checks are working perfectly fine, but the issue is that the page OnInitializedAsync or OnParametersSetAsync fire before the LoginRedirect OnInitialized.

I'm kicking off my calls for data (to an API, that uses a token stored on the logged in user's data) in OnInitializedAsync which results in it attempting to load the data (with no auth token) instead of just redirecting.  If I comment out the data call the redirect works as expected without issue, so it's just a timing/sequence of events issue.

Is there a solution to this? Should I just be changing my api client code to silently fail instead of throwing an unauthorized exception if the auth token is missing?

This is also my app.razor component:

CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <LoginRedirect />
                </NotAuthorized>
                <Authorizing>

Checking authorization...

                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">

These aren't the droids you're looking for.

            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

Body:
Simply check if you have a user before the call to the api:

@inject AuthenticationStateProvider AuthenticationStateProvider

...

@code {
    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (!user.Identity.IsAuthenticated)
        {
            return;
        }
    }
}

doc


问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答:
You could also change [[NSDictionary alloc] initWithObjectsAndKeys:] to [NSDictionary dictionaryWithObjectsAndKeys:].

This would be a good idea anyway, since your code is allocating an NSDictionary without releasing it. -dictionaryWithObjectsAndKeys: returns an autoreleased dictionary.

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

OwnerDisplayName: Matt Ball


问:
What's the official way of storing settings for Python programs?
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information.

Are one of these approaches blessed by Guido and/or the Python community more than another?

答:
I use a shelf ( http://docs.python.org/library/shelve.html ):</p>

```<code>shelf = shelve.open(filename)
shelf["users"] = ["David", "Abraham"]
shelf.sync() # Save
</code>```

Body:
I use a shelf ( http://docs.python.org/library/shelve.html ):

shelf = shelve.open(filename)
shelf["users"] = ["David", "Abraham"]
shelf.sync() # Save

ContentLicense: CC BY-SA 3.0


问:
Refresh Datatable on Insert Item
I'm a newbie.

I am using ngx-datatable.

Is there a way to refresh the UI View of the ngx-datatable.

Like rerender everything

Please see screenshot.

Thanks,

pOng

答:
the fix on my issue is

@ViewChild(DatatableComponent, { static: false }) table: DatatableComponent;
 this.table.recalculate()

also please refer to this link
https://github.com/swimlane/ngx-datatable/issues/1733

Title: Refresh Datatable on Insert Item


问:
AWS Cloudformation: How to use username as a tag
I need to create a Cloudformation Script for an ec2 instance which should have tags specifying among other things, the aws username of the person who ran the script to create the instance. What is the variable name to get the IAM Username? The tagging part of my script is shown below. Whereas the AccountId can be retrieved, I'm unable to get the username. </p>

```<code>    Tags:
    - Key: Name
      Value: !Ref InstanceName
    - Key: team
      Value: !Ref Team
    - Key: awsAccount
      Value: !Sub ${AWS::AccountId}
    - Key: userName
      Value: !Sub ${AWS::IAM::User}
    - Key: purpose
      Value: !Ref Purpose
</code>```

答:
Unfortunately there is no such pseudo parameter in CloudFormation. The list of all available parameters, such as AWS::AccountId is here.

One way around this is to create a parameter for your CloudFormation template (as you do with Purpose or team), e.g.

```<code>Parameters:
    UserName:
      Type: String
</code>```

and reference it in your Tags:

```<code>- Key: userName
  Value: !Ref UserName
</code>```

Body:
I need to create a Cloudformation Script for an ec2 instance which should have tags specifying among other things, the aws username of the person who ran the script to create the instance. What is the variable name to get the IAM Username? The tagging part of my script is shown below. Whereas the AccountId can be retrieved, I'm unable to get the username.

    Tags:
    - Key: Name
      Value: !Ref InstanceName
    - Key: team
      Value: !Ref Team
    - Key: awsAccount
      Value: !Sub ${AWS::AccountId}
    - Key: userName
      Value: !Sub ${AWS::IAM::User}
    - Key: purpose
      Value: !Ref Purpose

Body:
Unfortunately there is no such pseudo parameter in CloudFormation. The list of all available parameters, such as AWS::AccountId is here.

One way around this is to create a parameter for your CloudFormation template (as you do with Purpose or team), e.g.

Parameters:
    UserName:
      Type: String

and reference it in your Tags:

- Key: userName
  Value: !Ref UserName


问:
Error: Unable to determine the current character, it is not a string, number, array, or object in react-native for android
Whenever I run react-native run-android while keeping the emulator running, I get this error. react-native run-ios wroks completely fine.

```<code>Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
:ReactNative:Failed to parse React Native CLI configuration: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is 'E' with an int value of 69
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Error: Invalid attribute nameLine: 16Column: 18Char: .    at error (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:651:10)    at strictFail (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:677:7)    at SAXParser.write (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:1313:13)    at new XmlDocument (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/xmldoc/lib/xmldoc.js:261:15)    at readManifest (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/readManifest.js:38:10)    at Object.projectConfig (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/index.js:59:46)    at Object.get project [as project] (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/tools/config/index.js:114:50)    at /Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:452    at Array.forEach (<anonymous>)    at _objectSpread (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:392)
^

FAILURE: Build failed with an exception.

* Where:
Script '/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 201

* What went wrong:
A problem occurred evaluating script.
> Failed to parse React Native CLI configuration. Expected running 'npx --quiet --no-install react-native config' command from '/Users/yashatreya/Desktop/Realyze/Realyze' directory to output valid JSON, but it didn't. This may be caused by npx resolving to a legacy global react-native binary. Please make sure to uninstall any global 'react-native' binaries: 'npm uninstall -g react-native react-native-cli' and try again

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

</code>```

As indicated in the error message, I tried running npm uninstall -g react-native react-native-cli but it didn’t work.

Info about my environment:

```<code>System:
    OS: macOS 10.15
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
    Memory: 29.68 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 12.13.0 - /usr/local/bin/node
    Yarn: 1.19.1 - /usr/local/bin/yarn
    npm: 6.12.0 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.0, DriverKit 19.0, macOS 10.15, tvOS 13.0, watchOS 6.0
  IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.5977832
    Xcode: 11.0/11A420a - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: ^0.61.4 => 0.61.4
  npmGlobalPackages:
    react-native-cli: 2.0.1
</code>```

android/app/build.gradle below:

```<code>apply plugin: "com.android.application"

import com.android.build.OutputFile
project.ext.react = [
    entryFile: "index.js",
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.realyze"
        minSdkVersion 21
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    // rootProject.ext.minSdkVersion
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation project(':react-native-push-notification')
    implementation project(':react-native-sound')
    implementation project(':react-native-audio')
    implementation 'com.android.support:multidex:2.0.1'
    implementation project(':react-native-gesture-handler')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
    implementation 'com.google.firebase:firebase-auth:19.1.0'
    implementation project(path: ":@react-native-firebase_auth")
    implementation project(path: ":@react-native-firebase_messaging")
    implementation project(path: ":@react-native-firebase_database")
    implementation project(':react-native-datetimepicker')
    implementation project(path: ":@react-native-firebase_firestore")
    implementation project(path: ":@react-native-firebase_functions")
}

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
// }

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
</code>```

android/build.gradle below :

```<code>
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.4.2"
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}
</code>```

Initially I was getting this error: react-native build error: Could not find method implementation() for arguments [jscFlavor] on project ':app' of type org.gradle.api.Project but now I am getting the above.

答: Deleting the node_modules folder and running npm install again worked for me

Body:
Whenever I run react-native run-android while keeping the emulator running, I get this error. react-native run-ios wroks completely fine.

Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
:ReactNative:Failed to parse React Native CLI configuration: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is 'E' with an int value of 69
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Error: Invalid attribute nameLine: 16Column: 18Char: .    at error (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:651:10)    at strictFail (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:677:7)    at SAXParser.write (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/sax/lib/sax.js:1313:13)    at new XmlDocument (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/xmldoc/lib/xmldoc.js:261:15)    at readManifest (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/readManifest.js:38:10)    at Object.projectConfig (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/build/config/index.js:59:46)    at Object.get project [as project] (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/tools/config/index.js:114:50)    at /Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:452    at Array.forEach (<anonymous>)    at _objectSpread (/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/config/config.js:8:392)
^

FAILURE: Build failed with an exception.

* Where:
Script '/Users/yashatreya/Desktop/Realyze/Realyze/node_modules/@react-native-community/cli-platform-android/native_modules.gradle' line: 201

* What went wrong:
A problem occurred evaluating script.
> Failed to parse React Native CLI configuration. Expected running 'npx --quiet --no-install react-native config' command from '/Users/yashatreya/Desktop/Realyze/Realyze' directory to output valid JSON, but it didn't. This may be caused by npx resolving to a legacy global react-native binary. Please make sure to uninstall any global 'react-native' binaries: 'npm uninstall -g react-native react-native-cli' and try again

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

As indicated in the error message, I tried running npm uninstall -g react-native react-native-cli but it didn’t work.

Info about my environment:

System:
    OS: macOS 10.15
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
    Memory: 29.68 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 12.13.0 - /usr/local/bin/node
    Yarn: 1.19.1 - /usr/local/bin/yarn
    npm: 6.12.0 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.0, DriverKit 19.0, macOS 10.15, tvOS 13.0, watchOS 6.0
  IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.5977832
    Xcode: 11.0/11A420a - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0
    react-native: ^0.61.4 => 0.61.4
  npmGlobalPackages:
    react-native-cli: 2.0.1

android/app/build.gradle below:

apply plugin: "com.android.application"

import com.android.build.OutputFile
project.ext.react = [
    entryFile: "index.js",
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.realyze"
        minSdkVersion 21
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    // rootProject.ext.minSdkVersion
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation project(':react-native-push-notification')
    implementation project(':react-native-sound')
    implementation project(':react-native-audio')
    implementation 'com.android.support:multidex:2.0.1'
    implementation project(':react-native-gesture-handler')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
    implementation 'com.google.firebase:firebase-auth:19.1.0'
    implementation project(path: ":@react-native-firebase_auth")
    implementation project(path: ":@react-native-firebase_messaging")
    implementation project(path: ":@react-native-firebase_database")
    implementation project(':react-native-datetimepicker')
    implementation project(path: ":@react-native-firebase_firestore")
    implementation project(path: ":@react-native-firebase_functions")
}

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
// }

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

android/build.gradle below :

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.4.2"
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

Initially I was getting this error: react-native build error: Could not find method implementation() for arguments [jscFlavor] on project ':app' of type org.gradle.api.Project but now I am getting the above.


问:
text_extends behaves unexpected when i try to render a png, is this a bug?
I noticed lately that in some cases the png will look differently as the pdf. I rendered the preview images in different sizes an realized that the output could be totally different for the same input when I change the output size of the surface.

The problem is, that text_extends reports different normalized sizes for the same text when the surface pixel size is different. In this example the width varies from 113.861 to 120.175. Since I have to write each line separately those errors are some times much bigger in total.

Has anybody an idea how avoid those miscalculation?

Here is a small demonstration of this problem

```<code>import cairo
form StringIO import StringIO

def render_png(width, stream):
    width_px = height_px = width
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width_px, height_px)
    cr = cairo.Context(surface)
    cr.scale(float(width_px) / float(100),
             float(height_px) / float(100))
    cr.set_antialias(cairo.ANTIALIAS_GRAY)

    cr.set_source_rgb (1, 1, 1)
    cr.rectangle(0, 0, 100, 100)
    cr.fill()

    cr.select_font_face('Zapfino Extra LT') # a fancy font
    cr.set_font_size(20)
    example_string = 'Ein belieber Test Text'
    xbearing, ybearing, width, height, xadvance, yadvance = (
                        cr.text_extents(example_string))
    xpos = (100. - width) / 2. # centering text
    print width

    cr.move_to(xpos,50)
    cr.set_source_rgba(0,0,0)
    cr.show_text(example_string)

    surface.write_to_png(stream)
    return width

if __name__ == '__main__':
    l=[]
    for i in range(100,150,1):
        outs=StringIO()
        xpos = render_png(i,outs)
        l.append((i,xpos))
        #out = open('/home/hwmrocker/Desktop/FooBar/png_test%03d.png'%i, 'w')
        #outs.seek(0)
        #out.write(outs.read())
        #out.close()

    from operator import itemgetter
    l=sorted(l,key=itemgetter(1))
    print
    print l[0]
    print l[-1]
</code>```

答:
This behavior is likely due to the nature of text rendering itself - as glyphs in a font depend are drawn in different ways, depending on the pixel resolution. More so when the pixel resolution is small when compared to the glyph sizes (I'd say less than 30px height per glyph). This behavior is to be expected to some extend - always in order to prioritize readability of the text. If it is too off - or the png text is "uglier" than on the PDF (instead of incorrect size), then iis a bug in Cairo. Nevertheless, you probably should place this exact question on Cairo's issue tracker, so that the developers can tell wether it is a bug or not (and if it is, it maybe  the only possible way for they to get aware of it)
(Apparently they have no public bug tracker - just e-mail it to cairo-bugs@cairographics.org )

As for your specific problem, the workaround I will suggest to you is to render your text to a larger surface -- maybe 5 times larger, and resize that surface and paste the contents on your original surface (if needed at all). This way you might avoid glyph-size variations due to constraints in the number of pixels available for each glyph (at the cost of having a poorer text rendering on your final output).

Body:
I noticed lately that in some cases the png will look differently as the pdf. I rendered the preview images in different sizes an realized that the output could be totally different for the same input when I change the output size of the surface.

The problem is, that text_extends reports different normalized sizes for the same text when the surface pixel size is different. In this example the width varies from 113.861 to 120.175. Since I have to write each line separately those errors are some times much bigger in total.

Has anybody an idea how avoid those miscalculation?

Here is a small demonstration of this problem

import cairo
form StringIO import StringIO

def render_png(width, stream):
    width_px = height_px = width
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width_px, height_px)
    cr = cairo.Context(surface)
    cr.scale(float(width_px) / float(100),
             float(height_px) / float(100))
    cr.set_antialias(cairo.ANTIALIAS_GRAY)

    cr.set_source_rgb (1, 1, 1)
    cr.rectangle(0, 0, 100, 100)
    cr.fill()

    cr.select_font_face('Zapfino Extra LT') # a fancy font
    cr.set_font_size(20)
    example_string = 'Ein belieber Test Text'
    xbearing, ybearing, width, height, xadvance, yadvance = (
                        cr.text_extents(example_string))
    xpos = (100. - width) / 2. # centering text
    print width

    cr.move_to(xpos,50)
    cr.set_source_rgba(0,0,0)
    cr.show_text(example_string)

    surface.write_to_png(stream)
    return width

if __name__ == '__main__':
    l=[]
    for i in range(100,150,1):
        outs=StringIO()
        xpos = render_png(i,outs)
        l.append((i,xpos))
        #out = open('/home/hwmrocker/Desktop/FooBar/png_test%03d.png'%i, 'w')
        #outs.seek(0)
        #out.write(outs.read())
        #out.close()

    from operator import itemgetter
    l=sorted(l,key=itemgetter(1))
    print
    print l[0]
    print l[-1]


问:
Flutter: use "children: <Widget>" or "children:"?
In this document https://flutter.dev/docs/development/ui/layout#nesting-rows-and-columns
they use

```children:
```

But in the Android Studio, and this doc https://api.flutter.dev/flutter/widgets/Row-class.html
they use

```
children: &ltWidget&gt
```

So, what are the differences?
Thank you

答:
In dart when you want to set type of items in List to do this:

e.g.:

```<code>var intList = <int>[1, 2, 3];
</code>```

and type of var list become List<int>,

So the here in children is the same.

set <widget> before your widgets list, tell compiler, this list has items with widget type.

Body:
In this document https://flutter.dev/docs/development/ui/layout#nesting-rows-and-columns
they use

children:

But in the Android Studio, and this doc https://api.flutter.dev/flutter/widgets/Row-class.html
they use

children: &ltWidget&gt

So, what are the differences?
Thank you

Body:
In dart when you want to set type of items in List to do this:

e.g.:

var intList = <int>[1, 2, 3];

and type of var list become List<int>,

So the here in children is the same.

set <widget> before your widgets list, tell compiler, this list has items with widget type.


问:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

```<code>#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

</code>```

Or this one which do that using arrays:

```<code>#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

</code>```

But is it possible to use functions?if yes then how? thank you so much for helping.

答:
This is an example meant to give you an idea about what needs to be done. You can do this the following way:</p>

```<code>// we pass an array "a" that has N elements
double average(int a[], const int N)
{
    int sum = 0;
    // we go through each element and we sum them up
    for(int i = 0; i < N; ++i)
    {
        sum+=a[i];
    }
    // we divide the sum by the number of elements
    // but we first have to multiply the number of elements by 1.0
    // in order to prevent integer division from happening
    return sum/(N*1.0);
}

int main()
{
    const int N = 3;
    int a[N];

    cin >> a[0] >> a[1] >> a[2];

    cout << average(a, N) << endl;

    return 0;
}
</code>```

Body:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

Or this one which do that using arrays:

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

But is it possible to use functions?if yes then how? thank you so much for helping.

Body:
This is an example meant to give you an idea about what needs to be done. You can do this the following way:

// we pass an array "a" that has N elements
double average(int a[], const int N)
{
    int sum = 0;
    // we go through each element and we sum them up
    for(int i = 0; i < N; ++i)
    {
        sum+=a[i];
    }
    // we divide the sum by the number of elements
    // but we first have to multiply the number of elements by 1.0
    // in order to prevent integer division from happening
    return sum/(N*1.0);
}

int main()
{
    const int N = 3;
    int a[N];

    cin >> a[0] >> a[1] >> a[2];

    cout << average(a, N) << endl;

    return 0;
}


问:
Why JArray.Parse(json_array) gives me "{" in front of the result?
Why JArray.Parse(json_array) gives me "{" in front of the result? (it's like an object)
What I missed?</p>

```<code> string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
 JArray _j = JArray.Parse(_s);
</code>```

<p>_j returns: </p>

```<code>{[
   {
     "person": {
         "b2b_pid": "157"
       }
   }
  ]
}
</code>```

答:
```<code>string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
</code>```

Simply because you are not passing grammatically correct json object.
in some cases,array cannot be the root of a json object,you have to use dictionary to wrap the array even when you only have one array in your json object.

PS: I notice there is new standard that array top lier is supported.However,be careful of code compatibility.

C# statement JArray.Parse(_s); is adequate intelligent to try to fix your json issue While Key missing.

Body:
Why JArray.Parse(json_array) gives me "{" in front of the result? (it's like an object)
What I missed?

 string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
 JArray _j = JArray.Parse(_s);

_j returns:

{[
   {
     "person": {
         "b2b_pid": "157"
       }
   }
  ]
}

Body:
string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";

Simply because you are not passing grammatically correct json object.
in some cases,array cannot be the root of a json object,you have to use dictionary to wrap the array even when you only have one array in your json object.

PS: I notice there is new standard that array top lier is supported.However,be careful of code compatibility.

C# statement JArray.Parse(_s); is adequate intelligent to try to fix your json issue While Key missing.


问:
Split a string but a delimiter, only outside of [...] pair
How can i split a string, using ";" as a delimiter but only when this delimiter is NOT inside any [...].
e.g</p>

```<code>[a;b]c;d[e;f]  => <0>[a;b]c  <1>d[e;f]
a;b;c[e;f;g]   => <0>a <1>b <2>c[e;f;g]
abcd[e;f]      => <0>abcd[e;f]
</code>```

答:
Here is a regex approach which uses a negative lookahead to assert that only semicolons which are not nested inside [...] are used for splitting:

```<code>string input = "[a;b]c;d[e;f]";
string[] parts = Regex.Split(input, @";(?![^\[]*\])");
foreach (string part in parts)
{
   Console.WriteLine(part);
}
</code>```

This prints:

```<code>[a;b]c
d[e;f]
</code>```

Here is an explanation of the regex used:

```<code>;             match a semicolon
(?![^\[]*\])  provided that we can look ahead and confirm that we CANNOT hit a closing ]
              without first also hitting an opening [
</code>```

If the negative lookahead asserts, then it means that the semicolon is not inside [...].  Note that my answer assumes that you would never have nested brackets.  If you could have that, you should move away from regex and instead consider writing a simple parser.

Body:
How can i split a string, using ";" as a delimiter but only when this delimiter is NOT inside any [...].
e.g

[a;b]c;d[e;f]  => <0>[a;b]c  <1>d[e;f]
a;b;c[e;f;g]   => <0>a <1>b <2>c[e;f;g]
abcd[e;f]      => <0>abcd[e;f]

Body:
Here is a regex approach which uses a negative lookahead to assert that only semicolons which are not nested inside [...] are used for splitting:

string input = "[a;b]c;d[e;f]";
string[] parts = Regex.Split(input, @";(?![^\[]*\])");
foreach (string part in parts)
{
   Console.WriteLine(part);
}

This prints:

[a;b]c
d[e;f]

Here is an explanation of the regex used:

;             match a semicolon
(?![^\[]*\])  provided that we can look ahead and confirm that we CANNOT hit a closing ]
              without first also hitting an opening [

If the negative lookahead asserts, then it means that the semicolon is not inside [...].  Note that my answer assumes that you would never have nested brackets.  If you could have that, you should move away from regex and instead consider writing a simple parser.


问:
modify the Access policy SNS for inpector
how to modify the sns topic policy to permission to access to aws inspector in us-east-1?Assessment Templates has no permission to sns topic.
I got this error:</p>

```<code>The Inspector Account was denied access to the requested topic Grant account xxxxxxxxx permission to publish to the topic arn:aws:sns:us-east-1:xxxxxxxx:inspector
</code>```

```<code>{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "SNS:GetTopicAttributes",
        "SNS:SetTopicAttributes",
        "SNS:AddPermission",
        "SNS:RemovePermission",
        "SNS:DeleteTopic",
        "SNS:Subscribe",
        "SNS:ListSubscriptionsByTopic",
        "SNS:Publish",
        "SNS:Receive"
      ],
      "Resource": "arn:aws:sns:us-east-1:xxxxxxxx:inspector",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "xxxxxxxxx"
        }
      }
    }
  ]
}
</code>```

答:
Add this to your SNS access policy. It worked for me.

Note: My AWS Inspector is configured in Oregon so that I am using "arn:aws:iam::758058086616:root"

Reference.

And my SNS topic is already in the Oregon region.

```<code>{
  "Sid": "CustomInspectorPolicy",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::758058086616:root"
  },
  "Action": "SNS:Publish",
  "Resource": "arn:aws:sns:us-west-2:<YOUR AWS ACCOUNT NO>:<YOUR SNS TOPIC>"
}
</code>```

Body:
how to modify the sns topic policy to permission to access to aws inspector in us-east-1?Assessment Templates has no permission to sns topic.
I got this error:

The Inspector Account was denied access to the requested topic Grant account xxxxxxxxx permission to publish to the topic arn:aws:sns:us-east-1:xxxxxxxx:inspector

{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "SNS:GetTopicAttributes",
        "SNS:SetTopicAttributes",
        "SNS:AddPermission",
        "SNS:RemovePermission",
        "SNS:DeleteTopic",
        "SNS:Subscribe",
        "SNS:ListSubscriptionsByTopic",
        "SNS:Publish",
        "SNS:Receive"
      ],
      "Resource": "arn:aws:sns:us-east-1:xxxxxxxx:inspector",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "xxxxxxxxx"
        }
      }
    }
  ]
}

Body:
Add this to your SNS access policy. It worked for me.

Note: My AWS Inspector is configured in Oregon so that I am using "arn:aws:iam::758058086616:root"

Reference.

And my SNS topic is already in the Oregon region.

{
  "Sid": "CustomInspectorPolicy",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::758058086616:root"
  },
  "Action": "SNS:Publish",
  "Resource": "arn:aws:sns:us-west-2:<YOUR AWS ACCOUNT NO>:<YOUR SNS TOPIC>"
}


问:
IllegalArgumentException: navigation destination xxx is unknown to this NavController
I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:

```<code>java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController
</code>```

Every other navigation works fine except this particular one.

I use findNavController() function of Fragment to get access to the NavController.

Any help will be appreciated.

答: This error may have occured because you may have assigned the target screen to the wrong graph</p>

Body:
I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:

java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController

Every other navigation works fine except this particular one.

I use findNavController() function of Fragment to get access to the NavController.

Any help will be appreciated.


问:
Printing List Object in JSP
I'm getting close to printing objects in a table in JSP that was passed from a Servlet, however, they are not printing for some reason.

I have confirmed the servlet actually does save the data into the list but i have not confirmed whether the list was passed successfully to the JSP or if its i made a mistake with the printing of the objects.

Here is my code for the JSP page(listProduct is the list passed from the Servlet):

```<code><% List newList = (List)session.getAttribute("listProduct");%>

        <c:forEach  items="${listProduct}" var="Product">
            <tr>
                <td><c:out value="${Product.productId}" /></td>
                <td><c:out value="${product.productType}" /></td>
                <td><c:out value="${product.productPrice}" /></td>
                <td><c:out value="${product.vendorName}" /></td>
                <td><c:out value="${product.productName}" /></td>
                <td><c:out value="${product.productDescription}" /></td>
                <td><c:out value="${product.stockLevel}" /></td>
                <td><c:out value="action" /></td>
                <td>
                    <a href="/edit?id=<c:out value='${product.productId}' />">Edit</a>

                    <a href="/delete?id=<c:out value='${product.prodictId}' />">Delete</a>
                </td>
            </tr>
        </c:forEach>
</code>```

Also my "newList" in the JSP is unused however other tutorials had that in and even when I try to use the newList for the table it doesnt register and it still says that newList is unused.

Any pointers or help will be much appreciated.

EDIT: More information (Servlet code)

I have included my servlet code that is creating the list and sending it to the jsp page as well - just incase the problem is from there.

```<code>    List<Product> listProduct = db.listProducts();

            request.setAttribute("listProduct", listProduct);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("displayProduct.jsp");
            requestDispatcher.forward(request, response);
</code>```

**db is the DAO.
EDIT 2 DAO code: This code is what is providing the array list to the servlet.

```<code> public List<Product> listProducts() throws SQLException {
        List<Product> listProduct = new ArrayList<>();

        String sql = "SELECT * FROM PRODUCT";

        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            int productId = rs.getInt("productId");
            double productPrice = rs.getDouble("PRODUCTPRICE");
            String productType = rs.getString("productType");
            String vendorName = rs.getString("vendorName");
            String productName = rs.getString("productName");
            String productDescription = rs.getString("productDescription");
            int stockLevel = rs.getInt("stockLevel");

            Product product = new Product(productId, productPrice, productType, vendorName, productName, productDescription, stockLevel);
            listProduct.add(product);

        }

        return listProduct;
</code>```

ANOTHER EDIT!! :
I confirmed that the issue is with the coding in the JSP table section as the arraylist is successfully sent to the JSP page - but only issue now is printing it in the table per the attribute.

答:
```<code> <td>${Product.getProductId()}</td>
</code>```

Just use it without the c:out.
And sometimes u write product instead of Product

Title: Printing List Object in JSP

Body:
I'm getting close to printing objects in a table in JSP that was passed from a Servlet, however, they are not printing for some reason.

I have confirmed the servlet actually does save the data into the list but i have not confirmed whether the list was passed successfully to the JSP or if its i made a mistake with the printing of the objects.

Here is my code for the JSP page(listProduct is the list passed from the Servlet):

<% List newList = (List)session.getAttribute("listProduct");%>

        <c:forEach  items="${listProduct}" var="Product">

                <c:out value="${Product.productId}" />
                <c:out value="${product.productType}" />
                <c:out value="${product.productPrice}" />
                <c:out value="${product.vendorName}" />
                <c:out value="${product.productName}" />
                <c:out value="${product.productDescription}" />
                <c:out value="${product.stockLevel}" />
                <c:out value="action" />

                    <a href="/edit?id=<c:out value='${product.productId}' />">Edit

                    <a href="/delete?id=<c:out value='${product.prodictId}' />">Delete

        </c:forEach>

Also my "newList" in the JSP is unused however other tutorials had that in and even when I try to use the newList for the table it doesnt register and it still says that newList is unused.

Any pointers or help will be much appreciated.

EDIT: More information (Servlet code)

I have included my servlet code that is creating the list and sending it to the jsp page as well - just incase the problem is from there.

    List<Product> listProduct = db.listProducts();

            request.setAttribute("listProduct", listProduct);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("displayProduct.jsp");
            requestDispatcher.forward(request, response);

**db is the DAO.
EDIT 2 DAO code: This code is what is providing the array list to the servlet.

 public List<Product> listProducts() throws SQLException {
        List<Product> listProduct = new ArrayList<>();

        String sql = "SELECT * FROM PRODUCT";

        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            int productId = rs.getInt("productId");
            double productPrice = rs.getDouble("PRODUCTPRICE");
            String productType = rs.getString("productType");
            String vendorName = rs.getString("vendorName");
            String productName = rs.getString("productName");
            String productDescription = rs.getString("productDescription");
            int stockLevel = rs.getInt("stockLevel");

            Product product = new Product(productId, productPrice, productType, vendorName, productName, productDescription, stockLevel);
            listProduct.add(product);

        }

        return listProduct;

ANOTHER EDIT!! :
I confirmed that the issue is with the coding in the JSP table section as the arraylist is successfully sent to the JSP page - but only issue now is printing it in the table per the attribute.

Body:
 <td>${Product.getProductId()}</td>

Just use it without the c:out.
And sometimes u write product instead of Product


答:
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array</p>

```<code>#include <iostream>
#include <vector>

float average(std::vector<int> vec)
{
    float sum = 0;
    for (int i = 0; i < vec.size(); ++i)
    {
        sum += vec[i];
    }
    sum /= vec.size();
    return sum;
}
float average(int arr[],const int n)
{
    float sum = 0;
    for (int i = 0; i < n; ++i)
    {
        sum += arr[i];
    }
    sum /= n;
    return sum;
}
int main() {
    std::vector<int> vec = { 1,2,3,4,5,6,99};
    int arr[7] = { 1,2,3,4,5,6,99 };
    std::cout << average(vec) << " " << average(arr, 7);
}
</code>```

Title: Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers

Body:
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array

#include <iostream>
#include <vector>

float average(std::vector<int> vec)
{
    float sum = 0;
    for (int i = 0; i < vec.size(); ++i)
    {
        sum += vec[i];
    }
    sum /= vec.size();
    return sum;
}
float average(int arr[],const int n)
{
    float sum = 0;
    for (int i = 0; i < n; ++i)
    {
        sum += arr[i];
    }
    sum /= n;
    return sum;
}
int main() {
    std::vector<int> vec = { 1,2,3,4,5,6,99};
    int arr[7] = { 1,2,3,4,5,6,99 };
    std::cout << average(vec) << " " << average(arr, 7);
}


问:
Why would HttpErrors in web.config working differently in Azure to on-premise for URLs containing "%25f2"?
I have a react website hosted as an Azure app service. In the website I have a web.config file that includes httpErrors for providing custom error pages.

```<code><httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/Error.html" responseMode="ExecuteURL" />
</httpErrors>
</code>```

This mostly works as expected in Azure, if I navigate to a path that doesn't exist I get the custom error page. However, when I try to navigate to a path that contains "%25f2" like "/..%25f2.../a" then it doesn't show the custom error page and instead shows the standard Azure 404 error page.

To test this I setup a local website on my computer in IIS and used the same web.config configuration. When I try "/..%25f2.../a" on the local IIS site it does redirect to the custom error page.

Why do these have different behavior and how do I make Azure redirect to the custom error page for this type of URL?

答:
After testing, it works for me.

```<code><httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom" >
    <remove statusCode="404" />
    <error statusCode="404" path="/Home/Error" responseMode="ExecuteURL"/>
    <remove statusCode="500" />
    <error statusCode="500" path="/Home/Error" responseMode="ExecuteURL"/>
</httpErrors>
</code>```

Body:
I have a react website hosted as an Azure app service. In the website I have a web.config file that includes httpErrors for providing custom error pages.

<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/Error.html" responseMode="ExecuteURL" />
</httpErrors>

This mostly works as expected in Azure, if I navigate to a path that doesn't exist I get the custom error page. However, when I try to navigate to a path that contains "%25f2" like "/..%25f2.../a" then it doesn't show the custom error page and instead shows the standard Azure 404 error page.

To test this I setup a local website on my computer in IIS and used the same web.config configuration. When I try "/..%25f2.../a" on the local IIS site it does redirect to the custom error page.

Why do these have different behavior and how do I make Azure redirect to the custom error page for this type of URL?

Body:
After testing, it works for me.

<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom" >
    <remove statusCode="404" />
    <error statusCode="404" path="/Home/Error" responseMode="ExecuteURL"/>
    <remove statusCode="500" />
    <error statusCode="500" path="/Home/Error" responseMode="ExecuteURL"/>
</httpErrors>


问:
Highcharts x-axis tick starts with an offset
I am trying to remove the offset on the tick of the x-axis.

I want the first tick 10/8 to start from the x-axis and y-axis intersection.

10-8 should be on the marker which is between the two labels.

I have following code for it in highchart.

```<code>xAxis: {
            categories: categories,
            title: {
              text: title_x_axis,
              style: {
                fontWeight: 'bold'
              },
              formatter: function(){
                return "<h3><b>" + this.value + "</b></h3>";
              }
            },
            min: 0,
            startOnTick: true,
            endOnTick: true,
            minPadding: 0,
            maxPadding: 0,
            align: "left"
        },
</code>```

Max padding and min padding are set to 0, So I don't know what the problem is?

EDIT:

I have created a fiddle of the type of chart I am dealing with.
Note Image below has different x-axis values as I am not using the same value of fiddle.
Also I have set tickmarkPlacement: "on" after I took that snapshot.
I want Jan label to start from the beginning of line. It has some offset currently.

Can anyone help me with this?

答:
Add pointPlacement: 'on' in plotOptions.</p>

```<code>plotOptions: {
    series: {
     pointPlacement: 'on'
   }
}
</code>```

Body:
I am trying to remove the offset on the tick of the x-axis.

I want the first tick 10/8 to start from the x-axis and y-axis intersection.

10-8 should be on the marker which is between the two labels.

I have following code for it in highchart.

xAxis: {
            categories: categories,
            title: {
              text: title_x_axis,
              style: {
                fontWeight: 'bold'
              },
              formatter: function(){
                return "
" + this.value + "
";
              }
            },
            min: 0,
            startOnTick: true,
            endOnTick: true,
            minPadding: 0,
            maxPadding: 0,
            align: "left"
        },

Max padding and min padding are set to 0, So I don't know what the problem is?

EDIT:

I have created a fiddle of the type of chart I am dealing with.
Note Image below has different x-axis values as I am not using the same value of fiddle.
Also I have set tickmarkPlacement: "on" after I took that snapshot.
I want Jan label to start from the beginning of line. It has some offset currently.

Can anyone help me with this?

Body:
Add pointPlacement: 'on' in plotOptions.

plotOptions: {
    series: {
     pointPlacement: 'on'
   }
}


问:
Filtering using Regular Expressions
I am having a filter for the following regular expressions

```<code>[^@()[]\;:,<>]+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
</code>```

I need to negate the following special charters before the @domain.com

```<code>@()[]\;:",<
</code>```

any suggestions??

答:
Try escaping the ] in the character class.

```<code>[^@()[\]\;:,<>]+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
      ^^
</code>```

If not escaped the ] will be treated incorrectly as the end of the character class.

Since this has been tagged as Java, remember that you need to escape using \\ and not just \.

Title: Filtering using Regular Expressions

Body:
I am having a filter for the following regular expressions

[^@()[]\;:,<>]+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/

I need to negate the following special charters before the @domain.com

@()[]\;:",<

any suggestions??

Body:
Try escaping the ] in the character class.

[^@()[\]\;:,<>]+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
      ^^

If not escaped the ] will be treated incorrectly as the end of the character class.

Since this has been tagged as Java, remember that you need to escape using \\ and not just \.


问:
Where should I call a method to use data from it?
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>
        <div className="container" style={{ color: "white" }}>
          hello
        </div>
      </>
    );
  }
}

export default Albums;

</code>```

I wanna do something like this inside the div.

```<code>this.state.albums.map((album) => (<AlbumCard img={album.img}/>))
</code>```

答:
use componentDidMount()</p>

```<code>componentDidMount(){
getAlbums()
}
</code>```

Body:
I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.

Albums.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

export class Albums extends Component {
  constructor(props) {
    super(props);

    this.state = { albums: [] };
    this.getAlbums = this.getAlbums.bind(this);
  }

  async getAlbums() {
    const {
      match: { params },
    } = this.props;
    console.log(params.id);
    try {
      const res = await axios.get(
        `http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
        {
          params: {
            id: params.id,
          },
        }
      );
      console.log(`Returned album data from the server: ${res}`);
      this.setState({ albums: res.data });
    } catch (err) {
      console.log(err);
    }
  }

  render() {
    return (
      <>

          hello

      </>
    );
  }
}

export default Albums;

I wanna do something like this inside the div.

this.state.albums.map((album) => (<AlbumCard img={album.img}/>))

Body:
use componentDidMount()

componentDidMount(){
getAlbums()
}


问:
Downgrade to PHP 5.3
I've got a line of code that I need to get working in PHP 5.3.3.
I cannot upgrade the PHP version.

The error is in the last line below with the ::class property

(unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$').

The context is:

```<code>abstract class E
{

    public static function validate($value)
    {
        $reflector = new ReflectionClass(static::class);
</code>```

Is there any way to get this to work in PHP 5.3.3?

答:
::class constant on classes has been introduced in PHP 5.5. The equivalent of static::class in PHP < 5.5 would be get_called_class(), so the faulty line in your code should look like this:

```<code>    $reflector = new ReflectionClass(get_called_class());
</code>```

Title: Downgrade to PHP 5.3

Body:
I've got a line of code that I need to get working in PHP 5.3.3.
I cannot upgrade the PHP version.

The error is in the last line below with the ::class property

(unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$').

The context is:

abstract class E
{

    public static function validate($value)
    {
        $reflector = new ReflectionClass(static::class);

Is there any way to get this to work in PHP 5.3.3?

Body:
::class constant on classes has been introduced in PHP 5.5. The equivalent of static::class in PHP < 5.5 would be get_called_class(), so the faulty line in your code should look like this:

    $reflector = new ReflectionClass(get_called_class());


问:
Firebase onCall request fail on chrome browser?
I deployed this and tried to call it on my browser using the url given by firebase cmd. Is it possible to call onCall on browser or do I need to call it from a client?

```<code>exports.test = functions.https.onCall((input, context) => {
    // res.status(200).json({results: "Success"})
    console.log("test")
    return { status: 200, message: "Success"}
})
</code>```

Got this error

```<code>{
  "error": {
    "message": "Bad Request",
    "status": "INVALID_ARGUMENT"
  }
}
</code>```

答:
The URL of a callable function cannot be used to directly access it.  A callable function has a specific protocol used to pass data back and forth.  If the client doesn't implement that protocol, the request won't work.

If you want direct browser access without a special protocol, you should write an regular HTTP function using onRequest instead of a callable.

Body:
I deployed this and tried to call it on my browser using the url given by firebase cmd. Is it possible to call onCall on browser or do I need to call it from a client?

exports.test = functions.https.onCall((input, context) => {
    // res.status(200).json({results: "Success"})
    console.log("test")
    return { status: 200, message: "Success"}
})

Got this error

{
  "error": {
    "message": "Bad Request",
    "status": "INVALID_ARGUMENT"
  }
}


问:
Elasticsearch - Any way to find out all the documents with field value as text
In the elasticsearch cluster, I accidentally pushed some text in a field which should ideally be a Number. Later, I fixed that and pushed the Number type value. Now, I wanted to fix it such that all the old values can be replaced by some Number for which I need to find out all the documents which are having this field as text.

Is there any elasticsearch query that I can use to get this information?

答:
I think that can be possible by using a nested aggregations.

At the top-level; use terms aggregation to know text values, at the sub-level; use top_hits aggregation to get documents that includes these values.

for instance:

```<code>GET example_index/_search
{
  "size": 0,
  "aggs": {
    "NAME": {
      "terms": {
        "field": "example_field.keyword",
        "size": 10
      },
      "aggs": {
        "documents": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
}
</code>```

This query; will return distinct values of the field, and the related documents in the sub-level, something like:

```<code>{
  "aggregations": {
    "NAME": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "mistake",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "2QoDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                },
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "qAoDoXEBOCkJkkpwq5T0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                }
              ]
            }
          }
        },
        {
          "key": "520",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "5goDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "1"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}
</code>```

I the example above; we need to delete the documents with mistake value, you can simply delete them by id.

NOTE: if you have a big index, it's rather to write a function inside your code that builds aggregations, gets the response, filters values if it can be parsed to a number, then removes documents by id.

Body:
I think that can be possible by using a nested aggregations.

At the top-level; use terms aggregation to know text values, at the sub-level; use top_hits aggregation to get documents that includes these values.

for instance:

GET example_index/_search
{
  "size": 0,
  "aggs": {
    "NAME": {
      "terms": {
        "field": "example_field.keyword",
        "size": 10
      },
      "aggs": {
        "documents": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
}

This query; will return distinct values of the field, and the related documents in the sub-level, something like:

{
  "aggregations": {
    "NAME": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "mistake",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "2QoDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                },
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "qAoDoXEBOCkJkkpwq5T0",
                  "_score": 1,
                  "_source": {
                    "example_field": "mistake"
                  }
                }
              ]
            }
          }
        },
        {
          "key": "520",
          "doc_count": 2,
          "documents": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_index": "example_index",
                  "_type": "example_index",
                  "_id": "5goDoXEBOCkJkkpwq5P0",
                  "_score": 1,
                  "_source": {
                    "example_field": "1"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}

I the example above; we need to delete the documents with mistake value, you can simply delete them by id.

NOTE: if you have a big index, it's rather to write a function inside your code that builds aggregations, gets the response, filters values if it can be parsed to a number, then removes documents by id.