问:
Azure App Service deploy Failed to get resource ID for resource type 'Microsoft.Web/Sites'
In the last 6 months I have been releasing with a pipeline in Azure DevOps, but today I receive the following error:</p>

```<code>2019-09-25T14:24:38.4296875Z ##[section]Starting: Azure App Service Deploy: AS-ServiciosNegocio-API-UAT
2019-09-25T14:24:38.4419797Z ==============================================================================
2019-09-25T14:24:38.4419900Z Task         : Azure App Service deploy
2019-09-25T14:24:38.4419986Z Description  : Deploy to Azure App Service a web, mobile, or API app using Docker, Java, .NET, .NET Core, Node.js, PHP, Python, or Ruby
2019-09-25T14:24:38.4420053Z Version      : 3.4.31
2019-09-25T14:24:38.4420117Z Author       : Microsoft Corporation
2019-09-25T14:24:38.4420182Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-rm-web-app-deployment
2019-09-25T14:24:38.4420291Z ==============================================================================
2019-09-25T14:24:39.1630446Z Got connection details for Azure App Service:'AS-ServiciosNegocio-API-UAT'
2019-09-25T14:24:39.3091141Z ##[error]Error: Failed to get resource ID for resource type 'Microsoft.Web/Sites' and resource name 'AS-ServiciosNegocio-API-UAT'. Error: Could not fetch access token for Azure. Verify if the Service Principal used is valid and not expired.
2019-09-25T14:24:39.3140156Z ##[section]Finishing: Azure App Service Deploy: AS-ServiciosNegocio-API-UAT
</code>```

答:
I followed JamesD's answer but when I got to step 13, there was nowhere for me to put the Service Principle Key that was generated. So I went back to square one and approached it a different way. Instead of trying to reuse the existing service connection that had exired, I created a new service connection and then changed my release pipelines to use that new service connection and things worked fine.

Here were my steps:

click on Project Settings in the lower left corner

On the left nav under the "Pipelines" section, click on "Service connections"

in the upper right corner, click on the button "New service connection"

select "Azure Resource Manager" and then "Next"

select "Service principle (automatic)" (this is the recommended option)

select the subscription from the drop down.

select the resource group from the drop down

give it a good name and hit save

then authenticate with your azure portal creds

Now you have a service connection created, lets go change the pipeline to use it

Go to your pipeline for the release and edit it

click on the Stage you want to edit (aim for the # tasks link)

click on Deploy Azure App Service

under the azure subscription drop down, select your new subscription entry you created above

then you will select the App Service name in that drop down

hit save and you are good to go

Now repeat for any other stages of the pipeline or any other failing release pipelines

Body:
In the last 6 months I have been releasing with a pipeline in Azure DevOps, but today I receive the following error:

2019-09-25T14:24:38.4296875Z ##[section]Starting: Azure App Service Deploy: AS-ServiciosNegocio-API-UAT
2019-09-25T14:24:38.4419797Z ==============================================================================
2019-09-25T14:24:38.4419900Z Task         : Azure App Service deploy
2019-09-25T14:24:38.4419986Z Description  : Deploy to Azure App Service a web, mobile, or API app using Docker, Java, .NET, .NET Core, Node.js, PHP, Python, or Ruby
2019-09-25T14:24:38.4420053Z Version      : 3.4.31
2019-09-25T14:24:38.4420117Z Author       : Microsoft Corporation
2019-09-25T14:24:38.4420182Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-rm-web-app-deployment
2019-09-25T14:24:38.4420291Z ==============================================================================
2019-09-25T14:24:39.1630446Z Got connection details for Azure App Service:'AS-ServiciosNegocio-API-UAT'
2019-09-25T14:24:39.3091141Z ##[error]Error: Failed to get resource ID for resource type 'Microsoft.Web/Sites' and resource name 'AS-ServiciosNegocio-API-UAT'. Error: Could not fetch access token for Azure. Verify if the Service Principal used is valid and not expired.
2019-09-25T14:24:39.3140156Z ##[section]Finishing: Azure App Service Deploy: AS-ServiciosNegocio-API-UAT


来源: stackexchange

问:
Bulk Insert with child entities using EF6 extensions
I'm getting an error everytime I try to bulk insert using EF6 Extensions library

When using IncludeGraph, some options must be set in the IncludeGraphBuilder (See:
    https://entityframework-extensions.net/include-graph). The following options must be specified in IncludeGraphBuilder: ColumnPrimaryKeyExpression, LambdaPrimaryKeyExpression

The schema is as follows

Customer(PK,____,AddressId)

CustomerAddress(PK,____,AddressLookupId)

CustomerPhone(PK,___,CustomerId)

AddressCities(PK,CityName)

AddressLookup(PK,Zip,CityId, StateId)

I have the following as a lookup table

AddressStates(PK,_____)

options for filling the data as follows

```<code>options.InsertIfNotExists = true;
options.IncludeGraph = true;
options.IncludeGraphOperationBuilder = operation =>
                {
                    switch (operation)
                    {
                      case BulkOperation<Customer> customer:
                            customer.InsertIfNotExists = true;
                            customer.ColumnPrimaryKeyExpression = x => new {
                            x.FirstName, x.MiddleName, x.LastName};
                            customer.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerAddress> customerAddress:
                            customerAddress.InsertIfNotExists = true;
                            customerAddress.ColumnPrimaryKeyExpression = x =>
                            new { x.Address };
                            customerAddress.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerPhone> customerPhone:
                            customerPhone.InsertIfNotExists = true;
                            customerPhone.ColumnPrimaryKeyExpression = x =>
                            x.PhoneNumber;
                            //customerPhone.LambdaPrimaryKeyExpression =
                            customerPhone.AutoMapIdentityExpression;
                            customerPhone.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressCity> addressCity:
                            addressCity.InsertIfNotExists = true;
                            addressCity.ColumnPrimaryKeyExpression = x =>
                            x.City;
                            //addressCity.LambdaPrimaryKeyExpression =
                            addressCity.AutoMapIdentityExpression;
                            addressCity.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressLookup> addressLookup:
                            addressLookup.InsertIfNotExists = true;
                            addressLookup.ColumnPrimaryKeyExpression = x =>
                          new { x.Zip, x.CityId, x.StateId };
                            //addressLookup.LambdaPrimaryKeyExpression =
                            addressLookup.AutoMapIdentityExpression;
                            addressLookup.AutoMapOutputDirection = true;
                            break;
</code>```

I also tried setting the ColumnPrimaryKeyExpression to map the columns that should stay unique and no luck.

Update 1 : Added the Customer options inside the graph builder, error has changed to violation of FK Constraint on City, even though it's set to only allow cities that doesn't exist.

答: You aren't setting any settings for Customer. That likely is the issue</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm getting an error everytime I try to bulk insert using EF6 Extensions library

When using IncludeGraph, some options must be set in the IncludeGraphBuilder (See:
    https://entityframework-extensions.net/include-graph). The following options must be specified in IncludeGraphBuilder: ColumnPrimaryKeyExpression, LambdaPrimaryKeyExpression

The schema is as follows

Customer(PK,____,AddressId)

CustomerAddress(PK,____,AddressLookupId)

CustomerPhone(PK,___,CustomerId)

AddressCities(PK,CityName)

AddressLookup(PK,Zip,CityId, StateId)

I have the following as a lookup table

AddressStates(PK,_____)

options for filling the data as follows

options.InsertIfNotExists = true;
options.IncludeGraph = true;
options.IncludeGraphOperationBuilder = operation =>
                {
                    switch (operation)
                    {
                      case BulkOperation<Customer> customer:
                            customer.InsertIfNotExists = true;
                            customer.ColumnPrimaryKeyExpression = x => new {
                            x.FirstName, x.MiddleName, x.LastName};
                            customer.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerAddress> customerAddress:
                            customerAddress.InsertIfNotExists = true;
                            customerAddress.ColumnPrimaryKeyExpression = x =>
                            new { x.Address };
                            customerAddress.AutoMapOutputDirection = true;
                            //customer.LambdaPrimaryKeyExpression =
                            customer.AutoMapIdentityExpression;
                            break;
                        case BulkOperation<CustomerPhone> customerPhone:
                            customerPhone.InsertIfNotExists = true;
                            customerPhone.ColumnPrimaryKeyExpression = x =>
                            x.PhoneNumber;
                            //customerPhone.LambdaPrimaryKeyExpression =
                            customerPhone.AutoMapIdentityExpression;
                            customerPhone.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressCity> addressCity:
                            addressCity.InsertIfNotExists = true;
                            addressCity.ColumnPrimaryKeyExpression = x =>
                            x.City;
                            //addressCity.LambdaPrimaryKeyExpression =
                            addressCity.AutoMapIdentityExpression;
                            addressCity.AutoMapOutputDirection = true;
                            break;
                        case BulkOperation<AddressLookup> addressLookup:
                            addressLookup.InsertIfNotExists = true;
                            addressLookup.ColumnPrimaryKeyExpression = x =>
                          new { x.Zip, x.CityId, x.StateId };
                            //addressLookup.LambdaPrimaryKeyExpression =
                            addressLookup.AutoMapIdentityExpression;
                            addressLookup.AutoMapOutputDirection = true;
                            break;

I also tried setting the ColumnPrimaryKeyExpression to map the columns that should stay unique and no luck.

Update 1 : Added the Customer options inside the graph builder, error has changed to violation of FK Constraint on City, even though it's set to only allow cities that doesn't exist.


问:
Sockets : send 2Mb without loss of data
i am using sockets on linux, and i'd like to send a big table (more than 2 Mb) without losing any data, and fast enough to have a smooth video on the client. (what im sending is a video stream).

I've tried two things :

1°) send the entire table at once

```<code>socketError = send(newsockfd,(char*) DataTab,sizeof(DataTab),0);
if (socketError < 0)
    error("ERROR server writing to socket");
</code>```

2°) send the elements one by one

```<code>for (int i=0; i<nbelem; i++) // nbelem is greater than 600'000
{
    socketError = send(newsockfd,(char*) &DataTab[i],sizeof(&DataTab[i]),0);
    if (socketError < 0)
    error("ERROR server writing to socket");
}
</code>```

Sending the table at once is very fast, but i lose some data.

Sending the elements one by one works fine, no data loss, but it is too slow.

So I have 2 questions : What is the limitation of Data that can be sent in one socket (in bytes)? and How can I send my table quickly and without data loss ?

PS : My programs are supposed to comunicate in local, or in ethernet. Internet comunication is not envisaged.

答:
Network Programming is tricky and there are a lot of trade-offs you can consider. For example, if your server and client are both in LAN or a controlled & reliable WAN, you can use UDP. This way you'll save on the overheads of TCP and also won't loose any data for most transmissions.

If the video is being sent over the internet and you need reliability, you must use TCP. If you're using TCP, then just send() all the data at once. TCP has built-in reliability and flow-control mechanism. There isn't much you can do to speed up the data transfer in this case.

You can also consider using Raw sockets and implementing your own reliability and flow control. Else, work on your application so that it would go on fine even if there's a couple of lost video frames.

ContentLicense: CC BY-SA 3.0

Title: Sockets : send 2Mb without loss of data

Body:
i am using sockets on linux, and i'd like to send a big table (more than 2 Mb) without losing any data, and fast enough to have a smooth video on the client. (what im sending is a video stream).

I've tried two things :

1°) send the entire table at once

socketError = send(newsockfd,(char*) DataTab,sizeof(DataTab),0);
if (socketError < 0)
    error("ERROR server writing to socket");

2°) send the elements one by one

for (int i=0; i<nbelem; i++) // nbelem is greater than 600'000
{
    socketError = send(newsockfd,(char*) &DataTab[i],sizeof(&DataTab[i]),0);
    if (socketError < 0)
    error("ERROR server writing to socket");
}

Sending the table at once is very fast, but i lose some data.

Sending the elements one by one works fine, no data loss, but it is too slow.

So I have 2 questions : What is the limitation of Data that can be sent in one socket (in bytes)? and How can I send my table quickly and without data loss ?

PS : My programs are supposed to comunicate in local, or in ethernet. Internet comunication is not envisaged.


问:
Number recognition show wrong asnwer
i need to write such a network with two layers. The weights are defined in a pretty simple way: 1 for a blue and -1 for a white. For the first output neuron, you should set 15 weights for the number 1, for the second output neuron you should set another 15 weights for the number 2 etc and the last output neuron should recognize the number 0. In the end, you should choose the maximum out of all output neurons and it will be the result of the recognition.
and
bias is :
6 for 1
0 for 3, 5
1 for 2
2 for 4
3 for 7
-2 for 8
-1 for 6, 9, 0
if i will input 0 then w will be {+1, +1, +1, +1, -1, +1, +1, -1, +1, +1, -1, +1, +1, +1, +1}

and i wrote this code but it isnt work correctly can someone explain reason and give some hints

```<code>int[] w =  {+1, +1, +1, +1, -1, +1, +1, -1, +1, +1, -1, +1, +1, +1, +1};
        int[] output_num = {0,1, 2, 3, 4, 5, 6, 7,8,9};
        int[] bias = {-1, 6, 1, 0, 2, 0, -1, 3, -2, -1};
        Integer[] temp =new Integer[10];
        int[] output = new int[10];
        for (int i = 0; i < output_num.length; i++) {
            for (int j = 0; j < w.length; j++) {
                temp[i]  = output_num[i] * w[j];
            }
        }
        for (int i = 0; i < temp.length; i++) {
            temp[i] = temp[i] + bias[i];
        }
for (int x:temp) {
            System.out.print(x + " ");
        }
</code>```

its example when i input 0  its show this result is:-1 7 3 3 6 5 5 10 6 8
how we can see the max result is have index 7 but if i right understand  index should be 0 fro max element can someone give me some hits or explain

答:
You're doing things wrong here , the neural networks doesnt work like this , normally we shouldnt define the weights , they should be adapted using the input and output

You have to initialize them , but they have to be updated ( Descent of Gradient ) , suppose you have the following example :

```<code>input | output
x1    | y1
x2    | y2
</code>```

Then that's how you'll update your weights :

```<code>w[i] = w[i] + n ( d - yi ) xi
</code>```

where ( d - yi ) = the error and n = the learning rate

Title: Number recognition show wrong asnwer

Body:
i need to write such a network with two layers. The weights are defined in a pretty simple way: 1 for a blue and -1 for a white. For the first output neuron, you should set 15 weights for the number 1, for the second output neuron you should set another 15 weights for the number 2 etc and the last output neuron should recognize the number 0. In the end, you should choose the maximum out of all output neurons and it will be the result of the recognition.
and
bias is :
6 for 1
0 for 3, 5
1 for 2
2 for 4
3 for 7
-2 for 8
-1 for 6, 9, 0
if i will input 0 then w will be {+1, +1, +1, +1, -1, +1, +1, -1, +1, +1, -1, +1, +1, +1, +1}

and i wrote this code but it isnt work correctly can someone explain reason and give some hints

int[] w =  {+1, +1, +1, +1, -1, +1, +1, -1, +1, +1, -1, +1, +1, +1, +1};
        int[] output_num = {0,1, 2, 3, 4, 5, 6, 7,8,9};
        int[] bias = {-1, 6, 1, 0, 2, 0, -1, 3, -2, -1};
        Integer[] temp =new Integer[10];
        int[] output = new int[10];
        for (int i = 0; i < output_num.length; i++) {
            for (int j = 0; j < w.length; j++) {
                temp[i]  = output_num[i] * w[j];
            }
        }
        for (int i = 0; i < temp.length; i++) {
            temp[i] = temp[i] + bias[i];
        }
for (int x:temp) {
            System.out.print(x + " ");
        }

its example when i input 0  its show this result is:-1 7 3 3 6 5 5 10 6 8
how we can see the max result is have index 7 but if i right understand  index should be 0 fro max element can someone give me some hits or explain

Body:
You're doing things wrong here , the neural networks doesnt work like this , normally we shouldnt define the weights , they should be adapted using the input and output

You have to initialize them , but they have to be updated ( Descent of Gradient ) , suppose you have the following example :

input | output
x1    | y1
x2    | y2

Then that's how you'll update your weights :

w[i] = w[i] + n ( d - yi ) xi

where ( d - yi ) = the error and n = the learning rate


问:
Delete rows depending on values from another table
How to delete rows from my customer table depending on values from another table, let's say orders?

If the customer has no active orders they should be able to be deleted from the DB along with their rows (done using CASCADE). However, if they have any active orders at all, they can't be deleted.

I thought about a PLPGSQL function, then using it in a trigger to check, but I'm lost. I have a basic block of SQL shown below of my first idea of deleting the record accordingly. But it doesn't work properly as it deletes the customer regardless of status, it just needs one cancelled order in this function and not all cancelled.

```<code>CREATE OR REPLACE FUNCTION DelCust(int)
RETURNS void AS $body$
    DELETE FROM Customer
      WHERE CustID IN (
      SELECT CustID
      FROM Order
      WHERE Status = 'C'
      AND CustID = $1
    );
$body$
LANGUAGE SQL;

SELECT * FROM Customer;
</code>```

I have also tried to use a PLPGSQL function returning a trigger then using a trigger to help with the deletion and checks, but I'm lost on it. Any thoughts on how to fix this? Any good sources for further reading?

答:
Your basic function can work like this:

```<code>CREATE OR REPLACE FUNCTION del_cust(_custid int)
  RETURNS int  --③
  LANGUAGE sql AS
$func$
DELETE FROM customer c
WHERE  c.custid = $1
AND    NOT EXISTS ( -- ①
   SELECT FROM "order" o  -- ②
   WHERE  o.status = 'C'  -- meaning "active"?
   AND    o.custid = $1
   );
RETURNING c.custid; -- ③
$func$;
</code>```

① Avoid NOT IN if you can. It's inefficient and potentially treacherous. Related:

Select rows which are not present in other table

② "order" is a reserved word in SQL. Better chose a legal identifier, or you have to always double-quote.

③ I made it RETURNS int to signify whether the row was actually deleted. The function returns NULL if the DELETE does not go through. Optional addition.

For a trigger implementation, consider this closely related answer:

Foreign key contraints in many-to-many relationships

Body:
How to delete rows from my customer table depending on values from another table, let's say orders?

If the customer has no active orders they should be able to be deleted from the DB along with their rows (done using CASCADE). However, if they have any active orders at all, they can't be deleted.

I thought about a PLPGSQL function, then using it in a trigger to check, but I'm lost. I have a basic block of SQL shown below of my first idea of deleting the record accordingly. But it doesn't work properly as it deletes the customer regardless of status, it just needs one cancelled order in this function and not all cancelled.

CREATE OR REPLACE FUNCTION DelCust(int)
RETURNS void AS $body$
    DELETE FROM Customer
      WHERE CustID IN (
      SELECT CustID
      FROM Order
      WHERE Status = 'C'
      AND CustID = $1
    );
$body$
LANGUAGE SQL;

SELECT * FROM Customer;

I have also tried to use a PLPGSQL function returning a trigger then using a trigger to help with the deletion and checks, but I'm lost on it. Any thoughts on how to fix this? Any good sources for further reading?

Body:
Your basic function can work like this:

CREATE OR REPLACE FUNCTION del_cust(_custid int)
  RETURNS int  --③
  LANGUAGE sql AS
$func$
DELETE FROM customer c
WHERE  c.custid = $1
AND    NOT EXISTS ( -- ①
   SELECT FROM "order" o  -- ②
   WHERE  o.status = 'C'  -- meaning "active"?
   AND    o.custid = $1
   );
RETURNING c.custid; -- ③
$func$;

① Avoid NOT IN if you can. It's inefficient and potentially treacherous. Related:

Select rows which are not present in other table

② "order" is a reserved word in SQL. Better chose a legal identifier, or you have to always double-quote.

③ I made it RETURNS int to signify whether the row was actually deleted. The function returns NULL if the DELETE does not go through. Optional addition.

For a trigger implementation, consider this closely related answer:

Foreign key contraints in many-to-many relationships


问:
Get all the edited rows from Angular slick-grid on save all button click
I have an Ionic application where I use inline edit using Angular slick-grid for editing the gird. In my case, the user will make all the necessary changes and finally on the "save all" button click all the edited have to be updated in the DB. I want to know if there's any way of pulling the edited records from the grid/dataset by default rather than maintaining an external variable for storing the edited records IDs.

```<code>//I use this method to update the dataset.
onCellChanged(e, args) {
        this.angularGrid.gridService.updateDataGridItemById(args.item['id'], args.item);
    }
</code>```

答:
You can use the Edit Command Queue to know what item(s) got changed, this queue is useful to do an "Undo" when there's any error or when you just want to undo. The Queue keeps track of all the item row/cell indexes and their value before/after that got modified, you can get all item(s) from there and once you "Save All" you can just reset that queue.

export class MyComponent {
  private angularGrid: AngularGridInstance;
  private dataViewObj: any;
  private gridObj: any;
  private editQueue = [];

  angularGridReady(angularGrid: AngularGridInstance) {
    this.angularGrid = angularGrid;
    this.gridObj = angularGrid.slickGrid;
    this.dataViewObj = angularGrid.dataView;
  }

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  handleOnErrorCallback(error, gridObj) {
     // undo last edit in the grid
     const lastEdit = this.editQueue.pop();
     if (lastEdit && lastEdit.command) {
        lastEdit.command.undo();
        gridObj.gotoCell(lastEdit.command.row, lastEdit.command.cell, false);
     }
     return false;
  }

  saveAll() {
     // for example, to get the last Edit, you could type get it this way
     // const lastEdit = this.editQueue[this.editQueue.length - 1];
     // const lastEditField = lastEdit && lastEdit.column && lastEdit.column.field;

     const editItems = [];

     // in your case, you would want to loop through the entire queue
     this.editQueue.forEach((editObj) => {
       const previousValue = editObj.prevSerializedValue;
       const newValue = editObj.serializedValue;
       const rowIndex = editObj.row; // from the row index, you can get the item
       const item = this.angularGrid.dataView.getItem(rowIndex);

       // do what you want with the value or item
       editItems.push(item);
     });

     // call your save all method
     // this.saveInDb(editItems);

     // don't forget to reset your edit queue to restart with a new batch of edits
     this.editQueue = [];
  }
}
```

<p>Actually after writing this, I just saw that it might be easier to just get an array of items directly from the <code>editCommandHandler</code></p>

<pre class="lang-js prettyprint-override"><code>export class MyComponent {
  private editItems = [];

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editItems.push(item);
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  saveAll() {
    // call your save all method
    // this.saveInDb(editItems);

    // don't forget to reset your edit queue to restart with a new batch of edits
    this.editQueue = [];
    this.editItems = [];
  }
}
</code>```

Body:
I have an Ionic application where I use inline edit using Angular slick-grid for editing the gird. In my case, the user will make all the necessary changes and finally on the "save all" button click all the edited have to be updated in the DB. I want to know if there's any way of pulling the edited records from the grid/dataset by default rather than maintaining an external variable for storing the edited records IDs.

//I use this method to update the dataset.
onCellChanged(e, args) {
        this.angularGrid.gridService.updateDataGridItemById(args.item['id'], args.item);
    }

Body:
You can use the Edit Command Queue to know what item(s) got changed, this queue is useful to do an "Undo" when there's any error or when you just want to undo. The Queue keeps track of all the item row/cell indexes and their value before/after that got modified, you can get all item(s) from there and once you "Save All" you can just reset that queue.

export class MyComponent {
  private angularGrid: AngularGridInstance;
  private dataViewObj: any;
  private gridObj: any;
  private editQueue = [];

  angularGridReady(angularGrid: AngularGridInstance) {
    this.angularGrid = angularGrid;
    this.gridObj = angularGrid.slickGrid;
    this.dataViewObj = angularGrid.dataView;
  }

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  handleOnErrorCallback(error, gridObj) {
     // undo last edit in the grid
     const lastEdit = this.editQueue.pop();
     if (lastEdit && lastEdit.command) {
        lastEdit.command.undo();
        gridObj.gotoCell(lastEdit.command.row, lastEdit.command.cell, false);
     }
     return false;
  }

  saveAll() {
     // for example, to get the last Edit, you could type get it this way
     // const lastEdit = this.editQueue[this.editQueue.length - 1];
     // const lastEditField = lastEdit && lastEdit.column && lastEdit.column.field;

     const editItems = [];

     // in your case, you would want to loop through the entire queue
     this.editQueue.forEach((editObj) => {
       const previousValue = editObj.prevSerializedValue;
       const newValue = editObj.serializedValue;
       const rowIndex = editObj.row; // from the row index, you can get the item
       const item = this.angularGrid.dataView.getItem(rowIndex);

       // do what you want with the value or item
       editItems.push(item);
     });

     // call your save all method
     // this.saveInDb(editItems);

     // don't forget to reset your edit queue to restart with a new batch of edits
     this.editQueue = [];
  }
}

Actually after writing this, I just saw that it might be easier to just get an array of items directly from the editCommandHandler

export class MyComponent {
  private editItems = [];

  prepareGrid() {
    this.columnDefinitions = [ /*...*/ ];

    this.gridOptions = {
      autoEdit: true,
      editable: true,
      enableCellNavigation: true,
      editCommandHandler: (item, column, editCommand) => {
        this.editItems.push(item);
        this.editQueue.push(editCommand); // <-- last edit command
        editCommand.execute();
      },
    };
  }

  saveAll() {
    // call your save all method
    // this.saveInDb(editItems);

    // don't forget to reset your edit queue to restart with a new batch of edits
    this.editQueue = [];
    this.editItems = [];
  }
}


问:
ReactJS app deployed to firebase hosting not updating after first deployment
hope you all are doing well and staying safe.

I have been trying to deploy my react app to the net using firebase, and all was going well until i tried updating it/redeploying it. It shows ✔  Deploy complete! in my terminal but i check the website, it shows no update. I have tried putting the following code into firebase.json:

```<code>"headers": [
      {
        "source": "/service-worker.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]
</code>```

But that didn't change anything. My steps to release the app have been the following:

```<code>npx create-react-app firebase-test
cd firebase-test
firebase login
firebase init #I only chose hosting, chose to configure as a single-page application, wrote build as my public folder
npm run build
firebase deploy
</code>```

It shows the first deployment, but when I try to deploy again, I see no updates.

答: If the deploy is completed and you see a note of that, but the website is not updated then it means that your app bundle has not changed, make sure you run npm run build before running the deploy command</p>

Body:
hope you all are doing well and staying safe.

I have been trying to deploy my react app to the net using firebase, and all was going well until i tried updating it/redeploying it. It shows ✔  Deploy complete! in my terminal but i check the website, it shows no update. I have tried putting the following code into firebase.json:

"headers": [
      {
        "source": "/service-worker.js",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache"
          }
        ]
      }
    ]

But that didn't change anything. My steps to release the app have been the following:

npx create-react-app firebase-test
cd firebase-test
firebase login
firebase init #I only chose hosting, chose to configure as a single-page application, wrote build as my public folder
npm run build
firebase deploy

It shows the first deployment, but when I try to deploy again, I see no updates.


问:
How do I run PHPUnit in Laravel from my Windows Command prompt
I have a Laravel app installed in my directory f:\lara_app. I use PHP artisan serve to run the app. I have Laravel version 5.4.36 (via Composer Install)

I am not trying my hand in using the PHP Unit to do testing. Inside f:/lara_app/tests/Unit/ExampleTest.php, I have the following codes:

```<code>namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
         $this->assertTrue(true);
    }

    public function myFirstTest()
    {
        $value = 'Hello World';
        $this->assertTrue( 'Hello' === $value, 'Value should be Hello World');
    }
}
</code>```

I now try to run the test from my command prompt:

```<code>f:\lara_app> .vendor/phpunit/phpuni/phpunit
</code>```

But I'm getting the message below:

'.vendor' is not recognized as an internal or external command, operable program or batch file

How do I run the PHPUnit test?

Thanks in advance

答:
For every Laravel project from version 7.x, if you want to run tests you can do one of these:

You can use artisan: php artisan test docs

Or you can use phpunit: if you want to run phpunit on windows, only by typing phpunit, you can create a bat file in your project's main directory by running this command:@echo php vendor\phpunit\phpunit\phpunit > phpunit.bat and then you can type phpunit in your command and enjoy.

Happy Testing...

Body:
I have a Laravel app installed in my directory f:\lara_app. I use PHP artisan serve to run the app. I have Laravel version 5.4.36 (via Composer Install)

I am not trying my hand in using the PHP Unit to do testing. Inside f:/lara_app/tests/Unit/ExampleTest.php, I have the following codes:

namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
         $this->assertTrue(true);
    }

    public function myFirstTest()
    {
        $value = 'Hello World';
        $this->assertTrue( 'Hello' === $value, 'Value should be Hello World');
    }
}

I now try to run the test from my command prompt:

f:\lara_app> .vendor/phpunit/phpuni/phpunit

But I'm getting the message below:

'.vendor' is not recognized as an internal or external command, operable program or batch file

How do I run the PHPUnit test?

Thanks in advance


问:
Dependency Injection in every aspect of a spring app?
I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.

The concept of objects getting constructed in the container on run time is such a new concept.

I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?

It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?

I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.

Thanks in advance!

答:
Broadly speaking, an application is made up of a collection of classes that implement the business logic.

Normally each object is responsible to obtain references of the objects it needs (and this object's dependencies).

I think it is obvious that this leads to:

1)  tightly coupled classes

2)  code hard to test since each object instantiates specific classes it depends on and if there needs to be a change, the code must be modified.

So using Dependency Injections the objects do not instantiate the dependent objects themselves but an "external component" provides the dependencies at the object creation time i.e. injects the dependencies into the objects.

So in your example, the idea is that you can have for example a CsvRow object instantiated by Spring (along with all its dependencies) and get an object whenever needed. It is also possible to switch to for example CsvRow2 object (another implementation) by just changing your configuration


问:
How are hardware interruptions handled in non-preemtive scheduling?
Let's say I have a process A that is currently running. Then I press Ctrl+C, how is this interruption handled?

Does A finish executing first and then the interruption is handled?

Does A get put in the ready queue?

答:
In x86 interrupts are disabled and enabled with CLI (clear interrupt flag) and STI (set interrupt flag) commands respectively.
 Non-maskable interrupts will not be affected by it though. Other interrupts will be served as soon as you set interrupt flag back again.

The terminal in which you hit Ctrl-C sends an INT signal to all processes attached to it, ("interrupt", SIGINT) which by default, this causes the process to terminate.


问:
How to create an sql string to count selected rows with group by
I am trying to query a mysql database with columns AUTHOR, TITLE, TEXT to count all instances of texts by a given title, grouped by an author, e.g.
my table look like this

If my parameter is "Great Expectations", there are 2 entries of Great Expectaions by Dickens and 1 entry of Great Expectaions some Kathy Acker.

```<code>[{author=Charles Dickens, title=Great Expectations, count=2}, {author=Kathy Ackers, title=Great Expectations, count=1}]
</code>```

So far I have come up with this string:

```<code> jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote GROUP BY author")
</code>```

It somehow works but returns the counts of all entries by author in the database and all of my attempts to refine the search have failed.

I thought to include ...WHERE title = "Great Expectations"... but it does not work.

答:
You need to restrict the aggregation to only books entitled "The Lost World":

```<code>jdbcTemplate.queryForList("SELECT author, COUNT(*) AS count FROM Quote WHERE title = 'The Lost World' GROUP BY author")
</code>```

Actually, your current query would only work on a few databases, such as MySQL or SQLite, because of the GROUP BY issue.  Here is the raw query:

```<code>SELECT author, COUNT(*) AS count
FROM Quote
WHERE title = 'The Lost World'
GROUP BY author;
</code>```

Body:
I am trying to query a mysql database with columns AUTHOR, TITLE, TEXT to count all instances of texts by a given title, grouped by an author, e.g.
my table look like this

If my parameter is "Great Expectations", there are 2 entries of Great Expectaions by Dickens and 1 entry of Great Expectaions some Kathy Acker.

[{author=Charles Dickens, title=Great Expectations, count=2}, {author=Kathy Ackers, title=Great Expectations, count=1}]

So far I have come up with this string:

 jdbcTemplate.queryForList("SELECT author, title, COUNT(*) as count FROM Quote GROUP BY author")

It somehow works but returns the counts of all entries by author in the database and all of my attempts to refine the search have failed.

I thought to include ...WHERE title = "Great Expectations"... but it does not work.

Body:
You need to restrict the aggregation to only books entitled "The Lost World":

jdbcTemplate.queryForList("SELECT author, COUNT(*) AS count FROM Quote WHERE title = 'The Lost World' GROUP BY author")

Actually, your current query would only work on a few databases, such as MySQL or SQLite, because of the GROUP BY issue.  Here is the raw query:

SELECT author, COUNT(*) AS count
FROM Quote
WHERE title = 'The Lost World'
GROUP BY author;


问:
How does Perl handle password prompts?
I'd like to pass a password through Perl. In my Perl script, it invokes SSH but gets stuck when the terminal is promoted for a password.

I've looked into using NET::SSH::Perl and other libraries but as of now they are not viable options. I just need to SSH into the machine, retrieve a file and leave.

答:
You're telling me that Net::SSH::Perl won't work? You can give NET::SSH::Perl your password when you do your connection.

They even give you an example on the page:

```<code>my $ssh = Net::SSH::Perl->new("host1");
$ssh->login("user1", "pass1");

$ssh->cmd("foo");
$ssh->cmd("bar");
</code>```

Title: How does Perl handle password prompts?

Body:
You're telling me that Net::SSH::Perl won't work? You can give NET::SSH::Perl your password when you do your connection.

They even give you an example on the page:

my $ssh = Net::SSH::Perl->new("host1");
$ssh->login("user1", "pass1");

$ssh->cmd("foo");
$ssh->cmd("bar");


问:
How to align divs (selects) of different widths and lines vertically whilst also aligning them with other (text)- HTML and CSS
So, I know the question sounds super confusing but I have an image to demonstrate what I want to achieve.
The image:

The part that I am having trouble with is aligning the selection parts to "start" at the same place so that it's not messy. e.g. If you were to put a ruler on the screen they would all start at the same place. And the same problem for the text which looks messy as the words are different lengths.

I have tried using padding, css grids,   etc. but I haven't had luck - I don't feel that I need to add it because none of it really worked but I can if need be.

My HTML is as follows:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-  scale=1.0">
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel="stylesheet" href="main.css">
<title>Document</title>
</head>
<body>
    <h1>Solve the case!</h1>

    <div class="who-container">
        <h2 class="who">Who                </h2>
        <select class="who" id="who">
            <option>‘Small’ Paul Romano</option>
            <option>Steven Smith aka The Black Widow</option>
            <option>Ronnie ‘The Face’ Jones</option>
            <option>Joe Sharp</option>
        </select>
    </div>

    <div class="where-container">
        <h2 class="where">Where             </h2>
        <select class="where" id="where">
            <option>Mount Road</option>
            <option>Coronation Street</option>
            <option>Windsor Drive</option>
            <option>Back Street</option>
            <option>Queens Close</option>
            <option>Gladstone Road</option>
            <option>Kings Road</option>
            <option>Devon Road</option>
            <option>The Pines</option>
            <option>Saxon Way</option>
            <option>Alexandra Street</option>
            <option>The Grange</option>
            <option>Gloucester Road</option>
            <option>Larch Close</option>
            <option>Cedar Close</option>
            <option>Orchard Grove</option>
            <option>Robin Close</option>
            <option>Third Avenue</option>
            <option>Crescent Road</option>
            <option>Heath Lane</option>
            <option>Church Way</option>
            <option>South Drive</option>
            <option>Herbert Street</option>
            <option>Bedford Street</option>
            <option>Ash Grove</option>
            <option>St Peter's</option>
            <option>Road Thornton</option>
            <option>Road Avenue</option>
            <option>Road Parkway</option>
            <option>North Street</option>
            <option>Hazel Grove</option>
            <option>Shaftesbury Road</option>
            <option>Oak Tree</option>
            <option>Close Juniper</option>
            <option>Close Heron</option>
            <option>Close St</option>
            <option>Paul's Road</option>
            <option>Meadow Way</option>
            <option>Wordsworth Avenue</option>
            <option>Woodland Way</option>
            <option>Windsor Avenue</option>
            <option>Stanley Street</option>
            <option>The Moorings</option>
            <option>Wellington Street</option>
            <option>Edward Street</option>
            <option>Poplar Drive</option>
            <option>Trinity Close</option>
            <option>Railway Terrace</option>
            <option>Oak Close</option>
            <option>The Fairway</option>
            <option>Hall Street</option>
        </select>
    </div>

    <div class="when-container">
        <h2 class="when">When                 </h2>
        <select class="when" id="when">
            <option>00:00 - 00:30</option>
            <option>00:30 - 01:00</option>
            <option>01:00 - 01:30</option>
            <option>01:30 - 02:00</option>
            <option>02:00 - 02:30</option>
            <option>02:30 - 03:00</option>
            <option>03:00 - 03:30</option>
            <option>03:30 - 04:00</option>
            <option>04:00 - 04:30</option>
            <option>04:30 - 05:00</option>
            <option>05:00 - 05:30</option>
            <option>05:30 - 06:00</option>
            <option>06:00 - 06:30</option>
            <option>06:30 - 07:00</option>
            <option>07:00 - 07:30</option>
            <option>07:30 - 08:00</option>
            <option>08:00 - 08:30</option>
            <option>08:30 - 09:00</option>
            <option>09:00 - 09:30</option>
            <option>09:30 - 10:00</option>
            <option>10:00 - 10:30</option>
            <option>10:30 - 11:00</option>
            <option>11:00 - 11:30</option>
            <option>11:30 - 12:00</option>
            <option>12:00 - 12:30</option>
            <option>12:30 - 13:00</option>
            <option>13:00 - 13:30</option>
            <option>13:30 - 14:00</option>
            <option>14:00 - 14:30</option>
            <option>14:30 - 15:00</option>
            <option>15:00 - 15:30</option>
            <option>15:30 - 16:00</option>
            <option>16:00 - 16:30</option>
            <option>16:30 - 17:00</option>
            <option>17:00 - 17:30</option>
            <option>17:30 - 18:00</option>
            <option>18:00 - 18:30</option>
            <option>18:30 - 19:00</option>
            <option>19:00 - 19:30</option>
            <option>19:30 - 20:00</option>
            <option>20:00 - 20:30</option>
            <option>20:30 - 21:00</option>
            <option>21:00 - 21:30</option>
            <option>21:30 - 22:00</option>
            <option>22:00 - 22:30</option>
            <option>22:30 - 23:00</option>
            <option>23:00 - 23:30</option>
            <option>23:30 - 00:00</option>
        </select>
    </div>

    <div class="what-container">
        <h2 class="what">What                 </h2>
        <select class="what" id="what">
            <option>Candlestick</option>
            <option>Pipe</option>
            <option>Knife</option>
            <option>Gun</option>
            <option>Baseball Bat</option>
            <option>Spanner</option>
            <option>Hammer</option>
            <option>Rope</option>
            <option>Brick</option>
            <option>Golf Club</option>
        </select>
    </div>

    <div class="date-container">
        <h2 class="date">Date                 </h2>
        <input type="text" name="date" id="date">
    </div>

    <button onclick="submit()">Solve</button>

</body>
<script src="external/jquery/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

<script src="jquery-ui.min.js"></script>
<script>
    $( "#date" ).datepicker();
    $.datepicker.setDefaults({
    dateFormat: 'dd/mm/yy'
    });
    $( "#date" ).datepicker("setDate", new Date(2020,01,01));
</script>
<script src="form-handler.js"></script>
</html>
</code>```

And my CSS (that DOESN'T WORK!!!):

```<code>.who-container, .where-container, .when-container, .what-container,     .date-container{
    text-align: left;
}

.who, .where, .when, .what, .date{
    text-align: right;
    display: inline-block;
    padding-right: 20%
}

h2{
    padding-left: 40%;
}
</code>```

答:
Try add constant width to h2 tags:</p>

```<code>.container > div
{
  display: flex;
  align-items: center;
}

.container > div h2
{
  max-width: 100px;
}
</code>```

Body:
So, I know the question sounds super confusing but I have an image to demonstrate what I want to achieve.
The image:

The part that I am having trouble with is aligning the selection parts to "start" at the same place so that it's not messy. e.g. If you were to put a ruler on the screen they would all start at the same place. And the same problem for the text which looks messy as the words are different lengths.

I have tried using padding, css grids,   etc. but I haven't had luck - I don't feel that I need to add it because none of it really worked but I can if need be.

My HTML is as follows:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-  scale=1.0">
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel="stylesheet" href="main.css">
<title>Document</title>

Solve the case!

Who

        <select class="who" id="who">
            <option>‘Small’ Paul Romano</option>
            <option>Steven Smith aka The Black Widow</option>
            <option>Ronnie ‘The Face’ Jones</option>
            <option>Joe Sharp</option>
        </select>

Where

        <select class="where" id="where">
            <option>Mount Road</option>
            <option>Coronation Street</option>
            <option>Windsor Drive</option>
            <option>Back Street</option>
            <option>Queens Close</option>
            <option>Gladstone Road</option>
            <option>Kings Road</option>
            <option>Devon Road</option>
            <option>The Pines</option>
            <option>Saxon Way</option>
            <option>Alexandra Street</option>
            <option>The Grange</option>
            <option>Gloucester Road</option>
            <option>Larch Close</option>
            <option>Cedar Close</option>
            <option>Orchard Grove</option>
            <option>Robin Close</option>
            <option>Third Avenue</option>
            <option>Crescent Road</option>
            <option>Heath Lane</option>
            <option>Church Way</option>
            <option>South Drive</option>
            <option>Herbert Street</option>
            <option>Bedford Street</option>
            <option>Ash Grove</option>
            <option>St Peter's</option>
            <option>Road Thornton</option>
            <option>Road Avenue</option>
            <option>Road Parkway</option>
            <option>North Street</option>
            <option>Hazel Grove</option>
            <option>Shaftesbury Road</option>
            <option>Oak Tree</option>
            <option>Close Juniper</option>
            <option>Close Heron</option>
            <option>Close St</option>
            <option>Paul's Road</option>
            <option>Meadow Way</option>
            <option>Wordsworth Avenue</option>
            <option>Woodland Way</option>
            <option>Windsor Avenue</option>
            <option>Stanley Street</option>
            <option>The Moorings</option>
            <option>Wellington Street</option>
            <option>Edward Street</option>
            <option>Poplar Drive</option>
            <option>Trinity Close</option>
            <option>Railway Terrace</option>
            <option>Oak Close</option>
            <option>The Fairway</option>
            <option>Hall Street</option>
        </select>

When

        <select class="when" id="when">
            <option>00:00 - 00:30</option>
            <option>00:30 - 01:00</option>
            <option>01:00 - 01:30</option>
            <option>01:30 - 02:00</option>
            <option>02:00 - 02:30</option>
            <option>02:30 - 03:00</option>
            <option>03:00 - 03:30</option>
            <option>03:30 - 04:00</option>
            <option>04:00 - 04:30</option>
            <option>04:30 - 05:00</option>
            <option>05:00 - 05:30</option>
            <option>05:30 - 06:00</option>
            <option>06:00 - 06:30</option>
            <option>06:30 - 07:00</option>
            <option>07:00 - 07:30</option>
            <option>07:30 - 08:00</option>
            <option>08:00 - 08:30</option>
            <option>08:30 - 09:00</option>
            <option>09:00 - 09:30</option>
            <option>09:30 - 10:00</option>
            <option>10:00 - 10:30</option>
            <option>10:30 - 11:00</option>
            <option>11:00 - 11:30</option>
            <option>11:30 - 12:00</option>
            <option>12:00 - 12:30</option>
            <option>12:30 - 13:00</option>
            <option>13:00 - 13:30</option>
            <option>13:30 - 14:00</option>
            <option>14:00 - 14:30</option>
            <option>14:30 - 15:00</option>
            <option>15:00 - 15:30</option>
            <option>15:30 - 16:00</option>
            <option>16:00 - 16:30</option>
            <option>16:30 - 17:00</option>
            <option>17:00 - 17:30</option>
            <option>17:30 - 18:00</option>
            <option>18:00 - 18:30</option>
            <option>18:30 - 19:00</option>
            <option>19:00 - 19:30</option>
            <option>19:30 - 20:00</option>
            <option>20:00 - 20:30</option>
            <option>20:30 - 21:00</option>
            <option>21:00 - 21:30</option>
            <option>21:30 - 22:00</option>
            <option>22:00 - 22:30</option>
            <option>22:30 - 23:00</option>
            <option>23:00 - 23:30</option>
            <option>23:30 - 00:00</option>
        </select>

What

        <select class="what" id="what">
            <option>Candlestick</option>
            <option>Pipe</option>
            <option>Knife</option>
            <option>Gun</option>
            <option>Baseball Bat</option>
            <option>Spanner</option>
            <option>Hammer</option>
            <option>Rope</option>
            <option>Brick</option>
            <option>Golf Club</option>
        </select>

Date

        <input type="text" name="date" id="date">

    <button onclick="submit()">Solve</button>

And my CSS (that DOESN'T WORK!!!):

.who-container, .where-container, .when-container, .what-container,     .date-container{
    text-align: left;
}

.who, .where, .when, .what, .date{
    text-align: right;
    display: inline-block;
    padding-right: 20%
}

h2{
    padding-left: 40%;
}

Body:
Try add constant width to h2 tags:

.container > div
{
  display: flex;
  align-items: center;
}

.container > div h2
{
  max-width: 100px;
}


问:
Print items in array with increasing times
I have an array and I want every element in this array printed on the screen. But the time to print to the screen will be multiplied by 2 every time.

Example: a printed: 1 sec, b printed: 2sec, c printed: 4 sec...

How can I do that? This is my code. Can you help?

let exampleArray = ['a', 'b', 'c', 'd'];

const writeArray = (arr) => {
    let time = 1000;
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i])
    }
}

writeArray(exampleArray)```

答:
Try this:

let exampleArray = ['a', 'b', 'c', 'd'];

const writeArray = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        setTimeout(() => {
          console.log(arr[i])
        }, (i+1)*1000);
    }
}

writeArray(exampleArray)```


问:
Deserializing object ignoring certain nodes
I have an object that I serialized using an XmlSerializer. When trying to deserialize this XML file back into an object, it's skipping a node for some reason.

```<code><?xml version="1.0" encoding="utf-8"?>
<Dialogue xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Conversations>
    <Conversation Id="993fed92-6917-4003-975f-78df4ca77257" Name="sdfsf">
      <TextNode Id="8ce1fba9-9daf-4145-b374-d8d7df6ca983" IsGraphEntryPoint="false" NodePositionX="1056" NodePositionY="341">
        <Speaker>None</Speaker>
        <Lines />
      </TextNode>
      <ChoiceNode Id="7c697932-dbde-47a2-b931-bc881811ef63" IsGraphEntryPoint="false" NodePositionX="783" NodePositionY="605">
        <Choices>
          <ChoiceOptionNode ChoiceId="cbe28c44-a535-4191-80b2-1bb3d1881cb7" PortName="Choice#1" ConnectsTo="82fefda3-f6d9-4462-a39e-a20c56f97bcb">
            <Lines>
              <ChoiceOptionLineNode>
                <LanguageId>42d97432-c027-416d-2aa8-1ec47ca1410e</LanguageId>
                <LanguageCode>NL</LanguageCode>
                <Text />
              </ChoiceOptionLineNode>
            </Lines>
          </ChoiceOptionNode>
        </Choices>
      </ChoiceNode>
    </Conversation>
  </Conversations>
</Dialogue>
</code>```

All Textnodes are deserializing correctly, but the Choicenodes are seemingly completely ignored.

The object itself:

```<code>public class ChoiceNode : BaseConversationNode
    {
        [XmlArray("Choices")]
        [XmlArrayItem(ElementName = "ChoiceOptionNode")]
        public List<ChoiceOptionNode> Choices;
    }

public class ChoiceOptionNode
    {
        [XmlAttribute]
        public Guid ChoiceId;
        [XmlAttribute]
        public string PortName;
        [XmlArray("Lines")]
        [XmlArrayItem(ElementName = "ChoiceOptionLineNode")]
        public List<ChoiceOptionLineNode> Lines;
        [XmlAttribute]
        public Guid ConnectsTo;
    }

public class ChoiceOptionLineNode
    {
        public Guid LanguageId;
        public string LanguageCode;
        public string Text;
    }

public abstract class BaseConversationNode
    {
        [XmlElement(ElementName = "Connections")]
        public List<Output> Connections = new List<Output>();
        [XmlIgnore]
        public GraphNode Node;
        [XmlAttribute]
        public Guid Id;
        [XmlAttribute]
        public bool IsGraphEntryPoint;
        [XmlIgnore]
        public Rect NodeRect;
        [XmlAttribute]
        public float NodePositionX;
        [XmlAttribute]
        public float NodePositionY;
        /// <summary>
        /// The hex color of the node window
        /// </summary>
        /// <returns></returns>
        [XmlIgnore]
        public string NodeColorHex => !String.IsNullOrEmpty(options?.NodeColor) ? options.NodeColor : "c1c1c1";
        [XmlIgnore]
        public float NodeWidth => options?.NodeWidth ?? 200;
        [XmlIgnore]
        public float NodeHeight => options?.NodeHeight ?? 150;

        [XmlIgnore]
        private NodeOptionsAttribute _options;
        [XmlIgnore]
        private NodeOptionsAttribute options
        {
            get
            {
                if (_options == null)
                {
                    NodeOptionsAttribute attr = (NodeOptionsAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(NodeOptionsAttribute));
                    _options = attr;
                }

                return _options;
            }
        }
        [XmlIgnore]
        public List<Language> Languages;
}

[XmlRoot(ElementName = "Connection")]
    public class Output
    {
        [XmlAttribute]
        public Guid ConnectsTo;
        [XmlAttribute]
        public string PortName;
        [XmlAttribute]
        public Direction PortDirection;
        [XmlAttribute]
        public Port.Capacity Capacity;
    }

 public class Dialogue
    {
        /// <summary>
        /// The list of Conversations
        /// </summary>
        [XmlArrayItem(ElementName = "Conversation")]
        public List<Conversation> Conversations;
        /// <summary>
        /// The list of Languages
        /// </summary>
        public List<Language> Languages;

        [XmlIgnore]
        private List<Type> nodeTypes;
        [XmlIgnore]
        public List<Type> NodeTypes
        {
            get
            {
                if (nodeTypes == null)
                {
                    nodeTypes = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(assembly =>
                            assembly.GetTypes())
                            .Where(type =>
                                type.IsSubclassOf(typeof(BaseConversationNode))
                                //&& type.CustomAttributes.Any(x => x.AttributeType != typeof(AutoGeneratedNodeAttribute))
                                && !type.Equals(typeof(StartNode))
                            )
                            .ToList();
                }

                return nodeTypes;
            }
        }
}

public class Language
    {
        [XmlAttribute]
        public Guid Id;
        public string Name;
        public string Code;
    }

public class Conversation
    {
        [XmlAttribute]
        public Guid Id;
        [XmlAttribute]
        public string Name;
        [XmlElement(typeof(StartNode), ElementName = "StartNode")]
        [XmlElement(typeof(TextNode), ElementName = "TextNode")]
        public List<BaseConversationNode> Nodes;
}
</code>```

I find this really odd, as the XML I use is exactly what the XML Serializer returned in the first place. You'd think that it'd be able to properly deserialize it's own serialized XML...

What am I missing here?

Kind regards,

-Ferdy

Edit: Forgot to add the base class.
Edit 2: I'm a dumdum and forgot to add the other relevant classes with the first edit.

答:
I noticed my mistake.  In the following:

```<code>[XmlElement(typeof(StartNode), ElementName = "StartNode")]
[XmlElement(typeof(TextNode), ElementName = "TextNode")]
public List<BaseConversationNode> Nodes;

</code>```

I should have added another XmlElement attribute to the Nodes variable:

```<code>[XmlElement(typeof(StartNode), ElementName = "StartNode")]
[XmlElement(typeof(TextNode), ElementName = "TextNode")]
[XmlElement(typeof(ChoiceNode), ElementName = "ChoiceNode")]
public List<BaseConversationNode> Nodes;
</code>```

This does deserialize the XML properly.

Body:
I have an object that I serialized using an XmlSerializer. When trying to deserialize this XML file back into an object, it's skipping a node for some reason.

<?xml version="1.0" encoding="utf-8"?>
<Dialogue xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Conversations>
    <Conversation Id="993fed92-6917-4003-975f-78df4ca77257" Name="sdfsf">
      <TextNode Id="8ce1fba9-9daf-4145-b374-d8d7df6ca983" IsGraphEntryPoint="false" NodePositionX="1056" NodePositionY="341">
        <Speaker>None</Speaker>
        <Lines />
      </TextNode>
      <ChoiceNode Id="7c697932-dbde-47a2-b931-bc881811ef63" IsGraphEntryPoint="false" NodePositionX="783" NodePositionY="605">
        <Choices>
          <ChoiceOptionNode ChoiceId="cbe28c44-a535-4191-80b2-1bb3d1881cb7" PortName="Choice#1" ConnectsTo="82fefda3-f6d9-4462-a39e-a20c56f97bcb">
            <Lines>
              <ChoiceOptionLineNode>
                <LanguageId>42d97432-c027-416d-2aa8-1ec47ca1410e</LanguageId>
                <LanguageCode>NL</LanguageCode>
                <Text />
              </ChoiceOptionLineNode>
            </Lines>
          </ChoiceOptionNode>
        </Choices>
      </ChoiceNode>
    </Conversation>
  </Conversations>
</Dialogue>

All Textnodes are deserializing correctly, but the Choicenodes are seemingly completely ignored.

The object itself:

public class ChoiceNode : BaseConversationNode
    {
        [XmlArray("Choices")]
        [XmlArrayItem(ElementName = "ChoiceOptionNode")]
        public List<ChoiceOptionNode> Choices;
    }

public class ChoiceOptionNode
    {
        [XmlAttribute]
        public Guid ChoiceId;
        [XmlAttribute]
        public string PortName;
        [XmlArray("Lines")]
        [XmlArrayItem(ElementName = "ChoiceOptionLineNode")]
        public List<ChoiceOptionLineNode> Lines;
        [XmlAttribute]
        public Guid ConnectsTo;
    }

public class ChoiceOptionLineNode
    {
        public Guid LanguageId;
        public string LanguageCode;
        public string Text;
    }

public abstract class BaseConversationNode
    {
        [XmlElement(ElementName = "Connections")]
        public List<Output> Connections = new List<Output>();
        [XmlIgnore]
        public GraphNode Node;
        [XmlAttribute]
        public Guid Id;
        [XmlAttribute]
        public bool IsGraphEntryPoint;
        [XmlIgnore]
        public Rect NodeRect;
        [XmlAttribute]
        public float NodePositionX;
        [XmlAttribute]
        public float NodePositionY;
        ///
        /// The hex color of the node window
        ///
        /// <returns></returns>
        [XmlIgnore]
        public string NodeColorHex => !String.IsNullOrEmpty(options?.NodeColor) ? options.NodeColor : "c1c1c1";
        [XmlIgnore]
        public float NodeWidth => options?.NodeWidth ?? 200;
        [XmlIgnore]
        public float NodeHeight => options?.NodeHeight ?? 150;

        [XmlIgnore]
        private NodeOptionsAttribute _options;
        [XmlIgnore]
        private NodeOptionsAttribute options
        {
            get
            {
                if (_options == null)
                {
                    NodeOptionsAttribute attr = (NodeOptionsAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(NodeOptionsAttribute));
                    _options = attr;
                }

                return _options;
            }
        }
        [XmlIgnore]
        public List<Language> Languages;
}

[XmlRoot(ElementName = "Connection")]
    public class Output
    {
        [XmlAttribute]
        public Guid ConnectsTo;
        [XmlAttribute]
        public string PortName;
        [XmlAttribute]
        public Direction PortDirection;
        [XmlAttribute]
        public Port.Capacity Capacity;
    }

 public class Dialogue
    {
        ///
        /// The list of Conversations
        ///
        [XmlArrayItem(ElementName = "Conversation")]
        public List<Conversation> Conversations;
        ///
        /// The list of Languages
        ///
        public List<Language> Languages;

        [XmlIgnore]
        private List<Type> nodeTypes;
        [XmlIgnore]
        public List<Type> NodeTypes
        {
            get
            {
                if (nodeTypes == null)
                {
                    nodeTypes = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(assembly =>
                            assembly.GetTypes())
                            .Where(type =>
                                type.IsSubclassOf(typeof(BaseConversationNode))
                                //&& type.CustomAttributes.Any(x => x.AttributeType != typeof(AutoGeneratedNodeAttribute))
                                && !type.Equals(typeof(StartNode))
                            )
                            .ToList();
                }

                return nodeTypes;
            }
        }
}

public class Language
    {
        [XmlAttribute]
        public Guid Id;
        public string Name;
        public string Code;
    }

public class Conversation
    {
        [XmlAttribute]
        public Guid Id;
        [XmlAttribute]
        public string Name;
        [XmlElement(typeof(StartNode), ElementName = "StartNode")]
        [XmlElement(typeof(TextNode), ElementName = "TextNode")]
        public List<BaseConversationNode> Nodes;
}

I find this really odd, as the XML I use is exactly what the XML Serializer returned in the first place. You'd think that it'd be able to properly deserialize it's own serialized XML...

What am I missing here?

Kind regards,

-Ferdy

Edit: Forgot to add the base class.
Edit 2: I'm a dumdum and forgot to add the other relevant classes with the first edit.

Body:
I noticed my mistake.  In the following:

[XmlElement(typeof(StartNode), ElementName = "StartNode")]
[XmlElement(typeof(TextNode), ElementName = "TextNode")]
public List<BaseConversationNode> Nodes;

I should have added another XmlElement attribute to the Nodes variable:

[XmlElement(typeof(StartNode), ElementName = "StartNode")]
[XmlElement(typeof(TextNode), ElementName = "TextNode")]
[XmlElement(typeof(ChoiceNode), ElementName = "ChoiceNode")]
public List<BaseConversationNode> Nodes;

This does deserialize the XML properly.


问:
Editing NavigationBarItems and NavigationBarTitle in SwiftUI inside TabView
I'm trying to change the navigation bar title and leading & trailing items in a SwiftUI app.
Here is the situation:
A user logs in, then he gets transferred to a view inside a TabView.
Before login, in the welcome screen and login & register screens I have no navigation bar title, but after login, I want to add the navigation bar items and title.
What is important to know is that my after-login-view is inside a TabView.
If I wrap my after-login-view in a new NavigationView and then change the navigation bar items and title it works! but it shows me 2 navigation bars:

which is not what I want.

here is the code I use :
This is the after-Login-View

```<code>       import SwiftUI

       struct DiscoveryView: View {
             var body: some View {
                  List{
                       Text("List Items")
                  }.offset(y: 10)
                   .navigationBarTitle("", displayMode: .inline)
                   .navigationBarItems(leading:
                     Text("Discovery").font(Font.custom("Quicksand-             Bold", size: 24))
                   , trailing:
                       Button(action: {

                       }) {
                          HStack{
                             Text("120").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color("BlueColor"))
                          Text("following").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color.black)
                         }
                    }
                  ).navigationBarBackButtonHidden(true)
                }
              }
</code>```

This is the TabView:

```<code>struct TabController : View {

@State private var selection = 0
var body: some View {
    TabView(selection: $selection){

        DiscoveryView()
            .tabItem {
                VStack {
                    Image(systemName: "list.dash")
                    Text("Discover")
                }
        }.tag(1)

        ExploreView()
            .tabItem {
                VStack {
                    Image(systemName: "square.and.pencil")
                    Text("Explore")
                }
        }.tag(2)
        SelfProfileView()
            .tabItem{
                VStack {
                    Image(systemName: "person.circle")
                    Text("Profile")

                }
        }.tag(3)

    }.accentColor(Color("BlueColor"))
}
</code>```

}

This is the code of the login page:

```<code>import SwiftUI

struct LoginView: View {

var body: some View {
    ZStack{
        VStack{
            Image("mainLogo").resizable().frame(width: 250, height: 125)
            Text("").frame(width: UIScreen.main.bounds.width, height: 100)
            HStack{
                TextField("Username / Email", text: $email)
                    .padding(.leading, 10)
                    .frame(width: 313, height: 49)
                    .background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")))
            }
            Text("").frame(width: UIScreen.main.bounds.width, height: 40)
            HStack {
                HStack{
                        if self.visable{
                            TextField("Password", text: $password)
                                .padding(.horizontal)

                        } else {
                            SecureField("Password", text: $password)
                                .padding(.horizontal)

                        }
                        Button(action: {
                            self.visable.toggle()
                        }){
                            Image(systemName: self.visable ? "eye.slash" : "eye")
                                .padding(.trailing, 20)
                                .foregroundColor(Color.black)
                        }
                }.background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")) )
            }.padding(.horizontal, 40).padding(.vertical)
            Text("").frame(width: UIScreen.main.bounds.width, height: 100)
            Button(action: {
                //pass email password and conpassword to cognito
                DSManager().signIn(username: self.email, password: self.password, error: {
                    error in
                    if let error = error{
                        self.error = error.errorString
                        self.alert.toggle()
                        print(error.errorString)
                    }
                    else{
                        DSManager().getSelfUserInformation(response: {
                            userInfo, userCollections,dsError in
                            if let dsError = dsError{
                                self.error = dsError.errorString
                                self.alert.toggle()
                                print(dsError.errorString)
                            }
                            if let userInfo = userInfo{
                                print("success")
                                //use userInfo to load stuff for profile page
                                if let userCollections = userCollections{
                                    self.profileInfo.setProperties(userInfo: userInfo, collections: userCollections)
                                }
                                else{
                                    self.profileInfo.setProperties(userInfo: userInfo, collections: [:])
                                }
                                self.isComplete.toggle()

                            }
                        })
                    }
                })
            }) {
                Text("Login")
                    .fontWeight(.semibold)
                    .frame(width: 313, height: 48)
                    .background(fillAllFields() ? Color("YellowColor") : Color.gray)
                    .foregroundColor(Color.white)
                    .font(.system(size: 17))
                    .cornerRadius(15)
                    .shadow(color: Color("GrayColor"), radius: 0, x: 3, y: 3)
            }.disabled(!fillAllFields())
            NavigationLink(destination: ProfileView(), isActive: $isComplete) {
                EmptyView()
            }
            Spacer()
        }
        .padding()
        .navigationBarTitle("", displayMode: .inline)
        if self.alert {
            ErrorView(err: $error, alert: $alert)
        }
    }
}

func fillAllFields() -> Bool {
    if self.email == "" || self.password == "" {
        return false
    }
    return true
}
</code>```

}

As mentioned, I'm trying to edit bar items and title of a view inside and tab view .

Thanks!

答:
So as per your updated question, I added DiscoveryView Inside NavigationView and it worked as expected. I have added code and screenshot as well.

```<code>struct TabController : View {

@State private var selection = 0

var body: some View {
    TabView(selection: $selection) {
        NavigationView {
        DiscoveryView()
        }
            .tabItem {
                VStack {
                    Image(systemName: "list.dash")
                    Text("Discover")
                }
        }.tag(1)

        Text("Explore View")
            .tabItem {
                VStack {
                    Image(systemName: "square.and.pencil")
                    Text("Explore")
                }
        }.tag(2)
        Text("SelfProfileView")
            .tabItem{
                VStack {
                    Image(systemName: "person.circle")
                    Text("Profile")

                }
        }.tag(3)

    }.accentColor(Color("BlueColor"))
}}
</code>```

Body:
I'm trying to change the navigation bar title and leading & trailing items in a SwiftUI app.
Here is the situation:
A user logs in, then he gets transferred to a view inside a TabView.
Before login, in the welcome screen and login & register screens I have no navigation bar title, but after login, I want to add the navigation bar items and title.
What is important to know is that my after-login-view is inside a TabView.
If I wrap my after-login-view in a new NavigationView and then change the navigation bar items and title it works! but it shows me 2 navigation bars:

which is not what I want.

here is the code I use :
This is the after-Login-View

       import SwiftUI

       struct DiscoveryView: View {
             var body: some View {
                  List{
                       Text("List Items")
                  }.offset(y: 10)
                   .navigationBarTitle("", displayMode: .inline)
                   .navigationBarItems(leading:
                     Text("Discovery").font(Font.custom("Quicksand-             Bold", size: 24))
                   , trailing:
                       Button(action: {

                       }) {
                          HStack{
                             Text("120").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color("BlueColor"))
                          Text("following").font(Font.custom("Quicksand-Bold", size: 15)).foregroundColor(Color.black)
                         }
                    }
                  ).navigationBarBackButtonHidden(true)
                }
              }

This is the TabView:

struct TabController : View {

@State private var selection = 0
var body: some View {
    TabView(selection: $selection){

        DiscoveryView()
            .tabItem {
                VStack {
                    Image(systemName: "list.dash")
                    Text("Discover")
                }
        }.tag(1)

        ExploreView()
            .tabItem {
                VStack {
                    Image(systemName: "square.and.pencil")
                    Text("Explore")
                }
        }.tag(2)
        SelfProfileView()
            .tabItem{
                VStack {
                    Image(systemName: "person.circle")
                    Text("Profile")

                }
        }.tag(3)

    }.accentColor(Color("BlueColor"))
}

}

This is the code of the login page:

import SwiftUI

struct LoginView: View {

var body: some View {
    ZStack{
        VStack{
            Image("mainLogo").resizable().frame(width: 250, height: 125)
            Text("").frame(width: UIScreen.main.bounds.width, height: 100)
            HStack{
                TextField("Username / Email", text: $email)
                    .padding(.leading, 10)
                    .frame(width: 313, height: 49)
                    .background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")))
            }
            Text("").frame(width: UIScreen.main.bounds.width, height: 40)
            HStack {
                HStack{
                        if self.visable{
                            TextField("Password", text: $password)
                                .padding(.horizontal)

                        } else {
                            SecureField("Password", text: $password)
                                .padding(.horizontal)

                        }
                        Button(action: {
                            self.visable.toggle()
                        }){
                            Image(systemName: self.visable ? "eye.slash" : "eye")
                                .padding(.trailing, 20)
                                .foregroundColor(Color.black)
                        }
                }.background(RoundedRectangle(cornerRadius: 4).stroke( Color.black.opacity(0.3)).frame(width: 313, height: 39).background(Color("GrayColor")) )
            }.padding(.horizontal, 40).padding(.vertical)
            Text("").frame(width: UIScreen.main.bounds.width, height: 100)
            Button(action: {
                //pass email password and conpassword to cognito
                DSManager().signIn(username: self.email, password: self.password, error: {
                    error in
                    if let error = error{
                        self.error = error.errorString
                        self.alert.toggle()
                        print(error.errorString)
                    }
                    else{
                        DSManager().getSelfUserInformation(response: {
                            userInfo, userCollections,dsError in
                            if let dsError = dsError{
                                self.error = dsError.errorString
                                self.alert.toggle()
                                print(dsError.errorString)
                            }
                            if let userInfo = userInfo{
                                print("success")
                                //use userInfo to load stuff for profile page
                                if let userCollections = userCollections{
                                    self.profileInfo.setProperties(userInfo: userInfo, collections: userCollections)
                                }
                                else{
                                    self.profileInfo.setProperties(userInfo: userInfo, collections: [:])
                                }
                                self.isComplete.toggle()

                            }
                        })
                    }
                })
            }) {
                Text("Login")
                    .fontWeight(.semibold)
                    .frame(width: 313, height: 48)
                    .background(fillAllFields() ? Color("YellowColor") : Color.gray)
                    .foregroundColor(Color.white)
                    .font(.system(size: 17))
                    .cornerRadius(15)
                    .shadow(color: Color("GrayColor"), radius: 0, x: 3, y: 3)
            }.disabled(!fillAllFields())
            NavigationLink(destination: ProfileView(), isActive: $isComplete) {
                EmptyView()
            }
            Spacer()
        }
        .padding()
        .navigationBarTitle("", displayMode: .inline)
        if self.alert {
            ErrorView(err: $error, alert: $alert)
        }
    }
}

func fillAllFields() -> Bool {
    if self.email == "" || self.password == "" {
        return false
    }
    return true
}

}

As mentioned, I'm trying to edit bar items and title of a view inside and tab view .

Thanks!

Body:
So as per your updated question, I added DiscoveryView Inside NavigationView and it worked as expected. I have added code and screenshot as well.

struct TabController : View {

@State private var selection = 0

var body: some View {
    TabView(selection: $selection) {
        NavigationView {
        DiscoveryView()
        }
            .tabItem {
                VStack {
                    Image(systemName: "list.dash")
                    Text("Discover")
                }
        }.tag(1)

        Text("Explore View")
            .tabItem {
                VStack {
                    Image(systemName: "square.and.pencil")
                    Text("Explore")
                }
        }.tag(2)
        Text("SelfProfileView")
            .tabItem{
                VStack {
                    Image(systemName: "person.circle")
                    Text("Profile")

                }
        }.tag(3)

    }.accentColor(Color("BlueColor"))
}}


问:
HTTP Status 400 - Required String parameter 'walletName' is not present
I work with Java/ Spring MVC RESTful app and get 400 HTTP status error while doing a POST request. The @RestController method is provided,

```<code>@RequestMapping(value = "/generateAddress", method = RequestMethod.POST)
    public ResponseEntity<WalletInfoWrapper> generateAddress(@RequestParam("walletName") String walletName,
                                                             @RequestParam("currencyName") String currencyName) {

        logger.info("walletName {} and currencyName {}", walletName, currencyName);

        // return if the wallet name or the currency is null
        if (Objects.isNull(walletName) || Objects.isNull(currencyName)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfo walletInfo = walletService.generateAddress(walletName, currencyName);

        if (Objects.isNull(walletInfo)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper();
        walletInfoWrapper.setName(walletInfo.getName());

        return new ResponseEntity<WalletInfoWrapper>(walletInfoWrapper, HttpStatus.CREATED);
    }
</code>```

The POST request in the Postman provided below,

The error message informs, Required String parameter 'walletName' is not present

I can also provide the code for the services and the dataase layers for observing the drop-down operations. What is the issue here?

UPDATE

I updated the Postman request like this and still having the same error,

UPDATE 1

I still have the same issue,

I POST with the data,

```<code>{"walletName":"puut","currencyName":"Bitcoin"}
</code>```

The code is provided below,

```<code>@RequestMapping(value = "/generateAddress", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<WalletInfoWrapper> generateAddress(@RequestBody WalletWithMoneyRequest walletWithMoneyRequest) {

        String walletName = walletWithMoneyRequest.getWalletName();

        String currencyName = walletWithMoneyRequest.getCurrencyName();

        logger.info("walletName {} and currencyName {}", walletName, currencyName);

        // return if the wallet name or the currency is null
        if (Objects.isNull(walletName) || Objects.isNull(currencyName)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfo walletInfo = walletService.generateAddress(walletName, currencyName);

        if (Objects.isNull(walletInfo)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper();
        walletInfoWrapper.setName(walletInfo.getName());

        return new ResponseEntity<WalletInfoWrapper>(walletInfoWrapper, HttpStatus.CREATED);
    }
</code>```

The POJO is provided,

```<code>private class WalletWithMoneyRequest {

        String walletName;

        String currencyName;

        public WalletWithMoneyRequest(String walletName, String currencyName) {
            this.walletName = walletName;
            this.currencyName = currencyName;
        }

        public WalletWithMoneyRequest() {
        }

        public String getWalletName() {
            return walletName;
        }

        public String getCurrencyName() {
            return currencyName;
        }

        public void setCurrencyName(String currencyName) {
            this.currencyName = currencyName;
        }

        public void setWalletName(String walletName) {
            this.walletName = walletName;
        }
    }
</code>```

This is the error message,

Here ia the Tomcat server info,

```<code>org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver: 08/19/2017 19:45:55 - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `mobi.puut.controllers.WalletRestController$WalletWithMoneyRequest` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `mobi.puut.controllers.WalletRestController$WalletWithMoneyRequest` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: (PushbackInputStream); line: 1, column: 2]
</code>```

Tomcat Localhost log

Tomcat Catalina log

答: En POSTMAN set variables in params

Body:
I work with Java/ Spring MVC RESTful app and get 400 HTTP status error while doing a POST request. The @RestController method is provided,

@RequestMapping(value = "/generateAddress", method = RequestMethod.POST)
    public ResponseEntity<WalletInfoWrapper> generateAddress(@RequestParam("walletName") String walletName,
                                                             @RequestParam("currencyName") String currencyName) {

        logger.info("walletName {} and currencyName {}", walletName, currencyName);

        // return if the wallet name or the currency is null
        if (Objects.isNull(walletName) || Objects.isNull(currencyName)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfo walletInfo = walletService.generateAddress(walletName, currencyName);

        if (Objects.isNull(walletInfo)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper();
        walletInfoWrapper.setName(walletInfo.getName());

        return new ResponseEntity<WalletInfoWrapper>(walletInfoWrapper, HttpStatus.CREATED);
    }

The POST request in the Postman provided below,

The error message informs, Required String parameter 'walletName' is not present

I can also provide the code for the services and the dataase layers for observing the drop-down operations. What is the issue here?

UPDATE

I updated the Postman request like this and still having the same error,

UPDATE 1

I still have the same issue,

I POST with the data,

{"walletName":"puut","currencyName":"Bitcoin"}

The code is provided below,

@RequestMapping(value = "/generateAddress", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<WalletInfoWrapper> generateAddress(@RequestBody WalletWithMoneyRequest walletWithMoneyRequest) {

        String walletName = walletWithMoneyRequest.getWalletName();

        String currencyName = walletWithMoneyRequest.getCurrencyName();

        logger.info("walletName {} and currencyName {}", walletName, currencyName);

        // return if the wallet name or the currency is null
        if (Objects.isNull(walletName) || Objects.isNull(currencyName)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfo walletInfo = walletService.generateAddress(walletName, currencyName);

        if (Objects.isNull(walletInfo)) {
            return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
        }

        WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper();
        walletInfoWrapper.setName(walletInfo.getName());

        return new ResponseEntity<WalletInfoWrapper>(walletInfoWrapper, HttpStatus.CREATED);
    }

The POJO is provided,

private class WalletWithMoneyRequest {

        String walletName;

        String currencyName;

        public WalletWithMoneyRequest(String walletName, String currencyName) {
            this.walletName = walletName;
            this.currencyName = currencyName;
        }

        public WalletWithMoneyRequest() {
        }

        public String getWalletName() {
            return walletName;
        }

        public String getCurrencyName() {
            return currencyName;
        }

        public void setCurrencyName(String currencyName) {
            this.currencyName = currencyName;
        }

        public void setWalletName(String walletName) {
            this.walletName = walletName;
        }
    }

This is the error message,

Here ia the Tomcat server info,

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver: 08/19/2017 19:45:55 - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `mobi.puut.controllers.WalletRestController$WalletWithMoneyRequest` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `mobi.puut.controllers.WalletRestController$WalletWithMoneyRequest` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: (PushbackInputStream); line: 1, column: 2]

Tomcat Localhost log

Tomcat Catalina log

Body: En POSTMAN set variables in params


问:
Spring use different property files depending on request params
Background:

I am working on a java Spring REST microservice that needs to work with multiple identical back-end systems and multiple identical databases depending on the request parameters.

Basically I have 3 "brands". For each brand there is a set of downstream services and a database. I have no control over those.

My spring service will receive brand as a part of request and will need to call the right downstream services and use the correct database.

Previously I would deal with this by having a separate instance of the spring service for each of the brands. There would be a single property file for each brand and spring would use it to wire up beans. I would have separate URL's for each brand and there was no problem.

Some of my beans need to know about "brand" during creation as they are wrappers around connections downstream services. I.e. once the bean is created there won't be a way to switch it to be a "different brand".

Problem:

I would like to change this so that a single instance of my service can handle requests for any brand.

Requirements:
I was thinking about the following solution:

Have a general property file for non-branded stuff. Spring would wire any non-branded beans and keep them as singleton beans.

Have a property file with brand specific urls etc for each of the brands
Spring would create set of singleton beans for each of the brand using appropriate property file.

Next when the request comes in spring would read the request params and use bean specific for that brand.

Performance is important to me so I would like to reuse the beans as much as possible.

I would like to make this thing as transparent as possible so that people creating new beans don't have to worry about doing anything outside standard configuration/context class.

Does anyone know what would be the best solution to achieve this?

答:
Since your property files need to be declared statically anyway, you can just write all your different brand stuff in the same property file, like in a key-value format, that Spring can pick up as a list of configurations.

```<code>brandConfigs:
 - brand: foo
   property: foos
 - brand2: bar
   porperty: bars
</code>```

Load all your connection beans to your downstream services on startup and just route to them according to your request param. Imo this seems to be the most straight forward and performant way. If some of these downstreams are used very rarely you can lazy load the beans on-demand, but probably this wouldn't make a sense unless you have thousands of different downstream routes.

Body:
Since your property files need to be declared statically anyway, you can just write all your different brand stuff in the same property file, like in a key-value format, that Spring can pick up as a list of configurations.

brandConfigs:
 - brand: foo
   property: foos
 - brand2: bar
   porperty: bars

Load all your connection beans to your downstream services on startup and just route to them according to your request param. Imo this seems to be the most straight forward and performant way. If some of these downstreams are used very rarely you can lazy load the beans on-demand, but probably this wouldn't make a sense unless you have thousands of different downstream routes.


问:
Syntax error during updating value of dictionary with the text
I get the invalid syntax error:

答:
https://www.programiz.com/python-programming/methods/dictionary/update

update() Parameters

The update() method takes either a dictionary or an iterable object of key/value pairs (generally tuples).

If update() is called without passing parameters, the dictionary remains unchanged.

Body: I get the invalid syntax error:


问:
Using hex flag inside setiosflags function
```<code>int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;
</code>```

The above code is not working but if I use

```<code>cout<<hex
</code>```

and then

```<code>cout<<setiosflags(ios::showbase|ios::uppercase)
</code>```

then it is working

Why? and how i do know which one can be used inside setiosflags() ?

答:
You need to call resetiosflags before you call setiosflags.  The reason for this is that setiosflags(ios::hex|ios::showbase|ios::uppercase) just appends these flags into the stream as if calling setf and that gives conflicting flags in the stream.  Using

```<code>std::cout << std::resetiosflags(std::ios_base::dec)
          << std::setiosflags(std::ios::hex|std::ios::showbase|std::ios::uppercase)
          << a << endl;
</code>```

will make it display a correctly.

Body:
int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;

The above code is not working but if I use

cout<<hex

and then

cout<<setiosflags(ios::showbase|ios::uppercase)

then it is working

Why? and how i do know which one can be used inside setiosflags() ?

Body:
You need to call resetiosflags before you call setiosflags.  The reason for this is that setiosflags(ios::hex|ios::showbase|ios::uppercase) just appends these flags into the stream as if calling setf and that gives conflicting flags in the stream.  Using

std::cout << std::resetiosflags(std::ios_base::dec)
          << std::setiosflags(std::ios::hex|std::ios::showbase|std::ios::uppercase)
          << a << endl;

will make it display a correctly.