问:
How to create optional tuple return or unpack
I want to send tuple back if function returns error message and the data if success:

Example function:

```<code>def test(args):
   if (some success here):
     return data
   return None, error_message
</code>```

Call:

```<code>data, error_msg = test(args)
if error_msg:
   return somehttpresponse(error_msg, 400)
return somehttpresponse(data, 200)
</code>```

How can I achieve this in python? Or is there any other clean way to return error message without compromising the return data on success?

答:
So far I used Exception:

Example function:

```<code>def test(args):
   if (some success here):
     return data
   raise ValueError(error_message)
   return None
</code>```

Call:

```<code>try:
   data = test(args)
   return somehttpresponse(data, 200)
except ValueError as err:
   return somehttpresponse(err, 400)
</code>```

Not sure if it's the most efficient way. still hoping someone has an answer

Body:
I want to send tuple back if function returns error message and the data if success:

Example function:

def test(args):
   if (some success here):
     return data
   return None, error_message

Call:

data, error_msg = test(args)
if error_msg:
   return somehttpresponse(error_msg, 400)
return somehttpresponse(data, 200)

How can I achieve this in python? Or is there any other clean way to return error message without compromising the return data on success?

Body:
So far I used Exception:

Example function:

def test(args):
   if (some success here):
     return data
   raise ValueError(error_message)
   return None

Call:

try:
   data = test(args)
   return somehttpresponse(data, 200)
except ValueError as err:
   return somehttpresponse(err, 400)

Not sure if it's the most efficient way. still hoping someone has an answer


来源: stackexchange

问:
Loop through number array to construct object of index nodes in plain javascript
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

```<code>myObject.conversations[i].conversations[i]
</code>```

[2,5,3,1] would create:

```<code>myObject.conversations[i].conversations[i].conversations[i].conversations[i]
</code>```

I can only use basic javascript - es6, es5 etc not allowed. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

答:
You could iterate the indices array and use a variable for getting the nested references.</p>

```<code>var temp = myObject, // start value
    indices = [2, 5, 3, 1],
    i;

for (i = 0; i < indices.length; i++) {
    temp = temp.conversations[indices[i]];
}

// use temp
console.log(temp);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:

[2,5] would create:

myObject.conversations[i].conversations[i]

[2,5,3,1] would create:

myObject.conversations[i].conversations[i].conversations[i].conversations[i]

I can only use basic javascript - es6, es5 etc not allowed. I tried a for loop to construct a string which I could just keep adding to but it didn’t work.

Body:
You could iterate the indices array and use a variable for getting the nested references.

var temp = myObject, // start value
    indices = [2, 5, 3, 1],
    i;

for (i = 0; i < indices.length; i++) {
    temp = temp.conversations[indices[i]];
}

// use temp
console.log(temp);


问:
POST between c# and vue
---EDITED QUESTION:---

I am building my very first website with c# web application as backend and Vue as frontend.
My GET and DELETE works fine, but when I want to run POST I get problems I cant fully understand how to fix..

According to my teacher my Axios connection looks fine and the problem is only in my backend..

What I think I am trying to do is to somehow bind the models so they speak to eachother?

My datamodel is Sale.cs and my viewmodel (from Vue) is called SaleVM.cs

Sale.cs:

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Models
{
    public class Sale
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; } //++
        [Required]
        public string CustomerNumber { get; set; }
        public int UserId { get; set; } //fk
        [Required]
        public string YourReference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime? DateDone { get; set; }
        public DateTime? DateEdited { get; set; }
        public Status StatusId { get; set; }
        public DateTime? DateDelivered { get; set; }

        public virtual ICollection<SaleArticle> SaleArticles { get; set; }
        public virtual User User { get; set; }

    }
}
</code>```

SaleVM:

```<code>using System.Collections.Generic;

namespace Models
{
    public class SaleVM
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        public int Id { get; set; }
        public string Reference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public Status StatusId { get; set; }
        public int UserId { get; set; }

        public virtual ICollection<ArticleRow> ArticleRows { get; set; }
        public virtual SelectedCustomer SelectedCustomer { get; set; }

    }
}
</code>```

I think i have made them incorrectly because I have only guessed how to write them.

and lastly my SaleController:

```<code>{
    [Route("api/[controller]")]
    [ApiController]
    public class SaleController : ControllerBase
    {
        private readonly DataContext _context;

        public SaleController(DataContext context)
        {
            _context = context;
        }

        // POST: api/Sales/5
        [HttpPost]
        public async Task<ActionResult<Sale>> PostSale(SaleVM saleVM)
        {
          string customerNumber = (saleVM != null && saleVM.SelectedCustomer != null && Convert.ToInt32(saleVM.SelectedCustomer.CustomerNumber) > 0) ? saleVM.SelectedCustomer.CustomerNumber : "";

          List<SaleArticle> saleArticles = new List<SaleArticle>();
            if (saleVM != null && saleVM.ArticleRows != null && Convert.ToInt32(saleVM.ArticleRows) > 0)
            {
                foreach (var item in saleVM.ArticleRows)
                {
                    saleArticles.Add(new SaleArticle()
                    {
                        ArticleNumber = item.ArticleNumber,
                        Price = item.SalesPrice,
                        Quantity = item.Quantity,
                        Description = item.Description,
                        Id = item.Name
                    });
                }
            }
            //foreach (var saleVM in SaleVM)
            //{
            Sale sale = new Sale();
            {
                sale.CustomerNumber = saleVM.SelectedCustomer.CustomerNumber;
                sale.YourReference = saleVM.Reference;
                sale.SaleArticles = saleArticles;
                sale.DateCreated = saleVM.DateCreated;
                sale.DateSold = saleVM.DateSold;
                sale.StatusId = (Sale.Status)saleVM.StatusId;
                sale.UserId = saleVM.UserId;
            };

            _context.Sales.Add(sale);
            //}

            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetSale), new { id = saleVM.Id }, saleVM);
        }
    }
 }
</code>```

I dont get any errormessages in visual studio, but when I try the code out in postman i get statuscode 500 Internal Server Error:

System.NullReferenceException: Object reference not set to an instance of an object.
at E37SalesApi.Controllers.SaleController.PostSale(SaleVM saleVM) in C:\Users\fadaka\source\repos\E37SalesApi\Controllers\SaleController.cs:line 47
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I do understand what it says, its just I cant really understand how to fix it and get my POST method to fully work.

I hope I am clear with my problem

I am very new to programming and find it very hard to find information online that is on a level that a noob like me can understand, especially when it comes to c# and vue working together.

答:
For this issue

CS0019 Operator '>' cannot be applied to operands of type 'string' and 'int

Instead of

```<code>saleVM.SelectedCustomer.CustomerNumber > 0
</code>```

change to

```<code>Convert.ToInt32(saleVM.SelectedCustomer.CustomerNumber) > 0
</code>```

Title: POST between c# and vue

Body:
---EDITED QUESTION:---

I am building my very first website with c# web application as backend and Vue as frontend.
My GET and DELETE works fine, but when I want to run POST I get problems I cant fully understand how to fix..

According to my teacher my Axios connection looks fine and the problem is only in my backend..

What I think I am trying to do is to somehow bind the models so they speak to eachother?

My datamodel is Sale.cs and my viewmodel (from Vue) is called SaleVM.cs

Sale.cs:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Models
{
    public class Sale
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; } //++
        [Required]
        public string CustomerNumber { get; set; }
        public int UserId { get; set; } //fk
        [Required]
        public string YourReference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime? DateDone { get; set; }
        public DateTime? DateEdited { get; set; }
        public Status StatusId { get; set; }
        public DateTime? DateDelivered { get; set; }

        public virtual ICollection<SaleArticle> SaleArticles { get; set; }
        public virtual User User { get; set; }

    }
}

SaleVM:

using System.Collections.Generic;

namespace Models
{
    public class SaleVM
    {
        public enum Status
        {
            Started,
            Ongoing,
            Done,
            Removed
        }

        public int Id { get; set; }
        public string Reference { get; set; }
        public DateTime DateSold { get; set; }
        public DateTime DateCreated { get; set; }
        public Status StatusId { get; set; }
        public int UserId { get; set; }

        public virtual ICollection<ArticleRow> ArticleRows { get; set; }
        public virtual SelectedCustomer SelectedCustomer { get; set; }

    }
}

I think i have made them incorrectly because I have only guessed how to write them.

and lastly my SaleController:

{
    [Route("api/[controller]")]
    [ApiController]
    public class SaleController : ControllerBase
    {
        private readonly DataContext _context;

        public SaleController(DataContext context)
        {
            _context = context;
        }

        // POST: api/Sales/5
        [HttpPost]
        public async Task<ActionResult<Sale>> PostSale(SaleVM saleVM)
        {
          string customerNumber = (saleVM != null && saleVM.SelectedCustomer != null && Convert.ToInt32(saleVM.SelectedCustomer.CustomerNumber) > 0) ? saleVM.SelectedCustomer.CustomerNumber : "";

          List<SaleArticle> saleArticles = new List<SaleArticle>();
            if (saleVM != null && saleVM.ArticleRows != null && Convert.ToInt32(saleVM.ArticleRows) > 0)
            {
                foreach (var item in saleVM.ArticleRows)
                {
                    saleArticles.Add(new SaleArticle()
                    {
                        ArticleNumber = item.ArticleNumber,
                        Price = item.SalesPrice,
                        Quantity = item.Quantity,
                        Description = item.Description,
                        Id = item.Name
                    });
                }
            }
            //foreach (var saleVM in SaleVM)
            //{
            Sale sale = new Sale();
            {
                sale.CustomerNumber = saleVM.SelectedCustomer.CustomerNumber;
                sale.YourReference = saleVM.Reference;
                sale.SaleArticles = saleArticles;
                sale.DateCreated = saleVM.DateCreated;
                sale.DateSold = saleVM.DateSold;
                sale.StatusId = (Sale.Status)saleVM.StatusId;
                sale.UserId = saleVM.UserId;
            };

            _context.Sales.Add(sale);
            //}

            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetSale), new { id = saleVM.Id }, saleVM);
        }
    }
 }

I dont get any errormessages in visual studio, but when I try the code out in postman i get statuscode 500 Internal Server Error:

System.NullReferenceException: Object reference not set to an instance of an object.
at E37SalesApi.Controllers.SaleController.PostSale(SaleVM saleVM) in C:\Users\fadaka\source\repos\E37SalesApi\Controllers\SaleController.cs:line 47
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I do understand what it says, its just I cant really understand how to fix it and get my POST method to fully work.

I hope I am clear with my problem

I am very new to programming and find it very hard to find information online that is on a level that a noob like me can understand, especially when it comes to c# and vue working together.

Body:
For this issue

CS0019 Operator '>' cannot be applied to operands of type 'string' and 'int

Instead of

saleVM.SelectedCustomer.CustomerNumber > 0

change to

Convert.ToInt32(saleVM.SelectedCustomer.CustomerNumber) > 0


问:
How deploy UWP app like we did WPF from windows server?
I am new in UWP deployment need the right way to do this
I want to deploy my UWP to my users through group policy like we did WPF app?</p>

答:
Derive from Distribute LOB apps to enterprises document.

There are several options for distributing line of business (LOB) apps to your organization’s users using MSIX packages without making the apps broadly available to the public.

And App Installer is suit for your scenario that double-clicking an .appinstaller file that installs the app package from a web server. For the detail steps you could refer to  Installing Windows 10 apps from a web page document.

Update

For your comment questions, You could refer to Deploy an Application from Windows Store for Business via System Center Configuration Manager document.

you can take the .appx file for an app that has been made available for Offline use, and distribute the app with a management tool such as System Center Configuration Manager or the Windows Imaging and Configuration Designer.


问:
How to fix nextjs cloudfront static assets respond with 403?
I am trying to deploy my website to aws with cloudfront and route53. The site is deployed and running on https://higgle.io
However the assets are not loading, for the images are throwing 403. How do I fix it?
I am using serverless serverless-next.js. And I was following one of their blog post to set it up.
So far I added which has serverless.yml on the route level.

```<code>higgle:
 component: serverless-next.js
</code>```

and my next.config.js looks like

```<code>module.exports = {
  target: 'serverless',
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });
    return config
  }
}
</code>```

While the folder structrs looks like

```<code>-root
  -.next
  -pages
    -_document.js
    -index.js
  -public
    -static
      -favicon.ico
  -next.config.js
  -package.json
  -serverless.yml
</code>```

Any idea how to fix this?
Thanks

答:
S3 is returning a 403 because your items are private.

Change your S3 items to public. Check that they are accessible via your S3 static hosting address.

Step 1 will fix any static resources. If you are running a single page application, you will also need to return your index page when a 404 is returned by S3. In CloudFront, go to error pages, create a custom error response, choose 404 response, choose the option to customize the response, make the response code 200 and the response page path your index page.

Your bucket policy should be:

```<code>{
"Version": "2012-10-17",
"Id": "Policy1517754859350",
"Statement": [
    {
        "Sid": "Stmt1517754856505",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
    }
]
</code>```

}

Body:
I am trying to deploy my website to aws with cloudfront and route53. The site is deployed and running on https://higgle.io
However the assets are not loading, for the images are throwing 403. How do I fix it?
I am using serverless serverless-next.js. And I was following one of their blog post to set it up.
So far I added which has serverless.yml on the route level.

higgle:
 component: serverless-next.js

and my next.config.js looks like

module.exports = {
  target: 'serverless',
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });
    return config
  }
}

While the folder structrs looks like

-root
  -.next
  -pages
    -_document.js
    -index.js
  -public
    -static
      -favicon.ico
  -next.config.js
  -package.json
  -serverless.yml

Any idea how to fix this?
Thanks

Body:
S3 is returning a 403 because your items are private.

Change your S3 items to public. Check that they are accessible via your S3 static hosting address.

Step 1 will fix any static resources. If you are running a single page application, you will also need to return your index page when a 404 is returned by S3. In CloudFront, go to error pages, create a custom error response, choose 404 response, choose the option to customize the response, make the response code 200 and the response page path your index page.

Your bucket policy should be:

{
"Version": "2012-10-17",
"Id": "Policy1517754859350",
"Statement": [
    {
        "Sid": "Stmt1517754856505",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
    }
]

}


问:
How can I set the PHP version in PHPStorm?
Is it possible to set the PHP version value, say 4.0+ and have PHPStorm highlight functions that wouldn't work with the oldest version? For example, for PHP4 this should highlight static function etc. I have a PHP installation on my PC but I don't want to install an older PHP version for every small script I have to produce.

Thanks

答:
just like @mohammed my composer PHP version was synchronized to my phpstorm. so all i did was to update my composer.json php version number and it affected the whole project.

dont forget to composer update and php artisan config:clear

happy coding!

ContentLicense: CC BY-SA 2.5


问:
ASP.Net Core 2.2 SignInManager 'No sign-in authentication handler is registered for the scheme 'Identity.Application'
I have the following configurations in Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    //options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => {
    o.LoginPath = Routes.Urls.AdminAccountLogin;
    o.AccessDeniedPath = Routes.Urls.AdminAccountAccessdenied;
}).AddJwtBearer(configureOptions => {});
```

The application throws the following exception when the controller Login action calls SignInManger.PasswordSignInAsync:

Exception has occurred: CLR/System.InvalidOperationException

  Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll: 'No sign-in authentication handler is registered for the scheme 'Identity.Application'. The registered sign-in schemes are: Cookies. Did you forget to call AddAuthentication().AddCookies("Identity.Application",...)?'

Where does the Identity.Application come from?

答:
Short (and not as helpful) Answer:

Specifically it comes from the microsoft.aspnetcore.identity package in the class Microsoft.AspNetCore.Identity.IdentityConstants.ApplicationScheme

Long Answer, with the whole breakdown:

You need to add Identity - That scheme is stood up and connected to authentication in the AddIdentity extension method

The extension method is in Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions

public static IdentityBuilder AddIdentity<TUser, TRole>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser: class where TRole: class
        {
            services.AddAuthentication(delegate (AuthenticationOptions options) {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
            }).AddCookie(IdentityConstants.ApplicationScheme, delegate (CookieAuthenticationOptions o) {
                o.LoginPath = new PathString("/Account/Login");
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidatePrincipalAsync);
                o.Events = events1;
            }).AddCookie(IdentityConstants.ExternalScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes((double) 5.0);
            }).AddCookie(IdentityConstants.TwoFactorRememberMeScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidateAsync<ITwoFactorSecurityStampValidator>);
                o.Events = events1;
            }).AddCookie(IdentityConstants.TwoFactorUserIdScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes((double) 5.0);
            });
            services.AddHttpContextAccessor();
            services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
            services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
            services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
            services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped<IRoleValidator<TRole>, RoleValidator<TRole>>();
            services.TryAddScoped<IdentityErrorDescriber>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
            services.TryAddScoped<ITwoFactorSecurityStampValidator, TwoFactorSecurityStampValidator<TUser>>();
            services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
            services.TryAddScoped<UserManager<TUser>>();
            services.TryAddScoped<SignInManager<TUser>>();
            services.TryAddScoped<RoleManager<TRole>>();
            if (setupAction != null)
            {
                services.Configure<IdentityOptions>(setupAction);
            }
            return new IdentityBuilder(typeof(TUser), typeof(TRole), services);
        }
```

<p>If you follow this <code>AddCookie</code> call</p>

