问:
Debugging Blazor WebAssembly in VSCode (linux) doesn't work
I try to debug a Blazor WebAssembly app in Ubuntu, using VSCode. I'm able to start the application from VSCode but it doesn't hit at any breakpoints.

What I did
I followed the guides from Microsoft:

Debug ASP.NET Core Blazor WebAssembly

Tooling for ASP.NET Core Blazor

just created a new standard project using

dotnet new blazorwasm -o BlazorWasmApplication1
```
<p>I'm using the original code from the template.</p>
<p><strong>Properties/launchSettings.json</strong></p>
<pre class="lang-json prettyprint-override"><code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:11236",
      "sslPort": 44382
    }
  },
  "profiles": {
    "BlazorWasmLinux": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "applicationUrl": "https://localhost:7242;http://localhost:5285",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

.vscode/tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/BlazorWasmLinux.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/BlazorWasmLinux.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/BlazorWasmLinux.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}
```
<p><strong>.vscode/launch.json</strong></p>
<pre class="lang-json prettyprint-override"><code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch and Debug Standalone Blazor WebAssembly App",
            "type": "blazorwasm",
            "request": "launch",
            "cwd": "${workspaceFolder}",
            "url": "https://localhost:7242",
            "browser": "chrome"
        }
    ]
}
</code>```

This is what the debug console shows me.

```<code>-------------------------------------------------------------------
You may only use the Microsoft .NET Core Debugger (vsdbg) with
Visual Studio Code, Visual Studio or Visual Studio for Mac software
to help you develop and test your applications.
-------------------------------------------------------------------
Using launch settings from '/home/BooFar/MyProjects/learningblazor/BlazorWasmLinux/Properties/launchSettings.json' [Profile 'BlazorWasmLinux']...
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Private.CoreLib.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
...
... Many entries like the above, loading dlls
...
      Now listening on: https://localhost:7242
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5285
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/BooFar/MyProjects/learningblazor/BlazorWasmLinux
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.Requests.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.NetworkInformation.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.Sockets.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.NameResolution.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Security.Cryptography.Encoding.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Formats.Asn1.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Security.Cryptography.OpenSsl.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.ComponentModel.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

</code>```

The application pops up in a separate window. Hovering over the breakpoint shows unbound breakpoint. And of course it doesn't stop there when executing the code.

Has anyone an idea what I'm doing wrong? Or is there any known bug? Or any alternative approaches?
Thanks in advance.

MyEnvironment

Ubuntu 20.04

google-chrome (Version 97.0.4692.99 (Official Build) (64-bit)),

.Net 6.0.101

VSCode 1.63.2 with the current version of the extensions C# for Visual Studio Code and Microsoft.AspNetCore.Razor.VSCode.BlazorWasmDebuggingExtension.

答:
Seems that it was a bug in .NET SDK/runtime? Not really sure
See also here.

After updating to .NET Net 6.0.102 the code stopped at the position I was able to step through the code.

Additinally I had to start http not https, but this is a different story (certificate).

So the solution was updating .NET sdk.

Body:
I try to debug a Blazor WebAssembly app in Ubuntu, using VSCode. I'm able to start the application from VSCode but it doesn't hit at any breakpoints.

What I did
I followed the guides from Microsoft:

Debug ASP.NET Core Blazor WebAssembly

Tooling for ASP.NET Core Blazor

just created a new standard project using

dotnet new blazorwasm -o BlazorWasmApplication1

I'm using the original code from the template.

Properties/launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:11236",
      "sslPort": 44382
    }
  },
  "profiles": {
    "BlazorWasmLinux": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "applicationUrl": "https://localhost:7242;http://localhost:5285",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

.vscode/tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/BlazorWasmLinux.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/BlazorWasmLinux.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/BlazorWasmLinux.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch and Debug Standalone Blazor WebAssembly App",
            "type": "blazorwasm",
            "request": "launch",
            "cwd": "${workspaceFolder}",
            "url": "https://localhost:7242",
            "browser": "chrome"
        }
    ]
}

This is what the debug console shows me.

-------------------------------------------------------------------
You may only use the Microsoft .NET Core Debugger (vsdbg) with
Visual Studio Code, Visual Studio or Visual Studio for Mac software
to help you develop and test your applications.
-------------------------------------------------------------------
Using launch settings from '/home/BooFar/MyProjects/learningblazor/BlazorWasmLinux/Properties/launchSettings.json' [Profile 'BlazorWasmLinux']...
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Private.CoreLib.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
...
... Many entries like the above, loading dlls
...
      Now listening on: https://localhost:7242
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5285
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/BooFar/MyProjects/learningblazor/BlazorWasmLinux
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.Requests.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.NetworkInformation.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.Sockets.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Net.NameResolution.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Security.Cryptography.Encoding.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Formats.Asn1.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.Security.Cryptography.OpenSsl.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/6.0.1/System.ComponentModel.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

The application pops up in a separate window. Hovering over the breakpoint shows unbound breakpoint. And of course it doesn't stop there when executing the code.

Has anyone an idea what I'm doing wrong? Or is there any known bug? Or any alternative approaches?
Thanks in advance.

MyEnvironment

Ubuntu 20.04

google-chrome (Version 97.0.4692.99 (Official Build) (64-bit)),

.Net 6.0.101

VSCode 1.63.2 with the current version of the extensions C# for Visual Studio Code and Microsoft.AspNetCore.Razor.VSCode.BlazorWasmDebuggingExtension.


来源: stackexchange

问:
Is this possible in SQL? Min and Max Dates On a Total. Where it changes in between Dates
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

```<code>SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS
</code>```

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

答:
It looks like - for your sample data set - the following lead should suffice:

```<code>select id, points, date as MinDate,
  IsNull(DateAdd(day, -1, Lead(Date,1) over(partition by Id order by Date)), Date) as MaxDate
from t
</code>```

Example Fiddle

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out how to write a query that will give me the correct historical data between dates. But only using sql. I know it is possible coding a loop, but I'm not sure if this is possible in a SQL query. Dates: DD/MM/YYYY

An Example of Data

ID
Points
DATE

1
10
01/01/2018

1
20
02/01/2019

1
25
03/01/2020

1
10
04/01/2021

With a simple query

SELECT ID, Points, MIN(Date), MAX(Date)
FROM table
GROUP BY ID,POINTS

The Min date for 10 points would be 01/01/2018, and the Max Date would be 04/01/2021. Which would be wrong in this instance. As It should be:

ID
Points
Min DATE
Max DATE

1
10
01/01/2018
01/01/2019

1
20
02/01/2019
02/01/2020

1
25
03/01/2020
03/01/2021

1
10
04/01/2021
04/01/2021

I was thinking of using LAG, but need some ideas here. What I haven't told you is there is a record per day. So I would need to group until a change of points. This is to create a view from the data that I already have.

Body:
It looks like - for your sample data set - the following lead should suffice:

select id, points, date as MinDate,
  IsNull(DateAdd(day, -1, Lead(Date,1) over(partition by Id order by Date)), Date) as MaxDate
from t

Example Fiddle


问:
How do I replace part of a tree with another tree at the specified index in OCaml?
I have the following tree structure:

type 'a tree =
    | Function of string * 'a tree list  (* function name and arguments *)
    | Terminal of 'a
```
<p>I use this tree structure to construct an abstract syntax tree:</p>
<pre class="lang-ml prettyprint-override"><code>type atoms =
    | Int of int
    | Bool of bool

let t1 = Function ("+", [Function ("*", [Terminal (Int 5);
                                         Terminal (Int 6)]);
                         Function ("sqrt", [Terminal (Int 3)])])

let t2 = Function ("-", [Terminal (Int 4); Terminal (Int 2)])
</code>```

Tree representation of t1:

Tree representation of t2:

Goal: replace one of the subtrees in t1 with t2 at a specified t1 index position. The index position starts at 0 at the root node and is depth-first. In the figures above, I have labelled all the nodes with their index to show this.

For example, replace_subtree t1 4 t2 replaces the subtree at index 4 in t1 with t2, resulting in this tree:

Function ("+", [Function ("*", [Terminal (Int 5);
                                Terminal (Int 6)]);
                Function ("-", [Terminal (Int 4);
                                Terminal (Int 2)])])
```

This is essentially a crossover operation in tree-based genetic programming.

How do I implement replace_subtree in OCaml?

I would strongly prefer a purely functional solution.

Note that this question is similar to How do I replace part of a tree with another tree at the specified index?, except that the programming language in this question is OCaml instead of Scheme/Racket. I have some trouble understanding Scheme/Racket, so I am looking for an OCaml solution.

答:
Not sure if it's better than the solution you proposed...

I used on less recursive function than you :

let replace to_replace index replacement =
  let rec dfs i tree =
    if i = index then (replacement, i + 1) (* we can replace *)
    else if i > index then (tree, i) (* we already replaced *)
    else
      match tree with
      | Terminal _ -> (tree, i + 1)
      | Function (n, children) ->
          let new_i, new_children = iter_children (i + 1) children in
          (Function (n, new_children), new_i)
  and iter_children i = function
    | [] -> (i, [])
    | child :: children ->
        let new_child, new_i = bfs i child in
        if new_i = index + 1 then (new_i + 1, new_child :: children)
          (* +1 to stop the bfs after appending the children to the Function node *)
        else
          let last_i, last_children = iter_children new_i children in
          (last_i, new_child :: last_children)
  in
  fst @@ bfs 0 to_replace
