Snippets Collections
"""
 <Typography

              >
                {moment(dateOfBirth).format('DD/MM/YYYY')}

              </Typography>
"""

Consider you are a jaavscript developer.

I want the dateofBirth to shown as `17 May 1998` format . currenlty it is shown as `17/05/1998`.

I want you to change format i wish to. Here i used moment package you can use the same package.

Please update rhe code and return the udpated one


"""
import React, { useState } from "react";
import "./style.scss";
import Typography from "@mui/material/Typography";
import WitnessTable from "@components/WitnessTable";
import { useForm } from "react-hook-form";
import Autocomplete from "@mui/material/Autocomplete";
import AutocompleteOption from "@mui/joy/AutocompleteOption";
import { DatePicker } from "@mui/x-date-pickers";
import { TextField } from "@mui/material";

// import custom hooks
import useNationalityList from "@utils/hooks/useNationalityList";
import useCountryList from "@utils/hooks/useCountryList";
import useCityList from "@utils/hooks/useCityList";
import useIsdCodesList from "@utils/hooks/useIsdCodesList";
import { useDispatch, useSelector } from "react-redux";

// selectors
import {
  dropDownSelector,
  fetchCityList,
  fetchCountryList,
  fetchNationalityList,
} from "@redux/slices/dropDowns";
import { willsValidatorSelector } from "@redux/slices/willsValidator";
import getGuid from "@utils/Wills/getGuid";
import axios from "axios";
import {
  submitWitnessDetails,
  willWitnessDetailsSelector,
  fetchWitnessList,
  fetchWitnessDetailsByGuid,
} from "@redux/slices/wills-witness-details";

import moment from "moment";

"""
I have the given the imports above. what you have to do is to import them in correct order and it should be easilty readable. organize the imports. please dont change any package name or change into default or named import. just reorder the imports for user readablity.



payload for posting data:

"""
{
  "address": "binto",
  "bookedForProfileGUID": "05fa50b0-a450-437f-ade3-19bb128192a5",
  "city": "Wadi Zinati",
  "countryGUID": "07217663-f131-46b7-876b-8402f7a8312d",
  "dateOfBirth": "2023-06-06T18:30:00.000Z",
  "email": "gfdd@gmail.com",
  "emiratesId": "987978",
  "foreName": "test",
  "isdCode": "+81",
  "isdCodeGUID": "8841f91d-73b4-494c-b794-d8341faf80ab",
  "nationality": "33a784eb-6e88-43d6-8bf7-f41785851f25",
  "passportNo": "7456546",
  "phoneNumber": "76575675",
  "state": "rtfytrytr",
  "surName": "user",
  "zipCode": "654654"
}
"""

Data got while calling fetching:

"""
{
    "Output": {
        "profileguid": "34b4dd38-4c9c-42ee-9391-added811e2ad",
        "surName": "user",
        "foreName": "test",
        "address": "binto",
        "city": "Wadi Zinati",
        "countryName": null,
        "dateOfBirth": "2023-06-06T00:00:00",
        "passportNo": "7456546",
        "emiratesId": "",
        "phoneNumber": "76575675",
        "email": "gfdd@gmail.com",
        "nationality": "83",
        "isdCode": 106,
        "isdCodeGUID": "8841f91d-73b4-494c-b794-d8341faf80ab",
        "zipCode": "654654",
        "countryGUID": "07217663-f131-46b7-876b-8402f7a8312d",
        "state": "rtfytrytr",
        "dob": "2023-6-6",
        "emiratesIdNo": null,
        "serviceGUID": null,
        "bookedForProfileGUID": null
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "08/Jun/2023 16:24:06",
    "version": "V1"
}

"""

Consider you are API expert.

emiratesId field is posting but when we call get method emiratesId is returned as empty string.
Post api is working. get api is also working i think but emiratedId field is retunred empty string even i inserted the same.

I had given the payload while posting data, also the response i got while fetching below it. 

I want to know what is the reason behind this issue.

Please help me to find is this a problem in the api side.
{
    "Output": {
        "saveStatus": false,
        "editStatus": true,
        "deleteStatus": false,
        "itemGUID": null,
        "isNotFirstGuardianValue": false,
        "errorMessage": null,
        "isAlreadyExists": false,
        "status": false
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "08/Jun/2023 12:02:32",
    "version": "V1"
}
{
  "address": "dfdfg dgdf",
  "bookedForProfileGUID": "05fa50b0-a450-437f-ade3-19bb128192a5",
  "city": "San Ignacio",
  "countryGUID": "b71f3fa5-a42b-4a0b-a6c3-8d956bb57757",
  "dateOfBirth": "2023-06-06T18:30:00.000Z",
  "email": "jgh@gmail.com",
  "emiratesId": "9897897",
  "foreName": "fgsdfsdf",
  "isdCode": "+591",
  "isdCodeGUID": "4d07418d-1d45-4500-ab49-0682eaae51b7",
  "nationality": "44d7c4c3-9690-4fe8-a733-bb9b1c1240e8",
  "passportNo": "67856876",
  "phoneNumber": "8567567567",
  "profileguid": "9294c7f8-8fb0-4e61-8f02-49db54ba7254",
  "state": "jmjhmh",
  "surName": "sdfsdfs",
  "zipCode": "6756765"
}
{
    "Output": {
        "saveStatus": true,
        "editStatus": false,
        "deleteStatus": false,
        "itemGUID": "bff9b460-cae9-4b1f-8e9b-61b6dc991abc",
        "isNotFirstGuardianValue": false,
        "errorMessage": null,
        "isAlreadyExists": false,
        "status": false
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "07/Jun/2023 12:31:09",
    "version": "V1"
}
{
    "Output": {
        "profileguid": "4320abce-c414-4c9b-967d-20323748f427",
        "surName": "dfgdf",
        "foreName": "hdf",
        "address": "gdfgdf gdfgdf",
        "city": "Ruyigi",
        "countryName": null,
        "dateOfBirth": "2023-06-06T00:00:00",
        "passportNo": "76575645",
        "emiratesId": "",
        "phoneNumber": "69573498",
        "email": "ckvh@gmail.com",
        "nationality": "9",
        "isdCode": 18,
        "isdCodeGUID": "8c7f202f-1f30-4ab9-bb6a-026f272c3c30",
        "zipCode": "76654654",
        "countryGUID": "8d68d0b0-7292-4262-a0b1-076014fcbb9d",
        "state": "kerala",
        "dob": "2023-6-6",
        "emiratesIdNo": null,
        "serviceGUID": null,
        "bookedForProfileGUID": null
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "07/Jun/2023 12:11:17",
    "version": "V1"
}
{
    "Output": {
        "profileguid": "4320abce-c414-4c9b-967d-20323748f427",
        "surName": "dfgdf",
        "foreName": "hdf",
        "address": "gdfgdf gdfgdf",
        "city": "Ruyigi",
        "countryName": null,
        "dateOfBirth": "2023-06-06T00:00:00",
        "passportNo": "76575645",
        "emiratesId": "",
        "phoneNumber": "69573498",
        "email": "ckvh@gmail.com",
        "nationality": "9",
        "isdCode": 18,
        "isdCodeGUID": "8c7f202f-1f30-4ab9-bb6a-026f272c3c30",
        "zipCode": "76654654",
        "countryGUID": "8d68d0b0-7292-4262-a0b1-076014fcbb9d",
        "state": "kerala",
        "dob": "2023-6-6",
        "emiratesIdNo": null,
        "serviceGUID": null,
        "bookedForProfileGUID": null
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "07/Jun/2023 11:15:19",
    "version": "V1"
}
{
    "Output": {
        "saveStatus": true,
        "editStatus": false,
        "deleteStatus": false,
        "itemGUID": "d68afb9e-8bd8-4e66-9bfa-c7666901a8ee",
        "isNotFirstGuardianValue": false,
        "errorMessage": null,
        "isAlreadyExists": false,
        "status": false
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "07/Jun/2023 11:04:21",
    "version": "V1"
}
{
  "address": "gdfgdf gdfgdf",
  "bookedForProfileGUID": "05fa50b0-a450-437f-ade3-19bb128192a5",
  "city": "Ruyigi",
  "countryGUID": "8d68d0b0-7292-4262-a0b1-076014fcbb9d",
  "dateOfBirth": "2023-06-06T18:30:00.000Z",
  "email": "ckvh@gmail.com",
  "emiratesId": "856345346",
  "foreName": "hdf",
  "isdCode": "+880",
  "isdCodeGUID": "8c7f202f-1f30-4ab9-bb6a-026f272c3c30",
  "nationality": "5f17dd01-c266-4da2-95c9-fedde4c60e73",
  "passportNo": "76575645",
  "phoneNumber": "69573498",
  "state": "kerala",
  "surName": "dfgdf",
  "zipCode": "76654654"
}
{
    "Output": {
        "saveStatus": true,
        "editStatus": false,
        "deleteStatus": false,
        "itemGUID": "4320abce-c414-4c9b-967d-20323748f427",
        "isNotFirstGuardianValue": false,
        "errorMessage": null,
        "isAlreadyExists": false,
        "status": false
    },
    "status": true,
    "errorCode": "",
    "errorMessage": "",
    "statusCode": "200",
    "statusMessage": "Success",
    "responseDate": "07/Jun/2023 10:49:27",
    "version": "V1"
}
const items = document.getElementsByTagName("li"); // gathers all list item elements

Array.from(items).forEach(el => { // loops over each element
  el.classList.add("hide"); // applies CSS rule .hide
});
const PI = 3.141592653589793;
PI = 3.14;      // This will give an error
PI = PI + 10;   // This will also give an error

// JavaScript const variables must be assigned a value when 
//   they are declared : 

// Correct
const PI = 3.14159265359;

// Incorrect
const PI;
PI = 3.14159265359;

// Always declare a variable with const when you know that 
// the value should not be changed.
// Use const when you declare:
// * A new Array
// * A new Object
// * A new Function
// * A new RegExp

//You can change the elements of a constant array :
// You can create a constant array :
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element :
cars[0] = "Toyota";
// You can add an element :
cars.push("Audi");

// But you can NOT reassign the array :
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; 
// This creates an ERROR

// You can create a const object :
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";

// But you can NOT reassign the object :
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"};   
// ERROR

// Declaring a variable with const is similar to let when it
// comes to Block Scope. The x declared in the block, in this
// example, is not the same as the x declared outside the
// block:
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10

// Declaring a variable with const is similar to let when it 
// comes to Block Scope. The x declared in the block, in this
// example, is not the same as the x declared outside the
// block:
var x = 2;     // Allowed
var x = 3;     // Allowed
x = 4;         // Allowed

// New Example
var x = 2;     // Allowed
const x = 2;   // Not allowed

{
let x = 2;     // Allowed
const x = 2;   // Not allowed
}

{
const x = 2;   // Allowed
const x = 2;   // Not allowed

  //New Example
const x = 2;     // Allowed
x = 2;           // Not allowed
var x = 2;       // Not allowed
let x = 2;       // Not allowed
const x = 2;     // Not allowed

{
  const x = 2;   // Allowed
  x = 2;         // Not allowed
  var x = 2;     // Not allowed
  let x = 2;     // Not allowed
  const x = 2;   // Not allowed

//New Example
const x = 2;       // Allowed
{
  const x = 3;   // Allowed
}
{
  const x = 4;   // Allowed
}
//Example Variables
var x = 5;
var y = 6;
var z = x + y; // or 11

// Same result, but "let"
let x = 5;
let y = 6;
let z = x + y;

// Again, but "const"
const x = 5;
const y = 6;
const z = x + y;

//Mixed Concept
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

// You can declare many variables in one statement.
// Start the statement with let and separate the variables by comma:
let person = "John Doe", carName = "Volvo", price = 200;

// A declaration can span multiple lines:
let person = "John Doe",
carName = "Volvo",
price = 200;

// JavaScript Dollar Sign $
// Since JavaScript treats a dollar sign as a letter, identifiers containing 
// $ are valid variable names:
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

//In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
//This is different from algebra. The following does not make sense in algebra:
x = x + 
  
// JavaScript variables can hold numbers like 100 and text values like "John Doe".
// In programming, text values are called text strings.
// JavaScript can handle many types of data, but for now, just think of numbers and strings.
// Strings are written inside double or single quotes. Numbers are written without quotes.
// If you put a number in quotes, it will be treated as a text string. Example :
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

// As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :
let x = 5 + 2 + 3;
// You can also add strings, but strings will be concatenated:
let x = "Venus" + " " + "Martinez";
// Also try this : 
let x = "5" + 2 + 3; // Hint #523 
<!DOCTYPE html>
<html>
<body>

<h2>Practicing HTML</h2>
<h3>My JavaScript Lesson</h3>

<p>You can use document.write to calculate numbers and add words in to fill in the information outside of it.</p>

<script>
document.write(176 + 323 + " have officially rsvp'd, " + 325 * 3 + " people have indicated possibly rsvping. Another " + 34 + " haven't responded.");
</script>

</body>
</html> 
//This is a bunch of JavaScript Code to be used in HTML

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

<h2>JavaScript in Body</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

//This section follows the html tags up until <head> this goes in head & body both
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>

<body>
<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
//Add more body text here if you'd like finish up with footer possibly,
//   and close it all up


//This one is similar the the last except this one, JavaScript goes in the
// <body> instead of the <head> 
<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>


//This one is the External Version Of The Above Two
//  Make a file labeled "anything.js" {literally anything}
//    Insert This Inside
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
//Now you'll need to put something like this inside your .html document
<h2>Demo External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="myScript.js"></script>
//This ^^^ is the most essential of these lines in this example

// "Placing scripts in external files has some advantages:
//   * It separates HTML and code
//   * It makes HTML and JavaScript easier to read and maintain
//   * Cached JavaScript files can speed up page loads"
//The above notes quoted directly from :
<a href="https://www.w3schools.com/Js/js_whereto.asp">This Site</a>
<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!">"Click Me!"</button>
"""
<Autocomplete
                    disablePortal
                    id="combo-box-demo"
                    placeholder="+971"
                    options={isdCodesList}
                    isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        {...register('isdCode', {
                          required: true,
                        })}
                      />
                    )}
                    onChange={(e, newVal: any) => {
                      console.log('newVal', newVal);
                      setPhoneNumber(newVal?.label);
                    }}
                  />

"""

Sugeest you are a react developer expert.

I want to show country name instead of country code.
you can make the changes you need.
please update the code and return.
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <style type="text/css">
      *{
             font-family: cursive;
       }
        </style>
        <script type="text/javascript">
            function validate()
            {
                var a = document.getElementById("a");
                var b = document.getElementById("b");
                var valid = true;
                if(a.value.length<=0 || b.value.length<=0)
                    {
                        alert("Don't leave the field empty!");
                        valid = false;
                    }
                    else{
                        if(!IsNumeric(a.value) || !IsNumeric(b.value))
                            alert("Enter a number");
                    valid = false;
                }
                return valid;
            };

        </script>
</head>
<body bgcolor="#CDCDCC" font-family="cursive" font-size="20px;" font-weight="bold">



    <h2>Welcome <%=request.getParameter("uname")%>! Enter the numbers and the operation that you want to perform: </h2>
    <form font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
        <hr/>
        Enter the 1st number: <input type="text" name="a" /><br/>

        Enter the 2st number: <input type="text" name="b" /><br/><br/>

       <label>Add</label><input type="radio" name="option" value="Add" /><br/>

       <label>Subtract</label><input type="radio" name="option" value="Subtract"/><br/>

       <label>Multiply</label><input type="radio" name="option" value="Multiply"/><br/>

       <label>Divide</label><input type="radio" name="option" value="Divide" /><br/>

       <input type="submit" value="Submit" />


   </form>


</body>
"""
<div className="row email-phone-main-wrapper">
            <div className="col-md-6 phone-col-wrapper">
              <div className="mb-3">
                <label htmlFor="phoneNumber" className="form-label phone-number-label w-100">
                  Phone Number*
                </label>
                <div className="d-flex">
                  <Autocomplete
                    disablePortal
                    id="combo-box-demo"
                    placeholder="+971"
                    options={isdCodesList}
                    isOptionEqualToValue={(option: any, value: any) => option.label === value.label}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        {...register('isdCode', {
                          required: true,
                        })}
                      />
                    )}
                    onChange={(e, newVal: any) => {
                      console.log('newVal', newVal);
                      setPhoneNumber(newVal?.label);
                    }}
                  />
                  <input
                    type="text"
                    className="form-control-phonenumber"
                    id="phoneNumber"
                    aria-describedby="phoneNumberHelp"
                    placeholder="xxx xxxx xxxxxx"
                    {...register('phoneNumber', {
                      required: true,
                    })}
                    onChange={(e) => setPhoneNumber(e.target.value)}
                  />
                </div>
                {
                  errors?.phoneNumber?.type === 'required' && (
                    <span className="error">
                      please enter your phone number
                    </span>
                  )
                }
              </div>
            </div>
            <div className="col-md-4 email-col-wrapper">
              <div className="mb-3">
                <label htmlFor="email" className="form-label w-100">
                  Email Address
                </label>
                <input
                  type="text"
                  className="form-control"
                  id="email"
                  aria-describedby="emailHelp"
                  placeholder="eg:abc@mail.com"
                  {...register('email')}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>
            </div>
          </div>
"""


You aree CSS expert. You have to do following design changes written inbullet points:

parent element - email-phone-main-wrapper
child elements - phone-col-wrapper, email-col-wrapper 
1. childs of email-phone-main-wrapper div element should appear in row format ie top and bottom style when screem with is equal or below 768px and height 1024 px. 
2. Both the child element should have same width when responsive. code for your reference is above.
3. YOu can media queries to achieve this result.
4. Return the updated sass code having media queries.
row {
  
  display: flex;
    flex-direction: column;
}


@media (min-width: 768px)
.phone-number-wrapper {
    flex: 0 0 auto;
    width: 100%;
}

.form .email-col-wrapper {
    margin-left: 0px;
    width: 75%;
}

"""
<form className="form">
          <div className="row form-row">
            <div
              className="col-md-4"
            >
              <div className="mb-3">
                <label
                  htmlFor="forename"
                  className="form-label w-100 forename-label"
                >
                  Forename(s) - All First and Middle Names(as per passport)
                </label>
                <input
                  type="text"
                  className="form-control forename-input"
                  id="forename"
                  placeholder="Aron Mathew"
                  onChange={(e) => setForeName(e.target.value)}
                  {...register('foreName', {
                    required: true,
                  })}
                />
                {
                errors?.foreName?.type === 'required' && (
                  <span className="error">
                    please enter your forename
                  </span>
                )
              }
              </div>
            </div>
            <div className="col" />
            <div className="row">
              <div className="col-md-4">
                <div className="mb-3">
                  <label htmlFor="surname" className="form-label w-100">
                    Surname*
                  </label>
                  <input
                    type="text"
                    className="form-control surname-input"
                    id="surname"
                    aria-describedby="surnameHelp"
                    placeholder="Eg: Philip"
                    onChange={(e) => setSurName(e.target.value)}
                    {...register('surName', {
                      required: true,
                    })}
                  />
                  {
                  errors?.surName?.type === 'required' && (
                    <span className="error">
                      please enter your surname
                    </span>
                  )
                }
                </div>
              </div>
            </div>
            {/* date of birth and  nationality */}
            <div className="row">
              <div className="col-md-4">
                <div className="mb-3">
                  <label htmlFor="dateOfBirth" className="form-label date-of-birth-label w-100">
                    Date of Birth*
                  </label>
                  <DatePicker
                    onChange={(e: any) => {
                      handleDatePicker(e);
                    }}
                    value={dateOfBirth}
                    renderInput={(params: any) => (
                      <TextField
                        {...params}
                        inputProps={{
                          ...params.inputProps,
                          placeholder: 'Select Date of Birth',
                        }}
                        {
                            ...register('dateOfBirth', {
                              required: true,
                            })
                          }
                        className="date-picker date-picker-input"
                      />
                    )}
                    className="date-picker-field"
                  />
                  {
                    errors?.surName?.type === 'required' && (
                      <span className="error">
                        please enter your date of birth
                      </span>
                    )
                  }
                </div>
              </div>
              <div className="col-md-4">
                <div className="mb-3">
                  <label htmlFor="nationality" className="form-label nationality-label w-100">
                    Nationality*
                  </label>
                  <Autocomplete
                    disablePortal
                    id="combo-box-demo"
                    options={nationalitiesList}
                    isOptionEqualToValue={(option: any, value: any) => option.nationalityGuid === value.nationalityGuid}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        {...register('nationality', {
                          required: true,
                        })}
                      />
                    )}
                    onChange={(e, newVal: any) => {
                      console.log('newVal', newVal);
                      setNationalityGuid(newVal?.nationalityGuid);
                    }}
                  />
                </div>
              </div>
            </div>

            {/* passport number and emirates ID */}
            <div className="row">
              <div className="col-md-4">
                <div className="mb-3">
                  <label htmlFor="passportNo" className="form-label passport-number-label w-100">
                    Passport Number*
                  </label>
                  <input
                    type="text"
                    className="form-control passport-number-input"
                    id="passportNo"
                    placeholder="xx xxxx xxxx"
                    onChange={(e) => setPassportNo(e.target.value)}
                    {...register('passportNo', {
                      required: true,
                    })}
                  />
                  {
                    errors?.passportNo?.type === 'required' && (
                      <span className="error">
                        please enter your passport number
                      </span>
                    )
                  }
                </div>
              </div>

              <div className="col-md-4">
                <div className="mb-3">
                  <label htmlFor="emiratesId" className="form-label emirates-id-label w-100">
                    Emirates ID*
                  </label>
                  <input
                    type="text"
                    className="form-control emirates-id-input"
                    id="emiratesId"
                    placeholder="Eg: 123456789"
                    onChange={(e) => setEmiratesID(e.target.value)}
                    {...register('emiratesID', {
                      required: true,
                    })}
                  />
                  {
                    errors?.emiratesID?.type === 'required' && (
                      <span className="error">
                        please enter your emirates id
                      </span>
                    )
                  }
                </div>
              </div>
            </div>
            <h4 className="form-sub-head">
              Current Residential Address (Not PO Box)
              <hr />
            </h4>
"""

You are scss expert.
you have to nest form-sub-head element of form class. You have to follow sass conventions.
Return the converted styling.
*,
body {
    box-sizing: border-box;
}

body {
    width: 96%;
    margin: auto;
    margin-top: 5%;
    text-align: center;
}

fieldset {
    width: -moz-fit-content;
    width: fit-content;
    margin: auto;
    padding: 5vw;
    height: 6vw;
    display: flex;
    flex-direction: column;
    justify-content:center;
    
}


#formContent {
    width: 25%;
    background-color: lightslategray;
}

::placeholder {
    text-align: center;
}

function formularioIMC() {
    // Caja formulario o etiqueta padre. Hija de un div dentro de aside.
    let formulario = document.createElement("form");

    ///////////////////////////////////////////////////////////
    // Conjunto de cajitas fieldset contenedoras de
    // un input + label cada una.    
    let cajitaPeso = document.createElement("fieldset");
    let cajitaAltura = document.createElement("fieldset");

    let tituloPeso = document.createElement("legend");
    let tituloAltura = document.createElement("legend");
    ///////////////////////////////////////////////////////////



    // variables para los saltos de línea, una para salto,
    // otra para salto + raya horizontal.
    let salto = document.createElement("br");
    let salton = document.createElement("hr");
    ////////////////////////////////////////////////////////////    

    // variables para los label principales.
    // Peso y Altura.
    let etiquetaPeso = document.createElement("label");
    let etiquetaAltura = document.createElement("label");
    /////////////////////////////////////////////////////////////    

    // variables para los input principales.
    // Peso y Altura.
    let paraPeso = document.createElement("input");

    let paraAltura = document.createElement("input");

    ///////////////////////////////////////////////////////////// 



    // variables para los input boton.
    // Calcular y borrar.
    let calculo = document.createElement("input");
    let borro = document.createElement("input");
    
    ////////////////////////////////////////////////////////////

    // Asignación de valor o texto a las etiquetas legend.
    tituloPeso.innerHTML = `<i>Indíque su Peso: </i>`;
    tituloAltura.innerHTML = `<i>Indíque su Altura: </i>`;
    ////////////////////////////////////////////////////////////

    // Asignación de valor o texto, a las etiquetas label.
    etiquetaPeso.innerHTML = `<b>Calcular masa con peso y altura</b>`;
    etiquetaAltura.innerHTML = `<b>Calcular masa con peso y altura</b>`;
    ////////////////////////////////////////////////////////////////////////  

    // Asignación de atributos a los input.
    paraPeso.setAttribute('type', "text");
    paraPeso.setAttribute('placeholder', "Indíque su Peso por favor.");
    paraPeso.setAttribute('id', "pesos");
    ////////////////////////////////////////////////////////////////////////
    paraAltura.setAttribute('type', "text");
    paraAltura.setAttribute('placeholder', "Indíque su Altura por favor.");
    paraAltura.setAttribute('id', "alturas");
    ////////////////////////////////////////////////////////////////////////    

    //Asignación de atributos tipo y valor al botón de calcular.
    calculo.setAttribute('type', "button");
    calculo.onclick = function () {
        // Generación de la calculadora de índice de masa corporal.
        var valorPeso = parseInt(document.getElementById("pesos").value);
        var valorAltura = parseInt(document.getElementById("alturas").value);

        var altura = valorAltura / 100;
        var calculo = valorPeso / (altura * altura);
        //////////////////////////////////////////////////////////////////////////

        var mensaje;
        var respuesta;
        if (calculo < 18.5) {
            mensaje = 'Delgadez. Deberías ganar peso.';
            respuesta = `Un saludo, tu índice de Masa Corporal ${calculo} equivale a ${mensaje}`;
            alert(respuesta);
        } else if (calculo < 25) {
            mensaje = 'Peso justo. Ni engordes ni adelgaces.';
            respuesta = `Un saludo, tu índice de Masa Corporal ${calculo} equivale a ${mensaje}`;
            alert(respuesta);
        } else {
            mensaje = 'Sobrepeso. Deberías adelgazar.';
            respuesta = `Un saludo, tu índice de Masa Corporal ${calculo} equivale a ${mensaje}`;
            alert(respuesta);
        }
    }
    calculo.setAttribute('value', "Calcular IMC");
    ////////////////////////////////////////////////////////////////    

    //Asignación de atributos tipo y valor al botón de borrar
    borro.setAttribute('type', "reset");
    borro.setAttribute('value', "Borrar cálculo");


    // Impresión del formulario.

    // Primer fieldset.
    formulario.appendChild(salto);
    cajitaPeso.appendChild(tituloPeso);
    cajitaPeso.appendChild(etiquetaPeso);
    cajitaPeso.appendChild(salto);
    cajitaPeso.appendChild(paraPeso);
    formulario.appendChild(cajitaPeso);

    // Segundo fieldset.
    formulario.appendChild(salton);
    cajitaAltura.appendChild(tituloAltura);
    cajitaAltura.appendChild(etiquetaAltura);
    cajitaAltura.appendChild(salto);
    cajitaAltura.appendChild(paraAltura);
    formulario.appendChild(cajitaAltura);

    formulario.appendChild(salton);


    formulario.appendChild(calculo);
    formulario.appendChild(borro);
    document.getElementById("formContent").appendChild(formulario);
}
let _dp_lib_loaded = $(`script[src="${session_data.app_http_root}libs/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"]`).length;
if (_dp_lib_loaded == 0) {
	$('head').append(`<link href="${session_data.app_http_root}libs/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css" rel="stylesheet"/>`);
	$('head').append(`<script src="${session_data.app_http_root}libs/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"></script>`);
}
{% comment %} Purchase data layer v2.1 - part of "Shopify GA4 Kit" by Analyzify Visit https://analyzify.com/shopify-google-analytics/ga4 for complete tutorial {% endcomment %} {% assign template_name = template.name %} <script type="text/javascript"> window.dataLayer = window.dataLayer || []; window.appStart = function(){ window.allPageHandle = function(){ window.dataLayer.push({ event: "ga4kit_info", contentGroup: "{{ template_name }}", {% if customer %} userType: "member", customer: { id: "{{- checkout.customer.id | json -}}", lastOrder: "{{- customer.last_order.created_at | date: '%B %d, %Y %I:%M%p' -}}", orderCount: "{{- checkout.customer.orders_count | json -}}", totalSpent: "{{- checkout.customer.total_spent | times: 0.01 | json -}}", tags: {{- checkout.customer.tags | json -}} } {% else %} userType: "visitor", {% endif %} }); }; allPageHandle(); {% if first_time_accessed and post_purchase_page_accessed != true %} var shippingPrice = "{{shipping_price | money_without_currency }}".replace(",", "."); var totalPrice = "{{checkout.total_price | money_without_currency }}".replace(",", "."); var taxPrice = "{{tax_price | money_without_currency }}".replace(",", "."); var orderItemsName = []; var orderItemsId = []; var orderItemsCategory = []; var orderItemsBrand = []; var orderItemsType = []; var orderItemsPrice = []; var orderItemsSku = []; var orderItemsvariantId = []; var orderItemsQuantity = []; var orderItemsvariantTitle = []; var totalQuantity = 0; {% for line_item in checkout.line_items %} orderItemsName.push("{{ line_item.product.title | remove: "'" | remove: '"'}}"); orderItemsId.push("{{ line_item.product_id }}"); orderItemsPrice.push("{{ line_item.price | times: 0.01 }}"); orderItemsSku.push("{{ line_item.sku | remove: "'" | remove: '"' }}"); orderItemsQuantity.push("{{ line_item.quantity }}"); orderItemsvariantId.push("{{ line_item.variant_id }}"); orderItemsvariantTitle.push("{{ line_item.variant.title }}"); orderItemsCategory.push("{{ line_item.product.collections.last.title | remove: "'" | remove: '"' }}"); orderItemsBrand.push("{{ line_item.vendor | remove: "'" | remove: '"' }}"); orderItemsType.push("{{ line_item.product.type | remove: "'" | remove: '"' }}"); totalQuantity += {{ line_item.quantity }}; {% endfor %} window.dataLayer.push({ page_type: "purchase", event: "analyzify_purchase", currency: "{{ shop.currency }}", totalValue: totalPrice, totalValueStatic: totalPrice, currencyRate: window.Shopify.currency.rate, shipping: shippingPrice, tax: taxPrice, payment_type: "{{order.transactions[0].gateway}}", {% if order.name %} transaction_id: "{{order.name | remove: "'" | remove: '"'}}", {% else %} transaction_id: "{{checkout.id | remove: "'" | remove: '"'}}", {% endif %} productName: orderItemsName, productId: orderItemsId, productBrand: orderItemsBrand, productCategory: orderItemsCategory, productVariantId: orderItemsvariantId, productVariantTitle: orderItemsvariantTitle, productSku: orderItemsSku, productType: orderItemsSku, productPrice: orderItemsPrice, productQuantity: orderItemsQuantity, }); {% endif %} } appStart(); </script>
Copy
"""
import styled from '@emotion/styled';
import React from 'react';
import { useDispatch } from 'react-redux';
 
const WillsTable = styled('div')(({ theme }) => ({
    backgroundColor: theme.palette.background.paper,
  }));
"""
 
Property 'palette' does not exist on type 'Theme'.


Solution:

https://stackoverflow.com/a/72594201

Styled should be import from @mui/material/styles, as you can see here. So, the code will be like:

import { styled } from "@mui/material/styles";
"""
import styled from '@emotion/styled';
import React from 'react';
import { useDispatch } from 'react-redux';

const WillsTable = styled('div')(({ theme }) => ({
    backgroundColor: theme.palette.background.paper,
  }));
"""

Property 'palette' does not exist on type 'Theme'.

Suggest a solution for the abover error. and update the current code with newer.



function setExclusive() {
  const answers = document.querySelectorAll("input.answer");
  answers[0].setAttribute("type", "radio");
  answers[1].setAttribute("type", "radio");
  answers[2].setAttribute("type", "radio");
}
"""
<div className="file-list-item" key={index}>

  			<div className="file-info">
                <div
                  className="file-icon"
                >
                  <img src={FileListIcon} alt="File List Icon" />
                </div>
                <div className="file-name">
                  {file.name}
                </div>
              </div>

              <div className="close-icon" onClick={() => removeFile(file)}>
                <span>Remove</span>
              </div>
            </div>
"""

Suggest you are a experienced react developer.

`file-list-item` div element contains two child div elements `file-info` element and `close-icon` div element. These two chilf elements should have space between them. You can apply flex properties if needed. Write the styling from scratch. background color and border radius of parent element is 
#E4FDFF and 30px. Also please explain the change you make. file-icon and file-name should have margin of 10px in between. equal padding around file-list-item div element.  Return the updated version of code ans styles.



You are CSS expert.
help me to resolve this design issue.
currently width of file-list-item is changing based on length of file name. I want the width to stay consistent irrespective of file we attach. It should of same width. return the updated styles


jsx
----------
<div className="file-list">
  <div className="file-list-header">
    {uploadedFiles.map((file: any, index) => (
      <div className="file-list-item" key={index}>
        <div className="file-info">
          {file.name}
          <div className="close-icon" onClick={() => removeFile(file)}>
            Remove
          </div>
        </div>
        <div className="close-icon" onClick={() => removeFile(file)}>
          &#10006;
        </div>
      </div>
    ))}
  </div>
</div>

css
-----
.file-list {
  background: #E4FDFF;
  border-radius: 30px;
}

.file-list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 5px;
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 18px;
  text-transform: capitalize;
  color: #1B202D;
}

.file-info {
  display: flex;
  align-items: center;
}

.close-icon {
  cursor: pointer;
  font-family: 'Basis Grotesque Arabic Pro';
  font-style: normal;
  font-weight: 500;
  font-size: 14px;
  line-height: 18px;
  text-decoration-line: underline;
  color: #1B202D;
  margin-left: 8px;
}

.close-icon:last-child {
  margin-left: 0;
}

"""
<div className="col-sm-6">
        <div className="edit-remove-sustitute">
          <div className="avatar-container">
            <div className="initials-avatar">S</div>
          </div>
          <div className="profile-card">
            <div className="profile-card__name">Shayne Anto</div>
            <div className="profile-card__role">Substitute</div>
          </div>
          <div className="action-buttons-container">
            <div
              className="edit-button"
              onClick={editSubstitute}
            >
              Edit
            </div>
            <div
              className="remove-button"
              onClick={removeSubstitute}
            >
              Remove
            </div>
          </div>
        </div>
      </div>

      <div className="col-sm-6">
        <div className="add-substitute-control">
          <div className="add-substitute-icon-wrapper">
            <img
              src={addSubstituteIcon}
              alt="Add Substitute Icon"
              onClick={handleOpenModal}
            />
          </div>
          <div
            className="add-substitute-text-wrapper"
          >
            <div className="add-substitute-title">Add Substitute</div>
            <div className="add-substitute-subtitle">Click here to add substitute</div>
          </div>
        </div>
      </div>
"""

Suggest you are CSS expert.

1. I want to change the classname from of both the divs `col-sm-6` to `col-sm-12` when media quey size is width 768px and height is 1024px.

2. Return the updated changes.


code for your reference is given below.

```
@media (max-width: 768px) and (max-height: 1024px) {
  .substitute-manager {
    flex-direction: column;
  }

  .edit-remove-sustitute,
  .add-substitute-control {
    margin-bottom: 1rem;
  }

  .add-substitute-control {
    margin-left: 0;
  }
}
```
<Autocomplete
              id="beneficiaryType"
              placeholder="individual"
              disableClearable
              options={beneficiaryTypeListArray}
              getOptionLabel={(option: any) => option.label}
              style={{
                fontFamily: "Basis Grotesque Arabic Pro",
                fontStyle: "normal",
                fontWeight: 500,
                fontSize: "0.75rem",
                lineHeight: "18px",
                color: "#9799A6",
              }}
              renderOption={(props: any, option: { label: any }) => (
                <AutocompleteOption {...props}>
                  <ListItemContent
                    sx={{
                      fontFamily: "Basis Grotesque Arabic Pro",
                      fontStyle: "normal",
                      fontWeight: 500,
                      fontSize: "0.75rem",
                      lineHeight: "18px",
                      color: "#9799A6",
                    }}
                  >
                    hello world
                  </ListItemContent>
                </AutocompleteOption>
              )}
              {...register("beneficiaryTypeGuid", {
                required: true,
              })}
              onChange={(e: any, newVal: any) => {
                console.log(newVal);
                setBeneficiaryTypeGUID(newVal.beneficiaryTypeGUID);
              }}
            />

Consider you are a react developer.

help me to solve this problem.

- No values are populating in this Beneficiary type field
- api side is working.
- I want to populate the beneficiary types label on dropdown of beneficiary type fied.
- Make appropriate changes and return the updated version of code.
use('myworlddb')

//{} empty fetches all documents
db.person.deleteMany({name:"hemanth"})
use('myworlddb')
 
//{} empty fetches all documents
db.person.deleteOne({name:"hemanth"})
use('myworlddb')

//{} empty fetches all documents
db.person.updateMany({age:{$lt:30}},{
  $set:{age: 1}
})
use('myworlddb')
 
//{} empty fetches all documents
db.person.updateOne({name:"hemanth"},{
  $set:{age: 28}
})
use('myworlddb')
 
//{} empty fetches all documents
db.person.find({name:"naveen"})
<script>
func hide {
function listener(event) {
  const 1 = document.create("li")
  switch (event.type) {
    case "animationstart":
      l.textContent = `Started: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationend":
      l.textContent = `Ended: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationiteration":
      l.textContent = `New loop started at time ${event.elapsedTime}`;
      break;
  }
  document.getElementById("output").appendChild(l);
}
const element = document.getElementByClass("hidden");
element.addEventListener("animationstart", listener, true);
element.addEventListener("animationend", listener, true);
element.addEventListener("animationiteration", listener, true);
}

func bounce1 {
function listener(event) {
  const 2 = document.createElement("li");
  switch (event.type) {
    case "animationstart":
      l.textContent = `Started: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationend":
      l.textContent = `Ended: elapsed time is ${event.elapsedTime}`;
      break;
    case "animationiteration":
      l.textContent = `New loop started at time ${event.elapsedTime}`;
      break;
  }
  document.getElementById("output").appendChild(l);
}
const element = document.getElementByClass("bounce1");
element.addEventListener("animationstart", listener, true);
element.addEventListener("animationend", listener, true);
element.addEventListener("animationiteration", listener, true);

element.className = "bounce1";
}

const element = document.getElementByClass("slideInFromLeft");
element.addEventListener("animationstartLeft", listener, true);
element.addEventListener("animationendLeft", listener, true);
element.addEventListener("animationiterationLeft", listener, true);

element.className = "slideInFromLeft";

const element = document.getElementByClass("slideInFromRight");
element.addEventListener("animationstartRight", listener, true);
element.addEventListener("animationendRight", listener, true);
element.addEventListener("animationiterationRight", listener, true);

element.className = "slideInFromRight";

</script>
if (window.matchMedia("(max-width: 768px)").matches) {
   this.fullSideBar = false;
}
const handlePersonalInfo = (data: any, e: any) => {
    e.preventDefault();
    console.log('entered info::', data);
    let hasEmiratesId: boolean;
    if (selectedOption === 'Yes') hasEmiratesId = true;
    else hasEmiratesId = false;
    let isMirrorWill: boolean;
    if (singleWillCheck) isMirrorWill = false;
    else isMirrorWill = true;
    const allData = {
      ...data,
      maritalStatusGUID,
      dateOfBirth,
      referralQuestionGUID,
      hasEmiratesId,
      isMirrorWill,
      isdCodeGUID1: countryGUID,
      isdCodeGUID2: countryGUID,
      nationalityGuid,
      countryGUID,
    };
    console.log('allData test', allData);
    axios.post(personalInformationAPI, allData).then((res) => {
      console.log('res post', res);
    });
const colors = ["blue", "red", "cyan", "yellow", "orange", "black", "white", "pink", "green", "purple"];
const randomColors = [];

for (let i = 0; i < 3; i++){
      const randomNumbers = Math.floor(Math.random() * colors.length);
      randomColors.push(colors[randomNumbers])
};

console.log(randomColors);
<Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}> <button type="submit" className="next-btn"> Next Step </button> {/* {singleWillCheck ? ( <button type="submit" className="next-btn"> Next Step </button> ) : ( <button type="button" className="next-btn" onClick={handleMirrorWill}> Enter Spouse Information </button> )} */}
    <Box sx={{ flex: '1 1 auto' }} /> <Button color="inherit">Skip</Button> <Button color="inherit" onClick={handleBack}> Back </Button>
</Box>
{!(activeStep === 7) && (
if we set active step to 7, then we can view Upload Documents page.
/* eslint-disable array-callback-return */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable react/no-array-index-key */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-plusplus */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-alert */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable jsx-a11y/control-has-associated-label */
/* eslint-disable react/button-has-type */
/* eslint-disable max-len */
import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';

import { AiOutlineClose } from 'react-icons/ai';

import FileUploadIcon from '@assets/FileUploadIcon.svg';
import FileUploadIconDark from '@assets/FileUploadIconDark.svg';
import TickMarkIconGreen from '@assets/TickMarkIconGreen.svg';
import TickMarkIconGrey from '@assets/TickMarkIconGrey.svg';
import FileArrowIcon from '@assets/FileArrowIcon.svg';

import './style.scss';

function DocumentManager() {
  const [activeElement, setActiveElement] = useState('top');
  const [uploadedFiles, setUploadedFiles] = useState([]);

  /**
   * Sets the active element to the given element string.
   *
   * @param {string} element - The string representing the active element to set.
   */
  const handleElementClick = (element: string) => {
    setActiveElement(element);
  };

  /**
   * Returns the background color style object for a given element.
   *
   * @param {string} element - The element to get background style for.
   * @return {Object} The background color style object for the given element.
   */
  const getBackgroundStyle = (element: string) => ({
    backgroundColor: activeElement === element ? '#023979' : '#FFFFFF',
  });

  /**
   * Returns an object representing the style to be applied to the title element.
   *
   * @param {string} element - The element to apply the style to.
   * @return {Object} An object containing the color property to be applied to the title element.
   */
  const getTitleStyle = (element: string) => ({
    color: activeElement === element ? '#FFFFFF' : '#1B202D',
  });

  const getFileUploadIcon = (element: string) => (activeElement === element ? FileUploadIcon : FileUploadIconDark);

  const getTickMarkicon = (element: string) => (activeElement === element ? TickMarkIconGreen : TickMarkIconGrey);

  const handleAddFileClick = (e: any) => {
    e.preventDefault();
    if (e.target !== e.currentTarget) {
      return;
    }
    document.getElementById('file-upload-input')?.click();
  };

  /**
 * Handles the file input change event.
 *
 * @param {any} e - the event object
 * @return {void}
 */
  const handleFileInputChange = (e: any) => {
    const newFiles = Array.from(e.target.files);
    checkFileValidity(newFiles);
  };

  /**
   * Handles the file drop event by checking the validity of the accepted files.
   *
   * @param {any} acceptedFiles - the files that have been accepted for upload
   */
  const handleFileDrop = (acceptedFiles: any) => {
    checkFileValidity(acceptedFiles);
  };

  /**
   * Prevents the click event from propagating and executing other click events.
   *
   * @param {any} e - the click event to be stopped from propagating
   */
  const handleRowItemClick = (e: any) => {
    e.stopPropagation();
  };

  /**
   * Filters files by their extension and size, and adds the valid files to the uploadedFiles state.
   *
   * @param {Array} files - The array of files to be checked.
   * @return {void} Returns nothing.
   */
  const checkFileValidity = (files: any) => {
    const validExtensions = ['.pdf', '.jpeg', '.jpg', '.bmp', '.doc', '.docx'];
    const maxFileSize = 20 * 1024 * 1024;

    const validFiles = files.filter((file: any) => {
      const isValidExtension = validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext));
      const isWithinMaxSize = file.size <= maxFileSize;
      return isValidExtension && isWithinMaxSize;
    });

    const invalidFiles = files.filter((file: any) => !validFiles.includes(file));
    if (invalidFiles.length > 0) {
      const invalidFileNames = invalidFiles.map((file: any) => file.name).join(', ');
      alert(`Invalid files: ${invalidFileNames}. Please use A4-size PDF, JPEG, BMP, DOC, or DOCX files that are within 20MB.`);
    } else {
      setUploadedFiles((prevFiles) => [...prevFiles, ...validFiles]);
      alert('Files uploaded successfully');
    }
  };

  /**
   * Removes a file from the uploaded files list.
   *
   * @param {any} file - The file to be removed.
   */
  const removeFile = (file: any) => {
    setUploadedFiles((prevFiles) => prevFiles.filter((f) => f !== file));
  };

  const {
    getRootProps,
    getInputProps,
  } = useDropzone({
    onDrop: handleFileDrop,
  });

  return (
    <main>
      <section>
        <header className="header">Upload Documents</header>
        <p className="description">Upload the documents in PDF or JPEG format. Click on next to save the files once all the documents have been uploaded</p>
      </section>
      <div className="row document-upload-container">

        <div className="col-lg-6 container">
          <div
            className={`top${activeElement === 'top' ? ' active' : ''}`}
            style={getBackgroundStyle('top')}
            onClick={() => handleElementClick('top')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('top')} alt="File Uploader Icon" />
              </div>
              <div
                className="document-title"
                style={getTitleStyle('top')}
              >
                Testator Passport

              </div>
            </div>
            <div className="tick-icon">
              <img src={getTickMarkicon('top')} alt="Tick Mark" />
            </div>
          </div>

          <div
            className={`middle${activeElement === 'middle' ? ' active' : ''}`}
            style={getBackgroundStyle('middle')}
            onClick={() => handleElementClick('middle')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('middle')} alt="File Uploader Icon Dark" />
              </div>
              <div
                className="document-title text-bottom-2"
                style={getTitleStyle('middle')}
              >
                Additional Document
              </div>
            </div>
            <div className="tick-icon">
              <img src={getTickMarkicon('middle')} alt="Tick Mark" />
            </div>
          </div>

          <div
            className={`bottom${activeElement === 'bottom' ? ' active' : ''}`}
            style={getBackgroundStyle('bottom')}
            onClick={() => handleElementClick('bottom')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('bottom')} alt="File Uploader Icon Dark" />
              </div>
              <div
                className="document-title text-bottom-2"
                style={getTitleStyle('bottom')}
              >
                Executor Passport
              </div>
            </div>
            <div className="tick-icon tick-icon-last">
              <img src={getTickMarkicon('bottom')} alt="Tick Mark" />
            </div>
            <div />
          </div>
        </div>

        <div className="col-lg-6 row-item" {...getRootProps()} onClick={handleRowItemClick}>
          <div className="file-upload-arrow">
            <img src={FileArrowIcon} alt="File Upload Arrow Icon" />
          </div>
          <div className="file-upload-text">
            Drag and drop document here to upload
          </div>
          <div className="file-attach-instructions">
            Please attach the file(s) below (use the Add button). We recommend using A4-size PDF, BMP, PNG, DOC, DOCX, JPG and JPEG files. File size cannot be more than 20 megabytes (MB). Your files will be uploaded when you submit your form.
          </div>
          <div className="file-add-button">
            <button onClick={handleAddFileClick}>Add File</button>
            <input
              type="file"
              id="file-upload-input"
              name="file-upload-input"
              accept=".pdf, .bmp, .png, .doc, .docx, .jpg, .jpeg"
              multiple
              onChange={handleFileInputChange}
              style={{ display: 'none' }}
              {...getInputProps()}
            />
          </div>
          {uploadedFiles.length > 0 && (
          <div className="file-list">
            <ul>
              {uploadedFiles.map((file: any, index) => (
                <li key={index}>
                  {file.name}
                  <AiOutlineClose
                    className="close-icon"
                    onClick={() => removeFile(file)}
                  />
                </li>
              ))}
            </ul>
          </div>
          )}
        </div>
      </div>
    </main>
  );
}

export default DocumentManager;
const handleRowItemClick = (e) => {
  e.stopPropagation();
};

// ...

<div className="col-lg-6 row-item" {...getRootProps()} onClick={handleRowItemClick}>
  {/* Remaining code */}
</div>
document.querySelector('#myButton').addEventListener('click',e => {
  e.target.classList.toggle('black')

})
You are a React and frontend expert.

I want to achieve below changes to my current version of code.

Constraints:

1. Add a AiOutlineClose react icon on right side of each file which is listed.
2. On Clicking this icon, that uploaded file is removed from list and from UI as well.
3. Attached current code for reference.


```
/* eslint-disable react/no-array-index-key */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-plusplus */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-alert */
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable jsx-a11y/control-has-associated-label */
/* eslint-disable react/button-has-type */
/* eslint-disable max-len */
import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';

import FileUploadIcon from '@assets/FileUploadIcon.svg';
import FileUploadIconDark from '@assets/FileUploadIconDark.svg';
import TickMarkIconGreen from '@assets/TickMarkIconGreen.svg';
import TickMarkIconGrey from '@assets/TickMarkIconGrey.svg';
import FileArrowIcon from '@assets/FileArrowIcon.svg';

import './style.scss';

function DocumentManager() {
  const [activeElement, setActiveElement] = useState('top');
  const [uploadedFiles, setUploadedFiles] = useState([]);

  const handleElementClick = (element: string) => {
    setActiveElement(element);
    console.log(activeElement);
  };

  const getBackgroundStyle = (element: string) => ({
    backgroundColor: activeElement === element ? '#023979' : '#FFFFFF',
  });

  const getTitleStyle = (element: string) => ({
    color: activeElement === element ? '#FFFFFF' : '#1B202D',
  });

  const getFileUploadIcon = (element: string) => (activeElement === element ? FileUploadIcon : FileUploadIconDark);

  const getTickMarkicon = (element: string) => (activeElement === element ? TickMarkIconGreen : TickMarkIconGrey);

  const handleAddFileClick = () => {
    document.getElementById('file-upload-input')?.click();
  };

  const handleFileInputChange = (e: any) => {
    const newFiles = Array.from(e.target.files);
    console.log(newFiles);
    checkFileValidity(newFiles);
    setUploadedFiles((prevFiles) => [...prevFiles, ...newFiles]);
  };

  const handleFileDrop = (acceptedFiles: any) => {
    console.log(acceptedFiles);
    checkFileValidity(acceptedFiles);
    setUploadedFiles((prevFiles) => [...prevFiles, ...acceptedFiles]);
  };

  const checkFileValidity = (files: any) => {
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const validExtensions = ['.pdf', 'jpeg', 'jpg', '.bmp', '.doc', '.docx'];
      const maxFileSize = 20 * 1024 * 1024;

      if (!validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext))) {
        alert(`Invalid File: ${file.name}. Please use A4-size PDF, JPEG, BMP, DOC or DOCX files`);
      } else if (file.size > maxFileSize) {
        alert(`File size exceeds the limit: ${file.name}. Maximum file size is 20MB.`);
      } else {
        alert('File uploaded successfully');
      }
    }
  };

  const {
    getRootProps,
    getInputProps,
    isDragActive,
    isDragAccept,
    isDragReject,
  } = useDropzone({
    onDrop: handleFileDrop,
  });

  return (
    <main>
      <section>
        <header className="header">Upload Documents</header>
        <p className="description">Upload the documents in PDF or JPEG format. Click on next to save the files once all the documents have been uploaded</p>
      </section>
      <div className="row">

        <div className="col-lg-6 container">
          <div
            className={`top${activeElement === 'top' ? ' active' : ''}`}
            style={getBackgroundStyle('top')}
            onClick={() => handleElementClick('top')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('top')} alt="File Uploader Icon" />
              </div>
              <div
                className="document-title"
                style={getTitleStyle('top')}
              >
                Testator Passport

              </div>
            </div>
            <div className="tick-icon">
              <img src={getTickMarkicon('top')} alt="Tick Mark" />
            </div>
          </div>

          <div
            className={`middle${activeElement === 'middle' ? ' active' : ''}`}
            style={getBackgroundStyle('middle')}
            onClick={() => handleElementClick('middle')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('middle')} alt="File Uploader Icon Dark" />
              </div>
              <div
                className="document-title text-bottom-2"
                style={getTitleStyle('middle')}
              >
                Additional Document
              </div>
            </div>
            <div className="tick-icon">
              <img src={getTickMarkicon('middle')} alt="Tick Mark" />
            </div>
          </div>

          <div
            className={`bottom${activeElement === 'bottom' ? ' active' : ''}`}
            style={getBackgroundStyle('bottom')}
            onClick={() => handleElementClick('bottom')}
          >
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={getFileUploadIcon('bottom')} alt="File Uploader Icon Dark" />
              </div>
              <div
                className="document-title text-bottom-2"
                style={getTitleStyle('bottom')}
              >
                Executor Passport
              </div>
            </div>
            <div className="tick-icon tick-icon-last">
              <img src={getTickMarkicon('bottom')} alt="Tick Mark" />
            </div>
            <div />
          </div>
        </div>

        <div className="col-lg-6 row-item" {...getRootProps()}>
          <div className="file-upload-arrow">
            <img src={FileArrowIcon} alt="File Upload Arrow Icon" />
          </div>
          <div className="file-upload-text">
            Drag and drop document here to upload
          </div>
          <div className="file-attach-instructions">
            Please attach the file(s) below (use the Add button). We recommend using A4-size PDF, BMP, PNG, DOC, DOCX, JPG and JPEG files. File size cannot be more than 20 megabytes (MB). Your files will be uploaded when you submit your form.
          </div>
          <div className="file-add-button">
            <button onClick={handleAddFileClick}>Add File</button>
            <input
              type="file"
              id="file-upload-input"
              name="file-upload-input"
              accept=".pdf, .bmp, .png, .doc, .docx, .jpg, .jpeg"
              multiple
              onChange={handleFileInputChange}
              style={{ display: 'none' }}
              {...getInputProps()}
            />
          </div>
        </div>
        {uploadedFiles.length > 0 && (
          <div className="file-list">
            <ul>
              {uploadedFiles.map((file: any, index) => (
                <li key={index}>{file.name}</li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </main>
  );
}

export default DocumentManager;

```

''' 
 <div className="col-lg-6 row-item">
          <div className="file-upload-arrow">
            <img src={FileArrowIcon} alt="File Upload Arrow Icon" />
          </div>
          <div className="file-upload-text">
            Drag and drop document here to upload
          </div>
          <div className="file-attach-instructions">
            Please attach the file(s) below (use the Add button). We recommend using A4-size PDF, BMP, PNG, DOC, DOCX, JPG and JPEG files. File size cannot be more than 20 megabytes (MB). Your files will be uploaded when you submit your form.
          </div>
          <div className="file-add-button">
            <button onClick={addFileHandler}>Add File</button>
          </div>
        </div>
   '''
 
 Your are a senior react developer.
 
 I want you to implement a functionality to upload files on button click event and drag and drop.
 
 Contrainst:
 
1. function should be implemented on `addFileHandler` event given above.
2. File can also be uploaded by drag and drop into row-item div element.
3. instructions for file upload is given `file-attach-instructions` div element.
4. You can use packages like `react-uploader` to implement this.
5. Finally return the updated version of code. Current code is above for reference.


 
 
 
<div className="col-lg-6 row-item">
   <div className="file-upload-arrow">
     <img src={FileArrowIcon} alt="File Upload Arrow Icon" />
   </div>
   <div className="file-upload-text">
     Drag and drop document here to upload
   </div>
   <div className="file-attach-instructions">
     Please attach the file(s) below (use the Add button). We recommend using A4-size PDF, BMP, PNG, DOC, DOCX, JPG and JPEG files. File size cannot be more than 20 megabytes (MB). Your files will be uploaded when you submit your form.
   </div>
   <div className="file-add-button">
     <button>Add File</button>
   </div>
 </div>
 
 
 Consider you are a CSS expert. Above is the code you have to update and make neccessary styling based on below constraints
 
 Constraints:
 
 1. Center the child elements of row-item div element horizonatally & vertically.
 2. Each child element is aligned center.
 3. Update backgournd of Add File button to #023979.
 4. Set border radious of button to 5px and font color to #FFFFFF.
 5. Fibnally return the updated version of code with change in styles.
# Installing Rosetta
/usr/sbin/softwareupdate --install-rosetta --agree-to-license

# Install NVM
# https://github.com/nvm-sh/nvm#install--update-script
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

# Installing Node 14 by NVM
arch
# >>> arm64
arch -x86_64 zsh
arch
# >>> i386
nvm install 14
nvm use 14
"""
<div className="top">
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={FileUploadIcon} alt="File Uploader Icon" />
              </div>
              <div className="document-title">Testator Passport</div>
            </div>
            <div className="tick-icon">
              <img src={TickMarkIconGreen} alt="Tick Mark" />
            </div>
          </div>

          <div className="middle">
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={FileUploadIconDark} alt="File Uploader Icon Dark" />
              </div>
              <div className="document-title text-black">Additional Document</div>
            </div>
            <div className="tick-icon">
              <img src={TickMarkIconGrey} alt="Tick Mark" />
            </div>
          </div>

          <div className="bottom">
            <div className="left-container">
              <div className="file-upload-icon">
                <img src={FileUploadIconDark} alt="File Uploader Icon Dark" />
              </div>
              <div className="document-title text-black">Executor Passport</div>
            </div>
            <div className="tick-icon tick-icon-last">
              <img src={TickMarkIconGrey} alt="Tick Mark" />
            </div>
            <div />
         </div>
"""


You are an experienced React Developer.

I want to implement a UI change.

On clicking top, middle or bottom div elements, 
  1. its backgound should be changed to #023979. 
  2. Its document-title element color should be changed to #FFFFFF.
For example. middle div element is clicked, it is active and the backgound changes to #023979.
While background of Inactive elements changes to default color #f4f4f4.
Initially when component loads, top element background is #023979, and bottom 2 element background is #f4f4f4.
you can use react hooks and state if needed. 
Help me to achieve this change by modiyfinh current version of code

I will give styles for reference below.

.container {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.top, .middle, .bottom {
    display: flex;
    justify-content: space-between;
    background-color: #f4f4f4;
    border-radius: 5px 0px 0px 5px;
}

.top {
    display: flex;
    align-items: center;
    background-color: #023979;
}

.container div {
    padding: 5px;
    text-align: center;
    cursor: pointer;
}

.document-title {
    font-family: 'Basis Grotesque Arabic Pro';
    font-style: normal;
    font-weight: 700;
    font-size: 0.875rem;
    line-height: 14px;
    color: #FFFFFF;
}

.left-container {
    display: flex;
    align-items: center;
    margin-right: 12px;
}

.file-upload-icon,
.document-title {
    margin-right: 12px;
}

.tick-icon {
    margin-left: auto;
    margin-right: 12px;
}

.document-title {
    flex-grow: 1;
}

.tick-icon-last {
    margin-right: 2px !important;
}










var amplitud = 15; // Amplitud del movimiento
var frecuencia = 2; // Frecuencia del movimiento (en rebotes por segundo)
var duracionBucle = 8; // Duración del bucle en segundos

var wiggleX = wiggle(frecuencia, amplitud)[0];
var wiggleY = wiggle(frecuencia, amplitud)[1];

var tiempoTotal = duracionBucle / 2; // Dividimos por 2 porque el bucle completo consta de un ida y vuelta
var tiempo = time % tiempoTotal;

var posicionInicial = [0, 0]; // Posición inicial del objeto

[posicionInicial[0] + wiggleX, posicionInicial[1] + wiggleY]
var radio = 25; // Radio de la trayectoria circular
var velocidad = 0.5; // Velocidad de la animación (en grados por segundo)
var duracionBucle = 8; // Duración del bucle en segundos

var vueltasCompletas = duracionBucle * (360 / velocidad);
var angulo = degreesToRadians((360 * time * velocidad) % (360 * vueltasCompletas));

var posicionX = Math.cos(angulo) * radio;
var posicionY = Math.sin(angulo) * radio;

[posicionX+250, posicionY+536.3]
function past(h, m, s){
  return ((h*3600)+(m*60)+s)*1000;
}

//////

function past(h, m, s){
  return (m * 60000) + (h * 3600000) + (s * 1000);
}
function countPositivesSumNegatives(input) {
    if (!input || input.length === 0) {
    return [];
    }  
  var total1 = 0;
  var total2 = 0;
  for (i = 0; i < input.length; i++) {   
    if (input[i] > 0) {                  
      total1 += 1;
    }
    if (input[i] < 0) {
      total2 += input[i];
    }
  }
  return [total1, total2];    
}
function XO(str) {
  const x = (str.match(/x/ig) || []).length;
  const o = (str.match(/o/ig) || []).length;
  return x === o;
}
function check(a,x){
  return a.includes(x);
};
function repeatStr (n, s) {
  return s.repeat(n);
}
function betterThanAverage(classPoints, yourPoints) {
  return yourPoints > classPoints.reduce((a, b) => a + b, 0) / classPoints.length; 
}
//Opción 1:
function getCount(str) {
  const vocal = str.match(/[aeiou]/ig);
  return vocal === null ? 0 : vocal.length; //si no hay vocales devuelve 0, si hay devuelve la cantidad
}

//Opción 2:
function getCount(str) {
  return str.replace(/[^aeiou]/gi, '').length;
}

//Opción 3:
function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}
//Opción 1:
function areYouPlayingBanjo(name) {
  return name + (name[0].toLowerCase() == 'r' ? ' plays' : ' does not play') + " banjo";
}

//Opción 2:
function areYouPlayingBanjo(name) {
  const letra = name.charAt(0);
  if (letra === "r" || letra === "R") {
    return name + " toca el banjo";
  }
  return name + " no toca el banjo";
}
String.prototype.toJadenCase = function () { 
  return this.split(" ").map(function(word){
    return word.charAt(0).toUpperCase() + word.slice(1);
  }).join(" ");
}
const points=games=>games.reduce((output,current)=>{
    return output += current[0]>current[2] ? 3 : current[0]===current[2] ? 1 : 0;
  },0)

//DIFERENTE ESCRITO:
 function points(games) {
   return games.reduce((output,current)=>{
     let x = parseInt(current[0]);
     let y = parseInt(current[2]);
     let value= x>y ? 3 : x===y ? 1 : 0;
     return output+value;
   },0)
 }
function positiveSum(arr) {
  var total = 0;    
  for (i = 0; i < arr.length; i++) {   
    if (arr[i] > 0) {                   // if arr[i] es mayor a 0
      total += arr[i];                  // dar el total de la suma de esos arr[i]
    }
  }
  return total;                         // return total
}
//Opción 1:
function booleanToString(b){
  return b.toString();
}

//Opción 2:
function booleanToString(b){
  return b ? 'true' : 'false';
}
// si b es true? devolver 'true' si no lo es devolver 'false'.

//Opción3:
function booleanToString(b){
  return String(b);
}
//Opción 1:
function findAverage(array) {
  if(array.length === 0) {
    return(0);
  }
  return array.reduce((a, b) => a + b, 0) / array.length;
} 

//Opción 2:
var find_average = (array) => {  
  return array.length === 0 ? 0 : array.reduce((a, b)=> a + b, 0)/array.length
}
function findNeedle(haystack) {
  return "found the needle at position " + haystack.indexOf("needle");
}
smash = function (words) {
  return words.join(" ");
};
function century(year) {
  return Math.ceil(year / 100);
}
const parts = ["shoulders", "knees"];

const lyrics = ["head", ...parts, "and", "toes"];

// TOTAL lyrics ["head", "shoulders", "knees", "and", "toes"]
const min = (list) => Math.min(...list);
const max = (list) => Math.max(...list);
const rps = (p1, p2) => {
  if (p1 === p2) return "Draw!";
  var rules = {rock: "scissors", paper: "rock", scissors: "paper"};
  if (p2 === rules[p1]) {
    return "Player 1 won!";
  }
  else {
    return "Player 2 won!";
  }
};
//OPCIÓN 1
function getGrade (s1, s2, s3) {
  avg = (s1+s2+s3)/3;
  if (avg < 60)  return "F";
    else if (avg < 70) return "D";
    else if (avg < 80) return "C";
    else if (avg < 90) return "B";
    else return "A";
}

//OPCIÓN 2
function getGrade(...scores) {
  let avg = scores.reduce((a, b) => a + b, 0) / scores.length;
  
  if (avg < 60)  return "F";
    else if (avg < 70) return "D";
    else if (avg < 80) return "C";
    else if (avg < 90) return "B";
    else return "A";
function solution(str){
  return str.split('').reverse().join('');  
}
// Opción 1:
function simpleMultiplication(n) {
    return n * (n % 2 ? 9 : 8);
}


// Opción 2:
function simpleMultiplication(n){
  return (n % 2 == 0) ? n * 8 : n * 9;
}


// Opción 3:
function simpleMultiplication(n){
    
  if(n % 2 === 0 ){ //si el numero es par...
	return n * 8;
  }
  else{ // si no lo es...
	return n * 9;
  }    
}
function removeChar(str){
  return str.slice(1, -1); 
};
// 1: .toString
function numberToString(num) {
  return num.toString();
}

// 2: String()
function numberToString(num) {
  return String(num);
}

// 3: '' +
function numberToString(num) {
  return ''+num;
}
//minus a mayus
function makeUpperCase(str) {
  return str.toUpperCase();
}

//mayus a minus
function makeLowerCase(str) {
  return str.toLowerCase();
}
function squareSum(numbers) {
  return numbers.reduce((sum, n) => n * n + sum, 0);
}
<button
   className="modal-close-button"
   onClick={handleCloseModal}
 >
   <span aria-hidden="true">&times;</span>
 </button>
 
 You are a CSS expert
 
 I want you to do following changes in styling.
 
 1. Rounded shape. Apply border radius to 50pc.
 2. Background to "#f1f1f1".
 3. No outer border color.
 3. border of child element span should be 2px solid #494A53.
dataSrc: function (json) {
  json.draw = json.jsonData.draw;
  json.recordsTotal = json.jsonData.Total_Records;
  json.recordsFiltered = json.jsonData.Total_Records;
  // json.data.data = response.jsonData.CR_list;
  //Make your callback here.
  // alert("Done!");
  // console.log(json);
  return json.jsonData.CR_list;
},
.initials-avatar {
    background-color: #023979;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 5px;
    width: 38px;
    height: 38px;
}
function createWindow() {
  webix.Date.startOnMonday = true;
  
  let window = webix.ui({
    view: "window",
    head: "Изберете датум", // Set the window title in Macedonian
    width: 400,
    //position: "center",
    move: false,
    modal: true,
    body: {
      rows: [
        {
          view: "calendar",
          id: "calendar",
          timepicker: true,
          icons: true,
          weekStart: 1, // 1 represents Monday
          calendarTime:"%H:%i",
          format: "%Y-%m-%d %H:%i:%s",
          events:webix.Date.isHoliday,
        },
        {
          view: "toolbar",
          elements: [
            {
              view: "button",
              value: "Готово",
              click: function () {
                var selectedDate = $$("calendar").getValue(); // Get the selected date and time
                if (selectedDate) {
                  var formattedDate = webix.Date.dateToStr(
                    "%Y-%m-%d %H:%i:%s"
                  )(selectedDate); // Format the date in MySQL format
                  
                  document.getElementById("result").innerHTML = "Selected Date: " + formattedDate; // Display the selected date and time in the result div
                }
                window.hide(); // Hide the window when the Done button is clicked
              }
            },
            {
              view: "button",
              value: "Откажи",
              click: function () {
                //$$('result').setValue('otkaz');
                document.getElementById("result").innerHTML = ""; // Display an empty result in the result div
                window.hide(); // Hide the window when the Cancel button is clicked
              }
            }
          ]
        }
      ]
    }
  });
	
  $$("calendar").selectDate(new Date(), true);
  // Show the window when the HTML button is clicked
  document.getElementById("show_window").onclick = function () {
    let button = this;
    let buttonPos = webix.html.offset(button);
    window.setPosition(buttonPos.x, buttonPos.y + button.offsetHeight);
    window.show();
  };
}

// Call the function to create the window
createWindow();
webix.i18n.setLocale({
  // Date and time formats
  dateFormat: "%d.%m.%Y",
  timeFormat: "%H:%i",
  longDateFormat: "%j %F %Y",
  fullDateFormat: "%j %F %Y %H:%i",
  am: "",
  pm: "",
  // Number formatting
  groupDelimiter: ".",
  decimalDelimiter: ",",
  decimalSize: 2,
  // Currency formatting
  currencyCode: "MKD",
  currencySymbol: "ден.",
  currencyPosition: "right",
  // Calendar settings
  calendar: {
    monthFull: [
      "Јануари", "Февруари", "Март", "Април",
      "Мај", "Јуни", "Јули", "Август",
      "Септември", "Октомври", "Ноември", "Декември"
    ],
    monthShort: [
      "Јан.", "Фев.", "Мар.", "Апр.",
      "Мај", "Јун", "Јул", "Авг.",
      "Септ.", "Окт.", "Ноем.", "Дек."
    ],
    dayFull: [
      "Недела", "Понеделник", "Вторник", "Среда",
      "Четврток", "Петок", "Сабота"
    ],
    dayShort: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са"],
    hours: "Часови",
    minutes: "Минути",
    done: "Готово",
    clear: "Избриши",
    today: "Денес",
    monthSelect: true,
    yearSelect: true,
    yearsBefore: 100,
    yearsAfter: 100,
    weekStart: 1,
    narrow: true
  }
});
//---------------------------------------------------------
// REST service to add an image to a PDF document
//---------------------------------------------------------
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const pdfLib = require('pdf-lib');

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

// Routes
app.post('/api/addImageToPDF', async function(req, res) {
	const { pdfPath, imagePath, outputName } = req.body;

	// Read PDF file
	const pdfData = await fs.promises.readFile(pdfPath);

	// Read image file
	const imageData = await fs.promises.readFile(imagePath);

	// Load PDF document
	const pdfDoc = await pdfLib.PDFDocument.load(pdfData);

	// Embed image in PDF
	const image = await pdfDoc.embedPng(imageData);
	const page = pdfDoc.getPages()[0];
	const { width, height } = page.getSize();
	page.drawImage(image, {
		x: 0,
		y: height - image.height,
		width: image.width,
		height: image.height,
	});

	// Save modified PDF
	const outputPath = path.join(__dirname, 'modified', outputName);
	const modifiedPdfBytes = await pdfDoc.save();
	await fs.promises.writeFile(outputPath, modifiedPdfBytes);

	// Send response
	res.json({ success: true, message: 'Image added to PDF', url: `http://localhost:${port}/api/getModifiedPDF/${outputName}` });
});

app.get('/api/getModifiedPDF/:fileName', async function(req, res) {
	const { fileName } = req.params;
	const filePath = path.join(__dirname, 'arhiviran', `${fileName}-arhivirano-${new Date().toISOString().replace(/[^\d]/g, '')}.pdf`);
	
	// Read modified PDF file
	const pdfData = await fs.promises.readFile(filePath);

	// Create blob from PDF data
	const blob = new Blob([pdfData], { type: 'application/pdf' });

	// Set response headers
	res.setHeader('Content-Type', 'application/pdf');
	res.setHeader('Content-Disposition', 'attachment; filename=modified.pdf');
	res.setHeader('Content-Length', pdfData.length);

	// Send response
	res.send(blob);
});

// Listen command
app.listen(port, function() {
	console.log(`Server is running on port ${port}`);
});
//---------------------------------------------------------


//---------------------------------------------------------
// How to call the service (client side) with a file name
//---------------------------------------------------------
// Create a FormData object to send the file data
var fileData = new FormData();
fileData.append('file', 'sample.pdf');

// Send the AJAX request to modify the PDF file
$.ajax({
	url: '/modify-pdf',
	method: 'POST',
	data: fileData,
	processData: false,
	contentType: false,
	success: function(data) {
		console.log('File modified successfully. Modified file URL:', data.url);
	},
	error: function() {
		console.error('Error modifying file.');
	}
});

//---------------------------------------------------------
// Send the AJAX request to get the modified PDF file as a blob
//---------------------------------------------------------
$.ajax({
	url: '/get-modified-pdf',
	method: 'GET',
	success: function(data) {
		// Create a blob URL from the received blob
		var blobUrl = URL.createObjectURL(data);
		
		// Create an anchor element to download the file
		var downloadLink = $('<a>')
			.attr('href', blobUrl)
			.attr('download', 'modified.pdf')
			.text('Download modified PDF file');
			
		// Add the anchor element to the page
		$('body').append(downloadLink);
	},
	error: function() {
		console.error('Error getting modified file.');
	}
});
//---------------------------------------------------------
function checkType(value, expectedType, propName) {
  if (typeof value !== expectedType) {
    throw new Error(`Invalid ${propName} type. Expected ${expectedType}.`);
  }
}

function checkInstance(value, expectedInstance) {
  if (!(value instanceof expectedInstance)) {
    const expectedName = expectedInstance.constructor.name;
    throw new Error(`Invalid type. Expected ${expectedName} instance.`);
  }
}

class Person {
  constructor(id, name, age, isActive, hobbies, address) {
    checkType(id, 'number', "id");
    checkType(name, 'string', "name");
    checkType(age, 'number', "age");
    checkType(isActive, 'boolean', "isActive");
    checkType(hobbies, 'object', "hobbies");
    checkInstance(address, Address);

    this.id = id;
    this.name = name;
    this.age = age;
    this.isActive = isActive;
    this.hobbies = hobbies;
    this.address = address;
  }
}

class Address {
  constructor(city, country, street) {
    checkType(city, 'string', "city");
    checkType(country, 'string', "country");
    checkInstance(street, Street);

    this.city = city;
    this.country = country;
    this.street = street;
  }
}

class Street {
  constructor(name, number, apartment) {
    checkType(name, 'string', "name");
    checkType(number, 'number', "number");
    checkInstance(apartment, Apartment);

    this.name = name;
    this.number = number;
    this.apartment = apartment;
  }
}

class Apartment {
  constructor(floor, number) {
    checkType(floor, 'number', "floor");
    checkType(number, 'number', "number");

    this.floor = floor;
    this.number = number;
  }
}

class PersonBuilder {
  constructor(personData) {
    const person = this.#buildPerson(personData);
    Object.assign(this, person);
  }

  #buildApartment(apartmentData) {
    const { floor, number } = apartmentData;
    return new Apartment(floor, number);
  }

  #buildStreet(streetData) {
    const { name, number, apartment } = streetData;
    const apartmentObj = this.#buildApartment(apartment);
    return new Street(name, number, apartmentObj);
  }

  #buildAddress(addressData) {
    const { city, country, street } = addressData;
    const streetObj = this.#buildStreet(street);
    return new Address(city, country, streetObj);
  }

  #buildPerson(personData) {
    const { id, name, age, isActive, hobbies, address } = personData;
    const addressObj = this.#buildAddress(address);
    return new Person(id, name, age, isActive, hobbies, addressObj);
  }
}

const personData = {
  id: 1,
  name: 'John Doe',
  age: 30,
  isActive: true,
  hobbies:{},
address: {
    city: 'Cityville',
    country: 'Countryland',
    street: {
      name: 'Main Street',
      number: 123,
      apartment: {
        floor: 2,
        number: 201
      }
    }
  }
};

const personBuilder = new PersonBuilder(personData);

console.log(personBuilder);
Changing the Value of a Custom Property Using JavaScript
I’ve been mentioning throughout this whole article that variables can be updated using JavaScript, so let’s get into that.

Say you have a light theme and want to switch it to a dark theme, assuming you have some CSS like the following:

```css
:root {
  --text-color: black;
  --background-color: white;
}

body {
  color: var(--text-color);
  background: var(--background-color);
}
```

You can update the `--text-color` and `--background-color` custom properties by doing the following:

```js
var bodyStyles = document.body.style;
bodyStyles.setProperty('--text-color', 'white');
bodyStyles.setProperty('--background-color', 'black');
```
let today = new Date();
  let currentDay = today.getDay();
  let day = "";

  switch (currentDay) {
    case 1:
      day = "Monday";
      break;
    case 2:
      day = "Tuesday";
      break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
      break;
    case 0:
      day = "Sunday";
    default:
      console.log("Error: Current day is equal to: " + currentDay);
      break;
  }
let arr = [
  1,
  "Computer Science",
  5,
  "Computer security",
  6,
  "Graphic design",
  4,
  "Programming language",
  3,
  "Software engineering",
  2,
  "Web Designing",
];
let matchName = "Computer Science";
let num = 0;
arr.map((ele) => {
  ele == matchName ? num++ : "none are match";
});
num > 0
  ? console.log("item are already in the array")
  : console.log("item are not mathced");
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");

const app = express();

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});

app.post("/", function(req, res){
app
})

app.listen(3000, function () {
  console.log("Server is running on port 3000.");
});
let arrNum = [10, 20, 30, 40, 50, 60];
let reducedArr = arrNum.reduce(function (f , s) {
    // (f) for the first element (s) for the seconde element ;
    return f *= s;
});
console.log("reduced Array" , reducedArr);
let demoData = [
  [
    { name: "Himanshu", age: 30 },
    { name: "KK", age: 29 },
  ],
  [
    { name: "preyansh", age: 30 },
    { name: "aki", age: 29 },
  ],
];
let uName = "K";
let matched = [];
let notMatched = [];
let mapingData = demoData.map((element, index, array) => {
  return element.filter((innerEle) => {
    return (innerEle.name.toLowerCase().includes(uName.toLowerCase())) ? done.push(innerEle) : wrong.push(innerEle);
  })
});
console.log(done);
// Find the first element with id = 2
const objToFind = myArray.find(obj => obj.id === 2);
console.log(objToFind); // { id: 2, name: 'Jane' }
var placeholder = "&#xf002 Select a place";
$(".select2").select2({
  placeholder: placeholder,
  escapeMarkup: function(m) { 
    return m; 
  }
});
<select class="select2-icon" name="icon">
    <option value="fa-user" data-icon="fa-user">user</option>
    <option value="fa-user-circle" data-icon="fa-user-circle">user-circle</option>
    <option value="fa-user-tie" data-icon="fa-user-tie">user-tie</option>
    <option value="fa-user-secret" data-icon="fa-user-secret">user-secret</option>
    <option value="fa-user-ninja" data-icon="fa-user-ninja">user-ninja</option>
</select>


<script>
  function formatText (icon) {
      return $('<span><i class="fas ' + $(icon.element).data('icon') + '"></i> ' + icon.text + '</span>');
  };
  $('.select2-icon').select2({
      width: "50%",
      templateSelection: formatText,
      templateResult: formatText
  });
</script>
$('mydiv').on('DOMSubtreeModified', function(){
  console.log('changed');
});
import React, { useEffect, useState } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import Topbar from "./scenes/global/Topbar";
import Dashboard from "./scenes/dashboard";
import DashboardSales from "./scenes/dashboardsales/index";
import DashboardMerchant from "./scenes/dashboardmerchandiser/index";
import Contacts from "./scenes/contacts/index";
import MerchantInfo from "./scenes/contacts/app";
import Form from "./scenes/form/index.js";
import Merchant from "./scenes/merchant/app";
import { CssBaseline, ThemeProvider } from "@mui/material";
import { ColorModeContext, tokens, useMode } from "./theme";
import Calendar from "./scenes/calendar/calendar";
import GoogleMap from "./scenes/maps/maps";
import RoutePlan from "./scenes/routeplan/RoutePlan";
import Home from "./Home";
import SignUpAdmin from "./SignAdmin";
import LoginAdmin from "./LoginAdmin";
import LoginSales from "./LoginSales";
import LoginMerchant from "./LoginMerchant";
import ProtectedRoute from "./ProtectedRoute";


function App() {
  const [theme, colorMode] = useMode();
  const [isSidebar, setIsSidebar] = useState(true);

  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // function setAuthState(state) {
  //   setIsAuthenticated(state)
  // }
  useEffect(() => {
    const token = localStorage.getItem("jwt");
    console.log({ token });

  }, [isAuthenticated]);

  return (
    <ColorModeContext.Provider value={colorMode}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <div className="app">
          <main className="content">
            <Topbar setIsSidebar={setIsSidebar} />
            <Routes>
              <Route path="/" element={<Home />} />

              <Route path="/signup-admin" element={<SignUpAdmin />} />
              <Route path="/admin-log" element={<LoginAdmin />} />
              <Route path="/sales-log" element={<LoginSales />} />
              <Route path="/merchant-log" element={<LoginMerchant />} />
              {/* protect routesclear */}

              <Route
                path="/admin"
                element={
                  <ProtectedRoute
                    element={Dashboard}
                    isAuthenticated={isAuthenticated}
                  />
                }
              />
              <Route
                path="/sales"
                element={
                  <ProtectedRoute
                    element={DashboardSales}
                    isAuthenticated={isAuthenticated}
                  />
                }
              />
              <Route
                path="/merchant"
                element={
                  <ProtectedRoute
                    element={DashboardMerchant}
                    isAuthenticated={isAuthenticated}
                  />
                }
              />
              <Route
                path="/contacts"
                element={
                  <ProtectedRoute
                    element={Contacts}
                    isAuthenticated={isAuthenticated}
                  />
                }
              />
              <Route
                path="/merchantInfo"
                element={
                  <ProtectedRoute
                    element={MerchantInfo}
                    isAuthenticated={isAuthenticated}
                  />
                }
              />
              <Route path="/form" element={<Form />} />
              <Route path="/form-merchant" element={<Merchant />} />
              <Route path="/calendar" element={<Calendar />} />
              <Route path="/maps" element={<GoogleMap />} />
              <Route path="/routeplans" element={<RoutePlan />} />
            </Routes>
          </main>
        </div>
      </ThemeProvider>
    </ColorModeContext.Provider>
  );
}

export default App;
function doFirst(){
    var button = document.getElementById('button');
    button.addEventListener("click",save,false);
}

function save(){
    var FirstName = document.getElementById('FName').value;
    var LastName = document.getElementById('LName').value;
    localStorage.setItem(FirstName, LastName);
}


if(sessionStorage && window.onload === true){
    sessionStorage.clear('Fname', 'LName');
}

window.addEventListener("load",doFirst,false);

import React, { useEffect, useState } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import Topbar from "./scenes/global/Topbar";
import Dashboard from "./scenes/dashboard";
import DashboardSales from "./scenes/dashboardsales/index";
import DashboardMerchant from "./scenes/dashboardmerchandiser/index";
import Contacts from "./scenes/contacts/index";
import MerchantInfo from "./scenes/contacts/app"
import Form from "./scenes/form/index.js";
import Merchant from "./scenes/merchant/app";
import { CssBaseline, ThemeProvider } from "@mui/material";
import { ColorModeContext, useMode } from "./theme";
import Calendar from "./scenes/calendar/calendar";
import GoogleMap from "./scenes/maps/maps";
import RoutePlan from "./scenes/routeplan/RoutePlan";
import Home from './Home'
import SignUpAdmin from "./SignAdmin";
import LoginAdmin from "./LoginAdmin";
import LoginSales from "./LoginSales";
import LoginMerchant from "./LoginMerchant";

function App() {
  const [theme, colorMode] = useMode();
  const [isSidebar, setIsSidebar] = useState(true);

  const [isAuthenticated, setIsAuthenticated] = useState(false);
    useEffect(() => {
      const token = localStorage.getItem("jwt");
      console.log({token});
    
      if (!token) {
        setIsAuthenticated(false);
      } else {
        setIsAuthenticated(true);
      }
    }, []);

  return (
    <ColorModeContext.Provider value={colorMode}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <div className="app">
          <main className="content">
            <Topbar setIsSidebar={setIsSidebar} />
            <Routes>
              {/* protect routesclear */}
              <Route path="/admin" element={isAuthenticated?<Navigate replace to="/admin" />: <Navigate replace to="/" />} />
              <Route path="/sales" element={isAuthenticated?<Navigate replace to="/sales" />: <Navigate replace to="/" />} />
              <Route path="/merchant" element={isAuthenticated?<Navigate replace to="/merchant" />: <Navigate replace to="/" />} />
              <Route path="/contacts" element={isAuthenticated?<Navigate replace to="/contacts" />: <Navigate replace to="/" />} />
              <Route path="/merchantInfo" element={isAuthenticated?<Navigate replace to="/merchantInfo" />: <Navigate replace to="/" />} />
              <Route path="/form" element={isAuthenticated?<Navigate replace to="/form" />: <Navigate replace to="/" />} />
              <Route path="/form-merchant" element={isAuthenticated?<Navigate replace to="/form-merchant" />: <Navigate replace to="/" />} />
              <Route path="/calendar" element={isAuthenticated?<Navigate replace to="/calendar" />: <Navigate replace to="/" />} />
              <Route path="/maps" element={isAuthenticated?<Navigate replace to="/maps" />: <Navigate replace to="/" />} />
              <Route path="/routeplans" element={isAuthenticated?<Navigate replace to="/routeplans" />: <Navigate replace to="/" />} />

              <Route path ="/"  element={<Home/>}/>
              <Route path="/signup-admin" element={<SignUpAdmin />} />
              <Route path="/admin-log" element={<LoginAdmin />} />
              <Route path="/sales-log" element={<LoginSales />} />
              <Route path="/merchant-log" element={<LoginMerchant />} />
              <Route path="/admin" element={<Dashboard />} />
              <Route path="/sales" element={<DashboardSales />} />
              <Route path="/merchant" element={<DashboardMerchant />} />
              <Route path="/contacts" element={<Contacts />} />
              <Route path="/merchantInfo" element={<MerchantInfo />} />

              <Route path="/form" element={<Form />} />
              <Route path="/form-merchant" element={<Merchant />} />

              <Route path="/calendar" element={<Calendar />} />
              <Route path="/maps" element={<GoogleMap/>}/>
              <Route path="/routeplans" element={<RoutePlan />}/>
            </Routes>
          </main>
        </div>
      </ThemeProvider>
    </ColorModeContext.Provider>
  );
}
export default App;
calculateSpan(price, n)
    { var ans=[];
   
       var stack=[];
     for(var i=0;i<n;i++)
        { if(stack.length==0)
        ans.push(-1);
        else if(stack.length>0 && stack[stack.length-1][0]>price[i])
            { ans.push(stack[stack.length-1][1])
                
            }
            else if(stack.length>0 && stack[stack.length-1][0]<=price[i])
          { while(stack.length>0 && stack[stack.length-1][0]<=price[i])
              { stack.pop()
              }
              if(stack.length==0)
        ans.push(-1);
         else  { ans.push(stack[stack.length-1][1])
            
        }
           
      
        } stack.push([price[i],i]);
        }
      for(var i=0;i<n;i++)
      { ans[i]=i-ans[i]
          
      }
       return ans;
    }
jest.mock('react-i18next', () => {
  return {
    useTranslation: () => ({ t: (key: string) => key }),
  };
});
module.exports = {
  content: ['./src/**/*.{html,js,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {
        primaryColor: '#E17446',
        primaryColorHover: '#db5b24',
        primaryText: '#111130',
        primaryBlue: '#2b5a9c',
        textLight: '#9e9ebc',
        Gray: '#8f9bad',
        f6f9fd: '#f6f9fd',
        dddddd: '#dddddd',
        inputborder: '#e8e8e8',
        borderColor: '#ebebeb',
        green: '#008f02',
        lightGreen: '#e2f2e2',
        orange: '#f05c00',
        orangeLight: '#fcede4',
        redLight: '#fde5e5',
        red: '#f00000',
        border1: '#ebebeb',

        themecolor: '#E17446',
        hoverthemecolor: '#db5b24',
      },
      backgroundImage: {
        close: 'url(/public/images/colse.png)',
        trendBG1: 'url(../../public/images/blog-img.jpg)',
      },
      boxShadow: {
        inputFocus:
          'rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.06) 0px 1px 2px 0px',
        headerFix: 'rgba(0, 0, 0, 0.1) 0px 10px 50px',
        sibarToggle: '-4px 5px 5px #0000000d',
        sibarToggleRTL: '5px -4px 6px #0000000d',
      },
      spacing: {
        '5px': '5px',
        '10px': '10px',
        '14px': '14px',
        '15px': '15px',
        '18px': '18px',
        '20px': '20px',
        '25px': '25px',
        '30px': '30px',
        '35px': '35px',
        '40px': '40px',
        '45px': '45px',
        '50px': '50px',
        '55px': '55px',
        '60px': '60px',
        '65px': '65px',
        '70px': '70px',
        '75px': '75px',
        '80px': '80px',
        '85px': '85px',
        '90px': '90px',
        '95px': '95px',
        '100px': '100px',
        '106px': '106px',
        '120px': '120px',
        unset: 'unset',
      },
      fontFamily: {
        charter: 'var(--charterFont)',
        sohne: 'var(--sohneFont)',
        poppins: 'var(--poppins)',
        gloock: 'var(--gloock)',
      },
      fontSize: {
        0: '0',
        '5px': '5px',
        '10px': '10px',
        '14px': '14px',
        '15px': '15px',
        '16px': '16px',
        '17px': '17px',
        '20px': '20px',
        '22px': '22px',
        '25px': '25px',
        '28px': '28px',
        '30px': '30px',
        '35px': '35px',
        '40px': '40px',
        '45px': '45px',
        '50px': '50px',
        '55px': '55px',
        '60px': '60px',
        '65px': '65px',
        '70px': '70px',
        '75px': '75px',
        '80px': '80px',
        '85px': '85px',
        '90px': '90px',
        '95px': '95px',
        '100px': '100px',
        unset: 'unset',
      },
      lineHeight: {
        1: '1',
        '5px': '5px',
        '10x': '10px',
        '15px': '15px',
        '19px': '19px',
        '22px': '22px',
        '20px': '20px',
        '25px': '25px',
        '28px': '28px',
        '30px': '30px',
        '32px': '32px',
        '35px': '35px',
        '36px': '36px',
        '40px': '40px',
        '42px': '42px',
        '46px': '46px',
        '45px': '45px',
        '50px': '50px',
        '52px': '52px',
        '55px': '55px',
        '60px': '60px',
        '65px': '65px',
        '70px': '70px',
        '75px': '75px',
        '80px': '80px',
        '85px': '85px',
        '90px': '90px',
        '95px': '95px',
        '100px': '100px',
        unset: 'unset',
        Normal: 'normal',
      },
      zIndex: {
        1: '9',
        2: '99',
        3: '999',
        4: '9999',
        5: '99999',
        6: '999999',
      },
      borderRadius: {
        '5px': '5px',
        '10px': '10px',
        '15px': '15px',
      },
      screens: {
        768: '768px',
        992: '992px',
        1200: '1200px',
        1300: '1300px',
        1400: '1400px',
        1500: '1500px',
        1600: '1600px',
        1700: '1700px',
      },
      animation: {
        slow: 'wiggle 2s linear',
      },
      keyframes: {
        wiggle: {
          '0%': { transform: 'transform(164.25px)' },
          '100%': { transform: 'rotate(0px)' },
        },
      },
    },
  },
}
var object = {
  "main": [{
    "id": "123",
    "name": "name 1"
  }, {
    "id": "234",
    "name": "name 2"
  }]
};
var toFind = "name 1";
var filtered = object.main.filter(function(el) {
  return el.name === toFind;
});

