答:
Side note: Curiously, you did an iterative solution for reversal, but did a recursive solutions for create and printList

Your function is pretty close to optimal.

But, you fetched curr->next twice. Admittedly, with an optimizer, there should be no extra speed penalty.

But, I'd simplify that. And, I think a for loop can be cleaner:

```<code>node *
reversedFor(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *prev = NULL;
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
    }

    return prev;
}
</code>```

Edit: And, as Vlad mentioned, you don't check for curr being non-null before dereferencing it. So, my above refactoring fixed the bug with a bit of serendipity.

Here's what I'd to clean everything up:

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

// node
typedef struct node {
    int number;
    struct node *next;
} node;

// functions
node *reversedList(node *head);
node *reversedFor(node *head);
void printList(node *head,const char *tag);
node *create(int size);
node *delList(node *head);

typedef node *(revfnc_p)(node *head);

void
dotest(revfnc_p fnc,const char *tag)
{
    node *list;

    printf("dotest: %s\n",tag);

    list = create(10);
    printList(list,"orig");

    list = fnc(list);
    printList(list,"revd");

    delList(list);
}

int
main(void)
{

    dotest(reversedList,"reversedList");
    dotest(reversedFor,"reversedFor");

    return 0;
}

node *
reversedList(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *previous = NULL;

    while (curr->next != NULL) {
        node *curr_temp = curr->next;

        curr->next = previous;
        previous = curr;
        curr = curr_temp;
    }
    curr->next = previous;
    return curr;
}

node *
reversedFor(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *prev = NULL;
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
    }

    return prev;
}

void
printList(node *head,const char *tag)
{

    if (tag != NULL)
        printf("%s:",tag);

    for (node *curr = head;  curr != NULL;  curr = curr->next)
        printf(" %d",curr->number);

    printf("\n");
}

node *
create(int size)
{
    node *head = NULL;
    node *prev = NULL;
    node *curr;

    for (int idx = 0;  idx < size;  ++idx) {
        curr = malloc(sizeof(*curr));
        curr->number = idx;
        curr->next = NULL;

        if (head == NULL)
            head = curr;
        else
            prev->next = curr;

        prev = curr;
    }

    return head;
}

node *
delList(node *curr)
{
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        free(curr);
    }

    return curr;
}
</code>```

Here's the program output:

```<code>dotest: reversedList
orig: 0 1 2 3 4 5 6 7 8 9
revd: 9 8 7 6 5 4 3 2 1 0
dotest: reversedFor
orig: 0 1 2 3 4 5 6 7 8 9
revd: 9 8 7 6 5 4 3 2 1 0
</code>```

Title: What is the best way to create/reverse a linked list?

Body:
Side note: Curiously, you did an iterative solution for reversal, but did a recursive solutions for create and printList

Your function is pretty close to optimal.

But, you fetched curr->next twice. Admittedly, with an optimizer, there should be no extra speed penalty.

But, I'd simplify that. And, I think a for loop can be cleaner:

node *
reversedFor(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *prev = NULL;
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
    }

    return prev;
}

Edit: And, as Vlad mentioned, you don't check for curr being non-null before dereferencing it. So, my above refactoring fixed the bug with a bit of serendipity.

Here's what I'd to clean everything up:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// node
typedef struct node {
    int number;
    struct node *next;
} node;

// functions
node *reversedList(node *head);
node *reversedFor(node *head);
void printList(node *head,const char *tag);
node *create(int size);
node *delList(node *head);

typedef node *(revfnc_p)(node *head);

void
dotest(revfnc_p fnc,const char *tag)
{
    node *list;

    printf("dotest: %s\n",tag);

    list = create(10);
    printList(list,"orig");

    list = fnc(list);
    printList(list,"revd");

    delList(list);
}

int
main(void)
{

    dotest(reversedList,"reversedList");
    dotest(reversedFor,"reversedFor");

    return 0;
}

node *
reversedList(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *previous = NULL;

    while (curr->next != NULL) {
        node *curr_temp = curr->next;

        curr->next = previous;
        previous = curr;
        curr = curr_temp;
    }
    curr->next = previous;
    return curr;
}

node *
reversedFor(node *curr)
{
    // a->b->c->d
    // d->c->b->a
    node *prev = NULL;
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
    }

    return prev;
}

void
printList(node *head,const char *tag)
{

    if (tag != NULL)
        printf("%s:",tag);

    for (node *curr = head;  curr != NULL;  curr = curr->next)
        printf(" %d",curr->number);

    printf("\n");
}

node *
create(int size)
{
    node *head = NULL;
    node *prev = NULL;
    node *curr;

    for (int idx = 0;  idx < size;  ++idx) {
        curr = malloc(sizeof(*curr));
        curr->number = idx;
        curr->next = NULL;

        if (head == NULL)
            head = curr;
        else
            prev->next = curr;

        prev = curr;
    }

    return head;
}

node *
delList(node *curr)
{
    node *next;

    for (;  curr != NULL;  curr = next) {
        next = curr->next;
        free(curr);
    }

    return curr;
}

Here's the program output:

dotest: reversedList
orig: 0 1 2 3 4 5 6 7 8 9
revd: 9 8 7 6 5 4 3 2 1 0
dotest: reversedFor
orig: 0 1 2 3 4 5 6 7 8 9
revd: 9 8 7 6 5 4 3 2 1 0


来源: stackexchange

问:
block a button until the user accepts the geolocation react.js
Let's see how I explain this, I am trying that when a user presses a button it asks if they want to save the location or not, when they press the allow button it should send them to another page, but if on the contrary we press block it will show a message until the user decides to accept the geolocation. (Everything is done with the same button, that is, pressing it if there is no request for permission, and if it has already been granted or denied, it shows the content of allowing or blocking)</p>
```<code>   const getButtonId = (e) => {
        e.preventDefault();

        if(!('geolocation' in navigator)) {
            console.log('Opción no disponible');
            return;
        }
        navigator.geolocation.getCurrentPosition(pos => {

        }, err => {

            console.log('Error obteniendo localización: ' + err.message);
        });
      }

 <button className="btn primary mr-0 lg:mr-8 w-[200px] mb-4" onClick={getButtonId}>Continuar</button>