```

Body:
I have the following tree structure:

type 'a tree =
    | Function of string * 'a tree list  (* function name and arguments *)
    | Terminal of 'a

I use this tree structure to construct an abstract syntax tree:

type atoms =
    | Int of int
    | Bool of bool

let t1 = Function ("+", [Function ("*", [Terminal (Int 5);
                                         Terminal (Int 6)]);
                         Function ("sqrt", [Terminal (Int 3)])])

let t2 = Function ("-", [Terminal (Int 4); Terminal (Int 2)])

Tree representation of t1:

Tree representation of t2:

Goal: replace one of the subtrees in t1 with t2 at a specified t1 index position. The index position starts at 0 at the root node and is depth-first. In the figures above, I have labelled all the nodes with their index to show this.

For example, replace_subtree t1 4 t2 replaces the subtree at index 4 in t1 with t2, resulting in this tree:

Function ("+", [Function ("*", [Terminal (Int 5);
                                Terminal (Int 6)]);
                Function ("-", [Terminal (Int 4);
                                Terminal (Int 2)])])

This is essentially a crossover operation in tree-based genetic programming.

How do I implement replace_subtree in OCaml?

I would strongly prefer a purely functional solution.

Note that this question is similar to How do I replace part of a tree with another tree at the specified index?, except that the programming language in this question is OCaml instead of Scheme/Racket. I have some trouble understanding Scheme/Racket, so I am looking for an OCaml solution.


问:
Javascript JSON transform using Map, Reduce, Aggregate
I am beating my head trying to figure out this transformation.

This is the format of the JSON

I have:

```<code>{
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "reservations": [
        {
            "confirmNumber": "54047SC008976",
            "startDate": "2021-11-20T00:00:00.000Z"
        },
        {
            "confirmNumber": "54047SC008975",
            "startDate": "2021-11-13T00:00:00.000Z"
        },
        {
            "confirmNumber": "54058SC007379",
            "startDate": "2021-08-13T00:00:00.000Z"
        }
    ]
}
</code>```

I need:

```<code>[{
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "month": "November 2021",
    "reservations": [{
            "confirmNumber": "54047SC008976",
            "startDate": "2021-11-20T00:00:00.000Z"
        },
        {
            "confirmNumber": "54047SC008975",
            "startDate": "2021-11-13T00:00:00.000Z"
        }
    ]
}, {
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "month": "August 2021",
    "reservations": [{
        "confirmNumber": "54058SC007379",
        "startDate": "2021-08-13T00:00:00.000Z"
    }]
}]
</code>```

I need it that way so that I can build a SectionList in my react native app. I tried so many different options (aggregate+map+reduce) but I m not able to get it to this format. Any guides I can follow to help me?

The problem is a lot more complicated but I have simplified it by removing all the unneeded data properties. I was able to figure out the structure I need by looking at the example in the SectionList page and figuring out the structure of that

Edit: Pasting the picture of what it looks like when I follow one of the solutions. Nov 2022 shows up before Nov 2021

答:
I've often wished for some kind of easy "group by" function in JavaScript, but you can achieve the same effect with reduce(). Essentially, you can build up an array of grouped results by either creating or updating a group depending on if it already exists during each call to the reducer function:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

const initial = {
  "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
  "reservations": [{
      "confirmNumber": "54047SC008976",
      "startDate": "2021-11-20T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008975",
      "startDate": "2021-11-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54058SC007379",
      "startDate": "2021-08-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008971",
      "startDate": "2020-11-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008973",
      "startDate": "2022-11-13T00:00:00.000Z"
    }
  ]
};

const groupedReservations = initial.reservations
  .sort((reservationA, reservationB) => {
    // Sort descending according to startDate
    return new Date(reservationB.startDate) - new Date(reservationA.startDate);
  })
  .reduce((reservationGroups, reservation) =>
  {
    // Calculate the key that uniquely identifies the group, then look it up
    const date = new Date(reservation.startDate);
    const reservationMonth = monthNames[date.getMonth()] + " " + date.getFullYear();
    const existingGroup = reservationGroups.find(group => group.month === reservationMonth);

    // If the group doesn't exist, create it - otherwise, add the reservation to it
    if (!existingGroup) {
      reservationGroups.push({
        itineraryId: initial.itineraryId,
        month: reservationMonth,
        reservations: [reservation]
      });
    } else {
      existingGroup.reservations.push(reservation);
    }

    return reservationGroups;
  }, []);

console.log(groupedReservations);```

Note that I basically treat itineraryId as an afterthought here, since denormalizing the data didn't seem like an important step. Let me know if the context of your code requires something different.

Body:
I am beating my head trying to figure out this transformation.

This is the format of the JSON

I have:

{
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "reservations": [
        {
            "confirmNumber": "54047SC008976",
            "startDate": "2021-11-20T00:00:00.000Z"
        },
        {
            "confirmNumber": "54047SC008975",
            "startDate": "2021-11-13T00:00:00.000Z"
        },
        {
            "confirmNumber": "54058SC007379",
            "startDate": "2021-08-13T00:00:00.000Z"
        }
    ]
}

I need:

[{
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "month": "November 2021",
    "reservations": [{
            "confirmNumber": "54047SC008976",
            "startDate": "2021-11-20T00:00:00.000Z"
        },
        {
            "confirmNumber": "54047SC008975",
            "startDate": "2021-11-13T00:00:00.000Z"
        }
    ]
}, {
    "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
    "month": "August 2021",
    "reservations": [{
        "confirmNumber": "54058SC007379",
        "startDate": "2021-08-13T00:00:00.000Z"
    }]
}]

I need it that way so that I can build a SectionList in my react native app. I tried so many different options (aggregate+map+reduce) but I m not able to get it to this format. Any guides I can follow to help me?

The problem is a lot more complicated but I have simplified it by removing all the unneeded data properties. I was able to figure out the structure I need by looking at the example in the SectionList page and figuring out the structure of that

Edit: Pasting the picture of what it looks like when I follow one of the solutions. Nov 2022 shows up before Nov 2021

Body:
I've often wished for some kind of easy "group by" function in JavaScript, but you can achieve the same effect with reduce(). Essentially, you can build up an array of grouped results by either creating or updating a group depending on if it already exists during each call to the reducer function:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

const initial = {
  "itineraryId": "063fc878-b118-49fc-9106-39d51f647c9e",
  "reservations": [{
      "confirmNumber": "54047SC008976",
      "startDate": "2021-11-20T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008975",
      "startDate": "2021-11-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54058SC007379",
      "startDate": "2021-08-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008971",
      "startDate": "2020-11-13T00:00:00.000Z"
    },
    {
      "confirmNumber": "54047SC008973",
      "startDate": "2022-11-13T00:00:00.000Z"
    }
  ]
};

const groupedReservations = initial.reservations
  .sort((reservationA, reservationB) => {
    // Sort descending according to startDate
    return new Date(reservationB.startDate) - new Date(reservationA.startDate);
  })
  .reduce((reservationGroups, reservation) =>
  {
    // Calculate the key that uniquely identifies the group, then look it up
    const date = new Date(reservation.startDate);
    const reservationMonth = monthNames[date.getMonth()] + " " + date.getFullYear();
    const existingGroup = reservationGroups.find(group => group.month === reservationMonth);

    // If the group doesn't exist, create it - otherwise, add the reservation to it
    if (!existingGroup) {
      reservationGroups.push({
        itineraryId: initial.itineraryId,
        month: reservationMonth,
        reservations: [reservation]
      });
    } else {
      existingGroup.reservations.push(reservation);
    }

    return reservationGroups;
  }, []);

console.log(groupedReservations);

Note that I basically treat itineraryId as an afterthought here, since denormalizing the data didn't seem like an important step. Let me know if the context of your code requires something different.


问:
sass fails after upgrading to tailwind v3
After upgrading a react app v17.0.2 to TailwindCSS v3.0.5, the following sass error pops up:

```<code>ERROR in ./static/css/App.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Function rgb is missing argument $green.
        on line 392 of static/css/App.scss
>>   border-color: rgb(229 231 235 / var(--tw-border-opacity));

   ----------------^

    at processResult (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\webpack\lib\NormalModule.js:751:19)
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\webpack\lib\NormalModule.js:853:5
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:399:11
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:251:18
    at context.callback (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:124:13)
    at Object.callback (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\sass-loader\dist\index.js:54:7)
    at Object.done [as callback] (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\neo-async\async.js:8069:18)
    at options.error (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\node-sass\lib\index.js:293:32)
 @ ./src/index.js 5:0-30

1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details)
webpack 5.61.0 compiled with 2 errors in 9248 ms
</code>```

I'm using node-sass v7.0 and sass-loader v12.4

Anyone facing the same problem after upgrading to tailwindcss v3 while using sass?

答:
Ran into this - everything fine in dev then staging failed to precompile.

This (https://stackoverflow.com/a/70665740) solution worked for me.

I believe removing sassc-rails from your Gemfile will also resolve, but I'm not familiar enough with how Sass will get processed and if this would work for you.  It's working okay for me but that might be cssbundling/tailwind/postcss.

Body:
After upgrading a react app v17.0.2 to TailwindCSS v3.0.5, the following sass error pops up:

ERROR in ./static/css/App.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Function rgb is missing argument $green.
        on line 392 of static/css/App.scss
>>   border-color: rgb(229 231 235 / var(--tw-border-opacity));

   ----------------^

    at processResult (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\webpack\lib\NormalModule.js:751:19)
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\webpack\lib\NormalModule.js:853:5
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:399:11
    at C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:251:18
    at context.callback (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\loader-runner\lib\LoaderRunner.js:124:13)
    at Object.callback (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\sass-loader\dist\index.js:54:7)
    at Object.done [as callback] (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\neo-async\async.js:8069:18)
    at options.error (C:\Users\Alexander\repos\StockApp\StockApp.Frontend\node_modules\node-sass\lib\index.js:293:32)
 @ ./src/index.js 5:0-30

1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details)
webpack 5.61.0 compiled with 2 errors in 9248 ms