<pre class="lang-cs prettyprint-override"><code>.AddCookie(IdentityConstants.ApplicationScheme, delegate (CookieAuthenticationOptions o) {
                o.LoginPath = new PathString("/Account/Login");
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidatePrincipalAsync);
                o.Events = events1;
</code>```

it eventually configures AuthenticationOptions with the "Identity.Application" scheme and a CookieAuthenticationHandler

When you call SignInManager.PasswordSignInAsync:

SignInManager checks the username/password in the database (and does two factor flow if enabled), then if good

creates the ClaimsPrincipal and sends it to HttpContext.SignInAsync (an extension method) with the identity application scheme, see here

Which gets the IAuthenticationService (added to DI by AddAuthentication), see here

In AuthenticationService, it uses a chain of objects

IAuthenticationHandlerProvider => IAuthenticationSchemeProvider => the previously configured AuthenticationOptions to construct an AuthenticationScheme which serves up the IAuthenticationHandler in this  case CookieAuthenticationHandler. see here and here and here

CookieAuthenticationHandler.HandleSignInAsync creates, encrypts and adds the cookie.

Now the cookie is there, so the next request (often a redirect after login) in the AuthenticationMiddleware, the HttpContext.AuthenticateAsync method is called, which follows a similar flow to

CookieAuthenticationHandler.HandleAuthenticateAsync which reads the cookie and passes back a ClaimsPrincipal,

this is assigned to HttpContext.User, making it accessible to all the other areas of the request pipeline, like authorization, see here

Body:
I have the following configurations in Startup.cs:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    //options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => {
    o.LoginPath = Routes.Urls.AdminAccountLogin;
    o.AccessDeniedPath = Routes.Urls.AdminAccountAccessdenied;
}).AddJwtBearer(configureOptions => {});

The application throws the following exception when the controller Login action calls SignInManger.PasswordSignInAsync:

Exception has occurred: CLR/System.InvalidOperationException

  Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll: 'No sign-in authentication handler is registered for the scheme 'Identity.Application'. The registered sign-in schemes are: Cookies. Did you forget to call AddAuthentication().AddCookies("Identity.Application",...)?'

Where does the Identity.Application come from?

Body:
Short (and not as helpful) Answer:

Specifically it comes from the microsoft.aspnetcore.identity package in the class Microsoft.AspNetCore.Identity.IdentityConstants.ApplicationScheme

Long Answer, with the whole breakdown:

You need to add Identity - That scheme is stood up and connected to authentication in the AddIdentity extension method

The extension method is in Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions

public static IdentityBuilder AddIdentity<TUser, TRole>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser: class where TRole: class
        {
            services.AddAuthentication(delegate (AuthenticationOptions options) {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
            }).AddCookie(IdentityConstants.ApplicationScheme, delegate (CookieAuthenticationOptions o) {
                o.LoginPath = new PathString("/Account/Login");
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidatePrincipalAsync);
                o.Events = events1;
            }).AddCookie(IdentityConstants.ExternalScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes((double) 5.0);
            }).AddCookie(IdentityConstants.TwoFactorRememberMeScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidateAsync<ITwoFactorSecurityStampValidator>);
                o.Events = events1;
            }).AddCookie(IdentityConstants.TwoFactorUserIdScheme, delegate (CookieAuthenticationOptions o) {
                o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes((double) 5.0);
            });
            services.AddHttpContextAccessor();
            services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
            services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
            services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
            services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
            services.TryAddScoped<IRoleValidator<TRole>, RoleValidator<TRole>>();
            services.TryAddScoped<IdentityErrorDescriber>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
            services.TryAddScoped<ITwoFactorSecurityStampValidator, TwoFactorSecurityStampValidator<TUser>>();
            services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
            services.TryAddScoped<UserManager<TUser>>();
            services.TryAddScoped<SignInManager<TUser>>();
            services.TryAddScoped<RoleManager<TRole>>();
            if (setupAction != null)
            {
                services.Configure<IdentityOptions>(setupAction);
            }
            return new IdentityBuilder(typeof(TUser), typeof(TRole), services);
        }

If you follow this AddCookie call

.AddCookie(IdentityConstants.ApplicationScheme, delegate (CookieAuthenticationOptions o) {
                o.LoginPath = new PathString("/Account/Login");
                CookieAuthenticationEvents events1 = new CookieAuthenticationEvents();
                events1.OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidatePrincipalAsync);
                o.Events = events1;

it eventually configures AuthenticationOptions with the "Identity.Application" scheme and a CookieAuthenticationHandler

When you call SignInManager.PasswordSignInAsync:

SignInManager checks the username/password in the database (and does two factor flow if enabled), then if good

creates the ClaimsPrincipal and sends it to HttpContext.SignInAsync (an extension method) with the identity application scheme, see here

Which gets the IAuthenticationService (added to DI by AddAuthentication), see here

In AuthenticationService, it uses a chain of objects

IAuthenticationHandlerProvider => IAuthenticationSchemeProvider => the previously configured AuthenticationOptions to construct an AuthenticationScheme which serves up the IAuthenticationHandler in this  case CookieAuthenticationHandler. see here and here and here

CookieAuthenticationHandler.HandleSignInAsync creates, encrypts and adds the cookie.

Now the cookie is there, so the next request (often a redirect after login) in the AuthenticationMiddleware, the HttpContext.AuthenticateAsync method is called, which follows a similar flow to

CookieAuthenticationHandler.HandleAuthenticateAsync which reads the cookie and passes back a ClaimsPrincipal,

this is assigned to HttpContext.User, making it accessible to all the other areas of the request pipeline, like authorization, see here


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答:
Check out Mads Kristensen's article for an HttpModule that will encrypt/decrypt all of your querystrings.
http://madskristensen.net/post/httpmodule-for-query-string-encryption

His code uses an HttpModule to parses outgoing HTML to encrypt and replace all relative path querystrings. The HttpModule also captures incoming requests and rewrites the request url to use an unencrypted querystring.

The nice part is that you can drop in the module and your code doesn't need to know when the querystrings are encrypted or not.  From the code perspective, querystrings work like they always do.

We've been using it for over five years now and it works great.

OwnerDisplayName: Ksmps

OwnerDisplayName: slolife

ContentLicense: CC BY-SA 3.0


问:
How can I use preg_match in jQuery?
Can I use preg_match to validate phone number in jQuery? Here is my code which does not work:

```<code>if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() ))  {
            phone.addClass("needsfilled");
            phone.val(phonerror);
        }
</code>```

HTML
<input id="phone" type="text" value=""  name="phone" />

答: Instead of using preg_match, which is a PHP function, you should use the String object's match function. See the Mozilla docs for information on using the match function.

Title: How can I use preg_match in jQuery?

Body:
Can I use preg_match to validate phone number in jQuery? Here is my code which does not work:

if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() ))  {
            phone.addClass("needsfilled");
            phone.val(phonerror);
        }

HTML
<input id="phone" type="text" value=""  name="phone" />


问:
Dynamodb ondemand cost and scaling during hot partition(adaptive scaling)
I can understand the provisioned DB cost but there are few questions regd on-demand nodes.

does OnDemand pricing only considers the sum of WRU used by each partition or the overall WRU for the table based on the usage pattern which will be shared by each partition.

when there is a hot partition, does OnDemand increase WRU only for that partition or increases the overall WRU of the table.

does adaptive capacity work with OnDemand DB

ex:
OnDemand DB with 10 partitions and current peak at 1000WRU.
if 2 hot partitions require more than 300WRU will it use from adaptive capacity or increase the overall WRU to 3000WRU resulting in high cost?

答:
I'm not a DynamoDB insider, so I can only answer from what I understand from their documentation.

In on-demand pricing (see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html#HowItWorks.OnDemand) you pay exactly by the number and size of your requests. If you make one million requests, you will pay the same whether these requests were to a million different partitions, or they all went to the same partition.

You might wonder, then, why there was such an issue of load imbalance pricing in provisioned-capacity pricing - or at least why is the Web full of stories of such an issue. There should never have been such an issue, but in the past there was. But since recently, this isn't an issue any more. Here is the story:

In the provisioned pricing page, Amazon claims that if you reserve 1000 WCU, you should be able to use this number of write units that you paid for, per second, and if you try to use more, you'll be throttled. There is no mention or warning of imbalanced loads or hot partitions... But people discovered that this wasn't quite true - Amazon had a bug in their throttling code: The usage counting wasn't done across the entire cluster. Instead, if your data was spread over 10 nodes, your reservation of 1000 was evenly split among them, so each of the 10 nodes would start to throttle you after 100 (1000/10) requests per second. This split worked well for well-balanced loads, but with hot partitions, it didn't work well. People were paying for a reservation of 1000 but when they measured how much they were getting, they saw throttling after just 800 (for example) requests per second. Amazon acknowledge this was a bug, and fixed it with their "adaptive capacity" technique where each of the nodes picks a different throttling limit, modified until the user's total usage approaches what he had paid for. This technique is explained in this excellent official talk
https://www.youtube.com/watch?v=yvBR71D0nAQ - see time 19:38. Until very recently this "adaptive capacity" was a very blunt instrument, which only worked well if your workload doesn't change quickly, but since then, this issue was fixed too - as described in

https://aws.amazon.com/blogs/database/how-amazon-dynamodb-adaptive-capacity-accommodates-uneven-data-access-patterns-or-why-what-you-know-about-dynamodb-might-be-outdated/


问:
unable to clear my sharedPreferences using editor.clear().commit();
I am working on an android project where I have a scenario such as :

I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.

but the problem is when I closed activity and again open that activity; my data still visible in TextView.

even when I cleared it in onDestroy().

here is my code for send data :

```<code> SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = settings.edit();
 editor.putString("address", (String) Address);
 editor.commit();
 finish();
