问:
Performance of Scalar function in SQL SERVER
We have the below scalar function which is used in most of our select queries. I have added only a single IF condition but this function has around 50 IF statements. I tried to convert it to inline but failed at the last statement for @output.

This function is causing performance issues. So need to convert this to an inline function.

We currently using Microsoft SQL Azure (RTM) - 12.0.2000.8   Nov 16, 2022, 04:43:19   Copyright (C) 2022 Microsoft Corporation

```<code>     CREATE FUNCTION [dbo].[udf_GetLSLineDescByGUIDLocalised] (
            @ComputationID   INT,
            @AccountGUID   UNIQUEIDENTIFIER,
            @LSCode    nvarchar(50),
         @SpecificLevelOnly INT = -1,   --defaults to full description
         @LanguageID   INT
        )
        RETURNS nvarchar(1000)

        AS
        BEGIN

            DECLARE @Output   nvarchar(1000)

         DECLARE @FormatToken NVARCHAR(50)

         SELECT @FormatToken = ResourceString
         FROM dbo.tbl_ResourceString WITH(NOLOCK)
         WHERE ResourceKey = 'General.AccountSeparator' AND LanguageID = @LanguageID

            -------------------------------------------
            -- Balance Sheet
            -------------------------------------------
            if @LSCode = 'BS' begin

                select TOP 1 @Output =
           case
            when @SpecificLevelOnly > 0 then
             case
              when @SpecificLevelOnly = 1 then dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID)
              when @SpecificLevelOnly = 2 then dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID)
              when @SpecificLevelOnly = 3 then dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID)
              when @SpecificLevelOnly = 4 then dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID)
              when @SpecificLevelOnly = 5 and ls.Level5ID <> 0 then dbo.udf_AccountName(ls.AccountGUID, ls.Description, @LanguageID)
             end
            else
                     case
                         when l2.Description is null then dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID)
                         else dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID) + @formatToken
                     end +
                     case
                         when nullif(l2.Description, 'BLANK')is null then ''
                         when l3.Description is null then dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID)
                         else dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID) + @formatToken
                     end +
                     case
                         when l3.Description is null then ''
             when ls.Level4ID = 0 then dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID)
                         else dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID) + @formatToken
                     end +
               case
                         when l4.Description is null then ''
             when ls.Level5ID = 0 then dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID)
                         else dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID) + @formatToken
                     end +
            case
             when ls.Level5ID <> 0 then dbo.udf_AccountName(ls.AccountGUID, ls.Description, @LanguageID)
             else ''
            end
           end
             from tbl_ScheduleBS ls WITH (NOLOCK)

             left outer join dbo.tbl_ScheduleBS l1  WITH (NOLOCK)
             on  ls.ComputationID = l1.ComputationID
             and ls.Level1ID = l1.Level1ID
             and l1.Level2ID = 0

             left outer join dbo.tbl_ScheduleBS l2  WITH (NOLOCK)
                on  ls.ComputationID = l2.ComputationID
             and ls.Level1ID = l2.Level1ID
             and ls.Level2ID = l2.Level2ID and l2.Level2ID <> 0
             and l2.Level3ID = 0

             left outer join dbo.tbl_ScheduleBS l3 WITH (NOLOCK)
                on  ls.ComputationID = l3.ComputationID
             and ls.Level1ID = l3.Level1ID
             and ls.Level2ID = l3.Level2ID and l3.Level2ID <> 0
             and ls.Level3ID = l3.Level3ID and l3.Level3ID <> 0
             and l3.Level4ID = 0

         left outer join dbo.tbl_ScheduleBS l4 WITH (NOLOCK)
                on  ls.ComputationID = l4.ComputationID
             and ls.Level1ID = l4.Level1ID
             and ls.Level2ID = l4.Level2ID and l4.Level2ID <> 0
             and ls.Level3ID = l4.Level3ID and l4.Level3ID <> 0
             and ls.Level4ID = l4.Level4ID and l4.Level4ID <> 0
         and l4.Level5ID = 0

                where ls.ComputationID = @ComputationID
                and ls.AccountGUID = @AccountGUID

            -------------------------------------------
            -- Unknown @LSCode, perhaps not implemented yet?
            -------------------------------------------
            end else begin

                -- can't raise errors from within a function, return null
                select TOP 1 @Output = NULL

            end

         select @Output = case when @Output like  @formattoken + '%' then stuff(@Output, 1, 3, '') else @Output end

            return @Output

        END

</code>```

Body:
We have the below scalar function which is used in most of our select queries. I have added only a single IF condition but this function has around 50 IF statements. I tried to convert it to inline but failed at the last statement for @output.

This function is causing performance issues. So need to convert this to an inline function.

We currently using Microsoft SQL Azure (RTM) - 12.0.2000.8   Nov 16, 2022, 04:43:19   Copyright (C) 2022 Microsoft Corporation

     CREATE FUNCTION [dbo].[udf_GetLSLineDescByGUIDLocalised] (
            @ComputationID   INT,
            @AccountGUID   UNIQUEIDENTIFIER,
            @LSCode    nvarchar(50),
         @SpecificLevelOnly INT = -1,   --defaults to full description
         @LanguageID   INT
        )
        RETURNS nvarchar(1000)

        AS
        BEGIN

            DECLARE @Output   nvarchar(1000)

         DECLARE @FormatToken NVARCHAR(50)

         SELECT @FormatToken = ResourceString
         FROM dbo.tbl_ResourceString WITH(NOLOCK)
         WHERE ResourceKey = 'General.AccountSeparator' AND LanguageID = @LanguageID

            -------------------------------------------
            -- Balance Sheet
            -------------------------------------------
            if @LSCode = 'BS' begin

                select TOP 1 @Output =
           case
            when @SpecificLevelOnly > 0 then
             case
              when @SpecificLevelOnly = 1 then dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID)
              when @SpecificLevelOnly = 2 then dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID)
              when @SpecificLevelOnly = 3 then dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID)
              when @SpecificLevelOnly = 4 then dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID)
              when @SpecificLevelOnly = 5 and ls.Level5ID <> 0 then dbo.udf_AccountName(ls.AccountGUID, ls.Description, @LanguageID)
             end
            else
                     case
                         when l2.Description is null then dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID)
                         else dbo.udf_AccountName(l1.AccountGUID, l1.Description, @LanguageID) + @formatToken
                     end +
                     case
                         when nullif(l2.Description, 'BLANK')is null then ''
                         when l3.Description is null then dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID)
                         else dbo.udf_AccountName(l2.AccountGUID, l2.Description, @LanguageID) + @formatToken
                     end +
                     case
                         when l3.Description is null then ''
             when ls.Level4ID = 0 then dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID)
                         else dbo.udf_AccountName(l3.AccountGUID, l3.Description, @LanguageID) + @formatToken
                     end +
               case
                         when l4.Description is null then ''
             when ls.Level5ID = 0 then dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID)
                         else dbo.udf_AccountName(l4.AccountGUID, l4.Description, @LanguageID) + @formatToken
                     end +
            case
             when ls.Level5ID <> 0 then dbo.udf_AccountName(ls.AccountGUID, ls.Description, @LanguageID)
             else ''
            end
           end
             from tbl_ScheduleBS ls WITH (NOLOCK)

             left outer join dbo.tbl_ScheduleBS l1  WITH (NOLOCK)
             on  ls.ComputationID = l1.ComputationID
             and ls.Level1ID = l1.Level1ID
             and l1.Level2ID = 0

             left outer join dbo.tbl_ScheduleBS l2  WITH (NOLOCK)
                on  ls.ComputationID = l2.ComputationID
             and ls.Level1ID = l2.Level1ID
             and ls.Level2ID = l2.Level2ID and l2.Level2ID <> 0
             and l2.Level3ID = 0

             left outer join dbo.tbl_ScheduleBS l3 WITH (NOLOCK)
                on  ls.ComputationID = l3.ComputationID
             and ls.Level1ID = l3.Level1ID
             and ls.Level2ID = l3.Level2ID and l3.Level2ID <> 0
             and ls.Level3ID = l3.Level3ID and l3.Level3ID <> 0
             and l3.Level4ID = 0

         left outer join dbo.tbl_ScheduleBS l4 WITH (NOLOCK)
                on  ls.ComputationID = l4.ComputationID
             and ls.Level1ID = l4.Level1ID
             and ls.Level2ID = l4.Level2ID and l4.Level2ID <> 0
             and ls.Level3ID = l4.Level3ID and l4.Level3ID <> 0
             and ls.Level4ID = l4.Level4ID and l4.Level4ID <> 0
         and l4.Level5ID = 0

                where ls.ComputationID = @ComputationID
                and ls.AccountGUID = @AccountGUID

            -------------------------------------------
            -- Unknown @LSCode, perhaps not implemented yet?
            -------------------------------------------
            end else begin

                -- can't raise errors from within a function, return null
                select TOP 1 @Output = NULL

            end

         select @Output = case when @Output like  @formattoken + '%' then stuff(@Output, 1, 3, '') else @Output end

            return @Output

        END


来源: stackexchange

问:
VBA index/match formula returns an empty string despite the formula being correct
I am trying to write a macro to create an index/match formula which gets updated dynamically while running through a range of input values, which are in columns R (company codes) and AF (calendar years). Relevant parts of the code are below. I tested the macro several times and it seems that the main issue is the index/match formula line. The formula itself works fine (when written in Excel directly or copied out of the immediate window), yet the error message I get is "object-defined or application-defined error" and the following comment appears hovering over this line of code: ws_output.Range().Offset().Value = Empty. When I delete this line of code, everything else works fine. How can I fix this? Thank you!