I'm using node-sass v7.0 and sass-loader v12.4

Anyone facing the same problem after upgrading to tailwindcss v3 while using sass?


问:
python sequential bugs when call function more than one time
Why in a same page this sequence

```<code>C={1:[...
f(C)
</code>```

which is ok

but if in the same page call 2 times f(C) like that

```<code>C={1:[...
f(C)
f(C)
</code>```

i get errors

```<code>Traceback (most recent call last):
  File "c:\Users\*****", line 156, in <module>
</code>```

Thanks

More info:

```<code>C={
    1:['ic','ir'],
    2:['ic','vcp']
}
</code>```

and

```<code>def f(C,vcp_ilp,range):
    global V,U
    print('C:')
    for x in C:
        print(x,'\t',C[x])
    make_V_et_Sup(V,C,vcp_ilp)
    print('V:')
    for x in V:
        print(x,'\t',V[x])
    for x in range:
        # print(x)
        fc(x,'',set(),C,V,[],False)
    print('Résultats:')
    for x in U:
        print(x,U[x])
</code>```

where

make_V_et_Sup() :makes the global v=dict()

fc(x,'',set(),C,V,[],False) : is a function that calls an another
fv(...)

fv(...):is a function that calls fc(...)
so fc and fv call each other

Results:

```<code>Traceback (most recent call last):
  File "c:\Users\***.py", line 156, in <module>
    fait(C,['vcp','ilp'],range(1,len(C)+1))
  File "c:\Users\***.py", line 120, in fait
    fc(x,'',set(),C,V,[],False)
  File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
  File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
  File "c:\Users\***.py", line 85, in fc
    if v_asup in C[eq_i]:
KeyError: 1
</code>```

答:
In my fonction i secure copy with

```<code>def copyDict(d):
    r = dict()# no ref
    for y in d:
        r[y]=d[y][:] #[:] no ref
    return r
</code>```

but in

```<code>def f(C,vcp_ilp,range):
    global V,U
...
</code>```

I hadn't done V.clear()

so the function is now :

```<code>def f(C,vcp_ilp,range):
        global V,U
        V.clear()
...

...
</code>```

Body:
Why in a same page this sequence

C={1:[...
f(C)

which is ok

but if in the same page call 2 times f(C) like that

C={1:[...
f(C)
f(C)

i get errors

Traceback (most recent call last):
  File "c:\Users\*****", line 156, in <module>

Thanks

More info:

C={
    1:['ic','ir'],
    2:['ic','vcp']
}

and

def f(C,vcp_ilp,range):
    global V,U
    print('C:')
    for x in C:
        print(x,'\t',C[x])
    make_V_et_Sup(V,C,vcp_ilp)
    print('V:')
    for x in V:
        print(x,'\t',V[x])
    for x in range:
        # print(x)
        fc(x,'',set(),C,V,[],False)
    print('Résultats:')
    for x in U:
        print(x,U[x])

where

make_V_et_Sup() :makes the global v=dict()

fc(x,'',set(),C,V,[],False) : is a function that calls an another
fv(...)

fv(...):is a function that calls fc(...)
so fc and fv call each other

Results:

Traceback (most recent call last):
  File "c:\Users\***.py", line 156, in <module>
    fait(C,['vcp','ilp'],range(1,len(C)+1))
  File "c:\Users\***.py", line 120, in fait
    fc(x,'',set(),C,V,[],False)
  File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
  File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
File "c:\Users\***.py", line 102, in fc
    fv(nA,v,nC,nV,nc,ok)
  File "c:\Users\***.py", line 73, in fv
    fc(eq_i,v,nA,nC,nV,nc,ok)
  File "c:\Users\***.py", line 85, in fc
    if v_asup in C[eq_i]:
KeyError: 1

Body:
In my fonction i secure copy with

def copyDict(d):
    r = dict()# no ref
    for y in d:
        r[y]=d[y][:] #[:] no ref
    return r

but in

def f(C,vcp_ilp,range):
    global V,U
...

I hadn't done V.clear()

so the function is now :

def f(C,vcp_ilp,range):
        global V,U
        V.clear()
...

...


问:
Swift Push Notifications send if api change
How to send notification when api changes its data? I am getting data from url. When the data at this address changes, the user must receive it. I tried to use "UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)" but it sends the notification without change.

```<code>func apiNotification(urlString:String){
    if let url = URL(string: urlString) {
        if let data = try? Data(contentsOf: url) {
            parse(jsonData: data)
        }
    }
}

private func notificationSend(id:String, title: String, introtext: String){
    let content = UNMutableNotificationContent()
    content.subtitle = title
    content.body = introtext
    content.sound = UNNotificationSound.default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: false)
    let uid = UUID.init().uuidString

    let request = UNNotificationRequest(identifier: uid, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            print("Error \(error.localizedDescription)")
        } else{
            print("Notification Register Success")
            print("===================================")
        }
    }
}
private func parse(jsonData: Data) {
    do {
        let decodedData = try JSONDecoder().decode(ApiData.self, from: jsonData)

        notificationSend(id:decodedData.id, title: decodedData.title, introtext: decodedData.introtext)
     } catch {
        print("decode error")
    }
}
</code>```

API JSON:

```<code>{
  "id": "176",
  "title": "Notification title 1",
  "introtext": "Notification introtext 1",
}
</code>```

Changed JSON API:

```<code>{
  "id": "177",
  "title": "Notification title 2",
  "introtext": "Notification introtext 2",
}
</code>```

Please help me

答:
Your API must send an event when the data is changing. You must use the framework that Apple is providing; you need to enable this in the app settings, under capabilities, then push notifications. And your API needs to use a key registered in the Apple Developer Platform.

More details in this tutorial:
https://www.raywenderlich.com/11395893-push-notifications-tutorial-getting-started

Body:
How to send notification when api changes its data? I am getting data from url. When the data at this address changes, the user must receive it. I tried to use "UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)" but it sends the notification without change.

func apiNotification(urlString:String){
    if let url = URL(string: urlString) {
        if let data = try? Data(contentsOf: url) {
            parse(jsonData: data)
        }
    }
}

private func notificationSend(id:String, title: String, introtext: String){
    let content = UNMutableNotificationContent()
    content.subtitle = title
    content.body = introtext
    content.sound = UNNotificationSound.default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: false)
    let uid = UUID.init().uuidString

    let request = UNNotificationRequest(identifier: uid, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            print("Error \(error.localizedDescription)")
        } else{
            print("Notification Register Success")
            print("===================================")
        }
    }
}
private func parse(jsonData: Data) {
    do {
        let decodedData = try JSONDecoder().decode(ApiData.self, from: jsonData)

        notificationSend(id:decodedData.id, title: decodedData.title, introtext: decodedData.introtext)
     } catch {
        print("decode error")
    }
}

API JSON:

{
  "id": "176",
  "title": "Notification title 1",
  "introtext": "Notification introtext 1",
}

Changed JSON API:

{
  "id": "177",
  "title": "Notification title 2",
  "introtext": "Notification introtext 2",
}

Please help me


问:
Pandas column access w/column names containing spaces
If I import or create a pandas column that contains no spaces, I can access it as such:

```<code>from pandas import DataFrame

df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
                 'data1': range(7)})

df1.data1
</code>```

which would return that series for me.  If, however, that column has a space in its name, it isn't accessible via that method:

```<code>from pandas import DataFrame

df2 = DataFrame({'key': ['a','b','d'],
                 'data 2': range(3)})

df2.data 2      # <--- not the droid I'm looking for.
</code>```

I know I can access it using .xs():

```<code>df2.xs('data 2', axis=1)
</code>```

There's got to be another way.  I've googled it like mad and can't think of any other way to google it.  I've read all 96 entries here on SO that contain "column" and "string" and "pandas" and could find no previous answer.  Is this the only way, or is there something better?

答: You can do it with df['Column Name']

Body:
If I import or create a pandas column that contains no spaces, I can access it as such:

from pandas import DataFrame

df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
                 'data1': range(7)})

df1.data1

which would return that series for me.  If, however, that column has a space in its name, it isn't accessible via that method:

from pandas import DataFrame

df2 = DataFrame({'key': ['a','b','d'],
                 'data 2': range(3)})

df2.data 2      # <--- not the droid I'm looking for.

I know I can access it using .xs():

df2.xs('data 2', axis=1)

There's got to be another way.  I've googled it like mad and can't think of any other way to google it.  I've read all 96 entries here on SO that contain "column" and "string" and "pandas" and could find no previous answer.  Is this the only way, or is there something better?

Body: You can do it with df['Column Name']


问:
Google Sheets: Change currency dynamically
How can I change the currency on cells C4,C5,C6,C8,C9 based on what is selected on C3?

C3 values: USD,EUR,GBP,BRL

答:
Google Sheets has a very unique formula which interacts with Google Finance historical and real-time financial data. The formula is called =GOOGLEFINANCE(), you can do a lot with it but what you're looking for is to convert currencies:

```<code>=GOOGLEFINANCE("CURRENCY:"[from_currency][to_currency])
</code>```

Where [from_currency] and [to_currency] are in the 3 letter ISO 4217 currency code standard.

As for your specific need. Since =GOOGLEFINANCE() need to convert from one currency to another, I've added in Column C some currency codes in data validation so the user can set the currency in which each item was originally quoted at (EUR,USD,GBP,CAD,AUD,CNY).

