Snippets Collections
import pandas as pd

# Cargar el archivo CSV
input_file = 'input.csv'  # Reemplaza con el nombre de tu archivo CSV
output_file = 'filtered_output.csv'

# Leer el CSV en un DataFrame
df = pd.read_csv(input_file)

# Primer filtro: conservar filas donde 'orden' aparece más de una vez y 'item' contiene la palabra "Tip"
filtered_df = df.groupby('orden').filter(lambda x: (x['item'].str.contains('Tip', case=False, na=False).any()))

# Segundo filtro: eliminar filas donde el campo 'metodo' está vacío
filtered_df = filtered_df[filtered_df['metodo'].notna()]

# Eliminar la columna 'item'
filtered_df = filtered_df.drop(columns=['item'])

# Guardar el DataFrame filtrado en un nuevo archivo CSV
filtered_df.to_csv(output_file, index=False)

print(f'Filtrado completado. Archivo guardado como {output_file}')
#include<iostream>
using namespace std;

int main(){
  
  int n;
  cin>>n;
  for(int j=1;j<+n;i++){
  for( int i=1;j<=n+1-i;j++){
      cout<<j<<" ";
  }
    cout<<endl;
    
    return 0;
  }
using av_motion_api.Data;
using av_motion_api.Models;
using av_motion_api.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Cors;
using System.Text.RegularExpressions;
using SendGrid.Helpers.Mail;
using SendGrid;

namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAll")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly IUserClaimsPrincipalFactory<User> _claimsPrincipalFactory;
        private readonly IConfiguration _configuration;
        private readonly AppDbContext _appDbContext;
        private readonly RoleManager<Role> _roleManager;
        private readonly ILogger<UserController> _logger;

        public UserController(AppDbContext context, UserManager<User> userManager, IUserClaimsPrincipalFactory<User> claimsPrincipalFactory, IConfiguration configuration, RoleManager<Role> roleManager, ILogger<UserController> logger)
        {
            _appDbContext = context;
            _userManager = userManager;
            _claimsPrincipalFactory = claimsPrincipalFactory;
            _configuration = configuration;
            _roleManager = roleManager;
            _logger = logger;
        }

        ////addUser
        //[HttpPost]
        //[Route("Register")]
        //public async Task<IActionResult> Register(UserViewModel uvm)
        //{
        //    var user = await _userManager.FindByEmailAsync(uvm.Email);
        //    int lastUserID = _appDbContext.Users
        //                     .OrderByDescending(u => u.User_ID)
        //                     .Select(u => u.User_ID)
        //                     .FirstOrDefault();

        //    if (user == null)
        //    {
        //        user = new User
        //        {
        //            User_ID = lastUserID + 1,
        //            Name = uvm.Name,
        //            Surname = uvm.Surname,
        //            UserName = uvm.Email,
        //            Email = uvm.Email,
        //            PasswordHash = uvm.Password,
        //            User_Status_ID = uvm.User_Status_ID,
        //            User_Type_ID = uvm.User_Type_ID,
        //            PhoneNumber = uvm.PhoneNumber,
        //            Date_of_Birth = uvm.Date_of_Birth,
        //            ID_Number = uvm.Id_Number,
        //            Physical_Address = uvm.Physical_Address,
        //            Photo = uvm.Photo
        //        };

        //        IdentityResult result = await _userManager.CreateAsync(user, uvm.Password);

        //        if (result.Succeeded)
        //        {
        //            // Assign role based on User_Type_ID
        //            string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
        //            if (!string.IsNullOrEmpty(roleName))
        //            {
        //                var roleResult = await _userManager.AddToRoleAsync(user, roleName);
        //                if (!roleResult.Succeeded)
        //                {
        //                    return BadRequest(roleResult.Errors);
        //                }
        //            }
        //        }
        //        else
        //        {
        //            return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
        //        }
        //    }
        //    else
        //    {
        //        return Forbid("Account already exists.");
        //    }

        //    return Ok();
        //}

        //private string GetRoleNameByUserType(int userTypeId)
        //{
        //    return userTypeId switch
        //    {
        //        1 => "Administrator",
        //        2 => "Employee",
        //        3 => "Member",
        //        _ => string.Empty,
        //    };
        //}

        //addUser
        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("Register")]
        public async Task<IActionResult> Register([FromForm] UserViewModel uvm)
        {
            try
            {
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

                var user = await _userManager.FindByEmailAsync(uvm.Email);
                int lastUserID = _appDbContext.Users
                                 .OrderByDescending(u => u.User_ID)
                                 .Select(u => u.User_ID)
                                 .FirstOrDefault();

                // Validate Phone Number Pattern
                var phoneNumberPattern = @"^\d{10}$";

                bool isValidPhoneNumber = Regex.IsMatch(uvm.PhoneNumber, phoneNumberPattern);

                if (!isValidPhoneNumber) return BadRequest("Enter valid 10-digit phone number.");

                // Validate South African ID number
                if (!IsValidSouthAfricanIDNumber(uvm.Id_Number, uvm.Date_of_Birth))
                {
                    return BadRequest("Enter a valid South African ID number.");
                }

                if (user == null)
                {
                    if (photo != null && photo.Length > 0)
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            await photo.CopyToAsync(memoryStream);
                            var fileBytes = memoryStream.ToArray();
                            string base64Image = Convert.ToBase64String(fileBytes);

                            user = new User
                            {
                                User_ID = lastUserID + 1,
                                Name = uvm.Name,
                                Surname = uvm.Surname,
                                UserName = uvm.Email,
                                Email = uvm.Email,
                                PasswordHash = _userManager.PasswordHasher.HashPassword(null, uvm.Password),
                                User_Status_ID = uvm.User_Status_ID,
                                User_Type_ID = uvm.User_Type_ID,
                                PhoneNumber = uvm.PhoneNumber,
                                Date_of_Birth = uvm.Date_of_Birth,
                                ID_Number = uvm.Id_Number,
                                Physical_Address = uvm.Physical_Address,
                                Photo = base64Image // Store the base64 string of the photo
                            };

                            IdentityResult result = await _userManager.CreateAsync(user);

                            if (result.Succeeded)
                            {
                                // Assign role based on User_Type_ID
                                string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
                                if (!string.IsNullOrEmpty(roleName))
                                {
                                    var roleResult = await _userManager.AddToRoleAsync(user, roleName);
                                    if (!roleResult.Succeeded)
                                    {
                                        return BadRequest(new { Status = "Error", Errors = roleResult.Errors });
                                    }
                                }


                                return Ok(new { Status = "Success", Message = "Your profile has been created successfully!" });
                            }
                            else
                            {
                                return StatusCode(StatusCodes.Status500InternalServerError, result.Errors.FirstOrDefault()?.Description);
                            }
                        }
                    }
                    else
                    {
                        return BadRequest("Photo is required.");
                    }
                }
                else
                {
                    return Forbid("User already exists.");
                }
            }
            catch (DbUpdateException dbEx)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, dbEx.InnerException?.Message ?? "An error occurred while processing your request.");
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

        // Method to validate South African ID number
        private bool IsValidSouthAfricanIDNumber(string idNumber, DateTime dateOfBirth)
        {
            // Check if the ID number is exactly 13 digits long
            if (idNumber.Length != 13 || !long.TryParse(idNumber, out _))
            {
                return false;
            }

            // Validate date of birth (first six digits)
            string dateOfBirthPart = idNumber.Substring(0, 6);
            if (!DateTime.TryParseExact(dateOfBirthPart, "yyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
            {
                return false;
            }

            // Check if the last two digits of the ID number match the last two digits of the year of birth
            if (parsedDate.Year % 100 != dateOfBirth.Year % 100)
            {
                return false;
            }

            // If it passes the length, date of birth, and year checks, it is considered valid
            return true;
        }


        private string GetRoleNameByUserType(int userTypeId)
        {
            return userTypeId switch
            {
                1 => "Administrator",
                2 => "Employee",
                3 => "Member",
                _ => string.Empty,
            };
        }

        [HttpPost]
        [Route("Login")]
        public async Task<ActionResult> Login(LoginViewModel lv)
        {
            var user = await _userManager.FindByNameAsync(lv.Email);

            if (user != null && await _userManager.CheckPasswordAsync(user, lv.Password))
            {
                try
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);
                    return await GenerateJWTToken(user);
                }
                catch (Exception)
                {

                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            else
            {
                return NotFound("Incorrect email or password, Please Try Again");
            }
        }

        [HttpGet]
        private async Task<ActionResult> GenerateJWTToken(User user)
        {
            var role = await _userManager.GetRolesAsync(user);
            IdentityOptions _identityOptions = new IdentityOptions();
            // Create JWT Token
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                // Add user ID claim
                new Claim("userId", user.Id.ToString()),

                new Claim("User_Type_ID", user.User_Type_ID.ToString()),

            };

            if (role.Count() > 0)
            {
                claims.Add(new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
               issuer:  _configuration["Tokens:Issuer"],
               audience: _configuration["Tokens:Audience"],
               claims: claims,
               signingCredentials: credentials,
               expires: DateTime.UtcNow.AddHours(3)
            );

            return Created("", new
            {

                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = user.UserName,

                userTypeId = user.User_Type_ID,
                // Include user ID in the response
                userId = user.Id
            });
        }

        [HttpPost]
        [Route("ChangePassword")]
        public async Task<IActionResult> ChangePassword(int id, ChangePasswordViewModel cpvm)
        {
            var user = await _userManager.FindByIdAsync(id.ToString());
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ChangePasswordAsync(user, cpvm.CurrentPassword, cpvm.NewPassword);
            if (result.Succeeded)
            {
                return Ok("Password changed successfully.");
            }
            else
            {
                return BadRequest(result.Errors);
            }
        }

        [HttpPut]
        [Route("editUser/{id}")]
        public async Task<IActionResult> EditUser(int id, [FromForm] UpdateUserViewModel uv)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                // Read the form data to get the photo file
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

                user.Name = uv.Name;
                user.Surname = uv.Surname;
                user.Email = uv.Email;
                user.Physical_Address = uv.Physical_Address;
                user.PhoneNumber = uv.PhoneNumber;

                if (photo != null && photo.Length > 0)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await photo.CopyToAsync(memoryStream);
                        var fileBytes = memoryStream.ToArray();
                        string base64Image = Convert.ToBase64String(fileBytes);

                        user.Photo = base64Image; // Store the base64 string of the photo
                    }
                }

                // Update the user
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return Ok("User updated successfully.");
                }
                else
                {
                    return BadRequest(result.Errors);
                }
            }
            catch (Exception)
            {
                return BadRequest("An Error Occurred, Please Try Again");
            }
        }


        [HttpDelete]
        [Route("deleteUser/{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                var result = await _userManager.DeleteAsync(user);

                if (result.Succeeded)
                {
                    return Ok();
                }
                else
                {
                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getAllUsers")]
        public IActionResult GetAllUsers()
        {
            try
            {
                var users = _userManager.Users.ToList();


                if (users == null || users.Count == 0)
                {
                    return NotFound("No users found.");
                }

                return Ok(users);
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getUserById/{id}")]
        public async Task<IActionResult> GetUserById(int id)
        {
            try
            {
                var u = await _appDbContext.Users
                                .Include(u => u.User_Status)
                                .Include(u => u.User_Type)
                                .FirstOrDefaultAsync(u => u.Id == id);

                var user = new
                {
                    u.Id,
                    u.Name,
                    u.Surname,
                    u.Email,
                    u.Physical_Address,
                    u.PhoneNumber,
                    u.Date_of_Birth,
                    UserStatus = u.User_Status.User_Status_Description,
                    UserType = u.User_Type.User_Type_Name,
                    u.Photo,
                    u.ID_Number
                };

                return Ok(user);
            }
            catch (Exception ex)
            {
                // Log the exception for debugging
                Console.WriteLine(ex.Message);
                return BadRequest("An error occurred while fetching user details.");
            }
        }


        [HttpGet("GetMemberByUserId/{userId}")]
        public async Task<ActionResult<Member>> GetMemberByUserId(int userId)
        {
            var member = await _appDbContext.Members.FirstOrDefaultAsync(m => m.User_ID == userId);
            if (member == null)
            {
                return NotFound();
            }
            return Ok(member);
        }

        [HttpGet("employee")]
        public async Task<ActionResult<IEnumerable<EmployeeViewModel>>> GetEmployees()
        {
            var query = await( from e in _appDbContext.Employees
                        join u in _appDbContext.Users on e.User_ID equals u.User_ID
                        select new EmployeeViewModel
                        {
                            employee_ID = e.Employee_ID,
                            employee_name = u.Name
                        }).ToListAsync();

            return query;

        }
        //Roles

        [HttpPost]
        [Route("CreateRole")]
        public async Task<IActionResult> CreateRole(string roleName)
        {
            var role = await _roleManager.FindByNameAsync(roleName);
            if (role == null)
            {
                role = new Role
                {
                    Name = roleName,
                    NormalizedName = roleName.ToUpper(),
                    isEditable = true,
                };

                var result = await _roleManager.CreateAsync(role);
                if (!result.Succeeded) return BadRequest(result.Errors);
            }
            else
            {
                return Forbid("Role already exists.");
            }

            return Ok();
        }

        [HttpPost]
        [Route("AssignRole")]
        public async Task<IActionResult> AssignRole(string emailAddress, string roleName)
        {
            var user = await _userManager.FindByEmailAsync(emailAddress);
            if (user == null) return NotFound();

            var result = await _userManager.AddToRoleAsync(user, roleName);
            if (result.Succeeded) return Ok();

            return BadRequest(result.Errors);
        }


        [HttpPost("ForgotPassword")]
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    return BadRequest("Email is required.");
                }

                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    return Ok("User does not exist.");
                }

                var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                var resetLink = Url.Action("ResetPassword", "User",
                                           new { token, email = user.Email },
                                           protocol: HttpContext.Request.Scheme);

                await SendResetPasswordEmail(model.Email, resetLink);

                return Ok("Please check your email for password reset instructions.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                return StatusCode(StatusCodes.Status500InternalServerError, "Error sending reset password email.");
            }
        }

        [HttpPost("ResetPassword")]
        public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("Invalid data.");
            }

            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
            if (result.Succeeded)
            {
                return Ok("Password has been reset successfully.");
            }

            return BadRequest("Error while resetting the password.");
        }

        private async Task SendResetPasswordEmail(string email, string resetLink)
        {
            try
            {
                var apiKey = _configuration["SendGrid:ApiKey"];
                var client = new SendGridClient(apiKey);
                var from = new EmailAddress(_configuration["SendGrid:FromEmail"], _configuration["SendGrid:FromName"]);
                var to = new EmailAddress(email);
                var subject = "Reset Password";
                var htmlContent = $"<h4>Reset your password by <a href='{resetLink}'>clicking here</a></h4>";
                var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);

                var response = await client.SendEmailAsync(msg);
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new Exception($"Failed to send email. Status code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                throw;
            }
        }
    }
}
void deleteNode (node* &head, node* &tail, int position) {
  // delete first node
  if (position == 1) {
    node* temp = head;
    temp -> next -> prev = NULL;
    head = temp -> next;
    temp -> next = NULL;
    delete temp;
    return;
  }
  node* curr = head;
  node* back = NULL;
  int cnt = 1;
  while (cnt < position) {
    back = curr;
    curr = curr -> next;
    cnt++;
  }
  //delete last node 
  if (curr -> next == NULL) {
    tail = back;
    back -> next = NULL;
    curr -> prev = NULL;
    delete curr;
    return;
  }
  // delete in between node 
  back -> next = curr -> next;
  curr -> next -> prev = back;
  curr -> next = NULL;
  curr -> prev = NULL;
  delete curr;
}
void insertAtPosition(node *&head, node *&tail, int position, int d) {
  // insert at start
  if (position == 1) {
    insertAtHead(head, tail, d);
    return;
  }
  node *temp = new node(d);
  node *curr = head;
  int cnt = 1;
  while (cnt < position - 1) {
    curr = curr->next;
    cnt++;
  }
  // insert at last
  if (curr->next == NULL) {
    insertAtTail(tail, head, d);
    return;
  } else {
    temp->next = curr->next;
    curr->next = temp;
    temp->prev = curr;
    curr->next->prev = temp;
  }
}
void insertAtTail(node *&tail, node* &head, int d) {
  node *temp = new node(d);
  if (tail == NULL) {
    tail = head = temp;
  } else {
    tail->next = temp;
    temp->prev = tail;
    tail = temp;
  }
}
void insertAtHead(node *&head, node* & tail, int d) {
  node *temp = new node(d);
  if (head == NULL) {
    head = tail = temp;
  } else {
    head->prev = temp;
    temp->next = head;
    head = temp;
  }
}
int getLen(node *head) {
  int len = 0;
  node *temp = head;
  while (temp != NULL) {
    len++;
    temp = temp->next;
  }
  return len;
}
class node {
public:
  int data;
  node *next;
  node *prev;
  node(int d) {
    this->data = d;
    this->next = NULL;
    this->prev = NULL;
  }
  ~node() {
    int value = this -> data;
    if (next != NULL) {
      delete next;
      next = NULL;
    }
    cout << "memory free for node with data " << value << endl;
  }
};
using av_motion_api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Net.NetworkInformation;
using System.Reflection.Emit;
using System.Security.Claims;
using System.Xml.Linq;

namespace av_motion_api.Data
{
    public class AppDbContext : IdentityDbContext<User, Role, int>

    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        //set tables