```<code>Sub fetching_acq_data_compustat()

Dim ws_input As Worksheet
Dim strTkr As String
Dim rngTkr As Range
Dim c As Range

Dim ws_output As Worksheet

Dim strTkrCell As String
Dim strDatedCell As String

Set ws_input = ThisWorkbook.Sheets("MA_ExportFiltered_RawData")
Set ws_output = ThisWorkbook.Sheets("Acquirer_ETR")

ws_input.Activate

With ws_input
    Set rngTkr = .Range("R43:R3223")
    For Each c In rngTkr

        strTkrCell = c.Address

        k = 14
        If k < 16 Then
        strDatedCell = c.Offset(0, k).Address

        ws_output.Range("A1").Offset(2, 0).Value = c.Offset(0, 14).Value

        ws_output.Range("A1").Offset(2, 1). Value = "=INDEX( 'US acq_CUSIP data'!$A$3:$AJ$77388" & ";" & "MATCH(1; ('US acq_CUSIP data'!$I$3:$I$77388=" & "MA_ExportFiltered_RawData!" & strTkrCell & ")*('US acq_CUSIP data'!$C$3:$C$77388=" & "MA_ExportFiltered_RawData!" & strDatedCell & ");0); 26)"

        ws_output.Range("A1").Offset(1, 1).Value = ws_comp.Range("A1").Offset(0, 25).Value

        ws_output.Range("A1").Offset(0, 1).Value = c.Value

        k = k + 1

        End If

    Next
End With

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a macro to create an index/match formula which gets updated dynamically while running through a range of input values, which are in columns R (company codes) and AF (calendar years). Relevant parts of the code are below. I tested the macro several times and it seems that the main issue is the index/match formula line. The formula itself works fine (when written in Excel directly or copied out of the immediate window), yet the error message I get is "object-defined or application-defined error" and the following comment appears hovering over this line of code: ws_output.Range().Offset().Value = Empty. When I delete this line of code, everything else works fine. How can I fix this? Thank you!

Sub fetching_acq_data_compustat()

Dim ws_input As Worksheet
Dim strTkr As String
Dim rngTkr As Range
Dim c As Range

Dim ws_output As Worksheet

Dim strTkrCell As String
Dim strDatedCell As String

Set ws_input = ThisWorkbook.Sheets("MA_ExportFiltered_RawData")
Set ws_output = ThisWorkbook.Sheets("Acquirer_ETR")

ws_input.Activate

With ws_input
    Set rngTkr = .Range("R43:R3223")
    For Each c In rngTkr

        strTkrCell = c.Address

        k = 14
        If k < 16 Then
        strDatedCell = c.Offset(0, k).Address

        ws_output.Range("A1").Offset(2, 0).Value = c.Offset(0, 14).Value

        ws_output.Range("A1").Offset(2, 1). Value = "=INDEX( 'US acq_CUSIP data'!$A$3:$AJ$77388" & ";" & "MATCH(1; ('US acq_CUSIP data'!$I$3:$I$77388=" & "MA_ExportFiltered_RawData!" & strTkrCell & ")*('US acq_CUSIP data'!$C$3:$C$77388=" & "MA_ExportFiltered_RawData!" & strDatedCell & ");0); 26)"

        ws_output.Range("A1").Offset(1, 1).Value = ws_comp.Range("A1").Offset(0, 25).Value

        ws_output.Range("A1").Offset(0, 1).Value = c.Value

        k = k + 1

        End If

    Next
End With

End Sub


问:
How to close the excel operation using excel data reader in selenium c#
How to close the Excel operation using excel data reader in selenium c#?

```<code>public void ReadExcel(IWebDriver driver, int rowNum)
{
    try
    {
        invoices_Obj.hourscolumn_Gridfilter.Click();

        invoices_Obj.hourscolumn_dd_Field_dd.Click();
        Thread.Sleep(2000);
        Console.WriteLine("Select dd");

        invoices_Obj.hourscolumn_dd_Field_dd_value_equals.Click();
        Thread.Sleep(2000);
        Console.WriteLine("Select dd value as equals");

        string Totalhourseq = Exceloperations.ReadData(rowNum, "Hours_Customequals");

        if (rowNum != null)
        {
            Actions actions = new Actions(Driver.driver);
            invoices_Obj.hourscolumn_dd_input.SendKeys(Totalhourseq);
            Console.WriteLine("input value as "+ Totalhourseq);
            invoices_Obj.Gridcolumn_Apply.Click();
            invoices_Obj.hourscolumn_Gridfilter.Click();
            invoices_Obj.Grid_Clear.Click();
        }
    }
}
</code>```

If I am running continuously, for different orders, facing the below issue (screen)

Body:
How to close the Excel operation using excel data reader in selenium c#?

public void ReadExcel(IWebDriver driver, int rowNum)
{
    try
    {
        invoices_Obj.hourscolumn_Gridfilter.Click();

        invoices_Obj.hourscolumn_dd_Field_dd.Click();
        Thread.Sleep(2000);
        Console.WriteLine("Select dd");

        invoices_Obj.hourscolumn_dd_Field_dd_value_equals.Click();
        Thread.Sleep(2000);
        Console.WriteLine("Select dd value as equals");

        string Totalhourseq = Exceloperations.ReadData(rowNum, "Hours_Customequals");

        if (rowNum != null)
        {
            Actions actions = new Actions(Driver.driver);
            invoices_Obj.hourscolumn_dd_input.SendKeys(Totalhourseq);
            Console.WriteLine("input value as "+ Totalhourseq);
            invoices_Obj.Gridcolumn_Apply.Click();
            invoices_Obj.hourscolumn_Gridfilter.Click();
            invoices_Obj.Grid_Clear.Click();
        }
    }
}

If I am running continuously, for different orders, facing the below issue (screen)


问:
Distribute pre-compiled framework using cocoapods
I want to distribute my pre-compiled framework using cocoapod. I want to upload my framework to a third-party server (not git) and the podspec file to my repo. How I am able to do that?</p>


问:
socket.io-client-cpp. Consume error: websocketpp.processor:9 (Invalid use of reserved bits)
I tried to connect locally but got this error: consume error: websocketpp.processor:9 (Invalid use of reserved bits)

```<code>OpenGL Version: 3.1.0 - Build 9.17.10.4459
[2023-01-05 13:27:08] [connect] Successful connection
[2023-01-05 13:27:08] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672910828 101
[2023-01-05 13:27:08] [error] consume error: websocketpp.processor:9 (Invalid use of reserved bits)
[2023-01-05 13:27:08] [disconnect] Disconnect close local:[1002,Invalid use of reserved bits] remote:[1006]
[2023-01-05 13:27:13] [connect] Successful connection
[2023-01-05 13:27:13] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672910833 101
[2023-01-05 13:27:13] [error] consume error: websocketpp.processor:9 (Invalid use of reserved bits)
[2023-01-05 13:27:13] [disconnect] Disconnect close local:[1002,Invalid use of reserved bits] remote:[1006]
</code>```

main.cpp

    sio::client h;
    h.connect("https://127.0.0.1:3000");
```
<p>app.js:</p>
<pre class="lang-js prettyprint-override"><code>const express = require("express");
const io = require("socket.io")();
const http = require("http");
const path = require("path");

const app = express();
app.use(express.static(path.join(process.cwd(), "public")));
const httpServer = http.createServer(app);

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));
const sio = io.listen(httpServer);

sio.sockets.on("connection", (socket) => {
    console.log("client was connected");
});
</code>```

It should be noted that the connection occurs if ws is used on the server side instead of socket.io

const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");

const app = express();
const httpServer = http.createServer(app);

const wss = new ws.Server(
{
    server: httpServer
});

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));

wss.on("connection", socket =>
{
    console.log("client was connected");
});
```
```[2023-01-05 19:46:30] [connect] Successful connection
[2023-01-05 19:46:30] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672933590 101
```

Body:
I tried to connect locally but got this error: consume error: websocketpp.processor:9 (Invalid use of reserved bits)

OpenGL Version: 3.1.0 - Build 9.17.10.4459
[2023-01-05 13:27:08] [connect] Successful connection
[2023-01-05 13:27:08] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672910828 101
[2023-01-05 13:27:08] [error] consume error: websocketpp.processor:9 (Invalid use of reserved bits)
[2023-01-05 13:27:08] [disconnect] Disconnect close local:[1002,Invalid use of reserved bits] remote:[1006]
[2023-01-05 13:27:13] [connect] Successful connection
[2023-01-05 13:27:13] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672910833 101
[2023-01-05 13:27:13] [error] consume error: websocketpp.processor:9 (Invalid use of reserved bits)
[2023-01-05 13:27:13] [disconnect] Disconnect close local:[1002,Invalid use of reserved bits] remote:[1006]

main.cpp

    sio::client h;
    h.connect("https://127.0.0.1:3000");

app.js:

const express = require("express");
const io = require("socket.io")();
const http = require("http");
const path = require("path");

const app = express();
app.use(express.static(path.join(process.cwd(), "public")));
const httpServer = http.createServer(app);

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));
const sio = io.listen(httpServer);

sio.sockets.on("connection", (socket) => {
    console.log("client was connected");
});

It should be noted that the connection occurs if ws is used on the server side instead of socket.io

const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");

const app = express();
const httpServer = http.createServer(app);

const wss = new ws.Server(
{
    server: httpServer
});

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));

wss.on("connection", socket =>
{
    console.log("client was connected");
});

[2023-01-05 19:46:30] [connect] Successful connection
[2023-01-05 19:46:30] [connect] WebSocket Connection 127.0.0.1:3000 v-2 "WebSocket++/0.8.2" /socket.io/?EIO=3&transport=websocket&t=1672933590 101


问:
Making parent controller as base router path for a particular module in inversify express.js
I have multiple modules and want to club them under one route path based on module

```<code>example.com/api/moduleA/controller1
example.com/api/module1/controller2
example.com/api/module1/controller3
</code>```
```<code>example.com/api/module2/controller1
example.com/api/module2/controller2
example.com/api/module2/controller3
</code>```

In index we can setup the root path

```<code>const containerConfig = await InversifyConfigContainer();
let routerConfig = express.Router({caseSensitive: false});
const app = express();
const server = new InversifyExpressServer(
    containerConfig,
    routerConfig,
    {
        rootPath: '/api'
    },
    app);
</code>```

We have userRouter

```<code>import { NextFunction, Request, Response } from 'express';
import { inject } from 'inversify';
import { controller, httpPost, httpPut } from 'inversify-express-utils';
import { ApiOperationPost, ApiPath } from 'swagger-express-ts';
import TYPES from '@ioc/constant/Types';
import DtoRouteValidationMiddleware from '@shared-infra/http/middleware/DtoRouteValidationMiddleware';
import { UserDTO } from '@user-module/application/dtos/UserDto';
import { CreateUserController } from '../controller/CreateUserController';
import { UpdateUserController } from '../controller/UpdateUserController';

@ApiPath({
  name: 'Users',
  path: '/user'
})
@controller('/user')
export abstract class UserRouters {
  constructor(
    @inject(TYPES.CreateUserController)
    private readonly _createUserController: CreateUserController,

    @inject(TYPES.UpdateUserController)
    private readonly _updateUserController: UpdateUserController
  ) {}

  @ApiOperationPost({
    description: 'Create New User',
    summary: 'Creating the new user for todo application ',
    parameters: {
      body: { description: 'Create New User', required: true, model: 'User' }
    },
    responses: {
      200: { description: 'Success' },
      400: { description: 'Something fails' }
    }
  })
  @httpPost('/', DtoRouteValidationMiddleware(UserDTO))
  public async createUser(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    return this._createUserController.execute(request, response, next);
  }

  @httpPut('/:id')
  public async updateUser(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    return this._updateUserController.execute(request, response, next);
  }
}
</code>```

I want configure that path at top instead of writing again in all the child route as

moduleAcontroller1.ts

@controller('/moduleA/controller1')

moduleAcontroller2.ts

@controller('/moduleA/controller2')

Instead I am figuring how to do

module1Parent.ts // this should hold based path for moduleA

moduleAcontroller1.ts

@controller('/controller1')

moduleAcontroller2.ts

@controller('/controller2')

Lets say user, todo are related to moduleA and other features xyz, pqr related to moduleB

How can we make a parent route for moduleA which takes the path of example.com/api/moduleA and then pass all the child routes like user and todo under it, similarly for moduleB which should further handle route example.com/api/moduleB/xyz

example.com/api/moduleB/pqr

Body:
I have multiple modules and want to club them under one route path based on module

example.com/api/moduleA/controller1
example.com/api/module1/controller2
example.com/api/module1/controller3

example.com/api/module2/controller1
example.com/api/module2/controller2
example.com/api/module2/controller3

In index we can setup the root path

const containerConfig = await InversifyConfigContainer();
let routerConfig = express.Router({caseSensitive: false});
const app = express();
const server = new InversifyExpressServer(
    containerConfig,
    routerConfig,
    {
        rootPath: '/api'
    },
    app);

We have userRouter

import { NextFunction, Request, Response } from 'express';
import { inject } from 'inversify';
import { controller, httpPost, httpPut } from 'inversify-express-utils';
import { ApiOperationPost, ApiPath } from 'swagger-express-ts';
import TYPES from '@ioc/constant/Types';
import DtoRouteValidationMiddleware from '@shared-infra/http/middleware/DtoRouteValidationMiddleware';
import { UserDTO } from '@user-module/application/dtos/UserDto';
import { CreateUserController } from '../controller/CreateUserController';
import { UpdateUserController } from '../controller/UpdateUserController';

@ApiPath({
  name: 'Users',
  path: '/user'
})
@controller('/user')
export abstract class UserRouters {
  constructor(
    @inject(TYPES.CreateUserController)
    private readonly _createUserController: CreateUserController,

    @inject(TYPES.UpdateUserController)
    private readonly _updateUserController: UpdateUserController
  ) {}

  @ApiOperationPost({
    description: 'Create New User',
    summary: 'Creating the new user for todo application ',
    parameters: {
      body: { description: 'Create New User', required: true, model: 'User' }
    },
    responses: {
      200: { description: 'Success' },
      400: { description: 'Something fails' }
    }
  })
  @httpPost('/', DtoRouteValidationMiddleware(UserDTO))
  public async createUser(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    return this._createUserController.execute(request, response, next);
  }

  @httpPut('/:id')
  public async updateUser(
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    return this._updateUserController.execute(request, response, next);
  }
}

I want configure that path at top instead of writing again in all the child route as

moduleAcontroller1.ts

@controller('/moduleA/controller1')

moduleAcontroller2.ts

@controller('/moduleA/controller2')

Instead I am figuring how to do

module1Parent.ts // this should hold based path for moduleA

moduleAcontroller1.ts

@controller('/controller1')

moduleAcontroller2.ts

@controller('/controller2')

Lets say user, todo are related to moduleA and other features xyz, pqr related to moduleB

How can we make a parent route for moduleA which takes the path of example.com/api/moduleA and then pass all the child routes like user and todo under it, similarly for moduleB which should further handle route example.com/api/moduleB/xyz

example.com/api/moduleB/pqr


问:
react native ListHeaderComponent suddenly hidden when update new data to FlatList
I am trying to make header of FlatList into new component, look like this:

Here is my FlatList:

```<code><FlatList
        style={{
          width: '100%',
          height: '100%'
        }}
        data={roomList?.length > 0 ? roomList : roomListFromDb}
        key={(item, index) => `${item.RoomId}_${index}`}
        keyExtractor={(item) => `${item.RoomId}`}
        renderItem={({item}) => <RecentlyRoomItem room={item} updateReadMessageLocalFromRoom={updateReadMessageLocalFromRoom}/>}
        ItemSeparatorComponent={ListDivider}
        contentContainerStyle={{
          flexGrow: 1
        }}
        onScroll={handleScroll}
        ListHeaderComponent={RecentlyStoryHeader} -> here is my header
        ListEmptyComponent={FlatListEmptyView}
        onEndReached={(d) => {
          // console.log('onEndReached', canLoadMore)
          if (canLoadMore && roomList.length > 0) {
            console.log('onLoadmore', roomList.length)
            setLoadingMore(true)
          }
        }}
        initialNumToRender={20}
        onEndReachedThreshold={0.1}
        ListFooterComponent={
          <View>
            {(isLoadingMore && canLoadMore) ? (
              <ActivityIndicator color={theme.mainOrangeColor} style={{ margin: 10 }} />
            ) : <ListDivider/>}
          </View>
        }
</code>```

When first time set data, It's show Header normally

But after scroll to loadmore, I call to get data and set data again, after this I did not see the header any more

Here is the method I trigger get data again:

```<code>useEffect(() => {
    if (isLoadingMore) {
      console.log('refresh data based on isLoadingMore state changed')
      _getRoomList() => get more data and append to list
    }
  }, [isLoadingMore])
</code>```

Can someone help me to know the problem?
If I changed to

```<code>ListHeaderComponent={() => <RecentlyStoryHeader />}
</code>```

it's success show the header again, but the method getStoryData() called everytimes it's re-render, i dont want that

Body:
I am trying to make header of FlatList into new component, look like this:

Here is my FlatList:

<FlatList
        style={{
          width: '100%',
          height: '100%'
        }}
        data={roomList?.length > 0 ? roomList : roomListFromDb}
        key={(item, index) => `${item.RoomId}_${index}`}
        keyExtractor={(item) => `${item.RoomId}`}
        renderItem={({item}) => <RecentlyRoomItem room={item} updateReadMessageLocalFromRoom={updateReadMessageLocalFromRoom}/>}
        ItemSeparatorComponent={ListDivider}
        contentContainerStyle={{
          flexGrow: 1
        }}
        onScroll={handleScroll}
        ListHeaderComponent={RecentlyStoryHeader} -> here is my header
        ListEmptyComponent={FlatListEmptyView}
        onEndReached={(d) => {
          // console.log('onEndReached', canLoadMore)
          if (canLoadMore && roomList.length > 0) {
            console.log('onLoadmore', roomList.length)
            setLoadingMore(true)
          }
        }}
        initialNumToRender={20}
        onEndReachedThreshold={0.1}
        ListFooterComponent={
          <View>
            {(isLoadingMore && canLoadMore) ? (
              <ActivityIndicator color={theme.mainOrangeColor} style={{ margin: 10 }} />
            ) : <ListDivider/>}
          </View>
        }

When first time set data, It's show Header normally

But after scroll to loadmore, I call to get data and set data again, after this I did not see the header any more

Here is the method I trigger get data again:

useEffect(() => {
    if (isLoadingMore) {
      console.log('refresh data based on isLoadingMore state changed')
      _getRoomList() => get more data and append to list
    }
  }, [isLoadingMore])

Can someone help me to know the problem?
If I changed to

ListHeaderComponent={() => <RecentlyStoryHeader />}

it's success show the header again, but the method getStoryData() called everytimes it's re-render, i dont want that


问:
unrecognized arguments: in PyTest
I am unable to generate a html report in pytest. I have installed pytest --html without any issue.

When i tried to run

```<code> py.test --html=report.html
</code>```

getting unrecognized arguments error. I've surfed internet a lot everyone is telling pytest --html might not installed but in mu case everything been installed still getting that error message.

I tried installing package in PyCharm as well didn't worked

Title: unrecognized arguments: in PyTest

Body:
I am unable to generate a html report in pytest. I have installed pytest --html without any issue.

When i tried to run

 py.test --html=report.html

getting unrecognized arguments error. I've surfed internet a lot everyone is telling pytest --html might not installed but in mu case everything been installed still getting that error message.

I tried installing package in PyCharm as well didn't worked


问:
Connecting to two different databases from Spring Boot, second one not created
I am trying to connect to two different databases in Spring Boot.
I want to connect to a MySQL database and an in-memory H2 database.
My application runs fine, but when I try to return all data in a table from the second database connection (H2) called 'Lobby', I get the following error:

Table "LOBBY" not found (this database is empty)

Here is my application.properties file (Please note I put in some dummy MySQL credentials for this post).

# Main DB -
spring.datasource.jdbc-url=jdbc:mysql://localhost
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.tomcat.test-while-idle=true
spring.datasource.tomcat.validation-query=SELECT 1

# In Memory, WebSocket and Secondary DB -
spring.datasource.second.jdbc-url=jdbc:h2:mem:test
spring.datasource.second.username=sa
spring.datasource.second.password=sa
spring.datasource.second.driver-class-name=org.h2.Driver

# Extra Options -
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
server.error.include-message=always
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database=default
```
<p>Here are my code snippets.
PrimaryDbConfig:</p>
<pre class="lang-java prettyprint-override"><code>package codenemy.api.Configuration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {
                "codenemy.api.Auth.repository",
                "codenemy.api.Problem.repository",
                "codenemy.api.Submission.repository"})
public class PrimaryDbConfig {
    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    ) {
        return builder
                .dataSource(dataSource)
                .packages(
                        "codenemy.api.Auth.model",
                        "codenemy.api.Problem.model",
                        "codenemy.api.Submission.model")
                .persistenceUnit("Role")
                .persistenceUnit("User")
                .persistenceUnit("Language")
                .persistenceUnit("Problem")
                .persistenceUnit("ProblemLanguage")
                .persistenceUnit("Tag")
                .persistenceUnit("TestCase")
                .persistenceUnit("Submission")
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Primary
    @Bean
    public EntityManagerFactoryBuilder entityManagerFactoryBuilder() {
        return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), new HashMap<>(), null);
    }

}
</code>```

SecondaryDbConfig

package codenemy.api.Configuration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "secondaryEntityManagerFactory",
        transactionManagerRef = "secondaryTransactionManager",
        basePackages = {"codenemy.api.WebSocket.repository"})
public class SecondaryDbConfig {

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
            @Qualifier("secondaryEntityManagerFactoryBuilder") EntityManagerFactoryBuilder builder,
            @Qualifier("secondaryDataSource") DataSource dataSource)
    {
        return builder
                .dataSource(dataSource)
                .packages("codenemy.api.WebSocket.model").build();
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager(
            @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {
        return new JpaTransactionManager(secondaryEntityManagerFactory);
    }

    @Bean(name = "secondaryEntityManagerFactoryBuilder")
    public EntityManagerFactoryBuilder entityManagerFactoryBuilder() {
        return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), new HashMap<>(), null);
    }
}
```

Body:
I am trying to connect to two different databases in Spring Boot.
I want to connect to a MySQL database and an in-memory H2 database.
My application runs fine, but when I try to return all data in a table from the second database connection (H2) called 'Lobby', I get the following error:

Table "LOBBY" not found (this database is empty)

Here is my application.properties file (Please note I put in some dummy MySQL credentials for this post).

# Main DB -
spring.datasource.jdbc-url=jdbc:mysql://localhost
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.tomcat.test-while-idle=true
spring.datasource.tomcat.validation-query=SELECT 1

# In Memory, WebSocket and Secondary DB -
spring.datasource.second.jdbc-url=jdbc:h2:mem:test
spring.datasource.second.username=sa
spring.datasource.second.password=sa
spring.datasource.second.driver-class-name=org.h2.Driver

# Extra Options -
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
server.error.include-message=always
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database=default

Here are my code snippets.
PrimaryDbConfig:

package codenemy.api.Configuration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {
                "codenemy.api.Auth.repository",
                "codenemy.api.Problem.repository",
                "codenemy.api.Submission.repository"})
public class PrimaryDbConfig {
    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    ) {
        return builder
                .dataSource(dataSource)
                .packages(
                        "codenemy.api.Auth.model",
                        "codenemy.api.Problem.model",
                        "codenemy.api.Submission.model")
                .persistenceUnit("Role")
                .persistenceUnit("User")
                .persistenceUnit("Language")
                .persistenceUnit("Problem")
                .persistenceUnit("ProblemLanguage")
                .persistenceUnit("Tag")
                .persistenceUnit("TestCase")
                .persistenceUnit("Submission")
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Primary
    @Bean
    public EntityManagerFactoryBuilder entityManagerFactoryBuilder() {
        return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), new HashMap<>(), null);
    }

}

SecondaryDbConfig

package codenemy.api.Configuration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "secondaryEntityManagerFactory",
        transactionManagerRef = "secondaryTransactionManager",
        basePackages = {"codenemy.api.WebSocket.repository"})
public class SecondaryDbConfig {

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
            @Qualifier("secondaryEntityManagerFactoryBuilder") EntityManagerFactoryBuilder builder,
            @Qualifier("secondaryDataSource") DataSource dataSource)
    {
        return builder
                .dataSource(dataSource)
                .packages("codenemy.api.WebSocket.model").build();
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager(
            @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {
        return new JpaTransactionManager(secondaryEntityManagerFactory);
    }

    @Bean(name = "secondaryEntityManagerFactoryBuilder")
    public EntityManagerFactoryBuilder entityManagerFactoryBuilder() {
        return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), new HashMap<>(), null);
    }
}


问:
Comunication with object android-wfc
I need to comunicate information between a webservice wfc soad with an android device.
I get to comunicate strings, but now I want to send objects that the web service will work with.

I followed this tutorial.

However, it doesn't work for me. I get the error below:

```<code>SoapFault - faultcode: 'a:DeserializationFailed' faultstring: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:user. The InnerException message was 'Element user from namespace http://tempuri.org/ cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.'.  Please see InnerException for more details.' faultactor: 'null' detail: null
</code>```

Seems that my webservice can deserialize my object... but why?
Also I saw that the "user" object I sent is in another namespace of the webservice, so I don't know if it could influence, if this do something, how can I correct it?

And at last, is there any method to see what xml(soad) are using in the comunications?

Thanks

ContentLicense: CC BY-SA 3.0

Title: Comunication with object android-wfc

Body:
I need to comunicate information between a webservice wfc soad with an android device.
I get to comunicate strings, but now I want to send objects that the web service will work with.

I followed this tutorial.

However, it doesn't work for me. I get the error below:

SoapFault - faultcode: 'a:DeserializationFailed' faultstring: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:user. The InnerException message was 'Element user from namespace http://tempuri.org/ cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.'.  Please see InnerException for more details.' faultactor: 'null' detail: null

Seems that my webservice can deserialize my object... but why?
Also I saw that the "user" object I sent is in another namespace of the webservice, so I don't know if it could influence, if this do something, how can I correct it?

And at last, is there any method to see what xml(soad) are using in the comunications?

Thanks


问:
Getting a PWA to be shown without an address bar WITHOUT play store
I have a PWA in development. It is currently unavailable online.
I've used http-server npm module in order to serve the website locally.
Navigating to the URL through my android phone, I'm being able to install the app, but then, when it opens, the address bar is displayed - even though I have "display": "standalone" in my manifest.webmanifest file.
Looking up online, it seems like I have to have a ./well-known/assetlinks.json. I've manually created one, and served it staticly:

```<code>[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "il.co.my-app",
    "sha256_cert_fingerprints": ["14:6D:E9..."]
  }
}]
</code>```

Nothing changed.

However, it seems like this assetlinks.json is irellevant to me as I don't really have an app, just a PWA website.

Watching the following quick start guide, it shows that the fingerprints should be generated by the app store and that Android validates the integritiy of the app through its' Play Store.

So my question is - does it mean that you cannot have the address bar removed from an PWA without going through the process of actually deploying the app to the Play Store?
As mentioned, this is simply a responsive website, and doesn't have any APK's etc.

Thank you!

Body:
I have a PWA in development. It is currently unavailable online.
I've used http-server npm module in order to serve the website locally.
Navigating to the URL through my android phone, I'm being able to install the app, but then, when it opens, the address bar is displayed - even though I have "display": "standalone" in my manifest.webmanifest file.
Looking up online, it seems like I have to have a ./well-known/assetlinks.json. I've manually created one, and served it staticly:

[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "il.co.my-app",
    "sha256_cert_fingerprints": ["14:6D:E9..."]
  }
}]

Nothing changed.

However, it seems like this assetlinks.json is irellevant to me as I don't really have an app, just a PWA website.

Watching the following quick start guide, it shows that the fingerprints should be generated by the app store and that Android validates the integritiy of the app through its' Play Store.

So my question is - does it mean that you cannot have the address bar removed from an PWA without going through the process of actually deploying the app to the Play Store?
As mentioned, this is simply a responsive website, and doesn't have any APK's etc.

Thank you!


问:
How to create 3 layer Combo Box (Active X Control) on a sheet - Excel VBA
I am trying to create a 3 layer combo box drop down on one of my sheets (not in a form).

I achieved this using data validation and named ranges but the drop down arrow only appears when you click on the box which is annoying and I want this tool to be as intuitive as possible for the users.

I have found examples of 2 layer combo boxes using switch cases which I can kind of follow but the next layer is hurting my head.

```<code>Layer 1 - Route (30 Values)
Layer 2 - Conveyor Number (5-10 Values per Route)
Layer 3 - Record Reference (4-20 Values per Conveyor Number)
</code>```

I want to read the values from the combo boxes and pass to various command buttons on the sheet.

If there is an easy way of doing this rather than writing out many switch cases that would be great

I have included an image of Route 1 to give context and an image of my dashboard.

Body:
I am trying to create a 3 layer combo box drop down on one of my sheets (not in a form).

I achieved this using data validation and named ranges but the drop down arrow only appears when you click on the box which is annoying and I want this tool to be as intuitive as possible for the users.

I have found examples of 2 layer combo boxes using switch cases which I can kind of follow but the next layer is hurting my head.

Layer 1 - Route (30 Values)
Layer 2 - Conveyor Number (5-10 Values per Route)
Layer 3 - Record Reference (4-20 Values per Conveyor Number)

I want to read the values from the combo boxes and pass to various command buttons on the sheet.

If there is an easy way of doing this rather than writing out many switch cases that would be great

I have included an image of Route 1 to give context and an image of my dashboard.


问:
capacitor + axios ignores Content-Type header setting
Good day,
I am am developing an Vuejs application which runs an web, but will also be published as an app on both Android and iOS. Part of the application is uploading images to a server.
When using this function running on web this function works as supposed, but on within the android app (build with capacitor) the Content-Type header for sending a file is ignored.
On server-side i recieve a 'Content-Type', 'application/x-www-form-urlencoded' even though i force the header to be 'multipart/form-data'

Here's the code i use for sending the request

```<code>  var config = {
        method: 'post',
        url: '/api/urenbon/',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data: formData
    };

    axios(config)
</code>```

Body:
Good day,
I am am developing an Vuejs application which runs an web, but will also be published as an app on both Android and iOS. Part of the application is uploading images to a server.
When using this function running on web this function works as supposed, but on within the android app (build with capacitor) the Content-Type header for sending a file is ignored.
On server-side i recieve a 'Content-Type', 'application/x-www-form-urlencoded' even though i force the header to be 'multipart/form-data'

Here's the code i use for sending the request

  var config = {
        method: 'post',
        url: '/api/urenbon/',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data: formData
    };

    axios(config)


问:
Add sequential number in data frame start with the last column value in table + 1 in Scala
I have scenario to add monotonically_increasing_id but it should start from the number + 1 available in the column last value

Ex. If in table last value is 5, then it should start with 6

tried monotonically_increasing_id but it is generating seq number start from 1


问:
How to play raw audio data(G.711 μ-law) in Swift
I am not familiar with the handling of audio data and would appreciate your help.

I would like to playback audio data in real-time streaming.

Audio can be received via HTTP interface

The bytes returned are in G711 µlaw

I am implementing this with reference to https://github.com/syedhali/AudioStreamer
Implementation has confirmed that MP3 streaming data can be played.

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) of URLSessionDataDelegate is called and tries to parse the received Data using AudioFileStreamParseBytes, but a kAudioFileStreamError_UnsupportedFileType error occurs.

```<code>    public init() throws {
        let context = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
        guard AudioFileStreamOpen(context, ParserPropertyChangeCallback, ParserPacketCallback, 0, &streamID) == noErr else {
            throw ParserError.streamCouldNotOpen
        }
    }

    public func parse(data: Data) throws {
        let streamID = self.streamID!
        let count = data.count
        data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
            let result = AudioFileStreamParseBytes(streamID, UInt32(count), bytes, [])
            guard result == noErr else {
                throw ParserError.failedToParseBytes(result)
            }
        }
    }
</code>```

Please tell me how to handle G711 µlaw raw data on iOS?

Thanks.

Body:
I am not familiar with the handling of audio data and would appreciate your help.

I would like to playback audio data in real-time streaming.

Audio can be received via HTTP interface

The bytes returned are in G711 µlaw

I am implementing this with reference to https://github.com/syedhali/AudioStreamer
Implementation has confirmed that MP3 streaming data can be played.

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) of URLSessionDataDelegate is called and tries to parse the received Data using AudioFileStreamParseBytes, but a kAudioFileStreamError_UnsupportedFileType error occurs.

    public init() throws {
        let context = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
        guard AudioFileStreamOpen(context, ParserPropertyChangeCallback, ParserPacketCallback, 0, &streamID) == noErr else {
            throw ParserError.streamCouldNotOpen
        }
    }

    public func parse(data: Data) throws {
        let streamID = self.streamID!
        let count = data.count
        data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
            let result = AudioFileStreamParseBytes(streamID, UInt32(count), bytes, [])
            guard result == noErr else {
                throw ParserError.failedToParseBytes(result)
            }
        }
    }

Please tell me how to handle G711 µlaw raw data on iOS?

Thanks.


问:
How can I get the Exception message from code behind in my jQuery.ajax?
This is my ASP.NET code -

if (appointmentScheduledStartDate.HasValue)
{
   var appointmentDate = appointmentScheduledStartDate.Value.Date.AddDays(1);
   if(appointmentDate < currentDateAndTime)
   {
      throw new Exception("Link Expired");
   }
}
```
<p>And this is my jQuery.</p>
<pre class="lang-js prettyprint-override"><code>
function logChekInData(entityName, recordId, userId, lat, lon) {

x.innerHTML = "Please wait...";
            $.ajax({
                type: "POST",
                dataType: "Json",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("LogCheckIn", "InvestigatorCheckIn")',
                data: JSON.stringify({
                    'entityName': entityName,
                    "recordId": recordId,
                    "userId": userId,
                    "lat": lat,
                    "lon": lon
                }),
                async: false,
                success: function (data) {
                    x.innerHTML = "Successfully tracked your location.";
                },
                error: function (xhr) {
                    x.innerHTML = xhr.responseText.Message;
                    //x.innerHTML = "Error occured. Please try later.";
                   //alert(xhr.responseText);
                }
            });
    }

</code>```

Let me know how can I get the exception message via jQuery.ajax? I'm getting undefined message every time. How can I solve this ?

Body:
This is my ASP.NET code -

if (appointmentScheduledStartDate.HasValue)
{
   var appointmentDate = appointmentScheduledStartDate.Value.Date.AddDays(1);
   if(appointmentDate < currentDateAndTime)
   {
      throw new Exception("Link Expired");
   }
}

And this is my jQuery.

function logChekInData(entityName, recordId, userId, lat, lon) {

x.innerHTML = "Please wait...";
            $.ajax({
                type: "POST",
                dataType: "Json",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("LogCheckIn", "InvestigatorCheckIn")',
                data: JSON.stringify({
                    'entityName': entityName,
                    "recordId": recordId,
                    "userId": userId,
                    "lat": lat,
                    "lon": lon
                }),
                async: false,
                success: function (data) {
                    x.innerHTML = "Successfully tracked your location.";
                },
                error: function (xhr) {
                    x.innerHTML = xhr.responseText.Message;
                    //x.innerHTML = "Error occured. Please try later.";
                   //alert(xhr.responseText);
                }
            });
    }

Let me know how can I get the exception message via jQuery.ajax? I'm getting undefined message every time. How can I solve this ?


问:
node:internal/errors:484 ErrorCaptureStackTrace(err);
When i run vendor/bin/sail npm run dev i got this error. Can anyone explain why that is happening ? i am setting up aws server for my laravel website

```<code>  LARAVEL v9.46.0  plugin v0.7.3

  ➜  APP_URL: http://localhost
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error: ENOSPC: System limit for number of file watchers reached, watch '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub'                                                                                eption-report.stub'
    at FSWatcher.<computed> (node:internal/fs/watchers:244:19)
    at Object.watch (node:fs:2315:34)
    at createFsWatchInstance (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48596:17)
    at setFsWatchListener (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48643:15)
    at NodeFsHandler._watchWithNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48798:14)
    at NodeFsHandler._handleFile (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48862:23)
    at NodeFsHandler._addToNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:49104:21)
Emitted 'error' event on FSWatcher instance at:
    at FSWatcher._handleError (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:50296:10)
    at NodeFsHandler._addToNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:49112:18) {
  errno: -28,
  syscall: 'watch',
  code: 'ENOSPC',
  path: '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub',
  filename: '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub'
}

Node.js v18.12.1
</code>```

i have tried npm audit fix --force but it still not working

Body:
When i run vendor/bin/sail npm run dev i got this error. Can anyone explain why that is happening ? i am setting up aws server for my laravel website

  LARAVEL v9.46.0  plugin v0.7.3

  ➜  APP_URL: http://localhost
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error: ENOSPC: System limit for number of file watchers reached, watch '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub'                                                                                eption-report.stub'
    at FSWatcher.<computed> (node:internal/fs/watchers:244:19)
    at Object.watch (node:fs:2315:34)
    at createFsWatchInstance (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48596:17)
    at setFsWatchListener (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48643:15)
    at NodeFsHandler._watchWithNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48798:14)
    at NodeFsHandler._handleFile (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:48862:23)
    at NodeFsHandler._addToNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:49104:21)
Emitted 'error' event on FSWatcher instance at:
    at FSWatcher._handleError (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:50296:10)
    at NodeFsHandler._addToNodeFs (file:///var/www/html/node_modules/vite/dist/node/chunks/dep-5e7f419b.js:49112:18) {
  errno: -28,
  syscall: 'watch',
  code: 'ENOSPC',
  path: '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub',
  filename: '/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/exception-report.stub'
}

Node.js v18.12.1

i have tried npm audit fix --force but it still not working


问:
MongoDB - Aggregation Method
How to use aggregation method using MongoDB compass? May be an example with the output would be really helpful.

From a large amount of data had to find out how many people are interested in Golf. We used $match and $group focusing on a unique data type. But we aren't getting proper output.

Title: MongoDB - Aggregation Method


问:
Shaders and Postprocessing making textures darker
I am working on a Threejs image carousel with React. Currently trying to add a light motion blur whilst fast dragging. I found this shader composition on code pen but it seems to be making my textures darker or highly contrasted.

This is the appearance without the Effects.jsx component

This is the apperance with the Effects.jsx component

Here is my main ImageCarousel.jsx component

```<code>const ImageCarousel = () => {
  return (
    <>
      <Canvas
        orthographic
        gl={{ antialias: false }}
        dpr={[1, 1.5]}
        mode="concurrent"
        camera={{ zoom: 200, position: [0, 0, 5] }}
      >
        <Items />
        <Effects />
      </Canvas>
    </>
  );
};
</code>```

Here is my Effects.jsx component

```<code>import * as THREE from "three";
import React, { useMemo, useEffect } from "react";
import { useThree, useFrame } from "@react-three/fiber";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass";
import { SavePass } from "three/examples/jsm/postprocessing/SavePass";
import { CopyShader } from "three/examples/jsm/shaders/CopyShader";
import { BlendShader } from "three/examples/jsm/shaders/BlendShader";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass";

const Effects = () => {
  const { scene, gl, size, camera } = useThree();
  const composer = useMemo(() => {
    const composer = new EffectComposer(gl);
    const renderPass = new RenderPass(scene, camera);

    const savePass = new SavePass(
      new THREE.WebGLRenderTarget(
        size.width,
        size.height
      )
    );

    const blendPass = new ShaderPass(BlendShader, "tDiffuse1");
    blendPass.uniforms["tDiffuse2"].value = savePass.renderTarget.texture;
    blendPass.uniforms["mixRatio"].value = 0.5;

    const outputPass = new ShaderPass(CopyShader);
    outputPass.renderToScreen = true;
    composer.addPass(renderPass);
    composer.addPass(blendPass);
    composer.addPass(savePass);
    composer.addPass(outputPass);

    return composer;
  }, [camera, scene, gl, size]);
  useEffect(
    () => void composer.setSize(size.width, size.height),
    [size, composer]
  );
  useFrame(() => composer.render(), 1);
  return null;
};

export default Effects;
</code>```

Body:
I am working on a Threejs image carousel with React. Currently trying to add a light motion blur whilst fast dragging. I found this shader composition on code pen but it seems to be making my textures darker or highly contrasted.

This is the appearance without the Effects.jsx component

This is the apperance with the Effects.jsx component

Here is my main ImageCarousel.jsx component

const ImageCarousel = () => {
  return (
    <>
      <Canvas
        orthographic
        gl={{ antialias: false }}
        dpr={[1, 1.5]}
        mode="concurrent"
        camera={{ zoom: 200, position: [0, 0, 5] }}
      >
        <Items />
        <Effects />
      </Canvas>
    </>
  );
};

Here is my Effects.jsx component

import * as THREE from "three";
import React, { useMemo, useEffect } from "react";
import { useThree, useFrame } from "@react-three/fiber";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer";
import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass";
import { SavePass } from "three/examples/jsm/postprocessing/SavePass";
import { CopyShader } from "three/examples/jsm/shaders/CopyShader";
import { BlendShader } from "three/examples/jsm/shaders/BlendShader";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass";

const Effects = () => {
  const { scene, gl, size, camera } = useThree();
  const composer = useMemo(() => {
    const composer = new EffectComposer(gl);
    const renderPass = new RenderPass(scene, camera);

    const savePass = new SavePass(
      new THREE.WebGLRenderTarget(
        size.width,
        size.height
      )
    );

    const blendPass = new ShaderPass(BlendShader, "tDiffuse1");
    blendPass.uniforms["tDiffuse2"].value = savePass.renderTarget.texture;
    blendPass.uniforms["mixRatio"].value = 0.5;

    const outputPass = new ShaderPass(CopyShader);
    outputPass.renderToScreen = true;
    composer.addPass(renderPass);
    composer.addPass(blendPass);
    composer.addPass(savePass);
    composer.addPass(outputPass);

    return composer;
  }, [camera, scene, gl, size]);
  useEffect(
    () => void composer.setSize(size.width, size.height),
    [size, composer]
  );
  useFrame(() => composer.render(), 1);
  return null;
};

export default Effects;


问:
Conditional rendering from string in email template
I have a email template module in CMS. User can update and uses the variables in email content.

For example:

```<code>Hi {first_name},
</code>```

I want to also convert the if statement from the string like this:

```<code>Hi {first_name},
{% if foo == 'bar' %}
Some content
{% endif %}
</code>```

My code here:

```<code>// EmailTemplate.php
public function parse($content, $except = []){
    $data = collect($this->model->getEmailVars())->except($except)->toArray();
    $parsed = preg_replace_callback('/{\s?(.*?)\s?}/', function ($matches) use ($data) {
        list($shortCode, $index) = $matches;

        if(isset($data[$index]) ) {
            return $data[$index];
        }

        return $shortCode;

    }, $content);

    return $parsed;
}