</code>```

here is my code to set and clear data:

```<code> @Override
protected void onResume() {

    super.onResume();
    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    String n = settings.getString("name", "");
    String a = settings.getString("address", "");
    name.setText(n);
    location.setText(a);
}

@Override
protected void onDestroy() {

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}
</code>```

here is my preference manager class :

```<code>   public class PrefManager {

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "sara";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.clear().commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }
}
</code>```

And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.

答:
Try check the logs to make sure you are really going 'onDestory' well.

```<code>@Override
protected void onDestroy() {
    Log.d("address", "onDestory");

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}
</code>```

There is no problem with the code for creating and removing SharedPreferences.

Body:
I am working on an android project where I have a scenario such as :

I used place picker.and data that place picker gave is sent to different activities using shared preference.and show this data in TextView.

but the problem is when I closed activity and again open that activity; my data still visible in TextView.

even when I cleared it in onDestroy().

here is my code for send data :

 SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = settings.edit();
 editor.putString("address", (String) Address);
 editor.commit();
 finish();

here is my code to set and clear data:

 @Override
protected void onResume() {

    super.onResume();
    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    String n = settings.getString("name", "");
    String a = settings.getString("address", "");
    name.setText(n);
    location.setText(a);
}

@Override
protected void onDestroy() {

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}

here is my preference manager class :

   public class PrefManager {

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Context _context;

    // shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "sara";

    private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setFirstTimeLaunch(boolean isFirstTime) {
        editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
        editor.clear().commit();
    }

    public boolean isFirstTimeLaunch() {
        return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
    }
}

And please don't mark this question as duplicate because I see every related questions and see answers. I tried every possible solutions but nothing worked for me. I am new to android so please help me.

Body:
Try check the logs to make sure you are really going 'onDestory' well.

@Override
protected void onDestroy() {
    Log.d("address", "onDestory");

    SharedPreferences settings = getSharedPreferences("address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("address");
    editor.clear().commit();
    super.onDestroy();
}

There is no problem with the code for creating and removing SharedPreferences.


问:
XSL Combine Multiple Fields into New Field in Order
I'd like to create new elements. Each new element should contain the record key and the First Code Element and the first occurrence of Code_Text element. The process would repeat for each of the Code and Code_Text elements as theoretically, there should be an equal number of both. The same XSL would also be applied to the Opinion/Opinion_Text and Reason/Reason_Text value pairs.

I'm using a previous 1.0 solution from an earlier question, but not sure how to modify it. When testing, I only have access to version 1.0. 2.0 is only available on the server. I like 2.0 as it is easier to understand but either would work. In Java, I would just loop though the elements, build an array or list and then output when I done. Not sure how to do this in XSL. Also, there are many more elements in my file that what is shown and I prefer a generic solution that could be tailored to different XML file layouts. Basically, I would like to copy everything and then loop through the value pairs joined with the record key outputting each into a new element with the same name. I've been reading that using  isn't an optimal solution but do not understand why in my use case. Is there a way to loop through the data, accumulate the values I want and then pass them to an output template or is that the wrong path to a solution?

```<code>Input

<?xml version="1.0" encoding="UTF-8"?>
<Data>
   <Record>
      <Date>10/12/2019</Date>
      <Code>F1</Code>
      <Code>F2</Code>
      <Code>F13</Code>
      <Code>F9</Code>
      <Code>F10</Code>
      <Code>F11</Code>
      <Code_Text>F1 Text</Code_Text>
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F13 Text</Code_Text>
      <Code_Text>F9 Text</Code_Text>
      <Code_Text>F10 Text</Code_Text>
      <Code_Text>F11 Text</Code_Text>
      <Key>12345</Key>
      <Number>09095I</Number>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O3</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O7</Opinion>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O3 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason>R4</Reason>
      <Reason>R3</Reason>
      <Reason>R5</Reason>
      <Reason>R6</Reason>
      <Reason>R7</Reason>
      <Reason>R8</Reason>
      <Reason>R9</Reason>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      <Reason_Text>R4 Text</Reason_Text>
      <Reason_Text>R3 Text</Reason_Text>
      <Reason_Text>R5 Text</Reason_Text>
      <Reason_Text>R6 Text</Reason_Text>
      <Reason_Text>R7 Text</Reason_Text>
      <Reason_Text>R8 Text</Reason_Text>
      <Reason_Text>R9 Text</Reason_Text>
      <Summary>Record 1: Summary 1 Text</Summary>
      <Summary>Record 2: Summary 1 Text</Summary>
      <Text_Field_1>Record 1 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_1>Record 2 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_2>Record 1 Key 1: This is Text_Field_2</Text_Field_2>
      <Text_Field_2>Record 2 Key 1: This is Text_Field_2</Text_Field_2>
   </Record>
   <Record>
      <Date>01/12/2020</Date>
      <Code>F12</Code>
      <Code>F2</Code>
      <Code>F3</Code>
      <Code>F4</Code>
      <Code>F5</Code>
      <Code_Text>F12 Text</Code_Text>
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F3 Text</Code_Text>
      <Code_Text>F4 Text</Code_Text>
      <Code_Text>F5 Text</Code_Text>
      <Key>23456</Key>
      <Number>43095I</Number>
      <Opinion>O8</Opinion>
      <Opinion>O9</Opinion>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O6</Opinion>
      <Opinion>O7</Opinion>
      <Opinion_Text>O8 Text</Opinion_Text>
      <Opinion_Text>O9 Text</Opinion_Text>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O6 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Reason>R11</Reason>
      <Reason>R4</Reason>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason>R5</Reason>
      <Reason>R6</Reason>
      <Reason>R7</Reason>
      <Reason>R8</Reason>
      <Reason>R10</Reason>
      <Reason>R9</Reason>
      <Reason_Text>R11 Text</Reason_Text>
      <Reason_Text>R4 Text</Reason_Text>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      <Reason_Text>R5 Text</Reason_Text>
      <Reason_Text>R6 Text</Reason_Text>
      <Reason_Text>R7 Text</Reason_Text>
      <Reason_Text>R8 Text</Reason_Text>
      <Reason_Text>R10 Text</Reason_Text>
      <Reason_Text>R9 Text</Reason_Text>
      <Summary>Record 1: Summary 1 Text</Summary>
      <Summary>Record 2: Summary 1 Text</Summary>
      <Summary>Record 3: Summary 1 Text</Summary>
      <Text_Field_1>Record 1 Key 2: This is Text Field 1</Text_Field_1>
      <Text_Field_1>Record 2 Key 2: This is Text Field 1</Text_Field_1>
      <Text_Field_1>Record 3 Key 2: This is Text_Field_1</Text_Field_1>
      <Text_Field_1>Record 3 Key 2: This is Text_Field_2</Text_Field_1>
      <Text_Field_2>Record 1 Key 2: This is Text_Field_2</Text_Field_2>
      <Text_Field_2>Record 2 Key 2: This is Text_Field_2</Text_Field_2>
   </Record>
   <Record>
      <Date>10/12/2019</Date>
      <Code>F2</Code>
      <Code>F3</Code>
      <Code>F4</Code>
      <Code>F5</Code>
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F3 Text</Code_Text>
      <Code_Text>F4 Text</Code_Text>
      <Code_Text>F5 Text</Code_Text>
      <Key>778899</Key>
      <Number>998822I</Number>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O3</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O6</Opinion>
      <Opinion>O7</Opinion>
      <Opinion>O8</Opinion>
      <Opinion>O9</Opinion>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O3 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O6 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Opinion_Text>O8 Text</Opinion_Text>
      <Opinion_Text>O9 Text</Opinion_Text>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      <Summary>Record 1: Summary 1 Text</Summary>
      <Text_Field_1>Record 3 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_2>Record 3 Key 1: This is Text_Field_2</Text_Field_2>
   </Record>