</code>```

答:
I hope I understand you correctly, you want a button to be active or disabled based on something.
you can disable it by <button disabled={true}> and instead of hardcoding the "true" assign it to a useState() and change it with setState()

```<code>const demo = () => {
    const [btnState, setBtnState] = useState(false) // this is the starting value of the btn false == active

    // u can call the setBtnState to change the btn state like so:

    setBtnState(true) // here u give it the new state (true/false)

    // every time u set a new state using this function the "disabled" value will update

    return(
        <button disabled={btnState}></button>
    )
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
Let's see how I explain this, I am trying that when a user presses a button it asks if they want to save the location or not, when they press the allow button it should send them to another page, but if on the contrary we press block it will show a message until the user decides to accept the geolocation. (Everything is done with the same button, that is, pressing it if there is no request for permission, and if it has already been granted or denied, it shows the content of allowing or blocking)

   const getButtonId = (e) => {
        e.preventDefault();

        if(!('geolocation' in navigator)) {
            console.log('Opción no disponible');
            return;
        }
        navigator.geolocation.getCurrentPosition(pos => {

        }, err => {

            console.log('Error obteniendo localización: ' + err.message);
        });
      }

 <button className="btn primary mr-0 lg:mr-8 w-[200px] mb-4" onClick={getButtonId}>Continuar</button>

Body:
I hope I understand you correctly, you want a button to be active or disabled based on something.
you can disable it by <button disabled={true}> and instead of hardcoding the "true" assign it to a useState() and change it with setState()

const demo = () => {
    const [btnState, setBtnState] = useState(false) // this is the starting value of the btn false == active

    // u can call the setBtnState to change the btn state like so:

    setBtnState(true) // here u give it the new state (true/false)

    // every time u set a new state using this function the "disabled" value will update

    return(
        <button disabled={btnState}></button>
    )

}


问:
Serverless Framework - Cannot generate IAM policy statement for Task state
I'm trying to use serverless framework to deploy a step function that calls a couple of lambdas. Here's my serverless.yml:

    org: bizrob
    app: flexipod-2-queue
    service: flexipod-2-queue

    frameworkVersion: "2 || 3"

    custom:
      region: eu-west-1

    provider:
      name: aws
      runtime: nodejs14.x

    plugins:
      - serverless-step-functions

    functions:
      pullSqlSvr:
        handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"
          SQS_QUEUE_URL: !Ref "MyQueue"
      sendToDataLake:
        handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"

    stepFunctions:
      stateMachines:
        flexipodFlow:
          name: flexipodFlow
          definition:
            StartAt: pullSqlSvr
            States:
              pullSqlSvr:
                Type: Task
                Resource:
                  Fn::GetAtt:[pullSqlSvr, Arn]
                Next: sendToDataLake
              sendToDataLake:
                Type: Task
                Resource:
                  Fn::GetAtt:[sendToDataLake, Arn]
                End: true

    resources:
      Resources:
        MyQueue:
          Type: "AWS::SQS::Queue"
          Properties:
            QueueName: "flexipod"
```

When I run serverless deploy I see the following error:

Deploying flexipod-2-queue to stage dev (us-east-1,
"serverless-admin-2" provider) Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[pullSqlSvr,
Arn]', Next: 'sendToDataLake' } Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[sendToDataLake,
Arn]', End: true }

× Stack flexipod-2-queue-dev failed to deploy (72s) Environment:
win32, node 16.1.0, framework 3.0.0, plugin 6.0.0, SDK 4.3.0
Credentials: Serverless Dashboard, "serverless-admin-2" provider
(https://app.serverless.com/bizrob/apps/flexipod-2-queue/flexipod-2-queue/dev/us-east-1/providers)
Docs:        docs.serverless.com Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error: CREATE_FAILED: FlexipodFlow (AWS::StepFunctions::StateMachine)
Resource handler returned message: "Invalid State Machine Definition:
'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at
/States/pullSqlSvr/Resource, SCHEMA_VALIDATION_FAILED: Value is not a
valid resource ARN at /States/sendToDataLake/Resource' (Service:
AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition

Any advice on how to solve please?

答:
It's a YAML syntax problem.  Fn::GetAtt:[pullSqlSvr, Arn] is being parsed as a string, not a key-value pair.  Add a space after the last colon, or use the !GetAtt shortcut.

Resource:
  Fn::GetAtt:[pullSqlSvr, Arn] # string :(
  Fn::GetAtt: [pullSqlSvr, Arn] # key-value :)
  !GetAtt pullSqlSvr.Arn # alternative shorthand intrinsic function :)
```

Body:
I'm trying to use serverless framework to deploy a step function that calls a couple of lambdas. Here's my serverless.yml:

    org: bizrob
    app: flexipod-2-queue
    service: flexipod-2-queue

    frameworkVersion: "2 || 3"

    custom:
      region: eu-west-1

    provider:
      name: aws
      runtime: nodejs14.x

    plugins:
      - serverless-step-functions

    functions:
      pullSqlSvr:
        handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"
          SQS_QUEUE_URL: !Ref "MyQueue"
      sendToDataLake:
        handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"

    stepFunctions:
      stateMachines:
        flexipodFlow:
          name: flexipodFlow
          definition:
            StartAt: pullSqlSvr
            States:
              pullSqlSvr:
                Type: Task
                Resource:
                  Fn::GetAtt:[pullSqlSvr, Arn]
                Next: sendToDataLake
              sendToDataLake:
                Type: Task
                Resource:
                  Fn::GetAtt:[sendToDataLake, Arn]
                End: true

    resources:
      Resources:
        MyQueue:
          Type: "AWS::SQS::Queue"
          Properties:
            QueueName: "flexipod"

When I run serverless deploy I see the following error:

Deploying flexipod-2-queue to stage dev (us-east-1,
"serverless-admin-2" provider) Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[pullSqlSvr,
Arn]', Next: 'sendToDataLake' } Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[sendToDataLake,
Arn]', End: true }