Then, in Column F I added the following formula:

```<code>=IF(C3=$C$8,D3, ROUND(D3*GOOGLEFINANCE("CURRENCY:"&C3&E3),1))
</code>```

What it does essentially is to check Cell C8 (which sets the currency in which you wish to see the total costs), and then calculate the current exchange rate between the quoted currency ([from_currency]) and the Show-in currency ([to_currency]) and multiply that rate by the quoted price, in Column D, to get the orriginal quoted price in the currency desired. The IF function in the formula is to skip cases where the quoted currency and the show-in currency are the same.

Here is the resulting table:

Body:
Google Sheets has a very unique formula which interacts with Google Finance historical and real-time financial data. The formula is called =GOOGLEFINANCE(), you can do a lot with it but what you're looking for is to convert currencies:

=GOOGLEFINANCE("CURRENCY:"[from_currency][to_currency])

Where [from_currency] and [to_currency] are in the 3 letter ISO 4217 currency code standard.

As for your specific need. Since =GOOGLEFINANCE() need to convert from one currency to another, I've added in Column C some currency codes in data validation so the user can set the currency in which each item was originally quoted at (EUR,USD,GBP,CAD,AUD,CNY).

Then, in Column F I added the following formula:

=IF(C3=$C$8,D3, ROUND(D3*GOOGLEFINANCE("CURRENCY:"&C3&E3),1))

What it does essentially is to check Cell C8 (which sets the currency in which you wish to see the total costs), and then calculate the current exchange rate between the quoted currency ([from_currency]) and the Show-in currency ([to_currency]) and multiply that rate by the quoted price, in Column D, to get the orriginal quoted price in the currency desired. The IF function in the formula is to skip cases where the quoted currency and the show-in currency are the same.

Here is the resulting table:


问:
upload document file in stripe payment with React
According to the  Stripe API for verification document in front I can see that creating a file in Javascript isn't available, and I want to create a file verification ID on the client side using React/Javascript.

I successfully created a bank account but when I try to upload an identity verification file through my React client interface with method stripe.files.create does not work and returns Cannot read property 'create' of undefined knowing that stripe.createToken works so stripe is well integrated into my application.

Note that I interact with stripe from client side developed with React.

  stripeVerification = async () => {
    const formdata = new FormData();
    formdata.append('file', this.state.picture[0], 'picture');
    await this.props.stripe.files
      .create({
        purpose: 'identity_document',
        file: {
          data: formdata,
        },
      })
      .then(response => console.log(response));
  };```

答:
You can upload a file client-side using the approach documented in the "Handling a file upload" section of Stripe's Connect documentation.

When a user needs to provide Stripe with a scan of an identity document (for example, a passport), you can also do this through an account token. However, the JavaScript required is a bit more complicated as the file must be sent to Stripe as part of an XHR request.


问:
In tasks.json in vscode, Is it possible to reference single elements in an array defined in settings.json?
When writing an extension in vsCode, is it possible to create a configuration (a field in my settings.json) where I can store multiple values and configure an actively selected one?

Say I have an external dependency, which I need to reference in my tasks.json. Through the configuration contribution point of the extension i can provide the following property:

```<code>"myextension.dependencyDir": {
  "scope": "resource",
  "type": "string",
  "description": "Path to the external dependency"
}
</code>```

I can now reference this path in my tasks.json through ${config:myextension.dependencyDir}

However, lets say my dependency comes in various versions, which I would like to switch from the comfort of my settings(UI)

I know that by using an array I can store multiple versions of the dependency.

```<code>"myextension.dependencyDir": {
  "scope": "resource",
  "type": "array",
  "items": {
    "type": "string"
  },
  "description": "Path to the external dependency"
},
</code>```

However, I cannot seem to reference single elements out of this array from my tasks.json.

By calling ${config:myextension.dependencyDir} now, i get the entire array.

I have tried to call

${config:myextension.dependencyDir[0]}

${config:myextension.dependencyDir(0)}

${config:myextension.dependencyDir:0}

... and many other variations

to query the first item in my array. Neigther of those attempts have worked.

${config:myextension.dependencyDir}[0] just appends '[0]' to the
last element.

I know that I can create custom objects and configure them in my settings.

```<code>"myextension.dependencyDir": {
  "scope": "resource",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string",
        "description": "Name of your dependency version"
      },
      "value": {
        "type": "string",
        "description": "Path to the specific Dependency version"
      }
    }
  },
  "description": "Path to the external dependency"
},
</code>```

However, just like before, I don't know how to access a single entry in my array, let alone adress the specific fields name and value.

Is what I am trying to do possible? Is it even the proper way of doing this? Does anyone have a solution to my problem or suggestions for a different approach?

Thanks in advance

BioZons

答:
You can use the extension Command Variable v1.30.0

It has a command extension.commandvariable.config.expression. It allows to apply a JavaScript expression to the value of a configuration variable.

If the config variable is an array:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigArray: ${input:configArray}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configArray",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[1]"
      }
    }
  ]
}
```
<p>If the config variable is an array and you want to pick the array element:</p>
<pre class="lang-json prettyprint-override"><code>{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigArrayPick: ${input:configArrayPick}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configArrayPick",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[${pickStringRemember:serverNr}]",
        "pickStringRemember": {
          "serverNr": {
            "description": "Which server to use?",
            "options": [
              ["development", "0"],
              ["live", "1"]
            ]
          }
        }
      }
    }
  ]
}
</code>```

If the config variable is an array of objects:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigObject: ${input:configObject}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configObject",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[1].name"
      }
    }
  ]
}
```

Body:
When writing an extension in vsCode, is it possible to create a configuration (a field in my settings.json) where I can store multiple values and configure an actively selected one?

Say I have an external dependency, which I need to reference in my tasks.json. Through the configuration contribution point of the extension i can provide the following property:

"myextension.dependencyDir": {
  "scope": "resource",
  "type": "string",
  "description": "Path to the external dependency"
}

I can now reference this path in my tasks.json through ${config:myextension.dependencyDir}

However, lets say my dependency comes in various versions, which I would like to switch from the comfort of my settings(UI)

I know that by using an array I can store multiple versions of the dependency.

"myextension.dependencyDir": {
  "scope": "resource",
  "type": "array",
  "items": {
    "type": "string"
  },
  "description": "Path to the external dependency"
},

However, I cannot seem to reference single elements out of this array from my tasks.json.

By calling ${config:myextension.dependencyDir} now, i get the entire array.

I have tried to call

${config:myextension.dependencyDir[0]}

${config:myextension.dependencyDir(0)}

${config:myextension.dependencyDir:0}

... and many other variations

to query the first item in my array. Neigther of those attempts have worked.

${config:myextension.dependencyDir}[0] just appends '[0]' to the
last element.

I know that I can create custom objects and configure them in my settings.

"myextension.dependencyDir": {
  "scope": "resource",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string",
        "description": "Name of your dependency version"
      },
      "value": {
        "type": "string",
        "description": "Path to the specific Dependency version"
      }
    }
  },
  "description": "Path to the external dependency"
},

However, just like before, I don't know how to access a single entry in my array, let alone adress the specific fields name and value.

Is what I am trying to do possible? Is it even the proper way of doing this? Does anyone have a solution to my problem or suggestions for a different approach?

Thanks in advance

BioZons

Body:
You can use the extension Command Variable v1.30.0

It has a command extension.commandvariable.config.expression. It allows to apply a JavaScript expression to the value of a configuration variable.

If the config variable is an array:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigArray: ${input:configArray}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configArray",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[1]"
      }
    }
  ]
}

If the config variable is an array and you want to pick the array element:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigArrayPick: ${input:configArrayPick}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configArrayPick",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[${pickStringRemember:serverNr}]",
        "pickStringRemember": {
          "serverNr": {
            "description": "Which server to use?",
            "options": [
              ["development", "0"],
              ["live", "1"]
            ]
          }
        }
      }
    }
  ]
}

If the config variable is an array of objects:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo config var",
      "type": "shell",
      "command": "echo",
      "args": [
        "ConfigObject: ${input:configObject}",
      ],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "configObject",
      "type": "command",
      "command": "extension.commandvariable.config.expression",
      "args": {
        "configVariable": "myextension.dependencyDir",
        "expression": "content[1].name"
      }
    }
  ]
}


问:
Make an array with every character on keyboard
I want to make an array containing all the letters and numbers on the keyboard (+ !, @, #, $, %, &, etc.) via code, without declaring it. Is there any way to do this in js?</p>

答:
There are 95 characters so you can make an array of 95 elements and map the items to the String char code that matches the index + 32.

const characters = Array.from(Array(95), (val,i) => String.fromCharCode(i+32))
```


问:
How to apply exact match in Grid Filter feature using Extjs4?
I am using Extjs4 and I want to apply exactMatch on grid filtering. I am using the newly introduced Grid Filtering feature.I have tried to use exactMatch but it does not work. Here is my sample code:

```<code>Ext.define('MyModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'ID', type: 'string'},
            {name: 'Title', type: 'string'}
        ]
    });

var store = Ext.create('Ext.data.Store', {
        model: 'MyModel',
        proxy: {
            type: 'ajax',
            url: 'myurl',
            reader: {
                type: 'json'
            }
        },
        sorters: [{
            property: 'ID',
            direction:'DESC'
        }],
        autoLoad:true
    });

var filters = {
        ftype: 'filters',
        encode: true,
        local: true,
        filters: [{
            type: 'numeric',
            dataIndex: 'ID',
            disabled: true
        },{
            type: 'string',
            dataIndex: 'Title',
            exactMatch:true
        }]
    };

var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        columns: [{
            header: 'ID',
            dataIndex: 'ID',
            width: 20
        },{
            header: 'List Title',
            dataIndex: 'Title',
            flex:1
        }],
        renderTo: 'editor-grid',
        width: 700,
        height: 400,
        frame: true,
        features: [filters]
    });
</code>```

Thanks..

答:
The grid's features property can only contain classes that have been extended from the Feature class.

See the Grouping Feature:

```<code>Ext.define('Ext.grid.feature.Grouping', {
    extend: 'Ext.grid.feature.Feature',
    alias: 'feature.grouping'
    // More properties and functions...
}
</code>```

Grouping Feature Usage:

```<code>var groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
    groupHeaderTpl: 'Group: {name} ({rows.length})', //print the number of items in the group
    startCollapsed: true // start all groups collapsed
});

var grid = Ext.create('Ext.grid.Panel', {
          features:[groupingFeature]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Extjs4 and I want to apply exactMatch on grid filtering. I am using the newly introduced Grid Filtering feature.I have tried to use exactMatch but it does not work. Here is my sample code:

Ext.define('MyModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'ID', type: 'string'},
            {name: 'Title', type: 'string'}
        ]
    });

var store = Ext.create('Ext.data.Store', {
        model: 'MyModel',
        proxy: {
            type: 'ajax',
            url: 'myurl',
            reader: {
                type: 'json'
            }
        },
        sorters: [{
            property: 'ID',
            direction:'DESC'
        }],
        autoLoad:true
    });

var filters = {
        ftype: 'filters',
        encode: true,
        local: true,
        filters: [{
            type: 'numeric',
            dataIndex: 'ID',
            disabled: true
        },{
            type: 'string',
            dataIndex: 'Title',
            exactMatch:true
        }]
    };

var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        columns: [{
            header: 'ID',
            dataIndex: 'ID',
            width: 20
        },{
            header: 'List Title',
            dataIndex: 'Title',
            flex:1
        }],
        renderTo: 'editor-grid',
        width: 700,
        height: 400,
        frame: true,
        features: [filters]
    });

Thanks..

Body:
The grid's features property can only contain classes that have been extended from the Feature class.

See the Grouping Feature:

Ext.define('Ext.grid.feature.Grouping', {
    extend: 'Ext.grid.feature.Feature',
    alias: 'feature.grouping'
    // More properties and functions...
}

Grouping Feature Usage:

var groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
    groupHeaderTpl: 'Group: {name} ({rows.length})', //print the number of items in the group
    startCollapsed: true // start all groups collapsed
});