</Data>
</code>```

Desired Output

```<code><?xml version="1.0" encoding="UTF-8"?>
<Data>
    <Record>
        <Date>10/12/2019</Date>
        <Code>F1</Code>
        <Code>F2</Code>
        <Code>F13</Code>
        <Code>F9</Code>
        <Code>F10</Code>
        <Code>F11</Code>
        <Code_Text>F1 Text</Code_Text>
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F13 Text</Code_Text>
        <Code_Text>F9 Text</Code_Text>
        <Code_Text>F10 Text</Code_Text>
        <Code_Text>F11 Text</Code_Text>
        <Code_Combined>12345|F1|F1 Text</Code_Combined>
        <Code_Combined>12345|F2|F2 Text</Code_Combined>
        <Code_Combined>12345|F13|F13 Text</Code_Combined>
        <Code_Combined>12345|F9|F9 Text</Code_Combined>
        <Code_Combined>12345|F10|F10 Text</Code_Combined>
        <Code_Combined>12345|F11|F11 Text</Code_Combined>
        <Key>12345</Key>
        <Number>09095I</Number>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O3</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O7</Opinion>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O3 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Combined>12345|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>12345|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>12345|O3|O3 Text</Opinion_Combined>
        <Opinion_Combined>12345|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>12345|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>12345|O7|O7 Text</Opinion_Combined>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason>R4</Reason>
        <Reason>R3</Reason>
        <Reason>R5</Reason>
        <Reason>R6</Reason>
        <Reason>R7</Reason>
        <Reason>R8</Reason>
        <Reason>R9</Reason>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Text>R4 Text</Reason_Text>
        <Reason_Text>R3 Text</Reason_Text>
        <Reason_Text>R5 Text</Reason_Text>
        <Reason_Text>R6 Text</Reason_Text>
        <Reason_Text>R7 Text</Reason_Text>
        <Reason_Text>R8 Text</Reason_Text>
        <Reason_Text>R9 Text</Reason_Text>
        <Reason_Combined>12345|R1|R1 Text</Reason_Combined>
        <Reason_Combined>12345|R2|R2 Text</Reason_Combined>
        <Reason_Combined>12345|R4|R4 Text</Reason_Combined>
        <Reason_Combined>12345|R3|R3 Text</Reason_Combined>
        <Reason_Combined>12345|R5|R5 Text</Reason_Combined>
        <Reason_Combined>12345|R6|R6 Text</Reason_Combined>
        <Reason_Combined>12345|R7|R7 Text</Reason_Combined>
        <Reason_Combined>12345|R8|R8 Text</Reason_Combined>
        <Reason_Combined>12345|R9|R9 Text</Reason_Combined>
        <Summary>Record 1: Summary 1 Text</Summary>
        <Summary>Record 2: Summary 1 Text</Summary>
        <Text_Field_1>Record 1 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_1>Record 2 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_2>Record 1 Key 1: This is Text_Field_2</Text_Field_2>
        <Text_Field_2>Record 2 Key 1: This is Text_Field_2</Text_Field_2>
    </Record>
    <Record>
        <Date>01/12/2020</Date>
        <Code>F12</Code>
        <Code>F2</Code>
        <Code>F3</Code>
        <Code>F4</Code>
        <Code>F5</Code>
        <Code_Text>F12 Text</Code_Text>
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F3 Text</Code_Text>
        <Code_Text>F4 Text</Code_Text>
        <Code_Text>F5 Text</Code_Text>
        <Code_Combined>23456|F12|F12 Text</Code_Combined>
        <Code_Combined>23456|F2|F2 Text</Code_Combined>
        <Code_Combined>23456|F3|F3 Text</Code_Combined>
        <Code_Combined>23456|F4|F4 Text</Code_Combined>
        <Code_Combined>23456|F5|F5 Text</Code_Combined>
        <Key>23456</Key>
        <Number>43095I</Number>
        <Opinion>O8</Opinion>
        <Opinion>O9</Opinion>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O6</Opinion>
        <Opinion>O7</Opinion>
        <Opinion_Text>O8 Text</Opinion_Text>
        <Opinion_Text>O9 Text</Opinion_Text>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O6 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Combined>23456|O8|O8 Text</Opinion_Combined>
        <Opinion_Combined>23456|O9|O9 Text</Opinion_Combined>
        <Opinion_Combined>23456|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>23456|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>23456|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>23456|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>23456|O6|O6 Text</Opinion_Combined>
        <Opinion_Combined>23456|O7|O7 Text</Opinion_Combined>
        <Reason>R11</Reason>
        <Reason>R4</Reason>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason>R5</Reason>
        <Reason>R6</Reason>
        <Reason>R7</Reason>
        <Reason>R8</Reason>
        <Reason>R10</Reason>
        <Reason>R9</Reason>
        <Reason_Text>R11 Text</Reason_Text>
        <Reason_Text>R4 Text</Reason_Text>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Text>R5 Text</Reason_Text>
        <Reason_Text>R6 Text</Reason_Text>
        <Reason_Text>R7 Text</Reason_Text>
        <Reason_Text>R8 Text</Reason_Text>
        <Reason_Text>R10 Text</Reason_Text>
        <Reason_Text>R9 Text</Reason_Text>
        <Reason_Combined>23456|R11|R11 Text</Reason_Combined>
        <Reason_Combined>23456|R4|R4 Text</Reason_Combined>
        <Reason_Combined>23456|R1|R1 Text</Reason_Combined>
        <Reason_Combined>23456|R2|R2 Text</Reason_Combined>
        <Reason_Combined>23456|R5|R5 Text</Reason_Combined>
        <Reason_Combined>23456|R6|R6 Text</Reason_Combined>
        <Reason_Combined>23456|R7|R7 Text</Reason_Combined>
        <Reason_Combined>23456|R8|R8 Text</Reason_Combined>
        <Reason_Combined>23456|R10|R10 Text</Reason_Combined>
        <Reason_Combined>23456|R9|R9 Text</Reason_Combined>
        <Summary>Record 1: Summary 1 Text</Summary>
        <Summary>Record 2: Summary 1 Text</Summary>
        <Summary>Record 3: Summary 1 Text</Summary>
        <Text_Field_1>Record 1 Key 2: This is Text Field 1</Text_Field_1>
        <Text_Field_1>Record 2 Key 2: This is Text Field 1</Text_Field_1>
        <Text_Field_1>Record 3 Key 2: This is Text_Field_1</Text_Field_1>
        <Text_Field_1>Record 3 Key 2: This is Text_Field_2</Text_Field_1>
        <Text_Field_2>Record 1 Key 2: This is Text_Field_2</Text_Field_2>
        <Text_Field_2>Record 2 Key 2: This is Text_Field_2</Text_Field_2>
    </Record>
    <Record>
        <Date>10/12/2019</Date>
        <Code>F2</Code>
        <Code>F3</Code>
        <Code>F4</Code>
        <Code>F5</Code>
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F3 Text</Code_Text>
        <Code_Text>F4 Text</Code_Text>
        <Code_Text>F5 Text</Code_Text>
        <Code_Combined>778899|F2|F2 Text</Code_Combined>
        <Code_Combined>778899|F3|F3 Text</Code_Combined>
        <Code_Combined>778899|F4|F4 Text</Code_Combined>
        <Code_Combined>778899|F5|F5 Text</Code_Combined>
        <Key>778899</Key>
        <Number>998822I</Number>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O3</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O6</Opinion>
        <Opinion>O7</Opinion>
        <Opinion>O8</Opinion>
        <Opinion>O9</Opinion>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O3 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O6 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Text>O8 Text</Opinion_Text>
        <Opinion_Text>O9 Text</Opinion_Text>
        <Opinion_Combined>778899|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>778899|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>778899|O3|O3 Text</Opinion_Combined>
        <Opinion_Combined>778899|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>778899|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>778899|O6|O6 Text</Opinion_Combined>
        <Opinion_Combined>778899|O7|O7 Text</Opinion_Combined>
        <Opinion_Combined>778899|O8|O8 Text</Opinion_Combined>
        <Opinion_Combined>778899|O9|O9 Text</Opinion_Combined>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Combined>778899|R1|R1 Text</Reason_Combined>
        <Reason_Combined>778899|R2|R2 Text</Reason_Combined>
        <Summary>Record 1: Summary 1 Text</Summary>
        <Text_Field_1>Record 3 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_2>Record 3 Key 1: This is Text_Field_2</Text_Field_2>
    </Record>
</Data>
</code>```

Original Code

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="no" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Record">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
            <Combined>
                <xsl:for-each select="*[not(self::Date)]">
                    <xsl:choose>
                        <xsl:when test="name() = name(preceding-sibling::*[1])">, </xsl:when>
                        <xsl:when test="position() = 1" />
                        <xsl:otherwise>|</xsl:otherwise>
                    </xsl:choose>
                    <xsl:value-of select="." />
                </xsl:for-each>
            </Combined>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
If you can use xsl-2.0, you can use the xsl:for-each-group function using group-adjacent

We will group nodes ending with _Text. Use this template (read explanations in comments):

```<code><xsl:template match="Record">
    <xsl:variable name="key" select="Key"/>
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::*[ends-with(local-name(), '_Text')])">
        <!-- test if a node ends with '_Text', boolean will return either true or false -->
            <xsl:choose>
                <!-- when true -->
                <xsl:when test="current-grouping-key()">
                    <!-- copies the current group  -->
                    <xsl:copy-of select="current-group()"/>
                    <!-- process each node of the current group  -->
                    <xsl:for-each select="current-group()">
                        <xsl:variable name="new_name" select="concat(
                            substring-before(current-group()[1]/local-name(), '_'),
                            '_Combined')"/>
                        <xsl:element name="{$new_name}">
                            <xsl:value-of select="concat($key, '|', substring-before(., ' '), '|', .)"/>
                        </xsl:element>
                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>