document.write(filtered);
<select class="select1" multiple>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<script>
    let dlb1 = new DualListbox('.select1');
</script>
const sandwichOne = ["white bread", "lettuce", "brown bread"];
const sandwichTwo = ["white bread", "tomato", "white bread"];

function compareBread(array1,array2) {
     let sameBread;
     if ((array1[0] === array2[0]) && (array1[array1.length - 1] === array2[array2.length - 1])) {
         console.log("Both tops and bottoms are the same!");
         return true;
     } else {
         console.log("They both use different bread -- WEIRDO!");
         return false;
     }
}

compareBread(sandwichOne,sandwichTwo);
let myFriends = ["John", "Jane", "Irma", "Anna"];

// -- My friends are ${friend}.

function createSentence(friends) {
    let friendsStr = "";
    for (let i = 0; i < friends.length; i++) {
        if (i === 0) {
        friendsStr += friends[i];
        } else if (i === friends.length-1) {
            friendsStr += ", and " + friends[i];
        }
        else {
        friendsStr += ", " + friends[i];
        }
    }
    let sentence = `My friends are ${friendsStr}!`;
    return sentence;
}
console.log(createSentence(myFriends));
//html code
<p class="custom-text-selection">Select some of this text.</p>

//css code
::selection {
  background: aquamarine;
  color: black;
}
.custom-text-selection::selection {
  background: deeppink;
  color: white;
}
SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'public'
   AND    table_name   = 'abcd'
   );