× Stack flexipod-2-queue-dev failed to deploy (72s) Environment:
win32, node 16.1.0, framework 3.0.0, plugin 6.0.0, SDK 4.3.0
Credentials: Serverless Dashboard, "serverless-admin-2" provider
(https://app.serverless.com/bizrob/apps/flexipod-2-queue/flexipod-2-queue/dev/us-east-1/providers)
Docs:        docs.serverless.com Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error: CREATE_FAILED: FlexipodFlow (AWS::StepFunctions::StateMachine)
Resource handler returned message: "Invalid State Machine Definition:
'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at
/States/pullSqlSvr/Resource, SCHEMA_VALIDATION_FAILED: Value is not a
valid resource ARN at /States/sendToDataLake/Resource' (Service:
AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition

Any advice on how to solve please?


问:
How can I get the nth occurrence of a searchvalue in a string with a regular expression?
For example, string is "staaaae", If searchValue is "aa", n=2, then 3 will return. </p>

答:
This is not a feature of regex itself, but depending on your language you can get this information.

For one thing I have to correct you. The start index for the second match is 4 and not 3 (Standard regex matching behaviour)

```<code>staaaae
  ^^  first match
    ^^   second match
</code>```

The pattern continues to search after the first match, so the matches do not overlap.

Perl

In Perl for example its no problem.

In addition to what was matched, Perl (since 5.6.0) also provides the
  positions of what was matched as contents of the @- and @+ arrays.
  $-[0] is the position of the start of the entire match and $+[0] is
  the position of the end. Similarly, $-[n] is the position of the start
  of the $n match and $+[n] is the position of the end. If $n is
  undefined, so are $-[n] and $+[n] .

cited from Perlretut

so in Perl the information you want would be in $-[n].

c#/.net

In .net its also no problem. Only a bit more effort than in Perl.

The class Match returns you also the index of the match, but it matches only one at a time, so you have to go through a loop to get all matches.

```<code>string input = "staaaae";
string pattern = @"aa";
Match match = Regex.Match(input, pattern);
int count = 0;

while (match.Success)
{
    count++;
    Console.WriteLine("'{0}' was found the {1} timein the source code at position {2}.",
    match.Value, count, match.Index);
    match = match.NextMatch();
}
Console.ReadLine();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is not a feature of regex itself, but depending on your language you can get this information.

For one thing I have to correct you. The start index for the second match is 4 and not 3 (Standard regex matching behaviour)

staaaae
  ^^  first match
    ^^   second match

The pattern continues to search after the first match, so the matches do not overlap.

Perl

In Perl for example its no problem.

In addition to what was matched, Perl (since 5.6.0) also provides the
  positions of what was matched as contents of the @- and @+ arrays.
  $-[0] is the position of the start of the entire match and $+[0] is
  the position of the end. Similarly, $-[n] is the position of the start
  of the $n match and $+[n] is the position of the end. If $n is
  undefined, so are $-[n] and $+[n] .

cited from Perlretut

so in Perl the information you want would be in $-[n].

c#/.net

In .net its also no problem. Only a bit more effort than in Perl.

The class Match returns you also the index of the match, but it matches only one at a time, so you have to go through a loop to get all matches.

string input = "staaaae";
string pattern = @"aa";
Match match = Regex.Match(input, pattern);
int count = 0;

while (match.Success)
{
    count++;
    Console.WriteLine("'{0}' was found the {1} timein the source code at position {2}.",
    match.Value, count, match.Index);
    match = match.NextMatch();
}
Console.ReadLine();


问:
reference to 'Microsoft.Resources/deployments/' requires an API version
If I add a condition before deploying a template for a virtual network I always get this error :If I remove the condition it works???

template deployment returned the following errors:
Error: Code=InvalidTemplate; Message=Deployment template validation failed: 'The template resource 'Microsoft.Resources/deployments/dm5DbServer' reference to 'Microsoft.Resources/deployments/dm5VirtualNetwork' requires an API version.

```<code>"resources": [
{
  "condition": "[equals(parameters('BuildDatabaseServer'), 'yes')]",
  "apiVersion": "2016-02-01",
  "name": "[variables('virtualNetworkName')]",
  "type": "Microsoft.Resources/deployments",
  "dependsOn": [],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[concat(parameters('_artifactsLocation'), '/', variables('virtualNetworkTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "virtualNetworkName": { "value": "[variables('virtualNetworkName')]" },
      "vNetPrefix": { "value": "[variables('vNetPrefix')]" },
      "databaseSubnetPrimaryName": { "value": "[variables('databaseSubnetPrimaryName')]" },
      "databaseSubnetPrimaryPrefix": { "value": "[variables('databaseSubnetPrimaryPrefix')]" },
      "databaseSubnetPrimaryNsgName": { "value": "[variables('databaseSubnetPrimaryNsgName')]" }
    }
  }
},
</code>```

Template being called:

```<code>  {
  "name": "[parameters('virtualNetworkName')]",
  "type": "Microsoft.Network/virtualNetworks",
  "location": "[resourceGroup().location]",
  "apiVersion": "2016-03-30",
  "dependsOn": [
    "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('databaseSubnetPrimaryNsgName'))]",
  ],
  "tags": {
    "displayName": "[parameters('virtualNetworkName')]"
  },
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "[parameters('vNetPrefix')]"
      ]
    },
    "subnets": [

      {
        "name": "[parameters('databaseSubnetPrimaryName')]",
        "properties": {
          "addressPrefix": "[parameters('databaseSubnetPrimaryPrefix')]",
          "networkSecurityGroup": {
            "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('databaseSubnetPrimaryNsgName'))]"
          }
        }
      }

  {
  "condition": "[equals(parameters('BuildDatabaseServer'), 'yes')]",
  "apiVersion": "2016-02-01",
  "name": "[variables('databaseServerName')]",
  "type": "Microsoft.Resources/deployments",
  "dependsOn": [
    "[resourceId('Microsoft.Resources/deployments', variables('virtualNetworkName'))]"
  ],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[concat(parameters('_artifactsLocation'), '/', variables('commonTemplateArchiveFolder'), '/', variables('virtualMachineTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "serverName": { "value": "[variables('databaseServerName')]" },
      "adminUserName": { "value": "[variables('databaseServerAdminUserName')]" },
      "adminPassword": { "value": "[parameters('databaseServerAdminPassword')]" },
      "serverWindowsOSVersion": { "value": "[parameters('databaseServerWindowsOSVersion')]" },
      "serverVmSize": { "value": "[variables('databaseServerVmSize')]" },
      "primaryNetworkSecurityGroupName": { "value": "[variables('databaseSubnetPrimaryNsgName')]" },
      "primarySubnetRef": { "value": "[reference(variables('virtualNetworkName')).outputs.databaseSubnetPrimaryRef.value]" },
      "primaryPrivateIPAddress": { "value": "[variables('databaseServerPrimaryPrivateIPAddress')]" },
      "serverOsDiskStorageAccountType": { "value": "[variables('databaseServerOSDiskStorageAccountType')]" },
      "serverDataDiskStorageAccountType": { "value": "[variables('databaseServerDataDiskStorageAccountType')]" },
      "serverDataDiskSizeGB": { "value": "[variables('databaseServerDataDiskSizeGB')]" },
      "monitoringAgentWorkspaceID": { "value": "[parameters('monitoringAgentWorkspaceID')]" },
      "monitoringAgentWorkspaceKey": { "value": "[parameters('monitoringAgentWorkspaceKey')]" },
      "customscripts": { "value": "[variables('customScripts')]" }
    }
  }
},
</code>```

答:
Applying @DeveloperExceptionError answer, here is a bicep example using the aks_enable_private_cluster variable for conditional deployment:

```<code>// User Managed Identity
resource idAccessToAks 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = if (aks_enable_private_cluster) {
  name: 'id_aks_access_n'
  location: resourceGroup().location
}

// User Managed Identity RBAC assignment
resource idAccessToAksRoleAssignment 'Microsoft.Authorization/roleAssignments@2020-08-01-preview' = if (aks_enable_private_cluster) {
  name: guid(subscription().id, 'dev', '3498e952-d568-435e-9b2c-8d77e338d7f7')
  properties: {
    principalId: aks_enable_private_cluster ? idAccessToAks.properties.principalId : ''
    roleDefinitionId: '${subscription().id}/providers/Microsoft.Authorization/roleDefinitions/3498e952-d568-435e-9b2c-8d77e338d7f7'
    principalType: 'ServicePrincipal'
  }
}
</code>```

Body:
If I add a condition before deploying a template for a virtual network I always get this error :If I remove the condition it works???

template deployment returned the following errors:
Error: Code=InvalidTemplate; Message=Deployment template validation failed: 'The template resource 'Microsoft.Resources/deployments/dm5DbServer' reference to 'Microsoft.Resources/deployments/dm5VirtualNetwork' requires an API version.

"resources": [
{
  "condition": "[equals(parameters('BuildDatabaseServer'), 'yes')]",
  "apiVersion": "2016-02-01",
  "name": "[variables('virtualNetworkName')]",
  "type": "Microsoft.Resources/deployments",
  "dependsOn": [],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[concat(parameters('_artifactsLocation'), '/', variables('virtualNetworkTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "virtualNetworkName": { "value": "[variables('virtualNetworkName')]" },
      "vNetPrefix": { "value": "[variables('vNetPrefix')]" },
      "databaseSubnetPrimaryName": { "value": "[variables('databaseSubnetPrimaryName')]" },
      "databaseSubnetPrimaryPrefix": { "value": "[variables('databaseSubnetPrimaryPrefix')]" },
      "databaseSubnetPrimaryNsgName": { "value": "[variables('databaseSubnetPrimaryNsgName')]" }
    }
  }
},

Template being called:

  {
  "name": "[parameters('virtualNetworkName')]",
  "type": "Microsoft.Network/virtualNetworks",
  "location": "[resourceGroup().location]",
  "apiVersion": "2016-03-30",
  "dependsOn": [
    "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('databaseSubnetPrimaryNsgName'))]",
  ],
  "tags": {
    "displayName": "[parameters('virtualNetworkName')]"
  },
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "[parameters('vNetPrefix')]"
      ]
    },
    "subnets": [

      {
        "name": "[parameters('databaseSubnetPrimaryName')]",
        "properties": {
          "addressPrefix": "[parameters('databaseSubnetPrimaryPrefix')]",
          "networkSecurityGroup": {
            "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('databaseSubnetPrimaryNsgName'))]"
          }
        }
      }

  {
  "condition": "[equals(parameters('BuildDatabaseServer'), 'yes')]",
  "apiVersion": "2016-02-01",
  "name": "[variables('databaseServerName')]",
  "type": "Microsoft.Resources/deployments",
  "dependsOn": [
    "[resourceId('Microsoft.Resources/deployments', variables('virtualNetworkName'))]"
  ],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[concat(parameters('_artifactsLocation'), '/', variables('commonTemplateArchiveFolder'), '/', variables('virtualMachineTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "serverName": { "value": "[variables('databaseServerName')]" },
      "adminUserName": { "value": "[variables('databaseServerAdminUserName')]" },
      "adminPassword": { "value": "[parameters('databaseServerAdminPassword')]" },
      "serverWindowsOSVersion": { "value": "[parameters('databaseServerWindowsOSVersion')]" },
      "serverVmSize": { "value": "[variables('databaseServerVmSize')]" },
      "primaryNetworkSecurityGroupName": { "value": "[variables('databaseSubnetPrimaryNsgName')]" },
      "primarySubnetRef": { "value": "[reference(variables('virtualNetworkName')).outputs.databaseSubnetPrimaryRef.value]" },
      "primaryPrivateIPAddress": { "value": "[variables('databaseServerPrimaryPrivateIPAddress')]" },
      "serverOsDiskStorageAccountType": { "value": "[variables('databaseServerOSDiskStorageAccountType')]" },
      "serverDataDiskStorageAccountType": { "value": "[variables('databaseServerDataDiskStorageAccountType')]" },
      "serverDataDiskSizeGB": { "value": "[variables('databaseServerDataDiskSizeGB')]" },
      "monitoringAgentWorkspaceID": { "value": "[parameters('monitoringAgentWorkspaceID')]" },
      "monitoringAgentWorkspaceKey": { "value": "[parameters('monitoringAgentWorkspaceKey')]" },
      "customscripts": { "value": "[variables('customScripts')]" }
    }
  }
},

Body:
Applying @DeveloperExceptionError answer, here is a bicep example using the aks_enable_private_cluster variable for conditional deployment:

// User Managed Identity
resource idAccessToAks 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = if (aks_enable_private_cluster) {
  name: 'id_aks_access_n'
  location: resourceGroup().location
}

// User Managed Identity RBAC assignment
resource idAccessToAksRoleAssignment 'Microsoft.Authorization/roleAssignments@2020-08-01-preview' = if (aks_enable_private_cluster) {
  name: guid(subscription().id, 'dev', '3498e952-d568-435e-9b2c-8d77e338d7f7')
  properties: {
    principalId: aks_enable_private_cluster ? idAccessToAks.properties.principalId : ''
    roleDefinitionId: '${subscription().id}/providers/Microsoft.Authorization/roleDefinitions/3498e952-d568-435e-9b2c-8d77e338d7f7'
    principalType: 'ServicePrincipal'
  }
}


问:
How to convert array to Tree View with expand collapse functionality using jQuery?
This is quiet tricky, but some nerd can answer my query as I failed on achieving.

Let's say I have an array with below values.

globalResFiltered = [];
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"001"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"012"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"006"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Mango",Value:"011"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"013"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"004"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"010"});

    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"014"});
    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"015"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"005"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"016"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"003"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"017"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"018"});

    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"019"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"020"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Silver",Value:"007"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"002"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"008"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"009"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"021"});

console.log(globalResFiltered);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>(Please see console for array output)</code>```

Perfect, now my array has 3 main categories:

Fruit

Color

Jewellery

Each of them have Subcategories(can be repetetive):

Fruit - Orange, Mango & Apple

Color - Silver, Orange & Red

Jewellery - Bronze, Silver, Gold & Platinum

And each of those subcategories hold some values(from 001 to 021)

Now, the main part of the question. I want above array to be converted to tree view.

I already have HTML, JS & CSS code on how the output should be.

The values are hard coded.

Check below snippet

$(function () {
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #000000;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}</code>```

            Fruit

                    Orange

                            001

                            012

                            016

                    Mango

                            011

                    Apple

                            013

                            004

                            010

            Color

                    Silver

                            014

                            015

                    Orange

                            005

                            016

                    Red

                            003

                            017

                            018

            Jewellery

                    Bronze

                            019

                            020

                    Silver

                            007

                    Gold

                            002

                            008

                    Platinum

                            009

                            021

```
</div>
</div>
</p>
<br />
The above values are hard coded, I need something which would convert the output of array to above HTML.<br />
This is what I have tried so far. It does not loop subcategories(Incorrect Output)<br />
Also, not sure how to show values<br />
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var globalResFiltered = [];
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"001"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"012"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"006"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Mango",Value:"011"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"013"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"004"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"010"});

    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"014"});
    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"015"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"005"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"016"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"003"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"017"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"018"});

    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"019"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"020"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Silver",Value:"007"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"002"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"008"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"009"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"021"});

    var tempCat = "";
    var tempSubCat = "";

    $(globalResFiltered).each(function(i,v){

        if(i==0 || i==1 || i==2){debugger;}
        if(tempCat != v.Category)
        {
            $("#myTree").append("<ul><li>"+v.Category+"</li></ul>");
            $(".c_"+v.Category).after("<ul><li id='x_"+i+"_"+v.Category+"_"+v.Subcategory+"'><a>"+v.Subcategory+"</a></li></ul>");
        }
        else
        {
            $("#x_0"+v.Category+"_"+v.Subcategory).after("<li id='x_"+i+"_"+v.Category+"_"+v.Subcategory+"'><a>"+v.Subcategory+"</a></li>");
        }
        tempCat = v.Category;

    });

$(function () {
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});</code>```

/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #5a8dee;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Incorrect, it only shows one subcategory
<div class="vertical-tree" id="myTree">
</div></code>```

I have tried checking below reference, but in vain.

https://www.jqueryscript.net/table/jQuery-Plugin-For-Displaying-A-Tree-Of-Data-In-A-Table-treetable.html
https://www.jqueryscript.net/demo/simple-tree-table/

Thanks in advance for your help '

答:
I would do this in two steps:

Convert the data structure to a hierarchical one: toHierarchy

Turn that hierarchy to a hierarchy of DOM elements: createList

Here is the code:

function toHierarchy(data, ...fields) {
    let map = {};
    for (let item of data) {
        let node = map;
        for (let field of fields) {
            let value = item[field];
            node = (node[value] ??= {});
        }
    }
    return map;
}

function createList(hierarchy) {
    return $("
").css({display: "none"}).append(
        Object.entries(hierarchy).flatMap(([value, children]) => $("
").append(
             $("", { href: "javascript:void(0);" }).text(value),
             createList(children)
        ))
    );
}

// Your sample data:
const globalResFiltered = [{Category:"Fruit",Subcategory:"Orange",Value:"001"},{Category:"Fruit",Subcategory:"Orange",Value:"012"},{Category:"Fruit",Subcategory:"Orange",Value:"006"},{Category:"Fruit",Subcategory:"Mango",Value:"011"},{Category:"Fruit",Subcategory:"Apple",Value:"013"},{Category:"Fruit",Subcategory:"Apple",Value:"004"},{Category:"Fruit",Subcategory:"Apple",Value:"010"},{Category:"Color",Subcategory:"Silver",Value:"014"},{Category:"Color",Subcategory:"Silver",Value:"015"},{Category:"Color",Subcategory:"Orange",Value:"005"},{Category:"Color",Subcategory:"Orange",Value:"016"},{Category:"Color",Subcategory:"Red",Value:"003"},{Category:"Color",Subcategory:"Red",Value:"017"},{Category:"Color",Subcategory:"Red",Value:"018"},{Category:"Jewellery",Subcategory:"Bronze",Value:"019"},{Category:"Jewellery",Subcategory:"Bronze",Value:"020"},{Category:"Jewellery",Subcategory:"Silver",Value:"007"},{Category:"Jewellery",Subcategory:"Gold",Value:"002"},{Category:"Jewellery",Subcategory:"Gold",Value:"008"},{Category:"Jewellery",Subcategory:"Platinum",Value:"009"},{Category:"Jewellery",Subcategory:"Platinum",Value:"021"}];

// Convert data structure to a hierarchical one:
const hierarchy = toHierarchy(globalResFiltered, "Category", "Subcategory", "Value");

$(function () {
    // Added this line:
    $(".vertical-tree").empty().append(createList(hierarchy));
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #000000;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}</code>```

```

Body:
This is quiet tricky, but some nerd can answer my query as I failed on achieving.

Let's say I have an array with below values.

globalResFiltered = [];
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"001"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"012"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"006"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Mango",Value:"011"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"013"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"004"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"010"});

    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"014"});
    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"015"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"005"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"016"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"003"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"017"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"018"});

    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"019"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"020"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Silver",Value:"007"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"002"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"008"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"009"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"021"});

console.log(globalResFiltered);

(Please see console for array output)

Perfect, now my array has 3 main categories:

Fruit

Color

Jewellery

Each of them have Subcategories(can be repetetive):

Fruit - Orange, Mango & Apple

Color - Silver, Orange & Red

Jewellery - Bronze, Silver, Gold & Platinum

And each of those subcategories hold some values(from 001 to 021)

Now, the main part of the question. I want above array to be converted to tree view.

I already have HTML, JS & CSS code on how the output should be.

The values are hard coded.

Check below snippet

$(function () {
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});

/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #000000;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}

            Fruit

                    Orange

                            001

                            012

                            016

                    Mango

                            011

                    Apple

                            013

                            004

                            010

            Color

                    Silver

                            014

                            015

                    Orange

                            005

                            016

                    Red

                            003

                            017

                            018

            Jewellery

                    Bronze

                            019

                            020

                    Silver

                            007

                    Gold

                            002

                            008

                    Platinum

                            009

                            021

The above values are hard coded, I need something which would convert the output of array to above HTML.

This is what I have tried so far. It does not loop subcategories(Incorrect Output)

Also, not sure how to show values

var globalResFiltered = [];
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"001"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"012"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Orange",Value:"006"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Mango",Value:"011"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"013"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"004"});
    globalResFiltered.push({Category:"Fruit",Subcategory:"Apple",Value:"010"});

    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"014"});
    globalResFiltered.push({Category:"Color",Subcategory:"Silver",Value:"015"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"005"});
    globalResFiltered.push({Category:"Color",Subcategory:"Orange",Value:"016"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"003"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"017"});
    globalResFiltered.push({Category:"Color",Subcategory:"Red",Value:"018"});

    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"019"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Bronze",Value:"020"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Silver",Value:"007"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"002"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Gold",Value:"008"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"009"});
    globalResFiltered.push({Category:"Jewellery",Subcategory:"Platinum",Value:"021"});

    var tempCat = "";
    var tempSubCat = "";

    $(globalResFiltered).each(function(i,v){

        if(i==0 || i==1 || i==2){debugger;}
        if(tempCat != v.Category)
        {
            $("#myTree").append("

"+v.Category+"

");
            $(".c_"+v.Category).after("

"+v.Subcategory+"

");
        }
        else
        {
            $("#x_0"+v.Category+"_"+v.Subcategory).after("
"+v.Subcategory+"
");
        }
        tempCat = v.Category;

    });

$(function () {
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});

/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #5a8dee;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}

Incorrect, it only shows one subcategory

I have tried checking below reference, but in vain.

https://www.jqueryscript.net/table/jQuery-Plugin-For-Displaying-A-Tree-Of-Data-In-A-Table-treetable.html
https://www.jqueryscript.net/demo/simple-tree-table/

Thanks in advance for your help '

Body:
I would do this in two steps:

Convert the data structure to a hierarchical one: toHierarchy

Turn that hierarchy to a hierarchy of DOM elements: createList

Here is the code:

function toHierarchy(data, ...fields) {
    let map = {};
    for (let item of data) {
        let node = map;
        for (let field of fields) {
            let value = item[field];
            node = (node[value] ??= {});
        }
    }
    return map;
}

function createList(hierarchy) {
    return $("<ul>").css({display: "none"}).append(
        Object.entries(hierarchy).flatMap(([value, children]) => $("<li>").append(
             $("<a>", { href: "javascript:void(0);" }).text(value),
             createList(children)
        ))
    );
}

// Your sample data:
const globalResFiltered = [{Category:"Fruit",Subcategory:"Orange",Value:"001"},{Category:"Fruit",Subcategory:"Orange",Value:"012"},{Category:"Fruit",Subcategory:"Orange",Value:"006"},{Category:"Fruit",Subcategory:"Mango",Value:"011"},{Category:"Fruit",Subcategory:"Apple",Value:"013"},{Category:"Fruit",Subcategory:"Apple",Value:"004"},{Category:"Fruit",Subcategory:"Apple",Value:"010"},{Category:"Color",Subcategory:"Silver",Value:"014"},{Category:"Color",Subcategory:"Silver",Value:"015"},{Category:"Color",Subcategory:"Orange",Value:"005"},{Category:"Color",Subcategory:"Orange",Value:"016"},{Category:"Color",Subcategory:"Red",Value:"003"},{Category:"Color",Subcategory:"Red",Value:"017"},{Category:"Color",Subcategory:"Red",Value:"018"},{Category:"Jewellery",Subcategory:"Bronze",Value:"019"},{Category:"Jewellery",Subcategory:"Bronze",Value:"020"},{Category:"Jewellery",Subcategory:"Silver",Value:"007"},{Category:"Jewellery",Subcategory:"Gold",Value:"002"},{Category:"Jewellery",Subcategory:"Gold",Value:"008"},{Category:"Jewellery",Subcategory:"Platinum",Value:"009"},{Category:"Jewellery",Subcategory:"Platinum",Value:"021"}];

// Convert data structure to a hierarchical one:
const hierarchy = toHierarchy(globalResFiltered, "Category", "Subcategory", "Value");

$(function () {
    // Added this line:
    $(".vertical-tree").empty().append(createList(hierarchy));
    $('.vertical-tree ul').hide();
    $('.vertical-tree>ul').show();
    $('.vertical-tree ul.active').show();
    $('.vertical-tree li').on('click', function (e) {
        var children = $(this).find('> ul');
        if (children.is(":visible")) children.hide('fast').removeClass('active');
        else children.show('fast').addClass('active');
        e.stopPropagation();
    });
});

/*-------------vertical-tree-view------------*/
.vertical-tree{
    padding-top: 40px;
    padding-bottom: 40px;
}
.vertical-tree ul{
    padding-left: 30px;
}
.vertical-tree li {
    margin: 0px 0;
    list-style-type: none;
    position: relative;
    padding: 20px 5px 0px 5px;
}
.vertical-tree li::before{
    content: '';
    position: absolute;
    top: 0;
    width: 1px;
    height: 100%;
    right: auto;
    left: -20px;
    border-left: 2px solid #ccc;
    bottom: 50px;
}
.vertical-tree li::after{
    content: '';
    position: absolute;
    top: 34px;
    width: 25px;
    height: 20px;
    right: auto;
    left: -20px;
    border-top: 2px solid #ccc;
}
.vertical-tree li a{
    display: inline-block;
    padding: 8px 30px;
    text-decoration: none;
    background-color: #e1eafc;
    color: #000000;
    border: 1px solid #5285eb;
    font-size: 13px;
    border-radius: 4px;
}
.vertical-tree > ul > li::before,
.vertical-tree > ul > li::after{
    border: 0;
}
.vertical-tree li:last-child::before{
        height: 34px;
}
.vertical-tree li a:hover,
.vertical-tree li a:hover+ul li a {
    background-color: #5a8dee;
    color: #fff;
    border: 1px solid #5a8dee;
}
.vertical-tree li a:hover+ul li::after,
.vertical-tree li a:hover+ul li::before,
.vertical-tree li a:hover+ul::before,
.vertical-tree li a:hover+ul ul::before{
    border-color:  #fbba00;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv">
    <div class="vertical-tree"></div>
</div>


问:
Creating a list from a text file
I have a text file called my_urls.txt that has 3 URLs:

```<code>example1.com
example2.com
example3.com
</code>```
```<code>with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
    print(urls_list)

['example1.com', '']
</code>```

I wonder why urls_list is not giving me ['example1.com', 'example2.com', 'example3.com']

答:
readline reads a single line so it cannot give you anything past the first line. read could read the whole file and you will then be able to split the result on newlines.

But IMHO, as a file object is an iterable of lines, the Pythonic way would be to use a comprehension:

```<code>with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = [line.rstrip() for line in urlFile]
</code>```

Title: Creating a list from a text file

Body:
I have a text file called my_urls.txt that has 3 URLs:

example1.com
example2.com
example3.com

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = urlFile.readline().split('\n')
    print(urls_list)

['example1.com', '']

I wonder why urls_list is not giving me ['example1.com', 'example2.com', 'example3.com']

Body:
readline reads a single line so it cannot give you anything past the first line. read could read the whole file and you will then be able to split the result on newlines.

But IMHO, as a file object is an iterable of lines, the Pythonic way would be to use a comprehension:

with open("../test_data/my_urls.txt", "r") as urlFile:
    urls_list = [line.rstrip() for line in urlFile]


问:
How to resample including the last value of the previous resampled set?
I need to compute different measures of performance from prices at different time resolutions e.g., yearly or monthly. An ideal approach is to use Pandas' resample but I also need a way to pass the last value of the previous resampling set to the next i.e. due to intro-resampling set return calculations. This is apparently not supported by doing resample('M'):

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(1, 61), index=pd.date_range('2021-12-31', '2022-02-28'), columns=['price'])
print(df)
df.resample('M').apply(lambda x: (x[0], x[-1]))
</code>```

I get the following result:

```<code>            price
2021-12-31  (1, 1)
2022-01-31  (2, 32)
2022-02-28  (33, 60)
</code>```

I would like to instead get the following where the first element of the resampling set includes the last element from the previous resampling set:

```<code>            price
2021-12-31  (1, 1)
2022-01-31  (1, 32)
2022-02-28  (32, 60)
</code>```

答:
You cannot easily access the other groups from within a group.

But an easy way is to shift and concat the output:

```<code>d = df.resample('M').last()

pd.concat([d.shift().bfill(), d], axis=1).astype(int).apply(tuple, axis=1)
</code>```

output:

```<code>2021-12-31      (1, 1)
2022-01-31     (1, 32)
2022-02-28    (32, 60)
Freq: M, dtype: object
</code>```

Or if you have multiple columns:

```<code>(pd.concat([d.shift().bfill(), d], axis=1).astype(int)
   .groupby(level=0, axis=1, sort=False)
   .apply(lambda d: d.apply(tuple, axis=1))
 )
</code>```

output:

```<code>               price
2021-12-31    (1, 1)
2022-01-31   (1, 32)
2022-02-28  (32, 60)
</code>```

with another example:

```<code>df = pd.DataFrame({'price': np.arange(1, 61), 'other': np.arange(1, 61)*10},
                  index=pd.date_range('2021-12-31', '2022-02-28'),
                 )

s = df.resample('M').last()

(pd.concat([s.shift().bfill(), s], axis=1).astype(int)
   .groupby(level=0, axis=1, sort=False)
   .apply(lambda d: d.apply(tuple, axis=1))
 )

#                price       other
# 2021-12-31    (1, 1)    (10, 10)
# 2022-01-31   (1, 32)   (10, 320)
# 2022-02-28  (32, 60)  (320, 600)
</code>```

Body:
I need to compute different measures of performance from prices at different time resolutions e.g., yearly or monthly. An ideal approach is to use Pandas' resample but I also need a way to pass the last value of the previous resampling set to the next i.e. due to intro-resampling set return calculations. This is apparently not supported by doing resample('M'):

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(1, 61), index=pd.date_range('2021-12-31', '2022-02-28'), columns=['price'])
print(df)
df.resample('M').apply(lambda x: (x[0], x[-1]))

I get the following result:

            price
2021-12-31  (1, 1)
2022-01-31  (2, 32)
2022-02-28  (33, 60)

I would like to instead get the following where the first element of the resampling set includes the last element from the previous resampling set:

            price
2021-12-31  (1, 1)
2022-01-31  (1, 32)
2022-02-28  (32, 60)

Body:
You cannot easily access the other groups from within a group.

But an easy way is to shift and concat the output:

d = df.resample('M').last()

pd.concat([d.shift().bfill(), d], axis=1).astype(int).apply(tuple, axis=1)

output:

2021-12-31      (1, 1)
2022-01-31     (1, 32)
2022-02-28    (32, 60)
Freq: M, dtype: object

Or if you have multiple columns:

(pd.concat([d.shift().bfill(), d], axis=1).astype(int)
   .groupby(level=0, axis=1, sort=False)
   .apply(lambda d: d.apply(tuple, axis=1))
 )

output:

               price
2021-12-31    (1, 1)
2022-01-31   (1, 32)
2022-02-28  (32, 60)

with another example:

df = pd.DataFrame({'price': np.arange(1, 61), 'other': np.arange(1, 61)*10},
                  index=pd.date_range('2021-12-31', '2022-02-28'),
                 )

s = df.resample('M').last()

(pd.concat([s.shift().bfill(), s], axis=1).astype(int)
   .groupby(level=0, axis=1, sort=False)
   .apply(lambda d: d.apply(tuple, axis=1))
 )

#                price       other
# 2021-12-31    (1, 1)    (10, 10)
# 2022-01-31   (1, 32)   (10, 320)
# 2022-02-28  (32, 60)  (320, 600)


问:
Python requests returns 404 error status from today on amazon "sold by" page
There

https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link

I just can access on browser as well, but python requests returns 404 error status.

Until yesterday, this page worked as well with python requests. but from today, it does not work for me and it returns 404 error status.

import requests

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
    headers=headers
)
print(response.status_code) # 404
```

I really will appreciate if I can get any help from you.

Regards.

答: I suggest you add a referer url in header and generally I don't think Amazon allow scraping but use selenium if you want to scrape it easily (sure it may be overkill) but has more customization

Body:
There

https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link

I just can access on browser as well, but python requests returns 404 error status.

Until yesterday, this page worked as well with python requests. but from today, it does not work for me and it returns 404 error status.

import requests

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
    headers=headers
)
print(response.status_code) # 404

I really will appreciate if I can get any help from you.

Regards.


问:
Module 'path_provider' not found
I have used several times the Xcode simulator for my flutter app.
One time I tried to change the simulator to iPhone 11 Pro (don't know if it did or did not cause the problem) but since then:

I get the error Module 'path_provider' not found.

It seems that each time when I double click on the Runner.xcworkspace file, it opens the project file instead. I'm new to Xcode so not quite sure about that but I attached a screenshot.

Things I've tried:

updated according to the instructions in the warnings (which can be seen in the screenshot).

deleted all Xcode cache with Reset Xcode

deleted the android studio project and popped it again from git.

flutter clean + removed all the pod files + pod install from android studio terminal.
according to the explanations here: reinstall pod

What else can I do?

答:
I had the same problem that was caused by the linker.
I solved it as follows:
runner->build setting->other linker flags, and delete path_provider</p>

Title: Module 'path_provider' not found


问:
Convert 16-digit datetime string to datetime with microseconds
I am trying to convert a 16-digit datetime string (with milliseconds) in SQL Server to an actual datetime along with the milliseconds. An example would be changing a record like this, 2022020804180454, to read a US DateTime of 02/08/2022 04:18:04.54.

How do I go about doing this? Google/Bing searches speak to having the date with a midnight timestamp

```<code>CONVERT(datetime, CAST('2022020804180454' AS CHAR(8)), 101)
</code>```

which is not what I am after.

Any help or being pointed in the right direction would be helpful.

答:
You can use the handy DATETIMEFROMPARTS:

```<code>DECLARE @s nvarchar(16) = '2022020804180454';

SELECT DATETIMEFROMPARTS(LEFT(@s,4), --year
                         SUBSTRING(@s,5,2), --month
                         SUBSTRING(@s,7,2), --day
                         SUBSTRING(@s,9,2), --hour
                         SUBSTRING(@s,11,2), --minute
                         SUBSTRING(@s,13,2), --second
                         SUBSTRING(@s,15,2)*10 --millisecond
                         )
</code>```

Body:
I am trying to convert a 16-digit datetime string (with milliseconds) in SQL Server to an actual datetime along with the milliseconds. An example would be changing a record like this, 2022020804180454, to read a US DateTime of 02/08/2022 04:18:04.54.

How do I go about doing this? Google/Bing searches speak to having the date with a midnight timestamp

CONVERT(datetime, CAST('2022020804180454' AS CHAR(8)), 101)

which is not what I am after.

Any help or being pointed in the right direction would be helpful.

Body:
You can use the handy DATETIMEFROMPARTS:

DECLARE @s nvarchar(16) = '2022020804180454';

SELECT DATETIMEFROMPARTS(LEFT(@s,4), --year
                         SUBSTRING(@s,5,2), --month
                         SUBSTRING(@s,7,2), --day
                         SUBSTRING(@s,9,2), --hour
                         SUBSTRING(@s,11,2), --minute
                         SUBSTRING(@s,13,2), --second
                         SUBSTRING(@s,15,2)*10 --millisecond
                         )


问:
Increment Multiple Struct Variables using ForEach + Stepper SwiftUI
I have a list of toppings to include on a pizza. Each item in the list is a struct:

```<code>struct Topping: Identifiable {
    let name: String
    let price: Double
    @State var amount: Int
    let id = UUID()
}
</code>```

The list is created in a Class in file MenuDataService.swift, is defined using static let, then initialized in a ViewModel file:

```<code>//FILE MenuDataService.swift
Class MenuDataService {
    static let toppingsList: [Topping] = [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Sauce", price: 3.00, amount: 0)]
}

//FILE MenuViewModel.swift
Class MenuViewModel: ObservableObject {
    @Published var toppingsList: [Topping]
    init() {
        toppingsList = MenuDataService.toppingsList
        self.toppingsList = toppingsList
    }
}
</code>```

Inside the view im accessing the object using .environmentobject in the view. I'm iterating over the list of toppings using a ForEach loop, displaying the name and amount of toppings, followed by a stepper which should increment or decrement the 'amount' variable.

```<code>@EnvironmentObject private var vm = MenuViewModel
let toppingsList: [Topping]
var body: some View {
    VStack {
        ForEach(toppingsList, id: \.id) { topping in
            Stepper("\(topping.name): \(topping.amount)", value: topping.$amount)
        }
    }
}

struct ExtraToppingsView_Previews: PreviewProvider {
    static var previews: some View {
        ExtraToppingsView(toppingsList: MenuViewModel.init().toppingsList)
        .environmentObject(MenuViewModel())
    }
}
</code>```

I get this error in the Stepper() Line of code: Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.

When clicking the '+' in the 'Cheese' stepper, it should increment the variable, and change the title to 'Cheese: 1', but the title stays the same. I'm assuming this has something to do with '@State var amount' variable, or some binding to the '$amount' variable in the stepper. If someone can point me in the right direction, it would be much appreciated.

答:
Most of your code is close -- there are just subtle differences required to make it work. See inline comments for my changes:

```<code>struct Topping: Identifiable {
    let id = UUID()
    let name: String
    let price: Double
    var amount: Int //don't include `@State` in non-Views
}

//no changes
class MenuDataService {
    static let toppingsList: [Topping] = [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Sauce", price: 3.00, amount: 0)]
}

class MenuViewModel: ObservableObject {
    @Published var toppingsList: [Topping]
    init() {
        toppingsList = MenuDataService.toppingsList
        //remove unnecessary duplicate assignment
    }
}

//This is the parent view -- may be called something different in your code
struct ContentView : View {
    @StateObject private var vm = MenuViewModel() //declare as @StateObject

    var body: some View {
        ExtraToppingsView()
            .environmentObject(vm) //pass the environment object
    }
}

struct ExtraToppingsView : View {
    @EnvironmentObject private var vm : MenuViewModel //no need to take the toppingsList parameter separately -- just use the environment object

    var body: some View {
        VStack {
            ForEach($vm.toppingsList) { $topping in //use element binding to get a mutable binding to each item
                Stepper("\(topping.name): \(topping.amount)", value: $topping.amount) //see change of the position of the $ character
            }
        }
    }
}

struct ExtraToppingsView_Previews: PreviewProvider {
    static var previews: some View {
        ExtraToppingsView()
            .environmentObject(MenuViewModel())
    }
}
</code>```

For more info on element binding: https://www.swiftbysundell.com/articles/bindable-swiftui-list-elements/

Body:
I have a list of toppings to include on a pizza. Each item in the list is a struct:

struct Topping: Identifiable {
    let name: String
    let price: Double
    @State var amount: Int
    let id = UUID()
}

The list is created in a Class in file MenuDataService.swift, is defined using static let, then initialized in a ViewModel file:

//FILE MenuDataService.swift
Class MenuDataService {
    static let toppingsList: [Topping] = [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Sauce", price: 3.00, amount: 0)]
}

//FILE MenuViewModel.swift
Class MenuViewModel: ObservableObject {
    @Published var toppingsList: [Topping]
    init() {
        toppingsList = MenuDataService.toppingsList
        self.toppingsList = toppingsList
    }
}

Inside the view im accessing the object using .environmentobject in the view. I'm iterating over the list of toppings using a ForEach loop, displaying the name and amount of toppings, followed by a stepper which should increment or decrement the 'amount' variable.

@EnvironmentObject private var vm = MenuViewModel
let toppingsList: [Topping]
var body: some View {
    VStack {
        ForEach(toppingsList, id: \.id) { topping in
            Stepper("\(topping.name): \(topping.amount)", value: topping.$amount)
        }
    }
}

struct ExtraToppingsView_Previews: PreviewProvider {
    static var previews: some View {
        ExtraToppingsView(toppingsList: MenuViewModel.init().toppingsList)
        .environmentObject(MenuViewModel())
    }
}

I get this error in the Stepper() Line of code: Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.

When clicking the '+' in the 'Cheese' stepper, it should increment the variable, and change the title to 'Cheese: 1', but the title stays the same. I'm assuming this has something to do with '@State var amount' variable, or some binding to the '$amount' variable in the stepper. If someone can point me in the right direction, it would be much appreciated.

Body:
Most of your code is close -- there are just subtle differences required to make it work. See inline comments for my changes:

struct Topping: Identifiable {
    let id = UUID()
    let name: String
    let price: Double
    var amount: Int //don't include `@State` in non-Views
}

//no changes
class MenuDataService {
    static let toppingsList: [Topping] = [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Sauce", price: 3.00, amount: 0)]
}

class MenuViewModel: ObservableObject {
    @Published var toppingsList: [Topping]
    init() {
        toppingsList = MenuDataService.toppingsList
        //remove unnecessary duplicate assignment
    }
}

//This is the parent view -- may be called something different in your code
struct ContentView : View {
    @StateObject private var vm = MenuViewModel() //declare as @StateObject

    var body: some View {
        ExtraToppingsView()
            .environmentObject(vm) //pass the environment object
    }
}

struct ExtraToppingsView : View {
    @EnvironmentObject private var vm : MenuViewModel //no need to take the toppingsList parameter separately -- just use the environment object

    var body: some View {
        VStack {
            ForEach($vm.toppingsList) { $topping in //use element binding to get a mutable binding to each item
                Stepper("\(topping.name): \(topping.amount)", value: $topping.amount) //see change of the position of the $ character
            }
        }
    }
}

struct ExtraToppingsView_Previews: PreviewProvider {
    static var previews: some View {
        ExtraToppingsView()
            .environmentObject(MenuViewModel())
    }
}

For more info on element binding: https://www.swiftbysundell.com/articles/bindable-swiftui-list-elements/


问:
Tomcat 404 when deploying a war file which otherwise works in IntelliJ
I've been trying to create a WAR file and deploy it on a Tomcat server. If I run the WAR file WITHIN IntelliJ on a Tomcat server, it works.

To make things as simple as possible, I followed this tutorial (https://www.baeldung.com/spring-boot-war-tomcat-deploy) and even that one doesnt work. I still get the same 404 error when deploying the war file. The tutorial application works within IntelliJ just like my main project does. I am fairly new and have tried plenty of things to no avail:

Tried to either set the line war in the pom.xml file, clean maven and use the resulting war file from the target folder for the Tomcat server deployment or explicitly built the war artifact following the official website ( https://www.jetbrains.com/help/idea/deploying-a-web-app-into-an-app-server-container.html)
and tried to run that.

Tried different URLs but all of them throw the 404 error (except for the default Tomcat pages like /manager)

Setting a different path in the application.properties file (server.servlet.context-path=/test)

Tried a different computer

The error:

What newbie mistake might I be making?

My pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE

    com.example
    tomcat-test2
    0.0.1-SNAPSHOT
    war
    tomcat-test2
    Demo project for Spring Boot

```<code><properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

My Controller:

```<code>@RestController
</code>```

public class TomcatController {

```<code>@GetMapping("/hello")
public Collection<String> sayHello() {
    return IntStream.range(0, 10)
            .mapToObj(i -> "Hello number " + i)
            .collect(Collectors.toList());
}
</code>```

}

The Main Application:

@SpringBootApplication
public class TomcatTest2Application extends SpringBootServletInitializer {

```<code>public static void main(String[] args) {
    SpringApplication.run(TomcatTest2Application.class, args);
}
</code>```

}

Thanks in advance,
Alex

答: I solved a similar problem by changing the tomcat version. My war file was getting 404 on Tomcat 10, I got rid of the problem using Tomcat 9.</p>

Body:
I've been trying to create a WAR file and deploy it on a Tomcat server. If I run the WAR file WITHIN IntelliJ on a Tomcat server, it works.

To make things as simple as possible, I followed this tutorial (https://www.baeldung.com/spring-boot-war-tomcat-deploy) and even that one doesnt work. I still get the same 404 error when deploying the war file. The tutorial application works within IntelliJ just like my main project does. I am fairly new and have tried plenty of things to no avail:

Tried to either set the line war in the pom.xml file, clean maven and use the resulting war file from the target folder for the Tomcat server deployment or explicitly built the war artifact following the official website ( https://www.jetbrains.com/help/idea/deploying-a-web-app-into-an-app-server-container.html)
and tried to run that.

Tried different URLs but all of them throw the 404 error (except for the default Tomcat pages like /manager)

Setting a different path in the application.properties file (server.servlet.context-path=/test)

Tried a different computer

The error:

What newbie mistake might I be making?

My pom:

<?xml version="1.0" encoding="UTF-8"?>

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE

    com.example
    tomcat-test2
    0.0.1-SNAPSHOT
    war
    tomcat-test2
    Demo project for Spring Boot

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

My Controller:

@RestController

public class TomcatController {

@GetMapping("/hello")
public Collection<String> sayHello() {
    return IntStream.range(0, 10)
            .mapToObj(i -> "Hello number " + i)
            .collect(Collectors.toList());
}

}

The Main Application:

@SpringBootApplication
public class TomcatTest2Application extends SpringBootServletInitializer {

public static void main(String[] args) {
    SpringApplication.run(TomcatTest2Application.class, args);
}

}

Thanks in advance,
Alex


问:
Programmatically create a user in Cognito with email and password (permanent password)
I currently have some code that creates a new user with temporary password. I get an email with a temporary password to my account, but instead I want to get a verification code. to confirm my email.

here is the code:

```<code>  public static void registerUser(String email) {
    String userPoolId = "eu-central-1_xxx";
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();

    String password = "123456789";

    try {
      AdminCreateUserRequest userRequest =
              new AdminCreateUserRequest().withUserPoolId(userPoolId).withUsername(email);

      cognitoClient.adminCreateUser(userRequest);

      AdminSetUserPasswordRequest adminSetUserPasswordRequest =
              new AdminSetUserPasswordRequest().withUsername(email)
                      .withUserPoolId(userPoolId).withPassword(password).withPermanent(true);

      cognitoClient.adminSetUserPassword(adminSetUserPasswordRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }

  }
</code>```

Seems like .withPermanent(true) doesn't work.

Also currently I am creating a user with one call and setting the password (AdminSetUserPasswordRequest()) with another. Is there a simpler way of doing it?

答:
I was surprised how long it took me to actually find a solution to something quite trivial as creating a user without a temporary password.

```<code>public static void signUpUser(String email, String password) {
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();
    try {
      SignUpRequest signUpRequest = new SignUpRequest().withUsername(email).withPassword(password).withClientId("xxx");
      cognitoClient.signUp(signUpRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }
 }

</code>```

So the difference is stead instead of .adminCreateUser I'm using .signUp.

In this case you will need your clientId (which is not your pool id!) - .withClientId("xxx").

Tip: switch to the old view of Cognito console to find the client id faster - if will be under App Clients tab on the left side menu.

After sign up the user will be not confirmed and not verified and will receive an email with the code to verify email (not temporary password).

btw, my verification email landed in spam - so look there if you got no email.

Body:
I currently have some code that creates a new user with temporary password. I get an email with a temporary password to my account, but instead I want to get a verification code. to confirm my email.

here is the code:

  public static void registerUser(String email) {
    String userPoolId = "eu-central-1_xxx";
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();

    String password = "123456789";

    try {
      AdminCreateUserRequest userRequest =
              new AdminCreateUserRequest().withUserPoolId(userPoolId).withUsername(email);

      cognitoClient.adminCreateUser(userRequest);

      AdminSetUserPasswordRequest adminSetUserPasswordRequest =
              new AdminSetUserPasswordRequest().withUsername(email)
                      .withUserPoolId(userPoolId).withPassword(password).withPermanent(true);

      cognitoClient.adminSetUserPassword(adminSetUserPasswordRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }

  }

Seems like .withPermanent(true) doesn't work.

Also currently I am creating a user with one call and setting the password (AdminSetUserPasswordRequest()) with another. Is there a simpler way of doing it?

Body:
I was surprised how long it took me to actually find a solution to something quite trivial as creating a user without a temporary password.

public static void signUpUser(String email, String password) {
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();
    try {
      SignUpRequest signUpRequest = new SignUpRequest().withUsername(email).withPassword(password).withClientId("xxx");
      cognitoClient.signUp(signUpRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }
 }

So the difference is stead instead of .adminCreateUser I'm using .signUp.

In this case you will need your clientId (which is not your pool id!) - .withClientId("xxx").

Tip: switch to the old view of Cognito console to find the client id faster - if will be under App Clients tab on the left side menu.

After sign up the user will be not confirmed and not verified and will receive an email with the code to verify email (not temporary password).

btw, my verification email landed in spam - so look there if you got no email.


问:
How to dynamically set the HTTP Referer header in JMeter?
Hopefully this is a common issue with JMeter testing.

I setup a Proxy Server via JMeter to 'record' a test case in our DEVELOPMENT environment.  That worked fine and I setup some 'HTTP Request Defaults' to globally set the default 'Server Name or IP' and 'Protocol'.

Now that the tests are completed on DEV, we have moved our code to our QA servers for more testing -- and I thought I would simply have to change the 'Server Name' in my defaults and then run the tests.

One thing I noticed is that for each sampler in my test case, other headers are present in the 'HTTP Header Manager' for that specific sampler -- like User-Agent, Cache-Control, etc.  The Referer header is the only one that concerns me because it still is 'hard coded' to be the DEV server.

Is there a way to set this dynamically -- so that I can run this recorded test in multiple environments?  How is this normally handled?

Any help is appreciated!  Thanks.

jg

答:
Set JMeter variable named server at root of test plan

Use that variable in HTTP request defaults Server Name field

Use that variable in HTTP Header Manager Referer field setting

Also you may use JMeter property instead of variable if you want to pass it from command line to non-GUI JMeter run


问:
How boofuzz detect crashes and log crashed test cases
We are using boofuzz for fuzzing remote service with tcp protocol. The fuzzer script is as follows.

session = Session(target = Target(connection = SocketConnection(host, port, proto='tcp')))
s_initialize("Test")
s_string("Fuzz", fuzzable = True)
session.connect(s_get("Test"))
session.fuzz()
```
<p>After a while, we noticed the remote service is crashed but the fuzzer just repeatly tried to restart. The fuzzer did not detect the remote service is closed and the crashed test case is not stored.</p>
```[2022-02-02 04:18:42,231]    Test Step: Restarting target
[2022-02-02 04:18:42,231]     Info: Restarting target process using CallbackMonitor
[2022-02-02 04:18:42,231]    Test Step: Cleaning up connections from callbacks
[2022-02-02 04:18:42,231]     Info: Closing target connection...
[2022-02-02 04:18:42,231]     Info: Connection closed.
[2022-02-02 04:18:42,231]     Info: No reset handler available... sleeping for 5 seconds
[2022-02-02 04:18:47,236]     Info: Opening target connection (xxx)...
[2022-02-02 04:18:47,237]     Info: Cannot connect to target; retrying. Note: This likely indicates a failure caused by the previous test case, or a target that is slow to restart.
[2022-02-02 04:18:47,237]    Test Step: Restarting target
[2022-02-02 04:18:47,237]     Info: Restarting target process using CallbackMonitor
[2022-02-02 04:18:47,237]    Test Step: Cleaning up connections from callbacks
[2022-02-02 04:18:47,237]     Info: Closing target connection...
[2022-02-02 04:18:47,237]     Info: Connection closed.
[2022-02-02 04:18:47,237]     Info: No reset handler available... sleeping for 5 seconds
[2022-02-02 04:18:52,243]     Info: Opening target connection (xxx)...
[2022-02-02 04:18:52,244]     Info: Cannot connect to target; retrying. Note: This likely indicates a failure caused by the previous test case, or a target that is slow to restart.
```

How can we customize the boofuzz script so that:

we can detect the remote service is closed (e.g., try tcp connect)?

we can store the untruncated crashed test case to disk?

答:
If you are not using the monitors, you could add a post_test_case_callbacks that check if the server is alive. This function will be called after each test case.

post_test_case_callbacks (list of method) – The registered method will
be called after each fuzz test case. Default None.

e.g.

```<code>logger = FuzzLoggerText()
def target_alive(target, fuzz_data_logger, session, sock, *args, **kwargs):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((host, port))
        logger.log_pass(description="alive")
    except ConnectionRefusedError:
        logger.log_fail(description="Server down")

session = Session(target=Target(SocketConnection(host, int(port))), post_test_case_callbacks=[target_alive])
</code>```

Body:
We are using boofuzz for fuzzing remote service with tcp protocol. The fuzzer script is as follows.

session = Session(target = Target(connection = SocketConnection(host, port, proto='tcp')))
s_initialize("Test")
s_string("Fuzz", fuzzable = True)
session.connect(s_get("Test"))
session.fuzz()

After a while, we noticed the remote service is crashed but the fuzzer just repeatly tried to restart. The fuzzer did not detect the remote service is closed and the crashed test case is not stored.

[2022-02-02 04:18:42,231]    Test Step: Restarting target
[2022-02-02 04:18:42,231]     Info: Restarting target process using CallbackMonitor
[2022-02-02 04:18:42,231]    Test Step: Cleaning up connections from callbacks
[2022-02-02 04:18:42,231]     Info: Closing target connection...
[2022-02-02 04:18:42,231]     Info: Connection closed.
[2022-02-02 04:18:42,231]     Info: No reset handler available... sleeping for 5 seconds
[2022-02-02 04:18:47,236]     Info: Opening target connection (xxx)...
[2022-02-02 04:18:47,237]     Info: Cannot connect to target; retrying. Note: This likely indicates a failure caused by the previous test case, or a target that is slow to restart.
[2022-02-02 04:18:47,237]    Test Step: Restarting target
[2022-02-02 04:18:47,237]     Info: Restarting target process using CallbackMonitor
[2022-02-02 04:18:47,237]    Test Step: Cleaning up connections from callbacks
[2022-02-02 04:18:47,237]     Info: Closing target connection...
[2022-02-02 04:18:47,237]     Info: Connection closed.
[2022-02-02 04:18:47,237]     Info: No reset handler available... sleeping for 5 seconds
[2022-02-02 04:18:52,243]     Info: Opening target connection (xxx)...
[2022-02-02 04:18:52,244]     Info: Cannot connect to target; retrying. Note: This likely indicates a failure caused by the previous test case, or a target that is slow to restart.

How can we customize the boofuzz script so that:

we can detect the remote service is closed (e.g., try tcp connect)?

we can store the untruncated crashed test case to disk?

Body:
If you are not using the monitors, you could add a post_test_case_callbacks that check if the server is alive. This function will be called after each test case.

post_test_case_callbacks (list of method) – The registered method will
be called after each fuzz test case. Default None.

e.g.

logger = FuzzLoggerText()
def target_alive(target, fuzz_data_logger, session, sock, *args, **kwargs):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((host, port))
        logger.log_pass(description="alive")
    except ConnectionRefusedError:
        logger.log_fail(description="Server down")

session = Session(target=Target(SocketConnection(host, int(port))), post_test_case_callbacks=[target_alive])


问:
Error when creating a network namespace inside a docker container. error: mount --make-shared /run/netns failed: Permission denied
I'm getting an error when creating a network namespace inside a docker container saying permission denied.

```<code>command
ip netns add red
</code>```

```<code>error
mount --make-shared /run/netns failed: Permission denied
</code>```

I am running an image ubuntu:20.10 and tried by adding specific capabilities to the container and it did not help.

```<code>docker run -it --rm --name=ubuntu --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN ubuntu:20.10
apt-get update && apt-get install -y net-tools && apt-get install -y iproute2
</code>```

Even after adding all capabilities issue remain same.

```<code>docker run -it --rm --name=ubuntu --cap-add ALL ubuntu:20.10
</code>```

答:
The other answer suggests adding --privileged, but note that adding --privileged effectively removes all security features. If you are uncomfortable with this, you might prefer an approach that gives the container access only to what it needs.

The root cause is that Docker's default apparmor profile contains the rule deny mount which prevents mount from working inside Docker containers, which is what is causing the error message mount --make-shared /run/netns failed: Permission denied.

You can confirm this by adding --security-opt apparmor=unconfined to your command, which disables apparmor, and notice that the mount command succeeds.

docker run -it --rm --name=ubuntu \
  --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN \
  --security-opt apparmor=unconfined \
  ubuntu
apt-get update && apt-get install -y net-tools iproute2
ip netns add red # succeeds
```

If you don't want to fully opt out of apparmor, you can create a custom apparmor profile, then load it with apparmor_parser -r -W path/to/your/profile and then load it with --security-opt apparmor=your-profile-name. You can create a custom apparmor profile by copying Docker's template and then tweaking it to suit your needs.

At the time of writing, Docker does not have an easy way to show the apparmor profile it is currently using, but you can look at the source template and then expand the template manually (by following the template logic).

See https://docs.docker.com/engine/security/apparmor/

Body:
I'm getting an error when creating a network namespace inside a docker container saying permission denied.

command
ip netns add red

error
mount --make-shared /run/netns failed: Permission denied

I am running an image ubuntu:20.10 and tried by adding specific capabilities to the container and it did not help.

docker run -it --rm --name=ubuntu --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN ubuntu:20.10
apt-get update && apt-get install -y net-tools && apt-get install -y iproute2

Even after adding all capabilities issue remain same.

docker run -it --rm --name=ubuntu --cap-add ALL ubuntu:20.10

Body:
The other answer suggests adding --privileged, but note that adding --privileged effectively removes all security features. If you are uncomfortable with this, you might prefer an approach that gives the container access only to what it needs.

The root cause is that Docker's default apparmor profile contains the rule deny mount which prevents mount from working inside Docker containers, which is what is causing the error message mount --make-shared /run/netns failed: Permission denied.

You can confirm this by adding --security-opt apparmor=unconfined to your command, which disables apparmor, and notice that the mount command succeeds.

docker run -it --rm --name=ubuntu \
  --cap-add CAP_SYS_ADMIN --cap-add NET_ADMIN \
  --security-opt apparmor=unconfined \
  ubuntu
apt-get update && apt-get install -y net-tools iproute2
ip netns add red # succeeds

If you don't want to fully opt out of apparmor, you can create a custom apparmor profile, then load it with apparmor_parser -r -W path/to/your/profile and then load it with --security-opt apparmor=your-profile-name. You can create a custom apparmor profile by copying Docker's template and then tweaking it to suit your needs.

At the time of writing, Docker does not have an easy way to show the apparmor profile it is currently using, but you can look at the source template and then expand the template manually (by following the template logic).

See https://docs.docker.com/engine/security/apparmor/