</code>```

See it in action here: http://xsltransform.net/eiouzkP.

Body:
I'd like to create new elements. Each new element should contain the record key and the First Code Element and the first occurrence of Code_Text element. The process would repeat for each of the Code and Code_Text elements as theoretically, there should be an equal number of both. The same XSL would also be applied to the Opinion/Opinion_Text and Reason/Reason_Text value pairs.

I'm using a previous 1.0 solution from an earlier question, but not sure how to modify it. When testing, I only have access to version 1.0. 2.0 is only available on the server. I like 2.0 as it is easier to understand but either would work. In Java, I would just loop though the elements, build an array or list and then output when I done. Not sure how to do this in XSL. Also, there are many more elements in my file that what is shown and I prefer a generic solution that could be tailored to different XML file layouts. Basically, I would like to copy everything and then loop through the value pairs joined with the record key outputting each into a new element with the same name. I've been reading that using  isn't an optimal solution but do not understand why in my use case. Is there a way to loop through the data, accumulate the values I want and then pass them to an output template or is that the wrong path to a solution?

Input

<?xml version="1.0" encoding="UTF-8"?>
<Data>
   <Record>
      <Date>10/12/2019</Date>
      F1
      F2
      F13
      F9
      F10
      F11
      <Code_Text>F1 Text</Code_Text>
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F13 Text</Code_Text>
      <Code_Text>F9 Text</Code_Text>
      <Code_Text>F10 Text</Code_Text>
      <Code_Text>F11 Text</Code_Text>
      <Key>12345</Key>
      <Number>09095I</Number>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O3</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O7</Opinion>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O3 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason>R4</Reason>
      <Reason>R3</Reason>
      <Reason>R5</Reason>
      <Reason>R6</Reason>
      <Reason>R7</Reason>
      <Reason>R8</Reason>
      <Reason>R9</Reason>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      <Reason_Text>R4 Text</Reason_Text>
      <Reason_Text>R3 Text</Reason_Text>
      <Reason_Text>R5 Text</Reason_Text>
      <Reason_Text>R6 Text</Reason_Text>
      <Reason_Text>R7 Text</Reason_Text>
      <Reason_Text>R8 Text</Reason_Text>
      <Reason_Text>R9 Text</Reason_Text>
      Record 1: Summary 1 Text
      Record 2: Summary 1 Text
      <Text_Field_1>Record 1 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_1>Record 2 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_2>Record 1 Key 1: This is Text_Field_2</Text_Field_2>
      <Text_Field_2>Record 2 Key 1: This is Text_Field_2</Text_Field_2>
   </Record>
   <Record>
      <Date>01/12/2020</Date>
      F12
      F2
      F3
      F4
      F5
      <Code_Text>F12 Text</Code_Text>
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F3 Text</Code_Text>
      <Code_Text>F4 Text</Code_Text>
      <Code_Text>F5 Text</Code_Text>
      <Key>23456</Key>
      <Number>43095I</Number>
      <Opinion>O8</Opinion>
      <Opinion>O9</Opinion>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O6</Opinion>
      <Opinion>O7</Opinion>
      <Opinion_Text>O8 Text</Opinion_Text>
      <Opinion_Text>O9 Text</Opinion_Text>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O6 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Reason>R11</Reason>
      <Reason>R4</Reason>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason>R5</Reason>
      <Reason>R6</Reason>
      <Reason>R7</Reason>
      <Reason>R8</Reason>
      <Reason>R10</Reason>
      <Reason>R9</Reason>
      <Reason_Text>R11 Text</Reason_Text>
      <Reason_Text>R4 Text</Reason_Text>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      <Reason_Text>R5 Text</Reason_Text>
      <Reason_Text>R6 Text</Reason_Text>
      <Reason_Text>R7 Text</Reason_Text>
      <Reason_Text>R8 Text</Reason_Text>
      <Reason_Text>R10 Text</Reason_Text>
      <Reason_Text>R9 Text</Reason_Text>
      Record 1: Summary 1 Text
      Record 2: Summary 1 Text
      Record 3: Summary 1 Text
      <Text_Field_1>Record 1 Key 2: This is Text Field 1</Text_Field_1>
      <Text_Field_1>Record 2 Key 2: This is Text Field 1</Text_Field_1>
      <Text_Field_1>Record 3 Key 2: This is Text_Field_1</Text_Field_1>
      <Text_Field_1>Record 3 Key 2: This is Text_Field_2</Text_Field_1>
      <Text_Field_2>Record 1 Key 2: This is Text_Field_2</Text_Field_2>
      <Text_Field_2>Record 2 Key 2: This is Text_Field_2</Text_Field_2>
   </Record>
   <Record>
      <Date>10/12/2019</Date>
      F2
      F3
      F4
      F5
      <Code_Text>F2 Text</Code_Text>
      <Code_Text>F3 Text</Code_Text>
      <Code_Text>F4 Text</Code_Text>
      <Code_Text>F5 Text</Code_Text>
      <Key>778899</Key>
      <Number>998822I</Number>
      <Opinion>O1</Opinion>
      <Opinion>O2</Opinion>
      <Opinion>O3</Opinion>
      <Opinion>O4</Opinion>
      <Opinion>O5</Opinion>
      <Opinion>O6</Opinion>
      <Opinion>O7</Opinion>
      <Opinion>O8</Opinion>
      <Opinion>O9</Opinion>
      <Opinion_Text>O1 Text</Opinion_Text>
      <Opinion_Text>O2 Text</Opinion_Text>
      <Opinion_Text>O3 Text</Opinion_Text>
      <Opinion_Text>O4 Text</Opinion_Text>
      <Opinion_Text>O5 Text</Opinion_Text>
      <Opinion_Text>O6 Text</Opinion_Text>
      <Opinion_Text>O7 Text</Opinion_Text>
      <Opinion_Text>O8 Text</Opinion_Text>
      <Opinion_Text>O9 Text</Opinion_Text>
      <Reason>R1</Reason>
      <Reason>R2</Reason>
      <Reason_Text>R1 Text</Reason_Text>
      <Reason_Text>R2 Text</Reason_Text>
      Record 1: Summary 1 Text
      <Text_Field_1>Record 3 Key 1: This is Text_Field_1</Text_Field_1>
      <Text_Field_2>Record 3 Key 1: This is Text_Field_2</Text_Field_2>
   </Record>
</Data>

Desired Output

<?xml version="1.0" encoding="UTF-8"?>
<Data>
    <Record>
        <Date>10/12/2019</Date>
        F1
        F2
        F13
        F9
        F10
        F11
        <Code_Text>F1 Text</Code_Text>
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F13 Text</Code_Text>
        <Code_Text>F9 Text</Code_Text>
        <Code_Text>F10 Text</Code_Text>
        <Code_Text>F11 Text</Code_Text>
        <Code_Combined>12345|F1|F1 Text</Code_Combined>
        <Code_Combined>12345|F2|F2 Text</Code_Combined>
        <Code_Combined>12345|F13|F13 Text</Code_Combined>
        <Code_Combined>12345|F9|F9 Text</Code_Combined>
        <Code_Combined>12345|F10|F10 Text</Code_Combined>
        <Code_Combined>12345|F11|F11 Text</Code_Combined>
        <Key>12345</Key>
        <Number>09095I</Number>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O3</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O7</Opinion>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O3 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Combined>12345|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>12345|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>12345|O3|O3 Text</Opinion_Combined>
        <Opinion_Combined>12345|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>12345|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>12345|O7|O7 Text</Opinion_Combined>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason>R4</Reason>
        <Reason>R3</Reason>
        <Reason>R5</Reason>
        <Reason>R6</Reason>
        <Reason>R7</Reason>
        <Reason>R8</Reason>
        <Reason>R9</Reason>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Text>R4 Text</Reason_Text>
        <Reason_Text>R3 Text</Reason_Text>
        <Reason_Text>R5 Text</Reason_Text>
        <Reason_Text>R6 Text</Reason_Text>
        <Reason_Text>R7 Text</Reason_Text>
        <Reason_Text>R8 Text</Reason_Text>
        <Reason_Text>R9 Text</Reason_Text>
        <Reason_Combined>12345|R1|R1 Text</Reason_Combined>
        <Reason_Combined>12345|R2|R2 Text</Reason_Combined>
        <Reason_Combined>12345|R4|R4 Text</Reason_Combined>
        <Reason_Combined>12345|R3|R3 Text</Reason_Combined>
        <Reason_Combined>12345|R5|R5 Text</Reason_Combined>
        <Reason_Combined>12345|R6|R6 Text</Reason_Combined>
        <Reason_Combined>12345|R7|R7 Text</Reason_Combined>
        <Reason_Combined>12345|R8|R8 Text</Reason_Combined>
        <Reason_Combined>12345|R9|R9 Text</Reason_Combined>
        Record 1: Summary 1 Text
        Record 2: Summary 1 Text
        <Text_Field_1>Record 1 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_1>Record 2 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_2>Record 1 Key 1: This is Text_Field_2</Text_Field_2>
        <Text_Field_2>Record 2 Key 1: This is Text_Field_2</Text_Field_2>
    </Record>
    <Record>
        <Date>01/12/2020</Date>
        F12
        F2
        F3
        F4
        F5
        <Code_Text>F12 Text</Code_Text>
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F3 Text</Code_Text>
        <Code_Text>F4 Text</Code_Text>
        <Code_Text>F5 Text</Code_Text>
        <Code_Combined>23456|F12|F12 Text</Code_Combined>
        <Code_Combined>23456|F2|F2 Text</Code_Combined>
        <Code_Combined>23456|F3|F3 Text</Code_Combined>
        <Code_Combined>23456|F4|F4 Text</Code_Combined>
        <Code_Combined>23456|F5|F5 Text</Code_Combined>
        <Key>23456</Key>
        <Number>43095I</Number>
        <Opinion>O8</Opinion>
        <Opinion>O9</Opinion>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O6</Opinion>
        <Opinion>O7</Opinion>
        <Opinion_Text>O8 Text</Opinion_Text>
        <Opinion_Text>O9 Text</Opinion_Text>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O6 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Combined>23456|O8|O8 Text</Opinion_Combined>
        <Opinion_Combined>23456|O9|O9 Text</Opinion_Combined>
        <Opinion_Combined>23456|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>23456|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>23456|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>23456|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>23456|O6|O6 Text</Opinion_Combined>
        <Opinion_Combined>23456|O7|O7 Text</Opinion_Combined>
        <Reason>R11</Reason>
        <Reason>R4</Reason>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason>R5</Reason>
        <Reason>R6</Reason>
        <Reason>R7</Reason>
        <Reason>R8</Reason>
        <Reason>R10</Reason>
        <Reason>R9</Reason>
        <Reason_Text>R11 Text</Reason_Text>
        <Reason_Text>R4 Text</Reason_Text>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Text>R5 Text</Reason_Text>
        <Reason_Text>R6 Text</Reason_Text>
        <Reason_Text>R7 Text</Reason_Text>
        <Reason_Text>R8 Text</Reason_Text>
        <Reason_Text>R10 Text</Reason_Text>
        <Reason_Text>R9 Text</Reason_Text>
        <Reason_Combined>23456|R11|R11 Text</Reason_Combined>
        <Reason_Combined>23456|R4|R4 Text</Reason_Combined>
        <Reason_Combined>23456|R1|R1 Text</Reason_Combined>
        <Reason_Combined>23456|R2|R2 Text</Reason_Combined>
        <Reason_Combined>23456|R5|R5 Text</Reason_Combined>
        <Reason_Combined>23456|R6|R6 Text</Reason_Combined>
        <Reason_Combined>23456|R7|R7 Text</Reason_Combined>
        <Reason_Combined>23456|R8|R8 Text</Reason_Combined>
        <Reason_Combined>23456|R10|R10 Text</Reason_Combined>
        <Reason_Combined>23456|R9|R9 Text</Reason_Combined>
        Record 1: Summary 1 Text
        Record 2: Summary 1 Text
        Record 3: Summary 1 Text
        <Text_Field_1>Record 1 Key 2: This is Text Field 1</Text_Field_1>
        <Text_Field_1>Record 2 Key 2: This is Text Field 1</Text_Field_1>
        <Text_Field_1>Record 3 Key 2: This is Text_Field_1</Text_Field_1>
        <Text_Field_1>Record 3 Key 2: This is Text_Field_2</Text_Field_1>
        <Text_Field_2>Record 1 Key 2: This is Text_Field_2</Text_Field_2>
        <Text_Field_2>Record 2 Key 2: This is Text_Field_2</Text_Field_2>
    </Record>
    <Record>
        <Date>10/12/2019</Date>
        F2
        F3
        F4
        F5
        <Code_Text>F2 Text</Code_Text>
        <Code_Text>F3 Text</Code_Text>
        <Code_Text>F4 Text</Code_Text>
        <Code_Text>F5 Text</Code_Text>
        <Code_Combined>778899|F2|F2 Text</Code_Combined>
        <Code_Combined>778899|F3|F3 Text</Code_Combined>
        <Code_Combined>778899|F4|F4 Text</Code_Combined>
        <Code_Combined>778899|F5|F5 Text</Code_Combined>
        <Key>778899</Key>
        <Number>998822I</Number>
        <Opinion>O1</Opinion>
        <Opinion>O2</Opinion>
        <Opinion>O3</Opinion>
        <Opinion>O4</Opinion>
        <Opinion>O5</Opinion>
        <Opinion>O6</Opinion>
        <Opinion>O7</Opinion>
        <Opinion>O8</Opinion>
        <Opinion>O9</Opinion>
        <Opinion_Text>O1 Text</Opinion_Text>
        <Opinion_Text>O2 Text</Opinion_Text>
        <Opinion_Text>O3 Text</Opinion_Text>
        <Opinion_Text>O4 Text</Opinion_Text>
        <Opinion_Text>O5 Text</Opinion_Text>
        <Opinion_Text>O6 Text</Opinion_Text>
        <Opinion_Text>O7 Text</Opinion_Text>
        <Opinion_Text>O8 Text</Opinion_Text>
        <Opinion_Text>O9 Text</Opinion_Text>
        <Opinion_Combined>778899|O1|O1 Text</Opinion_Combined>
        <Opinion_Combined>778899|O2|O2 Text</Opinion_Combined>
        <Opinion_Combined>778899|O3|O3 Text</Opinion_Combined>
        <Opinion_Combined>778899|O4|O4 Text</Opinion_Combined>
        <Opinion_Combined>778899|O5|O5 Text</Opinion_Combined>
        <Opinion_Combined>778899|O6|O6 Text</Opinion_Combined>
        <Opinion_Combined>778899|O7|O7 Text</Opinion_Combined>
        <Opinion_Combined>778899|O8|O8 Text</Opinion_Combined>
        <Opinion_Combined>778899|O9|O9 Text</Opinion_Combined>
        <Reason>R1</Reason>
        <Reason>R2</Reason>
        <Reason_Text>R1 Text</Reason_Text>
        <Reason_Text>R2 Text</Reason_Text>
        <Reason_Combined>778899|R1|R1 Text</Reason_Combined>
        <Reason_Combined>778899|R2|R2 Text</Reason_Combined>
        Record 1: Summary 1 Text
        <Text_Field_1>Record 3 Key 1: This is Text_Field_1</Text_Field_1>
        <Text_Field_2>Record 3 Key 1: This is Text_Field_2</Text_Field_2>
    </Record>
</Data>

Original Code

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="no" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Record">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
            <Combined>
                <xsl:for-each select="*[not(self::Date)]">
                    <xsl:choose>
                        <xsl:when test="name() = name(preceding-sibling::*[1])">, </xsl:when>
                        <xsl:when test="position() = 1" />
                        <xsl:otherwise>|</xsl:otherwise>
                    </xsl:choose>
                    <xsl:value-of select="." />
                </xsl:for-each>
            </Combined>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Body:
If you can use xsl-2.0, you can use the xsl:for-each-group function using group-adjacent

We will group nodes ending with _Text. Use this template (read explanations in comments):

<xsl:template match="Record">
    <xsl:variable name="key" select="Key"/>
    <xsl:copy>
        <xsl:for-each-group select="*" group-adjacent="boolean(self::*[ends-with(local-name(), '_Text')])">
        <!-- test if a node ends with '_Text', boolean will return either true or false -->
            <xsl:choose>
                <!-- when true -->
                <xsl:when test="current-grouping-key()">
                    <!-- copies the current group  -->
                    <xsl:copy-of select="current-group()"/>
                    <!-- process each node of the current group  -->
                    <xsl:for-each select="current-group()">
                        <xsl:variable name="new_name" select="concat(
                            substring-before(current-group()[1]/local-name(), '_'),
                            '_Combined')"/>
                        <xsl:element name="{$new_name}">
                            <xsl:value-of select="concat($key, '|', substring-before(., ' '), '|', .)"/>
                        </xsl:element>
                    </xsl:for-each>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

See it in action here: http://xsltransform.net/eiouzkP.


问:
Kafka Topic And Offset
I have a question,Suppose there is a TOPIC T1 and there are two Consumer C1 and C2 belongs to two different groups and current offset is 0.We know that Kafka maintains the Offset for consumer.So if C1 consume the message and Offset becomes 1 then what will happen if C2 consume the message will it start from 1 offset or it will start consume the message from 0 offset?. Means how offset will be maintains for two different consumer Group?.

Thanks

答: Kafka maintains the consumer offsets per consumer group, topic and partition, which means, if you have multiple consumers with different consumer groups on the same topic, it will maintain the offset for each group individually. So, in that case, if consumer 1 reads messages, the offset for consumer 2 will not be affected, as long as it belongs to a different consumer group.</p>

Title: Kafka Topic And Offset


答:
I would just use .reduce

console.log(
    [2,5,3,1].reduce(function(carry, current) {
        return carry + '.conversations[' + current +']';
    }, 'myObject')
)```
</div>
</div>
</p>