const request = new Request('https://third-party-no-cors.com/', {
  mode: 'no-cors',
});

// Assume `cache` is an open instance of the Cache class.
fetch(request).then(response => cache.put(request, response));
alert("this is a test".split(" ").join("-"));

//or

title.replace(/\s/g , "-");
function fibonacciGenerator (n) {
    let output = []
    if (n === 1) { 
        return output=[0]
    }
    else if (n === 2) { 
        return output=[0,1]
    }
    else {
output=[0,1]
for (let i=2; i<n; i++) {
      output.push(output[output.length-2] + output[output.length-1]); 
        }  
return output 
}  
}
let numOfBottles = 99
let lyrics = []
function beerSong() {
while (numOfBottles >=0) {
}
console.log(numOfBottles + " bottles of beer on the wall " + numOfBottles + " bottles of beer. Take one down and pass it around, " + numOfBottles + " bottles of beer on the wall.");
    
numOfBottles--;
}
function whosPaying(names) {
    
names = ["Angela", "Ben", "Jenny", "Michael", "Chloe"]
 
    let nameChosen = names[names.length *Math.random() | 0];
 
    return nameChosen + " is going to buy lunch today!";
 
}
let output = [];

function fizzbuzz() {
    
  for (let count = 1; count <= 100; count++) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("Fizzbuzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else {
      output.push(count);
    }
    count++;
  }
    
}