// $this->model in EmailTemplate.php
public function getEmailVars(){

    return [
        'first_name' => $this->first_name,
        'foo' => $this->foo,
    ];
}
</code>```

Any idea how to achieve this? Thanks.

Body:
I have a email template module in CMS. User can update and uses the variables in email content.

For example:

Hi {first_name},

I want to also convert the if statement from the string like this:

Hi {first_name},
{% if foo == 'bar' %}
Some content
{% endif %}

My code here:

// EmailTemplate.php
public function parse($content, $except = []){
    $data = collect($this->model->getEmailVars())->except($except)->toArray();
    $parsed = preg_replace_callback('/{\s?(.*?)\s?}/', function ($matches) use ($data) {
        list($shortCode, $index) = $matches;

        if(isset($data[$index]) ) {
            return $data[$index];
        }

        return $shortCode;

    }, $content);

    return $parsed;
}

// $this->model in EmailTemplate.php
public function getEmailVars(){

    return [
        'first_name' => $this->first_name,
        'foo' => $this->foo,
    ];
}

Any idea how to achieve this? Thanks.


问:
::-webkit-scrollbar-thumb is not working with a page height of 100 percentage. Can anyone help me out?
Here I am trying to apply custom scrollbar and scrollbar-thumb to my webpage.
Below is my code in Sass.

app-overview is an Angular component.

```<code>app-overview {
   font-family: 'Interstate-Regular', sans-serif;
    height: 100%;
    width: 100%;
    // height: 500px;
    overflow: scroll;
    overflow-x: hidden;
    // overflow-y: auto;
</code>```

above is my app-overview css.

I am using this also

```<code>::-webkit-scrollbar{
    width: 0px;
} //it will remove scrollbar from the whole body.
</code>```

Here is my app-overview scrollbar code

```<code>app-overview::-webkit-scrollbar{
    width: 15px;
    background: rgb(142, 140, 140);
    // -webkit-appearance: none;
}
</code>```

Above code are working fine. But the problem is scrollbar-thumb is not working.

```<code>app-overview::-webkit-scrollbar-thumb{
    background-color: #ccd1d4;
    -webkit-appearance: none;
    // height: 50px;
}

//I've tried height also, but not working.
</code>```

Anyone have any solutions? Thanks in advance!

I've tried all possible ways to make the scrollbar-thumb visible, but not getting the scrollbar-thumb

Body:
Here I am trying to apply custom scrollbar and scrollbar-thumb to my webpage.
Below is my code in Sass.

app-overview is an Angular component.

app-overview {
   font-family: 'Interstate-Regular', sans-serif;
    height: 100%;
    width: 100%;
    // height: 500px;
    overflow: scroll;
    overflow-x: hidden;
    // overflow-y: auto;

above is my app-overview css.

I am using this also

::-webkit-scrollbar{
    width: 0px;
} //it will remove scrollbar from the whole body.

Here is my app-overview scrollbar code

app-overview::-webkit-scrollbar{
    width: 15px;
    background: rgb(142, 140, 140);
    // -webkit-appearance: none;
}

Above code are working fine. But the problem is scrollbar-thumb is not working.

app-overview::-webkit-scrollbar-thumb{
    background-color: #ccd1d4;
    -webkit-appearance: none;
    // height: 50px;
}

//I've tried height also, but not working.

Anyone have any solutions? Thanks in advance!

I've tried all possible ways to make the scrollbar-thumb visible, but not getting the scrollbar-thumb


问:
DwmSetWindowAttribute - change color and border (non client area)
I'm working on a .NET Framework (4.8) winform project and I fail to use dwmapi.

I'm trying to customize a non client area, the titlebar and the border.

Here's some code showing tests on corners and borders color... but I get the same error (HRESULT) : The value is not within the expected range.

Are the values wrong, is the signature wrong too?

Maybe I'm not using the right dll? Or I use it the wrong way?

Please enlighten me

PS: I can set formBorderStyle to none but I will loose many features that I don't want to implement myself. I already did, but I would like to go back to windows native titlebar.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PnvUserControls.AppTest
{
    public class FormNative : Form
    {

        [DllImport("dwmapi.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE dwAttribute, ref DWM_WINDOW_CORNER_PREFERENCE pvAttribute, int cbAttribute);

        [DllImport("dwmapi.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE dwAttribute, ref int pvAttribute, int cbAttribute);

        public FormNative() : base()
        {
            TestBorderColor();
            TestRoundCorner();
        }

        private void TestRoundCorner()
        {
            IntPtr hWnd = this.Handle;
            var dwAttribute = DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE;
            var pvAttribute = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_ROUND;
            DwmSetWindowAttribute(hWnd, dwAttribute, ref pvAttribute, Marshal.SizeOf(pvAttribute));
        }

        private void TestBorderColor()
        {
            IntPtr hWnd = this.Handle;
            var dwAttribute = DWMWINDOWATTRIBUTE.DWMWA_BORDER_COLOR;
            var pvAttribute = 0x00FF0000; //red
            DwmSetWindowAttribute(hWnd, dwAttribute, ref pvAttribute, Marshal.SizeOf(pvAttribute));
        }

    }
    // The DWM_WINDOW_CORNER_PREFERENCE enum for DwmSetWindowAttribute's third parameter, which tells the function
    // what value of the enum to set.
    // Copied from dwmapi.h
    public enum DWM_WINDOW_CORNER_PREFERENCE : uint
    {
        DWMWCP_DEFAULT = 0,
        DWMWCP_DONOTROUND = 1,
        DWMWCP_ROUND = 2,
        DWMWCP_ROUNDSMALL = 3
    }

    [Flags]
    public enum DWMWINDOWATTRIBUTE : uint
    {
        ///
        /// Use with DwmGetWindowAttribute. Discovers whether non-client rendering is enabled. The retrieved value is of type BOOL. TRUE if non-client rendering is enabled; otherwise, FALSE.
        ///
        DWMWA_NCRENDERING_ENABLED = 1,

        ///
        /// Use with DwmSetWindowAttribute. Sets the non-client rendering policy. The pvAttribute parameter points to a value from the DWMNCRENDERINGPOLICY enumeration.
        ///
        DWMWA_NCRENDERING_POLICY,

        ///
        /// Use with DwmSetWindowAttribute. Enables or forcibly disables DWM transitions. The pvAttribute parameter points to a value of type BOOL. TRUE to disable transitions, or FALSE to enable transitions.
        ///
        DWMWA_TRANSITIONS_FORCEDISABLED,

        ///
        /// Use with DwmSetWindowAttribute. Enables content rendered in the non-client area to be visible on the frame drawn by DWM. The pvAttribute parameter points to a value of type BOOL. TRUE to enable content rendered in the non-client area to be visible on the frame; otherwise, FALSE.
        ///
        DWMWA_ALLOW_NCPAINT,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the bounds of the caption button area in the window-relative space. The retrieved value is of type RECT. If the window is minimized or otherwise not visible to the user, then the value of the RECT retrieved is undefined. You should check whether the retrieved RECT contains a boundary that you can work with, and if it doesn't then you can conclude that the window is minimized or otherwise not visible.
        ///
        DWMWA_CAPTION_BUTTON_BOUNDS,

        ///
        /// Use with DwmSetWindowAttribute. Specifies whether non-client content is right-to-left (RTL) mirrored. The pvAttribute parameter points to a value of type BOOL. TRUE if the non-client content is right-to-left (RTL) mirrored; otherwise, FALSE.
        ///
        DWMWA_NONCLIENT_RTL_LAYOUT,

        ///
        /// Use with DwmSetWindowAttribute. Forces the window to display an iconic thumbnail or peek representation (a static bitmap), even if a live or snapshot representation of the window is available. This value is normally set during a window's creation, and not changed throughout the window's lifetime. Some scenarios, however, might require the value to change over time. The pvAttribute parameter points to a value of type BOOL. TRUE to require a iconic thumbnail or peek representation; otherwise, FALSE.
        ///
        DWMWA_FORCE_ICONIC_REPRESENTATION,

        ///
        /// Use with DwmSetWindowAttribute. Sets how Flip3D treats the window. The pvAttribute parameter points to a value from the DWMFLIP3DWINDOWPOLICY enumeration.
        ///
        DWMWA_FLIP3D_POLICY,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the extended frame bounds rectangle in screen space. The retrieved value is of type RECT.
        ///
        DWMWA_EXTENDED_FRAME_BOUNDS,

        ///
        /// Use with DwmSetWindowAttribute. The window will provide a bitmap for use by DWM as an iconic thumbnail or peek representation (a static bitmap) for the window. DWMWA_HAS_ICONIC_BITMAP can be specified with DWMWA_FORCE_ICONIC_REPRESENTATION. DWMWA_HAS_ICONIC_BITMAP normally is set during a window's creation and not changed throughout the window's lifetime. Some scenarios, however, might require the value to change over time. The pvAttribute parameter points to a value of type BOOL. TRUE to inform DWM that the window will provide an iconic thumbnail or peek representation; otherwise, FALSE. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_HAS_ICONIC_BITMAP,

        ///
        /// Use with DwmSetWindowAttribute. Do not show peek preview for the window. The peek view shows a full-sized preview of the window when the mouse hovers over the window's thumbnail in the taskbar. If this attribute is set, hovering the mouse pointer over the window's thumbnail dismisses peek (in case another window in the group has a peek preview showing). The pvAttribute parameter points to a value of type BOOL. TRUE to prevent peek functionality, or FALSE to allow it. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_DISALLOW_PEEK,

        ///
        /// Use with DwmSetWindowAttribute. Prevents a window from fading to a glass sheet when peek is invoked. The pvAttribute parameter points to a value of type BOOL. TRUE to prevent the window from fading during another window's peek, or FALSE for normal behavior. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_EXCLUDED_FROM_PEEK,

        ///
        /// Use with DwmSetWindowAttribute. Cloaks the window such that it is not visible to the user. The window is still composed by DWM. Using with DirectComposition: Use the DWMWA_CLOAK flag to cloak the layered child window when animating a representation of the window's content via a DirectComposition visual that has been associated with the layered child window. For more details on this usage case, see How to animate the bitmap of a layered child window. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_CLOAK,

        ///
        /// Use with DwmGetWindowAttribute. If the window is cloaked, provides one of the following values explaining why. DWM_CLOAKED_APP (value 0x0000001). The window was cloaked by its owner application. DWM_CLOAKED_SHELL(value 0x0000002). The window was cloaked by the Shell. DWM_CLOAKED_INHERITED(value 0x0000004). The cloak value was inherited from its owner window. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_CLOAKED,

        ///
        /// Use with DwmSetWindowAttribute. Freeze the window's thumbnail image with its current visuals. Do no further live updates on the thumbnail image to match the window's contents. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_FREEZE_REPRESENTATION,

        ///
        /// Use with DwmSetWindowAttribute. Enables a non-UWP window to use host backdrop brushes. If this flag is set, then a Win32 app that calls Windows::UI::Composition APIs can build transparency effects using the host backdrop brush (see Compositor.CreateHostBackdropBrush). The pvAttribute parameter points to a value of type BOOL. TRUE to enable host backdrop brushes for the window, or FALSE to disable it. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_USE_HOSTBACKDROPBRUSH,

        ///
        /// Use with DwmSetWindowAttribute. Allows the window frame for this window to be drawn in dark mode colors when the dark mode system setting is enabled. For compatibility reasons, all windows default to light mode regardless of the system setting. The pvAttribute parameter points to a value of type BOOL. TRUE to honor dark mode for the window, FALSE to always use light mode. This value is supported starting with Windows 10 Build 17763.
        ///
        DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19,

        ///
        /// Use with DwmSetWindowAttribute. Allows the window frame for this window to be drawn in dark mode colors when the dark mode system setting is enabled. For compatibility reasons, all windows default to light mode regardless of the system setting. The pvAttribute parameter points to a value of type BOOL. TRUE to honor dark mode for the window, FALSE to always use light mode. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_USE_IMMERSIVE_DARK_MODE = 20,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the rounded corner preference for a window. The pvAttribute parameter points to a value of type DWM_WINDOW_CORNER_PREFERENCE. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_WINDOW_CORNER_PREFERENCE = 33,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the window border. The pvAttribute parameter points to a value of type COLORREF. The app is responsible for changing the border color according to state changes, such as a change in window activation. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_BORDER_COLOR,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the caption. The pvAttribute parameter points to a value of type COLORREF. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_CAPTION_COLOR,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the caption text. The pvAttribute parameter points to a value of type COLORREF. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_TEXT_COLOR,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the width of the outer border that the DWM would draw around this window. The value can vary depending on the DPI of the window. The pvAttribute parameter points to a value of type UINT. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_VISIBLE_FRAME_BORDER_THICKNESS,

        ///
        /// The maximum recognized DWMWINDOWATTRIBUTE value, used for validation purposes.
        ///
        DWMWA_LAST,
    }
}

```

EDIT :

It's not available on Windows 10, only windows 11,
Is there something "similar", low level, that could allow to do this?
I imagine it won't be as easy if they added it lately...

Body:
I'm working on a .NET Framework (4.8) winform project and I fail to use dwmapi.

I'm trying to customize a non client area, the titlebar and the border.

Here's some code showing tests on corners and borders color... but I get the same error (HRESULT) : The value is not within the expected range.

Are the values wrong, is the signature wrong too?

Maybe I'm not using the right dll? Or I use it the wrong way?

Please enlighten me

PS: I can set formBorderStyle to none but I will loose many features that I don't want to implement myself. I already did, but I would like to go back to windows native titlebar.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PnvUserControls.AppTest
{
    public class FormNative : Form
    {

        [DllImport("dwmapi.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE dwAttribute, ref DWM_WINDOW_CORNER_PREFERENCE pvAttribute, int cbAttribute);

        [DllImport("dwmapi.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE dwAttribute, ref int pvAttribute, int cbAttribute);

        public FormNative() : base()
        {
            TestBorderColor();
            TestRoundCorner();
        }

        private void TestRoundCorner()
        {
            IntPtr hWnd = this.Handle;
            var dwAttribute = DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE;
            var pvAttribute = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_ROUND;
            DwmSetWindowAttribute(hWnd, dwAttribute, ref pvAttribute, Marshal.SizeOf(pvAttribute));
        }

        private void TestBorderColor()
        {
            IntPtr hWnd = this.Handle;
            var dwAttribute = DWMWINDOWATTRIBUTE.DWMWA_BORDER_COLOR;
            var pvAttribute = 0x00FF0000; //red
            DwmSetWindowAttribute(hWnd, dwAttribute, ref pvAttribute, Marshal.SizeOf(pvAttribute));
        }

    }
    // The DWM_WINDOW_CORNER_PREFERENCE enum for DwmSetWindowAttribute's third parameter, which tells the function
    // what value of the enum to set.
    // Copied from dwmapi.h
    public enum DWM_WINDOW_CORNER_PREFERENCE : uint
    {
        DWMWCP_DEFAULT = 0,
        DWMWCP_DONOTROUND = 1,
        DWMWCP_ROUND = 2,
        DWMWCP_ROUNDSMALL = 3
    }

    [Flags]
    public enum DWMWINDOWATTRIBUTE : uint
    {
        ///
        /// Use with DwmGetWindowAttribute. Discovers whether non-client rendering is enabled. The retrieved value is of type BOOL. TRUE if non-client rendering is enabled; otherwise, FALSE.
        ///
        DWMWA_NCRENDERING_ENABLED = 1,

        ///
        /// Use with DwmSetWindowAttribute. Sets the non-client rendering policy. The pvAttribute parameter points to a value from the DWMNCRENDERINGPOLICY enumeration.
        ///
        DWMWA_NCRENDERING_POLICY,

        ///
        /// Use with DwmSetWindowAttribute. Enables or forcibly disables DWM transitions. The pvAttribute parameter points to a value of type BOOL. TRUE to disable transitions, or FALSE to enable transitions.
        ///
        DWMWA_TRANSITIONS_FORCEDISABLED,

        ///
        /// Use with DwmSetWindowAttribute. Enables content rendered in the non-client area to be visible on the frame drawn by DWM. The pvAttribute parameter points to a value of type BOOL. TRUE to enable content rendered in the non-client area to be visible on the frame; otherwise, FALSE.
        ///
        DWMWA_ALLOW_NCPAINT,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the bounds of the caption button area in the window-relative space. The retrieved value is of type RECT. If the window is minimized or otherwise not visible to the user, then the value of the RECT retrieved is undefined. You should check whether the retrieved RECT contains a boundary that you can work with, and if it doesn't then you can conclude that the window is minimized or otherwise not visible.
        ///
        DWMWA_CAPTION_BUTTON_BOUNDS,

        ///
        /// Use with DwmSetWindowAttribute. Specifies whether non-client content is right-to-left (RTL) mirrored. The pvAttribute parameter points to a value of type BOOL. TRUE if the non-client content is right-to-left (RTL) mirrored; otherwise, FALSE.
        ///
        DWMWA_NONCLIENT_RTL_LAYOUT,

        ///
        /// Use with DwmSetWindowAttribute. Forces the window to display an iconic thumbnail or peek representation (a static bitmap), even if a live or snapshot representation of the window is available. This value is normally set during a window's creation, and not changed throughout the window's lifetime. Some scenarios, however, might require the value to change over time. The pvAttribute parameter points to a value of type BOOL. TRUE to require a iconic thumbnail or peek representation; otherwise, FALSE.
        ///
        DWMWA_FORCE_ICONIC_REPRESENTATION,

        ///
        /// Use with DwmSetWindowAttribute. Sets how Flip3D treats the window. The pvAttribute parameter points to a value from the DWMFLIP3DWINDOWPOLICY enumeration.
        ///
        DWMWA_FLIP3D_POLICY,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the extended frame bounds rectangle in screen space. The retrieved value is of type RECT.
        ///
        DWMWA_EXTENDED_FRAME_BOUNDS,

        ///
        /// Use with DwmSetWindowAttribute. The window will provide a bitmap for use by DWM as an iconic thumbnail or peek representation (a static bitmap) for the window. DWMWA_HAS_ICONIC_BITMAP can be specified with DWMWA_FORCE_ICONIC_REPRESENTATION. DWMWA_HAS_ICONIC_BITMAP normally is set during a window's creation and not changed throughout the window's lifetime. Some scenarios, however, might require the value to change over time. The pvAttribute parameter points to a value of type BOOL. TRUE to inform DWM that the window will provide an iconic thumbnail or peek representation; otherwise, FALSE. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_HAS_ICONIC_BITMAP,

        ///
        /// Use with DwmSetWindowAttribute. Do not show peek preview for the window. The peek view shows a full-sized preview of the window when the mouse hovers over the window's thumbnail in the taskbar. If this attribute is set, hovering the mouse pointer over the window's thumbnail dismisses peek (in case another window in the group has a peek preview showing). The pvAttribute parameter points to a value of type BOOL. TRUE to prevent peek functionality, or FALSE to allow it. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_DISALLOW_PEEK,

        ///
        /// Use with DwmSetWindowAttribute. Prevents a window from fading to a glass sheet when peek is invoked. The pvAttribute parameter points to a value of type BOOL. TRUE to prevent the window from fading during another window's peek, or FALSE for normal behavior. Windows Vista and earlier: This value is not supported.
        ///
        DWMWA_EXCLUDED_FROM_PEEK,

        ///
        /// Use with DwmSetWindowAttribute. Cloaks the window such that it is not visible to the user. The window is still composed by DWM. Using with DirectComposition: Use the DWMWA_CLOAK flag to cloak the layered child window when animating a representation of the window's content via a DirectComposition visual that has been associated with the layered child window. For more details on this usage case, see How to animate the bitmap of a layered child window. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_CLOAK,

        ///
        /// Use with DwmGetWindowAttribute. If the window is cloaked, provides one of the following values explaining why. DWM_CLOAKED_APP (value 0x0000001). The window was cloaked by its owner application. DWM_CLOAKED_SHELL(value 0x0000002). The window was cloaked by the Shell. DWM_CLOAKED_INHERITED(value 0x0000004). The cloak value was inherited from its owner window. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_CLOAKED,

        ///
        /// Use with DwmSetWindowAttribute. Freeze the window's thumbnail image with its current visuals. Do no further live updates on the thumbnail image to match the window's contents. Windows 7 and earlier: This value is not supported.
        ///
        DWMWA_FREEZE_REPRESENTATION,

        ///
        /// Use with DwmSetWindowAttribute. Enables a non-UWP window to use host backdrop brushes. If this flag is set, then a Win32 app that calls Windows::UI::Composition APIs can build transparency effects using the host backdrop brush (see Compositor.CreateHostBackdropBrush). The pvAttribute parameter points to a value of type BOOL. TRUE to enable host backdrop brushes for the window, or FALSE to disable it. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_USE_HOSTBACKDROPBRUSH,

        ///
        /// Use with DwmSetWindowAttribute. Allows the window frame for this window to be drawn in dark mode colors when the dark mode system setting is enabled. For compatibility reasons, all windows default to light mode regardless of the system setting. The pvAttribute parameter points to a value of type BOOL. TRUE to honor dark mode for the window, FALSE to always use light mode. This value is supported starting with Windows 10 Build 17763.
        ///
        DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19,

        ///
        /// Use with DwmSetWindowAttribute. Allows the window frame for this window to be drawn in dark mode colors when the dark mode system setting is enabled. For compatibility reasons, all windows default to light mode regardless of the system setting. The pvAttribute parameter points to a value of type BOOL. TRUE to honor dark mode for the window, FALSE to always use light mode. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_USE_IMMERSIVE_DARK_MODE = 20,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the rounded corner preference for a window. The pvAttribute parameter points to a value of type DWM_WINDOW_CORNER_PREFERENCE. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_WINDOW_CORNER_PREFERENCE = 33,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the window border. The pvAttribute parameter points to a value of type COLORREF. The app is responsible for changing the border color according to state changes, such as a change in window activation. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_BORDER_COLOR,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the caption. The pvAttribute parameter points to a value of type COLORREF. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_CAPTION_COLOR,

        ///
        /// Use with DwmSetWindowAttribute. Specifies the color of the caption text. The pvAttribute parameter points to a value of type COLORREF. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_TEXT_COLOR,

        ///
        /// Use with DwmGetWindowAttribute. Retrieves the width of the outer border that the DWM would draw around this window. The value can vary depending on the DPI of the window. The pvAttribute parameter points to a value of type UINT. This value is supported starting with Windows 11 Build 22000.
        ///
        DWMWA_VISIBLE_FRAME_BORDER_THICKNESS,

        ///
        /// The maximum recognized DWMWINDOWATTRIBUTE value, used for validation purposes.
        ///
        DWMWA_LAST,
    }
}

EDIT :

It's not available on Windows 10, only windows 11,
Is there something "similar", low level, that could allow to do this?
I imagine it won't be as easy if they added it lately...


问:
How to log the DN (destinguished-name) of the requester's certificate in Apache Camel
For a project i want to log the DN of the requester's certificate in a Apache camel route. I can't really find a specific header in the message that contains the DN. Also, I can't find any library online that makes this possible. Does anyone happen to have any experience with this and know how to achieve this?

The only thing i could find online is about the CxfMessageHelper library, but it seems like it doesn't allow accessing the DN anymore.