<p>And if you want the actual object (not the string path), it's as simple as:</p>

```[2,5,3,1].reduce(function(carry, current) {
    return carry.conversations[current];
}, myObject)
```

<p>Or if you want to only pass in <code>myObject</code> once:</p>

```function conversation(myObject) {
    return function(path) {
        return path.reduce(function(carry, current) {
            return carry.conversations[current];
        }, myObject)
    }
}
```

<p>And then you just do</p>

```var convo = conversation(myObject);

convo([2, 3, 5, 1]);
```

Title: Loop through number array to construct object of index nodes in plain javascript

Body:
I would just use .reduce

console.log(
    [2,5,3,1].reduce(function(carry, current) {
        return carry + '.conversations[' + current +']';
    }, 'myObject')
)

And if you want the actual object (not the string path), it's as simple as:

[2,5,3,1].reduce(function(carry, current) {
    return carry.conversations[current];
}, myObject)

Or if you want to only pass in myObject once:

function conversation(myObject) {
    return function(path) {
        return path.reduce(function(carry, current) {
            return carry.conversations[current];
        }, myObject)
    }
}

And then you just do

var convo = conversation(myObject);

convo([2, 3, 5, 1]);


问:
How do I copy all data from one Mongodb Cloud Project to another?
I have two projects on cloud.mongodb.com. One for staging, another - for prodution.

