问:
Counting based on partial strings in R
I'm working with some survey data collected from a google form. One of the questions allowed for respondents to provide multiple answers:

Data:

```<code>id_number <- c("101", "102", "103", "104", "105", "106")

why_join_program <- c("college assistance",
                     "college assistance, fasfa support",
                     "fasfa support, employment support",
                     "college assistance, fasfa support, employment support",
                     "college assistance, employment support",
                     "fasfa support")

df <- data.frame(id_number, why_join_program)
</code>```

I have two questions:

I want to count how many responses include a single answer (i.e., how many respondents identified "college support"?

Can you provide a good way to organize this into a table? group_by and summarize() creates a table that counts every combination of responses. I want to create a table broken down by response and count the number of respondents who indicated that answer. This table would count respondents multiple times if they indicated multiple answers.

Thank you.

答:
Using strsplit and table.

```<code>strsplit(df$why_join_program, ', ') |> unlist() |> table()
# college assistance employment support      fasfa support
#                  4                  3                  4
</code>```

Note: R >= 4.1 used

Title: Counting based on partial strings in R

Body:
I'm working with some survey data collected from a google form. One of the questions allowed for respondents to provide multiple answers:

Data:

id_number <- c("101", "102", "103", "104", "105", "106")

why_join_program <- c("college assistance",
                     "college assistance, fasfa support",
                     "fasfa support, employment support",
                     "college assistance, fasfa support, employment support",
                     "college assistance, employment support",
                     "fasfa support")

df <- data.frame(id_number, why_join_program)

I have two questions:

I want to count how many responses include a single answer (i.e., how many respondents identified "college support"?

Can you provide a good way to organize this into a table? group_by and summarize() creates a table that counts every combination of responses. I want to create a table broken down by response and count the number of respondents who indicated that answer. This table would count respondents multiple times if they indicated multiple answers.

Thank you.

Body:
Using strsplit and table.

strsplit(df$why_join_program, ', ') |> unlist() |> table()
# college assistance employment support      fasfa support
#                  4                  3                  4

Note: R >= 4.1 used


来源: stackexchange

问:
Is there a mongoDB runCommand that returns multiple collections?
I'm trying to write a mongoDB runCommand that returns multiple collections with one command.

I have successfully used the find command within runCommand but I'm unsure how to return multiple find searches. It's important that they are not merged.

Something similar to:

```<code>db.runCommand(
   [{
      "find": "venues"
   },
   {
      "find": "guests"
   }]
)
</code>```

Ideally the result would follow something similar to this structure:

```<code>{
  "venues": {all venue data from mongo},
  "guests": {all guest data from mongo}
}
</code>```

答:
As I see, this question has nothing common with runCommand.RunCommand just runs a single command. What you really need is to use unionWith aggregate stage and possibly some post data processing.

```<code>db.orders.aggregate([
  {
    $unionWith: {
      coll: "inventory",
      pipeline: [
        {
          $addFields: {
            "fromInventory": 1  // add a flag that shows that this data is not from original collection
          }
        }
      ]
    }
  },
  {
    "$group": {
      "_id": "$fromInventory",
      "content": {
        "$addToSet": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
      _id: 0
    }
  }
])
</code>```

See here. You may need to improve this result further for example with $replaceRoot

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a mongoDB runCommand that returns multiple collections with one command.

I have successfully used the find command within runCommand but I'm unsure how to return multiple find searches. It's important that they are not merged.

Something similar to:

db.runCommand(
   [{
      "find": "venues"
   },
   {
      "find": "guests"
   }]
)

Ideally the result would follow something similar to this structure:

{
  "venues": {all venue data from mongo},
  "guests": {all guest data from mongo}
}

Body:
As I see, this question has nothing common with runCommand.RunCommand just runs a single command. What you really need is to use unionWith aggregate stage and possibly some post data processing.

db.orders.aggregate([
  {
    $unionWith: {
      coll: "inventory",
      pipeline: [
        {
          $addFields: {
            "fromInventory": 1  // add a flag that shows that this data is not from original collection
          }
        }
      ]
    }
  },
  {
    "$group": {
      "_id": "$fromInventory",
      "content": {
        "$addToSet": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
      _id: 0
    }
  }
])

See here. You may need to improve this result further for example with $replaceRoot


问:
Prevent resizing first column in ListCtrl (ReportView)
I come from this
LVCFMT_FIXED_WIDTH
This format style works, but only after the first column. The first column items is always moveable. Why? Do I have missing something?</p>

```<code>for(int i = 0; i<NUM_COLUMNS; i++)
{
    m_ListCtrl.InsertColumn(i,_gszColumnLabel[i], _gnColumnFmt[i] |  LVCFMT_FIXED_WIDTH, _gnColumnWidth[i], -1);
}
</code>```

答:
A problem with LVCFMT_FIXED_WIDTH is that it is not possible to change the column width programmatically either (using SetColumnWidth). If you want to set the column width after the header control construction (for example in OnSize) you have to temporarily remove the LVCFMT_FIXED_WIDTH flag.

Here is an implementation that both has a workaround for not being able to modify the first column and one for not being able to programmatically modify a column with LVCFMT_FIXED_WIDTH:

```<code>void
MyTreeeCtrl::SetFixedColumnWidth(int col, int width)
{
  int colToModify = col;
  // Workaround 1: Insert a dummy column to be able to modify the attributes
  // of the first column.
  if (col == 0)
  {
    InsertColumn(0, L"");
    ++colToModify;
  }

  // Workaround 2: Temporarily remove the fixed width attribute to be able to
  // modify the width.
  LVCOLUMN colInfo;
  colInfo.mask = LVCF_FMT;
  GetColumn(colToModify, &colInfo);
  colInfo.fmt = colInfo.fmt & ~LVCFMT_FIXED_WIDTH;
  SetColumn(colToModify, &colInfo);

  // Set the column width
  SetColumnWidth(colToModify, width);

  // Restore the fixed width attribute
  colInfo.fmt = colInfo.fmt | LVCFMT_FIXED_WIDTH;
  SetColumn(colToModify, &colInfo);

  // Remove the dummy column
  if (col == 0)
  {
    DeleteColumn(0);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I come from this
LVCFMT_FIXED_WIDTH
This format style works, but only after the first column. The first column items is always moveable. Why? Do I have missing something?

for(int i = 0; i<NUM_COLUMNS; i++)
{
    m_ListCtrl.InsertColumn(i,_gszColumnLabel[i], _gnColumnFmt[i] |  LVCFMT_FIXED_WIDTH, _gnColumnWidth[i], -1);
}

Body:
A problem with LVCFMT_FIXED_WIDTH is that it is not possible to change the column width programmatically either (using SetColumnWidth). If you want to set the column width after the header control construction (for example in OnSize) you have to temporarily remove the LVCFMT_FIXED_WIDTH flag.

Here is an implementation that both has a workaround for not being able to modify the first column and one for not being able to programmatically modify a column with LVCFMT_FIXED_WIDTH:

void
MyTreeeCtrl::SetFixedColumnWidth(int col, int width)
{
  int colToModify = col;
  // Workaround 1: Insert a dummy column to be able to modify the attributes
  // of the first column.
  if (col == 0)
  {
    InsertColumn(0, L"");
    ++colToModify;
  }

  // Workaround 2: Temporarily remove the fixed width attribute to be able to
  // modify the width.
  LVCOLUMN colInfo;
  colInfo.mask = LVCF_FMT;
  GetColumn(colToModify, &colInfo);
  colInfo.fmt = colInfo.fmt & ~LVCFMT_FIXED_WIDTH;
  SetColumn(colToModify, &colInfo);

  // Set the column width
  SetColumnWidth(colToModify, width);

  // Restore the fixed width attribute
  colInfo.fmt = colInfo.fmt | LVCFMT_FIXED_WIDTH;
  SetColumn(colToModify, &colInfo);

  // Remove the dummy column
  if (col == 0)
  {
    DeleteColumn(0);
  }
}


问:
How to pass own unique key in firebase and update it as well without destroying the structure?
I am currently trying to make a script where I pass my own unique key in firebase as primary key. It needs to work like this

```<code>StudentData
  -Student Unique id
    - referadID : "active",
    - referadID2 : "inactive",
    - referadID3 : "active",
  -Student Unique id2
    -referadIDnew : "active",
</code>```

Here every student refers another student and once a refered student join that refered student who joined has his own unique id which stores value of active or inactive. The problem here is that if I use push it will generate a unique id which I don't want because it will make it difficult to work while using sorting. I don't want to do it. How can I create my own unique key in studentUniqueid2. I tried using transaction instead of push but the issue is that transaction instead of adding another key value pair would simply update the whole key leaving only the latest student unique id in the table which I don't want. Here is my code

```<code>let createData=adminDatabase.ref('/ReferralSystem/joinedtransactionlog');
createData.transaction(function(currentData){

  if(currentData !== InviterId){
    return {
      [InviterId]: {
        [member.id] : "active"
      }
    }
  }else{
    console.log("curretn data exists");
  }
});
</code>```

I am using javascript and working on firebase realtime database system with platform of Admin.

答:
If I understand correctly, you have two UIDs: one for the inviter and the other for the invitee/member. In that case, you can write the structure in your question with:

```<code>createData.child(inviterUID).child(memberUID).set("active");
</code>```

Doing this with a simple set operation will scale much better than the transaction you tried, since you're creating contention on the entire StudentData node while this merely performs an idempotent write.

There is no need to prevent writing the data if it already exists, as the operation is idempotent: subsequent writes don't change the result of the first write.

Body:
I am currently trying to make a script where I pass my own unique key in firebase as primary key. It needs to work like this

StudentData
  -Student Unique id
    - referadID : "active",
    - referadID2 : "inactive",
    - referadID3 : "active",
  -Student Unique id2
    -referadIDnew : "active",

Here every student refers another student and once a refered student join that refered student who joined has his own unique id which stores value of active or inactive. The problem here is that if I use push it will generate a unique id which I don't want because it will make it difficult to work while using sorting. I don't want to do it. How can I create my own unique key in studentUniqueid2. I tried using transaction instead of push but the issue is that transaction instead of adding another key value pair would simply update the whole key leaving only the latest student unique id in the table which I don't want. Here is my code

let createData=adminDatabase.ref('/ReferralSystem/joinedtransactionlog');
createData.transaction(function(currentData){

  if(currentData !== InviterId){
    return {
      [InviterId]: {
        [member.id] : "active"
      }
    }
  }else{
    console.log("curretn data exists");
  }
});

I am using javascript and working on firebase realtime database system with platform of Admin.

Body:
If I understand correctly, you have two UIDs: one for the inviter and the other for the invitee/member. In that case, you can write the structure in your question with:

createData.child(inviterUID).child(memberUID).set("active");

Doing this with a simple set operation will scale much better than the transaction you tried, since you're creating contention on the entire StudentData node while this merely performs an idempotent write.

There is no need to prevent writing the data if it already exists, as the operation is idempotent: subsequent writes don't change the result of the first write.


问:
TypeScript - The property does not exist in the type, but it actually exists
I'm trying to make my own xml builder on typescript. I have this issue:

```<code>Property 'children' does not exist on type 'XMLNode'.
  Property 'children' does not exist on type 'XMLNodeWithoutClidren'.
</code>```

its my code:

```<code>export interface Stringable {
  toString(): string
}

export type XMLProperty<T extends Stringable> = T

export interface XMLNodeWithoutClidren {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithClidren extends XMLNodeWithoutClidren {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutClidren | XMLNodeWithClidren;

class NodeWithoutChildrenBuilder {
  static build(node: XMLNodeWithoutClidren): string {
    return `some logic`
  }
}

class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithClidren): string {
    return `some logic`
  }
}

class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node);
    }

    return NodeWithoutChildrenBuilder.build(node);
  }
}
</code>```

Playground

What's wrong with my code?

答:
Sounds like a common case for a custom type guard:

```<code>function nodeHasChildren(node: XMLNode) : node is XMLNodeWithClidren {
    return (node as XMLNodeWithClidren).children !== undefined;
}
</code>```

and then you can rewrite your

```<code>if (node.children) {
</code>```

to

```<code>if (nodeHasChildren(node)) {
</code>```

which should correctly narrow the type in the scope.

Playground

Body:
I'm trying to make my own xml builder on typescript. I have this issue:

Property 'children' does not exist on type 'XMLNode'.
  Property 'children' does not exist on type 'XMLNodeWithoutClidren'.

its my code:

export interface Stringable {
  toString(): string
}

export type XMLProperty<T extends Stringable> = T

export interface XMLNodeWithoutClidren {
  readonly attributes: Map<string, XMLProperty<Stringable>>;
}

export interface XMLNodeWithClidren extends XMLNodeWithoutClidren {
  readonly children: Set<XMLNode>;
}

export type XMLNode = XMLNodeWithoutClidren | XMLNodeWithClidren;

class NodeWithoutChildrenBuilder {
  static build(node: XMLNodeWithoutClidren): string {
    return `some logic`
  }
}

class NodeWithChildrenBuilder {
  static build(node: XMLNodeWithClidren): string {
    return `some logic`
  }
}

class NodeParser {
  static parse(node: XMLNode) {
    if (node.children) {
      return NodeWithChildrenBuilder.build(node);
    }

    return NodeWithoutChildrenBuilder.build(node);
  }
}

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgZRimQHNMAjAGzwG8AoOOGCQ4pEgCgEoAuOAZyKk6AXzp1QkWEwCeYPAA0AsgBkAClAjzYMgDwAVOKFRIAJvwJD2FagD44AXjj7xk6PGSoMORaoByEKbAAOoIMAAWEACuMADClAimUMBIcPSMyZimEEiUMnCYMELkMcD8fEqYYLqCbCQANHDK6praMHqspDbAtrYA3KKu4O6IKGhYuE3%20gSFh4fGJyanGKeZTKgFBoRHRcQlJKWkMcJnZufnY4QiUB0h8%20MAwus2bPQNiEsPS7fLrr45-GbbSIxBa3OAAH0BWzmYKWAzo2EomH4FlewN2sSuNyWACEotcglAjoxBIUENg4CVCRwkDM%20C8gXNMfslrwBFYSCTGCdHlEoKkAAb8CAAWzwlAgJApguOYg%20SJRaKZESxhLxBJuaG5ZJgFKpmtMtPp0NmqtZKXZtVI3IyfIFcGFYolUplcsGiORqLgrzUmCg-G16Q55MpYH9geNQQZ0yCXFtiHQcCjwAAdJd1ZaE3aYPzUujYdjbvjCWhU9SbimuAMeXAPrXkrmHQWdqCixrS1By4aqzW66IgA" rel="nofollow noreferrer">Playground

What's wrong with my code?

Body:
Sounds like a common case for a custom type guard:

function nodeHasChildren(node: XMLNode) : node is XMLNodeWithClidren {
    return (node as XMLNodeWithClidren).children !== undefined;
}

and then you can rewrite your

if (node.children) {

to

if (nodeHasChildren(node)) {

which should correctly narrow the type in the scope.

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgZRimQHNMAjAGzwG8BYAKDjhgkOKRIAoBKALjgBnIqUYBfRo1CRYLAJ5g8ADQCyAGQAKUCIthyAPABU4oVEgAmggiM4VqAPjgBeOIckNp0eMlQYcy9QA5CHNgAHUEGAALCABXGABhSgRzKGAkOHomODTMcwgkSjk4TBgRcnjgQQEVTDB9YQ4SABo4VU1tXRgDdlI7YHt7AG5xd09ZHzQsXDagkPDIqKSUtIzTdMtZtWDQiOi4xOTU9MzGZlz8wuLsKIRKY6QBfGAYfXadgZGGCQYpcC95Ioth9nMD5nsYvFlg84AAfMG7RbQ1ZfRjYSiYQRWD4Qg4JW73VYAIVid1CUFO2WEpQQ2DgFTJXCQ8wE73BizxR1W-CENhIlOY5xesSgGQABoIIABbPCUCAkWlis5wH4-NEYrFwHFIgkPElktAC3k0ukM+5MlkIhbRZHpHmNUhGoUwEXiyUyuByhXYJXZVXudCxJDYGAIApwZmhAASmPxZNWFtCrLmoR4cAEkbwCCsbMRNq5JyygpywtFcETeExVohtqQPAAdDd4ycAIROFxB0LoZDAcxfNUMdGY7HzDSYKCCQ1F42hulgceTivJ7bzNPT5gIdDlzMxwRxwnpCs8NfK4tpF1l7U23XE0n3ND1s3mI9fYsDs+ljJXyGJG-pfX3lAj53s+mY8K+KriEAA" rel="nofollow noreferrer">Playground


问:
How to use $.ajax to retrieve access_token in Facebook's API (need creative solution)
I am using the JQuery function $.ajax to get an access token like so (an access token is a string containing letters, numbers, and a vertical pipe):

```<code>$.ajax({
url: 'https://graph.facebook.com/oauth/access_token',
type:'GET',
dataType: 'script',
data:{
           type:'client_cred',
           client_id:'CLIENT_ID', //CLIENT_ID IS REPLACED WITH ACTUAL VALUE IN CODE
           client_secret:'CLIENT_SECRET' //CLIENT_SECRET IS REPLACED WITH ACTUAL VALUE IN CODE
     },
success: function(response){
    console.log(response);
}
</code>```

});

I receive "400 Bad Request" errors if I use any dataType other than 'script' so I am funneled into using it (if anyone can explain this, it would be even better).  When I use the 'script' dataType, the ajax request goes through but breaks once it tries to evaluate the response because the response has a vertical pipe ('|') in it.  For instance, the response from the server would be

access_token=1045891579010403|Y1YlFJe3gRaUndfkjC6vcYE0LW8Q

but the function errors out because there is a vertical pipe in the assignment to access_token.

How would I go about overcoming this issue?  Is there a better way to get an access_token using the Facebook API?

答: baby, just use "&access_token=APP_ID|APP_SECRET" instead of retrieving the access_token, the way you try is not meant for ajax.</p>

Body:
I am using the JQuery function $.ajax to get an access token like so (an access token is a string containing letters, numbers, and a vertical pipe):

$.ajax({
url: 'https://graph.facebook.com/oauth/access_token',
type:'GET',
dataType: 'script',
data:{
           type:'client_cred',
           client_id:'CLIENT_ID', //CLIENT_ID IS REPLACED WITH ACTUAL VALUE IN CODE
           client_secret:'CLIENT_SECRET' //CLIENT_SECRET IS REPLACED WITH ACTUAL VALUE IN CODE
     },
success: function(response){
    console.log(response);
}

});

I receive "400 Bad Request" errors if I use any dataType other than 'script' so I am funneled into using it (if anyone can explain this, it would be even better).  When I use the 'script' dataType, the ajax request goes through but breaks once it tries to evaluate the response because the response has a vertical pipe ('|') in it.  For instance, the response from the server would be

access_token=1045891579010403|Y1YlFJe3gRaUndfkjC6vcYE0LW8Q

but the function errors out because there is a vertical pipe in the assignment to access_token.

How would I go about overcoming this issue?  Is there a better way to get an access_token using the Facebook API?


问:
While loop is running even though one of the conditions by the and is false
```<code>spam = 1
lam = ""

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")
</code>```

After I put 2 as my input lam = 2 making the condition false. However it still runs 4 more times due to the spam instead of ending.

答:
if you dont want to typecase just compare it with '2' instead of int 2

```<code>spam = 1
lam = ""

while spam < 5 and lam != '2':
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")
</code>```

Body:
spam = 1
lam = ""

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")

After I put 2 as my input lam = 2 making the condition false. However it still runs 4 more times due to the spam instead of ending.

Body:
if you dont want to typecase just compare it with '2' instead of int 2

spam = 1
lam = ""

while spam < 5 and lam != '2':
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1

if spam < 5:
    print("You got it right")

else:
        print("You got it wrong")


问:
How to apply stemming to a column in a pandas dataframe
If i had the following dataframe:

```<code>import pandas as pd

d = {'col1': ['goodness', 'beautiful'], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

Output
        col1  col2
0   goodness     3
1  beautiful     4
</code>```

I am using the porter stemmer:

```<code>print(porter.stem('goodness'))
print(porter.stem('beautiful'))

Output
good
beauti

</code>```

How can I apply this stem function to all elements of col1 from the original dataframe?

I have tried the following but no luck since it requires an input of word

```<code>df['col1'].apply(porter.stem(word), arg= word for word in df['col1'])
</code>```

The desired output is:

```<code>        col1  col2
0       good     3
1       beauti     4
</code>```

答:
```<code>df['col1'] = df['col1'].apply(porter.stem)
</code>```

should do the job.

Body:
If i had the following dataframe:

import pandas as pd

d = {'col1': ['goodness', 'beautiful'], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

Output
        col1  col2
0   goodness     3
1  beautiful     4

I am using the porter stemmer:

print(porter.stem('goodness'))
print(porter.stem('beautiful'))

Output
good
beauti

How can I apply this stem function to all elements of col1 from the original dataframe?

I have tried the following but no luck since it requires an input of word

df['col1'].apply(porter.stem(word), arg= word for word in df['col1'])

The desired output is:

        col1  col2
0       good     3
1       beauti     4

Body:
df['col1'] = df['col1'].apply(porter.stem)

should do the job.


问:
is it possible to do SOAP Xml parsing through jQuery?
Lot of SO  Answers are saying that SOAP webservice is not good using javascript.but the following URL   tells that it is possible.butis it possible through jquery using cross domain policy in for SOAP? any help please? I am working on HTML5 with javascript for mobiles,not in server side.</p>

答:
jQuery does have a SOAP project you can use, if you are interested.

http://plugins.jquery.com/project/jqSOAPClient

It is currently in beta, but it will get the job done.


问:
Decompress gz file using R
I have used ?unzip in the past to get at contents of a zipped file using R.  This time around, I am having a hard time extracting the files from a .gz file which can be found here.

I have tried ?gzfile and ?gzcon but have not been able to get it to work.  Any help you can provide will be greatly appreciated.

答:
If it's a comma/tab-separated file, you can use data.table's fread(). It can handle zipped (.zip, .gz) files:

fread('myFile.csv.gz')
```

Title: Decompress gz file using R


问:
After updating from Symfony 5.3 to 6, I got a Kernel error
After updating my composer, I got the following error when upgrading to Symfony 6:

Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization

It showed the trace on my Kernel.php file on line 30:

```<code><?php

namespace App;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    protected function configureContainer(ContainerConfigurator $container): void
    {
        $container->import('../config/{packages}/*.yaml');
        $container->import('../config/{packages}/'.$this->environment.'/*.yaml');

        if (is_file(\dirname(__DIR__).'/config/services.yaml')) {
            $container->import('../config/services.yaml');
            $container->import('../config/{services}_'.$this->environment.'.yaml');
        } elseif (is_file($path = \dirname(__DIR__).'/config/services.php')) {
            (require $path)($container->withPath($path), $this);
        }
    }

    protected function configureRoutes(RoutingConfigurator $routes): void
    {
        $routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
        $routes->import('../config/{routes}/*.yaml'); //<--- Error pointing here

        if (is_file(\dirname(__DIR__).'/config/routes.yaml')) {
            $routes->import('../config/routes.yaml');
        } elseif (is_file($path = \dirname(__DIR__).'/config/routes.php')) {
            (require $path)($routes->withPath($path), $this);
        }
    }
}
</code>```

I suspect this actually has nothing to do with my Kernel file, but my routing.yaml file?

routing.yaml contents:

framework:
    router:
        utf8: true
            # Configure how to generate URLs in non-HTTP contexts, such as CLI commands.
            # See https://symfony.com/doc/current/routing.html#generating-urls-in-commands
            #default_uri: http://localhost
```
<hr />
<p>I updated all of my packages utilizing <code>composer recipes:update</code>. After running that command, I'm now back to the original error:</p>
<blockquote>
<p>Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization</p>
</blockquote>
<p>I compared the file with the original here: https://github.com/symfony/symfony/blob/6.0/src/Symfony/Component/Routing/Annotation/Route.php and it's exactly the same.</p>
<p>After running <code>bin/console cache:clear</code> I got the following message:</p>
```00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\SensioFrameworkExtraExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\SensioFrameworkExtraExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\WebProfilerBundle\DependencyInjection\WebProfilerExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\WebProfilerBundle\DependencyInjection\WebProfilerExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\MonologBundle\DependencyInjection\MonologExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\MonologBundle\DependencyInjection\MonologExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\DebugBundle\DependencyInjection\DebugExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\DebugBundle\DependencyInjection\DebugExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\MakerBundle\DependencyInjection\MakerExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\MakerBundle\DependencyInjection\MakerExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\MigrationsBundle\DependencyInjection\DoctrineMigrationsExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\MigrationsBundle\DependencyInjection\DoctrineMigrationsExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Twig\Extra\TwigExtraBundle\DependencyInjection\TwigExtraExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Twig\Extra\TwigExtraBundle\DependencyInjection\TwigExtraExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\WebpackEncoreBundle\DependencyInjection\WebpackEncoreExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\WebpackEncoreBundle\DependencyInjection\WebpackEncoreExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension SymfonyCasts\Bundle\VerifyEmail\DependencyInjection\SymfonyCastsVerifyEmailExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "SymfonyCasts\Bundle\VerifyEmail\DependencyInjection\SymfonyCastsVerifyEmailExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\FixturesBundle\DependencyInjection\DoctrineFixturesExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\FixturesBundle\DependencyInjection\DoctrineFixturesExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension SymfonyCasts\Bundle\ResetPassword\DependencyInjection\SymfonyCastsResetPasswordExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "SymfonyCasts\Bundle\ResetPassword\DependencyInjection\SymfonyCastsResetPasswordExtension"]
00:00:27 CRITICAL  [php] Uncaught Error: Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization ["exception" => Error { …}]
```

The only place I see that has the $env variable is within bin/.phpunit/phpunit-8.5-0/** in 4 files within that directory.

答:
I found the issue.

After creating a separate new Symfony 6 project, this was the cause of the error:

framework.yaml

```<code>session:
        # enabled: true
        handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
</code>```

to

```<code>session:
        # enabled: true
        handler_id: null
</code>```

That fixed the issue.

Body:
After updating my composer, I got the following error when upgrading to Symfony 6:

Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization

It showed the trace on my Kernel.php file on line 30:

<?php

namespace App;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    protected function configureContainer(ContainerConfigurator $container): void
    {
        $container->import('../config/{packages}/*.yaml');
        $container->import('../config/{packages}/'.$this->environment.'/*.yaml');

        if (is_file(\dirname(__DIR__).'/config/services.yaml')) {
            $container->import('../config/services.yaml');
            $container->import('../config/{services}_'.$this->environment.'.yaml');
        } elseif (is_file($path = \dirname(__DIR__).'/config/services.php')) {
            (require $path)($container->withPath($path), $this);
        }
    }

    protected function configureRoutes(RoutingConfigurator $routes): void
    {
        $routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
        $routes->import('../config/{routes}/*.yaml'); //<--- Error pointing here

        if (is_file(\dirname(__DIR__).'/config/routes.yaml')) {
            $routes->import('../config/routes.yaml');
        } elseif (is_file($path = \dirname(__DIR__).'/config/routes.php')) {
            (require $path)($routes->withPath($path), $this);
        }
    }
}

I suspect this actually has nothing to do with my Kernel file, but my routing.yaml file?

routing.yaml contents:

framework:
    router:
        utf8: true
            # Configure how to generate URLs in non-HTTP contexts, such as CLI commands.
            # See https://symfony.com/doc/current/routing.html#generating-urls-in-commands
            #default_uri: http://localhost

I updated all of my packages utilizing composer recipes:update. After running that command, I'm now back to the original error:

Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization

I compared the file with the original here: https://github.com/symfony/symfony/blob/6.0/src/Symfony/Component/Routing/Annotation/Route.php and it's exactly the same.

After running bin/console cache:clear I got the following message:

00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\SensioFrameworkExtraExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\SensioFrameworkExtraExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\WebProfilerBundle\DependencyInjection\WebProfilerExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\WebProfilerBundle\DependencyInjection\WebProfilerExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\MonologBundle\DependencyInjection\MonologExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\MonologBundle\DependencyInjection\MonologExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\DebugBundle\DependencyInjection\DebugExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\DebugBundle\DependencyInjection\DebugExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\MakerBundle\DependencyInjection\MakerExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\MakerBundle\DependencyInjection\MakerExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\MigrationsBundle\DependencyInjection\DoctrineMigrationsExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\MigrationsBundle\DependencyInjection\DoctrineMigrationsExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Twig\Extra\TwigExtraBundle\DependencyInjection\TwigExtraExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Twig\Extra\TwigExtraBundle\DependencyInjection\TwigExtraExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Symfony\WebpackEncoreBundle\DependencyInjection\WebpackEncoreExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Symfony\WebpackEncoreBundle\DependencyInjection\WebpackEncoreExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension SymfonyCasts\Bundle\VerifyEmail\DependencyInjection\SymfonyCastsVerifyEmailExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "SymfonyCasts\Bundle\VerifyEmail\DependencyInjection\SymfonyCastsVerifyEmailExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension Doctrine\Bundle\FixturesBundle\DependencyInjection\DoctrineFixturesExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "Doctrine\Bundle\FixturesBundle\DependencyInjection\DoctrineFixturesExtension"]
00:00:27 WARNING   [app] Failed to generate ConfigBuilder for extension SymfonyCasts\Bundle\ResetPassword\DependencyInjection\SymfonyCastsResetPasswordExtension. ["exception" => Symfony\Component\DependencyInjection\Exception\EnvNotFoundException^ { …},"extensionClass" => "SymfonyCasts\Bundle\ResetPassword\DependencyInjection\SymfonyCastsResetPasswordExtension"]
00:00:27 CRITICAL  [php] Uncaught Error: Typed property Symfony\Component\Routing\Annotation\Route::$env must not be accessed before initialization ["exception" => Error { …}]

The only place I see that has the $env variable is within bin/.phpunit/phpunit-8.5-0/** in 4 files within that directory.

Body:
I found the issue.

After creating a separate new Symfony 6 project, this was the cause of the error:

framework.yaml

session:
        # enabled: true
        handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler

to

session:
        # enabled: true
        handler_id: null

That fixed the issue.


问:
Remove CSS pseudo element from jQuery form function
I developed a contact form for a website.

The field where users enter their message (a textarea box) has a jQuery character counter attached to it.

When the message is sent, an AJAX script refreshes the form and displays a success message.

All good so far.

The problem starts here:

When the user is entering their message and begins to reach the character limit, a warning notice appears, generated as a CSS pseudo element.

When the user exceeds the limit, a restriction notice appears, also generated by CSS.

The problem

When the user sends the message, while the warning notice is displayed, the warning notice won't leave after the page refresh.

This would also be a problem with the restriction notice, but another function disables the send button in this condition, so the form won't send when the counter is in negative territory.

I'm looking for a clean and simple function to integrate with my existing code that will remove the "approaching limit" pseudo element after the form is sent. Thank you.

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}</code>```

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>```

答:
Inside the ajax success call callback, after clearing the value of the textarea, you can trigger a change event on the textarea. This will in turn trigger .charCount() to reset everything back to defaults. Try this

```<code><!-- AJAX form messaging -->
<script>
    $(function() {

        // get the form
        var form = $('#modal-contact-form');

        // get the messages element
        var formMessages = $('#modal-contact-form-responses');

        // set up event listener for contact form
        $(form).submit(function(e) {
            // disable html submit button
            e.preventDefault();

            // serialize form data
            var formData = $(form).serialize();

            // submit form using AJAX
            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
                // make sure formMessages element has 'success' class
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');

                // set message text
                $(formMessages).text('Your message has been sent. Thank you!');

                // clear form
                $('input, textarea').val('');
                $("#modal-contact-form-message").trigger('change');
            })
            .fail(function(data) {
                // make sure formMessages element has 'error' class
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');

                // set the message text
                $(formMessages).text('Input error. Please review and re-submit.');
            });

        });

    });
</script>
</code>```

Body:
I developed a contact form for a website.

The field where users enter their message (a textarea box) has a jQuery character counter attached to it.

When the message is sent, an AJAX script refreshes the form and displays a success message.

All good so far.

The problem starts here:

When the user is entering their message and begins to reach the character limit, a warning notice appears, generated as a CSS pseudo element.

When the user exceeds the limit, a restriction notice appears, also generated by CSS.

The problem

When the user sends the message, while the warning notice is displayed, the warning notice won't leave after the page refresh.

This would also be a problem with the restriction notice, but another function disables the send button in this condition, so the form won't send when the counter is in negative territory.

I'm looking for a clean and simple function to integrate with my existing code that will remove the "approaching limit" pseudo element after the form is sent. Thank you.

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {
            allowed: 1250,
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj,submit){

            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }

            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');

            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});

/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}

/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}

<form action="" method="post" id="modal-contact-form">

    Name *
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>

    E-mail *
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>

    Subject
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">

    Message *
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

</form>

Body:
Inside the ajax success call callback, after clearing the value of the textarea, you can trigger a change event on the textarea. This will in turn trigger .charCount() to reset everything back to defaults. Try this

<!-- AJAX form messaging -->
<script>
    $(function() {

        // get the form
        var form = $('#modal-contact-form');

        // get the messages element
        var formMessages = $('#modal-contact-form-responses');

        // set up event listener for contact form
        $(form).submit(function(e) {
            // disable html submit button
            e.preventDefault();

            // serialize form data
            var formData = $(form).serialize();

            // submit form using AJAX
            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
                // make sure formMessages element has 'success' class
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');

                // set message text
                $(formMessages).text('Your message has been sent. Thank you!');

                // clear form
                $('input, textarea').val('');
                $("#modal-contact-form-message").trigger('change');
            })
            .fail(function(data) {
                // make sure formMessages element has 'error' class
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');

                // set the message text
                $(formMessages).text('Input error. Please review and re-submit.');
            });

        });

    });
</script>


问:
How to group/split array of objects by weeks with start and end date
I have big array of objects.

```<code>let objectsList = [
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'}
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01/2022'}
    {name: 'Alina', surname: 'Shulan', id: '3', createdProfile: '05/01/2021'}
    {name: 'Sasha', surname: 'Uena', id: '4', createdProfile: '11/02/2021'}
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'}
  ]
</code>```

And 2 dates let fromDate = '24/12/2021'; let toDate = '11/02/2022';
And i need to remove those objects which are not in range, and group those objects which are in range by weeks.
For instance result should look like this :

```<code>let result = [
  [
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01.2022'}
  ],
  [
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'},
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'},
     // Because they addad on same weak
  ],
]

let dates = [
  [
   '17/01/2022',
   '23/01/2022'
  ],
  [
   '07/02/2022',
   '13/02/2022'
  ],
]
</code>```

But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?
In order to not complicate application?
I was looking a lot and only found a few examples with lodash and groupBy

```<code>groupBy(objectsList, (dt) => moment(dt).week());
</code>```

But they all use only one from fromDate parameter and don't use toDate parameter.
And also this approach doesn't allow to get rid of those items which are not in range.
Sorry for not providing any code solutions, all my ideas have lots of nested loops and conditions.

答: You need to cast your string-dates into actual JavaScript Date-Objects with new Date('01/12/2022'). After all of your dates are actual Date-Objects, you can compare them with operators: new Date('01/12/2022') < new Date('02/12/2022') // true. After that, you need to loop over them and split them correctly. As this is more of a math-thing, you would benefit most, if you try to solve this with regular JS methods like map or foreach. This is a fairly easy task and good practice for yourself.

Body:
I have big array of objects.

let objectsList = [
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'}
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01/2022'}
    {name: 'Alina', surname: 'Shulan', id: '3', createdProfile: '05/01/2021'}
    {name: 'Sasha', surname: 'Uena', id: '4', createdProfile: '11/02/2021'}
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'}
  ]

And 2 dates let fromDate = '24/12/2021'; let toDate = '11/02/2022';
And i need to remove those objects which are not in range, and group those objects which are in range by weeks.
For instance result should look like this :

let result = [
  [
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01.2022'}
  ],
  [
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'},
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'},
     // Because they addad on same weak
  ],
]

let dates = [
  [
   '17/01/2022',
   '23/01/2022'
  ],
  [
   '07/02/2022',
   '13/02/2022'
  ],
]

But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?
In order to not complicate application?
I was looking a lot and only found a few examples with lodash and groupBy

groupBy(objectsList, (dt) => moment(dt).week());

But they all use only one from fromDate parameter and don't use toDate parameter.
And also this approach doesn't allow to get rid of those items which are not in range.
Sorry for not providing any code solutions, all my ideas have lots of nested loops and conditions.


问:
Azure Pipelines VSBuild configuration is invalid
I am new to Azure and I have inherited a pipeline which was built by someone else who is no longer with the company.  It's broken in many ways, so I am attempting to build a new one based on the original broken one I was given.  I am doing this one command at a time to fix the issues as i go.  Currently the following task is failing:

```<code>- task: VSBuild@1
    displayName: Build Solution
    inputs:
      solution: $(BuildParameters.solution)
      msbuildArgs: /p:DeployOnBuild=true /p:WebPublishingMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\$(BuildConfiguration)\\"
      platform: $(BuildPlatform)
      configuration: $(BuildConfiguration)
</code>```

I have researched other similar stack overflow posts but still can't figure out what the issue is.  The warning I am receiving is this:

```<code>Warning MSB4126: The specified solution configuration "$(BuildConfiguration)|$(BuildPlatform)" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration.
</code>```

Here is what I have tried so far:

I tried removing both the platform and configuration settings (the last two lines of the first quoted code above).  This resulted in 54 other warnings so that seemed like a bad idea.

next I put those two lines back in that I had deleted and instead i added this: /p:Configuration=Debug /p:Platform="Any CPU" to the very begining of the parameter string listed on the msbuildArgs setting.  This got rid of the 54 new warnings and brought back the original error (in other words it had no effect)

Also this other stack overflow question: TFS Build error MSB4126 (solution configuration is invalid) how to fix seems to have an a solution for this, however I can't figure out how to actually apply this solution.  There is a screenshot of the Azure UI in that ticket and I can't even figure out how to get to that page of Azure to see those options.  My guess is that this person is not using a yaml file to set up the pipeline and doing it the old way, but I do not want to configure it that way because I would prefer to have the yaml file define the pipeline and have this stored in my git repo.

Note: I have also been looking at the sln file associated with this project to try to make sense out of it, I think I get the basic idea of this file not sure...

Any advice will help, thanks

答:
Here the steps :-

Go to Azure Devops Pipeline where you have created your Pipeline.

Click on Edit pipeline using 3 dots visible for every pipeline you create.

Now Click on variables.

Leave BuildConfiguration and BuildPlatform blank (It will automatically pick based on your configuration in code).

Save and Run Queue.

Note:- This will only help if you have created your pipeline via classic method and not YAML.
I am not able to add images as it requires minimum 10 points. As soon as I get those points will add images for each step.

Body:
I am new to Azure and I have inherited a pipeline which was built by someone else who is no longer with the company.  It's broken in many ways, so I am attempting to build a new one based on the original broken one I was given.  I am doing this one command at a time to fix the issues as i go.  Currently the following task is failing:

- task: VSBuild@1
    displayName: Build Solution
    inputs:
      solution: $(BuildParameters.solution)
      msbuildArgs: /p:DeployOnBuild=true /p:WebPublishingMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\$(BuildConfiguration)\\"
      platform: $(BuildPlatform)
      configuration: $(BuildConfiguration)

I have researched other similar stack overflow posts but still can't figure out what the issue is.  The warning I am receiving is this:

Warning MSB4126: The specified solution configuration "$(BuildConfiguration)|$(BuildPlatform)" is invalid. Please specify a valid solution configuration using the Configuration and Platform properties (e.g. MSBuild.exe Solution.sln /p:Configuration=Debug /p:Platform="Any CPU") or leave those properties blank to use the default solution configuration.

Here is what I have tried so far:

I tried removing both the platform and configuration settings (the last two lines of the first quoted code above).  This resulted in 54 other warnings so that seemed like a bad idea.

next I put those two lines back in that I had deleted and instead i added this: /p:Configuration=Debug /p:Platform="Any CPU" to the very begining of the parameter string listed on the msbuildArgs setting.  This got rid of the 54 new warnings and brought back the original error (in other words it had no effect)

Also this other stack overflow question: TFS Build error MSB4126 (solution configuration is invalid) how to fix seems to have an a solution for this, however I can't figure out how to actually apply this solution.  There is a screenshot of the Azure UI in that ticket and I can't even figure out how to get to that page of Azure to see those options.  My guess is that this person is not using a yaml file to set up the pipeline and doing it the old way, but I do not want to configure it that way because I would prefer to have the yaml file define the pipeline and have this stored in my git repo.

Note: I have also been looking at the sln file associated with this project to try to make sense out of it, I think I get the basic idea of this file not sure...

Any advice will help, thanks


问:
How do I import setup colyseus with a svelte app?
I'm trying to start a colyseus app using Svelte.

I am import colyseus using:

```<code>import { Client } from 'colyseus.js'
</code>```

This builds fine but gives me the following messages when running the app:

```<code>Creating a browser bundle that depends on "https", "http" and "url". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node

- @colyseus/schema

LiveReload enabled
(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
https (guessing 'https')
http (guessing 'http$1')
url (guessing 'url')
</code>```

In the browser the app crashes with this console message:

```<code>Uncaught ReferenceError: https is not defined
    at main.js:8:2
</code>```

I've tried to setup the rollup-plugin-polyfill-node referenced in the log but this doesn't fix the issue

I'm also a newbie with Svelte/rollup etc so a simple explanation of what I am doing wrong would be appreciated!

答:
Colyseus.js (the client library) can not be run in a server environment, therefore you want to dynamically import Colyseus.js and run the setup code only after the component/page has mounted, and only in the browser environment.

Assuming this is a SvelteKit app, the following script (in a page or component) should work:

```<code><script>
    import { onMount } from 'svelte';
    import { browser } from '$app/env';

    async function connect() {
        let Colyseus = await import("colyseus.js");
        let client = new Colyseus.Client('ws://localhost:2567'); // or whereever your colyseus server instance is
        let room = await client.joinOrCreate("roomname", { /* options */ });
        // good to go
    }

    onMount(() => {
        if(browser) connect();
    })
</script>
</code>```

The key is to conditionally dynamically import Colyseus. A regular import would also import it on the server.

Body:
I'm trying to start a colyseus app using Svelte.

I am import colyseus using:

import { Client } from 'colyseus.js'

This builds fine but gives me the following messages when running the app:

Creating a browser bundle that depends on "https", "http" and "url". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node

- @colyseus/schema

LiveReload enabled
(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
https (guessing 'https')
http (guessing 'http$1')
url (guessing 'url')

In the browser the app crashes with this console message:

Uncaught ReferenceError: https is not defined
    at main.js:8:2

I've tried to setup the rollup-plugin-polyfill-node referenced in the log but this doesn't fix the issue

I'm also a newbie with Svelte/rollup etc so a simple explanation of what I am doing wrong would be appreciated!

Body:
Colyseus.js (the client library) can not be run in a server environment, therefore you want to dynamically import Colyseus.js and run the setup code only after the component/page has mounted, and only in the browser environment.

Assuming this is a SvelteKit app, the following script (in a page or component) should work:

<script>
    import { onMount } from 'svelte';
    import { browser } from '$app/env';

    async function connect() {
        let Colyseus = await import("colyseus.js");
        let client = new Colyseus.Client('ws://localhost:2567'); // or whereever your colyseus server instance is
        let room = await client.joinOrCreate("roomname", { /* options */ });
        // good to go
    }

    onMount(() => {
        if(browser) connect();
    })
</script>

The key is to conditionally dynamically import Colyseus. A regular import would also import it on the server.


问:
using two consecutive values from a list in each iteration
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.  </p>

```<code>import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :
</code>```

答:
Perhaps the pairwise iterator from itertools recipes will help?

```<code>from itertools import izip, tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
</code>```

Body:
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.

import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :

Body:
Perhaps the pairwise iterator from itertools recipes will help?

from itertools import izip, tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)


问:
React Native TextInput onChangeText triggered Modal onRequestClose
I created a Modal with TextInput to create a "Festival" in my database. To create i open a Modal by click "create". The Modal opens, the TextInput works fine.

But why is this TextInput onChangeText function triggering my Modal onRequestClose function?

```<code>import React, { Component } from 'react';
import { Alert, Button, Modal, Text, TextInput, StyleSheet, View } from 'react-native';

export default class EventCreate extends Component {
    state = { eventName: null, eventAdress: null, eventDate: null, eventPasskey: null }

render() {
    const { onSave, toggleModal } = this.props;
    const { eventName, eventAdress, eventDate, eventPasskey } = this.state;

    return (
        <Modal visible={this.props.visible} onRequestClose={console.log('wtf')} animationType={'slide'}>
            <View style={styles.container} >
                <Text>Bezeichnung</Text>
                <TextInput
                    style={styles.input}
                    onChangeText={text => this.setState({ eventName: text })}
                    placeholder="Bezeichnung"
                />
                <Button
                    onPress={() => {
                        Alert.alert(
                            "Event speichern?",
                            "Moechtest Du das Event" + " " + eventName + " " + "wirklich speichern?",
                            [
                                {
                                    text: "Abbruch",
                                    onPress: () => console.log("Eingabe vom Benutzer abgebrochen"),
                                    style: "cancel"
                                },
                                {
                                    text: "Speichern", onPress: function () {
                                        onSave(eventName, eventAdress, eventDate, eventPasskey);
                                        toggleModal();
                                    }
                                }
                            ]
                        );

                    }}
                    title="SAVE" />
            </View>
        </Modal>
    );
  }
}
const styles = StyleSheet.create({
    container: {
        alignItems: 'center'
    },
    input: {
        height: 40,
        width: 250,
        margin: 12,
        borderWidth: 1,
        padding: 10,
    },
});
</code>```

答:
Try this way</p>
```<code>onRequestClose={() => console.log('wtf')}
</code>```

Body:
I created a Modal with TextInput to create a "Festival" in my database. To create i open a Modal by click "create". The Modal opens, the TextInput works fine.

But why is this TextInput onChangeText function triggering my Modal onRequestClose function?

import React, { Component } from 'react';
import { Alert, Button, Modal, Text, TextInput, StyleSheet, View } from 'react-native';

export default class EventCreate extends Component {
    state = { eventName: null, eventAdress: null, eventDate: null, eventPasskey: null }

render() {
    const { onSave, toggleModal } = this.props;
    const { eventName, eventAdress, eventDate, eventPasskey } = this.state;

    return (
        <Modal visible={this.props.visible} onRequestClose={console.log('wtf')} animationType={'slide'}>
            <View style={styles.container} >
                <Text>Bezeichnung</Text>
                <TextInput
                    style={styles.input}
                    onChangeText={text => this.setState({ eventName: text })}
                    placeholder="Bezeichnung"
                />
                <Button
                    onPress={() => {
                        Alert.alert(
                            "Event speichern?",
                            "Moechtest Du das Event" + " " + eventName + " " + "wirklich speichern?",
                            [
                                {
                                    text: "Abbruch",
                                    onPress: () => console.log("Eingabe vom Benutzer abgebrochen"),
                                    style: "cancel"
                                },
                                {
                                    text: "Speichern", onPress: function () {
                                        onSave(eventName, eventAdress, eventDate, eventPasskey);
                                        toggleModal();
                                    }
                                }
                            ]
                        );

                    }}
                    title="SAVE" />
            </View>
        </Modal>
    );
  }
}
const styles = StyleSheet.create({
    container: {
        alignItems: 'center'
    },
    input: {
        height: 40,
        width: 250,
        margin: 12,
        borderWidth: 1,
        padding: 10,
    },
});

Body:
Try this way

onRequestClose={() => console.log('wtf')}


问:
Change value Array of Objects in mulesoft
I am beginner for mulesoft I have output payload transform message as below but I have to replace inside promotions array planChangeRequired attribute value as true always, can some one help me how can we replace it.

output Payload

```<code>{
  "content": {
    "data": {
      "sharedDataGroups": [
        {
          "empId": 100,
          "empName": "Ram"
        },
        {
          "empId": 200,
          "empName": "Santhosh"
        }
      ],
      "promotions": [
        {
          "id": "14400007",
          "discount": 10.0,
          "planChangeRequired": false
        }
      ]
    }
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}
</code>```

Expected Result

```<code>{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": **true**
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}
</code>```

答:
Update function would fit here.

Update function

Using update function, you dont need to map inside promotions array as this well change ALL the planChangeRequired to true

```<code>%dw 2.0
output application/json
import * from dw::util::Values
---
{
"info": payload.content.data update ["promotions", "planChangeRequired"]  with (true),
"meta-info":payload."meta-info"
}

</code>```

Output

```<code>{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

</code>```

Assuming you want to change different empName then update along with if-else can work here.

If you want to update all empName then you can follow the first approach
DW for all field update

```<code>%dw 2.0
output application/json
import * from dw::util::Values
---
{
"info": payload.content.data update ["promotions", "planChangeRequired"]  with (true) update ["sharedDataGroups", "empName"] with ((if (($)=="Ram")("Shyam")else "Krish")),
"meta-info":payload."meta-info"
}

</code>```

Output

```<code>{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Shyam"
      },
      {
        "empId": 200,
        "empName": "Krish"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      },
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}
</code>```

Body:
I am beginner for mulesoft I have output payload transform message as below but I have to replace inside promotions array planChangeRequired attribute value as true always, can some one help me how can we replace it.

output Payload

{
  "content": {
    "data": {
      "sharedDataGroups": [
        {
          "empId": 100,
          "empName": "Ram"
        },
        {
          "empId": 200,
          "empName": "Santhosh"
        }
      ],
      "promotions": [
        {
          "id": "14400007",
          "discount": 10.0,
          "planChangeRequired": false
        }
      ]
    }
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

Expected Result

{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": **true**
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

Body:
Update function would fit here.

Update function

Using update function, you dont need to map inside promotions array as this well change ALL the planChangeRequired to true

%dw 2.0
output application/json
import * from dw::util::Values
---
{
"info": payload.content.data update ["promotions", "planChangeRequired"]  with (true),
"meta-info":payload."meta-info"
}

Output

{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

Assuming you want to change different empName then update along with if-else can work here.

If you want to update all empName then you can follow the first approach
DW for all field update

%dw 2.0
output application/json
import * from dw::util::Values
---
{
"info": payload.content.data update ["promotions", "planChangeRequired"]  with (true) update ["sharedDataGroups", "empName"] with ((if (($)=="Ram")("Shyam")else "Krish")),
"meta-info":payload."meta-info"
}

Output

{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Shyam"
      },
      {
        "empId": 200,
        "empName": "Krish"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      },
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": true
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}