var grid = Ext.create('Ext.grid.Panel', {
          features:[groupingFeature]
}


问:
Securely pass password to PuTTY process on start
I am maintaining an application in our company (written in C#), which runs on a jumphost and provides the functionality to search across different servers and initiate a PuTTY connection to that server. For this the application currently starts the PuTTY process and passes arguments, like the hostname, username and password. The password for each server is retrieved from a password manager service. The arguments are passed to PuTTY through the command line interface. So the purpose of the application is to automate password retrieval and login to different servers.

The problem with the current approach is, that in the Windows Task Manager its possible for an administrator to see all started PuTTY instances and the corresponding credentials as command line arguments.

So far I haven't found any practical solution to circumvent this. These are the things I researched so far:

Instead of passing password argument, using SendKeys to type password into the promt: Unreliable, as there is no way to read the PuTTY output and know when the application is ready for the input to be typed in.

Using Plink instead of PuTTY and passing arguments through stdin: Plink supports stdin / stdout communication, however the terminal functionality is very limited and not usable in practice after the login was successful.

Modifying PuTTY to mask password: I have seen some suggestions, to modify the PuTTY source code, to overwrite the password in the main args, once the application started. However, this solution seems to only work on Linux, not Windows.

Using SSH.NET library to provide my own SSH terminal implementation: The SSH.NET library seems to be similarly to Plink more suitable for issuing commands programmatically, but not for opening a terminal for the user. I guess it would require a lot of work to implement a full terminal.

Some ideas, that might work:

Modify the PuTTY code, so that arguments can be passed through stdin: Could work, but I don't know how easy that would be, as I don't have very good C knowledge.

Use an alternate client, that supports stdin output. The Java library JSch looks quite powerful and seems to already include a terminal. Would it be possible to create a standalone application, that can a receive stdin and use that to open a terminal and auto login?

Any further suggestions would be greatly appreciated. Are you aware of any other Windows alternative to PuTTY, which supports passing credentials in a more secure way?

答: Since 0.77, PuTTY can read the password from a file using -pwfile switch.


问:
react-router-dom version 6 nested routes props not passing
I am unable to get the props from the nested routes, Products route has nested route which should print pc but I only get ssd,

Is this because I am using same component in the nested route ? or I am doing something wrong.

App.js

<BrowserRouter>

        <Routes>
          <Route index element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="products" element={<Products name="ssd"/>}>
            <Route path=":id" element={<Products ye="pc" />} />
          </Route>
          <Route path="*" element={<Err />}/>
        </Routes>

    </BrowserRouter>
```
<p>Products.jsx</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react'
import { useParams } from 'react-router-dom'

function Products(props) {
    const {id} = useParams();
    console.log(props);
  return (
    <div>
        <p>This product : {props.name} is in stock</p>
        <p>The id from the params is : {id}</p>
        <p>ye is : {props.ye}</p>
    </div>
  )
}

export default Products
</code>```

Here is the screenshot of the console which show that only ssd is passed

答:
Products is missing rendering an Outlet for nested Routes to be rendered into.

```<code>import React from 'react'
import { Outlet, useParams } from 'react-router-dom'

function Products(props) {
  const { id } = useParams();
  console.log(props);
  return (
    <div>
      <p>This product : {props.name} is in stock</p>
      <p>The id from the params is : {id}</p>
      <p>ye is : {props.ye}</p>
      <Outlet /> // <-- nested routes render out here
    </div>
  )
}
</code>```

Or alternatively if you don't want to nest Products components within other Products components, render the Outlet as the layout component and create an index route for the "ssd" route. The Route component renders an Outlet by default if no element prop is specified.

```<code><Route path="/products">
  <Route index element={<Products name="ssd" />} />   // <-- "/products"
  <Route path=":id" element={<Products ye="pc" />} /> // <-- "/products/1234"
</Route>
</code>```

Body:
I am unable to get the props from the nested routes, Products route has nested route which should print pc but I only get ssd,

Is this because I am using same component in the nested route ? or I am doing something wrong.

App.js

<BrowserRouter>

        <Routes>
          <Route index element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="products" element={<Products name="ssd"/>}>
            <Route path=":id" element={<Products ye="pc" />} />
          </Route>
          <Route path="*" element={<Err />}/>
        </Routes>

    </BrowserRouter>

Products.jsx

import React from 'react'
import { useParams } from 'react-router-dom'

function Products(props) {
    const {id} = useParams();
    console.log(props);
  return (

This product : {props.name} is in stock

The id from the params is : {id}

ye is : {props.ye}

  )
}

export default Products

Here is the screenshot of the console which show that only ssd is passed

Body:
Products is missing rendering an Outlet for nested Routes to be rendered into.

import React from 'react'
import { Outlet, useParams } from 'react-router-dom'

function Products(props) {
  const { id } = useParams();
  console.log(props);
  return (
    <div>
      <p>This product : {props.name} is in stock</p>
      <p>The id from the params is : {id}</p>
      <p>ye is : {props.ye}</p>
      <Outlet /> // <-- nested routes render out here
    </div>
  )
}

Or alternatively if you don't want to nest Products components within other Products components, render the Outlet as the layout component and create an index route for the "ssd" route. The Route component renders an Outlet by default if no element prop is specified.

<Route path="/products">
  <Route index element={<Products name="ssd" />} />   // <-- "/products"
  <Route path=":id" element={<Products ye="pc" />} /> // <-- "/products/1234"
</Route>


答:
Here minified implementation

// Convert ISO date to human readable date : August 2021

const formatYearMonth = (dateISO) => {

const formatYearMonth = (dateISO) => {

  const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
  const parsedDate =  new Date(dateISO)

  const year = parsedDate.getFullYear()
  const month = monthNames[parsedDate.getMonth()]

  return `${month} ${year}`;
};

  return `${month} ${year}`;
};

const getItineraryMonths = (reservations) => {
  let months = {};

  reservations.forEach((reservation) => {
    const formattedMonth = formatYearMonth(reservation.startDate);

    months[formattedMonth] = formattedMonth;
  });

  return Object.keys(months);
};

// Get reservation in specified month for specific itinerary

const getReservationsInMonth = (reservations, formatedMonthIn) => {
  return reservations.filter((reservation) => {
    const formattedMonth = formatYearMonth(reservation.startDate);

    return formattedMonth === formatedMonthIn;
  });
};

// Reformat JSON response

const formatJsonResponse = (response) => {
  const itineraryMonths = getItineraryMonths(response.reservations);

  const formattedResult = itineraryMonths.map((month) => {
    return {
      itineraryId: response.itineraryId,
      month,
      reservations: getReservationsInMonth(response.reservations, month),
    };
  });

  return formattedResult;
};

console.log(formatJsonResponse(input));

```

Test solution  - https://replit.com/@EmmanuelBYIRING/json-sanitise#index.js

Title: Javascript JSON transform using Map, Reduce, Aggregate

Body:
Here minified implementation

// Convert ISO date to human readable date : August 2021

const formatYearMonth = (dateISO) => {

const formatYearMonth = (dateISO) => {

  const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
  const parsedDate =  new Date(dateISO)

  const year = parsedDate.getFullYear()
  const month = monthNames[parsedDate.getMonth()]

  return `${month} ${year}`;
};

  return `${month} ${year}`;
};

const getItineraryMonths = (reservations) => {
  let months = {};

  reservations.forEach((reservation) => {
    const formattedMonth = formatYearMonth(reservation.startDate);

    months[formattedMonth] = formattedMonth;
  });

  return Object.keys(months);
};

// Get reservation in specified month for specific itinerary

const getReservationsInMonth = (reservations, formatedMonthIn) => {
  return reservations.filter((reservation) => {
    const formattedMonth = formatYearMonth(reservation.startDate);

    return formattedMonth === formatedMonthIn;
  });
};

// Reformat JSON response

const formatJsonResponse = (response) => {
  const itineraryMonths = getItineraryMonths(response.reservations);

  const formattedResult = itineraryMonths.map((month) => {
    return {
      itineraryId: response.itineraryId,
      month,
      reservations: getReservationsInMonth(response.reservations, month),
    };
  });

  return formattedResult;
};

console.log(formatJsonResponse(input));

Test solution  - https://replit.com/@EmmanuelBYIRING/json-sanitise#index.js


问:
Create Array of same Size
I have an array

```<code>a = zeros(2,3)

2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0
</code>```

and I want to create a Bool array of same size with all values set to false.

答:
Another option is to use zeros with Bool as the type option:

```<code>julia> zeros(Bool, size(a))
2×3 Matrix{Bool}:
 0  0  0
 0  0  0
</code>```

Title: Create Array of same Size

Body:
I have an array

a = zeros(2,3)

2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0

and I want to create a Bool array of same size with all values set to false.

Body:
Another option is to use zeros with Bool as the type option:

julia> zeros(Bool, size(a))
2×3 Matrix{Bool}:
 0  0  0
 0  0  0


问:
Excel: Count consecutive cells that are not empty
I would like to identify which rows don't have consecutive data. For this, I'd like to be able to count the cells across rows until and empty cell is encountered.

Please look at the the screenshot of an example and desired output.

I have tried to play around with the MATCH function, but no look yet. I've tried the following but it's not returning what I would've expect.

```<code>{=MATCH(FALSE,ISBLANK(C2:F2),0)}
</code>```

答:
You may try in this way however there might be a more eloquent way to solve this,

So the formula used in cell G2

```<code>    =IF(MAX(FREQUENCY(IF(C2:F2,COLUMN(C2:F2)),
IF(C2:F2=FALSE,COLUMN(C2:F2))))<3,"Jumps A Year",
MAX(FREQUENCY(IF(C2:F2,COLUMN(C2:F2)),
IF(C2:F2=FALSE,COLUMN(C2:F2)))))
</code>```

And Fill Down!

Also note, depending on your excel version you may or may need to press CTRL+SHIFT+ENTER, not just ENTER after entering the formula. You will know the array is active when you see curly braces { } appear around your formula.

Body:
I would like to identify which rows don't have consecutive data. For this, I'd like to be able to count the cells across rows until and empty cell is encountered.

Please look at the the screenshot of an example and desired output.

I have tried to play around with the MATCH function, but no look yet. I've tried the following but it's not returning what I would've expect.

{=MATCH(FALSE,ISBLANK(C2:F2),0)}

Body:
You may try in this way however there might be a more eloquent way to solve this,

So the formula used in cell G2

    =IF(MAX(FREQUENCY(IF(C2:F2,COLUMN(C2:F2)),
IF(C2:F2=FALSE,COLUMN(C2:F2))))<3,"Jumps A Year",
MAX(FREQUENCY(IF(C2:F2,COLUMN(C2:F2)),
IF(C2:F2=FALSE,COLUMN(C2:F2)))))

And Fill Down!

Also note, depending on your excel version you may or may need to press CTRL+SHIFT+ENTER, not just ENTER after entering the formula. You will know the array is active when you see curly braces { } appear around your formula.


问:
Python and arbitrary command line options
I am writing a command-line plugin-based program where the plugins will provide additional functionality on top of whatever I provide.

So for example suppose I wrote a simple script that parsed images and stored them, and that's all I do. Then someone else can write a set of scripts to manipulate the image, putting his scripts in a plugin.

The plugin would be loaded and users can access the plugin by specifying its name in the command line.

It is not uncommon for scripts to want to provide additional options for the user.
So suppose in some years, 20 different plugins have been written.

Now, all of the authors want to allow users to provide options, so the main engine should take the user's options and pass them to the plugin so that it can handle them however it wants.

To keep it uniform, they might agree that certain options should perform a similar operation. Like "-o name" should set the output name to "name". They would then go about implementing their own options and stuff, which the main engine does not know about (of course, it shouldn't know what the plugins do)

I am using the deprecated getopt module, and it will throw exceptions whenever I specify an undefined option. I have heard of optparse and argparse, but I am not sure if these will allow the user to specify any options he wants without the code throwing an exception.

How can I make it so I can specify any command-line option?

答:
The solution you want is probably to treat the command line arguments as a sort of in process pipeline.  Which options are also a part of where the options may go.

```<code> command <global options> sub_command <sub_options> new_sub_command <new_sub_options>
</code>```

each command will shift options off of sys.argv until it finds one it doesn't understand, or one that cannot be a valid option, and then it stops parsing arguments, does its job, and returns control to the plugin-dispatcher.

Body:
The solution you want is probably to treat the command line arguments as a sort of in process pipeline.  Which options are also a part of where the options may go.

 command <global options> sub_command <sub_options> new_sub_command <new_sub_options>

each command will shift options off of sys.argv until it finds one it doesn't understand, or one that cannot be a valid option, and then it stops parsing arguments, does its job, and returns control to the plugin-dispatcher.


问:
Angular How to combine Interval with Zip to show loading
I have a page which has to be update every minute, but I have several http request.
So I'm trying use Interval with zip operator.
How Can I combine these two to show my loading "isLoading" after all the request?

This is what I got :

```<code>    isLoading = true;
    source = interval(60000);

  ngOnInit(): void {
    const responseZipado = zip(
      this.monitorService.getSMPPstatus(),
      this.homeService.getCampaignsToday(),
      this.monitorService.getPerfomance(),
    );

      responseZipado.subscribe((valores) => {
      this.statusSMPP = valores[0],
      this.dataSourceToday = valores[1],
      this.perfomanceDataSource = valores[2],
    });

  }
</code>```

should I use other operator than Zip?

答:
You can use forkJoin for parallel http requests because you need value after loading all requests.

Example:

```<code>interval(60000).pipe(
  tap(() => this.isLoading = true),
  switchMap(() => forkJoin([
    this.monitorService.getSMPPstatus().pipe(catchError(error => of(error))),
    this.homeService.getCampaignsToday().pipe(catchError(error => of(error))),
    this.monitorService.getPerfomance().pipe(catchError(error => of(error))),
  ])),
).subscribe((valores) => {
  this.isLoading = false;
  this.statusSMPP = valores[0];
  this.dataSourceToday = valores[1];
  this.perfomanceDataSource = valores[2];
})
</code>```

Body:
I have a page which has to be update every minute, but I have several http request.
So I'm trying use Interval with zip operator.
How Can I combine these two to show my loading "isLoading" after all the request?

This is what I got :

    isLoading = true;
    source = interval(60000);

  ngOnInit(): void {
    const responseZipado = zip(
      this.monitorService.getSMPPstatus(),
      this.homeService.getCampaignsToday(),
      this.monitorService.getPerfomance(),
    );

      responseZipado.subscribe((valores) => {
      this.statusSMPP = valores[0],
      this.dataSourceToday = valores[1],
      this.perfomanceDataSource = valores[2],
    });

  }

should I use other operator than Zip?

Body:
You can use forkJoin for parallel http requests because you need value after loading all requests.

Example:

interval(60000).pipe(
  tap(() => this.isLoading = true),
  switchMap(() => forkJoin([
    this.monitorService.getSMPPstatus().pipe(catchError(error => of(error))),
    this.homeService.getCampaignsToday().pipe(catchError(error => of(error))),
    this.monitorService.getPerfomance().pipe(catchError(error => of(error))),
  ])),
).subscribe((valores) => {
  this.isLoading = false;
  this.statusSMPP = valores[0];
  this.dataSourceToday = valores[1];
  this.perfomanceDataSource = valores[2];
})


问:
Focus on next input with React Form Hook
I created a custom TextInput with React Hook Form, I'm trying to set the focus into the next TextInput.

I explain better: in order to focus the next element, I can easily create an useRef like this:

```<code>const passwordRef = useRef<HTMLInputElement>(null);
<FormProvider {...methods}>
  <TextInput
    name="email"
    label="Email"
    keyboardType="email-address"
    autoCompleteType="email"
    rules={{
      required: true,
      pattern: emailPattern,
    }}
    returnKeyType="next"
    autoCapitalize="none"
    autoCorrect={false}
    errorLabel={{
      type: "pattern",
      label: "Your email isn't correct",
    }}
    onSubmitEditing={() => passwordRef.current?.focus()}
  />
  <TextInput
    name="password"
    label="Password"
    autoCompleteType="password"
    returnKeyType="go"
    rules={{ required: true }}
    secureTextEntry={true}
    inputRef={passwordRef}
    blurOnSubmit={false}
    onSubmitEditing={methods.handleSubmit(onSubmit)}
  />
</FormProvider>;
</code>```

In this way, I can easily set the focus, but I'm trying to make it generic: the TextInput knows who is the next element to focus.

Hope my problem is clear, any suggestion is accepted.

答:
You need to create a Wrapper component to enclose the TextInputs, then use Children.map to loop through each of them dynamically and add the onSubmitEditing function while assigning refs.

```<code>function Wrapper({ children, onLastOnSubmitEditing }) {
  const arrayChildren = Children.toArray(children);
  const childrenRef = useRef([]);
  return <>{Children.map(arrayChildren, (child, index) => {
        const onSubmitEditing = () => {
           if (index < arrayChildren.length - 1) {
               childrenRef.current[index+1].focus();
           } else {
             onLastOnSubmitEditing();
           }
        }
        return cloneElement(child, { ref: (ref) => (childrenRef.current[index] = ref), onSubmitEditing });
     })}</>
}
</code>```

Usage:

```<code><FormProvider {...methods}>
  <Wrapper onLastOnSubmitEnding={methods.handleSubmit(onSubmit)}>
    <TextInput
      name="email"
      label="Email"
      keyboardType="email-address"
      autoCompleteType="email"
      rules={{
        required: true,
        pattern: emailPattern,
      }}
      returnKeyType="next"
      autoCapitalize="none"
      autoCorrect={false}
      errorLabel={{
        type: "pattern",
        label: "Your email isn't correct",
      }}
    />
    <TextInput
      name="password"
      label="Password"
      autoCompleteType="password"
      returnKeyType="go"
      rules={{ required: true }}
      secureTextEntry={true}
      inputRef={passwordRef}
      blurOnSubmit={false}
    />
  </Wrapper>
</FormProvider>;
</code>```

Codesandbox: https://codesandbox.io/s/suspicious-euclid-rqtrrb

Body:
I created a custom TextInput with React Hook Form, I'm trying to set the focus into the next TextInput.

I explain better: in order to focus the next element, I can easily create an useRef like this:

const passwordRef = useRef<HTMLInputElement>(null);
<FormProvider {...methods}>
  <TextInput
    name="email"
    label="Email"
    keyboardType="email-address"
    autoCompleteType="email"
    rules={{
      required: true,
      pattern: emailPattern,
    }}
    returnKeyType="next"
    autoCapitalize="none"
    autoCorrect={false}
    errorLabel={{
      type: "pattern",
      label: "Your email isn't correct",
    }}
    onSubmitEditing={() => passwordRef.current?.focus()}
  />
  <TextInput
    name="password"
    label="Password"
    autoCompleteType="password"
    returnKeyType="go"
    rules={{ required: true }}
    secureTextEntry={true}
    inputRef={passwordRef}
    blurOnSubmit={false}
    onSubmitEditing={methods.handleSubmit(onSubmit)}
  />
</FormProvider>;

In this way, I can easily set the focus, but I'm trying to make it generic: the TextInput knows who is the next element to focus.

Hope my problem is clear, any suggestion is accepted.

Body:
You need to create a Wrapper component to enclose the TextInputs, then use Children.map to loop through each of them dynamically and add the onSubmitEditing function while assigning refs.

function Wrapper({ children, onLastOnSubmitEditing }) {
  const arrayChildren = Children.toArray(children);
  const childrenRef = useRef([]);
  return <>{Children.map(arrayChildren, (child, index) => {
        const onSubmitEditing = () => {
           if (index < arrayChildren.length - 1) {
               childrenRef.current[index+1].focus();
           } else {
             onLastOnSubmitEditing();
           }
        }
        return cloneElement(child, { ref: (ref) => (childrenRef.current[index] = ref), onSubmitEditing });
     })}</>
}

Usage:

<FormProvider {...methods}>
  <Wrapper onLastOnSubmitEnding={methods.handleSubmit(onSubmit)}>
    <TextInput
      name="email"
      label="Email"
      keyboardType="email-address"
      autoCompleteType="email"
      rules={{
        required: true,
        pattern: emailPattern,
      }}
      returnKeyType="next"
      autoCapitalize="none"
      autoCorrect={false}
      errorLabel={{
        type: "pattern",
        label: "Your email isn't correct",
      }}
    />
    <TextInput
      name="password"
      label="Password"
      autoCompleteType="password"
      returnKeyType="go"
      rules={{ required: true }}
      secureTextEntry={true}
      inputRef={passwordRef}
      blurOnSubmit={false}
    />
  </Wrapper>
</FormProvider>;

Codesandbox: https://codesandbox.io/s/suspicious-euclid-rqtrrb


问:
Anylogic: How to add "output" value to presentation of optimization experiment?
In my Anylogic model I have an output that gets a value after simulation end (see picture 2). I want to add this output value to the presentation of an optimization experiment (see picture 1), so that it shows the output value of the Best iteration. Can anybody tell me how to add an output value to the presentation of an optimization experiment?

答:
Manually. In the "After Simulation run" code section of your opt-experiment, you can access your output: If it lives on Main, you would be able to access it via root.outputMAPE.

So you need to check after each individual sim run, if you currently have best iteration. If so, you update a local variable in the optimization experiment and plot that:


问:
How can I convert mixed datetime formats into one?
I am facing a little problem with time data in a dataframe. I am trying to convert mixed formats with single digits and slashes (2/19/22) as well as double digits with hyphen (2020-02-19) to zero padded data with point (19.02.2022).

Data:

```<code>d = {'Date':['24.06.2022','2022-01-23', '7/2/22',  '9/23/18', '23.05.2022'],
      'Flight': ['Rome', 'Zurich', 'Dallas', 'Madrid', 'Stockholm']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3, 4])
</code>```

My code:

```<code>def autoconvert_datetime(value):
    formats = ['%-m/%-d/%y', '%Y-%m-%d']
    result_format = '%d.%m.%Y'
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value

df['Date'] = df['Date'].apply(autoconvert_datetime)

</code>```

For other datetime formats it worked without any problem.

答:
Use pd.to_datetime and let Pandas infers the format:

```<code>df['Date2'] = pd.to_datetime(df['Date'])
print(df)

# Output
         Date     Flight      Date2
0  24.06.2022       Rome 2022-06-24
1  2022-01-23     Zurich 2022-01-23
2      7/2/22     Dallas 2022-07-02
3     9/23/18     Madrid 2018-09-23
4  23.05.2022  Stockholm 2022-05-23
</code>```

If you want more control, you can directly use dateutil.parser used by Pandas.

Body:
I am facing a little problem with time data in a dataframe. I am trying to convert mixed formats with single digits and slashes (2/19/22) as well as double digits with hyphen (2020-02-19) to zero padded data with point (19.02.2022).

Data:

d = {'Date':['24.06.2022','2022-01-23', '7/2/22',  '9/23/18', '23.05.2022'],
      'Flight': ['Rome', 'Zurich', 'Dallas', 'Madrid', 'Stockholm']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3, 4])

My code:

def autoconvert_datetime(value):
    formats = ['%-m/%-d/%y', '%Y-%m-%d']
    result_format = '%d.%m.%Y'
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value

df['Date'] = df['Date'].apply(autoconvert_datetime)

For other datetime formats it worked without any problem.

Body:
Use pd.to_datetime and let Pandas infers the format:

df['Date2'] = pd.to_datetime(df['Date'])
print(df)

# Output
         Date     Flight      Date2
0  24.06.2022       Rome 2022-06-24
1  2022-01-23     Zurich 2022-01-23
2      7/2/22     Dallas 2022-07-02
3     9/23/18     Madrid 2018-09-23
4  23.05.2022  Stockholm 2022-05-23

If you want more control, you can directly use dateutil.parser used by Pandas.


问:
How to programmatically remove an HttpModule from the ASP.NET pipeline?
We can programatically add HttpModules using DynamicModuleUtility.RegisterModule(typeof (SomeHttpModule)) - is there a way to remove them?

答:
Instantiate the HTTP Module in Init method in Global.asax

Call Module.Init() as described here

In Init method of your module, hook required eventhandlers.

Override the Dispose method in the handler and unhook the
eventhandlers.

Expose the instance as public property on global.asax so that you
can call Dispose when you want to unregister the module

```<code>// Global.asax
</code>```

public IHttpModule MyModuleInstance { get; private set; }

```<code>public override void Init()
{
    base.Init();
    MyModuleInstance = new MyModule();
    MyModuleInstance.Init(this);
}

 // MyModule.cs
    public void Dispose()
    {
        _context.BeginRequest -= context_BeginRequest;
    }

    public void Init(HttpApplication context)
    {
        _context = context;
        context.BeginRequest += context_BeginRequest;
    }
   private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        app.Context.Response.Write("Hello from OnBeginRequest in custom module.<br>");
    }