I need to quickly synchronize staging with production for debugging. Just erase everything on the staging and fill it with production data. How do I do that?

Trying mongomirror, but it seems require for cluster tiers to be the same. I want to keep using free tier on staging and whateve larger tier on produciton.

答:
Install mongodb tools:

```<code>brew tap mongodb/brew
brew install mongodb-community
</code>```

Download all data:

```<code>mongodump --uri="mongodb://username:password@<full uri with all replicas>/test?ssl=true&replicaSet=<cluster-name>&authSource=admin"
</code>```

```<code>mongorestore --uri="<the same kind of uri>" <directory or file to restore>
</code>```

Body:
Install mongodb tools:

brew tap mongodb/brew
brew install mongodb-community

Download all data:

mongodump --uri="mongodb://username:password@<full uri with all replicas>/test?ssl=true&replicaSet=<cluster-name>&authSource=admin"

mongorestore --uri="<the same kind of uri>" <directory or file to restore>


问:
How to get the indexpath.row when an element is activated?
I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped.
This is what I currently have, but it always is 0</p>

```<code>var point = Int()
func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)
}
</code>```

答:
Swift 4 and 5

Method 1 using Protocol delegate

For example, you have a UITableViewCell with name MyCell

```<code>class MyCell: UITableViewCell {

    var delegate:MyCellDelegate!

    @IBAction private func myAction(_ sender: UIButton){
        delegate.didPressButton(cell: self)
    }
}
</code>```

Now create a protocol

```<code>protocol MyCellDelegate {
    func didPressButton(cell: UITableViewCell)
}
</code>```

Next step, create an Extension of UITableView

```<code>extension UITableView {
    func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}
</code>```

In your UIViewController implement the protocol MyCellDelegate

```<code>class ViewController: UIViewController, MyCellDelegate {

    func didPressButton(cell: UITableViewCell) {
        if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
              print(indexpath)
        }
    }
}
</code>```

Method 2 using closures

In UIViewController

```<code>override func viewDidLoad() {
        super.viewDidLoad()
       //using the same `UITableView extension` get the IndexPath here
        didPressButton = { cell in
            if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                  print(indexpath)
            }
        }
    }
</code>```
```<code> var didPressButton: ((UITableViewCell) -> Void)

class MyCell: UITableViewCell {

    @IBAction private func myAction(_ sender: UIButton){
        didPressButton(self)
    }
}
</code>```

Note:- if you want to get UICollectionView indexPath you can use this UICollectionView extension and repeat the above steps

```<code>extension UICollectionView {
    func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}
</code>```

Body:
I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped.
This is what I currently have, but it always is 0

var point = Int()
func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)
}

Body:
Swift 4 and 5

Method 1 using Protocol delegate

For example, you have a UITableViewCell with name MyCell

class MyCell: UITableViewCell {

    var delegate:MyCellDelegate!

    @IBAction private func myAction(_ sender: UIButton){
        delegate.didPressButton(cell: self)
    }
}

Now create a protocol

protocol MyCellDelegate {
    func didPressButton(cell: UITableViewCell)
}

Next step, create an Extension of UITableView

extension UITableView {
    func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}

In your UIViewController implement the protocol MyCellDelegate

class ViewController: UIViewController, MyCellDelegate {

    func didPressButton(cell: UITableViewCell) {
        if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
              print(indexpath)
        }
    }
}

Method 2 using closures

In UIViewController

override func viewDidLoad() {
        super.viewDidLoad()
       //using the same `UITableView extension` get the IndexPath here
        didPressButton = { cell in
            if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                  print(indexpath)
            }
        }
    }

 var didPressButton: ((UITableViewCell) -> Void)

class MyCell: UITableViewCell {

    @IBAction private func myAction(_ sender: UIButton){
        didPressButton(self)
    }
}

Note:- if you want to get UICollectionView indexPath you can use this UICollectionView extension and repeat the above steps

extension UICollectionView {
    func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}


问:
Check mutiple values in Array and append third value in html
I want to check if mutiple vlaues exists in the array, and if they do, append the value of a third one- the script below obvously doesnt work, but might give a good idea on what I want to do. i only want to add this once, even if the array checks several times.

What's the best way to do this?

var names = {
  list: [{
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue"
    }, {
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue",
    }
    "model": "round",
    "type": "Special",
    "typedescription": "appendedvalue"
  },
  {
    "model": "square",
    "type": "Special",
    "typedescription": "appendedvalue"
  }]

};

if ($.inArray('model.round', 'type.special'
    names) !== -1) {
  $('.test').append('
' + typedescription.appendedvalue + '
');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

答:
You can use .find to try to find a matching object. Put the test (of whether the object has the model and type you want) in the callback. If it exists, append the property:

var names = {
  list: [{
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue"
    }, {
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue",
    }, {
    "model": "round",
    "type": "Special",
    "typedescription": "appendedvalue"
  },
  {
    "model": "square",
    "type": "Special",
    "typedescription": "appendedvalue"
  }]

};

const item = names.list.find(({ model, type }) => model === 'round' && type === 'Special');
if (item) {
  $('.test').append('
' + item.typedescription + '
');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div></code>```

Body:
You can use .find to try to find a matching object. Put the test (of whether the object has the model and type you want) in the callback. If it exists, append the property:

var names = {
  list: [{
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue"
    }, {
      "model": "round",
      "type": "Special",
      "typedescription": "appendedvalue",
    }, {
    "model": "round",
    "type": "Special",
    "typedescription": "appendedvalue"
  },
  {
    "model": "square",
    "type": "Special",
    "typedescription": "appendedvalue"
  }]

};

const item = names.list.find(({ model, type }) => model === 'round' && type === 'Special');
if (item) {
  $('.test').append('<p>' + item.typedescription + '</p>');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div>


问:
Does dart allows users to write platform specific implementation?
If not - are there are any plans to make it so?

I know that dart itself has different backends that might have different implementation. I was curious if users can do the same, e.g. have a function that delegates to one @patch for js runtime and to another @patch in case of dart vm.

答: If you're creating a package, you can export different implementations for different platforms, see here: https://dart.dev/guides/libraries/create-library-packages#conditionally-importing-and-exporting-library-files</p>


问:
continuous log file processing and extract required data using python
I have to analyze a log file which will generate continuously 24*7. So, the data will be huge. I will have credentials to where log file is generating. But how can I get that streaming data ( I mean like any free tools or processes) so that I can use it in my python code to extract some required information from that log stream and will have to prepare a real time dashboard with that data. please tell some possibilities to achieve above task.</p>

答:
You can create a logger in your python code by importing the following:

```<code>import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG) # Creates log file
</code>```

From there, you can use the logger to keep track of specific tasks in your program based off of their importance of the task that you wish to perform:

```<code>logging.info("Stream data recorded successfully")  # Reports events occuring
logging.debug("Running Diagnostics") # Can be used for detailed diagnostic tracking
logging.warning("Unknown File: " + filename) # Issues warnings about runtime events
logging.error("An issue occurred") # reports error without raising an exception
</code>```

After all of that data is collected, you can parse the logs to find the specific messages that you would like to use in the real time dashboard (parse for only errors and warnings for example), without having to display every single message that was sent to the logger. That being said, there is a log parser library package available for python that can be easily installed using pip:

```<code>pip install pylogsparser
</code>```

If you would rather parse manually via python code, this file from Code Hanger is useful to get started and modify based on your specific project.

There is also much more information about logger on python's documentation website, and here is a basic logging tutorial to help you get started. I hope this explanation helped you get started.

Body:
You can create a logger in your python code by importing the following:

import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG) # Creates log file

From there, you can use the logger to keep track of specific tasks in your program based off of their importance of the task that you wish to perform:

logging.info("Stream data recorded successfully")  # Reports events occuring
logging.debug("Running Diagnostics") # Can be used for detailed diagnostic tracking
logging.warning("Unknown File: " + filename) # Issues warnings about runtime events
logging.error("An issue occurred") # reports error without raising an exception

After all of that data is collected, you can parse the logs to find the specific messages that you would like to use in the real time dashboard (parse for only errors and warnings for example), without having to display every single message that was sent to the logger. That being said, there is a log parser library package available for python that can be easily installed using pip:

pip install pylogsparser

If you would rather parse manually via python code, this file from Code Hanger is useful to get started and modify based on your specific project.

There is also much more information about logger on python's documentation website, and here is a basic logging tutorial to help you get started. I hope this explanation helped you get started.