fizzbuzz();
function isLeap(year) {  
    
    //Write your code here.    


if (year % 4 !== 0) {
    return "Not leap year."
}

if (year % 4 === 0 && year % 100 !== 0)  {
    return "Leap year."
}

if (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) {
    return "Leap year"
}

}
function displayCash() {
 const money = 100;
 const currency = " Euros";
 console.log(money + currency);
}
displayCash();
const chores = ["sweep", "mop", "laundry"];
const priority = [];
for (i = (chores.length - 1); i >= 0; i--) {
  priority.push(chores[i]);
}
console.log(priority);
const topTen = ['Jack Reacher', 'Beautiful Creatures', 'Safe Haven',
  'Side Effects', 'The Last Stand', 'Silver Linings Playbook', 'Broken City',
  'Cloud Atlas', 'Parker', 'Eternals'
];
const topThree = [];
for (i = 0; i < 3; i++) {
  topThree.push(topTen[i]);
}
console.log(topThree);
const myNumbers = [];
for (let i = 1; i < 1001; i++) {
  myNumbers.push(i);
}
console.log(`The array now has ${myNumbers.length} numbers as elements.`);
let numbers = [5, 10, 12, 13, 17, 20, 21, 28];

let sumOfEvens = numbers.reduce((total,active) => {
    if (active % 2 === 0) {
        return active + total;
    console.log (`checking...even!`);
    }
    return total
}
, 0);

console.log (sumOfEvens);
let letters = ["M", "I", "M", "O"];

// console.log(letters);

let name = letters.reduce((total,active) => total + active, "");
if (name === "MIMO") {
    console.log(`Success! "${name}" is correct!`)
} else {
    console.log (`Error 0: You suck!`)
}
//prompt for names
 
let name1 = prompt("What is your name?")
let name2 = prompt("What is your crush's name?")
//calculate random number between 1-100
 
let loveScore = Math.random()* 100;
loveScore = Math.floor(loveScore) + 1;
 
 
//alert user their percentage
//alert(name1 + " and " + name2 + ", your love score is " + loveScore + "%");

// alert using conditions
if (loveScore === 100) {
    alert("Wow, " + name1 + " and " + name2 + ", your love score is " + loveScore + "%" + " you have a special kind of love! Marry each other right now!")
} 

if (loveScore > 30 && loveScore <= 99) {
    alert(name1 + " and " + name2 + ", your love score is " + loveScore + "%. Take your chances or go with your gut")
} 

if (loveScore <= 30) {
    alert ("oh dear, " + name1 + " and " + name2 + ", your love score is " + loveScore + "%. Your score is like mixing oil and water")
}
//Random Number Generation

var n = Math.random();
console.log(n);

//number will be between 0 and 0.9(to 16 decimal places)

//this will give 0-6 s adding 1 to every answer gives the numbers on a dice
//multiply by whatever range you need

n =  n * 6;

n = Math.floor(n) +1;
//called a pseudo random number generator
function bmiCalculator (weight, height) {
    
   let bmi = Math.round(weight / (Math.pow(height, 2)));
  
  let interpretation = bmi
  
   if (bmi < 18.5) {
        return "Your BMI is " + bmi + ", so you are underweight.";
    }
    if (bmi >= 18.5 && bmi <= 24.9) {
        return "Your BMI is " + bmi + ", so you have a normal weight.";
    }
    
    if (bmi > 24.9) {
        return "Your BMI is " + bmi + ", so you are overweight.";
    }
  
  
   return interpretation;
}
var testData = {
	name: 'filtered',
       data: 'This should be filtered',
	extras: {
         headers: {
           name: 'update',
           categpory: 'computing',
           location: 'London',
	    product: '"Laptop"',
    quantity: '10' 
         },
       },
     };
     var filterOption = {
       filter: 'headers.category == `"Computing"` && headers.location == `London`',
     };
...
/* set up realtime */
....
var rtChannel = realtime.channels.getDerived('chan', filterOption);
/* subscribe to event */
 rtChannel.subscribe('filtered', function (msg) {
function getMilk (money) {
  // this will take take the money you put in and use the modula to find the change received (remainder) when you divide the money by 1.5 and return the total
  return money % 1,5;
}
// this variable saves the result of running the function
let change = getMilk(4)
function lifeInWeeks(age) {   
    
    //Write your code here.
    let x = age
    let monthsLeft = (90 - x) * 12
    let weeksLeft = ((90-x) * 52)
    let daysLeft = ((90-x) * 365)
    
    console.log("You have " + daysLeft + " days, " + weeksLeft + " weeks, and " +  monthsLeft + " months left to live");

}
//create function
function getMilk(money, costPerBottle) {//enclose all the instructions
  console.log("leaveHouse");
  console.log("moveRight");
  console.log("moveRight");
  console.log("moveUp");
  console.log("moveUp");
  console.log("moveUp");
  console.log("moveUp");
  console.log("moveRight");
  console.log("moveRight");
  //numOfBottles = however much money you put in () and divide by 1.5, rounded down to the nearest whole number
    
    console.log("buy " + calcBottles(money, costPerBottle) + " bottles of milk");
  console.log("moveLeft");
  console.log("moveLeft");
  console.log("moveDown");
  console.log("moveDown");
  console.log("moveDown");
  console.log("moveDown");
  console.log("moveLeft");
  console.log("moveLeft");
  console.log("enterHouse");
  
  return calcChange(money, costPerBottle) ;
}

function calcBottles(startingMoney, costPerBottle) {
  let numberOfBottles = Math.floor(startingMoney / costPerBottle);
  
  return numberOfBottles;
}

function calcChange(startingMoney, costPerBottle) {
  let change = startingMoney % costPerBottle;
  return change;
}

//call the function
console.log("Hello Alana, here is you " + getMilk(5, 1.5) + " change.");
//create function

// function --> name of function --> () {}

function getMilk() {
    //enclose all the instructions
}

//call the function
getMilk();
x++ //increment expression
//is equal to x+1

x-- //decrement expression
//is equal to -1

x=2
y=5
x += y // =7

// +=
// -=
// *=
// /=
let dogAge = prompt("How old is your dog?");

let humanAge = ((dogAge-2)*4)+21;

alert("Your dog is " + humanAge + "in human years");
let name = prompt("What is your Name?");
let firstLettertoCapital = name.slice(0,1).toUpperCase()
let nameChangetoLowerCase = name.slice(1, name.length).toLowerCase()

//name.toUpperCase();

alert ("Hello, " + firstLettertoCapital + nameChangetoLowerCase)
var name = "Alana"

name.slice(1,4);

// will give l, a, n
// 4-1=3 so you will get 3 characters
// 1 starts at the 2nd letter. 4 stops up to but not including the 5th letter

alert(prompt("Compose your tweet:").slice(0,140));
// allows you to compose your tweet up to 140 characters and no more
realtime.channels.get('foo').publish({
    name: 'foo',
    data: 'msg',
    extras: {
        headers: {
            key_1: "value-1",
            key_2: 2,
            key_3: true,
        }
    }
});
let tweet = prompt("Compose your tweet:");
let tweetCount = tweet.length

alert ("You have written " + tweetCount " characters. You have " + (140 - tweetCount) + " chracters remaining.");
function currentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const format = n => n < 10 ? '0' + n : n;
    return year + '-' + format(month) + '-' + format(day);
}
function rand() {
    return Math.floor(Math.random() * 1_000_000);
}
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
import React, { useState } from 'react';

const UserSelect = () => {
  const [selectedOption, setSelectedOption] = useState(""); // Initialize selectedOption state

  const handleChange = (event) => {
    const selectedValue = event.target.value;
    setSelectedOption(selectedValue); // Update selectedOption state

    // Redirect to appropriate login page based on selected option
    switch(selectedValue) {
      case "admin":
        window.location.href = "/admin-login"; // Replace with the actual URL of your admin login page
        break;
      case "sales-manager":
        window.location.href = "/log-manager"; // Replace with the actual URL of your sales manager login page
        break;
      case "merchants":
        window.location.href = "/log-merchant"; // Replace with the actual URL of your merchant login page
        break;
      default:
        // Code for default option
        break;
    }
  }

  return (
    <div>
      <label htmlFor="users">Users:</label>
      <select name="user" id="users" placeholder="select user" onChange={handleChange}>
        <option value="">Select User</option>
        <option value="admin">Admin</option>
        <option value="sales-manager">Sales Manager</option>
        <option value="merchants">Merchants</option>
      </select>
    </div>
  );
}
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
import { Navbar, Nav, Container, Card, Form, Button } from "react-bootstrap";
const LoginPage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [redirectTo, setRedirectTo] = useState(null);

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleLogin = (event) => {
    event.preventDefault();
    // Implement your login logic here
    // Assume that you get a response object with the user's role as a property
    const response = { role: "admin" }; // replace with your authentication logic
    switch (response.role) {
      case "admin":
        setRedirectTo("/admin");
        break;
      case "manager":
        setRedirectTo("/manager");
        break;
      case "merchant":
        setRedirectTo("/merchants");
        break;
      default:
        console.log("Invalid role");
        break;
    }
  };

  if (redirectTo) {
    return <Navigate to={redirectTo} />;
  }

  return (
    <>
      <Navbar bg="dark" variant="dark" expand="lg">
        <Container>
          <Navbar.Brand>The Merchandisers</Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Nav className="me-auto">
              <Nav.Link>Contact Us</Nav.Link>
            </Nav>
            <Nav>
              <Nav.Link>Logout</Nav.Link>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>

      <Container className="mt-4 d-flex justify-content-center">
        <Card style={{ maxWidth: "500px" }}>
          <Card.Body>
            <h1>Product Smart</h1>
            <Form onSubmit={handleLogin}>
              <Form.Group controlId="formBasicUsername">
                <Form.Label></Form.Label>
                <Form.Control
                  type="text"
                  placeholder="enter username"
                  value={username}
                  onChange={handleUsernameChange}
                />
              </Form.Group>

              <Form.Group controlId="formBasicPassword">
                <Form.Label></Form.Label>
                <Form.Control
                  type="password"
                  placeholder="enter password"
                  value={password}
                  onChange={handlePasswordChange}
                />
              </Form.Group>
              <br />

              <Button variant="primary" type="submit">
                Login
              </Button>
              <br />
            </Form>
          </Card.Body>
        </Card>
      </Container>
      </>
  );
};

export default LoginPage;
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
import { Navbar, Nav, Container, Card, Form, Button } from "react-bootstrap";

const LoginPage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [redirectTo, setRedirectTo] = useState(null);

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleLogin = (event) => {
    event.preventDefault();
    // Implement your login logic here
    // Assume that you get a response object with the user's role as a property
    const response = { role: "admin" }; // replace with your authentication logic
    switch (response.role) {
      case "admin":
        setRedirectTo("/admin");
        break;
      case "manager":
        setRedirectTo("/manager");
        break;
      case "merchants":
        setRedirectTo("/merchants");
        break;
      default:
        console.log("Invalid role");
        break;
    }
  };

  if (redirectTo) {
    return <Navigate to={redirectTo} />;
  }

  return (
    <div>
      <Navbar bg="dark" variant="dark" expand="lg">
        <Container>
          <Navbar.Brand>The Merchandisers</Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Nav className="me-auto">
              <Nav.Link>Contact Us</Nav.Link>
            </Nav>
            <Nav>
              <Nav.Link>Logout</Nav.Link>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>
      {/* login form */}
      <Container className="mt-4 d-flex justify-content-center">
        <Card style={{ maxWidth: "500px" }}>
          <Card.Body>
            <h1>Product Smart</h1>
            <Form onSubmit={handleLogin}>
              <Form.Group controlId="formBasicUsername">
                <Form.Label></Form.Label>
                <Form.Control
                  type="text"
                  placeholder="enter username"
                  value={username}
                  onChange={handleUsernameChange}
                />
              </Form.Group>

              <Form.Group controlId="formBasicPassword">
                <Form.Label></Form.Label>
                <Form.Control
                  type="password"
                  placeholder="enter password"
                  value={password}
                  onChange={handlePasswordChange}
                />
              </Form.Group>
              <br />

              <Button variant="primary" type="submit">
                Login
              </Button>
              <br />
            </Form>
          </Card.Body>
        </Card>
      </Container>
    </div>
  );
};

export default LoginPage;
import 'bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import HomePage from './components/HomePage';
import LoginAdmin from './components/LoginAdmin';
import SignAdmin from './components/SignAdmin';
import LogManager from './components/LogManager';
import LogMerchant from './components/LogMerchant';
import AdminDashboard from './components/AdminDashboard';
import ManagerDashboard from './components/ManagerDashboard';
import MerchantDashboard from './components/MerchantDashboard';
import LogOut from './components/LogOut';
function App() {
  return (
    <Router>
      <div className="App">
        <div className="auth-wrapper">
          <div  className="auth-inner">
            <Routes>
              <Route exact path="/" element={<HomePage />} />
              <Route path="/sign-in" element={<LoginAdmin />} />
              <Route path="/sign-admin" element={<SignAdmin />} />
              <Route path="/dash-admin" element={<AdminDashboard />} />

              <Route path="/log-manager" element={<LogManager />} />
              <Route path="/dash-manager" element={<ManagerDashboard />} />
              <Route path="/log-merchant" element={<LogMerchant />} />
              <Route path="/dash-merchant" element={<MerchantDashboard />} />

              <Route path="/log-out" element={<LogOut />} />

            </Routes>
          </div>
        </div>
      </div>
    </Router>
  );
}

export default App;
//SIGN UP API
router.post('/auth/signup', async (req, res) => {
  try {
    const {
      email, password, firstname, lastname,
    } = req.body;
    if (!email || !password || !firstname || !lastname) {
      res.status(400).end();
    }
    const hashedPassword = await bcrypt.hash(password, 8);
    const userData = {
      email,
      password: hashedPassword,
      firstname,
      lastname,
    };
    const response = await gqlClient.request(CreateNextUserMutation, { userData });
    if (!response?.createNextUser) {
      console.log('CreateUser Failed, Response: ', response);
      res.status(400).end()
    }
    const token = jwt.sign({ user: response.createNextUser }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
    res.send({ user: response.createNextUser, token });
  } catch (err) {
    console.log('POST auth/signup, Something Went Wrong: ', err);
    res.status(400).send({ error: true, message: err.message });
  }
});
import React from 'react';
import { useUser } from '../lib/customHooks';


const Dashboard = () => {
  const { user, authenticated } = useUser();
  if (!user || !authenticated) {
    return <div className="p-16 bg-gray-800 h-screen">
        <div className="text-2xl mb-4 font-bold text-white">Dashboard</div>
        <div className="ml-2 w-8 h-8 border-l-2 rounded-full animate-spin border-white" />
      </div>;
  }


  return (
    <div className="p-16 bg-gray-800 h-screen">
      <div className="text-2xl mb-4 font-bold text-white"> Dashboard </div>
      {
        user &&
        <div className='text-white'>
          <div className="text-lg text-bold mb-2"> User Details </div>
          <div className="flex">
            <div className="w-24 font-medium">
              <div> Email : </div>
              <div> Firstname : </div>
              <div> Lastname : </div>
            </div>
            <div>
              <div> {user.email} </div>
              <div> {user.firstname} </div>
              <div> {user.lastname} </div>
            </div>
          </div>
        </div>
      }
    </div>
  );
}


export default Dashboard;
import React from 'react';
import axios from 'axios';
import { useState } from 'react';
import { API_ROUTES, APP_ROUTES } from '../utils/constants';
import { Link, useNavigate } from 'react-router-dom';
import { useUser } from '../lib/customHooks';
import { storeTokenInLocalStorage } from '../lib/common';


const SignIn = () => {
  const navigate = useNavigate();
  const { user, authenticated } = useUser();
  if (user || authenticated) {
    navigate(APP_ROUTES.DASHBOARD)
  }


  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);


  const signIn = async () => {
    try {
      setIsLoading(true);
      const response = await axios({
        method: 'post',
        url: API_ROUTES.SIGN_IN,
        data: {
          email,
          password
        }
      });
      if (!response?.data?.token) {
        console.log('Something went wrong during signing in: ', response);
        return;
      }
      storeTokenInLocalStorage(response.data.token);
      navigate(APP_ROUTES.DASHBOARD)
    }
    catch (err) {
      console.log('Some error occured during signing in: ', err);
    }
    finally {
      setIsLoading(false);
    }
  };




  return (
    // SIGN IN FORM TEMPLATE
  );
}


export default SignIn;
import React from 'react';
import axios from 'axios';
import { useState } from 'react';
import { API_ROUTES, APP_ROUTES } from '../utils/constants';
import { Link, useNavigate } from 'react-router-dom';


const SignUp = () => {
  const navigate = useNavigate()
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [firstname, setFirstname] = useState('');
  const [lastname, setLastname] = useState('');
  const [isLoading, setIsLoading] = useState(false);




  const signUp = async () => {
    try {
      setIsLoading(true);
      const response = await axios({
        method: 'POST',
        url: API_ROUTES.SIGN_UP,
        data: {
          email,
          password,
          firstname,
          lastname
        }
      });
      if (!response?.data?.token) {
        console.log('Something went wrong during signing up: ', response);
        return;
      }
      navigate(APP_ROUTES.SIGN_IN);
    }
    catch (err) {
      console.log('Some error occured during signing up: ', err);
    }
    finally {
      setIsLoading(false);
    }
  };


  return (
    // SIGN UP FORM TEMPLATE
  );
}


export default SignUp;
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom';
import Dashboard from './components/Dashboard';
import SignIn from './components/SignIn';
import SignUp from './components/SignUp';
import { APP_ROUTES } from './utils/constants';


function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route exact path="/" element={<Navigate to={APP_ROUTES.DASHBOARD} />} />
        <Route path={APP_ROUTES.SIGN_UP} exact element={<SignUp />} />
        <Route path={APP_ROUTES.SIGN_IN} element={<SignIn />} />
        <Route path={APP_ROUTES.DASHBOARD} element={<Dashboard />} />
      </Routes>
    </BrowserRouter>
  );
}


export default App;
import React, { useState } from 'react';
import { Navigate } from 'react-router-dom';
import { Navbar, Nav, Container, Card, Form, Button } from 'react-bootstrap';

const LoginPage = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [redirectTo, setRedirectTo] = useState(null);

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleLogin = (event) => {
    event.preventDefault();
    // Implement your login logic here
    // Assume that you get a response object with the user's role as a property
    const response = { role: 'admin' }; // replace with your authentication logic
    switch (response.role) {
      case 'admin':
        setRedirectTo('/admin');
        break;
      case 'manager':
        setRedirectTo('/manager');
        break;
      case 'manager':
        setRedirectTo('/merchants');
        break;
      default:
        console.log('Invalid role');
        break;
    }
  };

  if (redirectTo) {
    return <Navigate to={redirectTo} />;
  }

  return (
    <div>
      <Navbar bg="dark" variant="dark" expand="lg">
        <Container>
          <Navbar.Brand>The Merchandisers</Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
            <Nav className="me-auto">
              <Nav.Link>Contact Us</Nav.Link>
            </Nav>
            <Nav>
              <Nav.Link>Logout</Nav.Link>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>

      <Container className="mt-4 d-flex justify-content-center">
        <Card style={{ maxWidth: '500px' }}>
          <Card.Body>
            <h1>Product Smart</h1>
            <Form onSubmit={handleLogin}>
              <Form.Group controlId="formBasicUsername">
                <Form.Label></Form.Label>
                <Form.Control type="text" placeholder="Enter username" value={username} onChange={handleUsernameChange} />
              </Form.Group>

              <Form.Group controlId="formBasicPassword">
                <Form.Label></Form.Label>
                <Form.Control type="password" placeholder="Password" value={password} onChange={handlePasswordChange} />
              </Form.Group>
              <br />

              <Button variant="primary" type="submit">Login</Button>
              <br />
            </Form>
          </Card.Body>
        </Card>
      </Container>
    </div>
  );
};

export default LoginPage;
const tempObj = {
    prop1 : "value1",
    prop2 : "value2"
}

//-----Concatinating / Adding New Key Values to Object--------//
Object.assign(tempObj, 
{
    "prop123" : "value123",
    "prop456" : "value456"
},

{
    "prop888" : "value888",
    "prop090" : "value090"
}
)

//--------Cloning an Object---------------//
const clonedObject = Object.assign({}, tempObj)
clonedObject.prop1 = "newProperty"  //it does not affect the original object

console.log(tempObj);
//console.log(clonedObject, tempObj);

//Find more in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
//-----------------------------------------------------------//
const myArray = ['rock', 'paper', 'scissors'];

for(item of myArray){
        const index = myArray.indexOf(item);
        console.log(index)
    
}
const element = document.getElementById('btn');
document.addEventListener('mousedown', (event) => {
  if (!element.contains(event.target)) {
    // do something here
  }
});
{
  "category": "test",
  "routes": ["route1", "route2"]
}
// app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const createLogger = require('./createLogger');
const adminRoutes = require('./adminRoutes');
const useRoutes = require('./useRoutes');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Initialize the logger
const logger = createLogger();

// Add routes for the "admin" category
app.use('/admin/info', adminRoutes.info(logger));
app.use('/admin/warn', adminRoutes.warn(logger));
app.use('/admin/error', adminRoutes.error(logger));

// Add routes for the "use" category
app.use('/use/info', useRoutes.info(logger));
app.use('/use/warn', useRoutes.warn(logger));
app.use('/use/error', useRoutes.error(logger));

// Endpoint for adding a new category and routes dynamically
app.post('/addCategory', (req, res) => {
  const category = req.body.category;
  const routes = req.body.routes;

  // Create a new logger for the category
  const categoryLogger = createLogger(category);

  // Add routes for the category
  for (const route of routes) {
    app.use(`/${category}/${route}/info`, (req, res) => {
      categoryLogger.info({ message: req.query.message });
      res.send('Logged info message');
    });

    app.use(`/${category}/${route}/warn`, (req, res) => {
      categoryLogger.warn({ message: req.query.message });
      res.send('Logged warning message');
    });

    app.use(`/${category}/${route}/error`, (req, res) => {
      categoryLogger.error({ message: req.query.message });
      res.send('Logged error message');
    });
  }

  res.send(`Added category ${category} with routes ${routes.join(', ')}`);
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
const createCategoryLogger = require('./createLogger');

const appLogger = createCategoryLogger('app');
const adminLogger = createCategoryLogger('admin');
const userLogger = createCategoryLogger('user');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, json } = format;

const getLogFileName = (category) => {
  const date = new Date().toISOString().slice(0, 10);
  return `logs/${category}/${category}-${date}.log`;
};

const createCategoryLogger = (category) => {
  return createLogger({
    level: 'info',
    format: combine(timestamp(), json()),
    transports: [
      new transports.File({
        filename: getLogFileName(category),
        level: 'info',
        maxsize: 1024 * 1024 * 10, // 10MB
        maxFiles: 5,
        tailable: true,
      }),
      new transports.Console({
        level: 'debug',
        format: format.combine(format.colorize(), format.simple()),
      }),
    ],
  });
};

module.exports = createCategoryLogger;


const express = require('express');
const router = express.Router();
const userLogger = require('../controllers/userLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  userLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  userLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  userLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const express = require('express');
const router = express.Router();
const adminLogger = require('../controllers/adminLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  adminLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  adminLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  adminLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const express = require('express');
const router = express.Router();
const appLogger = require('../controllers/appLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  appLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  appLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  appLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const userLogRotate = new File({
  filename: path.join(__dirname, `../logs/users_${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const userLogger = createLogger({
  format: combine(
    label({ label: 'User' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    userLogRotate
  ]
});

module.exports = userLogger;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const adminLogRotate = new File({
  filename: path.join(__dirname, `../logs/admins_${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const adminLogger = createLogger({
  format: combine(
    label({ label: 'Admin' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    adminLogRotate
  ]
});

module.exports = adminLogger;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const appLogRotate = new File({
  filename: path.join(__dirname, `../logs/${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const appLogger = createLogger({
  format: combine(
    label({ label: 'App' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    appLogRotate
  ]
});

module.exports = appLogger;
├── controllers
│   ├── appLogger.js
│   ├── adminLogger.js
│   └── userLogger.js
├── logs
│   ├── app-2023-04-20.log
│   ├── admins-2023-04-20.log
│   └── users-2023-04-20.log
├── routes
│   ├── appRoutes.js
│   ├── adminRoutes.js
│   └── userRoutes.js
├── utils
│   └── createLogger.js
└── app.js
const express = require('express');
const { body, sanitizeBody, validationResult } = require('express-validator');

const app = express();

app.use(express.json());

// Define a route handler that uses request validation middleware
app.post('/register',
  body('username').trim().isLength({ min: 3, max: 30 })
    .withMessage('Username must be between 3 and 30 characters long')
    .escape(),
  body('email').trim().isEmail()
    .withMessage('Please enter a valid email address')
    .normalizeEmail(),
  body('password').isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters long')
    .matches(/\d/)
    .withMessage('Password must contain at least one number')
    .customSanitizer((value, { req }) => {
      // Hash the password before storing it in the database
      const hashedPassword = hashPassword(value);
      req.body.password = hashedPassword;
      return hashedPassword;
    }),
  (req, res) => {
    // Check for validation errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }

    // Sanitize input data
    sanitizeBody('username').escape();
    sanitizeBody('email').normalizeEmail();

    // Registration logic here
    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    const message = `Registered user: ${username} (${email}, ${password})`;
    res.send(message);
  });

// Start the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
// controllers/userController.js

const userModel = require('../models/userModel');

// Define route handling functions
function getAllUsers(req, res) {
  const users = userModel.getAllUsers();
  res.json(users);
}

function getUserById(req, res) {
  const id = req.params.id;
  const user = userModel.getUserById(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function createUser(req, res) {
  const newUser = req.body;
  const user = userModel.createUser(newUser);
  res.status(201).json(user);
}

function updateUser(req, res) {
  const id = req.params.id;
  const updatedUser = req.body;
  const user = userModel.updateUser(id, updatedUser);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function deleteUser(req, res) {
  const id = req.params.id;
  const user = userModel.deleteUser(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.send('User deleted successfully');
  }
}

// Export route handling functions
module.exports = {
  getAllUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser
};
// Here's how you can set up logging to a file:
// Install the winston package by running the following command in your terminal:
npm install winston

// Create a logger.js file in your project directory with the following code:
// This creates a logs folder in the same directory as your logger.js module,
// and places the log files inside it. You can adjust the logsDir variable 
// to specify a different directory if desired.

const path = require('path');
const winston = require('winston');
const { createLogger, format, transports } = winston;
const { combine, timestamp, printf } = format;

const logFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} ${level}: ${message}`;
});

const logsDir = path.join(__dirname, 'logs');

const logger = createLogger({
  level: 'info',
  format: combine(
    timestamp(),
    logFormat
  ),
  transports: [
    new transports.Console(),
    new transports.File({
      filename: path.join(logsDir, 'error.log'),
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    }),
    new transports.File({
      filename: path.join(logsDir, 'combined.log'),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      tailable: true
    })
  ]
});

module.exports = logger;


// You can keep environment variables in a file, usually named .env, and load them
// into your Node.js application using a package like dotenv.
// 
// Here are the steps to do so:
// 
// Create a file named .env in the root of your project directory.
// 
// Add your environment variables to the .env file in the following format:

VARIABLE_NAME=variable_value

// For example:
MYSQL_USER=myuser
MYSQL_PASSWORD=mypassword

// Install the dotenv package by running the following command in your terminal:
npm install dotenv

// In your Node.js application, require the dotenv package at the top of your entry file (usually index.js), like this:
require('dotenv').config();

// Access your environment variables in your code using the process.env object. For example:

const mysqlUser = process.env.MYSQL_USER;
const mysqlPassword = process.env.MYSQL_PASSWORD;

// It's important to keep your .env file outside of your version control system,
// as it can contain sensitive information that you don't want to share with others.
// If you're using Git, you can add the .env file to your .gitignore file to
// prevent it from being committed.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config');
const userRouter = require('./routes/user');

const app = express();

// Set up middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Set up routes
app.use('/users', userRouter);

// Start the server
app.listen(config.port, () => {
  console.log(`Server listening on port ${config.port}...`);
});
const express = require('express');
const router = express.Router();
const user = require('../models/user');

// GET all users
router.get('/', async (req, res) => {
  try {
    const userList = await user.getAllUsers();
    res.json(userList);
  } catch (err) {
    console.error(err);
    res.status(500).send('Server error');
  }
});

// POST new user
router.post('/', async (req, res) => {
  try {
    const newUser = req.body;
    await user.addUser(newUser);
    res.status(201).send('User added');
  } catch (err) {
    console.error(err);
    res.status(500).send('Server error');
  }
});

module.exports = router;
const mysql = require('mysql');
const config = require('../config');

// Set up database connection
const connection = mysql.createConnection({
  host: config.mysqlUri,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: config.mysqlDBName,
});

// Connect to database
connection.connect((err) => {
  if (err) {
    console.error(`Error connecting to database: ${err.stack}`);
    return;
  }
  console.log(`Connected to database as id ${connection.threadId}`);
});

module.exports = {
  async getAllUsers() {
    return new Promise((resolve, reject) => {
      connection.query('SELECT * FROM users', (error, results, fields) => {
        if (error) {
          console.error(`Error retrieving users: ${error}`);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },

  async addUser(user) {
    return new Promise((resolve, reject) => {
      connection.query('INSERT INTO users SET ?', user, (error, results, fields) => {
        if (error) {
          console.error(`Error adding user: ${error}`);
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  },
};
module.exports = {
  port: process.env.PORT || 3000,
  mysqlUri: process.env.MYSQL_URI || 'mysql://localhost:3306',
  mysqlDBName: process.env.MYSQL_DB_NAME || 'my_database',
};
├── app.js
├── config/
│   ├── index.js
│   ├── development.js
│   ├── production.js
│   └── test.js
├── controllers/
│   ├── userController.js
│   └── ...
├── models/
│   ├── user.js
│   └── ...
├── routes/
│   ├── userRoutes.js
│   └── ...
├── services/
│   ├── userService.js
│   └── ...
└── utils/
    ├── logger.js
    └── ...
/*
 * Backend tags list have changed add the changes if needed
 */
useEffect(() => {
    setTagsList(setTagsAdded);
}, [setTagsAdded]);

/*
 * Backend files have changed add the changes if needed
 */
useEffect(() => {
    for (let i = 0; i < changedFilesMeta.length; i += 1) {
        // Is the list item value changed
        if (changedFilesMeta[i].id === currentEditableFile.id) {
            unstable_batchedUpdates(() => {
                setTags(changedFilesMeta[i].tags ? changedFilesMeta[i].tags : []);
            });
        }
    }
}, [changedFilesMeta]);

/*
 * Reset when user select new files using the filepicker
 */
useEffect(() => {
    if (setNewFiles.length > 0) {
        unstable_batchedUpdates(() => {
            setCurrentFile(null);
            setDescription('');
            setTitle('');
            setTags([]);
        });
    }
}, [setNewFiles]);

/*
 * User selecet to edit a file, change to that file
 */
useEffect(() => {
    // When user select a file to edit it
    if (currentEditableFile && currentEditableFile !== theCurrentFile) {
        setCurrentFile(currentEditableFile);
        unstable_batchedUpdates(() => {
            setDescription(currentEditableFile.description);
            setTitle(currentEditableFile.title);
            setTags(currentEditableFile.tags);
        });
    }
}, [currentEditableFile]);
function isFreezing(temperature) {
 return temperature < 0;
}
const freezing = isFreezing(-3);
console.log(freezing);
function mix(first, second, third) {
 return first + second + third;
}
const result = mix("big\n", "bad\n", "wolf\n");
console.log(result);
// Get all the reviews on the page
const reviews = document.querySelectorAll('.review');

// Define the keywords to look for and their associated highlight colors
const keywords = {
  'work': 'yellow',
  'experience': 'yellow',
  'unpleasant': 'yellow',
  'felt': 'green'
};

// Loop through each review and highlight the keywords
reviews.forEach((review) => {
  // Get the text content of the review
  const reviewText = review.textContent.toLowerCase();

  // Loop through each keyword and highlight it if it's found in the review
  Object.keys(keywords).forEach((keyword) => {
    if (reviewText.includes(keyword)) {
      const regex = new RegExp(keyword, 'gi');
      const highlightedText = review.innerHTML.replace(regex, `<span style="background-color:${keywords[keyword]}">${keyword}</span>`);
      review.innerHTML = highlightedText;
    }
  });
});
// get all the reviews from the Amazon page
const reviews = document.querySelectorAll('.review');

// define the emotion keywords to search for
const emotions = ['less', 'love', 'success', 'relief'];
const highlightColor = 'yellow';

// loop through each review and search for the emotion keywords
reviews.forEach(review => {
  const reviewText = review.textContent.toLowerCase();
  
  emotions.forEach(emotion => {
    if (reviewText.includes(emotion)) {
      const highlightedText = review.innerHTML.replace(new RegExp(emotion, 'gi'), `<span style="background-color: ${highlightColor}">${emotion}</span>`);
      review.innerHTML = highlightedText;
    }
  });
  
  // search for the word "absolutely" and highlight it in green
  const absolutelyRegex = /\babsolutely\b/gi;
  const absolutelyColor = 'green';
  
  if (absolutelyRegex.test(reviewText)) {
    const highlightedText = review.innerHTML.replace(absolutelyRegex, `<span style="background-color: ${absolutelyColor}">absolutely</span>`);
    review.innerHTML = highlightedText;
  }
});
const emotions = ['love', 'thankful', 'happy', 'relief', 'success'];

function highlightEmotions() {
  const elements = document.getElementsByTagName('*');
  for(let i = 0; i < elements.length; i++) {
    const element = elements[i];
    for(let j = 0; j < element.childNodes.length; j++) {
      const node = element.childNodes[j];
      if(node.nodeType === 3) {
        const text = node.nodeValue;
        const words = text.split(' ');
        for(let k = 0; k < words.length; k++) {
          const word = words[k].toLowerCase();
          if(emotions.includes(word)) {
            const newSpan = document.createElement('span');
            newSpan.style.backgroundColor = 'yellow';
            newSpan.innerText = words[k];
            const parent = node.parentNode;
            parent.replaceChild(newSpan, node);
          }
        }
      }
    }
  }
}

highlightEmotions();
let btns = document.querySelectorAll('button');

btns.forEach(function (i) {
  i.addEventListener('click', function() {
    console.log(i);
  });
});

Code language: JavaScript (javascript)
let btns = document.querySelectorAll('button');

for (i of btns) {
  i.addEventListener('click', function() {
    console.log(this);
  });
}

Code language: JavaScript (javascript)
function uuid_v4() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}
fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))
function updateChat(messages, role, content){
  // tres 4/6 add socket.id for each message
  messages.push({"user": socket.id, "role": role, "content": content});
  return messages; //needed?
}
var messages = [
    {"role": "user", "content": "ask me which option they should take and make two buttons"}
  {"role": "assistant", "content": "which option should they take?  Investigate the mysterious soundsLook for another path through the woods"}];
function fetchStuff(prompt){


  updateChat(messages, "user", prompt);
  
  var to_send = [];
  // tres 4/6 iterate through messages array and only load relevant samples
  foreach (message in messages) {
    if (message["user"] == socket.id || message["user"] == "all") {
      to_send.push(message);
    }
  }
  
  fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer sk-(your key goes here)",
  },

  body: JSON.stringify({
    "model": "gpt-3.5-turbo",
    // tres 4/6 updated to send to_send
    "messages": to_send
  }),

})

  .then((response) => response.json())
  .then((data) => {
    let answer = data.choices[0].message.content;
    updateChat(messages, "assistant",data.choices[0].message.content);
    console.log(answer);
    io.sockets.emit('gpt-response', {
      message: "\n" + answer})
      console.log(messages)
  })
  .catch((error) => console.error(error));

} 
let temperature_data = [
  [60.2, 61.2, 63.4, 64.8, 65.1, 63.2, 62.9],
  [62.5, 63.8, 63.4, 64.6, 65.8, 64.9, 65.0],
  [63.4, 64.5, 65.2, 64.8, 65.1, 64.9, 66.2],
  [66.3, 66.8, 66.4, 66.8, 67.8, 67.9, 68.2]
];
for (i = 0; i < 4; i++) {
  let length = temperature_data[i].length;
  let weeklySum = 0;
  for (j = 0; j < length; j++) {
    weeklySum += temperature_data[i][j];
  }
  console.log("Week " + i + " Average Temperature: " + (weeklySum / 7));
}
let meetingAttendees = ["Diane Moll", "CEO", "Stanley Winstead", "CFO",
  "Herta Pickett", "CFO", "Lynn Hanby", "COO"
];

for (i = 0; i < meetingAttendees.length; i += 2) {
  console.log(meetingAttendees[i]);
}
<div id="header"></div>
<style>
    #header {
    	height: 200px;
        background-image: url('https://i.postimg.cc/BbRm96cn/daniel-mirlea-u5-Qzs-Kvu7-YA-unsplash.jpg');
    }
</style>

<script>
    document.addEventListener('mousemove', function (event) {
      if (window.event) { // IE fix
          event = window.event;
      }
    
      // Grab the mouse's X-position.
      var mousex = event.clientX;
      var mousey = event.clientY;
      var header = document.getElementById('header');
      header.style.backgroundPosition = '-' + mousex/3 + 'px -' + mousey/2 + 'px';
    }, false);
    
</script>
import axios from 'axios'
import fileDownload from 'js-file-download'
export default function App() {
  const handleClick = (url, filename) => {
    axios.get(url, {
      responseType: 'blob',
    })
    .then((res) => {
      fileDownload(res.data, filename)
    })
  }
  return (
    <div className="App">
      <button onClick={() => {() => handleClick('https://avatars.githubusercontent.com/u/9919?s=280&v=4', 'sample')}}>
        Download the File</button>
    </div>
  );
}
const cities = ["Washington", "New York", "Boston"];
const arrivalTimes = ["9:14 PM", "12:27 AM", "2:35 AM"];
for (i = 0; i < cities.length;) {
  console.log(cities[i] + ": " + arrivalTimes[i]);
  i++;
}
try {
  potentialFail();
} catch (error) {
  console.log(error);
}
let first_name = "Doe";
let last_name = "John";

//swap
[first_name, last_name] = [last_name, first_name];

console.log(first_name, last_name);
const users = [
  { name: "user1", age: 28 },
  { name: "user2", age: 21 },
  { name: "user3", age: 38 },
  { name: "user4", age: 18 }
];

users.sort((user1, user2) => user1.age - user2.age);

console.log(users);
const repository = {
  id: 1,
  language: "javascript",
  public: true
};

for (const value of Object.values(repository)) {
  console.log(value);
}
const nestedArray = [1, [2], [[3], 4], 5];

const flatten = nestedArray =>
  nestedArray.reduce(
    (flat, item) => flat.concat(Array.isArray(item) ? flatten(item) : [item]),
    []
  );

flatten(nestedArray);
const friends = [
  { name: "Abby", age: 22 },
  { name: "Boby", age: 16 },
  { name: "Coel", age: 20 },
  { name: "Dany", age: 15 }
];

//who can drink?
friends.filter(friend => friend.age >= 18);
const apps = ["phone", "calculator", "clock"];

apps.length = 0;

console.log(apps);
p::selection {
  color : #000;
  background-color : #2CD9FF;
}
const post = async (url, params) => {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(params),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        }
    })

    const data = await response.json()

    return data
}

// Then use it like so with async/await:
(async () => {
    const data = await post('https://jsonplaceholder.typicode.com/posts', {
        title: 'This will be the title',
        body: 'Setting the body property',
        userId: 1
    })

    console.log(data)
})()

// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
    title: 'This will be the title',
    body: 'Setting the body property',
    userId: 1,
}).then(data => console.log(data))
class Pencil {
  constructor(price) {
    this.price = price;
  }

  isExpensive() {
    return this.price >= 10;
  }
}

//usage
const bic = new Pencil(3);
bic.isExpensive();
const isUnderage = true;
const isDrunk = false;

if (isUnderage || isDrunk) {
  console.log("Cannot drive");
}
const isOverage = false;

if (!isOverage) {
  console.log("You are underage");
}
const isLearning = true;
const isOverwhelmed = true;

if (isLearning && isOverwhelmed) {
  console.log("Take a break");
}
const apps = ["phone", "calculator", "clock"];
const object = { ...apps };

console.log(object);
const apps = ["phone", "calculator", "clock"];

const clonedApps = [...apps];
const elements = ["Eat", "Sleep", "Code", "Repeat"];

elements.join(",");
const defaultOptions = {
  verbose: false,
  src: "./src",
  dist: "./dist"
};
const userOptions = { verbose: true };

const options = { ...defaultOptions, ...userOptions };
const winners = ["Jane", "Bob"];
const losers = ["Ronald", "Kevin"];

const players = [...winners, ...losers];
const person = {
  first_name: "Sam",
  last_name: "Bradley"
};

Object.values(person).includes("Bradley");
const person = {
  first_name: "Joan",
  last_name: "Leon",
  twitter: "@nucliweb"
};

Object.values(person)
  .toString()
  .includes("web");
const apps = ["phone", "calculator", "clock"];

apps.includes("calculator");
const ages = [18, 20, 21, 30];

const agesPlusOne = ages.map(age => age + 1);
const apps = [];

apps.push("calculator");

apps.push("phone", "clock");
const text = "Hello World";

text.toUpperCase();
const person = {
  key: "value",
  first_name: "John",
  last_name: "Doe"
};

Object.keys(person);
	function _initialize() {
		topMenuRender();

		pub.uuid = uuid();
		pub.id = 'mod-ocenuvac_prijava-'+pub.uuid;
		pub.idp = pub.id+'-';
		pub.dict = Dictionary;

		//--- URL variables ------------------------
		let _urlVars = nzObject(getUrlVars());
		pub.mode = _urlVars.mode;	// odobruvanje-kandidati|aktiviranje-ocenuvac

		_modules_render();

		$.busyLoadFull('hide');
	}
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import BleManager from 'react-native-ble-manager';

const App = () => {
  const [devices, setDevices] = useState([]);
  const [connectedDevice, setConnectedDevice] = useState(null);
  const [deviceData, setDeviceData] = useState(null);

  useEffect(() => {
    BleManager.start({ showAlert: false });
    BleManager.enableBluetooth();
  }, []);

  const scanDevices = () => {
    BleManager.scan([], 5, true)
      .then((results) => {
        setDevices(results);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const connectDevice = (device) => {
    BleManager.connect(device.id)
      .then(() => {
        setConnectedDevice(device);
        BleManager.startNotification(
          device.id,
          'serviceUUID',
          'characteristicUUID'
        ).then(() => {
          console.log('Notification started');
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const disconnectDevice = () => {
    BleManager.disconnect(connectedDevice.id)
      .then(() => {
        setConnectedDevice(null);
        setDeviceData(null);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const readDeviceData = () => {
    BleManager.read(
      connectedDevice.id,
      'serviceUUID',
      'characteristicUUID'
    )
      .then((data) => {
        setDeviceData(data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Bluetooth Medical Devices Manager</Text>
      {connectedDevice ? (
        <View style={styles.connectedDevice}>
          <Text style={styles.deviceName}>{connectedDevice.name}</Text>
          <Button
            title="Disconnect"
            onPress={() => disconnectDevice()}
          />
          <Button title="Read Data" onPress={() => readDeviceData()} />
          {deviceData ? (
            <Text style={styles.deviceData}>{deviceData}</Text>
          ) : null}
        </View>
      ) : (
        <View style={styles.deviceList}>
          <Text style={styles.subtitle}>Available Devices:</Text>
          {devices.map((device) => (
            <View style={styles.deviceItem} key={device.id}>
              <Text>{device.name}</Text>
              <Button
                title="Connect"
                onPress={() => connectDevice(device)}
              />
            </View>
          ))}
          <Button title="Scan" onPress={() => scanDevices()} />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  subtitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  connectedDevice: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  deviceName: {
    fontSize: 18,
    fontWeight: '
function showToast(message, duration) {
  // Create a new div element for the toast message
  const toast = document.createElement('div');
  toast.classList.add('toast');

  // Add the message content to the toast
  toast.innerHTML = message;

  // Add the toast to the container element
  const container = document.getElementById('toast-container');
  container.appendChild(toast);

  // Use a timer to remove the toast after the specified duration
  setTimeout(() => {
    container.removeChild(toast);
  }, duration);
}
import { Swiper, SwiperSlide } from "swiper/react";
import 'swiper/swiper-bundle.min.css'
import 'swiper/swiper.min.css'

<Swiper
      spaceBetween={50}
      slidesPerView={3}
      centeredSlides
      onSlideChange={() => console.log("slide change")}
      onSwiper={swiper => console.log(swiper)}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
    </Swiper>
<div class="eddy-new-three-banners">
    <div class="new-three-banners">
        <div class="eddy-big-banner">
            <div class="three-banner-content">
                <h3>20-30% Discount</h3>
                <p> Get the latest products of this category</p>
            </div>
                <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-LAP-DESK-EN.jpg}}"></a>
        </div>
        <div class="eddy-new-three-two-banners">
            <div class="two-banners-container">
                <div class="three-banner-content">
                    <h3>20-30% Discount</h3>
                    <p> Get the latest products of this category</p>
                </div>
                        <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-MON-DESK-EN.jpg}}"></a>
            </div>
            <div class="two-banners-container">
                <div class="three-banner-content">
                    <h3>20-30% Discount</h3>
                    <p> Get the latest products of this category</p>
                </div>
                        <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-TV-DESK-EN.jpg}}"></a> 
            </div>
        </div>
    </div>
</div>
<!-- End Of Three Banners -->

<div class="eddy-weekend-deals">
    <div class="weekend-deals-titles">
        <div class="Weekend-Deals">
            <h2>Weekend Deals</h2>
        </div>
<!--        <div class="weekend-deals-countdown-timer">-->
<!--            <p>End After - <span id="weekend-countdown"></span></p>-->
<!--        </div>-->
        <div class="weekend-deals-view-all">
            <a href="#">View All</a>
        </div>
    </div>
<div class="container">
    {{widget type="Magiccart\Magicproduct\Block\Widget\Product" identifier="cms-static-fearured-products" template="product.phtml"}}
</div>
</div>

<!-- End of WeekEnd Deals -->

<div class="deals-you-dont-want-to-miss-en">
    <div class="deals-you-dont-want-to-miss-titles">
        <div class="deals-you-dont-want-to-miss-heading">
            <h2>Deals You Don't Want To Miss</h2>
        </div>
        <div class="deals-you-dont-want-to-miss-view-all">
            <a href="#">View All</a>
        </div>
    </div>
    <div class="deals-miss-first-row">
        <div class="deals-miss-first-item">
            <a href="#"><img src="{{media url=wysiwyg/blocks/deals-dont-miss/ADS-CM-DESK-EN.jpg}}"></a>
        </div>
        <div class="deals-miss-first-item">
            <a href="#"><img src="{{media url=wysiwyg/blocks/deals-dont-miss/ADS-COOK-DESK-EN.jpg}}"></a>
        </div>
        <div class="deals-miss-first-item">
            <a href="#"><img src="{{media url=wysiwyg/blocks/deals-dont-miss/ADS-CS-DESK-EN.jpg}}"></a>
        </div>
    </div>
    <div class="deals-miss-last-items first-banner">
        <a href="#"><img src="{{media url=wysiwyg/blocks/deals-dont-miss/ADS-BED-DESK-EN.jpg}}"></a>
    </div>
    <div class="deals-miss-last-items last-banner">
        <a href="#"><img src="{{media url=wysiwyg/blocks/deals-dont-miss/ADS-DIN-DESK-EN.jpg}}"></a>
    </div>
</div>

<!-- End of Deals you don't want to miss -->

<div class="eddy-catalog-widget-banners">
    <div class="eddy-widget-category">
        <div class="eddy-cat-ban selected" data-widget=".first-widget">Air Conditioner</div>
        <div class="eddy-cat-ban" data-widget=".second-widget">Vacuums</div>
        <div class="eddy-cat-ban" data-widget=".third-widget">Pressure Washers</div>
        <div class="eddy-cat-ban" data-widget=".forth-widget">Drills</div>
        <div class="eddy-cat-ban" data-widget=".fifth-widget">Indoor Camera's</div>
    </div>

    <div class="eddy-widget-blocks">
        <div class="first-widget catalog-banners active">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-46.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-48.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>

        </div>
        <div class="second-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-54.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-55.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-56.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>

        </div>
        <div class="third-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-1.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-2.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-3.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
        </div>
        <div class="forth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-50.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-51.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-52.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
        </div>
        <div class="fifth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-58.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-59.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-60.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
        </div>
    </div>
</div>

<!-- End of First Catalog widget banner block -->

<div class="container">
    {{widget type="Magiccart\Magicproduct\Block\Widget\Product" identifier="cms-static-fearured-products" template="product.phtml"}}
</div>

<!-- End of product slider -->

<div class="eddy-your-own-comfort-zone">
    <div class="eddy-zones eddy-comfort-zone-first-items">
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small2.jpg}}"></a>
        </div>
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small1.jpg}}"></a>
        </div>
    </div>
    <div class="eddy-zones eddy-comfort-zone-second-items">
        <div class="eddy-comfort-zone-image-increase">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-big1.jpg}}"></a>
        </div>
    </div>
    <div class="eddy-zones eddy-comfort-zone-third-items">
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small3.jpg}}"></a>
        </div>
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small4.jpg}}"></a>
        </div>
    </div>
</div>


<!-- End of comfort zone block -->


<div class="eddy-catalog-widget-banners">
    <div class="eddy-widget-category">
        <div class="eddy-cat-ban selected" data-widget=".first-widget">Air Conditioner</div>
        <div class="eddy-cat-ban" data-widget=".second-widget">Vacuums</div>
        <div class="eddy-cat-ban" data-widget=".third-widget">Pressure Washers</div>
        <div class="eddy-cat-ban" data-widget=".forth-widget">Drills</div>
        <div class="eddy-cat-ban" data-widget=".fifth-widget">Indoor Camera's</div>
    </div>

    <div class="eddy-widget-blocks">
        <div class="first-widget catalog-banners active">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-46.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-48.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>

        </div>
        <div class="second-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-54.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-55.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-56.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>

        </div>
        <div class="third-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-1.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-2.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-3.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
        </div>
        <div class="forth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-50.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-51.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-52.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
        </div>
        <div class="fifth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-58.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-59.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-60.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
        </div>
    </div>
</div>

<!-- End of Second Catalog widget banner block -->


<div class="eddy-shop-laptops">
    <div class="shop-laptop">
        <div class="lap-content">
            <h3>IT Technologies for start</h3>
            <h3>Check limited in Opportunities</h3>
            <button class="btn btn-primary">Shop Laptop</button>
        </div>
    </div>
    <div class="shop-all-laptops">
        <div class="shop-all-laptop-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-laptops/COMP-BANNERS-EN-small1.jpg}}"></a>
        </div>
        <div class="shop-all-laptop-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-laptops/COMP-BANNERS-EN-small2.jpg}}"></a>
        </div>
        <div class="shop-all-laptop-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-laptops/COMP-BANNERS-EN-small3.jpg}}"></a>
        </div>
        <div class="shop-all-laptop-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-laptops/COMP-BANNERS-EN-small4.jpg}}"></a>
        </div>
    </div>
</div>

<!-- End of Eddy Shop Laptops -->

<div class="eddy-catalog-widget-banners">
    <div class="eddy-widget-category">
        <div class="eddy-cat-ban selected" data-widget=".first-widget">Air Conditioner</div>
        <div class="eddy-cat-ban" data-widget=".second-widget">Vacuums</div>
        <div class="eddy-cat-ban" data-widget=".third-widget">Pressure Washers</div>
        <div class="eddy-cat-ban" data-widget=".forth-widget">Drills</div>
        <div class="eddy-cat-ban" data-widget=".fifth-widget">Indoor Camera's</div>
    </div>

    <div class="eddy-widget-blocks">
        <div class="first-widget catalog-banners active">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-46.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-48.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-49.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/CE-320x320-47.jpg}}"/></a>

        </div>
        <div class="second-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-54.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-55.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-56.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Compu-320x320-57.jpg}}"/></a>

        </div>
        <div class="third-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-1.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-2.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-3.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/Fur-320x320-4.jpg}}"/></a>
        </div>
        <div class="forth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-50.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-51.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-52.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/HA-320x320-53.jpg}}"/></a>
        </div>
        <div class="fifth-widget catalog-banners">
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-58.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-59.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-60.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
            <a href="#"><img src="{{media url=wysiwyg/blocks/eddy-catalog-widget-banners/first/SDA-320x320-61.jpg}}"/></a>
        </div>
    </div>
</div>

<!-- End of Third catalog banner widget -->

<div class="eddy-shop-microwaves">
    <div class="shop-all-microwaves">
        <div class="shop-all-microwaves-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-microwaves/SDA-BANNERS-EN-small1.jpg}}"></a>
        </div>
        <div class="shop-all-microwaves-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-microwaves/SDA-BANNERS-EN-small2.jpg}}"></a>
        </div>
        <div class="shop-all-microwaves-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-microwaves/SDA-BANNERS-EN-small3.jpg}}"></a>
        </div>
        <div class="shop-all-microwaves-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/shop-microwaves/SDA-BANNERS-EN-small4.jpg}}"></a>
        </div>
    </div>
    <div class="shop-microwaves">
              <div class="microwaves-content">
        <a href="#"><img src="{{media url=wysiwyg/blocks/shop-microwaves/SDA-BANNERS-EN-big.jpg}}"></a>
                </div>
    </div>
</div>


<!-- End of Shop microwaves -->


<div class="eddy-bottom-banner">
    <div class="eddy-first-bottom-banner">
        <a href="#">
            <img src="{{media url=wysiwyg/alothemes/static/banner-menu-bottom_1.jpg}}" alt="" />
        </a>
    </div>
    <div class="eddy-second-bottom-banner">
        <a href="#">
            <img src="{{media url=wysiwyg/alothemes/static/banner-menu-bottom.jpg}}" alt="" />
        </a>
    </div>
</div>  
        

<!-- End of bottom banner -->

<div class="eddy-new-three-banners">
    <div class="new-three-banners">
        <div class="eddy-big-banner">
            <div class="three-banner-content">
                <h3>20-30% Discount</h3>
                <p> Get the latest products of this category</p>
            </div>
                <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-LAP-DESK-EN.jpg}}"></a>
        </div>
        <div class="eddy-new-three-two-banners">
            <div class="two-banners-container">
                <div class="three-banner-content">
                    <h3>20-30% Discount</h3>
                    <p> Get the latest products of this category</p>
                </div>
                        <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-MON-DESK-EN.jpg}}"></a>
            </div>
            <div class="two-banners-container">
                <div class="three-banner-content">
                    <h3>20-30% Discount</h3>
                    <p> Get the latest products of this category</p>
                </div>
                        <a href=""><img src="{{media url=wysiwyg/blocks/Three-banners/en/ADS-TV-DESK-EN.jpg}}"></a> 
            </div>
        </div>
    </div>
</div>

<!-- End of Eddy Three banners -->

<div class="eddy-your-own-comfort-zone">
    <div class="eddy-zones eddy-comfort-zone-first-items">
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small2.jpg}}"></a>
        </div>
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small1.jpg}}"></a>
        </div>
    </div>
    <div class="eddy-zones eddy-comfort-zone-second-items">
        <div class="eddy-comfort-zone-image-increase">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-big1.jpg}}"></a>
        </div>
    </div>
    <div class="eddy-zones eddy-comfort-zone-third-items">
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small3.jpg}}"></a>
        </div>
        <div class="eddy-comfort-zone-image">
            <a href="#"><img src="{{media url=wysiwyg/blocks/comfort-zone/FUR-BANNERS-EN-small4.jpg}}"></a>
        </div>
    </div>
</div>


<!-- End of eddyـyourـownـcomfortـzoneـen -->

<div class="eddy-get-ready">
    <div class="dining-furniture">
        <div class="dining-furniture-content">
            <h3>Get Ready To</h3>
            <h3>Host in Style</h3>
            <p>Dining set furniture</p>
            <button class="btn btn-primary">Shop Now</button>
        </div>
    </div>
    <div class="dining-tables">
        <div class="dining-table-banner">
            <a href="#"><img src="{{media url=wysiwyg/blocks/get-ready/ADS-DIN-DESK-EN.jpg}}"></a>
        </div>
    </div>
</div>

<!-- End of eddy-get-ready-en -->
let highestMark  = marks.reduce((a, b) => a.mark > b.mark ? a : b)
console.log(highestMark);
import "./App.css";

import { useState, useRef, useEffect } from "react";

function App() {
  const [isIntersecting, setIsIntersecting] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsIntersecting(entry.isIntersecting);
      },
      { rootMargin: "-300px" }
    );
    console.log(isIntersecting);
    observer.observe(ref.current);

    return () => observer.disconnect();
  }, [isIntersecting]);

  useEffect(() => {
    if (isIntersecting) {
      ref.current.querySelectorAll("div").forEach((el) => {
        el.classList.add("slide-in");
      });
    } else {
      ref.current.querySelectorAll("div").forEach((el) => {
        el.classList.remove("slide-in");
      });
    }
  }, [isIntersecting]);

  return (
    <div className="App">
      <header>This is the Header</header>
      <main ref={ref}>
        <div className="child-one">Child One</div>
        <div className="child-two">Child Two</div>
      </main>
      <footer>This is the Footer</footer>
    </div>
  );
}

export default App;
const express = require("express");

const socket = require("socket.io");

// App setup

const app = express();

const server = app.listen(5000, function () {

  console.log(`server running!`);

});

// Static files

app.use(express.static("public"));

// Socket setup

const io = socket(server);

io.on("connection", function (socket) {

  console.log("socket connection on");

});
let marks = [
    {
        name: 'student1',
        mark: 78
    },{
        name: 'student2',
        mark: 90
    },{
        name: 'student3',
        mark: 69
    },{
        name: 'student4',
        mark: 96
    },{
        name: 'student5',
        mark: 64
    }
]
export const copyToClipboard = (content) => {
  const el = document.createElement("textarea");
  el.value = content;
  document.body.appendChild(el);
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
}
function duplicateCount(text){
  //...
  const lowercase = text.toLowerCase()
  const arr = lowercase.split('')
  arr.sort()
  let answer = 0
  for (i=0; i<arr.length; i++) {
    if (arr[i]===arr[i+1]){
      const letter =arr[i] 
      while (arr[i+1] === letter) {
       i++
     } answer ++
    }
  }
  return answer
}
function rot13(message){
  //your code here
  const lowercase= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
  const uppercase= ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
  
  const answer = []
  
for (i=0; i<message.length; i++) {
  
  let arr 
  
  if (message[i]===message[i].toLowerCase()) {
    arr=lowercase
  } else { arr=uppercase }
  let pos = arr.indexOf(message[i])
  if (pos=== -1) {
    answer.push(message[i])
    continue
  }
  pos += 13
  pos = pos % 26
  answer.push(arr[pos])
}
  
  return answer.join('')
}
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
var box = document.createElement("div");
box.className = "ads AdSense adpopup adszone adslot AD300";
box.style.height = "1px";

var observer = new MutationObserver(function () {
  if (document.body.contains(box)) {
    console.log("It's in the DOM!");
    observer.disconnect();
    setTimeout(function () {
      var hasAdblocker = !box.offsetHeight;
      console.log({ hasAdblocker });
    }, 0);
  }
});

observer.observe(document.body, {
  attributes: false,
  childList: true,
  characterData: false,
  subtree: true,
});

document.body.appendChild(box);
https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js
<Stack direction="row" spacing={2}>
</Stack>
const firstValue = 10;
const secondValue = "10";
console.log(firstValue == secondValue);
// output : true 

console.log(firstValue === secondvalue);
// output : false
//USe.jsx file , this file export to App.jsx and run this file

import React,{useState} from 'react';


const use=()=>{
  const[store_age,update_age]=useState(19);
  const handle=()=>{
    update_age(store_age+2);
    
  }

  return(
    <div className="main">
  <h1>toadya ia am {store_age} old</h1>
  <button onClick={handle} > get oldder </button>

    </div>
  )
}
export default use;
const MultipleStateVars = () => {
  const [age, setAge] = useState(19)
  const [siblingsNum, setSiblingsNum] = 
    useState(10)

  const handleAge = () => setAge(age + 1)
  const handleSiblingsNum = () => 
      setSiblingsNum(siblingsNum + 1)
 

  return (
    <div>
      <p>Today I am {age} Years of Age</p>
      <p>I have {siblingsNum} siblings</p>

      <div>
        <button onClick={handleAge}>
          Get older! 
        </button>
        <button onClick={handleSiblingsNum}>
            More siblings! 
        </button>
      </div>
    </div>
  )
}
let results = await OrderModel.find().populate(['user', 'meal']);
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

echo "IP address: $ip<br>";
echo "User agent: $user_agent<br>";
echo "Referrer: $referer<br>";
echo "Preferred language(s): $language<br>";
?>
Hi was looking for same as complete log of request and response as middleware in express js. Found the solution as well w

    /*Added by vikram parihar for log  */
const moment = require('moment');
const rfs = require("rotating-file-stream");
const geoip = require('geoip-lite');
const { PassThrough } = require('stream')
let path = require('path');

const accessLogStream = rfs.createStream('access.log', {
    interval: '1M', // rotate daily
    compress: true,
    path: path.join(__dirname, '../../log')
});

module.exports = function (req, res, next) {
    try {
        let geo = geoip.lookup(req.ip);
        let country = geo ? geo.country : "Unknown";
        let region = geo ? geo.region : "Unknown";
        let log = {
            "time": moment().format('YYYY/MM/DD HH:mm:ss'),
            "host": req.hostname,
            "ip": req.ip,
            "originalUrl": req.originalUrl,
            "geo": {
                "browser": req.headers["user-agent"],
                "Language": req.headers["accept-language"],
                "Country": country,
                "Region": region,
            },
            "method": req.method,
            "path": req.path,
            "url": req.url,
            "body": req.body,
            "params": req.params,
            "query": req.query,
            "response": {
                "body": res.body
            }
        };
        const defaultWrite = res.write.bind(res);
        const defaultEnd = res.end.bind(res);
        const ps = new PassThrough();
        const chunks = [];

        ps.on('data', data => chunks.push(data));

        res.write = (...args) => {
            ps.write(...args);
            defaultWrite(...args);
        }

        res.end = (...args) => {
            ps.end(...args);
            defaultEnd(...args);
        }
        res.on('finish', () => {
            log.response.body = Buffer.concat(chunks).toString()
            accessLogStream.write(JSON.stringify(log) + "\n");
        })
    } catch (error) {
        console.log(error)
        next(error)
    }
    next();
}
import React from "https://esm.sh/react@18.2.0"
import ReactDom from "https://esm.sh/react-dom@18.2.0/client"
import moment from 'moment';

const expiryDate = '03-21-2023';
const currentDate = moment();

// Parse the expiry date using Moment.js
const parsedExpiryDate = moment(expiryDate, 'MM-DD-YYYY');

// Compare the expiry date to the current date to check if the token is expired
if (parsedExpiryDate.isBefore(currentDate)) {
  console.log('Token has expired!');
} else {
  console.log('Token is still valid');
}
function past(h, m, s){
  return s*1000 + m*60000 + h*3600000
}
function paperwork(n, m) {
  if (n < 0  || m < 0) {
return 0
  } else {
    return n * m 
  }
}
import './ExpenseItem.css'
export default function ExpenseItem(){
    const expenseDate=new Date(2021,2,8)
    const expenseTitle='Car Insurance'
    const expenseAmount=123.354
    let arr=[2,3,4]
    console.log(typeof expenseDate)
   
    console.log(typeof arr)
    return(
        <div className='expense-item '>
            <div>
                {expenseDate.toISOString()}
            </div>
            <div className='expense-item__description'>
                <h2>
                 {arr}
                </h2>
            <div className='expense-item__price'>
            ${expenseAmount}
        </div>
        </div>
        </div>
    );
}
var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});
npm i eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-node eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react --save-dev



aseve gvinda faili

.eslintrc.json   da shig


{
  "extends": ["airbnb", "prettier", "plugin:node/recommended"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "spaced-comment": "off",
    "no-console": "warn",
    "consistent-return": "off",
    "func-names": "off",
    "object-shorthand": "off",
    "no-process-exit": "off",
    "no-param-reassign": "off",
    "no-return-await": "off",
    "no-underscore-dangle": "off",
    "class-methods-use-this": "off",
    "prefer-destructuring": ["error", { "object": true, "array": false }],
    "no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }]
  }
}


// これまでの関数
var printName = function() {
    document.write(this + "<br>");
    document.write(this.myName + "<br>");
};
var human = {
    myName: "yuu",
    print: printName
}
human.print();
 
// アロー関数
var printNameArrow = () => {
    document.write(this + "<br>");
    document.write(this.myName + "<br>");
};
var humanArrow = {
    myName: "mamoru",
    print: printNameArrow
}
humanArrow.print();
// これまでの関数
var fnc = function(a, b) {
    return a + b;
};
document.write(fnc(2, 3) + "<br>");
 
// アロー関数1
var arrow1 = (a, b) => {
    return a + b;
};
document.write(arrow1(3, 4) + "<br>");
 
// アロー関数2(処理がreturnだけなら、省略可能)
var arrow2 = (a, b) => a + b;
document.write(arrow2(4, 5) + "<br>");
app.route('/api/v1/tours').get(rame migebis).post(rame migebisfunc)
import { useRecoilValue } from "recoil";
import { TodoItemCreator } from "./TodoItemCreator";
import { TodoItem } from "./TodoItem";
import { todoListAtom } from "../recoil/atoms/todoAtom";
import "./todo.css";

export const TodoMain = () => {
  const todoList = useRecoilValue(todoListAtom);

  return (
    <div className="parent-container">
      <div>
        <TodoItemCreator />
        {todoList.length > 0 && (
          <div className="todos-list">
            {todoList.map((todoItem) => (
              <TodoItem key={todoItem.id} item={todoItem} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};


import { atom } from "recoil";

export const todoListAtom = atom({
  key: "todoListState",
  default: [],
});
function all_max(...array ) // Put it first index of  in new Array 
{
   console.log(array)
}
function koko(array)//extract elements  of array 
{ 
  console.log(...array)
}
function arr(array)
{
  console.log(array)
}
function arr2(...array)
{
  console.log(...array)
}
all_max([20, 30, 40])
koko([20, 30, 40])
arr([20, 30, 40])
arr2([20, 30, 40])
const buttonA = document.querySelector('#button_A');
const headingA = document.querySelector('#heading_A');

buttonA.onclick = () => {
  const name = prompt('What is your name?');
  alert(`Hello ${name}, nice to see you!`);
  headingA.textContent = `Welcome ${name}`;
}
let sum = 44;
console.log(sum);   // 44
let arr = [3, 4, 5, 6];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-items: center;
            align-items: center;
            background-color: aqua;
            justify-content: center;
            /* text-align: center; */
            height: 100vh;
            background: url(https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1748&q=80);
            background-position: center;
            background-size: cover;
        
        }
        
        h1 {
            text-align: center;
        }
        
        #form {
            background-color: #c7ab9d;
            border: 2px solid rgb(4, 0, 255);
            border-radius: 10px;
            width: 400px;
            height: 300px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
        
        }
        
        
        
        h2 {
            font-size: 30px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 5px;
        }
        
        input {
            height: 30px;
            width: 250px;
            border-radius: 5px;
            padding: 10px;
            margin: 5px;
            /* padding: 10px; */
        }
        
        input[type='submit'] {
            background-color: purple;
            text-align: center;
            align-content: center;
            color: white;
            height: 50px;
            font-size: 30px;
            width: 200px;
            padding-bottom: 20px;
            border: 0px;
        }
        
        .error {
            margin: 10px;
            color: blue;
        }
    </style>
</head>

<body>
    <h1>Form Validation</h1>
    <div id="form">
        <h2>Login Form</h2>
        <form action="" onsubmit="return validateform()">
            <input type="text" class="form" name="" id="username" placeholder="Enter Username">
            <br>
            <span id="usererror" class="error"></span>
            <br>
            <input type="password" class="form" id="password" placeholder="Enter Password">
            <br>
            <span class="error" id="passerror"></span>
            <br>
            <!-- <input type="submit" value="Pls Submit"> -->
            <button type="submit">Pls Submit</button>
        </form>
    </div>
    <script>
        let user = document.getElementById('username');
        let pass = document.getElementById('password');
        let condition1 = 0;
        let condition2 = 0;
        
        flag
        function validateform() {
        
            if (user.value == '') {
                document.getElementById('usererror').innerHTML = "User Name Blank";
                condition1 = 0;
            } else if (user.value.length < 5) {
                document.getElementById('usererror').innerHTML = "Pls Enter more than 4 Charactre"
                condition1 = 0;
        
            } else {
                document.getElementById('usererror').innerHTML = ""
                document.getElementById('usererror').style.color = "Green";
                condition1 = 1;
        
            }
            if (pass.value == '') {
                document.getElementById('passerror').innerHTML = "Password Cannot Blank";
                condition2 = 0;
        
            }
            else if (pass.value.length < 5) {
                document.getElementById('passerror').innerHTML = "Pls Enter more than 4 Charactre";
                condition2 = 0;
        
            } else {
                document.getElementById('passerror').innerHTML = "";
                document.getElementById('passerror').style.color = "Green";
                condition2 = 1;
        
            }
            if (condition1 == 1 & condition2 == 1) {
                return true;
            } else {
                return false;
            }
        }
        
    </script>
</body>

</html>
Flex-direction:  Column,  row, reverse, - მიმართულება მაღლა დაბლა.
flex-wrap:  wrap, no-wrap, wrap-reverse,   - გადასვლა შემდეგ ხაზზე თუარა. 
flex-flow: column-reverse wrap-reverse;  - ზედა ორის მიქსი. 


The frogs are spread all over the pond, but the lilypads are bunched at the top. You can use align-content to set how multiple lines are spaced apart from each other. This property takes the following values:

flex-start: Lines are packed at the top of the container.
flex-end: Lines are packed at the bottom of the container.
center: Lines are packed at the vertical center of the container.
space-between: Lines display with equal spacing between them.
space-around: Lines display with equal spacing around them.
stretch: Lines are stretched to fit the container.
This can be confusing, but align-content determines the spacing between lines, while align-items determines how the items as a whole are aligned within the container. When there is only one line, align-content has no effect.
function h(html) { return html.replace(/<p>/g, '\n\n').replace(/<\/p>/g, '').replace(/<b>/g, '**').replace(/<\/b>/g, '**').replace(/<i>/g, '_').replace(/<\/i>/g, '_').replace(/<code[^>]*>/g, (match) => { const lm = match.match(/class="[^"]*language-([^"]*)"/); return lm ? '\n```' + lm[1] + '\n' : '```'; }).replace(/<\/code[^>]*>/g, '```').replace(/<[^>]*>/g, '').replace(/Copy code/g, '').replace(/This content may violate our content policy. If you believe this to be in error, please submit your feedback — your input will aid our research in this area./g, '').trim(); } (()=>{ const e=document.querySelectorAll(".text-base");let t="";for(const s of e)s.querySelector(".whitespace-pre-wrap")&&(t+=`**${s.querySelector('img')?'You':'ChatGPT'}**: ${h(s.querySelector(".whitespace-pre-wrap").innerHTML)}\n\n`);const o=document.createElement("a");o.download="Conversation with ChatGPT.md",o.href=URL.createObjectURL(new Blob([t])),o.style.display="none",document.body.appendChild(o),o.click()})();
export const data = [
    {
        id : 1,
        title: "Equifax UK brings agility and resilience with Google Cloud",
        date: "Case Studies | 24 Jun 2022",
        imgUrl: "https://www.tcs.com/content/dam/global-tcs/en/images/what-we-do/products-platforms/products/tcschroma/AdobeStock_423856912.jpeg/jcr:content/renditions/cq5dam.thumbnail.1280.765.png",
        cardUrl: "https://www.tcs.com/what-we-do/industries/communications-media-information-services/case-study/equifax-cloud-transformation-migration"
    },
    {
        id: 2,
        title: "Maersk partners with TCS for end-to-end IoT-based reefer monitoring solution",
        date: "Case Studies | 29 Jul 2022",
        imgUrl: "https://www.tcs.com/content/dam/global-tcs/en/images/what-we-do/services/iot-and-digital-engineering/next-gen-field-services/AdobeStock_318963598-Web-3840x1512.jpg/jcr:content/renditions/cq5dam.thumbnail.1280.765.png",
        cardUrl: "https://www.tcs.com/what-we-do/industries/travel-and-logistics/case-study/maersk-cloud-iot-platform-automate-reefer-monitoring-system"
    },
    {
        id: 3,
        title: "Morrisons Partners with TCS to Transform HR Operations and EX",
        date: "Case Studies | 30 Nov 2022",
        imgUrl: "https://www.tcs.com/content/dam/global-tcs/en/images/who-we-are/iron-mountain-Web-3840x1512.jpg/jcr:content/renditions/cq5dam.thumbnail.1280.765.png",
        cardUrl: "https://www.tcs.com/what-we-do/services/cognitive-business-operations/case-study/morrisons-supermarkets-hr-operations-employee-experience"
    },
    {
        id: 4,
        title: "Strengthening Cybersecurity with TCS’ Managed Security Services",
        date: "Case Studies | 16 Dec 2022",
        imgUrl: "https://www.tcs.com/content/dam/global-tcs/en/images/insights/blogs/women-workforce-cybersecurity-tcs-careers.jpg/jcr:content/renditions/cq5dam.thumbnail.1280.765.png",
        cardUrl: "https://www.tcs.com/what-we-do/services/cybersecurity/case-study/strengthening-cybersecurity-with-tcs-managed-security-services"
    }, 
]
import React from 'react'
import './App.css';
import { data } from './beliefdata'

export default function Belief() {

  const cardData = data.map(item => {
    return (
      <a key={item.id} className="beliefCard" href={item.cardUrl} target="_blank">
        <img src={item.imgUrl} alt='beliefCard' />
        <h1>{item.title}</h1>
        <p>{item.date}</p>
      </a>
    )
  })

  return (
    <div className='container1'>
      <div className='insightsTitle'>
        <h1>Belief in action</h1>
      </div>

      <div className="beliefCardsContainer">
        {cardData}
      </div>
    </div>
  )
}
$("#uiLocation").find('thead').prepend(`
      <tr> +
        <th class="t-Report-colHead" align="center" colspan="1"></th> +
        <th class="t-Report-colHead" align="center" colspan="2">Running Totals</th> +
        <th class="t-Report-colHead" align="center" colspan="2">End of Last Period</th> +
        <th class="t-Report-colHead" align="center" colspan="2">Stock Count
      </tr>`
    );
function longest(s1, s2) {
  const totalString = (s1+s2).split('').sort()
  for (let i=0; i < totalString.length; i++) {
    while(totalString[i] === totalString[i+1]) totalString.splice(i+1, 1)
  }
    return totalString.join('')
}
function countSheeps(arrayOfSheep) {
  let count = 0
  for (const sheep of arrayOfSheep)
    if (sheep === true) {
      count++
    }
  
  return count
}

function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(sheep => sheep).length
}

function countSheeps(arrayOfSheep) {
  //return arrayOfSheep.filter(sheep => sheep).length
  return arrayOfSheep.reduce((total, sheep)=>{
    return sheep ? total+=1 : total
  }, 0)
}
String.prototype.toJadenCase = function () { 
  const words = this.split(' ')

  for(let i = 0; i < words.length; i++){
    const wordArr = words[i].split('')
    wordArr[0] = wordArr[0].toUpperCase()
    words[i] = wordArr.join('')
  }
 return words.join(' ')
  
  }
/* why if i didnt add(return false) i cant see the result of my console  */


document.getElementById('reg').onsubmit=()=>{
  let phoneinput=document.getElementById('phone').value
  let phoneRe=/\(\d{4}\)\d{3}-\d{4}/ig  //(1234)567-8910
  let validationResult=phoneRe.test(phoneinput)
  console.log("🚀 ~ file: main.js:5 ~ document.getElementById ~ validationResult:", validationResult)
    // return false
}

// In the Dev Tools console, paste this:

monitorEvents($0); // $0 refers to the last element selected

// For a specific element, and optionally an event type:
monitorEvents(document.body, 'mouse')

// To cancel:
unmonitorEvents($0)
function reverseWords(str) {
let reverseWords = str.split(" ")
.map(word => word.split("").reverse().join(""))
return reverseWords.join(" ")
}
<!DOCTYPE html>
<html>
  <head>
	<title>Video Picker</title>
	<link rel="stylesheet" href="style.css">
  </head>
  <body>
	<h1>Video Picker</h1>
	<form>
	  <input type="text" id="videoUrl" placeholder="Enter video URL...">
	  <button type="button" id="addVideoBtn">Add Video</button>
	</form>
	<hr>
	
	<h3 id="videoCount"></h3>

	
	<div id="videoList"></div>
	
	<script src="script.js">
	alert("If you want you can modify the UI of this project, to adapt on your needs\n" + "\nhave a great and blessed day 🤝🏼😊");

alert("Enter as many YouTube video links as you want to, and see the magic")


window.onload = function() {
const videoList = document.getElementById('videoList');
const addVideoBtn = document.getElementById('addVideoBtn');

// Load videos from LocalStorage on page load
loadVideos();

addVideoBtn.addEventListener('click', addVideo);

function addVideo() {
  const videoUrl = document.getElementById('videoUrl').value;
  const videoId = getVideoId(videoUrl);

  if (videoId) {
	const videoItem = createVideoItem(videoId);
	videoList.appendChild(videoItem);
	
	// Save video to LocalStorage
	saveVideo(videoId);
  }

  document.getElementById('videoUrl').value = '';
}

function getVideoId(url) {
  const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/;
  const match = url.match(regex);

  if (match && match[1]) {
	return match[1];
  } else {
	alert('Invalid video URL');
	return null;
  }
}

function createVideoItem(videoId) {
  const videoItem = document.createElement('div');
  videoItem.className = 'video-item';
  const thumbnailUrl = `https://img.youtube.com/vi/${videoId}/mqdefault.jpg`;
  const videoUrl = `https://www.youtube.com/watch?v=${videoId}`;
  videoItem.innerHTML = `
	<a href="${videoUrl}" target="_blank">
	  <img src="${thumbnailUrl}" alt="Video thumbnail">
	  <h2>${videoId}</h2>
	</a>
	<button class="remove-video-btn">Remove</button>
  `;

  // Add event listener to the 'Remove' button
  const removeBtn = videoItem.querySelector('.remove-video-btn');

  removeBtn.addEventListener('click', () => {
	removeVideo(videoId);
	videoItem.remove();
  });

  return videoItem;
}

function removeVideo(videoId) {
  let videos = [];
  if (localStorage.getItem('videos')) {
	videos = JSON.parse(localStorage.getItem('videos'));
  }
  const index = videos.indexOf(videoId);
  if (index !== -1) {
	// Display confirmation dialog box
	const confirmed = confirm("Are you sure you want to remove this video? 😥");
	if (confirmed) {
	  // Remove video from list
	  videos.splice(index, 1);
	  localStorage.setItem('videos', JSON.stringify(videos));
	  const videoItem = document.getElementById(videoId);
	  videoList.removeChild(videoItem);
	}
  }
}


function saveVideo(videoId) {
  let videos = [];
  if (localStorage.getItem('videos')) {
	videos = JSON.parse(localStorage.getItem('videos'));
  }
  if (!videos.includes(videoId)) {
	videos.push(videoId);
	localStorage.setItem('videos', JSON.stringify(videos));
  }
}

function loadVideos() {
  if (localStorage.getItem('videos')) {
	const videos = JSON.parse(localStorage.getItem('videos'));
	const videoCount = document.getElementById('videoCount');
	videoCount.textContent = `You have ${videos.length} videos in the list.`;
	videos.forEach(videoId => {
	  const videoItem = createVideoItem(videoId);
	  videoList.appendChild(videoItem);
	});
  }
}

}
/*
The saveVideo() function takes the video ID and saves it to an array in LocalStorage. The loadVideos() function is called on page load and loads the videos from LocalStorage, creating a videoItem for each one and appending it to the videoList. This way, the user's added videos will persist even if they close and reopen the page.*/
	
	</script>
  </body>
</html>