</code>```

// TO unregister

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        this.ApplicationInstance.MyModuleInstance.Dispose();
    }
</code>```

Body:
Instantiate the HTTP Module in Init method in Global.asax

Call Module.Init() as described here

In Init method of your module, hook required eventhandlers.

Override the Dispose method in the handler and unhook the
eventhandlers.

Expose the instance as public property on global.asax so that you
can call Dispose when you want to unregister the module

// Global.asax

public IHttpModule MyModuleInstance { get; private set; }

public override void Init()
{
    base.Init();
    MyModuleInstance = new MyModule();
    MyModuleInstance.Init(this);
}

 // MyModule.cs
    public void Dispose()
    {
        _context.BeginRequest -= context_BeginRequest;
    }

    public void Init(HttpApplication context)
    {
        _context = context;
        context.BeginRequest += context_BeginRequest;
    }
   private void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        app.Context.Response.Write("Hello from OnBeginRequest in custom module.<br>");
    }

// TO unregister

protected void Button1_Click(object sender, EventArgs e)
    {
        this.ApplicationInstance.MyModuleInstance.Dispose();
    }


问:
ASP.NET Core 2 - Missing content-type boundary
I'm trying to upload a file from a Angular client to my ASP.NET Core 2 WebAPI service. When I call the service, I get back an Internal Server Error. That's the error I'm getting:

The component I'm using client-side is this one: ngx-uploader

In my request options, i set them as you can see here:

```<code>  const event: UploadInput = {
  type: 'uploadAll',
  url: this.printService.apiFilesBaseUrl + '/Upload',
  method: 'POST',
  file: this.files[0],
  headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': '*/*',
    'Authorization': 'Bearer ' + this.authService.getToken()
  }
};
</code>```

While, server-side my controller action signature is this one:

```<code>    [HttpPost]
    [Route("Upload")]
    [Authorize]
    public Guid Post(IFormFile file)
</code>```

Breakpoints in this controller action never get hit.

Can someone please share ideas about what's happening here?

Here, as requested, i will post my request header and payload:

Thanks in advance.

答:
You can add content-type: as multipart/form-data; boundary=--14737809831466499882746641449.

I am testing API on postman and added content-type like above it worked for me.

Body:
I'm trying to upload a file from a Angular client to my ASP.NET Core 2 WebAPI service. When I call the service, I get back an Internal Server Error. That's the error I'm getting:

The component I'm using client-side is this one: ngx-uploader

In my request options, i set them as you can see here:

  const event: UploadInput = {
  type: 'uploadAll',
  url: this.printService.apiFilesBaseUrl + '/Upload',
  method: 'POST',
  file: this.files[0],
  headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': '*/*',
    'Authorization': 'Bearer ' + this.authService.getToken()
  }
};

While, server-side my controller action signature is this one:

    [HttpPost]
    [Route("Upload")]
    [Authorize]
    public Guid Post(IFormFile file)

Breakpoints in this controller action never get hit.

Can someone please share ideas about what's happening here?

Here, as requested, i will post my request header and payload:

Thanks in advance.


问:
Unable to Connect to AWS Keyspace using a particular region
I am able to connect to aws keyspace using ap-south-1 but when I change it to us-east-2 it says
"NoHostAvailable('Unable to connect to any servers', {'3.12.23.133:9142': OperationTimedOut('errors=None, last_host=None')})"

I am using python for connection

```<code>if __name__ == '__main__':
    sUsername = '******-at-43*****6380240297'
    sPassword = '********'
    sUrl = 'cassandra.us-east-2.amazonaws.com'
    sSSLCertPath = 'C:\\Users\\KArora\\Downloads\\sf-class2-root.crt'
    sPort = 9142
    session = getDBClient(sUrl, sUsername, sPassword, sPort, sSSLCertPath)

def getDBClient(sURL, sUserName, sPassword, sPort, sSSLCertPath):
    error = ""
    try:
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.load_verify_locations(sSSLCertPath)
        ssl_context.verify_mode = CERT_REQUIRED
        auth_provider = PlainTextAuthProvider(username=sUserName, password=sPassword)
        sConn = []
        sConn.append(sURL)
        cluster = Cluster(sConn, ssl_context=ssl_context, auth_provider=auth_provider, port=sPort)
        session = cluster.connect()
        #error += "Success"
        return session
    except Exception as e:
        #error += "Failure"
        return str(e)
</code>```

答: Amazon Keyspaces requires that SSL is enabled for connections to ensure strong security. The SSL parameter might be missing if you receive that error. To resolve this error you can add the --sslflag to your to your cql connection command. We've listened to our customers and we've created this guide to help if you run into connection issues.

Body:
I am able to connect to aws keyspace using ap-south-1 but when I change it to us-east-2 it says
"NoHostAvailable('Unable to connect to any servers', {'3.12.23.133:9142': OperationTimedOut('errors=None, last_host=None')})"

I am using python for connection

if __name__ == '__main__':
    sUsername = '******-at-43*****6380240297'
    sPassword = '********'
    sUrl = 'cassandra.us-east-2.amazonaws.com'
    sSSLCertPath = 'C:\\Users\\KArora\\Downloads\\sf-class2-root.crt'
    sPort = 9142
    session = getDBClient(sUrl, sUsername, sPassword, sPort, sSSLCertPath)

def getDBClient(sURL, sUserName, sPassword, sPort, sSSLCertPath):
    error = ""
    try:
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.load_verify_locations(sSSLCertPath)
        ssl_context.verify_mode = CERT_REQUIRED
        auth_provider = PlainTextAuthProvider(username=sUserName, password=sPassword)
        sConn = []
        sConn.append(sURL)
        cluster = Cluster(sConn, ssl_context=ssl_context, auth_provider=auth_provider, port=sPort)
        session = cluster.connect()
        #error += "Success"
        return session
    except Exception as e:
        #error += "Failure"
        return str(e)


问:
Storybook.js (Vue) Docs Template Output
Using StoryBook.js, when I navigate to a component, view its "Docs" and click the "Show Code" button, why do I get code that looks like this...

```<code>(args, { argTypes }) => ({
    components: { Button },
    props: Object.keys(argTypes),
    template: '<Button v-bind="$props" />',
})
</code>```

...as opposed to this...

```<code><Button type="button" class="btn btn-primary">Label</Button>
</code>```

Button.vue

```<code><template>
  <button
    :type="type"
    :class="'btn btn-' + (outlined ? 'outline-' : '') + variant"
    :disabled="disabled">Label</button>
</template>

<script>
export default {
  name: "Button",
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    outlined: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: 'button',
    },
    variant: {
      type: String,
      default: 'primary',
      validator(value) {
        return ['primary', 'success', 'warning', 'danger'].includes(value)
      }
    }
  }
}
</script>
</code>```

Button.stories.js

```<code>import Button from '../components/Button'

export default {
    title: 'Button',
    component: Button,
    parameters: {
      componentSubtitle: 'Click to perform an action or submit a form.',
    },
    argTypes: {
        disabled: {
            description: 'Make a button appear to be inactive and un-clickable.',
        },
        outlined: {
            description: 'Add a border to the button and remove the fill colour.',
        },
        type: {
            options: ['button', 'submit'],
            control: { type: 'inline-radio' },
            description: 'Use "submit" when you want to submit a form. Use "button" otherwise.',
        },
        variant: {
            options: ['primary', 'success'],
            control: { type: 'select' },
            description: 'Bootstrap theme colours.',
        },
    },
}

const Template = (args, { argTypes }) => ({
    components: { Button },
    props: Object.keys(argTypes),
    template: '<Button v-bind="$props" />',
})

export const Filled = Template.bind({})
Filled.args = { disabled: false, outlined: false, type: 'button', variant: 'primary' }

export const Outlined = Template.bind({})
Outlined.args = { disabled: false, outlined: true, type: 'button', variant: 'primary' }

export const Disabled = Template.bind({})
Disabled.args = { disabled: true, outlined: false, type: 'button', variant: 'primary' }

</code>```

I thought I followed their guides to the letter, but I just can't understand why the code output doesn't look the way I expect it to.

I simply want any of my colleagues using this to be able to copy the code from the template and paste it into their work if they want to use the component without them having to be careful what they select from the code output.

答:
For anyone else who encounters this issue, I discovered that this is a known issue for StoryBook with Vue 3.

As mine is currently a green-field project at the time of writing this, I put a temporary workaround in place by downgrading Vue to ^2.6.

This is OK for me. I'm using the options API to build my components anyway so I'll happily upgrade to Vue ^3 when Storybook resolve the above linked issue.

Title: Storybook.js (Vue) Docs Template Output

Body:
Using StoryBook.js, when I navigate to a component, view its "Docs" and click the "Show Code" button, why do I get code that looks like this...

(args, { argTypes }) => ({
    components: { Button },
    props: Object.keys(argTypes),
    template: '<Button v-bind="$props" />',
})

...as opposed to this...

<Button type="button" class="btn btn-primary">Label</Button>

Button.vue

<template>
  <button
    :type="type"
    :class="'btn btn-' + (outlined ? 'outline-' : '') + variant"
    :disabled="disabled">Label</button>
</template>

Button.stories.js

import Button from '../components/Button'

export default {
    title: 'Button',
    component: Button,
    parameters: {
      componentSubtitle: 'Click to perform an action or submit a form.',
    },
    argTypes: {
        disabled: {
            description: 'Make a button appear to be inactive and un-clickable.',
        },
        outlined: {
            description: 'Add a border to the button and remove the fill colour.',
        },
        type: {
            options: ['button', 'submit'],
            control: { type: 'inline-radio' },
            description: 'Use "submit" when you want to submit a form. Use "button" otherwise.',
        },
        variant: {
            options: ['primary', 'success'],
            control: { type: 'select' },
            description: 'Bootstrap theme colours.',
        },
    },
}

const Template = (args, { argTypes }) => ({
    components: { Button },
    props: Object.keys(argTypes),
    template: '<Button v-bind="$props" />',
})

export const Filled = Template.bind({})
Filled.args = { disabled: false, outlined: false, type: 'button', variant: 'primary' }

export const Outlined = Template.bind({})
Outlined.args = { disabled: false, outlined: true, type: 'button', variant: 'primary' }

export const Disabled = Template.bind({})
Disabled.args = { disabled: true, outlined: false, type: 'button', variant: 'primary' }

I thought I followed their guides to the letter, but I just can't understand why the code output doesn't look the way I expect it to.

I simply want any of my colleagues using this to be able to copy the code from the template and paste it into their work if they want to use the component without them having to be careful what they select from the code output.