        public DbSet<Attendance_List> Attendance_Lists { get; set; }
        public DbSet<Audit_Trail> Audit_Trails { get; set; }
        public DbSet<Booking> Bookings { get; set; }
        public DbSet<Booking_Time_Slot> Booking_Time_Slots { get; set; }
        public DbSet<Contract> Contracts { get; set; }
        public DbSet<Contract_History> Contract_History { get; set; }
        public DbSet<Contract_Type> Contract_Types { get; set; }
        public DbSet<Discount> Discounts { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Employee_Type> Employee_Types { get; set; }
        public DbSet<Equipment> Equipment { get; set; }
        public DbSet<Inspection> Inspection { get; set; }
        public DbSet<Inspection_Status> Inspection_Status { get; set; }
        public DbSet<Inspection_Type> Inspection_Type { get; set; }
        public DbSet<Inventory> Inventory { get; set; }
        public DbSet<Lesson_Plan> Lesson_Plans { get; set; }

        public DbSet<Lesson_Plan_Workout> lesson_Plan_Workout { get; set; }

        public DbSet<Member> Members { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Order_Line> Order_Lines { get; set; }
        public DbSet<Order_Status> Order_Status { get; set; }
        public DbSet<Outstanding_Payment> Outstanding_Payments { get; set; }
        public DbSet<Owner> Owners { get; set; }
        public DbSet<Payment> Payments { get; set; }
        public DbSet<Payment_Method> Payment_Methods { get; set; }
        public DbSet<Payment_Type> Payment_Types { get; set; }
        public DbSet<Price> Prices { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Product_Category> Product_Categories { get; set; }
        public DbSet<Received_Supplier_Order> Received_Supplier_Orders { get; set; }
        public DbSet<Received_Supplier_Order_Line> Received_Supplier_Order_Lines { get; set; }
        public DbSet<Report> Reports { get; set; }
        public DbSet<Reward> Rewards { get; set; }

        public DbSet<Role> Roles { get; set; }
        public DbSet<Reward_Member> Reward_Members { get; set; }
        public DbSet<Reward_Type> Reward_Types { get; set; }
        public DbSet<Shift> Shifts { get; set; }
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<Supplier_Order> Supplier_Orders { get; set; }
        public DbSet<Supplier_Order_Line> Supplier_Order_Lines { get; set; }
        public DbSet<Time_Slot> Time_Slots { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<User_Status> Users_Status{ get; set; }

        public DbSet<User_Type> User_Types { get; set; }
        public DbSet<VAT> VAT { get; set; }

        public DbSet<Workout_Category> Workout_Category { get; set; }
        public DbSet<Workout> Workout { get; set; }
  
        public DbSet<Write_Off> Write_Offs { get; set; }



        protected override void OnModelCreating(ModelBuilder builder)
        {
            //Renaming of Default asp Tables
            builder.Entity<User>().ToTable("Users");
            builder.Entity<IdentityUserRole<int>>().ToTable("User_Roles");
            builder.Entity<IdentityUserLogin<int>>().ToTable("User_Logins");
            builder.Entity<Role>().ToTable("Roles");
            builder.Entity<IdentityRoleClaim<int>>().ToTable("Role_Claims");
            builder.Entity<IdentityUserClaim<int>>().ToTable("User_Claims");
            builder.Entity<IdentityUserToken<int>>().ToTable("Tokens");

            //Validation fix for database, specifying coulm types to be type decimal
            builder.Entity<Contract>()
           .Property(c => c.Initial_Fee)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<VAT>()
            .Property(v => v.VAT_Percentage)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Order>()
           .Property(o => o.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Amount_Due)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Late_Fee)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Payment>()
           .Property(pay => pay.Amount)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Price>()
           .Property(pr => pr.Unit_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order>()
           .Property(so => so.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Discount>()
           .Property(d => d.Discount_Percentage)
           .HasColumnType("decimal(18, 2)");

            //Delete cascade error fix
            builder.Entity<Payment>()
            .HasOne(p => p.Payment_Type)
            .WithMany()
            .HasForeignKey(p => p.Payment_Type_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Supplier_Order_Line>()
             .HasOne(s => s.Product)
             .WithMany()
             .HasForeignKey(s => s.Product_ID)
             .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Supplier_Order_Line>()
            .HasOne(s => s.Supplier)
            .WithMany()
            .HasForeignKey(s => s.Supplier_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Received_Supplier_Order)
            .WithMany()
            .HasForeignKey(r => r.Received_Supplier_Order_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Supplier_Order)
            .WithMany()
            .HasForeignKey(r => r.Supplier_Order_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Product)
            .WithMany()
            .HasForeignKey(r => r.Product_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Member)
            .WithMany()
            .HasForeignKey(op => op.Member_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Payment)
            .WithMany()
            .HasForeignKey(op => op.Payment_ID)
            .OnDelete(DeleteBehavior.NoAction);


            builder.Entity<Booking>()
            .HasOne(b => b.Member)
            .WithMany()
            .HasForeignKey(b => b.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Member)
            .WithMany()
            .HasForeignKey(rm => rm.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Reward)
            .WithMany()
            .HasForeignKey(rm => rm.Reward_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Booking)
            .WithMany()
            .HasForeignKey(bts => bts.Booking_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Time_Slot)
            .WithMany()
            .HasForeignKey(bts => bts.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Attendance_List>()
            .HasOne(b => b.Time_Slot)
            .WithMany()
            .HasForeignKey(b => b.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Workout)
            .WithMany()
            .HasForeignKey(lpw => lpw.Workout_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Lesson_Plan)
            .WithMany()
            .HasForeignKey(lpw => lpw.Lesson_Plan_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Workout>()
           .HasOne(w => w.Workout_Category)
           .WithMany()
           .HasForeignKey(w => w.Workout_Category_ID)
           .IsRequired()
           .OnDelete(DeleteBehavior.Restrict);

            base.OnModelCreating(builder);



            var Contract_Types = new Contract_Type[]
            {
                new Contract_Type { Contract_Type_ID = 1, Contract_Type_Name = "3-Month Membership", Contract_Description = "Three-month gym membership contract" },              
            };
            builder.Entity<Contract_Type>().HasData(Contract_Types);



            var Discounts = new Discount[]
            {
                new Discount { Discount_ID = 1, Discount_Percentage = 10.00m, Discount_Date = new DateTime(2024, 4, 10) }

            };
            builder.Entity<Discount>().HasData(Discounts);


            var Employee_Types = new Employee_Type[]
            {
                new Employee_Type { Employee_Type_ID = 1, Job_Title = "Administrator", Job_Description = "Responsible for managing administrative tasks and operations" }
            };
            builder.Entity<Employee_Type>().HasData(Employee_Types);

            var Inspection_Statuses = new Inspection_Status[]
            {
                new Inspection_Status { Inspection_Status_ID = 1, Inspection_Status_Description= "Pending" }


            };
            builder.Entity<Inspection_Status>().HasData(Inspection_Statuses);

            var Inspection_Types = new Inspection_Type[]
            {
                new Inspection_Type { Inspection_Type_ID = 1, Inspection_Type_Name = "Safety Inspection", Inspection_Type_Criteria = "Ensure compliance with safety standards" }
    
            };
            builder.Entity<Inspection_Type>().HasData(Inspection_Types);

            var Membership_Statuses = new Membership_Status[]
            {
                new Membership_Status { Membership_Status_ID = 1, Membership_Status_Description = "Active" }

            };
            builder.Entity<Membership_Status>().HasData(Membership_Statuses);

            var Newsletters = new Newsletter[]
            {
                new Newsletter { Newsletter_ID = 1, Newsletter_Title = "Fitness Tips", Newsletter_Photo = "fitness_tips.jpg", Newsletter_Description = "Stay updated with our latest fitness tips!" }

            };
            builder.Entity<Newsletter>().HasData(Newsletters);

            var Payment_Methods = new Payment_Method[]
            {
                new Payment_Method { Payment_Method_ID = 1, Payment_Method_Name = "Card" },
                new Payment_Method { Payment_Method_ID = 2, Payment_Method_Name = "EFT" },

  
            };
            builder.Entity<Payment_Method>().HasData(Payment_Methods);

            var Payment_Types = new Payment_Type[]
            {
                new Payment_Type { Payment_Type_ID = 1, Payment_Type_Name = "Online Payment" },
                new Payment_Type { Payment_Type_ID = 2, Payment_Type_Name = "Cash Payment" },
             
            };
            builder.Entity<Payment_Type>().HasData(Payment_Types);

            var Product_Categories = new Product_Category[]
            {
                new Product_Category { Product_Category_ID = 1, Category_Name = "Clothing", Category_Description = "Fitness clothing for various activities" }
            };
            builder.Entity<Product_Category>().HasData(Product_Categories);

            var Reports = new Report[]
            {
                new Report { Report_ID = 1, Report_Name = "Monthly Sales Report", Report_Description = "Report summarizing monthly sales data", Generated_Date = new DateTime(2024, 4, 10) }
            };
            builder.Entity<Report>().HasData(Reports);

            var Reward_Types = new Reward_Type[]
            {
                new Reward_Type { Reward_Type_ID = 1, Reward_Type_Name = "Membership Renewal Discount", Reward_Criteria = "Receive a discount on membership renewal after completing a certain number of workouts" }

            };
            builder.Entity<Reward_Type>().HasData(Reward_Types);

            var Suppliers = new Supplier[]
            {
                new Supplier { Supplier_ID = 1, Name = "FitnessGear", Contact_Number = "1234567890", Email_Address = "info@fitnessgear.com", Physical_Address = "123 Fitness Street, Cityville, South Africa" }
            };
            builder.Entity<Supplier>().HasData(Suppliers);


            var userStatus = new User_Status[]
            {
                new User_Status { User_Status_ID = 1, User_Status_Description = "Actived" },
                new User_Status { User_Status_ID = 2, User_Status_Description = "Deactivated" },
                new User_Status { User_Status_ID = 3, User_Status_Description = "Idle" }
            };
            builder.Entity<User_Status>().HasData(userStatus);

            var userTypes = new User_Type[]
    {
                new User_Type { User_Type_ID = 1, User_Type_Name = "Owner" },
                new User_Type { User_Type_ID = 2, User_Type_Name = "Employee" },
                new User_Type { User_Type_ID = 3, User_Type_Name = "Member" }
    };
            builder.Entity<User_Type>().HasData(userTypes);

            var Users = new User[]                
            {
                new User 
                {
                    User_ID = 1,
                    Id = 1,
                    Name = "Don",
                    Surname = "Percival",
                    ID_Number = "0203057644931",
                    Email = "DonPercival@gmail.com",
                    Physical_Address = "456 Oak Avenue",
                    PhoneNumber = "0734457681",
                    Photo = "DonProfilePic.jpg",
                    PasswordHash = "AEWR54Q35H5T4HRGRGQ",
                    Date_of_Birth = new DateTime(1994,10,11),
                    User_Type_ID =1,
                    User_Status_ID =1
                },
                new User
                {
                    User_ID = 2,
                    Id = 2,
                    Name = "Barbra",
                    Surname = "Gordon",
                    ID_Number = "1220231231312",
                    Email = "barbragordon@gmail.com",
                    Physical_Address = "456 Oak Avenue",
                    PhoneNumber = "9876543210",
                    Photo = "barbra_photo.jpg",
                    PasswordHash = "HJDKL3948SJDF3JSHFD",
                    Date_of_Birth = new DateTime(1985, 5, 15),
                    User_Type_ID =2,
                    User_Status_ID =1
                },

                new User

                {
                User_ID = 3,
                Id = 3,
                Name = "Jane",
                Surname = "Smith",
                ID_Number = "1220231231312",
                Email = "JaneSmith@gmail.com",
                Physical_Address = "456 Oak Avenue",
                PhoneNumber = "9876543210",
                Photo = "jane_smith_photo.jpg",    
                PasswordHash = "JKLFSF34JKLRE983JFSD",
                Date_of_Birth = new DateTime(1985, 5, 15),
                User_Type_ID =3,
                User_Status_ID =1
                }


            };
        builder.Entity<User>().HasData(Users);








            var Contracts = new Contract[]
            {
               new Contract { Contract_ID = 1, Subscription_Date = new DateTime(2023, 1, 1), Expiry_Date = new DateTime(2023, 4, 1), Terms_Of_Agreement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Approval_Status = true, Approval_Date = new DateTime(2023, 1, 1), Initial_Fee = 100.00m, Contract_Type_ID = 1, Payment_Type_ID = 1 }
            };
            builder.Entity<Contract>().HasData(Contracts);


            var ContractHistories = new Contract_History[]
            {
                new Contract_History { Contract_History_ID = 1, Modification_Date = new DateTime(2023, 5, 15), Previous_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Updated_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut enim ad minim veniam.", Reasons_For_Changes = "To include additional benefits for members.", Contract_ID = 1 },

            };
            builder.Entity<Contract_History>().HasData(ContractHistories);


            var VAT = new VAT[]
            {
               new VAT { VAT_ID = 1, VAT_Percentage = 15.00m, VAT_Date = new DateTime(2024, 1, 1) }
            };
            builder.Entity<VAT>().HasData(VAT);


            var Audit_Trails = new Audit_Trail[]
            {
                new Audit_Trail { Audit_Trail_ID = 1, Action = "Action description", Timestamp = DateTime.Now }

            };
            builder.Entity<Audit_Trail>().HasData(Audit_Trails);

            var Shifts = new Shift[]
            {
              new Shift { Shift_ID = 1, Start_Time = new TimeSpan(8, 0, 0), End_Time = new TimeSpan(12, 0, 0) }

            };
            builder.Entity<Shift>().HasData(Shifts);


            var Employees = new Employee[]
            {
               new Employee { Employee_ID = 1, Employment_Date = new DateTime(2024, 4, 12), Employee_Type_ID = 1 , Shift_ID =1, User_ID = 2 }
            };
            builder.Entity<Employee>().HasData(Employees);


            var Members = new Member[]
            {
               new Member { Member_ID = 1, Contract_ID = 1,User_ID = 3 }
               
            };
            builder.Entity<Member>().HasData(Members);


            var AttendanceLists = new Attendance_List[]
            {

                new Attendance_List { Attendance_ID = 1, Number_Of_Bookings = 1, Members_Present = 10, Members_Absent = 5, Time_Slot_ID = 1}
            };
            builder.Entity<Attendance_List>().HasData(AttendanceLists);


            var Bookings = new Booking[]
            {
                new Booking { Booking_ID = 1,  Member_ID = 1}
            };
            builder.Entity<Booking>().HasData(Bookings);

            var workoutcategories = new Workout_Category[]
            {
                new Workout_Category { Workout_Category_ID = 1, Workout_Category_Name = "Cardio", Workout_Category_Description = "Cardio workouts to improve endurance and burn calories." },
                new Workout_Category { Workout_Category_ID = 2, Workout_Category_Name = "Strength", Workout_Category_Description = "Strength training workouts to build muscle and increase strength." },
                new Workout_Category { Workout_Category_ID = 3, Workout_Category_Name = "Flexibility", Workout_Category_Description = "Flexibility workouts to improve range of motion and reduce injury risk." }
            };
            builder.Entity<Workout_Category>().HasData(workoutcategories);


            var workouts = new Workout[]
            {
                    new Workout
                    {
                        Workout_ID = 1,
                        Workout_Name = "Cardio Blast",
                        Workout_Description = "High-intensity cardio workout to burn calories and improve endurance.",
                        Sets = 4,
                        Reps = 10,
                        Workout_Category_ID = 1
                    },
                    new Workout
                    {
                        Workout_ID = 2,
                        Workout_Name = "Strength Training",
                        Workout_Description = "Build muscle strength and endurance.",
                        Sets = 3,
                        Reps = 12,
                        Workout_Category_ID = 2
                    },
                    new Workout
                    {
                        Workout_ID = 3,
                        Workout_Name = "Flexibility Routine",
                        Workout_Description = "Improve your flexibility with this stretching routine.",
                        Sets = 2,
                        Reps = 15,
                        Workout_Category_ID = 3
                    }
            };
            builder.Entity<Workout>().HasData(workouts);


            var Lesson_Plans = new Lesson_Plan[]
            {
                new Lesson_Plan { Lesson_Plan_ID = 1, Program_Name = "Base", Program_Description = "Base program description", }

            };
            builder.Entity<Lesson_Plan>().HasData(Lesson_Plans);


            var orderStatuses = new Order_Status[]
            {
                new Order_Status { Order_Status_ID = 1, Order_Status_Description = "Pending" },
            };
            builder.Entity<Order_Status>().HasData(orderStatuses);


            var Orders = new Order[]
            {
               new Order { Order_ID = 1, Order_Date = new DateTime(2024, 4, 12), Order_Details = "Example order details", Total_Price = 100.00m, Member_ID = 1, Order_Status_ID = 1 }
            };
            builder.Entity<Order>().HasData(Orders);


            var Outstanding_Payments = new Outstanding_Payment[]
            {
               new Outstanding_Payment { Outstanding_Payment_ID = 1, Due_Date = new DateTime(2024, 4, 12), Amount_Due = 50.00m, Late_Fee = 0.00m, Member_ID = 1, Payment_ID = 1 }
            };
            builder.Entity<Outstanding_Payment>().HasData(Outstanding_Payments);


            var Owners = new Owner[]
            {
               new Owner { Owner_ID = 1, User_ID = 1 }
            };
            builder.Entity<Owner>().HasData(Owners);


            var Payments = new Payment[]
            {
              new Payment { Payment_ID = 1, Amount = 50.00m, Payment_Date = new DateTime(2024, 4, 12), Order_ID = 1, Payment_Type_ID = 1, Payment_Method_ID = 1 }
            };
            builder.Entity<Payment>().HasData(Payments);


            var Products = new Product[]
            {
               new Product { Product_ID = 1, Product_Name = "T-Shirt", Product_Description = "Cotton Shirt sleevless", Create_Date = new DateTime(2024, 4, 12), Last_Update_Date = new DateTime(2024, 4, 12), IsActive = true,Size = "XS" ,Product_Category_ID = 1, Supplier_ID = 1 }
            };
            builder.Entity<Product>().HasData(Products);


            var prices = new Price[]
            {
                new Price { Price_ID = 1, Unit_Price = 50.00m, Product_ID = 1 }
            };
            builder.Entity<Price>().HasData(prices);


            var OrderLines = new Order_Line[]
            {
                new Order_Line { Order_Line_ID = 1, Order_ID = 1, Product_ID = 1 }

            };
            builder.Entity<Order_Line>().HasData(OrderLines);


            var Received_Supplier_Orders = new Received_Supplier_Order[]
            {
                new Received_Supplier_Order { Received_Supplier_Order_ID = 1, Supplies_Received_Date = new DateTime(20, 04, 10) }
            };

            builder.Entity<Received_Supplier_Order>().HasData(Received_Supplier_Orders);



            var Received_Supplier_Order_Lines = new Received_Supplier_Order_Line[]
            {
                new Received_Supplier_Order_Line { Received_Supplier_Order_Line_ID = 1,Received_Supplier_Order_ID = 1,Supplier_Order_ID = 1,Product_ID = 1,Received_Supplies_Quantity = 10 }
            };

            builder.Entity<Received_Supplier_Order_Line>().HasData(Received_Supplier_Order_Lines);

            var Rewards = new Reward[]
            {
                new Reward { Reward_ID = 1, IsPosted = false, Reward_Issue_Date = new DateTime(2024, 4, 10), Reward_Type_ID = 1 }

            };
            builder.Entity<Reward>().HasData(Rewards);

            var Reward_Members = new Reward_Member[]
            {
                new Reward_Member{ Reward_Member_ID = 1, IsRedeemed = false, Member_ID = 1, Reward_ID = 1}
            };
            builder.Entity<Reward_Member>().HasData(Reward_Members);

            var Roles = new Role[]
            {
                new Role{ Id = 1, Name = "Owner", NormalizedName= "OWNER", isEditable = false},
                new Role{ Id = 2, Name = "Employee", NormalizedName= "EMPLOYEE", isEditable =true},
                new Role{ Id = 3, Name = "Member", NormalizedName= "MEMBER", isEditable =true}
            };
            builder.Entity<Role>().HasData(Roles);


            int claimId = 1;
            //Owner Claims
            //for each admin claim
            var ownerClaims = new Claim[]

            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Create"),
                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),
                new Claim("Employee Manager", "Delete"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory  Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),

                new Claim("Gym Manager", "Create"),
                new Claim("Gym Manager", "Read"),
                new Claim("Gym  Manager", "Update"),
                new Claim("Gym Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in ownerClaims) 
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                { 
                   Id = claimId++,
                   RoleId = Roles[0].Id,
                   ClaimType = claim.Type,
                   ClaimValue = claim.Value
                });
            }

            //Employee Claims , they are admin too but just for separation        
            //for each employee claim
            var employeeClaims = new Claim[]
            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in employeeClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[1].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            var memberClaims = new Claim[]
            {
                new Claim("Booking Interface", "Create"),
                new Claim("Booking Interface", "Read"),
                new Claim("Booking Interface", "Update"),
                new Claim("Booking Interface", "Delete"),

                new Claim("Profile", "Create"),
                new Claim("Profile", "Read"),
                new Claim("Profile", "Update"),

            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in memberClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[2].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            var Supplier_Orders = new Supplier_Order[]
            {
                new Supplier_Order { Supplier_Order_ID = 1, Date = new DateTime(2024, 4, 10), Supplier_Order_Details = "Ordered 50 units of dumbbells and 20 yoga mats", Total_Price = 1500.00m, Supplier_ID = 1, Owner_ID = 1 }

            };
            builder.Entity<Supplier_Order>().HasData(Supplier_Orders);

            var Supplier_Order_Lines = new Supplier_Order_Line[]
            {
                new Supplier_Order_Line { Supplier_Order_Line_ID = 1, Supplier_Qauntity = 12, Supplier_ID = 1, Product_ID = 1 }

            };
            builder.Entity<Supplier_Order_Line>().HasData(Supplier_Order_Lines);

            var Inventory = new Inventory[]
            {
                new Inventory { Inventory_ID = 1, Inventory_Item_Category = "Clothes", Inventory_Item_Name = "Men's Dry-fit Tops", Inventory_Item_Quantity = 20, Inventory_Item_Photo = "dry_fit_tops.jpg", Received_Supplier_Order_ID = 1, Supplier_ID = 1 }

            };
            builder.Entity<Inventory>().HasData(Inventory);

            var Equipments = new Equipment[]
            {
                
                 new Equipment{ Equipment_ID = 1, Equipment_Name = "Treadmill", Equipment_Description = "A motorized device used for running or walking while staying in one place." }
                
            };
            builder.Entity<Equipment>().HasData(Equipments);

            var Inspections = new Inspection[]
            {
                new Inspection { Inspection_ID = 1, Inspection_Date = new DateTime(2024, 4, 12),Inspection_Notes = "Holes in AVS pants" , Equipment_ID = 1,  Inspection_Type_ID = 1, Inspection_Status_ID = 1 }

            };
            builder.Entity<Inspection>().HasData(Inspections);

            var Booking_Time_Slots = new Booking_Time_Slot[]
            {
                new Booking_Time_Slot{Booking_Time_Slot_ID = 1, Booking_ID = 1,Time_Slot_ID = 1}
            };
            builder.Entity<Booking_Time_Slot>();


            var Time_Slots = new Time_Slot[]
            {

                new Time_Slot{Time_Slot_ID = 1,Slot_Date =  new DateTime(2024, 4, 12)  , Slot_Time = DateTime.Parse("11:00:00"), Availability = true, Lesson_Plan_ID= 1, Employee_ID=1}

            };
            builder.Entity<Time_Slot>().HasData(Time_Slots);


            var Write_Offs = new Write_Off[]
            {
                new Write_Off { Write_Off_ID = 1, Date = new DateTime(2024, 4, 12), Write_Off_Reason = "Expired items", Inventory_ID = 1 }

            };
            builder.Entity<Write_Off>().HasData(Write_Offs);


            var lessonPlanWorkOuts = new Lesson_Plan_Workout[]
            {
                new Lesson_Plan_Workout {Lesson_Plan_Workout_ID =1, Lesson_Plan_ID = 1, Workout_ID = 1}
            };
            builder.Entity<Lesson_Plan_Workout>().HasData(lessonPlanWorkOuts);

        }

    }
}

<?xml version='1.0' encoding='UTF-8'?>
<Products>
    <Product>
        <name>TTS Bee-Bot Programmable Floor Robot</name>
        <product_code>IT10077B</product_code>
        <price_wholesale>XX.XX</price_rrp>
        <price_rrp>XX.XX</price_rrp>
        <stock>349.0</stock>
        <brand_id>(35, 'TTS')</brand_id>
        <description>Along with a memory of 200 steps, Bee-Bot® can now detect another Bee-Bot® or Blue-Bot® and say hello.</description>
        <descriptione_long>They will play a default sound or the students can record their own...</description_long>
        <sale_argument>Bee-Bot® is a perfect starting point for teaching control, directional language and programming.</sale_argument>
        <Images>
            <Image>https://www.insplay.eu/web/image/product.product/3488/image_raw</Image>
            <Image>https://www.insplay.eu/web/image/product.image/38470/image_raw</Image>
            <Image>https://www.insplay.eu/web/image/product.image/38471/image_raw</Image>
        </Images>
        <age_from>3.0</age_from>
        <age_to>False</age_to>
        <under_3_forbidden>True</under_3_forbidden>
        <ean>False</ean>
        <origin_country>CN</origin_country>
        <weight>0.34</weight>
        <more_info_url>www.tts-international.com</more_info_url>
        <tariff_no>95030075</tariff_no>
        <date_create>2019-01-29</date_created>
        <date_updated>2019-11-26</date_updated>
    </Product>
</Products>
void insertInPosition(node *&head, node *&tail, int d, int position) {
  if (position == 1) {
    insertAtHead(head, d);
    return;
  }

  node *temp = head;
  int count = 1;
  while (count < position - 1) {
    temp = temp->next;
    count++;
  }
  if (temp->next == NULL) {
    insertAtTail(tail, d);
    return;
  }

  node *nodeToInsert = new node(d);
  nodeToInsert->next = temp->next;
  temp->next = nodeToInsert;
}
void print (node* &head) {
  node* temp = head;
  while (temp != NULL) {
    cout << temp -> data << " ";
    temp = temp -> next;
  }
}
void insertAtTail(node *&tail, int d) {
  node *temp = new node(d);
  tail->next = temp;
  tail = temp;
}
void insertAtHead(node *&head, int d) {
  node *temp = new node(d);
  temp->next = head;
  head = temp;
}
void deleteNode(node *&head, int position) {
  if (position == 1) {
    node *temp = head;
    head = head->next;
    temp->next = NULL;
    delete temp;
  }

  else {
    node *curr = head;
    node *prev = NULL;
    int cnt = 1;
    while (cnt < position) {
      prev = curr;
      curr = curr->next;
      cnt++;
    }
    prev->next = curr->next;
    curr->next = NULL;
    delete curr;
  }
}
const test = [3, 5, 6, 7, 8, 0, "", null, undefined, "testing"];


 test.forEach(listItem);

function listItem(item, number, total) {
    return `<li class="${number}">${item} ${number} of ${total}</li>`;
}


let htmlDOM = `<ul>${test.map((item, index, array) => listItem(item, `${index + 1}`, `${array.length}`)).join("")}</ul>`;
  

//console.log(htmlDOM);

/**

'<ul><li class="1">3 1 of 10</li><li class="2">5 2 of 10</li><li class="3">6 3 of 10</li><li class="4">7 4 of 10</li><li class="5">8 5 of 10</li><li class="6">0 6 of 10</li><li class="7"> 7 of 10</li><li class="8">null 8 of 10</li><li class="9">undefined 9 of 10</li><li class="10">testing 10 of 10</li></ul>'

*/


(function () {
  "use strict";

  const person = {
    name: "John Doe",
    age: 30,
    hobbies: ["reading", "traveling", "coding"],
  };

  const { hobbies, name, age } = person; // descructure

  hobbies.forEach((item, idx) => passInfo(item, idx, { name, age })); // pass function into the foreach

  function passInfo(item, idx, ...args) {
    console.log({ item, idx, args });
  }
})();



// another example

const test = [3, 5, 6, 7, 8, 0, "", null, undefined, "testing"];

test.forEach(listItem);


 function listItem(item, number, total) {
    return `<li class="${number}">${item} ${number} of ${total}</li>`;
  }
{
  "eventId": 168,
  "associationId": 72,
  "eventTypeId": 2,
  "title": "Tech Conference 2024",
  "description": "A conference for tech enthusiasts to share ideas and innovations.",
  "cityId": 148013,
  "stateId": 32,
  "countryId": 1,
  "eventModeId": 45,
  "registrationStartDate": "2024-07-17T06:32:21.324Z",
  "registrationEndDate": "2024-07-18T06:32:21.324Z",
  "eventStartDate": "2024-07-18T06:32:21.324Z",
  "eventEndDate": "2024-07-23T06:32:21.324Z",
  "broucherUrl": "",
  "address": "Madhapur",
  "videoUrl": "https://youtube.com/shorts/t6SLjTQbPh0?si=gJ9_eiYVqS3JFsGJ",
  "eventStatusId": 0,
  "phoneCode": "+91",
  "phoneCountryId": 1,
  "contactNumber": "7898561235",
  "contactEmail": "contact@sustainablefuture.com",
  "webSite": "https://sustainablefutureforum.com",
  "geolocation": {
    "x": 17.419791987251436,
    "y": 78.32488111758651
  },
  "isFreeEvent": true,
   "noOfSeats": 100,
   "categoryId": 6,
}
// Splide JS
function splide_js_script () {
    wp_enqueue_script( 'splide-js', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js', null, null, true );
    wp_enqueue_style('splide-css', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css');
}
add_action( 'wp_enqueue_scripts', 'splide_js_script' );
import React, { useCallback, useEffect, useState } from 'react';
import { NavLink, useParams } from 'react-router-dom';
import Loader from '../common/components/Loader';
import { IRouteParams } from '../common/interfaces/IRouteParams';
import Repository from '../common/repository/repository';
import { AssetType, IAsset } from './interfaces/IAsset';
import styled from 'styled-components';
import config from '../config.json';
import Title from '../common/components/LayoutComponents/Title';
// import { Button, Col, Input, Row, UncontrolledAlert } from 'reactstrap';
import { Button, Col, Form, FormGroup, Input, Label, Row, UncontrolledAlert } from 'reactstrap';
import Asset from '../composition_riv/components/Asset';
import { IApiPostResponse } from '../common/interfaces/IApiPostResponse';
import { formatDateString } from '../common/utils/Date';
import AppRoutes from '../AppRoutes';
import { useTranslations } from '../i18n/useTranslations';
import * as Constants from "../common/constants/library-constants";
import * as Global_Constants from "../common/constants/shared-constants";
import * as Dam_Constants from "../digital_assets_management/constants/dam-constants";

const AssetContainer = styled.div`
  overflow-y: auto;
  height:100%;
  
`;

const AssetDiv = styled.div`
  display: flex;
  flex-direction: column;
`;

const AssetIllustration = styled.div`
  width: 100%;
  max-height: 270px;
  height: 270px;
  display: flex;
  justify-content: center;

  .sdc-asset {
    &.sdc-playlist {
      height: 100%;
      width: 100%;
    }
  }
`;

const AssetPropertyTitle = styled.div`
  width: 100%;
  font-weight: bold;
  justify-content: top;
`;

const AssetTagsContainer = styled.div`
  width: 100%;
  display: flex;
  width: 9rem;
`;

const TagContainer = styled.div.attrs({
  'data-testid': 'new-asset-tag-container',
})`
  display: flex;
  align-items: center;
  width: 9rem;
  padding-bottom: 0.25rem;
`;
const ScrollableContainer = styled.div`
 	 max-height: 270px;
 		  overflow-y: auto;
 		  width: 100%;
 		`;
const TagsList = styled.div.attrs({
  className: 'col-sm-9',
})`
  display: flex;
  flex-wrap: wrap;
`;

const TagButton = styled.i`
  cursor: pointer;
  padding: 0.25rem 0.5rem;
  color: darkred;
`;

export const AssetDetails = () => {
  const i18n = useTranslations()
  const [changeNameErrorMessage, setChangeNameErrorMessage] = useState('');
  const [tagsErrorMessage, setTagsErrorMessage] = useState('');
  const [resultLoaded, setResultLoaded] = useState(false);
  const [assetVersions, setAssetVersions] = useState([] as IAsset[]);
  const [selectedAsset, setSelectedAsset] = useState(null as unknown as IAsset);
  const [selectedAssetIndex, setSelectedAssetIndex] = useState(0);
  const [selectedAssetRoute, setSelectedAssetRoute] = useState<
    string | undefined
  >('');
  const [showEditNameForm, setShowEditNameForm] = useState(false);
  const [newAssetName, setNewAssetName] = useState('');
  const [newTag, setNewTag] = useState('');
  const [sequencesForScene, setSequencesForScene] = useState<IAsset[]>([]);
  const { id } = useParams<IRouteParams>();

  const retrieveAssetVersions = useCallback(async () => {
    setResultLoaded(false);

    const assets = await Repository.getInstance().getAssetVersions(
      parseInt(id)
    );

    setAssetVersions(assets);
    if (
      assets !== null &&
      assets[selectedAssetIndex] !== undefined &&
      assets[selectedAssetIndex] !== null
    ) {
      setSelectedAsset(assets[selectedAssetIndex]);
      setSelectedAssetRoute(assetToRoute(assets[selectedAssetIndex]));
    } else {
      setSelectedAsset(null as unknown as IAsset);
    }
    setResultLoaded(true);
  }, [id, selectedAssetIndex]);

  useEffect(() => {
    retrieveAssetVersions();
  }, [retrieveAssetVersions]);

  useEffect(() => {
    if (!selectedAsset) return;
    if (selectedAsset.file_type !== AssetType.Scene) return;
    const retrieveSequences = async () => {
      const sequenceNames =
        await Repository.getInstance().getSequencesUsingScene(
          selectedAsset.name
        );
      setSequencesForScene(sequenceNames);
    };
    retrieveSequences();
  }, [selectedAsset]);

  function changeSelectedVersion(e: React.ChangeEvent<HTMLInputElement>) {
    const selectedId = e.target.value;
    const selectedIndex = assetVersions.findIndex((ast) => ast.id.toString() === selectedId);
    setSelectedAssetIndex(selectedIndex);
  }

  function toggleEditNameForm() {
    setShowEditNameForm(!showEditNameForm);
  }

  function changeNewAssetName(evt: React.ChangeEvent<HTMLInputElement>) {
    setNewAssetName(evt.target.value);
  }

  function changeNewTag(evt: React.ChangeEvent<HTMLInputElement>) {
    setNewTag(evt.target.value);
  }

  function validateNewNameForm() {
    return newAssetName !== '' && newAssetName !== selectedAsset?.name;
  }

  async function sendNewName() {
    setChangeNameErrorMessage('');
    setResultLoaded(false);

    const data = new FormData();
    data.append('newName', newAssetName);
    const apiResponse = new IApiPostResponse();
    await Repository.getInstance().editAssetName(
      selectedAsset?.id,
      data,
      apiResponse,
      i18n(Global_Constants.GLOBAL, Dam_Constants.CHECK_NETWORK_STATUS)
    );
    if (apiResponse.errorMessage != null) {
      setChangeNameErrorMessage(apiResponse.errorMessage);
    }
    await retrieveAssetVersions();
  }

  async function removeTag(tagId: number) {
    setResultLoaded(false);
    await Repository.getInstance().removeTagFromAsset(selectedAsset?.id, tagId);
    await retrieveAssetVersions();
  }

  async function addTag(tagName: string) {
    if (selectedAsset?.tags.findIndex((t) => t.name === tagName) !== -1) return;

    setTagsErrorMessage('');
    setResultLoaded(false);

    const data = new FormData();
    data.append('assetId', selectedAsset?.id.toString());
    data.append('tagName', tagName);

    const apiResponse = new IApiPostResponse();
    await Repository.getInstance().addTagToAsset(data, apiResponse);
    if (apiResponse.errorMessage != null) {
      setTagsErrorMessage(apiResponse.errorMessage);
    }
    setNewTag('');
    await retrieveAssetVersions();
  }

  const setAssetIsSubstitution = async (checked: boolean) => {
    setResultLoaded(false);
    if (checked)
      await Repository.getInstance().setIsSubstitutionAsset(selectedAsset.id);
    else
      await Repository.getInstance().UnsetIsSubstitutionAsset(selectedAsset.id);
    await retrieveAssetVersions();
  };

  const assetTypeToDescription = (assetType: AssetType) => {
    const types = new Map([
      [AssetType.Image, 'Image'],
      [AssetType.Scene, 'Scene'],
      [AssetType.Sound, 'Son'],
      [AssetType.Video, 'Vidéo'],
      [AssetType.Sequence, 'Séquence'],
      [AssetType.Text, 'Texte'],
      [AssetType.Font, 'Police'],
      [AssetType.Style, 'Style'],
      [AssetType.PredefMessage, 'Message'],
      [AssetType.Programmation, 'Programmation'],
    ]);
    return types.get(assetType);
  };

  const assetToRoute = (asset: IAsset) => {
    const types = new Map([
      [AssetType.Sequence, AppRoutes.sequence(asset.id.toString())],
      [AssetType.Scene, AppRoutes.editor(asset.id.toString())],
      [
        AssetType.PredefMessage,
        AppRoutes.predefinedMessage(asset.id.toString()),
      ],
      [AssetType.Playlist, AppRoutes.audioPlaylist(asset.id.toString())],
      [AssetType.Style, AppRoutes.style(asset.id.toString())],
      [AssetType.Programmation, AppRoutes.programmation(asset.id.toString())],
    ]);

    return types.get(asset.file_type);
  };

  return (
    <AssetContainer>
      {!resultLoaded && <Loader />}
      <Title>{i18n(Global_Constants.LIBRARY, Constants.RESOURCE_DETAILS)}: {selectedAsset?.name}</Title>
      <Form>
        <AssetDiv>
          <AssetIllustration>
            {selectedAsset && <Asset asset={selectedAsset} />}
          </AssetIllustration>

          <FormGroup row >
            <Label for="version" sm={3}><AssetPropertyTitle>Version</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input
                type="select"
                id="version"
                value={selectedAsset?.id}
                onChange={changeSelectedVersion}
                disabled={!assetVersions || !assetVersions.length || assetVersions.length === 1}
              >
                {assetVersions?.map((asset, index) => (
                  <option key={`${asset.version}-${index}`} value={asset.id}>
                    {asset.version}
                  </option>
                ))}
              </Input>
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="assetName" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.NAME)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <div className="d-flex align-items-center">
                {selectedAsset?.name}
                <i
                  className={`ms-1 fa fa-lg fa-pencil-square${showEditNameForm ? '' : '-o'}`}
                  style={{ cursor: 'pointer' }}
                  onClick={toggleEditNameForm}
                />
              </div>
            </Col>
          </FormGroup>

          {showEditNameForm && (
            <FormGroup row>
              <Label for="newAssetName" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.NEW_NAME)}</AssetPropertyTitle></Label>
              <Col sm={3}>
                <Input
                  type="text"
                  id="newAssetName"
                  value={newAssetName}
                  onChange={changeNewAssetName}
                  placeholder={selectedAsset.name}
                />
                <Button
                  className="btn btn-danger mt-1"
                  disabled={!validateNewNameForm()}
                  onClick={sendNewName}
                >
                  {i18n(Global_Constants.LIBRARY, Global_Constants.CHANGE)}
                </Button>
              </Col>
              {changeNameErrorMessage && (
                <UncontrolledAlert color="danger">
                  Error: {changeNameErrorMessage}
                </UncontrolledAlert>
              )}
            </FormGroup>
          )}

          <FormGroup row>
            <Label for="creationDate" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.CREATION_DATE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="creationDate" value={formatDateString(selectedAsset?.created_at)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="modificationDate" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.LAST_MODIFICATION_DATE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="modificationDate" value={formatDateString(selectedAsset?.updated_at)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="resourceType" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.RESOURCE_TYPE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="resourceType" value={assetTypeToDescription(selectedAsset?.file_type)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="dimension" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.SIZE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="dimension" value={String(selectedAsset?.dimension)} readOnly />
            </Col>
          </FormGroup>

          {selectedAsset && (selectedAsset?.file_type === AssetType.Image || selectedAsset?.file_type === AssetType.Text || selectedAsset?.file_type === AssetType.Style) && (
            <FormGroup row>
              <Label for="substitute" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.SUBSTITUTE_MESSAGE)}</AssetPropertyTitle></Label>
              <Col sm={3}>
                <Input
                  id="isSubstitution"
                  type="checkbox"
                  className="form-check-input"
                  checked={selectedAsset?.isSubstitution ?? false}
                  onChange={(e) => setAssetIsSubstitution(e.target.checked)}
                />
              </Col>
            </FormGroup>
          )}

          <FormGroup row>
            <Label for="keywords" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.KEYWORDS)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <AssetTagsContainer>
                <TagsList>
                  {selectedAsset?.tags.map((tag, i) => (
                    <TagContainer key={`asset-tag-${selectedAsset.name}-${i}`}>
                      <Input type="text" value={tag.name} readOnly />
                      <TagButton className="fa fa-xs fa-close" onClick={() => removeTag(tag.id)} />
                    </TagContainer>
                  ))}
                  <TagContainer>
                    <Input
                      type="text"
                      id="new-asset-tag"
                      value={newTag}
                      placeholder={i18n(Global_Constants.LIBRARY, Constants.KEYWORD)}
                      onChange={changeNewTag}
                    />
                    <TagButton className={`fa fa-plus ${newTag === '' ? 'sdc-disabled' : ''}`} onClick={() => addTag(newTag)} />
                  </TagContainer>
                </TagsList>
              </AssetTagsContainer>
              {tagsErrorMessage && (
                <UncontrolledAlert color="danger">
                  Error: {tagsErrorMessage}
                </UncontrolledAlert>
              )}
            </Col>
          </FormGroup>

          {selectedAsset?.file_type === AssetType.Scene && sequencesForScene.length > 0 && (
            <FormGroup row>
              <Label for="sequences" sm={3}><AssetPropertyTitle>Utilized in sequences</AssetPropertyTitle></Label>
              <Col sm={3}>
                {sequencesForScene.map((s) => (
                  <div key={`seq-for-scene-${s.name}`}>
                    <NavLink to={AppRoutes.assetDetails(s.id.toString())}>
                      {s.name}
                    </NavLink>
                  </div>
                ))}
              </Col>
            </FormGroup>
          )}

          {selectedAssetRoute && (
            <div>
              <NavLink className="btn btn-secondary" to={selectedAssetRoute}>
                {i18n(Global_Constants.INFORMATION, Global_Constants.MODIFY_BUTTON)}
              </NavLink>
            </div>
          )}
        </AssetDiv>
      </Form>
    </AssetContainer>
  );
};

export default AssetDetails;
<div class="bottom-row">
    <div class="footer-nav">
        <small>
            <ul>
                <li>
                    <a href="/returnpolicy">Policy</a>
                </li>
                <li>
                    <a href="/privacypolicy">Privacy</a>
                </li>
                <li>
                    <a href="/termsandconditions">Terms</a>
                </li>
                <li>
                    <a href="/sitemap">Site Map</a>
                </li>
            </ul>
        </small>
    </div>
	<div class="footer-copyright">
        <a href="https://www.dealerspike.com/" target="_blank" title="Powered by Dealer Spike">
            <small>COPYRIGHT© <script>document.write(new Date().getFullYear())</script> DEALER SPIKE | ALL RIGHTS RESERVED</small>
        </a>
    </div>
	<div class="footer-ds-logo">
		<a href="https://www.dealerspike.com" title="Powered by Dealer Spike" target="_blank">
			<img src="//published-assets.ari-build.com/Content/Published/Site/{{Site.Id}}/images/ds-light.webp" alt="Powered by Dealer Spike" width="101" height="auto">
		</a>
	</div>
</div>
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
# Download the latest available Chrome for Testing binary corresponding to the Stable channel.
npx @puppeteer/browsers install chrome@stable

# Download a specific Chrome for Testing version.
npx @puppeteer/browsers install chrome@116.0.5793.0

# Download the latest available ChromeDriver version corresponding to the Canary channel.
npx @puppeteer/browsers install chromedriver@canary

# Download a specific ChromeDriver version.
npx @puppeteer/browsers install chromedriver@116.0.5793.0
SELECT 
    CASE 
        WHEN column1 IS NULL OR column1 = 0 THEN column2
        ELSE column1
    END AS result_column
FROM example_table;


SELECT 
    COALESCE(NULLIF(column1, 0), column2) AS result_column
FROM example_table;

AND CAST(CC.EDITDATE AS DATE) > CAST(DATEADD(DAY, -1, GETDATE()) AS DATE)
--AND CONVERT(DATE,(CC.EDITDATE)) = CONVERT(DATE, DATEADD(DAY, -30 , GETDATE()))
{'envs': [{'type': 'encrypted', 'value': 'Na1IRD7uhchPTvv3Io4QaJmef0GiPPkYS/j+CUSGXsY=', 'target': ['production'], 'configurationId': None, 'comment': '', 'id': 'GUetd8WLeysIWAZN', 'key': 'TEST3', 'createdAt': 1721114058202, 'updatedAt': 1721114058202, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiN0tpWkQrSEJGM2V3ZE9hK0RIUDYrZmpqOW5SZ0hsQzg5NUVEWm00Wm9NUmRrektRaVVUc25tYWFPN1VNSjFQN28vbmVLRTRoWWlZUWlXaDFXVzdyc2hNNlhGaDE4Z2ZCa1d1QzdRPT0iLCJrIjpbMTg0LDEsMiwzLDAsMTIwLDExNSwxNjMsMTYxLDI4LDE3NiwxNDgsOTksMTY1LDI0NiwyMjcsMjQ0LDIzMyw0NywxNTMsNjMsOTQsMTM5LDEsMjQzLDEwLDMwLDgxLDE0NSw2Myw1OSwxOTMsMzQsMTA5LDE1OCw4LDczLDExNywxLDM0LDEyMSwxNDYsMTE1LDc0LDc4LDE0NywxMzksMTQ0LDE0NywyMjUsMzEsMjA2LDE2MywyMzMsMTk2LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDE4OSwxMDQsMjM2LDEyMiwxNDUsMyw4LDE5MSwzNywyNywyNywyMjQsMiwxLDE2LDEyOCw1OSwyNTEsMjEwLDIyMCw3Niw2NiwxMyw4MywxNTgsMjE1LDE0OSw2OSwxNTcsOTAsMTM5LDExLDQwLDI0NSwxNjMsMTIzLDExNywxMzIsNzIsNTMsNjUsMTA3LDIyLDEyNywxNSwyMTgsMjI4LDk1LDE3MSwxOTYsNzksMjA3LDIxLDExMSwxNzQsMjIxLDE5MiwxMDEsNDAsMjQwLDEzOCwxMzgsMjUsMTczLDE3MSwyMywxOTUsOTIsMTYsMSw2Miw3MCwxNDcsMTgzLDIwNiwxMzddfQ==', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': '8uTSK+Bz1Y1VbOCgq92DI0kQ92nrR3GClP52bULsgnY=', 'target': ['development', 'preview'], 'configurationId': None, 'comment': '', 'id': 'HCtPog8aPyhaWhSw', 'key': 'TEST3', 'createdAt': 1721114049773, 'updatedAt': 1721114049773, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiUWZEQjdzQXU3ME9aakV5aW5NWlJCNFdZc3BDSjZ6Q3VlUHUyRXRCTnVKdEJMTTdMcEdaTCtiYWNhUGhzWGNjSEovR1BTRElUSmI0aHlDMXVzNUROcUI2YzZwUCswWGx2T3F2KzJ3PT0iLCJrIjpbMTg0LDEsMiwzLDAsMTIwLDExNSwxNjMsMTYxLDI4LDE3NiwxNDgsOTksMTY1LDI0NiwyMjcsMjQ0LDIzMyw0NywxNTMsNjMsOTQsMTM5LDEsMjQzLDEwLDMwLDgxLDE0NSw2Myw1OSwxOTMsMzQsMTA5LDE1OCw4LDczLDExNywxLDM0LDEyMSwxNDYsMTE1LDc0LDc4LDE0NywxMzksMTQ0LDE0NywyMjUsMzEsMjA2LDE2MywyMzMsMTk2LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDE4OSwxMDQsMjM2LDEyMiwxNDUsMyw4LDE5MSwzNywyNywyNywyMjQsMiwxLDE2LDEyOCw1OSwyNTEsMjEwLDIyMCw3Niw2NiwxMyw4MywxNTgsMjE1LDE0OSw2OSwxNTcsOTAsMTM5LDExLDQwLDI0NSwxNjMsMTIzLDExNywxMzIsNzIsNTMsNjUsMTA3LDIyLDEyNywxNSwyMTgsMjI4LDk1LDE3MSwxOTYsNzksMjA3LDIxLDExMSwxNzQsMjIxLDE5MiwxMDEsNDAsMjQwLDEzOCwxMzgsMjUsMTczLDE3MSwyMywxOTUsOTIsMTYsMSw2Miw3MCwxNDcsMTgzLDIwNiwxMzddfQ==', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': 'VthAYNl9F6jelOiJ+QpYjZVNn4cT2QjAsr/9jsnUfao=', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'id': '9KaKpHEVEIQxqT5U', 'key': 'TEST2', 'createdAt': 1721114034269, 'updatedAt': 1721114034269, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoibE9tMnZpay9POTAwRXdaK1pYdFlVWUlCeVhnVDBhSlZZZkIySnJyRTNmall1b0JzNVlLTHcxYlJFNTRleHZTcVlDdkVVUkgzQzUxMExCekhaTnBncHFhS1dtdnRnUXJqZ2JXRHpHdDFWaWM9IiwiayI6WzE4NCwxLDIsMywwLDEyMCwxMTUsMTYzLDE2MSwyOCwxNzYsMTQ4LDk5LDE2NSwyNDYsMjI3LDI0NCwyMzMsNDcsMTUzLDYzLDk0LDEzOSwxLDI0MywxMCwzMCw4MSwxNDUsNjMsNTksMTkzLDM0LDEwOSwxNTgsOCw3MywxMTcsMSw3LDU4LDExNiwxMTIsMTA5LDgsMjIsMTYxLDIwNCwyMjksMjAwLDE3MywxNjQsMTUzLDcyLDM0LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDEwMSwyMDYsMTU1LDkxLDg2LDQ0LDQzLDk4LDEwNSwyMTIsMjMzLDI1MCwyLDEsMTYsMTI4LDU5LDEzNiwzMywyMCwxMzEsMTg1LDE1Niw4MSwzMSwxLDI0MSw1MSwxNTIsOTMsMjQsMzUsMCwyMDksMjUzLDYwLDEwNywxMjEsOCwzMCwxNjAsNzIsMTQ5LDIxMSwxOTEsMjI1LDEyNCwxNjIsOCwxOCw0MSwyMzcsODEsODcsNjksMCwxNTksMTUzLDEwLDE3NSwyMjksMjcsMTYzLDIsMTk1LDEwNiw5MiwxNTUsMjA1LDgxLDEzMiwxOTcsMzAsMjMyLDY0LDE0NV19', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': 'ZmSwfuTbZ4MRBTrCUTuLyDS9SXlSj5qvkCoujMAJyQ4=', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'comment': '', 'id': 'UtjkbLwia47Ac1vr', 'key': 'TEST1', 'createdAt': 1721114034267, 'updatedAt': 1721114034267, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiUXNBM3FHUkJqS014blRTcEZVdGZwVGdXSU0yZ210SWxnd0d4QmZURzFjZFZvdEREK0Z3anVYc3pwYTBrdEhURUVrN2ZUcVBGb2RrbG1WbWV2bEZpdjJZaUFncHlxQUFZMkVTOUFibW9sMFU9IiwiayI6WzE4NCwxLDIsMywwLDEyMCwxMTUsMTYzLDE2MSwyOCwxNzYsMTQ4LDk5LDE2NSwyNDYsMjI3LDI0NCwyMzMsNDcsMTUzLDYzLDk0LDEzOSwxLDI0MywxMCwzMCw4MSwxNDUsNjMsNTksMTkzLDM0LDEwOSwxNTgsOCw3MywxMTcsMSwyMDMsMTk5LDIwOCwxNzksMTQ4LDE1NiwxNDQsMTUxLDcxLDkxLDEzMCwxNTcsMjYsMTUwLDY3LDE2OSwwLDAsMCwxMjYsNDgsMTI0LDYsOSw0MiwxMzQsNzIsMTM0LDI0NywxMywxLDcsNiwxNjAsMTExLDQ4LDEwOSwyLDEsMCw0OCwxMDQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNywxLDQ4LDMwLDYsOSw5NiwxMzQsNzIsMSwxMDEsMyw0LDEsNDYsNDgsMTcsNCwxMiwxNywxNTYsMjE3LDIxMyw1Miw0MCw1MSwyMTgsMTQ0LDU0LDQyLDI0NSwyLDEsMTYsMTI4LDU5LDIwNSwxOTUsMTQzLDExOCwyMTksMjAzLDE3NiwxNywxMDIsODIsNjcsMzYsODMsMTk5LDE4MSw3MSwxNzMsNjMsNTksMTI5LDE5MCw3Niw2MywxODMsMTgzLDIwMiwyNywxNDgsNDAsMTk0LDE4OSwyNDEsMTcsNSw1MywyMywxMzMsMTYyLDEyMiw2Myw1MSw1NywyMzYsMTg3LDIwMCw5NiwxOSwyNDksMjI0LDIzMiw5OSwxNzMsMjQ1LDUwLDI1NCwxMSwxNzYsMjA5LDE3MF19', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}]}
{'type': 'encrypted', 'value': 'third', 'target': ['production'], 'configurationId': None, 'comment': '', 'id': 'KJhnBWOrfs34dU2Q', 'key': 'TEST3', 'createdAt': 1721122368822, 'updatedAt': 1721122368822, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
{'type': 'encrypted', 'value': 'second', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'id': 'DUF1G3ZywlIC9bXx', 'key': 'TEST2', 'createdAt': 1721122359445, 'updatedAt': 1721122359445, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
{'type': 'encrypted', 'value': 'first', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'comment': '', 'id': 'IMm31XhwQfnXFs2o', 'key': 'TEST1', 'createdAt': 1721122359442, 'updatedAt': 1721122359442, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = (
    f"https://api.vercel.com/v9/projects/"
    f"{os.getenv('PROJECT_ID')}/env"
)
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']


# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = (
            f"https://api.vercel.com/v9/projects/"
            f"{os.getenv('PROJECT_ID')}/env/{env['id']}"
        )
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = (
                f"https://api.vercel.com/v9/projects/"
                f"{os.getenv('PROJECT_ID')}/env"
            )
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.
# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file
load_dotenv()
import os
import requests
import json
from dotenv import load_dotenv
PROJECT_ID=
SLUG=
TEAM_ID=
VERCEL_TOKEN=
%%[set @firstName = AttributeValue("First_Name__c")
set @UNvalue= "?" 
set @firstName = ProperCase(@firstName)
if @firstName == "unknown" OR IndexOf(@firstName,@UNvalue) > 0 then set @FirstName = "" endif
if not Empty(@firstName) then set @greeting = Concat(", ", @firstName)
else
set @greeting = ""
endif ]%%
kubectl -n fleet-system scale deployment fleet-agent --replicas 0

helm -n mo-desktop uninstall mo-desktop-auth-new
helm -n mo-desktop uninstall mo-desktop-iam-new

while read crd; do
        while read resource; do
            echo "Patching mo-desktop/$resource"
            kubectl -n "mo-desktop" patch "$crd" "$resource" --type json --patch '[{ "op": "replace", "path": "/metadata/finalizers", "value": [] }]'
        done < <(kubectl -n "mo-desktop" get "$crd" --ignore-not-found | sed 1d | cut -d' ' -f1)
    done < <(kubectl get crd | sed 1d | grep -E "keycloak" | cut -d' ' -f1)

kubectl delete ns mo-desktop

kubectl -n fleet-system scale deployment fleet-agent --replicas 1
import { useEffect, useRef, useState } from "react";
import {
  MultiLangListContainer,
  MultiLangListItemContainer,
  MultiLangTextContainer,
} from "../containers/Container";
import {
  MultiLangListContainerStyle,
  MultiLangListTextAnimationStyle,
  MultiLangTextContainerStyle,
} from "../styles/InlineStyles";
import { IMlTextProps, IMultilingualText } from "./MlFreeTextMessage";
import { GenericUtil } from "../../../common/utils/GenericUtil";
import { DDRPlaceholderSelector } from "../../../composition_riv/constants/RIV";

export const MultiLanguageText = ({
  fontSize,
  style,
  color,
  multilanguage,
  multiLineText,
  direction,
}: IMlTextProps) => {
  const [previous, setPrevious] = useState(multilanguage);
  const [previousDirection, setPreviousDirection] = useState(direction);
  const [languages, setLanguages] = useState<IMultilingualText[]>([]);
  const nextTextIndex = useRef(0);
  const arrayOfDivs = useRef<INode[]>([]);
  const uniqueId = useRef(GenericUtil.getInstance().getRandomID());

  interface INode {
    node: HTMLDivElement;
    id: string;
    pNode: Element | null;
  }

  interface IDivData {
    sampleText: string;
    localecode: string;
    duration: string;
  }

  const textInitialPosition: {
    [key: string]: {
      left: string;
      top: string;
    };
  } = {
    up: { left: "0%", top: "100%" },
    down: { left: "0%", top: "-100%" },
    right: { left: "100%", top: "0%" },
    left: { left: "-100%", top: "0%" },
  };
  useEffect(() => {
    if (previous !== multilanguage || direction !== previousDirection) {
      populateLanguageList();
    }
  }, [multilanguage, direction]);

  useEffect(() => {
    if (multilanguage) {
      populateLanguageList();
    }
    return () => {
      arrayOfDivs.current.map((elt) =>
        elt.node.removeEventListener("animationend", callAppendNextDiv)
      );
    };
  }, []);

  useEffect(() => {
    setMultilingualTexts();
  }, [multilanguage, direction]);
  function renderMultilanguageText(): IMultilingualText[] {

    const previousTextInfo = JSON.parse(String(multilanguage));

    return (

      Object.keys(previousTextInfo)

        .filter((lang) => previousTextInfo[lang].checked)

        .map((lang) => ({

          sampleText: previousTextInfo[lang].sampleText,

          localecode: previousTextInfo[lang].id,

        })) || []

    );

  }
  function populateLanguageList() {

    setPrevious(multilanguage);

    const language = renderMultilanguageText() || [];

    setLanguages(language);

  }
  function createDiv(divData: IDivData) {
    const div = document.createElement("div");
    div.classList.add("lang");
    div.id = "mlText" + divData.localecode;
    div.setAttribute("data-duration", divData.duration);
    div.setAttribute("data-direction", direction);
    div.style.position = "absolute";
    div.style.paddingLeft = "1rem";
    div.style.width = "100%";
    div.style.height = "100%";
    div.style.left = textInitialPosition[direction].left;
    div.style.top = textInitialPosition[direction].top;
    div.style.animationName = `multilingual-anim-${direction}`;
    div.style.animationDelay = "0s";
    div.style.animationDuration = divData.duration + "s";
    div.innerText = divData.sampleText;
    return div;
  }

  function appendDiv(divToAppend: INode, index: number) {
    const elt = divToAppend.node;
    nextTextIndex.current = index;
    if (divToAppend.pNode) {
      divToAppend.pNode.appendChild(elt);
    }
  }

  function appendNextDiv(index: number) {
    if (arrayOfDivs.current.length > 0) {
      index = (index + 1) % arrayOfDivs.current.length;
      appendDiv(arrayOfDivs.current[index], index);
    }
  }

  function callAppendNextDiv() {
    if (arrayOfDivs.current.length > 0) {
      appendNextDiv(nextTextIndex.current);
    }
  }

  function setMultilingualTexts() {
    if (!multilanguage) return;
    nextTextIndex.current = 0;
    const parentElement = document.getElementById(uniqueId.current);
    parentElement!.innerHTML = "";
    const previousTextInfo = JSON.parse(String(multilanguage));
    const checkedLanguages = Object.keys(previousTextInfo).filter(
      (lang) => previousTextInfo[lang].checked
    );
    const multilingualText = checkedLanguages.map((lang) => ({
      sampleText: previousTextInfo[lang].sampleText,
      localecode: previousTextInfo[lang].id,
      duration: previousTextInfo[lang].duration,
    }));
    const newArrayOfDivs = multilingualText
      .map((element) => {
        if (element.sampleText !== null && element.sampleText.trim() !== "") {
          const dynamicDiv = createDiv(element);
          dynamicDiv.addEventListener("animationend", callAppendNextDiv);
          return {
            node: dynamicDiv,
            id: dynamicDiv.id,
            pNode: parentElement,
          };
        }
        return null;
      })
      .filter((div): div is { node: HTMLDivElement; id: string; pNode: HTMLElement | null } => div !== null);

    arrayOfDivs.current = newArrayOfDivs;
    if (arrayOfDivs.current.length > 0) {
      appendDiv(arrayOfDivs.current[0], 0);
    }
  }
  const itemCount = languages.length;
  const isSameContent = () => {
    return previous === multilanguage && previousDirection === direction;
  };


  return (
    <MultiLangTextContainer style={MultiLangTextContainerStyle()}>
      <MultiLangListContainer
        id={uniqueId.current}
        className="multiLingual"
        style={MultiLangListContainerStyle(
          fontSize,
          color,
          multiLineText,
          style
        )}
      >
        {isSameContent() &&

          languages.map(
            (item: { sampleText: any; localecode: string }, index: number) => (
              <MultiLangListItemContainer
                className="multiLingual"
                style={MultiLangListTextAnimationStyle(
                  index * 12,
                  itemCount,
                  12,

                  direction

                )}

                key={`mlListItem${item.sampleText}${index}`}

                data-ddrvarid={`${DDRPlaceholderSelector.MultiLangFreeTextMessage}.${item.localecode}`}

              >

                {item.sampleText}

              </MultiLangListItemContainer>

            )

          )}

      </MultiLangListContainer>

    </MultiLangTextContainer>
  );
};
[Authorize(Policy = "Owner")]
[HttpGet]
[Route("SearchUsers")]
public async Task<IActionResult> SearchUsers([FromQuery] string? criteria) 
{
    try
    {
        if (string.IsNullOrEmpty(criteria)) // Check if criteria is null or empty
        {
            // If criteria is not provided, return all users
            var users = await _userManager.Users
                                         .Select(u => new SearchUserViewmodel
                                         {
                                             User_ID = u.User_ID,
                                             Name = u.Name,
                                             Surname = u.Surname
                                         })
                                         .ToListAsync();

            return Ok(users);
        }

        // If criteria is provided, filter users based on the criteria
        var filteredUsers = await _userManager.Users
                                              .Where(u => u.Name.Contains(criteria) || u.Surname.Contains(criteria))
                                              .Select(u => new SearchUserViewmodel
                                              {
                                                  User_ID = u.User_ID,
                                                  Name = u.Name,
                                                  Surname = u.Surname
                                              })
                                              .ToListAsync();

        if (filteredUsers == null || filteredUsers.Count == 0)
        {
            return NotFound("No users found.");
        }

        return Ok(filteredUsers);
    }
    catch (Exception)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
    }
}
lib/main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}
//html
<div class="gym-manager-container">
    <div class="back-button">
      <button class="btn btn-link" (click)="goBack()">
        <i class="bi bi-arrow-left-circle"></i>Back
      </button>
    </div>
    <div class="content">
      <div class="header">
        <h1>Search Users</h1>
      </div>
  
      <input type="text" class="form-control mb-3" placeholder="Search User Types" [(ngModel)]="searchCriteria" (ngModelChange)="filterUsers()">
  
      <div class="table-responsive">
        <table class="table table-hover table-centered">
          <thead class="thead-light">
            <tr>
              <th>User ID</th>
              <th>Name</th>
              <th>Surname</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let user of filteredUsers">
              <td>{{ user.user_ID }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.surname }}</td>
              <td>
                <button class="btn btn-link" (click)="openModal(user)">
                  <i class="fa fa-eye"></i> View
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  
    <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content" style="text-align: center;">
          <div class="modal-header">
            <h5 class="modal-title" id="userModalLabel"><strong>User Details</strong></h5>
          </div>
          <div class="modal-body">
            <p><strong>User ID:</strong> {{ selectedUser?.user_ID }}</p>
            <p><strong>Name:</strong> {{ selectedUser?.name }}</p>
            <p><strong>Surname:</strong> {{ selectedUser?.surname }}</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" (click)="closeModal()">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  
//TS
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs';
import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { UserService } from '../Services/userprofile.service';
import { UserViewModel } from '../shared/search-user';
import { Location } from '@angular/common';
declare var $: any;

@Component({
  selector: 'app-member-manager',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule, RouterLink],
  templateUrl: './member-manager.component.html',
  styleUrl: './member-manager.component.css'
})
export class MemberManagerComponent implements OnInit {
  searchCriteria: string = '';
  users: UserViewModel[] = [];
  filteredUsers: UserViewModel[] = [];
  selectedUser: UserViewModel | null = null;

  constructor(private router: Router, private userService: UserService, private location: Location) { }

  ngOnInit(): void {
    this.loadUsers();
  }

  loadUsers(): void {
    this.userService.searchUsers('').subscribe(users => {
      this.users = users;
      this.filteredUsers = users;
    });
  }

  filterUsers(): void {
    const term = this.searchCriteria.toLowerCase();
    if (!term) {
      this.filteredUsers = this.users;
    } else {
      this.filteredUsers = this.users.filter(user =>
        user.user_ID.toString().includes(term) ||
        user.name.toLowerCase().includes(term) ||
        user.surname.toLowerCase().includes(term)
      );
    }
  }

  openModal(user: UserViewModel): void {
    this.selectedUser = user;
    $('#userModal').modal('show');
  }

  closeModal(): void {
    $('#userModal').modal('hide');
  }

  goBack(): void {
    this.location.back();
  }
}

//css
.gym-manager-container {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.content {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 5px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.table-centered thead th, 
.table-centered tbody td {
  text-align: center;
}

.table-hover tbody tr:hover {
  background-color: #f1f1f1;
}

.modal-dialog {
  max-width: 400px;
  margin: 1.75rem auto;
}

.modal-content {
  text-align: center;
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body p {
  margin-bottom: 10px;
}

/* eslint-disable no-bitwise */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-loop-func */
/* eslint-disable no-restricted-syntax */
import axios from 'axios';
import _ from 'lodash';
import { expose } from 'threads/worker';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';

dayjs.extend(isBetween); // Use the isBetween plugin for dayjs
const config = {};

const MAX_RETRY_ATTEMPTS = 2; // Số lần thử lại tối đa khi link download thất baị

const downloadFile = async (url) => {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    let { data } = response;
    if (data.byteLength % 5 !== 0) {
      data = data.slice(0, data.byteLength - (data.byteLength % 5));
    }
    return { data };
  } catch (error) {
    console.error('Failed to download file:', error);
    return { error: error.message }; // Return error message if the download fails
  }
};

const retryDownloadFile = async (url, attempts = MAX_RETRY_ATTEMPTS) => {
  let response = null;
  for (let i = 0; i < attempts; i += 1) {
    try {
      response = await axios.get(url, { responseType: 'arraybuffer' });
      if (response.data && (response.data.byteLength > 0 || response.data.length > 0)) {
        let { data } = response;
        if (data.byteLength % 5 !== 0) {
          data = data.slice(0, data.byteLength - (data.byteLength % 5));
        }
        return { data };
      }
    } catch (error) {
      console.error(`Retry attempt ${i + 1} failed for URL: ${url}`, error);
    }
  }
  return { error: `All retry attempts failed for URL: ${url}` }; // Return error message if all retry attempts fail
};

const processChunkedArray = (chunkedArray, start, stop) => {
  const beatData = {
    start,
    stop,
    beatPositions: [],
    beatEpochs: [],
    hesBeatStatus: [],
  };

  chunkedArray.forEach((item) => {
    const beatBytes = item.slice(2, 5).map(byte => (byte < 0 ? 256 + byte : byte));
    const beatPosition = (beatBytes[0] << 16) + (beatBytes[1] << 8) + beatBytes[2];
    const beatEpoch = dayjs(start).add(beatPosition / config.samplingFrequency, 'second').valueOf();
    beatData.beatPositions.push(beatPosition);
    beatData.beatEpochs.push(beatEpoch);
    beatData.hesBeatStatus.push(item[1]);
  });

  return beatData;
};

const processBeatData = (data, start, stop) => {
  const array = new Int8Array(data);
  const chunkedArray = _.chunk(array, 5);
  return processChunkedArray(chunkedArray, start, stop);
};

expose({
  createConfig: ({ samplingFrequency, querySignature }) => {
    config.samplingFrequency = samplingFrequency;
    config.querySignature = querySignature;
  },
  downloadSingleBeatFile: async (items) => {
    try {
      const pendingDownloads = [];
      const results = [];

      for (const item of items) {
        const { start, stop, aiPredict: { beatFinalPath } } = item;
        const trackedPromise = downloadFile(beatFinalPath)
          .then((result) => {
            if (result.data) {
              const processedData = processBeatData(result.data, start, stop);
              results.push(processedData);
            } else {
              console.error(`Failed to download file for item ID: ${item.id}`, result.error);
            }
          })
          .catch((error) => {
            console.error(`Failed to download file for item ID: ${item.id}`, error);
          });

        pendingDownloads.push(trackedPromise);
      }

      await Promise.all(pendingDownloads);

      const finalResult = {
        success: true, data: results,
      };

      return finalResult;
    } catch (error) {
      console.error('Failed to download and process single beat files:', error);
      return { success: false, message: error.message };
    }
  },

  downloadBeatListByDay: async (dateEpoch, data) => {
    try {
      const pendingDownloads = [];
      let completed = 0;
      const total = data.length;
      const results = [];
      let failedLinks = []; // Array to store failed link IDs

      const incrementCompleted = () => {
        completed += 1;
        return completed;
      };

      for (const [i, fileUrl] of data.entries()) {
        const { start, stop, id } = data[i];
        const keyStart = dayjs(start).startOf('hour').valueOf();
        const url = fileUrl?.aiPredict?.beatFinalPath;
        const trackedPromise = downloadFile(url)
          .then((result) => {
            if (result.data && (result.data.byteLength > 0 || result.data.length > 0)) {
              results.push({ key: keyStart, value: processBeatData(result.data, start, stop) });
              incrementCompleted();
            } else {
              failedLinks.push({ id, url, error: result.error || 'Empty or invalid response' }); // Store failed link with ID, URL, and error message
            }
          })
          .catch((error) => {
            console.error('Failed to download Beat list:', error);
            failedLinks.push({ id, url, error: error.message }); // Store failed link with ID, URL, and error message
            incrementCompleted();
          });

        pendingDownloads.push(trackedPromise);
      }

      await Promise.all(pendingDownloads);

      // Retry failed links
      for (const failedLink of failedLinks) {
        const { id, url } = failedLink;
        const result = await retryDownloadFile(url);
        if (result.data) {
          const keyStart = dayjs(data.find(item => item.id === id).start).startOf('hour').valueOf();
          results.push({ key: keyStart, value: processBeatData(result.data, data.find(item => item.id === id).start, data.find(item => item.id === id).stop) });
          failedLinks = failedLinks.filter(item => item.id !== id); // Remove successfully retried link
        } else {
          console.error('Failed to retry download of failed beat link:', id, url, result.error);
        }
      }

      const status = (completed / total) * 100;
      const metadata = {
        dateEpoch: +dateEpoch,
        status,
        total,
        completed,
        remaining: total - completed,
        failedLinks: failedLinks.map(link => ({ id: link.id, error: link.error })), // Include failed link IDs and errors in metadata
      };
      const finalResult = { result: results, metadata };
      postMessage({ type: 'beatData', data: finalResult });
      return 'done';
    } catch (error) {
      console.error('Failed to download beat list:', error);
      return [];
    }
  },

  downloadECGListByDay: async (dateEpoch, data) => {
    try {
      const pendingDownloads = [];
      const { querySignature } = config;
      let completed = 0;
      const total = data.length;
      const results = [];
      let failedLinks = []; // Array to store failed link IDs

      const incrementCompleted = () => {
        completed += 1;
        return completed;
      };

      for (const itemECG of data) {
        const url = `${itemECG.dataUrl}?${querySignature}`;
        const key = dayjs(itemECG.start.$d).startOf('hour').valueOf();

        const trackedPromise = downloadFile(url)
          .then((result) => {
            if (result.data && (result.data.byteLength > 0 || result.data.length > 0)) {
              results.push({ key, value: result.data });
              incrementCompleted();
            } else {
              failedLinks.push({ id: itemECG.id, url, error: result.error || 'Empty or invalid response' }); // Store failed link with ID, URL, and error message
            }
          })
          .catch((error) => {
            console.error('Failed to download ECG list:', error);
            failedLinks.push({ id: itemECG.id, url, error: error.message }); // Store failed link with ID, URL, and error message
            incrementCompleted();
          });

        pendingDownloads.push(trackedPromise);
      }

      await Promise.all(pendingDownloads);

      // Retry failed links
      for (const failedLink of failedLinks) {
        const { id, url } = failedLink;
        const result = await retryDownloadFile(url);
        if (result.data) {
          const key = dayjs(data.find(item => item.id === id).start.$d).startOf('hour').valueOf();
          results.push({ key, value: result.data });
          failedLinks = failedLinks.filter(item => item.id !== id); // Remove successfully retried link
        } else {
          console.error('Failed to retry download of failed ecg link:', id, url, result.error);
        }
      }

      const status = (completed / total) * 100;
      const metadata = {
        dateEpoch: +dateEpoch,
        status,
        total,
        completed,
        remaining: total - completed,
        failedLinks: failedLinks.map(link => ({ id: link.id, error: link.error })), // Include failed link IDs and errors in metadata
      };
      const finalResult = { result: results, metadata };
      postMessage({ type: 'ecgData', data: finalResult });
      return 'done';
    } catch (error) {
      console.error('Failed to download ECG list:', error);
      return [];
    }
  },
});
/* eslint-disable no-await-in-loop */
/* eslint-disable no-restricted-syntax */
/* eslint-disable import/no-webpack-loader-syntax */
/* eslint-disable import/no-unresolved */
import classnames from 'classnames';
import dayjs from 'dayjs';
import _ from 'lodash';
import React, {
  startTransition,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  useHistory,
  useParams,
} from 'react-router-dom';
import {
  TabContent,
  TabPane,
  UncontrolledTooltip,
} from 'reactstrap';
import {
  useRecoilState,
  useRecoilValue,
  useSetRecoilState,
} from 'recoil';
import { t } from 'ttag';
import {
  clearInterval,
  setInterval,
} from 'worker-timers';
import {
  Thread,
  Worker,
  spawn,
} from 'threads';
import beatWorker from 'threads-plugin/dist/loader?name=beats!../../Worker/beats.worker';
import fetchHolterBeatEventsCount from '../../Apollo/Functions/fetchHolterBeatEventsCount';
import fetchHolterEcgDataMap from '../../Apollo/Functions/fetchHolterEcgDataMap';
import fetchHolterOtherEventsCount from '../../Apollo/Functions/fetchHolterOtherEventsCount';
import fetchHolterRhythmEventsCount from '../../Apollo/Functions/fetchHolterRhythmEventsCount';
import fetchHolterTasks from '../../Apollo/Functions/fetchHolterTasks';
import fetchListEcgBookmarks from '../../Apollo/Functions/fetchListEcgBookmarks';
import fetchNewReportData from '../../Apollo/Functions/fetchNewReportData';
import fetchQuerySignature from '../../Apollo/Functions/fetchQuerySignature';
import handleMarkReportAsArtifactReport from '../../Apollo/Functions/handleMarkReportAsArtifactReport';
import handleUpdateReportStatusV2 from '../../Apollo/Functions/handleUpdateReportStatusV2';
import IconButton from '../../ComponentsV2/Buttons/iconButton';
import ConfirmModal from '../../ComponentsV2/ConfirmModal';
import FacilityInfoDrawer from '../../ComponentsV2/Drawers/facilityInfoDrawer';
import PatientInfoDrawer from '../../ComponentsV2/Drawers/patientInfoDrawer';
import StudyInfoDrawer from '../../ComponentsV2/Drawers/studyInfoDrawer';
import {
  // resetEcgViewerConfigStore,
  ECG_VIEWER_CONFIG_STORE,
} from '../../ComponentsV2/FabricJS/Constants';
import {
  CALL_CENTER_PORTAL_URL,
  EMITTER_CONSTANTS,
} from '../../ConstantsV2';
import {
  // OTHER_EVENT_TYPE_OBJECT,
  // OTHER_EVENT_TYPES,
  IS_NOT_EDIT_REPORT_MESSAGE,
} from '../../ConstantsV2/aiConstants';
import LOADING_TYPES from '../../ConstantsV2/loadingTypes';
import AiPDFReportTab from '../../LayoutV2/Reports/AiEditReport/AiPdfReport';
import BeatHR from '../../LayoutV2/Reports/AiEditReport/BeatHR';
import { combinedEventsInHeatmapState } from '../../LayoutV2/Reports/AiEditReport/BeatHR/recoil';
import {
  actionSnapshotRecoilState,
  ecgBookmarksState,
  ecgDataMapState,
  facilityNoteState,
  findingsState,
  isLoadedIndexDBState,
  isOpenProcessingLimitState,
  isShowTabHeaderState,
  isStartedAiProcessingState,
  originalDailySummariesState,
  profileAfibAvgHrState,
  reportDataState,
  reportInfoState,
  isUndoDisabledState,
  highPassThumbnailState,
  channelsThumbnailState,
  gainThumbnailState,
  sizeEventThumbnailConfigState,
} from '../../LayoutV2/Reports/AiEditReport/Recoil';
import {
  defaultReportOptions,
  reportOptionsState,
} from '../../LayoutV2/Reports/AiEditReport/AiPdfReport/recoil';
import eventEmitter from '../../UtilsV2/eventEmitter';
import RhythmEvents from '../../LayoutV2/Reports/AiEditReport/RhythmEvents';
import {
  beatEventCountState,
  otherEventCountState,
  rhythmEventCountState,
} from '../../LayoutV2/Reports/AiEditReport/RhythmEvents/recoil';
import StripsManagement from '../../LayoutV2/Reports/AiEditReport/StripsManagement';
import {
  CONFIG_ECG,
  REPORT_TYPE,
  logError,
} from '../../LayoutV2/Reports/AiEditReport/handler';
import { fetchHolterOtherEventsTypesRequest } from '../../ReduxV2/Actions/holterOtherEventsTypes';
import loadingPage from '../../ReduxV2/Actions/loading';
import closeIcon from '../../StaticV2/Images/Components/close-icon.svg';
import icArtifactActive from '../../StaticV2/Images/Components/ic-artifact-active.svg';
import icArtifact from '../../StaticV2/Images/Components/ic-artifact.svg';
import {
  timezoneToOffset,
  zeroPad,
  simulateKeyEvent,
} from '../../UtilsV2';
import {
  generateAiStatusReport,
  generateListDate,
  isHolterProcessingAvailable,
} from '../../UtilsV2/aiUtils';
import auth from '../../UtilsV2/auth';
import {
  useActions,
  useEmitter,
  useGetRecoilValue,
  useMergeState,
} from '../../UtilsV2/customHooks';
import logHandler from '../../UtilsV2/logHandler';
import socketio from '../../UtilsV2/socketio';
import {
  toastrError,
  toastrSuccess,
} from '../../UtilsV2/toastNotification';
import CheckSavePrompt from './CheckSavePrompt';
import ReportHeaderWrapper from './ReportHeader/reportHeaderWrapper';
import ReviewedReportIcon from './assets/reviewed-report-icon.svg';
import UnreviewedReportIcon from './assets/unreviewed-report-icon.svg';
import UndoIcon from './assets/undo-icon.svg';
import DebugObserver from './debugObserver';
import { clearAllDataStateRecoil, getDataStateRecoil, upsertDataStateRecoil } from '../../Store/dbStateRecoil';
import { resetHistoryStateRecoil } from '../../Store/dbHistoryStateRecoil';
import InitRecoilFromIndexDB from '../../LayoutV2/Reports/AiEditReport/Recoil/InitRecoilFromIndexDB';
import handleUpdateHolterProfile from '../../Apollo/Functions/handleUpdateHolterProfile';
import UndoStateRecoil from '../../LayoutV2/Reports/AiEditReport/Recoil/undoStateRecoil';
import ProgressLoading from '../../LayoutV2/Reports/AiEditReport/SharedModule/progressLoading';
import { checkHasChangedSavedIndexDB } from './handler';

// IndexDB for Beat Data and ECG Data
import {
  addMultipleBeatData, addMetaBeatData, clearDBBeatData,
} from '../../Store/dbBeatData';
import {
  addMultipleECGData, addMetaEcgData, clearDBEcgData,
} from '../../Store/dbECGData';

import studySummariesJson from '../../../dummyData/studySummaries.json';
// eslint-disable-next-line import/no-webpack-loader-syntax

/*
  All hot keys:
  N,S,V,Q,Z,X,C,W,F,ESC,B,CTRL+A,CTRL+S,D,R,A,arrow up down left right,>,<,1,2,3,4,5,6
  N,S,V,Q: change beat type
  D: delete beat/event
  Z: previous page
  X: next page
  C: open change duration event
  W: open add new event
  F: open add bookmark
  R: mark/unmark event reviewed
  ESC: escape from mode
  B: toggle Add Remove Beat mode (ECGViewer)
  A: mark event as artifact
  CTRL+A: select all strip
  CTRL+S: Save data
  arrow up down left right: navigate through strip in page
  1,2,3,4,5,6: set bulk action beat
*/
const AiReportPage = () => {
  const { studyFid } = useParams();

  const history = useHistory();

  const isMacOS = navigator.userAgent.indexOf('Mac') !== -1;
  const [loadingPageAction, fetchHolterOtherEventsTypesAction] = useActions([loadingPage, fetchHolterOtherEventsTypesRequest]);

  const defaultActiveTab = useRef('4');

  const [state, setState] = useMergeState({
    isLoadedData: false,
    isGeneratingNormalReportInCallCenter: false,
    isOpenStudyInfoDrawer: false,
    isOpenPatientInfoDrawer: false,
    isOpenFacilityInfoDrawer: false,
    isOpenNoActivityModal: false,
    isOpenConfirmArtifact: false,
    isOpenConfirmNavigateTab: false,
    isOpenUseDbIndexModal: false,
    isLoadingSaveAiReport: false,
    conflictUsers: [],
    activeTab: defaultActiveTab.current,
  });
  const [isNotEdit, setIsNotEdit] = useState(true);
  const [isLoadIndexDB, setIsLoadIndexDB] = useState(false);
  const [prevEcgDataMap, setPrevEcgDataMap] = useState(null);
  const [reportData, setReportData] = useRecoilState(reportDataState);
  const [reportInfo, setReportInfo] = useRecoilState(reportInfoState);
  const getReportInfo = useGetRecoilValue(reportInfoState);
  const [ecgDataMap, setEcgDataMap] = useRecoilState(ecgDataMapState);
  const isStartedAiProcessing = useRecoilValue(isStartedAiProcessingState);
  const [isOpenProcessingLimit, setIsOpenProcessingLimit] = useRecoilState(isOpenProcessingLimitState);
  const setFindings = useSetRecoilState(findingsState);
  const setFacilityNote = useSetRecoilState(facilityNoteState);
  const setOriginalDailySummaries = useSetRecoilState(originalDailySummariesState);
  const setProfileAfibAvgHr = useSetRecoilState(profileAfibAvgHrState);
  const isShowTabHeader = useRecoilValue(isShowTabHeaderState);
  const setCombinedEventsInHeatmap = useSetRecoilState(combinedEventsInHeatmapState);
  const setEcgBookmarks = useSetRecoilState(ecgBookmarksState);
  const setActionSnapshotRecoil = useSetRecoilState(actionSnapshotRecoilState);
  const setHolterBeatEventsCount = useSetRecoilState(beatEventCountState);
  const setHolterRhythmEventsCount = useSetRecoilState(rhythmEventCountState);
  const setHolterOtherEventsCount = useSetRecoilState(otherEventCountState);
  const setHighPassThumbnail = useSetRecoilState(highPassThumbnailState);
  const setSizeEventThumbnailConfig = useSetRecoilState(sizeEventThumbnailConfigState);
  const setGainThumbnail = useSetRecoilState(gainThumbnailState);
  const setChannelsThumbnail = useSetRecoilState(channelsThumbnailState);
  const setReportOptions = useSetRecoilState(reportOptionsState);

  const isLoadedIndexDB = useRecoilValue(isLoadedIndexDBState);
  const [isUndoDisabled, setIsUndoDisabled] = useRecoilState(isUndoDisabledState);
  useEffect(() => {
    // Set the default value to true
    setTimeout(() => {
      setIsUndoDisabled(true);
    }, 100);
    const updateIndex = (currentIndex) => {
      setIsUndoDisabled(currentIndex < 1);
    };
    eventEmitter.addListener(EMITTER_CONSTANTS.UNDO_REDO_CURRENT_INDEX, updateIndex);

    // Clean up the event listener on component unmount
    return () => {
      // eventEmitter.removeListener(EMITTER_CONSTANTS.UNDO_REDO_CURRENT_INDEX, updateIndex);
    };
  }, []);

  const {
    studyId,
    profileId,
    facilityId,
    reportId,
    isAbortedStudy,
    startReport,
    timezoneOffset,
  } = reportInfo;

  const roomReport = useRef();
  const updatingTabCount = useRef(0);
  const tabIndexConfirmNavigate = useRef();
  const tab1Ref = useRef();
  const tab2Ref = useRef();
  const tab3Ref = useRef();
  const tab4Ref = useRef();
  const findingRef = useRef();
  const ecgDisclosureRef = useRef();
  const sessionInfoRef = useRef();

  const fetchEventsCount = async () => {
    try {
      const eventsCountFilter = {
        studyId,
        profileId,
      };
      const promises = [
        fetchHolterBeatEventsCount(eventsCountFilter, false, null, false),
        fetchHolterRhythmEventsCount(eventsCountFilter, false, null, false),
        fetchHolterOtherEventsCount(eventsCountFilter, false, null, false),
      ];
      const [
        holterBeatEventsCount,
        holterRhythmEventsCount,
        holterOtherEventsCount,
      ] = await Promise.all(promises);
      setHolterBeatEventsCount(holterBeatEventsCount);
      setHolterRhythmEventsCount(holterRhythmEventsCount);
      setHolterOtherEventsCount(holterOtherEventsCount);
    } catch (error) {
      logError('Failed to fetch holter rhythm events count: ', error);
    }
  };

  const getDatabaseStateRecoil = async () => {
    const activeTab = await getDataStateRecoil('activeTab');
    if (activeTab?.value) {
      setState({ activeTab: activeTab?.value });
      defaultActiveTab.current = activeTab?.value;
    }
  };

  const restDefaultState = () => {
    setHighPassThumbnail(1);
    setGainThumbnail(7.5);
    setChannelsThumbnail([4]);
    setSizeEventThumbnailConfig({ name: 'Small', width: 415, height: 87.1 });
    setReportOptions(defaultReportOptions);
    upsertDataStateRecoil('hourlyBeatDataArray', []);
  };

  // TODO : handle clear all beat and ecg data
  const clearAllBeatData = async () => {
    await clearDBEcgData();
    await clearDBBeatData();
  };

  const clearDataAndResaveSessionInfo = async () => {
    await clearAllDataStateRecoil();
    clearAllBeatData();
    setFindings(findingRef.current);
    if (!isNotEdit && sessionInfoRef.current) {
      upsertDataStateRecoil('sessionInfo', sessionInfoRef.current);
      upsertDataStateRecoil('activeTab', state.activeTab);
    }
  };

  const handleClearIndexDB = async (info) => {
    try {
      const dataSave = await getDataStateRecoil('sessionInfo');
      if (dataSave?.value) {
        const { studyId, profileId, sessionTime } = info;
        if (dataSave?.value?.studyId !== studyId
          || dataSave?.value?.profileId !== profileId
          || dayjs(dataSave?.value?.sessionTime).valueOf() !== dayjs(sessionTime).valueOf()) {
          // clean all data
          clearDataAndResaveSessionInfo();
          setIsLoadIndexDB(true);
        } else {
          // show popup when stay in tab 1 or tab 2
          const activeTab = await getDataStateRecoil('activeTab');
          // check has change data
          const isChanged = await checkHasChangedSavedIndexDB({
            activeTab: activeTab?.value,
            currentFinding: findingRef.current,
            currentEcgDisclosure: ecgDisclosureRef.current,
          });
          if (isChanged) {
            setState({ isOpenUseDbIndexModal: true });
          } else {
            clearDataAndResaveSessionInfo();
            setIsLoadIndexDB(true);
          }
        }
      } else {
        setIsLoadIndexDB(true);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const onDiscardChangeSavedData = () => {
    setState({ isOpenUseDbIndexModal: false });
    clearDataAndResaveSessionInfo();
    setIsLoadIndexDB(true);
  };

  const onKeepEditingWithSavedData = () => {
    setState({ isOpenUseDbIndexModal: false });
    setIsLoadIndexDB(true);
  };

  const fetchReportData = async (studyFid) => {
    try {
      const input = {
        studyFid: studyFid ? parseInt(studyFid, 10) : undefined,
        type: REPORT_TYPE,
      };
      const aiReportData = await fetchNewReportData({ input });
      const { reportData, isSuccess } = aiReportData;
      if (isSuccess && !_.isEmpty(reportData)) {
        if (reportData.study?.isArchived || generateAiStatusReport(reportData.study) !== 'Ready') {
          history.replace('/404');
          return;
        }
        const studyId = reportData.study?.id;
        const profileId = reportData.study?.holterProfile?.id;
        const [downloadEcgDataMap, holterTasks, studyReportsData] = await Promise.all([
          fetchHolterEcgDataMap({ studyId, profileId }),
          fetchHolterTasks(),
          fetchNewReportData({ id: studyId, isStudyReport: true }),
        ]);
        if (downloadEcgDataMap) {
          CONFIG_ECG.samplingFrequency = downloadEcgDataMap.samplingFrequency;
          CONFIG_ECG.gain = downloadEcgDataMap.gain;
          ECG_VIEWER_CONFIG_STORE.visibleChannels = _.map(downloadEcgDataMap.channels, item => Number(item.slice(-1)) - 1);
          ECG_VIEWER_CONFIG_STORE.originalChannels = downloadEcgDataMap.channels;
        }
        const studyReport = _.filter(studyReportsData, x => x.type === 'Study')[0];
        const aiReport = _.find(studyReportsData, x => x.type === 'AI EOU');
        socketio.emitRoom(EMITTER_CONSTANTS.HOLTER_GENERAL_ROOM);
        socketio.emitRoom(EMITTER_CONSTANTS.HOLTER_PROFILE_ROOM.replace('{profileId}', profileId));
        socketio.emitRoom(reportData.study?.device?.deviceId);
        // *: Join room report
        if (reportData?.report?.type === 'Study' || reportData.report?.type === 'AI EOU' || reportData?.report?.reportId) {
          const room = `${zeroPad(studyFid)}_ai_eou`;
          roomReport.current = room;
          socketio.sendJoinReportRoom(roomReport.current);
        }
        // isHolterReport: [STUDY_TYPE.HOLTER, STUDY_TYPE.EXTENDED_HOLTER, STUDY_TYPE.MCT_PEEK].includes(reportData.study?.studyType)
        const startReport = reportData?.report?.start;
        const stopReport = reportData?.report?.stop;
        const timezone = reportData.study?.timezone;
        const timezoneOffset = timezoneToOffset(timezone);
        const listDate = generateListDate(startReport, stopReport, timezoneOffset);
        const combinedEventsInHeatmap = {};
        _.forEach(listDate, (date) => {
          combinedEventsInHeatmap[date] = [];
        });
        setCombinedEventsInHeatmap(combinedEventsInHeatmap);
        const info = {
          studyId: reportData.study?.id,
          profileId: reportData.study?.holterProfile?.id,
          sessionTime: reportData.study?.holterProfile?.sessionTime,
          facilityId: reportData.study?.facility?.id,
          reportId: reportData.report?.id,
          reportFid: reportData.report?.reportId,
          isAbortedStudy: reportData.study?.status === 'Aborted',
          studyFid: reportData.study?.friendlyId,
          patientName: `${reportData.study?.info?.patient?.firstName} ${reportData.study?.info?.patient?.lastName}`,
          facilityName: reportData.study?.facility?.name,
          reportType: reportData.report?.type,
          timezone,
          timezoneOffset,
          startReport,
          stopReport,
        };
        setReportInfo(info);

        // *: Sort data by start time
        downloadEcgDataMap.data.sort((a, b) => a.start - b.start);
        for (let i = 0; i < downloadEcgDataMap.data.length; i += 1) {
          const item = downloadEcgDataMap.data[i];
          item.start = dayjs(item.start);
          item.stop = dayjs(item.stop);
        }

        findingRef.current = reportData?.report?.technicianComments || reportData?.study?.holterProfile?.technicianComments;
        ecgDisclosureRef.current = {
          ecgDisclosure: reportData.study?.holterProfile?.ecgDisclosure,
          timezoneOffset,
          ecgDataMap: downloadEcgDataMap,
        };
        // check clean IndexDB
        handleClearIndexDB(info);

        logHandler.setStudyId(studyId);
        setProfileAfibAvgHr(reportData.study?.holterProfile?.afibAvgHr);
        setOriginalDailySummaries(reportData.study?.holterProfile?.mctDailySummaries);
        setEcgDataMap(downloadEcgDataMap);
        // setFindings(reportData?.report?.technicianComments || reportData?.study?.holterProfile?.technicianComments);
        setFacilityNote(reportData?.study?.facility?.facilityNote);
        setReportData(reportData);
        setIsOpenProcessingLimit(!isHolterProcessingAvailable(holterTasks, reportData?.study?.friendlyId));
        setState({
          isLoadedData: true,
          isGeneratingNormalReportInCallCenter: studyReport?.status === 'Rendering',
          studyReport,
          aiReport,
        });
      } else {
        history.replace('/404');
      }
    } catch (error) {
      logError('Failed to load report data ', error);
      history.push('/404');
    }
    loadingPageAction();
  };

  const toggleDisplayStudyInfoDrawer = () => {
    setState({ isOpenStudyInfoDrawer: !state.isOpenStudyInfoDrawer });
  };

  const toggleDisplayPatientInfoDrawer = () => {
    setState({ isOpenPatientInfoDrawer: !state.isOpenPatientInfoDrawer });
  };

  const toggleDisplayFacilityInfoDrawer = () => {
    setState({ isOpenFacilityInfoDrawer: !state.isOpenFacilityInfoDrawer });
  };

  const onClickReload = () => {
    // *Cannot use window.location.reload() because it not work in Firefox
    //  window.location.reload();
    window.location.href = window.location.href;
  };

  const handleOnClickArtifactReport = async (flag) => {
    try {
      await handleMarkReportAsArtifactReport(reportId, flag);
    } catch (err) {
      toastrError(err, t`Error`);
    }
    setState({ isOpenConfirmArtifact: false });
  };

  const navigateTab = (tab) => {
    if (tab !== state.activeTab) {
      if (isNotEdit) {
        setState({ activeTab: tab || defaultActiveTab.current });
        return;
      }

      // check data changed
      const tabRef = {
        1: tab1Ref.current,
        2: tab2Ref.current,
        3: tab3Ref.current,
        4: tab4Ref.current,
      }[state.activeTab];
      const isChangedData = tabRef ? tabRef.isChangedData() : false;
      console.log('[aiReport]-navigateTab', isChangedData, tab);
      if (isChangedData) {
        tabIndexConfirmNavigate.current = tab;
        setState({ isOpenConfirmNavigateTab: true });
      } else {
        //* Do not reset config
        // resetEcgViewerConfigStore();
        tabIndexConfirmNavigate.current = undefined;
        setState({ activeTab: tab || defaultActiveTab.current, isOpenConfirmNavigateTab: false });
        setActionSnapshotRecoil(1);
        // reset undo/redo related components
        restDefaultState();
        setTimeout(() => {
          resetHistoryStateRecoil();
        }, 500);
      }
    }
  };

  const onClickCancelNavigateTab = () => {
    tabIndexConfirmNavigate.current = undefined;
    setState({ isOpenConfirmNavigateTab: false });
  };

  const onClickNavigateWithoutSave = () => {
    const tabRef = {
      1: tab1Ref.current,
      2: tab2Ref.current,
      3: tab3Ref.current,
      4: tab4Ref.current,
    }[state.activeTab];
    if (tabRef) {
      tabRef.resetData();
    }
    const tabNavigate = tabIndexConfirmNavigate.current;
    // reset undo/redo related components
    restDefaultState();
    setTimeout(() => {
      resetHistoryStateRecoil();
    }, 500);
    setTimeout(() => {
      navigateTab(tabNavigate);
    }, 20);
  };

  const onClickConfirmNavigateTab = () => {
    const tabRef = {
      1: tab1Ref.current,
      2: tab2Ref.current,
      3: tab3Ref.current,
      4: tab4Ref.current,
    }[state.activeTab];
    if (tabRef) {
      tabRef.onClickSaveReport();
    }
    // reset undo/redo related components
    restDefaultState();
    setTimeout(() => {
      resetHistoryStateRecoil();
    }, 500);
  };

  const saveReportOnClick = () => {
    const tabRef = {
      1: tab1Ref.current,
      2: tab2Ref.current,
      3: tab3Ref.current,
      4: tab4Ref.current,
    }[state.activeTab];
    if (tabRef) {
      tabRef.onClickSaveReport();
    }
    // reset undo/redo related components
    restDefaultState();
    setTimeout(() => {
      resetHistoryStateRecoil();
    }, 500);
  };

  const handleNoActivity = () => {
    if (window.isStopAiProcess) {
      return;
    }

    socketio.sendLeaveAllRooms();
    setState({ isOpenNoActivityModal: true });
  };

  const checkDataChange = () => {
    const result = (state.isOpenNoActivityModal ? false : (
      tab1Ref.current?.isChangedData?.()
      || tab2Ref.current?.isChangedData?.()
      || tab3Ref.current?.isChangedData?.()
      || tab4Ref.current?.isChangedData?.()
    ));
    console.log('[aiReport]-checkStudyReportDataChange', result, state.isOpenNoActivityModal);
    return result;
  };

  const renderMarkArtifact = () => (
    <div id="bt-artifact">
      <IconButton
        disabled={
          reportData?.study?.holterProfile?.isArtifactReport
          || isNotEdit
        }
        iconComponent={(
          <img
            src={
              (reportData?.study?.holterProfile?.isArtifactReport || reportData?.report?.isArtifactReport)
                ? icArtifactActive
                : icArtifact
            }
            alt={t`Artifact icon`}
          />
        )}
        onClick={() => {
          if (!reportData?.report?.isArtifactReport) {
            setState({ isOpenConfirmArtifact: true });
          } else {
            handleOnClickArtifactReport(!reportData?.report?.isArtifactReport);
          }
        }}
      />

      <UncontrolledTooltip
        target="bt-artifact"
        className="custom-tooltip"
        placement="bottom"
        delay={{ show: 0, hide: 0 }}
        hideArrow
      >
        {(() => {
          if (reportData?.study?.holterProfile?.isArtifactReport) return t`Artifact report due to no beats and events detected`;
          if (isNotEdit) return IS_NOT_EDIT_REPORT_MESSAGE;
          return reportData?.report?.isArtifactReport ? t`Unmark report as artifact` : t`Mark report as artifact`;
        })()}
      </UncontrolledTooltip>
    </div>
  );

  const handleMarkReviewedClick = async () => {
    if (_.isEmpty(state.studyReport) && _.isEmpty(state.aiReport)) {
      return;
    }

    const isReviewedAiReport = state.aiReport.status === 'Reviewed';
    try {
      const status = state.aiReport.status === 'Reviewed'
        ? 'Ready'
        : 'Reviewed';
      const aiReportFilter = {
        id: state.aiReport.id,
        status,
      };
      let reportFilter;
      const promises = [handleUpdateReportStatusV2(aiReportFilter)];
      if (state.studyReport) {
        reportFilter = {
          id: state.studyReport.id,
          status,
        };
        promises.push(handleUpdateReportStatusV2(reportFilter));
      }
      await Promise.all(promises);
      setState({
        studyReport: state.studyReport
          ? {
            ...state.studyReport,
            status: reportFilter.status,
          }
          : null,
        aiReport: {
          ...state.aiReport,
          status: aiReportFilter.status,
        },
      });
      toastrSuccess(
        isReviewedAiReport
          ? t`Mark as unreviewed`
          : t`Mark as reviewed`,
        t`Success`,
      );
    } catch (error) {
      console.error('Failed to mark reviewed', error);
      toastrError(
        isReviewedAiReport
          ? t`Failed to mark as unreviewed`
          : t`Failed to mark as reviewed`,
        t`Error`,
      );
    }
  };

  const renderMarkReviewed = () => {
    // const isReviewedReport = state.studyReport?.status === 'Reviewed';
    const isReviewedAiReport = state.aiReport?.status === 'Reviewed';
    return (
      <div id="bt-mark-reviewed">
        <IconButton
          iconComponent={(
            <img
              src={
                isReviewedAiReport
                  ? ReviewedReportIcon
                  : UnreviewedReportIcon
              }
              alt={t`Artifact icon`}
            />
          )}
          MarkAsReviewedIcon
          onClick={handleMarkReviewedClick}
        />

        <UncontrolledTooltip
          target="bt-mark-reviewed"
          className="custom-tooltip"
          placement="bottom"
          delay={{ show: 0, hide: 0 }}
          hideArrow
        >
          {
            isReviewedAiReport
              ? t`Mark as unreviewed`
              : t`Mark as reviewed`
          }
        </UncontrolledTooltip>
      </div>
    );
  };

  const renderUndoState = () => (
    <div id="bt-undo-btn">
      <IconButton
        className="more-icon mr-3"
        isOutline
        disabled={isUndoDisabled}
        iconComponent={(
          <img src={UndoIcon} alt={t`Undo icon`} />
          )}
        onClick={() => { simulateKeyEvent('Z', { ctrlKey: true }); }}
      />

      <UncontrolledTooltip
        target="bt-undo-btn"
        className="custom-tooltip"
        placement="bottom"
        delay={{ show: 0, hide: 0 }}
        hideArrow
      >
        {/* TODO: currently set disabled is true */}
        {isUndoDisabled ? t`There is nothing to undo` : (isMacOS ? t`Undo  ⌘ Z` : t`Undo  Ctrl Z`)}
      </UncontrolledTooltip>
    </div>
  );

  const handleFetchBookmarks = async () => {
    try {
      const ecgBookmarks = await fetchListEcgBookmarks({
        studyId,
        sortOrder: 'asc',
        skip: 0,
      }, 0);
      setEcgBookmarks(ecgBookmarks);
    } catch (error) {
      logError('Failed to fetch bookmarks ', error);
    }
  };

  useEffect(() => {
    if (isStartedAiProcessing) {
      fetchEventsCount();
      handleFetchBookmarks();
    }
  }, [isStartedAiProcessing]);

  useEffect(() => {
    let interval;
    //* Refresh query signature every 1 hour
    if (state.isLoadedData) {
      const fetchNewQuerySignature = async () => {
        try {
          const querySignature = await fetchQuerySignature({ studyId });
          startTransition(() => {
            setEcgDataMap(currentEcgDataMap => ({ ...currentEcgDataMap, querySignature }));
          });
        } catch (error) {
          console.log(error);
        }
      };
      interval = setInterval(() => {
        fetchNewQuerySignature();
      }, 3600000); // 1 hour
    }
    return () => {
      try {
        if (interval) {
          clearInterval(interval);
        }
      } catch (error) {
        console.log(error);
      }
    };
  }, [state.isLoadedData, studyId]);

  useEffect(() => {
    if (Number(studyFid)) {
      // get database local
      getDatabaseStateRecoil();
      fetchReportData(studyFid);

      // TODO: Fetch other holter events types
      // handleFetchHolterOtherEventsTypes();
      // fetchHolterOtherEventsTypesAction();
    } else {
      history.replace('/404');
    }
  }, [studyFid]);

  useEffect(() => {
    upsertDataStateRecoil('activeTab', state.activeTab);
  }, [state.activeTab]);

  useEffect(() => {
    if (!isNotEdit) {
      const info = getReportInfo();
      const sessionTime = dayjs();
      // update session time
      const sessionInfo = {
        sessionTime: sessionTime.toISOString(),
        studyId: info.studyId,
        profileId: info.profileId,
      };
      const updateHolterProfileInput = {
        id: info.profileId,
        sessionTime,
      };
      sessionInfoRef.current = sessionInfo;
      handleUpdateHolterProfile(updateHolterProfileInput);
      upsertDataStateRecoil('sessionInfo', sessionInfo);
    }
  }, [isNotEdit]);

  useEmitter(EMITTER_CONSTANTS.REPORT_UPDATED, (msg) => {
    const reportDataClone = _.cloneDeep(reportData);
    if (msg.studyFid === reportDataClone.study?.friendlyId) {
      if (msg.id === reportDataClone.report?.id) {
        _.assign(reportDataClone.report, msg);
        setReportData(reportDataClone);
      } else {
        // Report format cũ ở bên callcenter nếu đang generate sẽ chặn ko cho copy report AI
        setState({ isGeneratingNormalReportInCallCenter: msg.status === 'Rendering' });
      }
    }
  }, [reportData]);

  useEmitter(EMITTER_CONSTANTS.REPORT_ROOM_USER, async (msg) => {
    const updatedEvent = _.findLast(msg, x => x.room === roomReport.current);
    if (updatedEvent) {
      const { users } = updatedEvent;

      const accessToken = auth.getOriginalToken();
      // *: Check user can edit report
      let newIsNotEdit = true;
      const sortedConflictUsers = users?.sort((a, b) => (a.time - b.time));
      const firstUser = sortedConflictUsers?.length > 0 ? sortedConflictUsers[0] : {};
      if (!_.isEmpty(firstUser.userId) && !_.isEmpty(firstUser.token)) {
        if (firstUser.userId === auth.userId() && firstUser.token === (accessToken || '').slice(-10)) {
          newIsNotEdit = false;
        } else {
          newIsNotEdit = true;
        }
      } else {
        newIsNotEdit = true;
      }
      console.log('[aiReport]-SOCKETROOMUSER', users, accessToken, firstUser, newIsNotEdit);
      //* Reload 2nd user when 1st user exit
      if (isNotEdit && !newIsNotEdit && isStartedAiProcessing && state.conflictUsers.length > 1 && users.length === 1) {
        logHandler.addLog('reload', {
          users, conflictUsers: state.conflictUsers, isNotEdit, newIsNotEdit,
        });
        await logHandler.sendLog();
        onClickReload();
        return;
      }
      setIsNotEdit(newIsNotEdit);
      setState({ conflictUsers: sortedConflictUsers });
    }
  }, [isNotEdit, state.conflictUsers, isStartedAiProcessing]);

  useEmitter(EMITTER_CONSTANTS.HOLTER_PROFILE_UPDATED, (msg) => {
    const reportDataClone = _.cloneDeep(reportData);
    if (msg?.ecgDisclosure) {
      _.assign(reportDataClone.study?.holterProfile, { ecgDisclosure: msg.ecgDisclosure });
    }
    if (!_.isEmpty(msg?.reportConfiguration)) {
      _.assign(reportDataClone.study?.holterProfile, { reportConfiguration: msg.reportConfiguration });
    }
    setReportData(reportDataClone);
  }, [reportData]);

  useEmitter(EMITTER_CONSTANTS.AI_UPDATE_TAB, (msg) => {
    updatingTabCount.current += 1;
    console.log('[aiReport]-AI_UPDATE_TAB', updatingTabCount.current);
  }, []);

  useEmitter(EMITTER_CONSTANTS.AI_LOADING, (msg) => {
    // {
    //   isLoading: boolean,
    // }
    const { isLoading } = msg || {};
    console.log('[aiReport]-AI_LOADING', msg, updatingTabCount.current, tabIndexConfirmNavigate.current, state.isOpenConfirmNavigateTab);
    if (isLoading) {
      updatingTabCount.current = 0;
      setState({ isLoadingSaveAiReport: true });
    } else if (updatingTabCount.current > 0) {
      updatingTabCount.current -= 1;
      if (updatingTabCount.current === 0) {
        setState({ isLoadingSaveAiReport: false });
        const tabNavigate = tabIndexConfirmNavigate.current;
        if (state.isOpenConfirmNavigateTab && tabNavigate) {
          setTimeout(() => {
            navigateTab(tabNavigate);
          }, 20);
        }
      }
    } else {
      updatingTabCount.current = 0;
      setState({ isLoadingSaveAiReport: false });
      const tabNavigate = tabIndexConfirmNavigate.current;
      if (state.isOpenConfirmNavigateTab && tabNavigate) {
        setTimeout(() => {
          navigateTab(tabNavigate);
        }, 20);
      }
    }
  }, [state.isOpenConfirmNavigateTab]);

  useEmitter(EMITTER_CONSTANTS.COMMAND_PROGRESS_UPDATED, (msg) => {
    const {
      command, doneTasks, totalTasks, percentage,
    } = msg;
    if (command === 'update-report-data') {
      loadingPageAction(`${LOADING_TYPES.GENERATE_REPORT} ${percentage} %`);
    }
  }, []);

  useEmitter(EMITTER_CONSTANTS.EVENTSUPDATED_EVENT, (msg) => {
    if (isStartedAiProcessing) {
      fetchEventsCount();
    }
  }, [isStartedAiProcessing]);

  // Generic function to group data by epoch start of the day
  const groupDataByEpochStartOfDay = (data, dateKey) => data.reduce((acc, item) => {
    const dateEpoch = dayjs(item[dateKey]).startOf('day').valueOf();
    if (!acc[dateEpoch]) {
      acc[dateEpoch] = [];
    }
    acc[dateEpoch].push(item);
    return acc;
  }, {});


  const handleDownloadBeatList = async () => {
    let thread;

    try {
      // Initialize worker and spawn a thread
      const worker = new Worker(beatWorker);
      thread = await spawn(worker);

      // Configure the thread with necessary parameters
      await thread.createConfig({
        samplingFrequency: ecgDataMap.samplingFrequency,
        querySignature: ecgDataMap.querySignature,
      });

      // Define how the worker should handle incoming messages
      worker.onmessage = async (message) => {
        const { type, data } = message.data;
        if (type === 'beatData' || type === 'ecgData') {
          const { result, metadata } = data;
          console.log(`[beatWorker] ${type}`, result.length, metadata);

          if (metadata.failedLinks && metadata.failedLinks.length > 0) {
            metadata.failedLinks.forEach((link) => {
              console.error(`Failed to download file ${type} with ID: ${link.id}, Error: ${link.error}`);
            });
          }

          if (type === 'beatData') {
            await addMultipleBeatData(result);
            await addMetaBeatData(metadata.dateEpoch, metadata);
          } else if (type === 'ecgData') {
            await addMultipleECGData(result);
            await addMetaEcgData(metadata.dateEpoch, metadata);
          }
        }
      };

      // Group data by epoch start of the day
      const groupedDataBeat = groupDataByEpochStartOfDay(studySummariesJson, 'start');
      const groupedDataECG = groupDataByEpochStartOfDay(ecgDataMap.data, 'start');

      // Process beat data in worker
      for (const dateEpoch of Object.keys(groupedDataBeat)) {
        const data = groupedDataBeat[dateEpoch];
        await thread.downloadBeatListByDay(dateEpoch, data);
      }

      // Process ECG data in worker
      for (const dateEpoch of Object.keys(groupedDataECG)) {
        const data = groupedDataECG[dateEpoch];
        await thread.downloadECGListByDay(dateEpoch, data);
      }
    } catch (error) {
      console.error('Failed to download beat list:', error);
    } finally {
      // Terminate the worker thread
      if (thread) {
        // Thread.terminate(thread).catch(console.error);
      }
    }
  };

  useEffect(() => {
    if (
      ecgDataMap
      && Object.keys(ecgDataMap).length > 0
      && !_.isEqual(ecgDataMap.data.length, prevEcgDataMap?.data.length)
    ) {
      handleDownloadBeatList();
      setPrevEcgDataMap(ecgDataMap);
    }
  }, [ecgDataMap]);


  return (
    <>
      <CheckSavePrompt
        isNotEdit={isNotEdit}
        condition={checkDataChange}
      />
      <StudyInfoDrawer
        visible={state.isOpenStudyInfoDrawer}
        title={t`Study Information`}
        fetchStudyId={studyId}
        handleClickCloseButton={toggleDisplayStudyInfoDrawer}
      />
      <PatientInfoDrawer
        visible={state.isOpenPatientInfoDrawer}
        title={t`Patient Information`}
        studyId={studyId}
        handleClickCloseButton={toggleDisplayPatientInfoDrawer}
      />
      <FacilityInfoDrawer
        visible={state.isOpenFacilityInfoDrawer}
        title={t`Facility Information`}
        facilityId={facilityId}
        handleClickCloseButton={toggleDisplayFacilityInfoDrawer}
        isAbortedStudy={isAbortedStudy}
      />
      <ConfirmModal
        isOpen={isOpenProcessingLimit}
        onClickRightButton={() => { document.location.href = CALL_CENTER_PORTAL_URL; }}
        rightButtonName={t`Okay`}
        title={t`Approaching processing limit`}
        question={t`The current limit for viewing and processing reports by AI has been exceeded.
          Please try again later.`}
        isRedBtn={false}
      />
      <ConfirmModal
        isOpen={state.isOpenNoActivityModal}
        onClickRightButton={onClickReload}
        rightButtonName={t`Reload The Page`}
        title={t`Notification`}
        question={t`Since there has been no activity for the past 30 minutes, please reload the page to resume.`}
        isRedBtn={false}
      />
      <ConfirmModal
        isOpen={state.isOpenConfirmArtifact}
        onClickLeftButton={() => { setState({ isOpenConfirmArtifact: false }); }}
        onClickRightButton={() => handleOnClickArtifactReport(true)}
        leftButtonName={t`No`}
        rightButtonName={t`Yes`}
        title={t`Mark report as artifact`}
        question={t`Are you sure you want to mark this report as an "Artifact report"?`}
      />
      <ConfirmModal
        isOpen={state.isOpenUseDbIndexModal}
        className="unsaved-change-modal --use-db-index"
        onClickLeftButton={onDiscardChangeSavedData}
        onClickRightButton={onKeepEditingWithSavedData}
        leftButtonName={t`Discard changes`}
        rightButtonName={t`Keep editing`}
        title={t`Unsaved changes`}
        question={t`There are unsaved changes. If you would like to keep changes, press the “Keep editing” button below.`}
      />
      <ConfirmModal
        isOpen={state.isOpenConfirmNavigateTab}
        className="unsaved-change-modal"
        onClickLeftButton={onClickNavigateWithoutSave}
        onClickRightButton={onClickConfirmNavigateTab}
        leftButtonName={state.isLoadingSaveAiReport ? null : t`Don’t Save`}
        rightButtonName={t`Save Changes`}
        isFilledRightBtn
        isBoldLeftBtn
        title={(
          <div className="title-unsaved-change">
            <div>{t`Unsaved changes`}</div>
            <IconButton
              iconComponent={(
                <img
                  src={closeIcon}
                  alt={t`Close icon`}
                />
              )}
              onClick={onClickCancelNavigateTab}
            />
          </div>
        )}
        question={t`You're about to leave this tab with unsaved changes. What would you like to do before proceeding?`}
        isRedBtn={false}
        isSaving={state.isLoadingSaveAiReport}
      />
      <div
        className={classnames('custom-page')}
      >
        <ReportHeaderWrapper
          isLoadedData={state.isLoadedData}
          title={t`End of Use report`}
          conflictUsers={state.conflictUsers}
          toggleDisplayStudyInfoDrawer={toggleDisplayStudyInfoDrawer}
          toggleDisplayPatientInfoDrawer={toggleDisplayPatientInfoDrawer}
          toggleDisplayFacilityInfoDrawer={toggleDisplayFacilityInfoDrawer}
          markArtifactComponent={renderMarkArtifact()}
          markReviewedComponent={renderMarkReviewed()}
          undoStateComponent={renderUndoState()}
          isDisableSaveReport={isNotEdit || isAbortedStudy}
          onClickSaveReport={saveReportOnClick}
          isLoadingSaveAiReport={state.isLoadingSaveAiReport}
          isNotEdit={isNotEdit}
          profileId={profileId}
          studyId={studyId}
          isArtifactReport={reportData?.report?.isArtifactReport}
          activeTab={state.activeTab}
          navigateTab={navigateTab}
          isStartedAiProcessing={isStartedAiProcessing}
        />
        {
          state.isLoadedData && (
            <>
              {
                isLoadIndexDB && (
                  <InitRecoilFromIndexDB />
                )
              }
              {/* component undo and redo */}
              <UndoStateRecoil />

              <DebugObserver tab1Ref={tab1Ref} tab2Ref={tab2Ref} tab3Ref={tab3Ref} tab4Ref={tab4Ref} />
              <TabContent
                className={classnames('study-report-top-tab-content', isShowTabHeader ? '' : '--hide-tab')}
                activeTab={state.activeTab}
              >
                <TabPane tabId="1">
                  <BeatHR
                    tabRef={tab1Ref}
                    handleNoActivity={handleNoActivity}
                    activeTab={state.activeTab}
                  />
                </TabPane>

                <TabPane tabId="2">
                  <RhythmEvents
                    tabRef={tab2Ref}
                    handleNoActivity={handleNoActivity}
                    activeTab={state.activeTab}
                  />
                </TabPane>

                <TabPane tabId="3">
                  {isLoadedIndexDB ? (
                    <StripsManagement
                      ref={tab3Ref}
                      isActive={state.activeTab === '3'}
                      ecgDataMap={ecgDataMap}
                      reportData={reportData}
                      studyFid={parseInt(studyFid, 10)}
                      timezoneOffset={timezoneOffset}
                      startReport={startReport}
                      isNotEdit={isNotEdit}
                      reportType={REPORT_TYPE}
                    />
                  ) : <ProgressLoading />}
                </TabPane>

                <TabPane tabId="4">
                  {isLoadedIndexDB ? (
                    <AiPDFReportTab
                      ref={tab4Ref}
                      isActive={state.activeTab === '4'}
                      isAbortedStudy={isAbortedStudy}
                      isNotEdit={isNotEdit}
                      isGeneratingNormalReportInCallCenter={state.isGeneratingNormalReportInCallCenter}
                    />
                  ) : <ProgressLoading />}

                </TabPane>
              </TabContent>
            </>
          )
        }
      </div>
    </>
  );
};

AiReportPage.propTypes = {

};

export default AiReportPage;
    @Override
    public List<HumanAgent> findByBotIdAndStatus(String botId, String status) {
        List<HumanAgent> humanAgents = new ArrayList<>();
        try {
            Query query = new Query().addCriteria(Criteria.where("bot_id").is(botId))
                    .addCriteria(Criteria.where("status").is(status));
            humanAgents = mongoTemplate.find(query, HumanAgent.class);
            log.info("find HumanAgent by botId {}, status {},  have size {}",
                    botId, status, humanAgents.size());
        }catch (Exception ex){
            log.error("ERROR {}", ExceptionUtils.getStackTrace(ex));
        }
        return humanAgents;
    }
def factorial(n):
	if n < 1:
    	return 1

	return n*factorial(n-1)

factorial(5)
public class Employee {

    // Instance variables

    private String name;

    private int id;

    private double salary;

    // Constructor to initialize instance variables

    public Employee(String name, int id, double salary) {

        this.name = name;

        this.id = id;

        this.salary = salary;

    }

    // Getter for name

    public String getName() {

        return name;

    }

    // Setter for name

    public void setName(String name) {

        this.name = name;

    }

    // Getter for id

    public int getId() {

        return id;

    }

    // Setter for id

    public void setId(int id) {

        this.id = id;

    }

    // Getter for salary

    public double getSalary() {

        return salary;

    }

    // Setter for salary

    public void setSalary(double salary) {

        this.salary = salary;

    }

    // Method to display employee details

    public void displayDetails() {

        System.out.println("Employee Details:");

        System.out.println("Name: " + name);

        System.out.println("ID: " + id);

        System.out.println("Salary: $" + salary);

    }

}

public class Employee {

    // Instance variables

    private String name;

    private int id;

    private double salary;

    // Constructor to initialize instance variables

    public Employee(String name, int id, double salary) {

        this.name = name;

        this.id = id;

        this.salary = salary;

    }

    // Getter for name

    public String getName() {

        return name;

    }

    // Setter for name

    public void setName(String name) {

        this.name = name;

    }

    // Getter for id

    public int getId() {

        return id;

    }

    // Setter for id

    public void setId(int id) {

        this.id = id;

    }

    // Getter for salary

    public double getSalary() {

        return salary;

    }

    // Setter for salary

    public void setSalary(double salary) {

        this.salary = salary;

    }

    // Method to display employee details

    public void displayDetails() {

        System.out.println("Employee Details:");

        System.out.println("Name: " + name);

        System.out.println("ID: " + id);

        System.out.println("Salary: $" + salary);

    }

}

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:ghalam_jadoee/component/api_service.dart';
import 'package:ghalam_jadoee/component/body3.dart';
import 'package:ghalam_jadoee/component/user_textfield.dart';
import 'package:ghalam_jadoee/pages/bottomnav.dart';
import 'package:ghalam_jadoee/pages/sign.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(Moarf());
}

String PUser = "";

class Moarf extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Referral Code Page',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ReferralCodePage(),
    );
  }
}

final TextEditingController _nameController = TextEditingController();

class ReferralCodePage extends StatefulWidget {
  @override
  _ReferralCodePageState createState() => _ReferralCodePageState();
}

class _ReferralCodePageState extends State<ReferralCodePage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _referralCodeController = TextEditingController();
  String _message = '';
  bool _isButtonActive = false;

  @override
  void initState() {
    super.initState();
    _referralCodeController.addListener(_validateCode);
    _nameController.addListener(_validateCode);
  }

  void _validateCode() {
    setState(() {
      final code = _referralCodeController.text;
      final name = _nameController.text;
      _isButtonActive = name.isNotEmpty &&
          (code.isEmpty ||
              (code.length == 6 && RegExp(r'^[a-zA-Z0-9]+$').hasMatch(code)));
    });
  }

  Future<void> saveLogin(String PUser) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("userkey", PUser);
    await prefs.setBool("loggedIn", true);
  }

  void _submitCode() async {
    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = _referralCodeController.text;

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print(jsonResponse);
          _message = 'کد معرف وارد شده: $referral';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  void _clearCode() async {
    _referralCodeController.clear();

    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = "0";

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print('jsonResponse');
          print(jsonResponse);

          _message = 'معرفی ندارم';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  @override
  void dispose() {
    _referralCodeController.removeListener(_validateCode);
    _nameController.removeListener(_validateCode);
    _referralCodeController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  @override
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
          body: SingleChildScrollView(
              child: Container(
            height: MediaQuery.of(context).size.height,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Body3(),
                Align(
                  alignment: Alignment.topCenter,
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).size.height * 0.48),
                      child: Padding(
                        padding: const EdgeInsets.all(24.0),
                        child: Form(
                          key: _formKey,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              UserNameTextField(controller: _nameController),
                              SizedBox(height: 30),
                              Align(
                                alignment: Alignment.centerRight,
                                child: const Text(
                                  ': کد معرف ',
                                  textAlign: TextAlign.end,
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ),
                              SizedBox(height: 10),
                              Container(
                                alignment: Alignment.centerRight,
                                child: TextFormField(
                                  controller: _referralCodeController,
                                  decoration: InputDecoration(
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    contentPadding: const EdgeInsets.symmetric(
                                      vertical: 16.0,
                                      horizontal: 12.0,
                                    ),
                                  ),
                                  maxLength: 6,
                                  validator: (value) {
                                    if (value != null && value.isNotEmpty) {
                                      if (value.length != 6) {
                                        return 'کد معرف باید ۶ کاراکتر باشد';
                                      } else if (!RegExp(r'^[a-zA-Z]+$')
                                          .hasMatch(value)) {
                                        return 'کد معرف باید فقط حاوی حروف انگلیسی باشد';
                                      }
                                    }
                                    return null;
                                  },
                                ),
                              ),
                              SizedBox(height: 20),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  TextButton(
                                    onPressed:
                                        _isButtonActive ? _submitCode : null,
                                    style: TextButton.styleFrom(
                                      foregroundColor: _isButtonActive
                                          ? Colors.blue
                                          : Colors.grey,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('ارسال'),
                                  ),
                                  TextButton(
                                    onPressed: _clearCode,
                                    style: TextButton.styleFrom(
                                      foregroundColor: Colors.red,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('معرفی ندارم'),
                                  ),
                                ],
                              ),
                              SizedBox(height: 20),
                              Text(
                                _message,
                                style: TextStyle(
                                  fontSize: 16,
                                  color: _message.contains('کد معرف وارد شده')
                                      ? Colors.green
                                      : Colors.red,
                                ),
                                textDirection: TextDirection.rtl,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )),
        ));
  }
}
star

Wed Jul 17 2024 19:00:57 GMT+0000 (Coordinated Universal Time)

@vjg #python

star

Wed Jul 17 2024 16:49:12 GMT+0000 (Coordinated Universal Time) code

@9315256437

star

Wed Jul 17 2024 16:47:03 GMT+0000 (Coordinated Universal Time)

@9315256437

star

Wed Jul 17 2024 16:17:23 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Jul 17 2024 16:14:41 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:11:36 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:10:45 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:09:39 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist

star

Wed Jul 17 2024 16:08:58 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist

star

Wed Jul 17 2024 14:53:32 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Jul 17 2024 14:19:45 GMT+0000 (Coordinated Universal Time)

@insplay

star

Wed Jul 17 2024 12:23:02 GMT+0000 (Coordinated Universal Time)

@hedviga

star

Wed Jul 17 2024 12:02:21 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle

star

Wed Jul 17 2024 12:00:47 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print

star

Wed Jul 17 2024 11:57:55 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast

star

Wed Jul 17 2024 11:56:35 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #deletenode

star

Wed Jul 17 2024 11:55:01 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #deletenode

star

Wed Jul 17 2024 09:44:53 GMT+0000 (Coordinated Universal Time)

@davidmchale #nested #function #foreach #...args #literals

star

Wed Jul 17 2024 09:41:09 GMT+0000 (Coordinated Universal Time)

@davidmchale #nested #function #foreach #...args

star

Wed Jul 17 2024 09:38:18 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Wed Jul 17 2024 09:09:41 GMT+0000 (Coordinated Universal Time)

@omnixima #php

star

Wed Jul 17 2024 07:21:44 GMT+0000 (Coordinated Universal Time)

@faizan

star

Wed Jul 17 2024 07:14:44 GMT+0000 (Coordinated Universal Time)

@vishalsingh21

star

Wed Jul 17 2024 06:08:22 GMT+0000 (Coordinated Universal Time) https://www.cloudways.com/blog/wp-cli-commands/

@Merel1988

star

Tue Jul 16 2024 23:39:35 GMT+0000 (Coordinated Universal Time) https://www.chromium.org/getting-involved/download-chromium/

@Dewaldt

star

Tue Jul 16 2024 19:25:53 GMT+0000 (Coordinated Universal Time)

@darshcode #sql

star

Tue Jul 16 2024 16:14:18 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #json

star

Tue Jul 16 2024 16:13:47 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #json

star

Tue Jul 16 2024 16:12:45 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:11:36 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:05:41 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:03:39 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:03:09 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:02:33 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:02:14 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:01:40 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak

star

Tue Jul 16 2024 16:01:14 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak

star

Tue Jul 16 2024 15:06:44 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Jul 16 2024 14:38:06 GMT+0000 (Coordinated Universal Time)

@oce1907

star

Tue Jul 16 2024 12:39:58 GMT+0000 (Coordinated Universal Time)

@faizan

star

Tue Jul 16 2024 12:29:50 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jul 16 2024 10:54:42 GMT+0000 (Coordinated Universal Time) https://firebase.flutter.dev/

@zemax_c4 ##flutter

star

Tue Jul 16 2024 10:38:09 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jul 16 2024 10:16:56 GMT+0000 (Coordinated Universal Time)

@khainguyenhm #javascript

star

Tue Jul 16 2024 10:16:37 GMT+0000 (Coordinated Universal Time)

@khainguyenhm #javascript

star

Tue Jul 16 2024 09:37:45 GMT+0000 (Coordinated Universal Time)

@manhmd #java

star

Tue Jul 16 2024 07:29:05 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 05:32:50 GMT+0000 (Coordinated Universal Time)

@projectrock

star

Tue Jul 16 2024 05:20:18 GMT+0000 (Coordinated Universal Time)

@mehran

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension